/* 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 recording PCM sound data. It reads
 * 500K of sound data (about 3 seconds of audio at the default
 * settings) and writes it to standard output.
 */

#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;
	const int blocks = 500;
	short buffer[size];
	int i, len;

	csl_options_parse (&options, &argc, &argv);
	csl_set_debug_mask (options.debug_flags);

	fprintf(stderr, "Data format: %d channels, %d samples/sec, %s\n",
			options.n_channels, options.rate, csl_describe_pcm_format(options.pcm_format));

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

	/* read some data and write it to standard output */
	fprintf(stderr, "Reading %d bytes and writing to standard out\n", blocks*size);
	for (i = 0; i < blocks; i++)
	{
		len = csl_pcm_read (stream, size, buffer);
		if (len != size)
			csl_warning("short read");
		len = write(1, buffer, size);
		if (len != size)
			csl_warning("short write");
	}
	fprintf(stderr, "Done\n");

	/* clean up */
	csl_pcm_close (stream);
	csl_driver_shutdown (driver);
	
	return 0;
}
