Beispiel #1
1
/***************** read_write_streams *****************
 * inputs: char* bandSpacing
 *         char* maskNoise
 *         char* maskType
 * outputs: int (literal)
 Description:
  ...
 ****************************************************** */
int read_write_streams(char* bandSpacing, char* maskNoise, char* maskType)
{
/* DECLARATION */ 
  float den, fres, *recordsamples,*powerspec, *A, *weights, *bands, summation;
  int i, numBands, totalframes, numsamples, numbytes, y, counter; //y might cause problems 
  bool dynamic, rain, linear;

  PaStreamParameters input, output; 
  PaStream *stream_input,  *stream_output; 
  PaError error_input,error_output;
  fftw_complex *in, *out;
  fftw_plan plan;
  FILE *powerspec_file; 
  data* struct_data; 
  
/* INITIALIZE STATE VARIABLES */
  counter = 0;
  struct_data = (data*) malloc(sizeof(data));

  // Convert command line args to booleans 
  dynamic = !strcmp(maskType,"Dynamic")?   1:0;
  rain    = !strcmp(maskNoise, "Rain")?    1:0;
  linear  = !strcmp(bandSpacing, "linear")? 1:0;
  if(linear) numBands = 10;
  else       numBands = 7;

/* READ THE .WAV */
  struct_data = output_file(numBands,linear,rain);
  for(i=0; i<(2*struct_data->num_frames); i++) // is accessing num_frames bad?
  {
    summation = 0;
    for(y = 0; y <= numBands; y++)
      summation += struct_data->noise[2*y*struct_data->num_frames+i];
    
    struct_data->data[i] = summation;
  }

/* ALLOCATE MEMORY FOR DATA STRUCTURES */
  totalframes   = CHANNELS*FRAMES;//5*SAMPLE_RATE; why????
  numsamples    = FRAMES; //why totalframes is 5*sample rate change to totalframes if wrong 
  fres          = (float) SAMPLE_RATE/FRAMES;
  numbytes      = numsamples * sizeof(float);
  recordsamples = (float*) malloc(numbytes);
  powerspec     = (float*) malloc(numbytes); //malloc too much memory but i think that cool we will figure it out
  A             = (float*) malloc(numbytes);
  weights       = (float*)malloc(sizeof(float)*numBands); //final computed band weights
  bands         = (float*)malloc(sizeof(float)*numBands);  //bands specified to compute band weights
  in            = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * numsamples);
  out           = (fftw_complex*) fftw_malloc(sizeof(fftw_complex) * numsamples);
  CHECK_MALLOC(recordsamples,"read_write_streams");
  CHECK_MALLOC(powerspec,"read_write_streams"); 
  CHECK_MALLOC(weights,"read_write_streams");
  CHECK_MALLOC(bands,"read_write_streams");
  CHECK_MALLOC(in,"read_write_streams");
  CHECK_MALLOC(out,"read_write_streams");
  CHECK_MALLOC(A,"read_write_streams");
  
  
  plan                = fftw_plan_dft_1d(numsamples, in, out, FFTW_FORWARD, FFTW_MEASURE);
  struct_data->cursor = 0;


  //struct_data->num_frames = 441000;
  for (i = 0; i < numsamples; i++)
    recordsamples[i] = powerspec[i] = A[i] = 0;
  for (i = 0; i <= numBands; i++)
    weights[i]      = .75;  //init weights to 1 equal volume 
  
  if (linear)
  { bands[0] = 80;
    for (i = 1; i <= numBands; i++)
      bands[i] = i*(SAMPLE_RATE/2)/numBands;
  }
  else
  {
     bands[0] = 60;
     bands[1] = 125;
     bands[2] = 250;
     bands[3] = 500;
     bands[4] = 1000;
     bands[5] = 2000;
     bands[6] = 4000;
     bands[7] = 8000;
 }

  A_compute_coeff(numsamples/2,A,fres);

/* PORT AUDIO INIT W/ ERROR CHECKING */
  if( paNoError != (error_input = Pa_Initialize()) ) goto error;
  if( paNoError != (error_output = Pa_Initialize()) ) goto error;
  if( paNoDevice == (input.device = Pa_GetDefaultInputDevice()))
    { fprintf(stderr, "Error: No default input device. \n");  goto error; }
  if( paNoDevice == (output.device = Pa_GetDefaultOutputDevice()))
    { fprintf(stderr, "Error: No default output device. \n");  goto error; }

 
  input.channelCount              =  CHANNELS;
  input.sampleFormat              =  paFloat32;
  input.suggestedLatency          =  Pa_GetDeviceInfo( input.device )->defaultLowInputLatency;
  input.hostApiSpecificStreamInfo =  NULL;

  output.channelCount              =  CHANNELS;
  output.sampleFormat              =  paFloat32;
  output.suggestedLatency          =  Pa_GetDeviceInfo( output.device )->defaultLowInputLatency;
  output.hostApiSpecificStreamInfo =  NULL;

  // Open the port audio stream for input
  error_input = Pa_OpenStream( 
        &stream_input,
              &input,
              NULL,                  /* &outputParameters, */
              SAMPLE_RATE,
              FRAMES,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              NULL, /* no callback, use blocking API */
              NULL);
  if (error_input !=paNoError) goto error; 
  
  // Open the port audio stream for output
  error_output = Pa_OpenStream(
          &stream_output,
                NULL, 
              &output,
              44100,
              paFramesPerBufferUnspecified,
              paClipOff,      
              output_callback, 
              struct_data);
  if (error_output != paNoError) goto error; 
  



  error_input  = Pa_StartStream(stream_input);
  error_output = Pa_StartStream(stream_output);

  /* Intialization */

  /* Read and Write */
   while(1)
   {
      powerspec_file = fopen("../streams/powerspec.txt","w");
      if( error_output  != paNoError && 0) goto error_o;
      error_input = Pa_ReadStream(stream_input,recordsamples, FRAMES);
      if(error_input != paNoError && 0) goto error;


      /* FFT PROCESSING */
      inputsignal(in, recordsamples, CHANNELS*numsamples); //converts to fftw_complex and averages stereo to mono
      weighted_power_spectrum_fftw(numsamples,in,out,powerspec,A,den,4, plan);

      //compute bands if dynamic masking
      if (dynamic)
        compute_band_weights(numBands,linear,numsamples,powerspec,fres,weights,bands);
      

      for(i = 0;i<struct_data->num_frames*2;i++) // is accessing num_frames bad?
        {
          summation = 0;
          for(y = 0; y <= numBands;y++)
            summation +=  weights[y]*struct_data->data[y*struct_data->num_frames*2+i];
    
          struct_data->data[i] = summation;
        }
      fclose(powerspec_file);
   }

   free(recordsamples);
   free(in);
   free(out);
  //clean up other stuff fft and other malloced items

  /* Read and Write */
error:

    Pa_Terminate();
    fprintf( stderr, "An error occured while using the portaudio stream_input\n" );
    fprintf( stderr, "Error number: %d\n", error_input );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( error_input) );

