
/*
 * beep.c
 *
 * Simple duration-beep.
 * MWS, 4/92.
 *
 * Hacked from audio1.c (RKM companion disks)...
 * ...Copyright (c) 1990 Commodore-Amiga, Inc.
 */
#include <exec/types.h>		/* Some header files for system calls */
#include <exec/memory.h>
#include <devices/audio.h>
#include <graphics/gfxbase.h>
#include <proto/exec.h>
#include <proto/dos.h>

void FreeAudio(void);
BOOL AllocAudio(void);
void dobeep(LONG);

static UBYTE whichannel[] = {1, 2, 4, 8};
static UBYTE __chip waveptr[] = {  0, 45, 90, 127, 90, 45,
			    	   0,-45,-90,-127,-90,-45  };
#define FREQUENCY 1500
#define SAMPLES (sizeof(waveptr))

static struct IOAudio *AIOptr;	/* Pointer to the IO block for IO commands   */
static struct MsgPort *port;	/* Pointer to a port so the device can reply */

void 
FreeAudio ()			/* free allocated audio resources */
{
	if (port) DeleteMsgPort (port);
	if (AIOptr) FreeMem (AIOptr, sizeof (struct IOAudio));
}

BOOL 
AllocAudio ()			/* allocate audio resources */
{
	if ((AIOptr = (void *) AllocMem (sizeof (struct IOAudio), MEMF_PUBLIC | MEMF_CLEAR)) &&
	    (port = CreateMsgPort ()))
	  {
		  return TRUE;
	  }
	FreeAudio ();
	return FALSE;
}

void
dobeep (long duration)		/* duration in milliseconds */
{
	static struct Message *msg;	/* Pointer for the reply message             */
	if (!AllocAudio())
		return;

	/** open audio.device **/
	AIOptr->ioa_Request.io_Message.mn_ReplyPort = port;
	AIOptr->ioa_Request.io_Message.mn_Node.ln_Pri = 0;
	AIOptr->ioa_Request.io_Command = ADCMD_ALLOCATE;
	AIOptr->ioa_Request.io_Flags = ADIOF_NOWAIT;
	AIOptr->ioa_AllocKey = 90;
	AIOptr->ioa_Data = whichannel;
	AIOptr->ioa_Length = sizeof (whichannel);

	/** Open the audio device and allocate a channel **/
	if (OpenDevice ("audio.device", 0L, (struct IORequest *) AIOptr, 0L))
		return;
	AIOptr->ioa_Request.io_Message.mn_ReplyPort = port;
	AIOptr->ioa_Request.io_Command = CMD_WRITE;
	AIOptr->ioa_Request.io_Flags = ADIOF_PERVOL;
	AIOptr->ioa_Data = (BYTE *) waveptr;
	AIOptr->ioa_Length = SAMPLES;
	AIOptr->ioa_Period = 3579545 / (SAMPLES * FREQUENCY);
	AIOptr->ioa_Cycles = (FREQUENCY * duration) / 1000;
	AIOptr->ioa_Volume = 64;

	BeginIO ((struct IORequest *) AIOptr);
	Wait (1L << port->mp_SigBit);
	msg = GetMsg (port);
	CloseDevice ((struct IORequest *) AIOptr);

	FreeAudio();
}
