// Copyright 1994 Brad Pitzel
//
// Feel free to use/distribute/modify as long as credit/copyrights for myself 
// are included.

// Sound code: still under construction, and not extensively tested.
// For now, the sound code is NOT compiled into sasteroids by default

#include "Sound.h"
#include <iostream.h>

int Sound::dsp_fd=-1;

#ifdef TEST_SOUND
int Sound::init()
	{
	dsp_fd = open("/dev/dsp"  , O_WRONLY | O_NONBLOCK);
	
	if (dsp_fd==-1)
		{
		cerr << "Cannot open /dev/dsp for sound." << endl;
		return -1;
		}

	return 0;
	}
	
void Sound::restore() 
	{ 
	if (dsp_fd!=-1) close(dsp_fd); 
	}

int Sound::playwave( int samplerate, int bitspersample, 
                      int stereo, long size, void *data ) 
	{
	int bps;
	bps = bitspersample;
/*
	ioctl( dsp_fd, SNDCTL_DSP_GETBLKSIZE, &audiobufsize );
	printf( "audiobufsize is %li\n", audiobufsize );
*/
		
	ioctl( dsp_fd, SNDCTL_DSP_SAMPLESIZE, &bps );
	if( bps!=bitspersample )
		{
		cerr << "Sound::playwave, Invalid nr of bits per sample\n";
		return -1;
		}
		
	ioctl( dsp_fd, SNDCTL_DSP_SPEED, &samplerate );
	if( samplerate==-1 )
		{
		cerr << "Sound::playwave, Invalid samplerate\n";
		return -1;
		}
		
	ioctl( dsp_fd, SNDCTL_DSP_STEREO, &stereo );

	// I need to 'chunk' the sound instead of writing it all out,
	// because the sound data might be larger than the /dev/dsp
	// buffer.		
	write( dsp_fd, data, size );

	// this seems to get the sound to start playing right away..
	ioctl(dsp_fd, SNDCTL_DSP_POST, 0);
	
	return 0;
	}
	
	
void Sound::play_file(char *file)
	{
	int buffersize, fd;
	char *buffer;

	fd = open(file, O_RDONLY);

	buffersize = lseek(fd, 0, SEEK_END);
	lseek(fd, 0, SEEK_SET);

	buffer =  new char[buffersize];
	read(fd, buffer, buffersize);

	// kills any sound currently playing so our new sound
	// will be heard immmediately.  Need to figure out a way
	// to dynamically mix sound files so that 2 or more
	// sounds can be heard at once.
	ioctl(dsp_fd, SNDCTL_DSP_RESET, 0);

	playwave( 8000, 8, 0, buffersize, buffer);

	delete [] buffer;
	}

#else
// Sound not compiled in, so just use stub routines.
int Sound::init() 
	{
	return 0;
	}

void Sound::restore() 
	{
	}

int Sound::playwave( int samplerate, int bitspersample, 
              int stereo, long size, void *data ) 
        {
        return 0;
        }

void Sound::play_file(char *file) 
	{
	}

#endif
