#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/soundcard.h>

#define DEVICE_NAME "/dev/dsp2"
#define FORMAT AFMT_S16_LE
#define CHANNELS 2
#define SAMPLE_RATE 44100

int audio_fd;

int main()
{
	int format = FORMAT;
	int channels = CHANNELS;
	int sample_rate = SAMPLE_RATE;

	if ((audio_fd = open(DEVICE_NAME, O_WRONLY, 0)) == -1) {
		perror(DEVICE_NAME);
		exit(1);
	}
	fprintf(stderr, "Opening of %s successful\n", DEVICE_NAME);

	if (ioctl(audio_fd, SNDCTL_DSP_SETFMT, &format) == -1) {
		perror("SNDCTL_DSP_SETFMT");
		close(audio_fd);
		exit(1);
	}
	if (format != FORMAT) {
		fprintf(stderr, "Set format failed with wrong format\n");
		close(audio_fd);
		exit(1);
	}
	fprintf(stderr, "Set format successful\n");

	if (ioctl(audio_fd, SNDCTL_DSP_CHANNELS, &channels) == -1) {
		perror("SNDCTL_DSP_CHANNELS");
		close(audio_fd);
		exit(1);
	}
	if (channels != CHANNELS) {
		fprintf(stderr, "Set channels to %d failed\n", CHANNELS);
		fprintf(stderr, "   returned %d\n", channels);
		close(audio_fd);
		exit(1);
	}
	fprintf(stderr, "Set channels to %d successful\n", channels);

	if (ioctl(audio_fd, SNDCTL_DSP_SPEED, &sample_rate) == -1) {
		perror("SNDCTL_DSP_SPEED");
		close(audio_fd);
		exit(1);
	}
	if (sample_rate != SAMPLE_RATE) {
		fprintf(stderr, "Set sample rate to %d failed\n", SAMPLE_RATE);
		fprintf(stderr, "   returned rate: %d\n", sample_rate);
		close(audio_fd);
		exit(1);
	}
	fprintf(stderr, "Set sample rate to %d successful\n", sample_rate);

	close(audio_fd);
	return 0;
}
