#include <stdio.h>
#include <stdlib.h>
#include <err.h>
#include <stdint.h>
#include <alsa/asoundlib.h>

enum {
	SRATE = 44100,
	NSAMP = SRATE / 5,
};

void
alsa(char *op, int err)
{
	if(err < 0){
		fprintf(stderr, "%s: %s\n", op, snd_strerror(err));
		exit(1);
	}
}

int
load(void)
{
	static int fd = -1;
	static char buf[64];
	char *p;
	int rc, ret;
	static int lastval;

	if(fd < 0)
		fd = open("/proc/stat", O_RDONLY);
	if(fd < 0)
		err(1, "open");
	lseek(fd, 0, 0);
	if((rc = read(fd, buf, sizeof(buf)-1)) < 0)
		err(1, "read");
	buf[rc] = 0;
	if(rc < 5 || strncmp(buf, "cpu ", 4) != 0)
		errx(1, "/proc/stat is wrong");
	p = buf + 4;
	while(*p == ' ')
		p++;
	rc = atoi(p);
	ret = rc - lastval;
	lastval = rc;
	return ret;
}

int
main(int argc, char **argv)
{
	static unsigned char buf[4 * NSAMP];
	unsigned char *p;
	int16_t s;
	unsigned int samp;
	int cps;
	uint32_t tresh;
	uint64_t tmp;
	snd_pcm_t *dev;
	snd_pcm_hw_params_t *parm;
	
	alsa("open audio device", snd_pcm_open(&dev, "plughw:0,0", SND_PCM_STREAM_PLAYBACK, 0));
	alsa("malloc params", snd_pcm_hw_params_malloc(&parm));
	alsa("init params", snd_pcm_hw_params_any(dev, parm));
	alsa("set type", snd_pcm_hw_params_set_access(dev, parm, SND_PCM_ACCESS_RW_INTERLEAVED));
	alsa("set format", snd_pcm_hw_params_set_format(dev, parm, SND_PCM_FORMAT_S16_LE));
	samp = 44100;
	alsa("set rate", snd_pcm_hw_params_set_rate_near(dev, parm, &samp, 0));
	alsa("set channels", snd_pcm_hw_params_set_channels(dev, parm, 2));
	alsa("set params", snd_pcm_hw_params(dev, parm));
	snd_pcm_hw_params_free(parm);
	alsa("prepare", snd_pcm_prepare(dev));

	s = 0;
	load();
	for(;;){
		cps = 3 + load() * 5;
		tmp = RAND_MAX;
		tresh = (tmp * cps) / SRATE;
		for(p = buf; p < buf + sizeof(buf);){
			s = (uint32_t) rand() < tresh ? (32767 - s) : s;
			*p++ = s;
			*p++ = s >> 8;
			*p++ = s;
			*p++ = s >> 8;
		}
		alsa("write", snd_pcm_writei(dev, buf, NSAMP));
	}
}
