/*
 * Copyright (c) 1997 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * Author: Lennart Augustsson
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *        This product includes software developed by the NetBSD
 *        Foundation, Inc. and its contributors.
 * 4. Neither the name of The NetBSD Foundation nor the names of its
 *    contributors may be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

/* SparcLinux audio modifications by Derrick J Brashear, shadow@dementia.org */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <linux/kdev_t.h>
#include <asm/audioio.h>

struct field *findfield __P((char *name));
void prfield __P((struct field *p, char *sep));
void rdfield __P((struct field *p, char *q));
void getinfo __P((int fd));
void usage __P((void));
int main __P((int argc, char **argv));

FILE *out;

char *prog;

audio_device_t adev;

audio_info_t info;

char encbuf[1000];

int rerror;

struct field {
	char *name;
	void *valp;
	int format;
#define STRING 1
#define INT 2
#define UINT 3
#define P_R 4
#define ULONG 5
#define UCHAR 6
#define ENC 7
#define XINT 8
#define IPORTX 9
#define OPORTX 10
	char flags;
#define READONLY 1
#define ALIAS 2
#define SET 4
} fields[] = {
	{ "name", 		&adev.name, 		STRING, READONLY },
	{ "version",		&adev.version,		STRING, READONLY },
	{ "config",		&adev.config,		STRING, READONLY },
	{ "encodings",		encbuf,			STRING, READONLY },
	{ "monitor_gain",	&info.monitor_gain,	UINT,	0 },
	{ "output_muted",	&info.output_muted,	UCHAR,	0 },
	{ "play.rate",		&info.play.sample_rate,	UINT,	0 },
	{ "play.sample_rate",	&info.play.sample_rate,	UINT,	ALIAS },
	{ "play.channels",	&info.play.channels,	UINT,	0 },
	{ "play.precision",	&info.play.precision,	UINT,	0 },
	{ "play.encoding",	&info.play.encoding,	ENC,	0 },
	{ "play.gain",		&info.play.gain,	UINT,	0 },
	{ "play.balance",	&info.play.balance,	UCHAR,	0 },
	{ "play.port",		&info.play.port,	OPORTX,	0 },
	{ "play.avail_ports",	&info.play.avail_ports,	OPORTX,	READONLY },
	{ "play.samples",	&info.play.samples,	UINT,	READONLY },
	{ "play.eof",		&info.play.eof,		UINT,	READONLY },
	{ "play.pause",		&info.play.pause,	UCHAR,	0 },
	{ "play.error",		&info.play.error,	UCHAR,	READONLY },
	{ "play.waiting",	&info.play.waiting,	UCHAR,	READONLY },
	{ "play.open",		&info.play.open,	UCHAR,	READONLY },
	{ "play.active",	&info.play.active,	UCHAR,	READONLY },
	{ "play.buffer_size",	&info.play.buffer_size,	UINT,	0 },
	{ "record.rate",	&info.record.sample_rate,UINT,	0 },
	{ "record.sample_rate",	&info.record.sample_rate,UINT,	ALIAS },
	{ "record.channels",	&info.record.channels,	UINT,	0 },
	{ "record.precision",	&info.record.precision,	UINT,	0 },
	{ "record.encoding",	&info.record.encoding,	ENC,	0 },
	{ "record.gain",	&info.record.gain,	UINT,	0 },
	{ "record.balance",	&info.record.balance,	UCHAR,	0 },
	{ "record.port",	&info.record.port,	IPORTX,	0 },
	{ "record.avail_ports",	&info.record.avail_ports,IPORTX,	READONLY },
	{ "record.samples",	&info.record.samples,	UINT,	READONLY },
	{ "record.eof",		&info.record.eof,	UINT,	READONLY },
	{ "record.pause",	&info.record.pause,	UCHAR,	0 },
	{ "record.error",	&info.record.error,	UCHAR,	READONLY },
	{ "record.waiting",	&info.record.waiting,	UCHAR,	READONLY },
	{ "record.open",	&info.record.open,	UCHAR,	READONLY },
	{ "record.active",	&info.record.active,	UCHAR,	READONLY },
	{ "record.buffer_size",	&info.record.buffer_size,UINT,	0 },
	{ "record.errors",	&rerror,		INT,	READONLY },
	{ 0 }
};

struct {
	char *ename;
	int eno;
} encs[] = {
	{ "ulaw",		AUDIO_ENCODING_ULAW },
	{ "alaw", 		AUDIO_ENCODING_ALAW },
	{ "linear8",		AUDIO_ENCODING_LINEAR8 },
	{ "ADPCM",		AUDIO_ENCODING_DVI },
	{ "linear_le",		AUDIO_ENCODING_LINEARLE },
	{ "linear_be",		AUDIO_ENCODING_LINEAR },
	{ "linear",		AUDIO_ENCODING_LINEAR },
	{ 0 }
};

struct {
	char *oname;
	int ono;
} oports[] = {
	{ "speaker", 		AUDIO_SPEAKER },
	{ "headphone",		AUDIO_HEADPHONE },
	{ "line out",		AUDIO_LINE_OUT },
	{ 0 }
};