error_o:

    Pa_Terminate();
    fprintf( stderr, "An error occured while using the portaudio stream_input\n" );
    fprintf( stderr, "Error number: %d\n", error_output );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( error_output) );
 return 0;

}
Beispiel #2
0
void PortAudioInput::run() {
	PaStream           *inputStream = 0;
	PaError             err;

	//qWarning() << "PortAudioInput::run() BEGIN ===";
	if (!PortAudioSystem::initStream(&inputStream, g.s.iPortAudioInput, iFrameSize, reinterpret_cast<int *>(&iMicChannels), true))
		return; // PA init or stream opening failed, we will give up

	iMicFreq = SAMPLE_RATE;
	eMicFormat = SampleShort;
	initializeMixer();

	short inBuffer[iMicLength * iMicChannels];

	// depend on the stream having started
	bRunning = PortAudioSystem::startStream(inputStream);
	while (bRunning) {
		err = Pa_ReadStream(inputStream, inBuffer, iMicLength);
		if (err == paNoError) {
			addMic(inBuffer, iMicLength);
		} else if (err == paInputOverflowed) {
			qWarning("PortAudioInput: Overflow on PortAudio input-stream, we lost incoming data!");
		} else { // other error, aborg
			qWarning("PortAudioInput: Could not read from PortAudio stream, error %s", Pa_GetErrorText(err));
			bRunning = false;
		}
	}
	// ignoring return value on purpose, we cannot do anything about it anyway
	PortAudioSystem::stopStream(inputStream);

	// ignoring return value on purpose, we cannot do anything about it anyway
	PortAudioSystem::terminateStream(inputStream);
	inputStream = 0; // just for gdb sessions ;)
}
JNIEXPORT void JNICALL
Java_net_java_sip_communicator_impl_neomedia_portaudio_PortAudio_Pa_1ReadStream
    (JNIEnv *env, jclass clazz, jlong stream, jbyteArray buffer, jlong frames)
{
    jbyte* data = (*env)->GetByteArrayElements(env, buffer, NULL);

    if (data)
    {
        PortAudioStream *portAudioStream = (PortAudioStream *) stream;
        PaError errorCode
            = Pa_ReadStream(portAudioStream->stream, data, frames);

        if ((paNoError == errorCode) || (paInputOverflowed == errorCode))
        {
            if (portAudioStream->audioQualityImprovement)
            {
                AudioQualityImprovement_process(
                    portAudioStream->audioQualityImprovement,
                    AUDIO_QUALITY_IMPROVEMENT_SAMPLE_ORIGIN_INPUT,
                    portAudioStream->sampleRate,
                    portAudioStream->sampleSizeInBits,
                    portAudioStream->channels,
                    data,
                    frames * portAudioStream->inputFrameSize);
            }
            (*env)->ReleaseByteArrayElements(env, buffer, data, 0);
        }
        else
        {
            (*env)->ReleaseByteArrayElements(env, buffer, data, 0);
            PortAudio_throwException(env, errorCode);
        }
    }
}
Beispiel #4
0
void GuitarSori::callback(PaStream *stream, char *sampleBlock, double *sampleBlockConverted, double *sampleBlockFFT, const int framesPerBuffer)
{
	float *floatBuffer = (float*)sampleBlock;
	isThreadRunning = true;

	while (isThreadRunning)
	{
		Pa_ReadStream(stream, sampleBlock, framesPerBuffer);
		for (int i = 0; i < framesPerBuffer; i++)
		{
			sampleBlockConverted[i] = (double)floatBuffer[i];
		}

		
		realfft_packed(sampleBlockConverted, framesPerBuffer);
		for (int i = 0; i < framesPerBuffer / 2; i++)
		{
			sampleBlockFFT[i] = 1000 * (sampleBlockConverted[2 * i] * sampleBlockConverted[2 * i] 
								+ sampleBlockConverted[2 * i + 1] * sampleBlockConverted[2 * i + 1] );
		}
		Pa_WriteStream(stream, sampleBlock, framesPerBuffer);
	}

	isThreadRunning = false;

	Pa_Terminate();
}
Beispiel #5
0
int softrock_read(float* left_samples,float* right_samples) {
    int rc;
    int i;
    float audio_buffer[SAMPLES_PER_BUFFER*2];

    //if (softrock_get_verbose()) fprintf(stderr,"read available=%ld\n",Pa_GetStreamReadAvailable(stream));
    rc=Pa_ReadStream(stream,audio_buffer,SAMPLES_PER_BUFFER);
    if(rc<0) {
        if (softrock_get_verbose()) fprintf(stderr,"error reading audio_buffer %s (rc=%d)\n",Pa_GetErrorText(rc),rc);
    }

    // de-interleave samples
    if(softrock_get_iq()) {
        for(i=0;i<SAMPLES_PER_BUFFER;i++) {
            left_samples[i]=audio_buffer[i*2];
            right_samples[i]=audio_buffer[(i*2)+1];
					//if (softrock_get_verbose()) fprintf(stderr,"%d left=%f right=%f\n",i, left_samples[i],right_samples[i]);
        }
    } else {
        for(i=0;i<SAMPLES_PER_BUFFER;i++) {
            right_samples[i]=audio_buffer[i*2];
            left_samples[i]=audio_buffer[(i*2)+1];
//if (softrock_get_verbose()) fprintf(stderr,"%d left=%f right=%f\n",i, left_samples[i],right_samples[i]);
        }
    }

    return rc;
}
Beispiel #6
0
int CPaInput::Read( sqbind::CSqBinary *data, int frames )
{_STT();

	// Sanity checks
	if ( !m_stream || !data )
		return 0;

	// Use number of bytes available if blocking
	if ( m_bBlocking && 0 >= frames )
		frames = Pa_GetStreamReadAvailable( m_stream );

	// Anything new to read?
	if ( !frames )
		return data->getUsed();

	// How many bytes to read?
	unsigned long bytes = frames * getFrameBytes();
	if ( !m_bBlocking && 0 >= bytes )
		bytes = m_buf.GetMaxRead();

	// Ensure space
	unsigned long total = bytes + data->getUsed();
	unsigned long reserve = oex::cmn::NextPower2( total );
	if ( data->Size() < reserve )
		if ( !data->Resize( reserve ) )
			return data->getUsed();

	if ( m_bBlocking )
	{
		// Must specify an amount for blocking read
		if ( 0 >= bytes )
			return data->getUsed();

		// Read from stream
		m_errLast = Pa_ReadStream( m_stream, (void*)data->Ptr( data->getUsed() ), frames );
		if ( paNoError == m_errLast )
			data->setUsed( total );

	} // end if

	else
	{
		oex::CCircBuf::t_size uRead = 0;

		// Read the string from the buffer
		m_buf.Read( (oex::oexPVOID)data->Ptr( data->getUsed() ), bytes, &uRead );

		// Bounds check bytes read
		if ( uRead < 0 ) 
			uRead = 0;
		else if ( uRead > bytes ) 
			uRead = bytes;

		// Set new buffer size
		data->setUsed( data->getUsed() + uRead );

	} // end else

	return data->getUsed();
}
RTC::ReturnCode_t PortAudioInput::onExecute(RTC::UniqueId ec_id)
{
  RTC_DEBUG(("onExecute start"));
  //! The data read from the device is output.
  m_mutex.lock();
  RTC_DEBUG(("onExecute:mutex lock"));
  if ( Pa_IsStreamActive(m_stream) ) {
    m_out_data.data.length(m_totalframes); //!< set outport data length
    m_err = Pa_ReadStream( m_stream, (void *)&(m_out_data.data[0]), FRAMES_PER_BUFFER );
//    if( ( m_gain != 0 ) && ( m_gain != 1 ) && ( m_agc != 0 ) ) {
//      AutoGainControl((void *)&(m_out_data.data[0]), (int)m_totalframes );
//    }

    if ( m_err != paNoError ) {
      std::string error_str = Pa_GetErrorText(m_err);
      RTC_WARN(("PortAudio ReadStream failed:%s", error_str.c_str()));
    }
    setTimestamp(m_out_data);
    m_out_dataOut.write();
  }
  m_mutex.unlock();
  RTC_DEBUG(("onExecute:mutex unlock"));

  RTC_DEBUG(("onExecute finish"));
  return RTC::RTC_OK;
}
 void read(float* data, int count) {
     PaError pa_error;
     pa_error = Pa_ReadStream(input_stream, data, count);
     if (pa_error != 0) {
         std::ostringstream ss;
         ss << "failure reading from input stream " << pa_error;
         throw std::runtime_error(ss.str());
     }
 }
void Audio_IO::read(float *buf)
{
  if(mode == AUDIO_IO_READONLY || mode == AUDIO_IO_READWRITE)
  {
    // blocking read
    err = Pa_ReadStream(stream,buf,framesperbuffer);
    if(err != paNoError) leave();
  }
}
Beispiel #10
0
static void do_pa_run(PaDeviceIndex idx, PaTime latency)
{
	PaError err;
	struct PaStreamParameters param;
	PaStream *stream = NULL;

	if(log_len) flow_report(f_log,log_min,log_max,log_len);

	memset(&param,0,sizeof(param));
	param.device = idx;
	param.channelCount = 1;
	param.sampleFormat = paUInt8;
	param.suggestedLatency = latency;

	err = Pa_IsFormatSupported(&param,NULL,rate);
	do_pa_error(err,"unsupported");

	err = Pa_OpenStream(&stream, &param, NULL, (double)rate,
	         paFramesPerBufferUnspecified,paNoFlag, /* &do_pa_callback */ NULL, NULL);
	do_pa_error(err,"open");
	
	err = Pa_StartStream(stream);
	do_pa_error(err,"start");

	while(1) {
#if 1
		unsigned char buf[128];
		FLOW **f = flows;
		err = Pa_ReadStream(stream,buf,sizeof(buf));
		if (err == paInputOverflowed)
			fprintf(stderr,"Input overflow\n");
		else do_pa_error(err, "read");
		while(*f)
			do_pa_callback(buf,NULL,sizeof(buf),NULL,0,*(f++));
#endif
		err = Pa_IsStreamActive(stream);
		if (err < 0) do_pa_error(err, "is_active");
		if (err == 0) break;
#if 0
		sleep(60);
#endif
	}
	err = Pa_AbortStream(stream);
	do_pa_error(err,"end");

	err = Pa_CloseStream(stream);
	do_pa_error(err,"close");

	err = Pa_Terminate();
	do_pa_error(err,"exit");
	exit(err != 0);
}
Beispiel #11
0
portaudio_decoder *quiet_portaudio_decoder_create(const decoder_options *opt, PaDeviceIndex device, PaTime latency, double sample_rate, size_t sample_buffer_size) {
    PaStream *stream;
    PaStreamParameters param = {
        .device = device,
        .channelCount = 2,
        .sampleFormat = paFloat32,
        .suggestedLatency = latency,
        .hostApiSpecificStreamInfo = NULL,
    };
    PaError err = Pa_OpenStream(&stream, &param, NULL, sample_rate,
                        sample_buffer_size, paNoFlag, NULL, NULL);
    if (err != paNoError) {
        printf("failed to open port audio stream, %s\n", Pa_GetErrorText(err));
        return NULL;
    }

    err = Pa_StartStream(stream);
    if (err != paNoError) {
        printf("failed to start port audio stream, %s\n", Pa_GetErrorText(err));
        return NULL;
    }

    const PaStreamInfo *info = Pa_GetStreamInfo(stream);
    decoder *d = quiet_decoder_create(opt, info->sampleRate);

    quiet_sample_t *sample_buffer = malloc(2 * sample_buffer_size * sizeof(quiet_sample_t));
    quiet_sample_t *mono_buffer = malloc(sample_buffer_size * sizeof(quiet_sample_t));
    portaudio_decoder *decoder = malloc(1 * sizeof(portaudio_decoder));
    decoder->dec = d;
    decoder->stream = stream;
    decoder->sample_buffer = sample_buffer;
    decoder->mono_buffer = mono_buffer;
    decoder->sample_buffer_size = sample_buffer_size;

    return decoder;
}

ssize_t quiet_portaudio_decoder_recv(quiet_portaudio_decoder *d, uint8_t *data, size_t len) {
    return quiet_decoder_recv(d->dec, data, len);
}

