/*
    sndctrl.c - A simple user-space program to access an ALSA mixer
                device.
    Copyright (c) 2005 Andrew Calkin <calkina@geexbox.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <stdio.h>
#include <alsa/asoundlib.h>
#include "sndctrl.h"

int getvolume(long *vol)
{
  snd_mixer_t *mixer; /* handle pointer for the mixer */
  snd_mixer_selem_id_t *sid; /* stores simple id of control */
  snd_mixer_elem_t *elem; /* used for master element */

  snd_mixer_open(&mixer, 0); /* open up the mixer for card 0 */
  snd_mixer_attach(mixer, "default" );
  snd_mixer_selem_register(mixer, 0, 0 );
  snd_mixer_load(mixer);

  snd_mixer_selem_id_alloca(&sid); /* gets address of control */
  snd_mixer_selem_id_set_name(sid, "Master");
  elem = snd_mixer_find_selem(mixer, sid);
  /* Only need one channel (left)- assume both the same */
  snd_mixer_selem_get_playback_volume (elem, 0, vol);
  snd_mixer_close(mixer);
  return 0;
}

int setvolume(long newvol)
{
  snd_mixer_t *mixer; /* handle pointer for the mixer */
  snd_mixer_selem_id_t *sid; /* stores simple id of control */
  snd_mixer_elem_t *elem; /* used for master element */

  snd_mixer_open(&mixer, 0); /* open up the mixer for card 0 */
  snd_mixer_attach(mixer, "default" );
  snd_mixer_selem_register(mixer, 0, 0 );
  snd_mixer_load(mixer);

  snd_mixer_selem_id_alloca(&sid); /* gets address of control */
  snd_mixer_selem_id_set_name(sid, "Master");
  elem = snd_mixer_find_selem(mixer, sid);
  /* left and then right channels */
  snd_mixer_selem_set_playback_volume (elem, 0, newvol);
  snd_mixer_selem_set_playback_volume (elem, 1, newvol);
  snd_mixer_close(mixer);
  return 0;
}

int getvolrange(long *vmin, long *vmax)
{
  snd_mixer_t *mixer; /* handle pointer for the mixer */
  snd_mixer_selem_id_t *sid; /* stores simple id of control */
  snd_mixer_elem_t *elem; /* used for master element */

  snd_mixer_open(&mixer, 0); /* open up the mixer for card 0 */
  snd_mixer_attach(mixer, "default" );
  snd_mixer_selem_register(mixer, 0, 0 );
  snd_mixer_load(mixer);

  snd_mixer_selem_id_alloca(&sid); /* gets address of control */
  snd_mixer_selem_id_set_name(sid, "Master");
  elem = snd_mixer_find_selem(mixer, sid);

  snd_mixer_selem_get_playback_volume_range (elem, vmin, vmax);
  snd_mixer_close(mixer);
  return 0;
}

