/* misc.c */

/* Volume.app -- a simple volume control
 *
 * Copyright (C) 2000
 *	Daniel Richard G. <skunk@mit.edu>,
 *	timecop <timecop@japan.co.jp>
 *
 * 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

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

#include "common.h"
#include "misc.h"

#include <assert.h>
#include <sys/time.h>
#include <X11/X.h>
#include <X11/Xlib.h>

/* Converts separate left and right channel volumes (each in [0, 1]) to
 * volume and balance values. (Volume is in [0, 1], balance is in [-1, 1])
 */
void
lr_to_vb(float left, float right, float *volume, float *balance)
{
	assert((left >= 0.0) && (right >= 0.0));

	*volume = MAX(left, right);

	if (left > right)
		*balance = -1.0 + right / left;
	else if (right > left)
		*balance = 1.0 - left / right;
	else
		*balance = 0.0;
}

/* Performs the reverse calculation of lr_to_vb()
 */
void
vb_to_lr(float volume, float balance, float *left, float *right)
{
	*left = volume * (1.0 - MAX(0.0, balance));
	*right = volume * (1.0 + MIN(0.0, balance));
}

double
get_current_time(void)
{
	struct timeval tv;
	double t;

	gettimeofday(&tv, NULL);
	t = (double)tv.tv_sec;
	t += (double)tv.tv_usec / 1.0e6;

	return t;
}

unsigned long
get_color(Display *display, char *color_name)
{
	XWindowAttributes winattrs;
	XColor color;

	XGetWindowAttributes(
		display,
		RootWindow(display, DefaultScreen(display)),
		&winattrs);

	color.pixel = 0;
	XParseColor(display, winattrs.colormap, color_name, &color);

	color.flags = DoRed | DoGreen | DoBlue;
	XAllocColor(display, winattrs.colormap, &color);

	return color.pixel;
}

/* end misc.c */
