bool PortAudioDeviceDriver::renderSound(yarp::sig::Sound& sound)
{
    int freq  = sound.getFrequency();
    int chans = sound.getChannels();
    if (freq  != this->frequency ||
        chans != this->numChannels)
    {
        //wait for current playback to finish
        while (Pa_IsStreamStopped(stream )==0)
        {
            yarp::os::Time::delay(SLEEP_TIME);
        }

        //reset the driver
        printf("***** driver configuration changed, resetting *****\n");
        this->close();
        driverConfig.channels = chans;
        driverConfig.rate = freq;
        bool ok = open(driverConfig);
        if (ok == false)
        {
            printf("error occurred during driver reconfiguration, aborting\n");
            return false;
        }
    }

    if (renderMode == RENDER_IMMEDIATE)
        return immediateSound(sound);
    else if (renderMode == RENDER_APPEND)
        return appendSound(sound);

    return false;
}
bool PortAudioDeviceDriver::getSound(yarp::sig::Sound& sound)
{
    if (pThread.something_to_record == false)
    {
        this->startRecording();
    }

    int buff_size = 0;
    static int buff_size_wdt = 0;
    while (buff_size<this->numSamples*this->numChannels)
    {
         buff_size = dataBuffers.recData->size();
         if (buff_size == 0 && buff_size_wdt++ == 100) break;
         yarp::os::SystemClock::delaySystem(SLEEP_TIME);
    }
    buff_size_wdt = 0;

    if (sound.getChannels()!=this->numChannels && sound.getSamples() != this->numSamples)
    {
        sound.resize(this->numSamples,this->numChannels);
    }
    sound.setFrequency(this->driverConfig.rate);

    for (int i=0; i<this->numSamples; i++)
        for (int j=0; j<this->numChannels; j++)
            {
                SAMPLE s = dataBuffers.recData->read();
                sound.set(s,i,j);
            }
    return true;
}
bool PortAudioDeviceDriver::appendSound(yarp::sig::Sound& sound)
{
    //unsigned char* dataP= sound.getRawData();
    int num_bytes = sound.getBytesPerSample();
    int num_channels = sound.getChannels();
    int num_samples = sound.getRawDataSize()/num_channels/num_bytes;
    // memcpy(data.samplesBuffer,dataP,num_samples/**num_bytes*num_channels*/);

    for (int i=0; i<num_samples; i++)
        for (int j=0; j<num_channels; j++)
            dataBuffers.playData->write (sound.get(i,j));

    pThread.something_to_play = true;
    return true;
}