/*
 *   ALSA sequencer Timer
 *   Copyright (c) 1998 by Frank van de Pol <frank@vande-pol.demon.nl>
 *                         Jaroslav Kysela <perex@suse.cz>
 *
 *
 *   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 "../../include/driver.h"
#include "seq_timer.h"
#include "seq_queue.h"
#include "seq_info.h"

extern int snd_seq_default_timer;
extern int snd_seq_default_timer_resolution;

static void inline snd_seq_timer_set_tick_time(timer_t *tmr)
{
	tmr->tick_time = (tmr->tempo * 1000) / tmr->ppq;
}

/* create new timer (constructor) */
timer_t *snd_seq_timer_new(void)
{
	timer_t *tmr;
	
	tmr = snd_kcalloc(sizeof(timer_t), GFP_KERNEL);
	if (tmr == NULL) {
		snd_printd("malloc failed for snd_seq_timer_new() \n");
		return NULL;
	}
	tmr->lock = SPIN_LOCK_UNLOCKED;

	/* reset setup to defaults */
	snd_seq_timer_defaults(tmr);
	/* reset time */
	snd_seq_timer_reset(tmr);
	
	return tmr;
}

/* delete timer (destructor) */
void snd_seq_timer_delete(timer_t **tmr)
{
	timer_t *t = *tmr;
	*tmr = NULL;

	if (t == NULL) {
		snd_printd("oops: snd_seq_timer_delete() called with NULL timer\n");
		return;
	}
	t->running = 0;

	/* reset time */
	snd_seq_timer_stop(t);
	snd_seq_timer_reset(t);

	snd_kfree(t);
}

void snd_seq_timer_defaults(timer_t * tmr)
{
	/* setup defaults */
	tmr->ppq = 96;		/* 96 PPQ */
	tmr->tempo = 500000;	/* 120 BPM */
	snd_seq_timer_set_tick_time(tmr);
	tmr->running = 0;
	tmr->ticks = 1;

	tmr->type = SND_SEQ_TIMER_MASTER;
	tmr->resolution = snd_seq_default_timer_resolution;
	tmr->timer_no = snd_seq_default_timer;
}

void snd_seq_timer_reset(timer_t * tmr)
{
	unsigned long flags;

	spin_lock_irqsave(&tmr->lock, flags);

	/* reset time & songposition */
	tmr->cur_tick = 0;
	tmr->cur_time.tv_sec = 0;
	tmr->cur_time.tv_nsec = 0;

	tmr->tempo_tick = 0;
	tmr->tempo_time.tv_sec = 0;
	tmr->tempo_time.tv_nsec = 0;

	tmr->cur_tick_time = 0;

	tmr->sync_tmp = 0;
	spin_unlock_irqrestore(&tmr->lock, flags);
}


