#include <stdio.h>
#include "../common/jack-ringbuffer.h"
#include "../common/print.h"

/* Read data from ring buffer and write to udp port. Packets are
   always sent with a full payload. */

void *jackudp_send_thread(void *PTR)
{
  jackudp_t *d = (jackudp_t *) PTR;
  packet_t p;
  p.index = 0;
  while(1) {
    jack_ringbuffer_wait_for_read(d->rb, PAYLOAD_BYTES, d->pipe[0]);
    p.index++;
    p.channels = d->channels;
    p.frames = PAYLOAD_SAMPLES / d->channels;
    jack_ringbuffer_read_exactly(d->rb, (char *)&(p.data), PAYLOAD_BYTES);
    packet_sendto(d->fd,  &p, d->address);
  }
  return NULL;
}

/* Write data from the JACK input ports to the ring buffer. */

int jackudp_send(jack_nframes_t n, void *PTR )
{
  jackudp_t *d = (jackudp_t *) PTR;
  float *in[MAX_CHANNELS];
  int i, j;
  for(i = 0; i < d->channels; i++) {
    in[i] = (float *) jack_port_get_buffer(d->j_port[i], n);
  }
  for(i = 0; i < n; i++) {
    for(j = 0; j < d->channels; j++) {
      d->j_buffer[(i*d->channels)+j] = (f32) in[j][i];
    }
  }

  int bytes_available = (int) jack_ringbuffer_write_space(d->rb);
  int bytes_to_write = n * sizeof(f32) * d->channels;
  if(bytes_to_write > bytes_available) {
    eprintf ("jack.udp send: buffer overflow error (UDP thread late)\n");
  } else {
    jack_ringbuffer_write_exactly(d->rb, 
				    (char *) d->j_buffer, bytes_to_write );
  }

  char b = 1;
  if(write(d->pipe[1], &b, 1)== -1) {
    eprintf ("jack.udp send: error writing communication pipe.\n");
    FAILURE;
  }
  return 0;
}
