/*
 *   ALSA sequencer Timing queue handling
 *   Copyright (c) 1998 by Frank van de Pol <frank@vande-pol.demon.nl>
 *
 *   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 "driver.h"

#include "seq_memory.h"
#include "seq_queue.h"
#include "seq_clientmgr.h"
#include "seq_fifo.h"
#include "seq_timer.h"
#include "seq_info.h"


/* root for the queues */
static queue_t *queuetab[SND_SEQ_MAX_QUEUES];

/* number of queues allocated */
static int num_queues = 0;


/* FIXME: should add list of active queues (for optimisation of timer), sort of 'run queue' */



/* setup queues */
void snd_seq_queues_init(int num)
{
	int c;
	queue_t *q;

	if (num > SND_SEQ_MAX_QUEUES) {
		snd_printd("Limiting number of timing queues to %d (SND_SEQ_MAX_QUEUES)\n", SND_SEQ_MAX_QUEUES);
		num = SND_SEQ_MAX_QUEUES;
	}
	num_queues = num;

	for (c = 0; c < num; c++) {
		q = snd_seq_queue_new();
		queuetab[q->queue = c] = q;
	}
}

/* delete queues */
void snd_seq_queues_delete(void)
{
	int c;

	for (c = 0; c < num_queues; c++)
		snd_seq_queue_delete(&queuetab[c]);

	num_queues = 0;
}


/* create new queue (constructor) */
queue_t *snd_seq_queue_new(void)
{
	queue_t *q;

	q = snd_calloc(sizeof(queue_t));
	if (q == NULL) {
		snd_printd("malloc failed for snd_seq_queue_new()\n");
		return NULL;
	}

	snd_spin_prepare(q, owner);
	snd_spin_prepare(q, clients);
	snd_spin_prepare(q, check);
	snd_mutex_prepare(q, use);

	q->pool = snd_seq_pool_new();
	q->tickq = snd_seq_prioq_new();
	q->timeq = snd_seq_prioq_new();
	q->timer = snd_seq_timer_new();

	q->owner = SEQ_QUEUE_NO_OWNER;
	q->locked = q->klocked = 0;
	
	return q;
}

/* delete queue (destructor) */
void snd_seq_queue_delete(queue_t ** queue)
{
	queue_t *q = *queue;

	*queue = NULL;

	if (q == NULL) {
		snd_printd("oops: snd_seq_queue_delete() called with NULL queue\n");
		return;
	}
	if (q->owner != SEQ_QUEUE_NO_OWNER) {
		snd_printd("warning: snd_seq_queue_delete(), timer is still owned by client #%d\n", q->owner);
	}
	q->locked = 0;

	/* release resources... */
	snd_seq_prioq_delete(&q->tickq);
	snd_seq_prioq_delete(&q->timeq);
	snd_seq_timer_delete(&q->timer);
	snd_seq_pool_delete(&q->pool);

	snd_free(q, sizeof(queue_t));
}



/* return pointer to queue structure for specified id */
queue_t *queueptr(int queueid)
{
	if (queueid < 0 || queueid >= num_queues) {
		snd_printd("Seq: oops. Trying to get pointer to queue %d\n", queueid);
		return NULL;
	}
	return queuetab[queueid];
}




/* -------------------------------------------------------- */

