/*  SpiralSynth
 *  Copyleft (C) 2000 David Griffiths <dave@pawfal.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/ 

#include "Output.h"

Output::Output() :
m_Amp(0.5)
{
	Init();
	m_Buffer = new short[SpiralInfo::BUFSIZE];
	for (int n=0; n<SpiralInfo::BUFSIZE; n++)
	{
		m_Buffer[n]=0;
	}
}

void Output::Send(short *data) 
{
	for (int n=0; n<SpiralInfo::BUFSIZE; n++)
	{
		data[n]=static_cast<short>(data[n]*m_Amp);
		
		// clip
		if (data[n]<-SpiralInfo::MAXSAMPLE/2) data[n]=static_cast<short>(-SpiralInfo::MAXSAMPLE/2);
		if (data[n]>SpiralInfo::MAXSAMPLE/2) data[n]=static_cast<short>(SpiralInfo::MAXSAMPLE/2);
		
		m_Buffer[n]+=(short)(data[n]);
	}
}

void Output::Play()
{
	#if __BYTE_ORDER == BIG_ENDIAN
	static short *buf16 = new short[SpiralInfo::BUFSIZE];
	for (int n=0; n<SpiralInfo::BUFSIZE; n++)
	{
		buf16[n]=(short)((m_Buffer[n]<<8)&0xff00) | ((m_Buffer[n]>>8)&0xff);
	}
	if (SpiralInfo::REALTIMEOUT)
	{
		write(m_Dspfd,buf16,sizeof(short)*SpiralInfo::BUFSIZE);
	}
	
	if(m_Wav.Recording()) 
	{
		m_Wav.Save(SpiralInfo::BUFSIZE,buf16);
	}
	#else
	if (SpiralInfo::REALTIMEOUT)
	{
		write(m_Dspfd,m_Buffer,sizeof(short)*SpiralInfo::BUFSIZE);
	}
	
	if(m_Wav.Recording()) 
	{
		m_Wav.Save(SpiralInfo::BUFSIZE,m_Buffer);
	}
	#endif
}

void Output::ClearBuffer()
{
	for (int n=0; n<SpiralInfo::BUFSIZE; n++)
	{
		m_Buffer[n]=0;
	}
}

void Output::Init()
{ 
  if (!SpiralInfo::REALTIMEOUT)
  {
  	return;
  }	
	
  int r,val;
  
  m_Dspfd = open(SpiralInfo::OUTPUTFILE.c_str(),O_WRONLY);  
  if(m_Dspfd<0) 
  	{
     fprintf(stderr,"Can't open audio driver.\n");
     exit(999);
  	}
   
  r = ioctl(m_Dspfd,SNDCTL_DSP_RESET,NULL);

  if (r>=0)
  	{
	 val=262152;
	 r=ioctl(m_Dspfd, SNDCTL_DSP_SETFRAGMENT, &val);
    }
  if(r>=0) 
  	{
	 val = 1;
     r = ioctl(m_Dspfd, SOUND_PCM_WRITE_CHANNELS, &val);
	}
  if(r>=0) 
  	{
     val = AFMT_S16_LE;
     r = ioctl(m_Dspfd,SNDCTL_DSP_SETFMT,&val);	 
  	}
  if(r>=0) 
  	{
     val = 0;
     r = ioctl(m_Dspfd,SNDCTL_DSP_STEREO,&val);
  	}
  if(r>=0) 
  	{
     val = SpiralInfo::SAMPLERATE;
     r = ioctl(m_Dspfd,SNDCTL_DSP_SPEED,&val);
  	}
  if(r<0) 
  	{
     fprintf(stderr,"Sound device did not accept settings.\n");
     exit(999);
  	}  
}