struct {
	char *iname;
	int ino;
} iports[] = {
	{ "microphone", 	AUDIO_MICROPHONE },
	{ "line in",		AUDIO_LINE_IN },
	{ "internal cd",	AUDIO_CD },
	{ "analog loopback",	AUDIO_ANALOG_LOOPBACK },
	{ 0 }
};

struct field *
findfield(name)
	char *name;
{
	int i;
	for(i = 0; fields[i].name; i++)
		if (strcmp(fields[i].name, name) == 0)
			return &fields[i];
	return 0;
}

void
prfield(p, sep)
	struct field *p;
	char *sep;
{
	u_int v;
	char *cm;
	int i;

	if (sep)
		fprintf(out, "%s%s", p->name, sep);
	switch(p->format) {
	case STRING:
		fprintf(out, "%s", (char*)p->valp);
		break;
	case INT:
		fprintf(out, "%d", *(int*)p->valp);
		break;
	case UINT:
		fprintf(out, "%u", *(u_int*)p->valp);
		break;
	case XINT:
		fprintf(out, "0x%x", *(u_int*)p->valp);
		break;
	case UCHAR:
		fprintf(out, "%u", *(u_char*)p->valp);
		break;
	case ULONG:
		fprintf(out, "%lu", *(u_long*)p->valp);
		break;
#if 0
	case P_R:
		v = *(u_int*)p->valp;
		cm = "";
		if (v & AUMODE_PLAY) {
			if (v & AUMODE_PLAY_ALL)
				fprintf(out, "play");
			else
				fprintf(out, "playsync");
			cm = ",";
		}
		if (v & AUMODE_RECORD)
			fprintf(out, "%srecord", cm);
		break;
#endif
	case ENC:
		v = *(u_int*)p->valp;
		for(i = 0; encs[i].ename; i++)
			if (encs[i].eno == v)
				break;
		if (encs[i].ename)
			fprintf(out, "%s", encs[i].ename);
		else
			fprintf(out, "%u", v);
		break;
	case IPORTX:
	  {
	    int tmp = 0;
	    fprintf(out, "0x%x (", *(u_int*)p->valp);
	    v = *(u_int*)p->valp;
	    for(i = 0; iports[i].iname; i++)
	      if (iports[i].ino & v) {
		if (tmp) {
		  fprintf(out, "|%s (0x%x)", iports[i].iname, iports[i].ino);
		} else {
		  tmp = 1;
		  fprintf(out, "%s (0x%x)", iports[i].iname, iports[i].ino);
		}
	      }
	    fprintf(out, ")");
	    break;
	  }
	case OPORTX:
	  {
	    int tmp = 0;
	    fprintf(out, "0x%x (", *(u_int*)p->valp);
	    v = *(u_int*)p->valp;
	    for(i = 0; oports[i].oname; i++)
	      if (oports[i].ono & v) {
		if (tmp) {
		  fprintf(out, "|%s (0x%x)", oports[i].oname, oports[i].ono);
		} else {
		  tmp = 1;
		  fprintf(out, "%s (0x%x)", oports[i].oname, oports[i].ono);
		}
	      }
	    fprintf(out, ")");
	    break;
	  }
	default:
		fprintf(stderr, "Invalid print format.\n");
	}
}

void
rdfield(p, q)
	struct field *p;
	char *q;
{
	int i;
	u_int u;

	switch(p->format) {
	case UINT:
		if (sscanf(q, "%u", (unsigned int *)p->valp) != 1)
			fprintf(stderr, "Bad number %s\n", q);
		break;
	case UCHAR:
		if (sscanf(q, "%u", &u) != 1)
			fprintf(stderr, "Bad number %s\n", q);
		else
			*(u_char *)p->valp = u;
		break;
	case XINT:
		if (sscanf(q, "0x%x", (unsigned int *)p->valp) != 1 &&
		    sscanf(q, "%x", (unsigned int *)p->valp) != 1)
			fprintf(stderr,"Bad number %s\n", q);
		break;
	case IPORTX:
		if (sscanf(q, "0x%x", (unsigned int *)p->valp) != 1 &&
		    sscanf(q, "%x", (unsigned int *)p->valp) != 1) {
		  for(i = 0; iports[i].iname; i++)
		    if (strcmp(iports[i].iname, q) == 0)
		      break;
		  if (iports[i].iname)
		    *(u_int*)p->valp = iports[i].ino;
		  else
		    fprintf(stderr,"Unknown input port: %s\n", q);
		}
		break;
	case OPORTX:
		if (sscanf(q, "0x%x", (unsigned int *)p->valp) != 1 &&
		    sscanf(q, "%x", (unsigned int *)p->valp) != 1) {
		  for(i = 0; oports[i].oname; i++)
		    if (strcmp(oports[i].oname, q) == 0)
		      break;
		  if (oports[i].oname)
		    *(u_int*)p->valp = oports[i].ono;
		  else
		    fprintf(stderr,"Unknown output port: %s\n", q);
		}
		break;
	case ENC:
		for(i = 0; encs[i].ename; i++)
			if (strcmp(encs[i].ename, q) == 0)
				break;
		if (encs[i].ename)
			*(u_int*)p->valp = encs[i].eno;
		else
			fprintf(stderr,"Unknown encoding: %s\n", q);
		break;
	default:
		fprintf(stderr, "Invalid read format.\n");
	}
	p->flags |= SET;
}