void quiet_portaudio_decoder_consume(quiet_portaudio_decoder *d) {
    PaError err = Pa_ReadStream(d->stream, d->sample_buffer, d->sample_buffer_size);
    if (err != paNoError) {
        printf("failed to read port audio stream, %s\n", Pa_GetErrorText(err));
        return;
    }
    for (size_t i = 0; i < d->sample_buffer_size; i++) {
        d->mono_buffer[i] = d->sample_buffer[i * 2] + d->sample_buffer[i * 2 + 1];
    }
    quiet_decoder_consume(d->dec, d->mono_buffer, d->sample_buffer_size);
}
bool AudioCapturePortAudio::readAudio(int maxSize)
{
    Q_ASSERT(stream != NULL);

    int err = Pa_ReadStream( stream, m_audioBuffer, maxSize );
    if( err )
    {
        qWarning("read from audio interface failed (%s)\n", Pa_GetErrorText (err));
        return false;
    }

    qDebug() << "[PORTAUDIO readAudio] " << maxSize << "bytes read";

    return true;
}
Beispiel #13
0
 void test1()
 {
     float block[FRAMES_PER_BUFFER];
     Sample sample;
     for(int j = 0; j< 2500; j++)
     {
         //std::unique_lock<std::mutex> mlock(this->bqMutex);
         std::cout<<"nagrywam"<<j;
         Pa_ReadStream(inputStream, block, FRAMES_PER_BUFFER);
         sample.setSample(block);
         bq.push(sample);
        // mlock.unlock();
         
     }
 }
