; Audio channel allocation/freeing routines, by Teijo Kinnunen.
; No copyrights - use if you wish...
; (...at your own risk!! ;^)

		CODE
		XDEF	_AllocChannels
		XDEF	_FreeChannels

_AllocChannels:	movem.l	a4/a6,-(sp)	;save two registers
		lea	DB,a4
		movea.l	4,a6		
		moveq	#-1,d0		;any bit will do fine
		jsr	-$14a(a6)	;AllocSignal()
		tst.b	d0
		bmi.w	ac_err		;-1 => failure
		move.b	d0,sigbitnum-DB(a4)
		lea	allocport-DB(a4),a1	;get port address
		move.b	d0,15(a1)		;set mp_SigBit
		move.l	a1,-(sp)
		suba.l	a1,a1
		jsr	-$126(a6)	;FindTask(0)
		move.l	(sp)+,a1
		move.l	d0,16(a1)	;set mp_SigTask
		lea	reqlist-DB(a4),a0
		move.l	a0,8(a0)
		addq.l	#4,a0
		clr.l	(a0)
		move.l	a0,-(a0)
		lea	allocreq-DB(a4),a1
		lea	audiodevname-DB(a4),a0
		moveq	#0,d0
		moveq	#0,d1
		jsr	-$1bc(a6)	;OpenDevice()
		tst.b	d0
		beq.s	ac_noerr
		bsr.s	_FreeChannels
		bra.s	ac_err
ac_noerr	st	audiodevopen-DB(a4)
		moveq	#0,d0		;return ZERO = no error
		bra.s	ac_exit
ac_err		moveq	#-1,d0		;return NONZERO = error
ac_exit		movem.l	(sp)+,a4/a6	;restore these regs
		rts

_FreeChannels:	movem.l	a5-a6,-(sp)
		lea	DB,a5		;again, the DataBase pointer
		movea.l	4,a6
		tst.b	audiodevopen-DB(a5)
		beq.s	fc_nodevalloc
		lea	allocreq-DB(a5),a1
		jsr	-$1c2(a6)	;CloseDevice()
		clr.b	audiodevopen-DB(a5)
fc_nodevalloc	moveq	#0,d0
		move.b	sigbitnum-DB(a5),d0
		bmi.s	fc_nosigbit
		jsr	-$150(a6)		;FreeSignal()
		st	sigbitnum-DB(a5)	;clear (= set) sigbitnum
fc_nosigbit	movem.l	(sp)+,a5-a6
		rts

		DATA
DB:		;data base pointer
sigbitnum	dc.b	$ff
audiodevopen	dc.b	0
allocmask	dc.b	$0f
		dc.b	0	;a pad byte

allocport	dc.l	0,0	;succ, pred
		dc.b	4,0	;NT_MSGPORT
		dc.l	0	;name
		dc.b	0,0	;flags = PA_SIGNAL
		dc.l	0	;task
reqlist		dc.l	0,0,0	;list head, tail and tailpred
		dc.b	5,0
allocreq	dc.l	0,0
		dc.b	5,127	;NT_MESSAGE, use maximum priority (127)
		dc.l	0,allocport	;name, replyport
		dc.w	68		;length
		dc.l	0		;io_Device
		dc.l	0		;io_Unit
		dc.w	0		;io_Command
		dc.b	0,0		;io_Flags, io_Error
		dc.w	0		;ioa_AllocKey
		dc.l	allocmask	;ioa_Data
		dc.l	1		;ioa_Length
		dc.w	0,0,0		;ioa_Period, Volume, Cycles
		dc.w	0,0,0,0,0,0,0,0,0,0	;ioa_WriteMsg

audiodevname	dc.b	'audio.device',0

		END