/* called by timer interrupt routine. the period time since previous invocation is passed */
static void snd_seq_timer_interrupt(snd_timer_instance_t *timeri,
				    unsigned long resolution,
				    unsigned long ticks, void *data)
{
	unsigned long flags;
	snd_seq_real_time_t period;
	queue_t *q = (queue_t *)data;
	timer_t *tmr;

	q = queueptr(q->queue);
	if (q == NULL)
		return;
	tmr = q->timer;
	if (tmr == NULL)
		return;
	if (!tmr->running)
		return;

	resolution *= ticks;
	period.tv_sec = 0;
	period.tv_nsec = resolution % 1000000000;

	spin_lock_irqsave(&tmr->lock, flags);

	/* update timer */
	snd_seq_inc_real_time(&tmr->cur_time, &period);

	/* calculate current tick */
	if (tmr->tempo > 0) {
		unsigned long result;
		
		result = tmr->cur_tick_time + resolution;
		tmr->cur_tick += result / tmr->tick_time;
		tmr->cur_tick_time = result % tmr->tick_time;
	}

	/* register actual time of this timer update  */
	do_gettimeofday(&tmr->last_update);

	spin_unlock_irqrestore(&tmr->lock, flags);

#if 0
	/* sync timer has expired *//* FIXME: hack to send midi sync info */
	if ((tmr->cur_tick > tmr->sync_tmp) && (snd_seq_unused_cells() > 10)) {
		snd_seq_event_t ev;

		ev.type = SND_SEQ_EVENT_CLOCK;
		ev.flags = SND_SEQ_TIME_STAMP_TICK | SND_SEQ_TIME_MODE_ABS;
		ev.time.tick = 0;
		ev.source.queue = 0;
		ev.source.client = 0;
		ev.source.port = 0;
		ev.dest.queue = 1;
		ev.dest.client = 255;
		ev.dest.port = 255;
		if (!snd_seq_kernel_client_dispatch(0, &ev)) {
			tmr->sync_tmp += tmr->ppq / 24;
	}
#endif
	/* check queues and dispatch events */
	snd_seq_check_queue(q, 1, 0);
}


int snd_seq_timer_set_tempo(timer_t * tmr, int tempo)
{
	unsigned long flags;

	if (tmr && tempo > 0) {
		spin_lock_irqsave(&tmr->lock, flags);
		/* store location of tempo change */
		tmr->tempo_tick = tmr->cur_tick;
		tmr->tempo_time.tv_sec = tmr->cur_time.tv_sec;
		tmr->tempo_time.tv_nsec = tmr->cur_time.tv_nsec;

		tmr->tempo = tempo;
		snd_seq_timer_set_tick_time(tmr);
		tmr->cur_tick += tmr->cur_tick_time / tmr->tick_time;
		tmr->cur_tick_time %= tmr->tick_time;
		spin_unlock_irqrestore(&tmr->lock, flags);
		return 0;
	}
	return -EINVAL;
}


int snd_seq_timer_set_ppq(timer_t * tmr, int ppq)
{
	unsigned long flags;

	if (tmr && ppq > 0) {
		if (tmr->running && (ppq != tmr->ppq)) {
			/* refuse to change ppq on running timers */
			/* because it will upset the song position (ticks) */
			snd_printd("seq: cannot change ppq of a running timer\n");
			return -EBUSY;
		} else {
			spin_lock_irqsave(&tmr->lock, flags);
			tmr->ppq = ppq;
			snd_seq_timer_set_tick_time(tmr);
			tmr->cur_tick += tmr->cur_tick_time / tmr->tick_time;
			tmr->cur_tick_time %= tmr->tick_time;
			spin_unlock_irqrestore(&tmr->lock, flags);		
		}
		return 0;
	}
	return -EINVAL;
}


int snd_seq_timer_open(queue_t *q)
{
	snd_timer_instance_t *t;
	timer_t *tmr;
	unsigned int tmp, tmp1;
	char str[32];

	tmr = q->timer;
	if (!tmr)
		return -EINVAL;
	if (tmr->timeri)
		return -EBUSY;
	sprintf(str, "sequencer queue %i", q->queue);
	switch (tmr->type) {
	case SND_SEQ_TIMER_MASTER:	/* standard timer */
		t = snd_timer_open(str, tmr->timer_no, SND_TIMER_STYPE_SEQUENCER, q->queue);
		if (!t) {
			if (tmr->timer_no != (SND_TIMER_TYPE_GLOBAL | SND_TIMER_GLOBAL_SYSTEM))
				t = snd_timer_open(str, SND_TIMER_TYPE_GLOBAL | SND_TIMER_GLOBAL_SYSTEM, SND_TIMER_STYPE_SEQUENCER, q->queue);
			if (!t) {
				snd_printk("sequencer fatal error: cannot create timer\n");
				return -ENODEV;
			}
		}
		break;
	case SND_SEQ_TIMER_SLAVE:
		t = snd_timer_open_slave(str, tmr->slave_type, tmr->timer_no);
		if (!t)
			return -ENODEV;
		break;
	default:
		return -EINVAL;
	}
	t->callback = snd_seq_timer_interrupt;
	t->callback_data = q;
	if (t->timer->hw.flags & SND_TIMER_HW_SLAVE) {
		tmr->ticks = 1;
	} else {
		tmp = 1000000000UL / tmr->resolution;
		tmp1 = snd_timer_resolution(t);
		if (tmp1 >= tmp) {
			tmr->ticks = 1;
		} else {
			tmr->ticks = tmp / tmp1;
		}
	}
	t->flags |= SND_TIMER_IFLG_AUTO;
	tmr->timeri = t;
	return 0;
}

int snd_seq_timer_close(queue_t *q)
{
	timer_t *tmr;
	
	tmr = q->timer;
	if (!tmr)
		return -EINVAL;
	if (tmr->timeri) {
		snd_timer_stop(tmr->timeri);
		snd_timer_close(tmr->timeri);
		tmr->timeri = NULL;
	}
	return 0;
}

void snd_seq_timer_stop(timer_t * tmr)
{
	if (!tmr->running)
		return;
	tmr->running = 0;
	snd_timer_stop(tmr->timeri);
}

void snd_seq_timer_start(timer_t * tmr)
{
	if (tmr->running)
		snd_seq_timer_stop(tmr);
	snd_seq_timer_reset(tmr);
	snd_timer_start(tmr->timeri, tmr->ticks);
	tmr->running = 1;
	do_gettimeofday(&tmr->last_update);
}

void snd_seq_timer_continue(timer_t * tmr)
{
	if (tmr->running)
		return;
	snd_timer_start(tmr->timeri, tmr->ticks);
	tmr->running = 1;
	do_gettimeofday(&tmr->last_update);
}

int snd_seq_timer_midi_open(queue_t *q)
{
	return -ENXIO;	/* not implemented */
}

int snd_seq_timer_midi_close(queue_t *q)
{
	return -ENXIO;	/* not implemented */
}


/* return current 'real' time. use timeofday() to get better granularity. */
snd_seq_real_time_t snd_seq_timer_get_cur_time(timer_t *tmr)
{
	snd_seq_real_time_t cur_time = tmr->cur_time;
	struct timeval tm;
	
	if (tmr->running) { 
		do_gettimeofday(&tm);
		cur_time.tv_nsec += 1000 * (tm.tv_usec - tmr->last_update.tv_usec);
		while (cur_time.tv_nsec >= 1000000000) {
			/* roll-over */
			cur_time.tv_nsec -= 1000000000;
        	        cur_time.tv_sec ++;
        	}
        }
                
	return cur_time;	
}

/* TODO: use interpolation on tick queue (will only be usefull for very
 high PPQ values) */
snd_seq_tick_time_t snd_seq_timer_get_cur_tick(timer_t *tmr)
{
	return tmr->cur_tick;
}


/* exported to seq_info.c */
void snd_seq_info_timer_read(snd_info_buffer_t * buffer, void *private_data)
{
	int idx;
	queue_t *q;
	timer_t *tmr;
	snd_timer_instance_t *ti;
	unsigned long resolution;
	
	for (idx = 0; idx < SND_SEQ_MAX_QUEUES; idx++) {
		q = queueptr(idx);
		if (q == NULL)
			continue;
		tmr = q->timer;
		if (tmr == NULL)
			continue;
		ti = tmr->timeri;
		if (ti == NULL)
			continue;
		snd_iprintf(buffer, "Timer for queue %i : %s\n", q->queue, ti->timer->name);
		resolution = snd_timer_resolution(ti) * tmr->ticks;
		snd_iprintf(buffer, "  Period time : %d.%09d\n", resolution / 1000000000, resolution % 1000000000);
 	}
}