void PortAudioRecordBackend::vuMeterTimerSlot() {
    int err;
    signed long availableFrames;
    float volume;

    volume = 0;
    availableFrames = Pa_GetStreamReadAvailable(vuMeterStream);

    if(availableFrames > 0) {
        float *buffer = new float[availableFrames];
        err = Pa_ReadStream(vuMeterStream, buffer, availableFrames);

        if(err != paNoError) {
            qDebug("Error reading from vuMeter stream:\n %s", Pa_GetErrorText(err));
            updateVuMeter(&volume);
            return;
        }

        for(int i = 0; i < availableFrames; i++) {
            volume = fmax(volume, fabs(buffer[i]));
        }

        if(volume < 0) {
            volume = 0;
        }

        if(volume > 1) {
            volume = 1;
        }

        updateVuMeter(&volume);

    } else {
        updateVuMeter(&volume);

#ifndef WIN32
        /*
         * FIXME:
         * Quite a hack to resolve an issue where the stream unexpectedly aborted.
         * Here we simply restart the whole shebang to resolve this situation.
         * This problem does not seem to occur in Windows.
         */
        closeVuMeterStream();
        createVuMeterStream();
#endif
    }
}
Beispiel #15
0
int audio_pa_run(audio_callback_fn_pt callback, double sample_rate, unsigned long chunk_size) {
    chunk = calloc(chunk_size, sizeof *chunk);
    if(chunk == NULL) MEMFAIL();

    PaError err = Pa_Initialize();
    if(err != paNoError) FAIL("Could not initialize PortAudio\n");

    PaStreamParameters inputParameters;
    inputParameters.device = Pa_GetDefaultInputDevice();
    inputParameters.channelCount = NUM_CHANNELS;
    inputParameters.sampleFormat = PA_SAMPLE_TYPE;
    inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    PaStream *stream = NULL;
    err = Pa_OpenStream(&stream,
                        &inputParameters,
                        0,
                        sample_rate,
                        chunk_size,
                        paClipOff,
                        0,
                        0);
    if(err != paNoError) FAIL("Could not open PortAudio input stream\n");

    err = Pa_StartStream(stream);
    if(err != paNoError) FAIL("Could not open audio input stream\n");

    /*
    printf("Gracefully terminated PortAudio\n");
    */

    int cb_err = 0;
    while(cb_err == 0){
        err = Pa_ReadStream(stream, chunk, chunk_size );
        if(err != paNoError) FAIL("Could not read audio chunk\n");
        cb_err = callback(chunk);
    }

    err = Pa_Terminate();
    if(err != paNoError) FAIL("Could not terminate PortAudio\n");

    free(chunk);
    return 0;
}
Beispiel #16
0
void PortAudioRead::run()
{
    //this->index = Pa_GetDefaultInputDevice();
    const PaDeviceInfo* info = Pa_GetDeviceInfo(this->index);
    PaStream* stream = NULL;
    PaStreamParameters parameter;
    parameter.channelCount = 2;
    parameter.device = this->index;
    parameter.hostApiSpecificStreamInfo = NULL;
    parameter.sampleFormat = paInt24;
    parameter.suggestedLatency = info->defaultHighInputLatency;

    PaError err = Pa_OpenStream(&stream, &parameter, NULL, 44100, 1024, paNoFlag, NULL, NULL);
    //PaError err = Pa_OpenDefaultStream(&stream, 2, 0, paFloat32, 44100, paFramesPerBufferUnspecified, NULL, NULL);

    if (err == paNoError)
    {
        err = Pa_StartStream(stream);
    }

    char buffer[12288];

    while (!this->toEnd && err == paNoError)
    {
        long count = Pa_GetStreamReadAvailable(stream);
        if (count > 4096)
            count = 4096;
        if (count > 0)
        {
            err = Pa_ReadStream(stream, &buffer[0], count);
            if (err == paNoError)
            {
                this->rb->Put((samplePtr)&buffer, int24Sample, count * 2);
            }
        }
        else
        {
            msleep(100);
        }
    }

    Pa_StopStream(stream);

    Pa_CloseStream(stream);
}
Beispiel #17
0
/*-----------------------------------------------------------------------------------------*/
static int TestBadActions( void )
{
    PaStream*           stream = NULL;
    PaError             result;
    PaQaData            myData;
    PaStreamParameters  opp;
    const PaDeviceInfo* info = NULL;

    /* Setup data for synthesis thread. */
    myData.framesLeft = (unsigned long)(SAMPLE_RATE * 100); /* 100 seconds */
    myData.numChannels = 1;
    myData.mode = MODE_OUTPUT;

    opp.device                    = Pa_GetDefaultOutputDevice(); /* Default output. */
    opp.channelCount              = 2;                           /* Stereo output.  */
    opp.hostApiSpecificStreamInfo = NULL;
    opp.sampleFormat              = paFloat32;
    info = Pa_GetDeviceInfo(opp.device);
    opp.suggestedLatency          = info ? info->defaultLowOutputLatency : 0.100;

    if (opp.device != paNoDevice) {
        HOPEFOR(((result = Pa_OpenStream(&stream, NULL, /* Take NULL as input parame-     */
                                         &opp,          /* ters, meaning try only output. */
                                         SAMPLE_RATE, FRAMES_PER_BUFFER,
                                         paClipOff, QaCallback, &myData )) == paNoError));
    }

    HOPEFOR(((result = Pa_StartStream(NULL))    == paBadStreamPtr));
    HOPEFOR(((result = Pa_StopStream(NULL))     == paBadStreamPtr));
    HOPEFOR(((result = Pa_IsStreamStopped(NULL)) == paBadStreamPtr));
    HOPEFOR(((result = Pa_IsStreamActive(NULL)) == paBadStreamPtr));
    HOPEFOR(((result = Pa_CloseStream(NULL))    == paBadStreamPtr));
    HOPEFOR(((result = Pa_SetStreamFinishedCallback(NULL, NULL)) == paBadStreamPtr));
    HOPEFOR(((result = !Pa_GetStreamInfo(NULL))));
    HOPEFOR(((result = Pa_GetStreamTime(NULL))  == 0.0));
    HOPEFOR(((result = Pa_GetStreamCpuLoad(NULL))  == 0.0));
    HOPEFOR(((result = Pa_ReadStream(NULL, NULL, 0))  == paBadStreamPtr));
    HOPEFOR(((result = Pa_WriteStream(NULL, NULL, 0))  == paBadStreamPtr));

    /** @todo test Pa_GetStreamReadAvailable and Pa_GetStreamWriteAvailable */

    if (stream != NULL) Pa_CloseStream(stream);
    return result;
}
Beispiel #18
0
int quisk_read_portaudio(struct sound_dev * dev, complex * cSamples)
{	// Read sound samples from the soundcard.
	// Samples are converted to 32 bits with a range of +/- CLIP32 and placed into cSamples.
	int i;
	long avail;
	int nSamples;
	complex c;
	PaError error;
	float fi, fq;

	if (!dev->handle)
		return -1;

	avail = dev->read_frames;		// size of read request
	if (avail == 0) {				// non-blocking: read available frames
		avail = Pa_GetStreamReadAvailable((PaStream * )dev->handle);
		if (avail > SAMP_BUFFER_SIZE / dev->num_channels)		// limit read request to buffer size
			avail = SAMP_BUFFER_SIZE / dev->num_channels;
	}
	error = Pa_ReadStream ((PaStream * )dev->handle, fbuffer, avail);
	if (error != paNoError)
		quisk_sound_state.read_error++;
	nSamples = 0;
	for (i = 0; avail; i += dev->num_channels, nSamples++, avail--) {
		fi = fbuffer[i + dev->channel_I];
		fq = fbuffer[i + dev->channel_Q];
		if (fi >=  1.0 || fi <= -1.0)
			dev->overrange++;	// assume overrange returns max int
		if (fq >=  1.0 || fq <= -1.0)
			dev->overrange++;
		cSamples[nSamples] = (fi + I * fq) * CLIP32;
	}
	for (i = 0; i < nSamples; i++) {	// DC removal; R.G. Lyons page 553
		c = cSamples[i] + dev->dc_remove * 0.95;
		cSamples[i] = c - dev->dc_remove;
		dev->dc_remove = c;
	}
	return nSamples;
}
OsStatus MpSyncPortAudioStream::readStream(void *buffer, unsigned long frames)
{
   OsStatus status = OS_FAILED;

   PaError paError = Pa_ReadStream(m_streamId, buffer, frames);

   if (paError == paNoError)
   {
      // copy input frames to meter
      if (m_inputVolumeMeter)
      {
         m_inputVolumeMeter->pushBuffer(buffer, (unsigned int)frames);
      }

      status = OS_SUCCESS;
   }
   else if (paError == paInputOverflowed)
   {
      status = OS_OVERFLOW;
   }

   return status;
}
Beispiel #20
0
std::vector<short> AudioInput::record(unsigned msecs)
{
    if (!stream)
        return std::vector<short>();

    std::cout << "AudioInput::record(" << msecs << ")\n";

    PaTime startTime = Pa_GetStreamTime(stream);

    std::vector<short> samples;
    while (Pa_GetStreamTime(stream) < startTime + msecs * .001) {
        samples.resize(samples.size() + CHUNK_SIZE);
        PaError err = Pa_ReadStream(stream, &samples[samples.size() - CHUNK_SIZE], CHUNK_SIZE);
        if (err != paInputOverflowed && err != paNoError) {
            std::cerr << "Pa_ReadStream(): " << Pa_GetErrorText(err) << '\n';
            return samples;
        }
    }

    std::cout << "Recorded " << (Pa_GetStreamTime(stream) - startTime) << "s worth of audio\n";

    return samples;
}
Beispiel #21
0
/* -- main function -- */
int main( int argc, char **argv ) {
    PaStreamParameters inputParameters;
    float a[2], b[3], mem1[4], mem2[4];
    float data[FFT_SIZE];
    float datai[FFT_SIZE];
    float window[FFT_SIZE];
    float freqTable[FFT_SIZE];
    char * noteNameTable[FFT_SIZE];
    float notePitchTable[FFT_SIZE];
    void * fft = NULL;
    PaStream *stream = NULL;
    PaError err = 0;
    struct sigaction action;

    // add signal listen so we know when to exit:
    action.sa_handler = signalHandler;
    sigemptyset (&action.sa_mask);
    action.sa_flags = 0;

    sigaction (SIGINT, &action, NULL);
    sigaction (SIGHUP, &action, NULL);
    sigaction (SIGTERM, &action, NULL);

    // build the window, fft, etc
    /*
       buildHanWindow( window, 30 );
       for( int i=0; i<30; ++i ) {
          for( int j=0; j<window[i]*50; ++j )
             printf( "*" );
          printf("\n");
       }
       exit(0);
    */
    buildHanWindow( window, FFT_SIZE );
    fft = initfft( FFT_EXP_SIZE );
    computeSecondOrderLowPassParameters( SAMPLE_RATE, 330, a, b );
    mem1[0] = 0;
    mem1[1] = 0;
    mem1[2] = 0;
    mem1[3] = 0;
    mem2[0] = 0;
    mem2[1] = 0;
    mem2[2] = 0;
    mem2[3] = 0;
    //freq/note tables
    for( int i=0; i<FFT_SIZE; ++i ) {
        freqTable[i] = ( SAMPLE_RATE * i ) / (float) ( FFT_SIZE );
    }
    for( int i=0; i<FFT_SIZE; ++i ) {
        noteNameTable[i] = NULL;
        notePitchTable[i] = -1;
    }
    for( int i=0; i<127; ++i ) {
        float pitch = ( 440.0 / 32.0 ) * pow( 2, (i-9.0)/12.0 ) ;
        if( pitch > SAMPLE_RATE / 2.0 )
            break;
        //find the closest frequency using brute force.
        float min = 1000000000.0;
        int index = -1;
        for( int j=0; j<FFT_SIZE; ++j ) {
            if( fabsf( freqTable[j]-pitch ) < min ) {
                min = fabsf( freqTable[j]-pitch );
                index = j;
            }
        }
        noteNameTable[index] = NOTES[i%12];
        notePitchTable[index] = pitch;
        //printf( "%f %d %s\n", pitch, index, noteNameTable[index] );
    }



    // initialize portaudio
    err = Pa_Initialize();
    if( err != paNoError ) goto error;

    inputParameters.device = Pa_GetDefaultInputDevice();
    inputParameters.channelCount = 1;
    inputParameters.sampleFormat = paFloat32;
    inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    printf( "Opening %s\n",
            Pa_GetDeviceInfo( inputParameters.device )->name );

    err = Pa_OpenStream( &stream,
                         &inputParameters,
                         NULL, //no output
                         SAMPLE_RATE,
                         FFT_SIZE,
                         paClipOff,
                         NULL,
                         NULL );
    if( err != paNoError ) goto error;

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

    // this is the main loop where we listen to and
    // process audio.
    while( running )
    {
        // read some data
        err = Pa_ReadStream( stream, data, FFT_SIZE );
        if( err ) goto error; //FIXME: we don't want to err on xrun

        // low-pass
        //for( int i=0; i<FFT_SIZE; ++i )
        //   printf( "in %f\n", data[i] );
        for( int j=0; j<FFT_SIZE; ++j ) {
            data[j] = processSecondOrderFilter( data[j], mem1, a, b );
            data[j] = processSecondOrderFilter( data[j], mem2, a, b );
        }
        // window
        applyWindow( window, data, FFT_SIZE );

        // do the fft
        for( int j=0; j<FFT_SIZE; ++j )
            datai[j] = 0;
        applyfft( fft, data, datai, false );

        //find the peak
        float maxVal = -1;
        int maxIndex = -1;
        for( int j=0; j<FFT_SIZE/2; ++j ) {
            float v = data[j] * data[j] + datai[j] * datai[j] ;
            /*
                     printf( "%d: ", j*SAMPLE_RATE/(2*FFT_SIZE) );
                     for( int i=0; i<sqrt(v)*100000000; ++i )
                        printf( "*" );
                     printf( "\n" );
            */
            if( v > maxVal ) {
                maxVal = v;
                maxIndex = j;
            }
        }
        float freq = freqTable[maxIndex];
        //find the nearest note:
        int nearestNoteDelta=0;
        while( true ) {
            if( nearestNoteDelta < maxIndex && noteNameTable[maxIndex-nearestNoteDelta] != NULL ) {
                nearestNoteDelta = -nearestNoteDelta;
                break;
            } else if( nearestNoteDelta + maxIndex < FFT_SIZE && noteNameTable[maxIndex+nearestNoteDelta] != NULL ) {
                break;
            }
            ++nearestNoteDelta;
        }
        char * nearestNoteName = noteNameTable[maxIndex+nearestNoteDelta];
        float nearestNotePitch = notePitchTable[maxIndex+nearestNoteDelta];
        float centsSharp = 1200 * log( freq / nearestNotePitch ) / log( 2.0 );

        // now output the results:
        printf("\033[2J\033[1;1H"); //clear screen, go to top left
        fflush(stdout);

        printf( "Tuner listening. Control-C to exit.\n" );
        printf( "%f Hz, %d : %f\n", freq, maxIndex, maxVal*1000 );
        printf( "Nearest Note: %s\n", nearestNoteName );
        if( nearestNoteDelta != 0 ) {
            if( centsSharp > 0 )
                printf( "%f cents sharp.\n", centsSharp );
            if( centsSharp < 0 )
                printf( "%f cents flat.\n", -centsSharp );
        } else {
            printf( "in tune!\n" );
        }
        printf( "\n" );
        int chars = 30;
        if( nearestNoteDelta == 0 || centsSharp >= 0 ) {
            for( int i=0; i<chars; ++i )
                printf( " " );
        } else {
            for( int i=0; i<chars+centsSharp; ++i )
                printf( " " );
            for( int i=chars+centsSharp<0?0:chars+centsSharp; i<chars; ++i )
                printf( "=" );
        }
        printf( " %2s ", nearestNoteName );
        if( nearestNoteDelta != 0 )
            for( int i=0; i<chars && i<centsSharp; ++i )
                printf( "=" );
        printf("\n");
    }
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;

    // cleanup
    destroyfft( fft );
    Pa_Terminate();

    return 0;
error:
    if( stream ) {
        Pa_AbortStream( stream );
        Pa_CloseStream( stream );
    }
    destroyfft( fft );
    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 inputParameters, outputParameters;
    PaStream *stream = NULL;
    PaError err;
    char *sampleBlock;
    int i;
    int numBytes;
    
    
    printf("patest_read_write_wire.c\n"); fflush(stdout);

    numBytes = FRAMES_PER_BUFFER * NUM_CHANNELS * SAMPLE_SIZE ;
    sampleBlock = (char *) malloc( numBytes );
    if( sampleBlock == NULL )
    {
        printf("Could not allocate record array.\n");
        exit(1);
    }
    CLEAR( sampleBlock );

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

    inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
    printf( "Input device # %d.\n", inputParameters.device );
    printf( "Input LL: %g s\n", Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency );
    printf( "Input HL: %g s\n", Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency );
    inputParameters.channelCount = NUM_CHANNELS;
    inputParameters.sampleFormat = PA_SAMPLE_TYPE;
    inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
    printf( "Output device # %d.\n", outputParameters.device );
    printf( "Output LL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency );
    printf( "Output HL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency );
    outputParameters.channelCount = NUM_CHANNELS;
    outputParameters.sampleFormat = PA_SAMPLE_TYPE;
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;

    /* -- setup -- */

   err = Pa_OpenStream(
              &stream,
              &inputParameters,
              &outputParameters,
              SAMPLE_RATE,
              FRAMES_PER_BUFFER,
              paClipOff,      /* we won't output out of range samples so don't bother clipping them */
              NULL, /* no callback, use blocking API */
              NULL ); /* no callback, so no callback userData */
    if( err != paNoError ) goto error;

    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    printf("Wire on. Will run %d seconds.\n", NUM_SECONDS); fflush(stdout);

    for( i=0; i<(NUM_SECONDS*SAMPLE_RATE)/FRAMES_PER_BUFFER; ++i )
    {
       err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER );
       if( err && CHECK_UNDERFLOW ) goto xrun;
       err = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER );
       if( err && CHECK_OVERFLOW ) goto xrun;
    }
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;

    CLEAR( sampleBlock );
/*
    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    printf("Wire on. Interrupt to stop.\n"); fflush(stdout);

    while( 1 )
    {
       err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER );
       if( err ) goto xrun;
       err = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER );
       if( err ) goto xrun;
    }
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;

    Pa_CloseStream( stream );
*/
    free( sampleBlock );

    Pa_Terminate();
    return 0;

xrun:
    if( stream ) {
       Pa_AbortStream( stream );
       Pa_CloseStream( stream );
    }
    free( sampleBlock );
    Pa_Terminate();
    if( err & paInputOverflow )
       fprintf( stderr, "Input Overflow.\n" );
    if( err & paOutputUnderflow )
       fprintf( stderr, "Output Underflow.\n" );
    return -2;

error:
    if( stream ) {
       Pa_AbortStream( stream );
       Pa_CloseStream( stream );
    }
    free( sampleBlock );
    Pa_Terminate();
    fprintf( stderr, "An error occured while using the portaudio stream\n" );
    fprintf( stderr, "Error number: %d\n", err );
    fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
    return -1;
}
Beispiel #23
0
int pa_send_dacs(void)
{
    t_sample *fp;
    float *fp2, *fp3;
    float *conversionbuf;
    int j, k;
    int rtnval =  SENDDACS_YES;
#ifndef FAKEBLOCKING
    double timebefore;
#endif /* FAKEBLOCKING */
    if (!sys_inchannels && !sys_outchannels || !pa_stream)
        return (SENDDACS_NO);
    conversionbuf = (float *)alloca((sys_inchannels > sys_outchannels?
        sys_inchannels:sys_outchannels) * DEFDACBLKSIZE * sizeof(float));

#ifdef FAKEBLOCKING
    if (!sys_inchannels)    /* if no input channels sync on output */
    {
#ifdef THREADSIGNAL
        pthread_mutex_lock(&pa_mutex);
#endif
        while (sys_ringbuf_getwriteavailable(&pa_outring) <
            (long)(sys_outchannels * DEFDACBLKSIZE * sizeof(float)))
        {
            rtnval = SENDDACS_SLEPT;
#ifdef THREADSIGNAL
            pthread_cond_wait(&pa_sem, &pa_mutex);
#else
#ifdef _WIN32
            Sleep(1);
#else
            usleep(1000);
#endif /* _WIN32 */
#endif /* THREADSIGNAL */
        }
#ifdef THREADSIGNAL
        pthread_mutex_unlock(&pa_mutex);
#endif
    }
        /* write output */
    if (sys_outchannels)
    {
        for (j = 0, fp = sys_soundout, fp2 = conversionbuf;
            j < sys_outchannels; j++, fp2++)
                for (k = 0, fp3 = fp2; k < DEFDACBLKSIZE;
                    k++, fp++, fp3 += sys_outchannels)
                        *fp3 = *fp;
        sys_ringbuf_write(&pa_outring, conversionbuf,
            sys_outchannels*(DEFDACBLKSIZE*sizeof(float)), pa_outbuf);
    }
    if (sys_inchannels)    /* if there is input sync on it */
    {
#ifdef THREADSIGNAL
        pthread_mutex_lock(&pa_mutex);
#endif
        while (sys_ringbuf_getreadavailable(&pa_inring) <
            (long)(sys_inchannels * DEFDACBLKSIZE * sizeof(float)))
        {
            rtnval = SENDDACS_SLEPT;
#ifdef THREADSIGNAL
            pthread_cond_wait(&pa_sem, &pa_mutex);
#else
#ifdef _WIN32
            Sleep(1);
#else
            usleep(1000);
#endif /* _WIN32 */
#endif /* THREADSIGNAL */
        }
#ifdef THREADSIGNAL
        pthread_mutex_unlock(&pa_mutex);
#endif
    }
    if (sys_inchannels)
    {
        sys_ringbuf_read(&pa_inring, conversionbuf,
            sys_inchannels*(DEFDACBLKSIZE*sizeof(float)), pa_inbuf);
        for (j = 0, fp = sys_soundin, fp2 = conversionbuf;
            j < sys_inchannels; j++, fp2++)
                for (k = 0, fp3 = fp2; k < DEFDACBLKSIZE;
                    k++, fp++, fp3 += sys_inchannels)
                        *fp = *fp3;
    }

#else /* FAKEBLOCKING */
    timebefore = sys_getrealtime();
        /* write output */
    if (sys_outchannels)
    {
        if (!pa_started)
        {
            memset(conversionbuf, 0,
                sys_outchannels * DEFDACBLKSIZE * sizeof(float));
            for (j = 0; j < pa_nbuffers-1; j++)
                Pa_WriteStream(pa_stream, conversionbuf, DEFDACBLKSIZE);
        }
        for (j = 0, fp = sys_soundout, fp2 = conversionbuf;
            j < sys_outchannels; j++, fp2++)
                for (k = 0, fp3 = fp2; k < DEFDACBLKSIZE;
                    k++, fp++, fp3 += sys_outchannels)
                        *fp3 = *fp;
        Pa_WriteStream(pa_stream, conversionbuf, DEFDACBLKSIZE);
    }

    if (sys_inchannels)
    {
        Pa_ReadStream(pa_stream, conversionbuf, DEFDACBLKSIZE);
        for (j = 0, fp = sys_soundin, fp2 = conversionbuf;
            j < sys_inchannels; j++, fp2++)
                for (k = 0, fp3 = fp2; k < DEFDACBLKSIZE;
                    k++, fp++, fp3 += sys_inchannels)
                        *fp = *fp3;
    }
    if (sys_getrealtime() - timebefore > 0.002)
    {
        rtnval = SENDDACS_SLEPT;
    }
#endif /* FAKEBLOCKING */
    pa_started = 1;

    memset(sys_soundout, 0, DEFDACBLKSIZE*sizeof(t_sample)*sys_outchannels);
    return (rtnval);
}
Beispiel #24
0
_CGUL_EXPORT CGUL::SInt32 CGUL::PortAudio::Stream::Read(void* buffer, UInt64 frames)
{
    return (SInt32)Pa_ReadStream(stream, buffer, frames);
}
Beispiel #25
0
_JATTA_EXPORT Jatta::SInt32 Jatta::PortAudio::Stream::Read(void* buffer, UInt64 frames)
{
    return (SInt32)Pa_ReadStream(stream, buffer, frames);
}
int main(int argc, char *argv[]) {
    long i = 0;
    long readcount = 0;
    PaStreamParameters inputParameters;
    PaStream *stream = NULL;
    long sizeonesec = (PLAY_FRAMES_PER_BUFFER * 2) * sizeof(float);

    /* Alloc size for one block */
    float *sampleBlock = (float *)malloc(sizeonesec);
    PaError retval = 0;
    struct sigaction sa;

    printf("Record to file: '%s'\n", argv[1]);

    /*
      We use two channels
      Samplerate is 44100
      Wave 16 bit output format
    */
    sfinfo.channels = 2;
    sfinfo.samplerate = 44100;
    sfinfo.format = SF_FORMAT_WAV | SF_FORMAT_PCM_16;

    /* Open file. Because this is just a example we asume
      What you are doing and give file first argument */
    if (! (outfile = sf_open(argv[1], SFM_WRITE, &sfinfo))) {
        printf ("Not able to open output file %s.\n", argv[1]) ;
        sf_perror (NULL) ;
        return  1 ;
    }

    sa.sa_flags = SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = handler;

    if (sigaction(SIGINT, &sa, NULL) == -1) {
        printf("Can't set SIGINT handler!\n");
        sf_close(outfile);
        return -1;
    }

    if (sigaction(SIGHUP, &sa, NULL) == -1) {
        printf("Can't set SIGHUP handler!\n");
        sf_close(outfile);
        return -1;
    }

    /* -- initialize PortAudio -- */
    retval = Pa_Initialize();

    if(retval != paNoError) {
        goto exit;
    }

    inputParameters.device = Pa_GetDefaultInputDevice(); /* default output device */

    if (inputParameters.device == paNoDevice) {
        fprintf(stderr, "Error: No default output device.\n");
        goto exit;
    }

    /* -- setup stream -- */
    inputParameters.channelCount = 2;       /* stereo output */
    inputParameters.sampleFormat = paFloat32;  /* 32 bit floating point output */
    inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowOutputLatency;
    inputParameters.hostApiSpecificStreamInfo = NULL;

    retval = Pa_OpenStream(
                 &stream,
                 &inputParameters,
                 NULL, /* no output */
                 44100,
                 PLAY_FRAMES_PER_BUFFER,
                 paClipOff,      /* we won't output out of range samples so don't bother clipping them */
                 NULL,
                 outfile);

    if(retval != paNoError) {
        printf("Can't open device\n");
        goto exit;
    }

    /* -- start stream -- */
    retval = Pa_StartStream(stream);

    if(retval != paNoError) {
        goto exit;
    }

    printf("Wire on. Will run one minute.\n");
    fflush(stdout);

    /* -- Here's the loop where we pass data from input to output -- */
    for(i = 0; i < ((10 * sizeonesec) / (44100 * 2)); ++i) {
        retval = Pa_ReadStream(stream, (void *)sampleBlock, sizeonesec / 8);

        if(retval != paNoError) {
            printf("** Can't read from input!\n");
            goto exit;
        }

        readcount = sf_write_float(outfile, sampleBlock, sizeonesec / 4);

        if(readcount <= 0) {
            printf("** Can't write to file!\n");
            goto exit;
        }


    }

exit:
    sf_close(outfile);
    retval = Pa_StopStream(stream);
    retval = Pa_CloseStream(stream);
    Pa_Terminate();
    return 0;

}
Beispiel #27
0
//INSERT NEW CODE HERE==========================================================
int main (void)
{
	 PaStream *stream = NULL;
	int i;
	PaError err;
	char * sampleBlock ;
	
	/* -- initialize PortAudio -- */
	err = Pa_Initialize();
	 PaStreamParameters inputParameters, outputParameters;
	if( err != paNoError ) goto error;
	
	/* -- setup input and output -- */
	inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
	inputParameters.channelCount = NUM_CHANNELS;
	inputParameters.sampleFormat = PA_SAMPLE_TYPE;
	inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ;
	inputParameters.hostApiSpecificStreamInfo = NULL;
	outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
	outputParameters.channelCount = NUM_CHANNELS;
	outputParameters.sampleFormat = PA_SAMPLE_TYPE;
	outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency;
	outputParameters.hostApiSpecificStreamInfo = NULL;
	
	
	/* -- setup stream -- */
	err = Pa_OpenStream(
	&stream,
	&inputParameters,
	&outputParameters,
	SAMPLE_RATE,
	FRAMES_PER_BUFFER,
	paClipOff, /* we won't output out of range samples so don't bother clipping them */
	NULL, /* no callback, use blocking API */
	NULL ); /* no callback, so no callback userData */
	if( err != paNoError ) goto error;
	/* -- start stream -- */
	int errx;
	errx = Pa_StartStream( stream );
	if( err != paNoError ) goto error;
	printf("Wire on. Will run one minute.\n"); fflush(stdout);
	/* -- Here's the loop where we pass data from input to output -- */
	for( i=0; i<(60*SAMPLE_RATE)/FRAMES_PER_BUFFER; ++i )
	{
	errx = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER );
	if( errx ) goto xrun;
	errx = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER );
	if( errx ) goto xrun;
	}
	/* -- Now we stop the stream -- */
	errx = Pa_StopStream( stream );
	if( errx != paNoError ) goto error;
	/* -- don't forget to cleanup! -- */
	errx = Pa_CloseStream( stream );
	if( errx != paNoError ) goto error;
	Pa_Terminate();
	return 0;
