/* Extended Module Player
 * Copyright (C) 1996-2000 Claudio Matsuoka and Hipolito Carraro Jr
 *
 * This file is part of the Extended Module Player and is distributed
 * under the terms of the GNU General Public License. See doc/COPYING
 * for more information.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>


#include "xmpi.h"
#include "driver.h"
#include "mixer.h"

#include "xmms/util.h"
#include "xmp-plugin.h"

static short audio_open = FALSE;

extern XMPConfig xmp_cfg;
extern gboolean xmp_going;
gboolean xmp_xmms_audio_error = FALSE;

static int init (struct xmp_control *);
static void bufdump (int);
static void shutdown ();

static void dummy () { }

struct xmp_drv_info drv_xmms = {
    "xmms_mix",		/* driver ID */
    "XMMS plugin",	/* driver description */
    NULL,		/* help */
    init,		/* init */
    shutdown,		/* shutdown */
    xmp_smix_numvoices,	/* numvoices */
    dummy,		/* voicepos */
    xmp_smix_echoback,	/* echoback */
    dummy,		/* setpatch */
    xmp_smix_setvol,	/* setvol */
    dummy,		/* setnote */
    xmp_smix_setpan,	/* setpan */
    dummy,		/* setbend */
    dummy,		/* seteffect */
    dummy,		/* starttimer */
    dummy,		/* stctlimer */
    dummy,		/* resetvoices */
    bufdump,		/* bufdump */
    dummy,		/* bufwipe */
    dummy,		/* clearmem */
    dummy,		/* sync */
    xmp_smix_writepatch,/* writepatch */
    xmp_smix_getmsg,	/* getmsg */
    NULL
};

static int init (struct xmp_control *ctl)
{
    AFormat fmt;
    int nch;

    fmt = ctl->resol == 16 ? FMT_S16_LE : FMT_U8;
    nch = ctl->outfmt & XMP_FMT_MONO ? 1 : 2;

    if (audio_open)
	xmp_ip.output->close_audio();

    if (!xmp_ip.output->open_audio(fmt, ctl->freq, nch)) {
	xmp_xmms_audio_error = TRUE;
	return -1;
    }

    audio_open = TRUE;

    return xmp_smix_on (ctl);
}


static void bufdump (int i)
{
    void *b;

    b = xmp_smix_buffer ();
    xmp_ip.add_vis_pcm (xmp_ip.output->written_time(),
	xmp_cfg.force8bit ? FMT_U8 : FMT_S16_NE,
	xmp_cfg.force_mono ? 1 : 2,
	i, b);
	
    while(xmp_ip.output->buffer_free() < i && xmp_going)
	xmms_usleep(10000);
    if(xmp_going)
        xmp_ip.output->write_audio(b, i);
}


static void shutdown ()
{
    xmp_smix_off ();

    if (audio_open) {
	xmp_ip.output->close_audio();
	audio_open = FALSE;
    }
}