void
getinfo(fd)
	int fd;
{
	int pos, i;

	if (ioctl(fd, AUDIO_GETDEV, &adev) < 0) {
		fprintf(stderr, "AUDIO_GETDEV\n");
		exit(1);
	}
#if 0
	for(pos = 0, i = 0; ; i++) {
		audio_encoding_t enc;
		enc.index = i;
		if (ioctl(fd, AUDIO_GETENC, &enc) < 0)
			break;
		if (pos)
			encbuf[pos++] = ',';
		sprintf(encbuf+pos, "%s:%d%s", enc.name, 
			enc.precision, 
			enc.flags & AUDIO_ENCODINGFLAG_EMULATED ? "*" : "");
		pos += strlen(encbuf+pos);
	}
#else
	sprintf(encbuf, "not yet implemented");
#endif
	if (ioctl(fd, AUDIO_GETINFO, &info) < 0)
		fprintf(stderr, "AUDIO_GETINFO\n");
}

void
usage()
{
	fprintf(out, "%s [-f file] [-n] name ...\n", prog);
	fprintf(out, "%s [-f file] [-n] -w name=value ...\n", prog);
	fprintf(out, "%s [-f file] [-n] -a\n", prog);
	exit(1);
}

int
main(argc, argv)
	int argc;
	char **argv;
{
	int fd, i, ch;
	int aflag = 0, wflag = 0;
	struct stat dstat, ostat;
	char *file;
	char *sep = "=";
	out = stdout;
    
	file = getenv("AUDIOCTLDEVICE");
	if (file == 0)
		file = "/dev/audioctl";

	prog = *argv;
    
	while ((ch = getopt(argc, argv, "af:nw")) != -1) {
		switch(ch) {
		case 'a':
			aflag++;
			break;
		case 'w':
			wflag++;
			break;
		case 'n':
			sep = 0;
			break;
		case 'f':
			file = optarg;
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;
    
	fd = open(file, O_WRONLY);
	if (fd < 0)
		fd = open(file, O_RDONLY);
	if (fd < 0)
		fprintf(stderr, "%s\n", file);
    
	/* Check if stdout is the same device as the audio device. */
	if (fstat(fd, &dstat) < 0) {
		fprintf(stderr, "fstat au\n");
		exit(0);
	}

	if (fstat(STDOUT_FILENO, &ostat) < 0) {
		fprintf(stderr, "fstat stdout\n");
		exit(0);
	}
#if 1
	if (S_ISCHR(dstat.st_mode) && S_ISCHR(ostat.st_mode) &&
	    MAJOR(dstat.st_dev) == MAJOR(ostat.st_dev) &&
	    MINOR(dstat.st_dev) == MINOR(ostat.st_dev))
#else
	if (S_ISCHR(dstat.st_mode) && S_ISCHR(ostat.st_mode))
#endif
		/* We can't write to stdout so use stderr */
		out = stderr;

	if (!wflag)
		getinfo(fd);

	if (argc == 0 && aflag && !wflag) {
		for(i = 0; fields[i].name; i++) {
			if (!(fields[i].flags & ALIAS)) {
				prfield(&fields[i], sep);
				fprintf(out, "\n");
			}
		}
	} else if (argc > 0 && !aflag) {
		struct field *p;
		if (wflag) {
			AUDIO_INITINFO(&info);
#if 0
			if (ioctl(fd, AUDIO_GETINFO, &info) < 0)
				fprintf(stderr, "get failed");
#endif
			while(argc--) {
				char *q;
		
				q = strchr(*argv, '=');
				if (q) {
					*q++ = 0;
					p = findfield(*argv);
					if (p == 0)
						fprintf(stderr,"field `%s' does not exist\n", *argv);
					else {
						if (p->flags & READONLY)
							fprintf(stderr,"`%s' is read only\n", *argv);
						else {
							rdfield(p, q);
						}
					}
				} else
					fprintf(stderr,"No `=' in %s\n", *argv);
				argv++;
			}
			if (ioctl(fd, AUDIO_SETINFO, &info) < 0) {
				fprintf(stderr, "set failed\n");
				exit(1);
			}
			if (sep) {
				getinfo(fd);
				for(i = 0; fields[i].name; i++) {
					if (fields[i].flags & SET) {
						fprintf(out, "%s: -> ", fields[i].name);
						prfield(&fields[i], 0);
						fprintf(out, "\n");
					}
				}
			}
		} else {
			while(argc--) {
				p = findfield(*argv);
				if (p == 0) {
					if (strchr(*argv, '='))
						fprintf(stderr,"field %s does not exist (use -w to set a variable)\n", *argv);
					else
						fprintf(stderr,"field %s does not exist\n", *argv);
				} else {
					prfield(p, sep);
					fprintf(out, "\n");
				}
				argv++;
			}
		}
	} else
		usage();
	exit(0);
}