xrun:
  if( stream ) {
  Pa_AbortStream( stream );
  Pa_CloseStream( stream );
  }
 free( sampleBlock );
  Pa_Terminate();
  if( err & paInputOverflow )
  fprintf( stderr, "Input Overflow.\n" );
  if( err & paOutputUnderflow )
  fprintf( stderr, "Output Underflow.\n" );
  return -2;
error:
  if( stream ) {
  Pa_AbortStream( stream );
  Pa_CloseStream( stream );
  }
  free( sampleBlock );
  Pa_Terminate();
  fprintf( stderr, "An error occured while using the portaudio stream\n" );
  fprintf( stderr, "Error number: %d\n", err );
  fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
  return -1;
 }
int main (int argc, char ** argv) {
int buffersize;
int stereo;
int samplerate;
int numBytes;
int numSample;
int maxnumchannel_input;

// state of keypress
int state, oldstate;

// vars for portaudio
char * portaudiodevice;
int exact=0;
PaStreamParameters inputParameters;
PaStream * stream;
PaError pa_ret;

const PaDeviceInfo *devinfo;

// vars for networking
char * ipaddrtxtin;
int udpport;
struct sockaddr_in * udp_aiaddr_in = NULL;
struct sockaddr_in6 * udp_aiaddr_in6 = NULL;
struct sockaddr * sendto_aiaddr = NULL; // structure used for sendto
int sendto_sizeaiaddr=0; // size of structed used for sendto
int udpsd;
int udp_family;

char ipaddrtxt[INET6_ADDRSTRLEN];

// vars for getaddrinfo
struct addrinfo * hint;
struct addrinfo * info;

// for SAMPLE RATE CONVERSION
SRC_STATE *src=NULL;
SRC_DATA src_data;
int src_error;

// vars for codec2
void *codec2;
unsigned char *c2_buff;
int mode, nc2byte;

// vars for audio
int16_t * audiobuffer;
float * inaudiobuffer_f = NULL;
float * outaudiobuffer_f = NULL;

// other vars
int ret;

// structure for c2encap data
c2encap c2_voice;
c2encap c2_begin, c2_end;

// "audio in" posix thread
pthread_t thr_keypress;

// init data
stereo=-1;
global.transmit=0;

// We need at least 3 arguments: IP-address, udpport and samplerate
if (argc < 4) {
	fprintf(stderr,"Error: at least 3 arguments needed. \n");
	fprintf(stderr,"Usage: %s <ip-addr> <udp port> <samplerate> [ <audiodevice> [exact] ] \n",argv[0]);
	fprintf(stderr,"Note: allowed audio samplerate are 8000, 44100 or 48000 samples/second.\n");
	fprintf(stderr,"Note: use device \"\" to get list of devices.\n");
	exit(-1);
}; // end if

ipaddrtxtin=argv[1];
udpport=atoi(argv[2]);
samplerate=atoi(argv[3]);


// if 1st argument exists, use it as capture device
if (argc >= 5) {
	portaudiodevice = argv[4];

	// is there the "exact" statement?
	if (argc >= 6) {
		if (!strcmp(argv[5],"exact")) {
			exact=1;
		} else {
			fprintf(stderr,"Error: parameter \"exact\" expected. Got %s. Ignoring! \n",argv[5]);
		}; // end else - if
	}; // end if
} else {
	// no argument given
	portaudiodevice = NULL;
}; // end else - if



// create network structure
if ((udpport < 0) || (udpport > 65535)) {
	fprintf(stderr,"Error: UDPport number must be between 0 and 65535! \n");
	exit(-1);
}; // end if


if ((IPV4ONLY) && (IPV6ONLY)) {
	fprintf(stderr,"Error: internal configuration error: ipv4only and ipv6only are mutually exclusive! \n");
	exit(-1);
}; // end if


// sample rates below 8Ksamples/sec or above 48Ksamples/sec do not make sence
if (samplerate == 8000) {
	numSample = 320;
} else if (samplerate == 44100) {
	numSample = 1764;
} else if (samplerate == 48000) {
	numSample = 1920;
} else {
	fprintf(stderr,"Error: audio samplerate should be 8000, 44100 or 48000 samples/sec! \n");
	exit(-1);
}; // end if


// DO DNS query for ipaddress
hint=malloc(sizeof(struct addrinfo));

if (!hint) {
	fprintf(stderr,"Error: could not allocate memory for hint!\n");
	exit(-1);
}; // end if

// clear hint
memset(hint,0,sizeof(hint));

hint->ai_socktype = SOCK_DGRAM;

// resolve hostname, use function "getaddrinfo"
// set address family of hint if ipv4only or ipv6only
if (IPV4ONLY) {
	hint->ai_family = AF_INET;
} else if (IPV6ONLY) {
	hint->ai_family = AF_INET6;
} else {
	hint->ai_family = AF_UNSPEC;
}; // end else - elsif - if

// do DNS-query, use getaddrinfo for both ipv4 and ipv6 support
ret=getaddrinfo(ipaddrtxtin, NULL, hint, &info);

if (ret < 0) {
	fprintf(stderr,"Error: resolving hostname %s failed: (%s)\n",ipaddrtxtin,gai_strerror(ret));
	exit(-1);
}; // end if


udp_family=info->ai_family;

// open UDP socket + set udp port
if (udp_family == AF_INET) {
	udpsd=socket(AF_INET,SOCK_DGRAM,0);
	
	// getaddrinfo returns pointer to generic "struct sockaddr" structure.
	// 		Cast to "struct sockaddr_in" to be able to fill in destination port
	udp_aiaddr_in=(struct sockaddr_in *)info->ai_addr;
	udp_aiaddr_in->sin_port=htons((unsigned short int) udpport);

	// set pointer to be used for "sendto" ipv4 structure
	// sendto uses generic "struct sockaddr" just like the information
	// 		returned from getaddrinfo, so no casting needed here
	sendto_aiaddr=info->ai_addr;
	sendto_sizeaiaddr=sizeof(struct sockaddr);

	// get textual version of returned ip-address
	inet_ntop(AF_INET,&udp_aiaddr_in->sin_addr,ipaddrtxt,INET6_ADDRSTRLEN);
	
} else if (udp_family == AF_INET6) {
	udpsd=socket(AF_INET6,SOCK_DGRAM,0);

	// getaddrinfo returns pointer to generic "struct sockaddr" structure.
	// 		Cast to "struct sockaddr_in6" to be able to fill in destination port
	udp_aiaddr_in6=(struct sockaddr_in6 *)info->ai_addr;
	udp_aiaddr_in6->sin6_port=htons((unsigned short int) udpport);

	// set pointer to be used for "sendto" ipv4 structure
	// sendto uses generic "struct sockaddr" just like the information
	// 		returned from getaddrinfo, so no casting needed here
	sendto_aiaddr=info->ai_addr;
	sendto_sizeaiaddr=sizeof(struct sockaddr_in6);

	// get textual version of returned ip-address
	inet_ntop(AF_INET6,&udp_aiaddr_in6->sin6_addr,ipaddrtxt,INET6_ADDRSTRLEN);
	
} else {
	fprintf(stderr,"Error: DNS query for %s returned an unknown network-family: %d \n",ipaddrtxtin,udp_family);
	exit(-1);
}; // end if



// getaddrinfo can return multiple results, we only use the first one
// give warning is more then one result found.
// Data is returned in info as a linked list
// If the "next" pointer is not NULL, there is more then one
// element in the chain

if (info->ai_next != NULL) {
	fprintf(stderr,"Warning. getaddrinfo returned multiple entries. Using %s\n",ipaddrtxt);
}; // end if


if (udpsd < 0) {
	fprintf(stderr,"Error: could not create socket for UDP! \n");
	exit(-1);
}; // end if

// init c2encap structures
memcpy(c2_begin.header,C2ENCAP_HEAD,sizeof(C2ENCAP_HEAD));
c2_begin.header[3]=C2ENCAP_MARK_BEGIN;
memcpy(c2_begin.c2data.c2data_text3,"BEG",3);

memcpy(c2_end.header,C2ENCAP_HEAD,sizeof(C2ENCAP_HEAD));
c2_end.header[3]=C2ENCAP_MARK_END;
memcpy(c2_end.c2data.c2data_text3,"END",3);

memcpy(c2_voice.header,C2ENCAP_HEAD,sizeof(C2ENCAP_HEAD));
c2_voice.header[3]=C2ENCAP_DATA_VOICE1400;



// PORTAUDIO STUFF

fprintf(stderr,"INITIALISING PORTAUDIO    (this can take some time, please ignore any errors below) .... \n");
// open portaudio device
pa_ret=Pa_Initialize();
fprintf(stderr,".... DONE\n");

if (pa_ret != paNoError) {
	Pa_Terminate();
	fprintf(stderr,"Error: Could not initialise Portaudio: %s(%d) \n",Pa_GetErrorText(pa_ret),pa_ret);
	exit(-1);
}; // end if

if (portaudiodevice == NULL) {
	// portaudio device = NULL -> use portaudio "get default input device"
	inputParameters.device = Pa_GetDefaultInputDevice();

	if (inputParameters.device == paNoDevice) {
		fprintf(stderr,"Error: no portaudio default input device!\n");
		exit(-1);
	}; // end if

	if (inputParameters.device >= Pa_GetDeviceCount()) {
		fprintf(stderr,"Internal Error: portaudio \"GetDefaultInputDevice\" returns device number %d while possible devices go from 0 to %d \n,",inputParameters.device, (Pa_GetDeviceCount() -1) );
		exit(-1);
	}; // end if


	// check if device supports samplerate:
	inputParameters.sampleFormat = paInt16;
	inputParameters.suggestedLatency = 0; // not used in Pa_IsFormatSupported
	inputParameters.hostApiSpecificStreamInfo = NULL;

	devinfo = Pa_GetDeviceInfo (inputParameters.device);

   maxnumchannel_input = devinfo->maxInputChannels;
	printf("Audio device = %d (%s %s)\n",inputParameters.device,Pa_GetHostApiInfo(devinfo->hostApi)->name,devinfo->name);

	if (maxnumchannel_input >= 1) {
		// first check if samplerate is supported in mono
		inputParameters.channelCount = 1;
		pa_ret = Pa_IsFormatSupported(NULL,&inputParameters,(double) samplerate);

		if (pa_ret == paFormatIsSupported) {
			printf("Samplerate %d supported in mono.\n",samplerate);
			stereo=0;
		} else {
			// try again using stereo
			inputParameters.channelCount = 2;

			if (maxnumchannel_input >= 2) {
				pa_ret = Pa_IsFormatSupported(NULL,&inputParameters,(double) samplerate);

				if (pa_ret == paFormatIsSupported) {
					printf("Samplerate %d supported in stereo.\n",samplerate);
					stereo=1;
				} else {
					printf("Error: Samplerate %d not supported in mono or stereo!\n",samplerate);
					exit(-1);
				}; // end if
			} else {
				// stereo not supported on this device
				printf("Error: Samplerate %d not supported in mono. Stereo not supported on this device!\n",samplerate);
				exit(-1);
			}; // end if
		}; // end else - if
	} else {
		printf("Error: input not supported on this device!\n");
		exit(-1);
	}; // end if
	
	printf("\n");
	fflush(stdout);


} else {
	// CLI option "device" contains text, look throu list of all devices if there are
	// devices that match that name and support the particular requested samplingrate
	int loop;
	int numdevice;

	int numdevicefound=0;
	int devicenr=0;
	int devicestereo=0;



	// init some vars
	numdevice=Pa_GetDeviceCount();

	inputParameters.sampleFormat = paInt16;
	inputParameters.suggestedLatency = 0; // not used in Pa_IsFormatSupported
	inputParameters.hostApiSpecificStreamInfo = NULL;

	for (loop=0; loop<numdevice;loop++) {
		int devnamematch=0;

		// get name of device
		devinfo = Pa_GetDeviceInfo (loop);

		// only do check if searchstring is smaller or equal is size of device name
		if (strlen(devinfo->name) >= strlen(portaudiodevice)) {
			int numcheck;
			int devnamesize;
			int loop;
			char *p;

			// init pointer to beginning of string
			p=(char *)devinfo->name;
			devnamesize = strlen(portaudiodevice);

			if (exact) {
				// exact match, only check once: at the beginning
				numcheck=1;
			} else {
				numcheck=strlen(p) - strlen(portaudiodevice) +1;
			}; // end if

			// loop until text found or end-of-string
			for (loop=0; (loop<numcheck && devnamematch == 0); loop++) {
				if (strncmp(portaudiodevice,p,devnamesize) ==0) {
					devnamematch=1;
				}; // end if

				// move up pointer
				p++;
			};
		}; // end if

		if (devnamematch) {
			printf("Audio device: %d (API: %s ,NAME: %s)\n",loop,Pa_GetHostApiInfo(devinfo->hostApi)->name,devinfo->name);

   		maxnumchannel_input = devinfo->maxInputChannels;

			if (maxnumchannel_input >= 1) {
				// next step: check if this device supports the particular requested samplerate
				inputParameters.device = loop;

				inputParameters.channelCount = 1;
				pa_ret = Pa_IsFormatSupported(NULL,&inputParameters,(double) samplerate);

				if (pa_ret == paFormatIsSupported) {
					printf("Samplerate %d supported in mono.\n",samplerate);
					numdevicefound++;
					devicenr=loop;
					devicestereo=0;
				} else {
					if (maxnumchannel_input >= 2) {
						inputParameters.channelCount = 2;
						pa_ret = Pa_IsFormatSupported(NULL,&inputParameters,(double) samplerate);

						if (pa_ret == paFormatIsSupported) {
							printf("Samplerate %d supported in stereo.\n",samplerate);
							numdevicefound++;
							devicenr=loop;
							devicestereo=1;
						} else {
							printf("Error: Samplerate %d not supported in mono or stereo.\n",samplerate);
						}; // end else - if
					} else {
						// stereo not supported on this device
						printf("Error: Samplerate %d not supported in mono. Stereo not supported on this device!\n",samplerate);
					}; // end if
				}; // end else - if
			} else {
				printf("Error: Input not supported on device.\n");
			}; // end if

			printf("\n");
			fflush(stdout);
		};// end if
	}; // end for

	// did we find any device
	if (numdevicefound == 0) {
		fprintf(stderr,"Error: did not find any audio-device supporting that audio samplerate\n");
		fprintf(stderr,"       Try again with other samplerate of devicename \"\" to get list of all devices\n");
		exit(-1);
	} else if (numdevicefound > 1) {
		fprintf(stderr,"Error: Found multiple devices matching devicename supporting that audio samplerate\n");
		fprintf(stderr,"       Try again with a more strict devicename or use \"exact\" clause!\n");
		exit(-1);
	} else {
		// OK, we have exactly one device: copy its parameters
		inputParameters.device=devicenr;
		stereo=devicestereo;

		if (devicestereo) {
			inputParameters.channelCount = 2;
		} else {
			inputParameters.channelCount = 1;
		}; // end else - if

		// get name info from device
		devinfo = Pa_GetDeviceInfo (inputParameters.device);

		fprintf(stderr,"Selected Audio device = (API: %s ,NAME: %s)\n",Pa_GetHostApiInfo(devinfo->hostApi)->name,devinfo->name);
	};
}; // end else - if

// set other parameters of inputParameters structure
inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;

// configure portaudio global data
if (samplerate == 8000) {
	numSample = 320;
} else if (samplerate == 44100) {
	numSample = 1764;
} else if (samplerate == 48000) {
	numSample = 1920;
} else {
	fprintf(stderr,"Error: invalid value for samplerate in funct_audioout: %d !\n",samplerate);
	exit(-1);
}; // end if


// configure portaudio global data
if (stereo) {
	numBytes = (numSample << 2);
} else {
	numBytes = (numSample << 1); 
}; // end if

// create memory for audiobuffer
audiobuffer = malloc(numBytes); // allow memory for buffer 0
if (!audiobuffer) {
	// memory could not be allocated
	fprintf(stderr,"Error: could not allocate memory for portaudio buffer 0!\n");
	exit(-1);
}; // end if


// some network debug info
fprintf(stderr,"Sending CODEC2 DV stream to ip-address %s udp port %d\n",ipaddrtxt,udpport);


// open PortAudio stream
// do not start stream yet, will be done further down
pa_ret = Pa_OpenStream (
	&stream,
	&inputParameters,
	NULL, // output Parameters, not used here 
	samplerate, // sample rate
	numSample, // frames per buffer: 40 ms @ 8000 samples/sec
	paClipOff, // we won't output out of range samples,
					// so don't bother clipping them
	NULL, // no callback function, syncronous read
	&global // parameters passed to callback function (not used here)
);

if (pa_ret != paNoError) {
	Pa_Terminate();
	fprintf(stderr,"Error in Pa_OpenStream: %s(%d) \n",Pa_GetErrorText(pa_ret),pa_ret);
	exit(-1);
}; // end if

// init codec2
mode = CODEC2_MODE_1400;
codec2 = codec2_create (mode);

nc2byte = (codec2_bits_per_frame(codec2) + 7) >> 3; // ">>3" is same as "/8"

if (nc2byte != 7) {
	fprintf(stderr,"Error: number of bytes for codec2 frames should be 7. We got %d \n",nc2byte);
}; // end if

if (codec2_samples_per_frame(codec2) != 320) {
	fprintf(stderr,"Error: number of samples for codec2 frames should be 320. We got %d \n",codec2_samples_per_frame(codec2));
}; // end if

c2_buff = (unsigned char *)&c2_voice.c2data.c2data_data7;


// allocate audiobuffer
if (stereo) {
	buffersize= numSample << 2; // = number of samples  * 4 (stereo and 16 bit/sample)
} else {
	// mono
	buffersize= numSample << 1; // = number of samples * 2 (16 bit/sample)
}; // end else - if
audiobuffer=malloc(buffersize);

if (!audiobuffer) {
	fprintf(stderr,"Error: malloc audiobuffer: %s",strerror(errno));
	exit(-1);
}; // end if


// init samplerate conversion
if (samplerate != 8000) {

// allocate memory for audio sample buffers (only needed when audio rate conversion is used)
	inaudiobuffer_f=malloc(numSample * sizeof(float));
	if (!inaudiobuffer_f) {
		fprintf(stderr,"Error in malloc for inaudiobuffer_f! \n");
		exit(-1);
	}; // end if

	outaudiobuffer_f=malloc(320 * sizeof(float)); // output buffer is 320 samples (40 ms @ 8000 samples/sec)
	if (!outaudiobuffer_f) {
		fprintf(stderr,"Error in malloc for outaudiobuffer_f! \n");
		exit(-1);
	}; // end if

	src = src_new(SRC_SINC_FASTEST,1,&src_error);

	if (!src) {
		fprintf(stderr,"src_new failed! \n");
		exit(-1);
	}; // end if

	src_data.data_in = inaudiobuffer_f;
	src_data.data_out = outaudiobuffer_f;
	src_data.input_frames = numSample;
	src_data.output_frames = 320; // 40 ms @ 8000 samples / sec
	src_data.end_of_input = 0; // no further data, every 40 ms frame is concidered to be a seperate unit

	if (samplerate == 48000) {
		src_data.src_ratio = (float) 8000/48000;
	} else {
		src_data.src_ratio = (float) 8000/44100;
	}; // end else - if
}; // end if


// start thread to read detect keypress (used to switch transmitting)
pthread_create (&thr_keypress, NULL, funct_keypress, (void *) &global);


// Start stream
pa_ret=Pa_StartStream(stream);

if (pa_ret != paNoError) {
	Pa_Terminate();
	fprintf(stderr,"Error in Pa_StartStream: %s(%d) \n",Pa_GetErrorText(pa_ret),pa_ret);
	exit(-1);
}; // end if


// init some vars;
oldstate=0;


while (( pa_ret = Pa_IsStreamActive (stream)) == 1) {
// get audio

	pa_ret = Pa_ReadStream(stream, audiobuffer, numSample);

	if (pa_ret != paNoError) {
		Pa_Terminate();
		fprintf(stderr,"Error in Pa_ReadStream: %s(%d) \n",Pa_GetErrorText(pa_ret),pa_ret);
		exit(-1);
	}; // end if


	// get state from subthread
	state=global.transmit;

	if (state) {
		// State = 1: write audio

		// first check old state, if we go from oldstate=0 to state=1, this is
		// the beginning of a new stream; so send start packe
		if (oldstate == 0) {
			// start "start" marker
			// fwrite((void *) &c2_begin,C2ENCAP_SIZE_MARK,1,stdout);
			// fflush(stdout);

			// send start 3 times, just to be sure
			sendto(udpsd,&c2_begin,C2ENCAP_SIZE_MARK,0,sendto_aiaddr, sendto_sizeaiaddr);
			sendto(udpsd,&c2_begin,C2ENCAP_SIZE_MARK,0,sendto_aiaddr, sendto_sizeaiaddr);
			sendto(udpsd,&c2_begin,C2ENCAP_SIZE_MARK,0,sendto_aiaddr, sendto_sizeaiaddr);

//			putc('B',stderr);
		}


		// if stereo, only use left channel
		if (stereo) {
			int loop;

			int16_t *p1, *p2;

			// start at 2th element (in stereo format); which is 3th (in mono format)
			p1=&audiobuffer[1];
			p2=&audiobuffer[2];
	
			for (loop=1; loop < numSample; loop++) {
				*p1=*p2;
				p1++; p2 += 2;
			}; // end for
		}; // end if


		// if not 8000 samples / second: convert
		if (samplerate != 8000) {
fprintf(stderr,"2!!! \n");
			if (!inaudiobuffer_f) {
				fprintf(stderr,"Internal Error: inaudiobuffer_f not initialised \n");
				exit(-1);
			}; // end if

			if (!outaudiobuffer_f) {
				fprintf(stderr,"Internal Error: outaudiobuffer_f not initialised \n");
				exit(-1);
			}; // end if

			// convert int16 to float
			src_short_to_float_array(audiobuffer,inaudiobuffer_f,numSample);

			// convert
			ret=src_process(src,&src_data);

			if (ret) {
				fprintf(stderr,"Warning: samplerate conversion error %d (%s)\n",ret,src_strerror(ret));
			}; // end if

			// some error checking
			if (src_data.output_frames_gen != 320) {
				fprintf(stderr,"Warning: number of frames generated by samplerateconvert should be %d, got %ld. \n",numSample,src_data.output_frames_gen);
			}; // end if

			// convert back from float to int
			src_float_to_short_array(outaudiobuffer_f,audiobuffer,320); // 40 ms @ 8000 samples/sec = 320 samples

fprintf(stderr,"3!!! \n");
		}; // end if

		// do codec2 encoding
		codec2_encode(codec2, c2_buff, audiobuffer);

		//fwrite((void *)&c2_voice,C2ENCAP_SIZE_VOICE1400,1,stdout);
		//fflush(stdout);

		sendto(udpsd,&c2_voice,C2ENCAP_SIZE_VOICE1400,0,sendto_aiaddr, sendto_sizeaiaddr);

//		putc('T',stderr);
	} else {
		// state = 0, do not send
		// however, if we go from "oldstate = 1 - > state = 0", this is
		// the end of a stream

		if (oldstate) {
			// send "end" marker
			//fwrite((void *)&c2_end,C2ENCAP_SIZE_MARK,1,stdout);
			//fflush(stdout);

			// send end 3 times, just to be sure
			sendto(udpsd,&c2_end,C2ENCAP_SIZE_MARK,0,sendto_aiaddr, sendto_sizeaiaddr);
			sendto(udpsd,&c2_end,C2ENCAP_SIZE_MARK,0,sendto_aiaddr, sendto_sizeaiaddr);
			sendto(udpsd,&c2_end,C2ENCAP_SIZE_MARK,0,sendto_aiaddr, sendto_sizeaiaddr);

//			putc('E',stderr);
		}; // end if 
	}; // end else - if

	oldstate=state;

	
}; // end while
// dropped out of endless loop. Should not happen

if (pa_ret < 0) {
	Pa_Terminate();
	fprintf(stderr,"Error in Pa_isStreamActive: %s(%d) \n",Pa_GetErrorText(pa_ret),pa_ret);
	exit(-1);
}; // end if

fprintf(stderr,"Error: audiocap dropped out of audiocapturing loop. Should not happen!\n");

pa_ret=Pa_CloseStream(stream);

if (pa_ret != paNoError) {
	Pa_Terminate();
	fprintf(stderr,"Error in Pa_CloseStream: %s(%d) \n",Pa_GetErrorText(pa_ret),pa_ret);
	exit(-1);
}; // end if

// Done!!!

Pa_Terminate();

exit(0);


}; // end main applicion
Beispiel #29
0
int main(void)
{
    PaStreamParameters inputParameters, outputParameters;
    PaStream *stream;
    PaError err;
    SAMPLE *recordedSamples;
    int i;
    int totalFrames;
    int numSamples;
    int numBytes;
    SAMPLE max, average, val;
    
    
    printf("patest_read_record.c\n"); fflush(stdout);

    totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */
    numSamples = totalFrames * NUM_CHANNELS;

    numBytes = numSamples * sizeof(SAMPLE);
    recordedSamples = (SAMPLE *) malloc( numBytes );
    if( recordedSamples == NULL )
    {
        printf("Could not allocate record array.\n");
        exit(1);
    }
    for( i=0; i<numSamples; i++ ) recordedSamples[i] = 0;

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

    inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
    if (inputParameters.device == paNoDevice) {
      fprintf(stderr,"Error: No default input device.\n");
      goto error;
    }
    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 */
    if (outputParameters.device == paNoDevice) {
      fprintf(stderr,"Error: No default output device.\n");
      goto error;
    }
    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 #30
0
static enum audiotap_status portaudio_set_buffer(void *priv, int32_t *buffer, uint32_t bufsize, uint32_t *numframes){
  if (Pa_ReadStream((PaStream*)priv, buffer, bufsize) != paNoError)
    return AUDIOTAP_LIBRARY_ERROR;
  *numframes=bufsize;
  return AUDIOTAP_OK;
}