'/* Alsa driver for libxmp examples */
'/* This file is in public domain */
#Include "crt.bi"
#Include "alsa.bi"
#include "xmp.bi"


static shared As snd_pcm_t pcm_handle


function sound_init(sampling_rate As Integer, channels As Integer) As Integer

	dim as snd_pcm_hw_params_t ptr hwparams
	dim as integer ret
	dim as UINTEGER chan, rate
	Dim As UInteger btime = 250000'	/* 250ms */
	Dim As UInteger ptime = 50000'	/* 50ms */
	dim as STRING card_name = "default"

	ret = snd_pcm_open(@pcm_handle, card_name,_
		SND_PCM_STREAM_PLAYBACK, 0)
	if ret < 0 then
		fprintf(stderr, !"Unable to initialize ALSA pcm device: %s\n",_
					snd_strerror(ret))
		return -1		
	EndIf


	chan = channels
	rate = sampling_rate

	snd_pcm_hw_params_alloca(hwparams)
	snd_pcm_hw_params_any(pcm_handle, hwparams)
	snd_pcm_hw_params_set_access(pcm_handle, hwparams,_
				SND_PCM_ACCESS_RW_INTERLEAVED)
	snd_pcm_hw_params_set_format(pcm_handle, hwparams, SND_PCM_FORMAT_S16)
	snd_pcm_hw_params_set_rate_near(pcm_handle, hwparams, @rate, 0)
	snd_pcm_hw_params_set_channels_near(pcm_handle, hwparams, @chan)
	snd_pcm_hw_params_set_buffer_time_near(pcm_handle, hwparams, @btime, 0)
	snd_pcm_hw_params_set_period_time_near(pcm_handle, hwparams, @ptime, 0)
	snd_pcm_nonblock(pcm_handle, 0)
	
	ret = snd_pcm_hw_params(pcm_handle, hwparams)
	if ret < 0 Then
		fprintf(stderr, !"Unable to set ALSA output parameters: %s\n",_
					snd_strerror(ret))
		return -1		
	EndIf
ret = snd_pcm_prepare(pcm_handle)
	if ret < 0 Then
		fprintf(stderr, !"Unable to prepare ALSA: %s\n",_
					snd_strerror(ret))
		return -1		
	EndIf
 
	return 0
End Function

sub sound_play(b As Any Ptr, i As Integer)
	Dim As integer frames

	frames = snd_pcm_bytes_to_frames(pcm_handle, i)
	if (snd_pcm_writei(pcm_handle, b, frames) < 0) Then
		snd_pcm_prepare(pcm_handle)
	EndIf
End Sub

Sub sound_deinit()
	snd_pcm_drain(pcm_handle)
	snd_pcm_close(pcm_handle)	
End Sub

