/* CSL - Common Sound Layer
 * Copyright (C) 2001 Jeff Tranter
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General
 * Public License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/* 
 * This example illustrates playing PCM sound data. It is similar
 * to the cslcat program. I should probably rework this so it
 * reads from standard input to make it more useful.
 */

#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <csl/csl.h>

int main (int argc, char **argv)
{
	CslErrorType error;
	CslDriver *driver;
	CslPcmStream *stream;
	CslOptions options;
	const int size = 1024;
	short buffer[size];
	int i, j, len, fd;

/* Here I pick a specific data format. In a real app you probably want
 * to allow the user to set it from the command line using something
 * like this:
 *
 * csl_options_parse (&options, &argc, &argv);
 * csl_set_debug_mask (options.debug_flags);
 */

	/* 16 bit, signed, little endian, stereo, 44100 samples/sec */
	options.n_channels = 2;
	options.rate = 44100;
	options.pcm_format = CSL_PCM_FORMAT_S16_LE;

	printf("data format: %s\n", csl_describe_pcm_format(options.pcm_format));

	/* init driver */
	error = csl_driver_init (NULL, &driver);	/* choose backend */
	if (error)
		csl_error ("unable to initialize driver: %s", csl_strerror (error));
	
	/* open PCM output stream */
	error = csl_pcm_open_output (driver, "cslpcm1", options.rate, options.n_channels, options.pcm_format, &stream);
	if (error)
		csl_error ("failed to open output device: %s", csl_strerror (error));

	/* input source is random generator */
	fd = open("/dev/urandom", O_RDONLY);
	if (fd == -1)
		csl_error("unable to open input device /dev/urandom");


    /* generate some random data (sounds like white noise) */	
	for (i=0; i <500; i++)
	{
		len = read(fd, buffer, size);
		if (len != size)
			csl_warning("short read");
		for (j = 0; j < size; j++)
			buffer[j] = CLAMP(buffer[j], -4000, 4000); /* clamp it to limit volume */
		len = csl_pcm_write (stream, size, buffer);
		if (len != size)
			csl_warning("short write");
	}
	
	/* clean up */
	csl_pcm_close (stream);
	csl_driver_shutdown (driver);
	
	return 0;
}