void snd_seq_check_queue(queue_t *q, int atomic)
{
	unsigned long flags;
	int dequeue = SND_SEQ_MAX_DEQUEUE;
	snd_seq_event_cell_t *cell;

	if (q == NULL)
		return;

	/* make this function non-reentrant */
	snd_spin_lock(q, check, &flags);
	if (q->check_blocked) {
		q->check_again = 1;
		snd_spin_unlock(q, check, &flags);
		return;		/* other thread is already checking queues */
	}
	q->check_blocked = 1;
	snd_spin_unlock(q, check, &flags);

      __again:

	/* Process tick queue... */

	/* limit the number of elements dequeued per pass to save the machine from lockups */
	while (dequeue > 0) {

		cell = snd_seq_prioq_cell_peek(q->tickq);
		if (cell == NULL)
			break;
		if (snd_seq_compare_tick_time(&q->timer->cur_tick, &cell->event.time.tick)) {
			cell = snd_seq_prioq_cell_out(q->tickq);
			if (cell != NULL)
				snd_seq_dispatch_event(cell, atomic);
			dequeue--;
		} else {
			/* event remains in the queue */
			break;
		}
	}


	/* Process time queue... */

	/* limit the number of elements dequeued per pass to save the machine from lockups */
	while (dequeue > 0) {
		cell = snd_seq_prioq_cell_peek(q->timeq);
		if (cell == NULL)
			break;
		if (snd_seq_compare_real_time(&q->timer->cur_time, &cell->event.time.real)) {
			cell = snd_seq_prioq_cell_out(q->timeq);
			if (cell != NULL)
				snd_seq_dispatch_event(cell, atomic);
			dequeue--;
		} else {
			/* event remains in the queue */
			break;
		}
	}

	/* free lock */
	snd_spin_lock(q, check, &flags);
	if (q->check_again) {
		q->check_again = 0;
		snd_spin_unlock(q, check, &flags);
		goto __again;
	}
	q->check_blocked = 0;
	snd_spin_unlock(q, check, &flags);
}

/* check queues and dispatch events */
void snd_seq_check_queues(int atomic)
{
	int c;

	/* NOTE: this is not efficient for large number of queues! */
	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		queue_t *q = queueptr(c);

		if (q == NULL)
			continue;
		snd_seq_check_queue(q, atomic);
	}
}


/* change time stamp if possible */
static void snd_seq_enqueue_process_time(snd_seq_event_cell_t * cell, int realtime)
{
	switch (cell->event.flags & SND_SEQ_TIME_STAMP_MASK) {
	case SND_SEQ_TIME_STAMP_TICK:
		if (cell->event.time.tick)	/* don't change */
			return;
		break;
	case SND_SEQ_TIME_STAMP_REAL:
		if (cell->event.time.real.tv_sec || cell->event.time.real.tv_nsec)
			return;
		break;
	}
	cell->event.flags &= ~SND_SEQ_TIME_STAMP_MASK;
	cell->event.flags |=
		realtime ? SND_SEQ_TIME_STAMP_REAL : SND_SEQ_TIME_STAMP_TICK;
}


/* enqueue a event to singe queue */
static void snd_seq_enqueue_single_event(snd_seq_event_cell_t * cell, int atomic)
{
	int dest;
	queue_t *q;

	if (cell == NULL)
		return;
	dest = cell->event.dest.queue;	/* dest queue */
	q = queueptr(dest);
	if (q == NULL)
		return;
	/* handle relative time stamps, convert them into absolute */
	if ((cell->event.flags & SND_SEQ_TIME_MODE_MASK) == SND_SEQ_TIME_MODE_REL) {
		switch (cell->event.flags & SND_SEQ_TIME_STAMP_MASK) {
			case SND_SEQ_TIME_STAMP_TICK:
				cell->event.time.tick += q->timer->cur_tick;
				cell->event.flags &= ~SND_SEQ_TIME_STAMP_MASK;
				cell->event.flags |= SND_SEQ_TIME_STAMP_TICK;
				break;

			case SND_SEQ_TIME_STAMP_REAL:
				snd_seq_inc_real_time(&cell->event.time.real, &q->timer->cur_time);
				cell->event.flags &= ~SND_SEQ_TIME_STAMP_MASK;
				cell->event.flags |= SND_SEQ_TIME_STAMP_REAL;
				break;
		}
	}
	/* enqueue event in the real-time or midi queue */
	switch (cell->event.flags & SND_SEQ_TIME_STAMP_MASK) {
		case SND_SEQ_TIME_STAMP_TICK:
			snd_seq_prioq_cell_in(q->tickq, cell);
			break;

		case SND_SEQ_TIME_STAMP_REAL:
			snd_seq_prioq_cell_in(q->timeq, cell);
			break;
	}

	/* trigger dispatching */
	snd_seq_check_queues(atomic);

	return;
}



