/*
 * xrick/src/syssnd.c
 *
 * This source code file is part of the xrick distribution, and as such is
 * copyrighted. Please read the README file in the root directory of the
 * distribution for information about copyrights, trademarks, license,
 * disclaimers, etc.
 */

#include <SDL.h>
#include <stdlib.h>

#include "system.h"
#include "game.h"
#include "syssnd.h"
#include "debug.h"

#define ADJVOL(S) (((S)*sndVol)/SDL_MIX_MAXVOLUME)

static U8 isAudioActive = FALSE;
static channel_t channel[SYSSND_MIXCHANNELS];

static U8 sndVol = SDL_MIX_MAXVOLUME;  /* internal volume */
static U8 sndUVol = SYSSND_MAXVOL;  /* user-selected volume */
static U8 sndMute = FALSE;  /* mute flag */

static SDL_mutex *sndlock;

/*
 * Callback -- this is also where all sound mixing is done
 *
 * Note: it may not be that much a good idea to do all the mixing here ; it
 * may be more efficient to mix samples every frame, or maybe everytime a
 * new sound is sent to be played. I don't know.
 */
void syssnd_callback(UNUSED(void *userdata), U8 *stream, int len)
{
  U8 c;
  S16 s;
  U32 i;

  SDL_mutexP(sndlock);

  for (i = 0; i < (U32)len; i++) {
    s = 0;
    for (c = 0; c < SYSSND_MIXCHANNELS; c++) {
      if (channel[c].loop != 0) {  /* channel is active */
	if (channel[c].len > 0) {  /* not ending */
	  s += ADJVOL(*channel[c].buf - 0x80);
	  channel[c].buf++;
	  channel[c].len--;
	}
	else {  /* ending */
	  if (channel[c].loop > 0) channel[c].loop--;
	  if (channel[c].loop) {  /* just loop */
	    IFDEBUG_AUDIO2(sys_printf("xrick/audio: channel %d - loop\n", c););
	    channel[c].buf = channel[c].buf0;
	    channel[c].len = channel[c].len0;
	    s += ADJVOL(*channel[c].buf - 0x80);
	    channel[c].buf++;
	    channel[c].len--;
	  }
	  else {  /* end for real */
	    IFDEBUG_AUDIO2(sys_printf("xrick/audio: channel %d - end\n", c););
	  }
	}
      }
    }
    if (sndMute)
      stream[i] = 0x80;
    else {
      s += 0x80;
      if (s > 0xff) s = 0xff;
      if (s < 0x00) s = 0x00;
      stream[i] = (U8)s;
    }
  }

  memcpy(stream, stream, len);

  SDL_mutexV(sndlock);
}

void
syssnd_init(void)
{
  SDL_AudioSpec desired, obtained;
  U16 c;

  if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) {
    IFDEBUG_AUDIO(
      sys_printf("xrick/audio: can not initialize audio subsystem\n");
      );
    return;
  }

  desired.freq = SYSSND_FREQ;
  desired.format = AUDIO_U8;
  desired.channels = SYSSND_CHANNELS;
  desired.samples = SYSSND_MIXSAMPLES;
  desired.callback = syssnd_callback;
  desired.userdata = NULL;

  if (SDL_OpenAudio(&desired, &obtained) < 0) {
    IFDEBUG_AUDIO(
      sys_printf("xrick/audio: can not open audio (%s)\n", SDL_GetError());
      );
    return;
  }

  sndlock = SDL_CreateMutex();
  if (sndlock == NULL) {
    IFDEBUG_AUDIO(sys_printf("xrick/audio: can not create lock\n"););
    SDL_CloseAudio();
    return;
  }

  if (sysarg_args_vol != 0) {
    sndUVol = sysarg_args_vol;
    sndVol = SDL_MIX_MAXVOLUME * sndUVol / SYSSND_MAXVOL;
  }

  for (c = 0; c < SYSSND_MIXCHANNELS; c++)
    channel[c].loop = 0;  /* deactivate */

  isAudioActive = TRUE;
  SDL_PauseAudio(0);
}

/*
 * Shutdown
 */
void
syssnd_shutdown(void)
{
  if (!isAudioActive) return;

  SDL_CloseAudio();
  SDL_DestroyMutex(sndlock);
  isAudioActive = FALSE;
}

/*
 * Toggle mute
 *
 * When muted, sounds are still managed but not sent to the dsp, hence
 * it is possible to un-mute at any time.
 */
void
syssnd_toggleMute(void)
{
  SDL_mutexP(sndlock);
  sndMute = !sndMute;
  SDL_mutexV(sndlock);
}

void
syssnd_vol(S8 d)
{
  if ((d < 0 && sndUVol > 0) ||
      (d > 0 && sndUVol < SYSSND_MAXVOL)) {
    sndUVol += d;
    SDL_mutexP(sndlock);
    sndVol = SDL_MIX_MAXVOLUME * sndUVol / SYSSND_MAXVOL;    
    SDL_mutexV(sndlock);
  }
}

/*
 * Play a sound
 *
 * loop: number of times the sound should be played, -1 to loop forever
 * returns: channel number, or -1 if none was available
 *
 * NOTE if sound is already playing, simply reset it (i.e. can not have
 * twice the same sound playing -- tends to become noisy when too many
 * bad guys die at the same time).
 */
S8
syssnd_play(sound_t *sound, S8 loop)
{
  S8 c;

  if (!isAudioActive) return -1;
  if (sound == NULL) return -1;

  c = 0;
  SDL_mutexP(sndlock);
  while ((channel[c].buf0 != sound->buf || channel[c].loop == 0) &&
	 channel[c].loop != 0 &&
	 c < SYSSND_MIXCHANNELS)
    c++;
  if (c == SYSSND_MIXCHANNELS)
    c = -1;

  IFDEBUG_AUDIO(
    if (channel[c].buf0 == sound->buf && channel[c].loop != 0)
      sys_printf("xrick/sound: already playing %s on channel %d - resetting\n",
		 sound->name, c);
    else if (c >= 0)
      sys_printf("xrick/sound: playing %s on channel %d\n", sound->name, c);
    );

  if (c >= 0) {
    channel[c].loop = loop;
    channel[c].buf0 = sound->buf;
    channel[c].buf = sound->buf;
    channel[c].len0 = sound->len;
    channel[c].len = sound->len;
  }
  SDL_mutexV(sndlock);

  return c;
}

/*
 * Pause
 *
 * pause: TRUE or FALSE
 * clear: TRUE to cleanup all sounds and make sure we start from scratch
 */
void
syssnd_pause(U8 pause, U8 clear)
{
  U8 c;

  if (!isAudioActive) return;

  if (clear == TRUE) {
    SDL_mutexP(sndlock);
    for (c = 0; c < SYSSND_MIXCHANNELS; c++)
      channel[c].loop = 0;
    SDL_mutexV(sndlock);
  }

  if (pause == TRUE)
    SDL_PauseAudio(1);
  else
    SDL_PauseAudio(0);
}

/*
 * Stop a channel
 */
void
syssnd_stop(S8 chan)
{
  if (chan < 0 || chan > SYSSND_MIXCHANNELS)
    return;

  SDL_mutexP(sndlock);
  channel[chan].loop = 0;
  SDL_mutexV(sndlock);
}

/* eof */

