/*
  This code is a part of amp.
  Advanced Linux Sound Architecture(ALSA) native sound driver for replay.

  Daisuke. Taruki. <daicyan@osa.att.ne.jp>
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/asoundlib.h>

#define PCM_MIXER_INDEX 0

static int audio_fd=0;
static int mixer_fd=0;
static int card_id=0;

void *mixer_handle;
void *pcm_handle;

int AUSIZ = 0;

void audioSetVolume(int volume);

void
audioOpen(int frequency, int stereo, int volume)
{
  snd_pcm_format_t format;

  void *ctl_handle;

  /* Initialize PCM Device */
  if (snd_pcm_open( &pcm_handle, card_id, audio_fd,
		    SND_PCM_OPEN_PLAYBACK ) < 0 )
    die ("Can't open pcm device.\n" );

  /* open mixer device */
  if (snd_mixer_open( &mixer_handle, card_id, mixer_fd ) < 0)
    die ("Can't open mixer device.\n" );
  audioSetVolume(volume);

  format.rate=frequency;
  format.channels=(stereo?2:1);
  format.format=SND_PCM_SFMT_S16_LE;
  if ( snd_pcm_playback_format( pcm_handle, &format ) < 0 )
    die ("Can't set pcm format.\n" );

}

void
audioSetVolume(int volume)
{
  snd_mixer_channel_t cdata = { 0 };

  if (snd_mixer_channel_read(mixer_handle, PCM_MIXER_INDEX, &cdata)<0)
      die ("Can't write snd_mixer_channel_read\n");

  cdata.left=cdata.right=volume;

  if (snd_mixer_channel_write(mixer_handle, PCM_MIXER_INDEX, &cdata)<0)
    die ("Can't write snd_mixer_channel_write\n");
}

inline void
audioFlush()
{
  snd_pcm_flush_playback(pcm_handle);
}

void
audioClose()
{
  snd_pcm_close(pcm_handle);
  snd_mixer_close(mixer_handle);
}

inline int
audioWrite(char *buffer, int count)
{
  return(snd_pcm_write(pcm_handle,buffer,count));
}

int
getAudioFd()
{
  return(audio_fd);
}