/* enqueue a event received from one client */
void snd_seq_enqueue_event(snd_seq_event_cell_t * cell, int atomic)
{
	int dest;

	if (cell == NULL) {
		snd_printd("oops: snd_seq_enqueue_event() called with NULL cell\n");
		return;
	}
	dest = cell->event.dest.queue;		/* dest queue */

	/* handle special addressing types */
	switch (dest) {
		case SND_SEQ_ADDRESS_BROADCAST:
			snd_printk("Seq: broadcasts to all queues are not supported yet (dest = %d)\n", dest);

			/* release the original cell */
			snd_seq_cell_free(cell);
			break;

		case SND_SEQ_ADDRESS_SUBSCRIBERS:
			{
				queue_t *q;
				client_t *c;
				client_port_t *p;
				subscribers_t *subs;

				/* get pointer to client and lock it */
				c = snd_seq_client_use_ptr(cell->event.source.client);
				if (!c) {
					/* release the original cell */
					snd_seq_cell_free(cell);
					break;
				}

				/* get pointer to subscription list */
				p = snd_seq_port_use_ptr(c, cell->event.source.port);
				if (!p) {
					snd_seq_client_unlock(c);
					/* release the original cell */
					snd_seq_cell_free(cell);
					break;
				}
				if (!(p->capability & SND_SEQ_PORT_CAP_SUBSCRIPTION)) {
					snd_seq_ports_unlock(c);
					snd_seq_client_unlock(c);
					/* release the original cell */
					snd_seq_cell_free(cell);
					break;
				}
				/* go through list of subscribers */
				snd_seq_subscribers_lock(&p->input);
				for (subs = p->input.list; subs != NULL; subs = subs->next) {

					snd_seq_event_cell_t *new_cell;

					/* enqueue copy of the cell for the specified subscriber */
					q = queueptr(subs->addr.queue);
					if (q == NULL)
						continue;
					new_cell = snd_seq_cell_dup(q->pool, cell, atomic);
					if (new_cell) {
						snd_seq_enqueue_process_time(new_cell, subs->realtime);
						new_cell->event.dest.queue = subs->addr.queue;
						new_cell->event.dest.client = subs->addr.client;
						new_cell->event.dest.port = subs->addr.port;
						snd_seq_enqueue_single_event(new_cell, atomic);
					} else {
						snd_printk("seq: failed enqueing for subscriber %d:%d:%d (no mem)\n",
						     subs->addr.queue,
						     subs->addr.client,
						     subs->addr.port);
					}
				}
				snd_seq_subscribers_unlock(&p->input);
				snd_seq_ports_unlock(c);
				snd_seq_client_unlock(c);

				/* release the original cell */
				snd_seq_cell_free(cell);
				break;

			}
			break;

		default:
			snd_seq_enqueue_single_event(cell, atomic);
	}
}


/* check if client has access to queue's parameters, return 1 if client is
   allowed to make changes to the queue */

static inline int check_access(queue_t * q, int client)
{
	return ((!q->locked && !q->klocked) || (q->owner == client));
}

int snd_seq_queue_check_access(int queueid, int client)
{
	queue_t *q = queueptr(queueid);

	if (q) {
		return check_access(q, client);
	} else {
		return 0;
	}
}


/* access to queue's timer */
int snd_seq_queue_timer_stop(int queueid, int client)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);

	if (!q)
		return -EINVAL;

	snd_spin_lock(q, owner, &flags);
	if (check_access(q, client)) {
		q->owner = client;
		q->klocked = 0;
		snd_spin_unlock(q, owner, &flags);
		snd_seq_timer_stop(q->timer);
	} else {
		snd_spin_unlock(q, owner, &flags);
		return -EPERM;
	}
	return 0;
}


