// Runs update logic
void KissFileSampleApp::update() 
{

	// Check if track is playing and has a PCM buffer available
	if (mTrack->isPlaying() && mTrack->isPcmBuffering())
	{

		// Get buffer
		mBuffer = mTrack->getPcmBuffer();
		if (mBuffer && mBuffer->getInterleavedData())
		{

			// Get sample count
			uint32_t mSampleCount = mBuffer->getInterleavedData()->mSampleCount;
			if (mSampleCount > 0)
			{

				// Initialize analyzer, if needed
				if (!mFftInit)
				{
					mFftInit = true;
					mFft.setDataSize(mSampleCount);
				}

				// Analyze data
				if (mBuffer->getInterleavedData()->mData != 0) 
					mFft.setData(mBuffer->getInterleavedData()->mData);

			}

		}

	}

}
// Set up
void KissFileSampleApp::setup()
{

	// Set up window
	setWindowSize(600, 600);

	// Set up OpenGL
	gl::enableAlphaBlending();
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	glEnable(GL_LINE_SMOOTH);
	glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);

	// Set line color
	gl::color(Color(1, 1, 1));
	
	// Load and play audio
	mAudioSource = audio::load(loadResource(RES_SAMPLE));
	mTrack = audio::Output::addTrack(mAudioSource, false);
	mTrack->enablePcmBuffering(true);
	mTrack->play();

	// Set init flag
	mFftInit = false;

}
//*************************************************************************
void BeatDetectorApp::NextFile()
{
	roto = 0;
	if(mTrack && mTrack->isPlaying())
	{
		mTrack->enablePcmBuffering(false);
		mTrack->stop();
	}

#ifdef WIN32
	time_t now;
	time(&now);
	int time_int = (int)now;
#else
	timeval now;
	gettimeofday(&now, NULL);
	int time_int = now.tv_sec;
#endif

	Rand r;
	r.seed(time_int);
	int rand_file = r.nextInt(m_FileList.size());
	path my_path = m_FileList[rand_file].path();
	m_CurrentFile = my_path.string();
	
	if(!write_frames)
	{
		mAudioSource = audio::load(m_CurrentFile);
		mTrack = audio::Output::addTrack(mAudioSource, false);
		mTrack->enablePcmBuffering(true);
		mTrack->play();		
	}
	//rot_inc = r.nextFloat(1.5f, 30.0f);
}
//*************************************************************************
void BeatDetectorApp::keyDown(KeyEvent event)
{
	switch(event.getChar())
	{
		case 'n':
			NextFile();
			break;
		case 'f':
			setFullScreen(!isFullScreen());
			break;
		case 'p':
			if(mTrack)
			{
				if(mTrack->isPlaying())
				{
					mTrack->stop();
				}
				else
				{
					mTrack->play();
				}
			}
			break;
	}
}
// Called on exit
void KissFileSampleApp::quit() 
{

	// Stop track
	mTrack->enablePcmBuffering(false);
	mTrack->stop();

}
//*************************************************************************
void BeatDetectorApp::update() 
{
	if(write_frames)
	{
		if(curr_sample < p_sample->m_SampleCount)
		{
			// Initialize analyzer, if needed
			if (!mFftInit)
			{
				Init(samples_per_frame);
			}
			
			mFft.setData(p_sample->mp_Buffer + (curr_sample));
			curr_sample += samples_per_frame;

			CSoundAnalyzer::Get().ProcessData(mFft.getAmplitude(), mFft.getData());
		}
		else
		{
			shutdown();
		}
	}
	else
	{
		// Check if track is playing and has a PCM buffer available
		if (mTrack->isPlaying() && mTrack->isPcmBuffering())
		{
			// Get buffer
			mBuffer = mTrack->getPcmBuffer();
			if (mBuffer && mBuffer->getInterleavedData())
			{
				// Get sample count
				uint32_t mSampleCount = mBuffer->getChannelData(CHANNEL_FRONT_LEFT)->mSampleCount;
				
				if (mSampleCount > 0)
				{
					// Initialize analyzer, if needed
					if (!mFftInit)
					{
						Init(samples_per_frame);
					}
					
					// Analyze data
					if (mBuffer->getChannelData(CHANNEL_FRONT_LEFT)->mData != 0) 
						mFft.setData(mBuffer->getChannelData(CHANNEL_FRONT_LEFT)->mData);

					CSoundAnalyzer::Get().ProcessData(mFft.getAmplitude(), mFft.getData());
				}
			}
		}
	}
}
void AudioAnalysisSampleApp::setup()
{
    //mTrack1 = audio::Output::addTrack( audio::load( "C:\\code\\cinder\\samples\\AudioPlayback\\resources\\booyah.mp3" ) );
    //mTrack1->setPcmBuffering( true );
    mTrack1 = audio::Output::addTrack( audio::load( loadResource( RES_TTV ) ) );
    mTrack1->setPcmBuffering( true );
    //mTrack2 = audio::Output::addTrack( audio::load( loadResource( RES_DRUMS ) ) );
    //mTrack2->setPcmBuffering( true );
}
void RoboticaProjectApp::setup()
{
    
    
    
    bandCount = 12;
    
    particleImg = new gl::Texture( loadImage( loadResource( RES_PARTICLE ) ) );
    
    //add the audio track the default audio output
	mTrack = audio::Output::addTrack( audio::load( loadResource( RES_WOLFGANG ) ) );
    mTrack.get()->setLooping(true);
    
    audio::Output::setVolume(2);
	//you must enable enable PCM buffering on the track to be able to call getPcmBuffer on it later
	mTrack->enablePcmBuffering( true );

    particleC = new ParticleController(getWindowSize(), bandCount);
    
}
void SoundScapingApp::setup() {
   setFullScreen(true);
    
    //add the audio track the default audio output
	//mTrack = audio::Output::addTrack( audio::load( loadResource( "../resources/drums.mp3", 129, "MP3" )));
    mTrack = audio::Output::addTrack( audio::load( loadResource( "../resources/MakeLight.m4a", 129, "M4A" )));
	
	//you must enable enable PCM buffering on the track to be able to call getPcmBuffer on it later
	mTrack->enablePcmBuffering( true );
    
    bandCount = 50;;
    cumlFFT = std::vector<float>(bandCount, 0.0f);

}
void RoboticaProjectApp::update()
{
    //get the latest pcm buffer from the track
	mPcmBuffer = mTrack->getPcmBuffer();
    
    if( mPcmBuffer ){
       // mPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT )
        fftRef = audio::calculateFft( mPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT ), bandCount );
        if(mAddParticle){
            particleC->addParticle(mAddPos);
            mAddParticle = false;
        }
        
        particleC->update(fftRef, bandCount, getElapsedSeconds());
    }    
        
    
    
}
void AudioAnalysisSampleApp::drawWaveForm( audio::TrackRef track )
{


    audio::PcmBuffer32fRef aPcmBuffer = track->getPcmBuffer();
    if( ! aPcmBuffer ) {
        return;
    }



    uint32_t bufferSamples = aPcmBuffer->getSampleCount();


    audio::Buffer32fRef leftBuffer = aPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT );
    audio::Buffer32fRef rightBuffer = aPcmBuffer->getChannelData( audio::CHANNEL_FRONT_RIGHT );

    int displaySize = getWindowWidth();
    int endIdx = bufferSamples;

    float scale = displaySize / (float)endIdx;

    glColor3f( 1.0f, 0.5f, 0.25f );
    glBegin( GL_LINE_STRIP );
    for( int i = 0; i < endIdx; i++ ) {
        float y = ( ( leftBuffer->mData[i] - 1 ) * - 100 );
        glVertex2f( ( i * scale ) , y );
    }
    glEnd();

    glColor3f( 1.0f, 0.96f, 0.0f );
    glBegin( GL_LINE_STRIP );
    for( int i = 0; i < endIdx; i++ ) {
        float y = ( ( rightBuffer->mData[i] - 1 ) * - 100 );
        glVertex2f( ( i * scale ) , y );
    }
    glEnd();
}
void AudioAnalysisSampleApp::drawFft( audio::TrackRef track )
{


    float ht = (float)getWindowHeight();

    float dutyCycle = 0.8;
    float barWidth = (float)getWindowWidth()/(float)kBandCount;

    audio::PcmBuffer32fRef aPcmBuffer = track->getPcmBuffer();
    if( ! aPcmBuffer ) {
        return;
    }
    boost::shared_ptr<float> fftRef = audio::calculateFft( aPcmBuffer->getChannelData( audio::CHANNEL_FRONT_LEFT ), kBandCount );
    if( ! fftRef ) {
        return;
    }

    float * fftBuffer = fftRef.get();

    welch->addFft(fftBuffer);

    float * fftDisplayBuffer = welch->getFft();

// float *fftDisplayBuffer = fftRef.get();

    for( int i = 0; i < ( kBandCount ); i++ ) {
        float barY = 10.0f*kFFTHistory*fftDisplayBuffer[i] / kBandCount * ht;
        glBegin( GL_QUADS );
        glColor3f( 255.0f, 255.0f, 0.0f );
        glVertex2f( i * barWidth, ht );
        glVertex2f( i * barWidth + barWidth*dutyCycle, ht );
        glColor3f( 0.0f, 255.0f, 0.0f );
        glVertex2f( i * barWidth + barWidth*dutyCycle, ht - barY );
        glVertex2f( i * barWidth, ht - barY );
        glEnd();
    }
}
void AudioNewTestApp::keyDown( KeyEvent event )
{
	//float volume = audio::Output::getVolume();
	float volume = mTrack1->getVolume();
	switch( event.getChar() ) {
		case 'q':
			//audio::Output::setVolume( volume + 0.1f );
			mTrack1->setVolume( volume + 0.1f );
		break;
		case 'a':
			//audio::Output::setVolume( volume - 0.1f );
			mTrack1->setVolume( volume - 0.1f );
		break;
		case 'w':
			mTrack1->setTime( 1.5 );
			console() << mTrack1->getTime() << std::endl;
		break;
	}
	console() << mTrack1->getVolume() << std::endl;
}
void AudioAnalysisSampleApp::keyDown( KeyEvent e ) {
    if( e.getChar() == 'p' ) {
        ( mTrack1->isPlaying() ) ? mTrack1->stop() : mTrack1->play();
    }
}
void SoundScapingApp::update() {
    //get the latest pcm buffer from the track
	mPcmBuffer = mTrack->getPcmBuffer();
}
//*************************************************************************
void BeatDetectorApp::quit() 
{
	// Stop track
	mTrack->enablePcmBuffering(false);
	mTrack->stop();
}