int snd_seq_queue_timer_start(int queueid, int client)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);

	if (!q)
		return -EINVAL;

	snd_spin_lock(q, owner, &flags);
	if (check_access(q, client)) {
		q->owner = client;
		q->klocked = 1;
		snd_spin_unlock(q, owner, &flags);
		snd_seq_prioq_leave(q->tickq, client, 1);
		snd_seq_prioq_leave(q->timeq, client, 1);
		snd_seq_timer_start(q->timer);
	} else {
		snd_spin_unlock(q, owner, &flags);
		return -EPERM;
	}
	return 0;
}


int snd_seq_queue_timer_continue(int queueid, int client)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);

	if (!q)
		return -EINVAL;

	snd_spin_lock(q, owner, &flags);
	if (check_access(q, client)) {
		q->owner = client;
		q->klocked = 1;
		snd_spin_unlock(q, owner, &flags);
		snd_seq_timer_continue(q->timer);
	} else {
		snd_spin_unlock(q, owner, &flags);
		return -EPERM;
	}
	return 0;
}


int snd_seq_queue_timer_set_tempo(int queueid, int client, int tempo)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (!q)
		return -EINVAL;

	snd_spin_lock(q, owner, &flags);
	if (check_access(q, client)) {
		result = snd_seq_timer_set_tempo(q->timer, tempo);
		if (result >= 0)
			q->owner = client;
	} else {
		result = -EPERM;
	}
	snd_spin_unlock(q, owner, &flags);
	return result;
}

int snd_seq_queue_timer_set_ppq(int queueid, int client, int ppq)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (!q)
		return -EINVAL;

	snd_spin_lock(q, owner, &flags);
	if (check_access(q, client)) {
		result = snd_seq_timer_set_ppq(q->timer, ppq);
		if (result >= 0)
			q->owner = client;
	} else {
		result = -EPERM;
	}
	snd_spin_unlock(q, owner, &flags);
	return result;
}


int snd_seq_queue_set_owner(int queueid, int client)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (!q)
		return -EINVAL;

	snd_spin_lock(q, owner, &flags);
	if (check_access(q, client)) {
		q->owner = client;
	} else {
		result = -EPERM;
	}
	snd_spin_unlock(q, owner, &flags);
	return result;
}



int snd_seq_queue_set_locked(int queueid, int client, int locked)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (!q)
		return -EINVAL;

	snd_spin_lock(q, owner, &flags);
	if (check_access(q, client)) {
		q->locked = locked ? 1 : 0;
		q->owner = client;
	} else {
		result = -EPERM;
	}
	snd_spin_unlock(q, owner, &flags);
	return result;
}

int snd_seq_queue_timer_open(int queueid)
{
	int result = 0;
	queue_t *queue;
	timer_t *tmr;

	queue = queueptr(queueid);
	if (queue == NULL)
		return -EINVAL;
	tmr = queue->timer;
	switch (tmr->type) {
	case SND_SEQ_TIMER_MASTER:
	case SND_SEQ_TIMER_SLAVE:
		if ((result = snd_seq_timer_open(queue)) < 0) {
			snd_seq_timer_defaults(tmr);
			return snd_seq_timer_open(queue);
		}
		break;
	case SND_SEQ_TIMER_MIDI_CLOCK:
	case SND_SEQ_TIMER_MIDI_TICK:
		if ((result = snd_seq_timer_midi_open(queue)) < 0) {
			snd_seq_timer_defaults(tmr);
			return snd_seq_timer_open(queue);
		}
		break;
	default:
		return -EINVAL;
	}
	return result;
}

int snd_seq_queue_timer_close(int queueid)
{
	queue_t *queue;
	timer_t *tmr;

	queue = queueptr(queueid);
	if (queue == NULL)
		return -EINVAL;
	tmr = queue->timer;
	switch (tmr->type) {
	case SND_SEQ_TIMER_MASTER:
	case SND_SEQ_TIMER_SLAVE:
		snd_seq_timer_close(queue);
		break;
	case SND_SEQ_TIMER_MIDI_CLOCK:
	case SND_SEQ_TIMER_MIDI_TICK:
		snd_seq_timer_midi_close(queue);
		break;
	default:
		return -EINVAL;
	}
	return 0;
}

int snd_seq_queue_use(int queueid, int client, int use)
{
	queue_t *queue;
	unsigned long flags;

	queue = queueptr(queueid);
	if (queue == NULL)
		return -EINVAL;
	snd_mutex_down(queue, use);
	snd_spin_lock(queue, clients, &flags);
	if (use) {
		if (!test_and_set_bit(client, &queue->clients_bitmap))
			queue->clients++;
	} else {
		if (test_and_clear_bit(client, &queue->clients_bitmap))
			queue->clients--;
	}
	snd_spin_unlock(queue, clients, &flags);
	if (queue->clients) {
		snd_seq_pool_init(queue->pool, SND_SEQ_MAX_EVENTS);
		if (use && queue->clients == 1)
			snd_seq_timer_defaults(queue->timer);
		snd_seq_timer_open(queue);
	} else {
		snd_seq_timer_close(queue);
		snd_seq_pool_done(queue->pool);
	}
	snd_mutex_up(queue, use);
	return 0;
}


/* notification that client has left the system */
void snd_seq_queue_client_termination(int client)
{
	unsigned long flags;
	queue_t *q;
	int c;

	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		q = queueptr(c);
		if (!q)
			continue;
		snd_spin_lock(q, owner, &flags);
		if (q->owner == client) {
			q->klocked = 1;
		}
		snd_spin_unlock(q, owner, &flags);
		if (q->owner == client) {
			if (q->timer->running)
				snd_seq_timer_stop(q->timer);
			snd_seq_timer_reset(q->timer);
		}
	}
}

/* final stage notification - remove cells for no longer exist client */
void snd_seq_queue_client_leave(int client)
{
	unsigned long flags;
	int c;
	queue_t *q;

	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		q = queueptr(c);
		if (!q)
			continue;
		snd_seq_prioq_leave(q->tickq, client, q->owner == client);
		snd_seq_prioq_leave(q->timeq, client, q->owner == client);
		snd_spin_lock(q, owner, &flags);
		if (q->owner == client) {
			q->owner = SEQ_QUEUE_NO_OWNER;
			q->locked = 0;
			q->klocked = 0;
		}
		snd_spin_unlock(q, owner, &flags);
		snd_seq_queue_use(c, client, 0);
	}
}

/* exported to seq_info.c */
void snd_seq_info_queues_read(snd_info_buffer_t * buffer, void *private_data)
{
	int c;
	int bpm;
	queue_t *q;
	timer_t *tmr;

	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		q = queueptr(c);
		if (q == NULL)
			continue;
		tmr = q->timer;

		if (tmr->tempo)
			bpm = 60000000 / tmr->tempo;
		else
			bpm = 0;

		snd_iprintf(buffer, "queue %d:\n", c);
		snd_iprintf(buffer, "owned by client    : %d\n", q->owner);
		snd_iprintf(buffer, "lock status        : %s\n", q->locked ? "Locked" : "Free");
		snd_iprintf(buffer, "queued time events : %d\n", snd_seq_prioq_avail(q->timeq));
		snd_iprintf(buffer, "queued tick events : %d\n", snd_seq_prioq_avail(q->tickq));
		snd_iprintf(buffer, "timer state        : %s\n", tmr->running ? "Running" : "Stopped");
		snd_iprintf(buffer, "timer PPQ          : %d\n", tmr->ppq);
		snd_iprintf(buffer, "current tempo      : %d\n", tmr->tempo);
		snd_iprintf(buffer, "current BPM        : %d\n", bpm);
		snd_iprintf(buffer, "current time       : %d.%09d s\n", tmr->cur_time.tv_sec, tmr->cur_time.tv_nsec);
		snd_iprintf(buffer, "current tick       : %d\n", tmr->cur_tick);
		snd_iprintf(buffer, "\n");
	}
}
