#include <stdint.h>
#include <stdio.h>

#include "../common/byte-order.h"
#include "../common/network.h"

#define PAYLOAD_SAMPLES   256
#define PAYLOAD_BYTES     (PAYLOAD_SAMPLES*sizeof(f32))

typedef struct
{
  u32 index;
  u16 channels;
  u16 frames;
  u8 data[PAYLOAD_BYTES];
} packet_t;

void packet_ntoh(packet_t *p)
{
  p->index = ntoh_i32(p->index);
  p->channels = ntoh_i16(p->channels);
  p->frames = ntoh_i16(p->frames);
  u8 *d = p->data;
  u32 i = p->channels * p->frames;
  while(i--) {
    ntoh32_buf(d, d);
    d += 4;
  }
}

void packet_hton(packet_t *p)
{
  u8 *d = p->data;
  int i = p->channels * p->frames;
  while(i--){
    hton32_buf(d, d);
    d += 4;
  }
  p->index = hton_i32(p->index);
  p->channels = hton_i16(p->channels);
  p->frames = hton_i16(p->frames);
}

void packet_sendto(int fd, packet_t *p, struct sockaddr_in address)
{
  packet_hton(p);
  sendto_exactly(fd, (unsigned char *)p, sizeof(packet_t), address);
}

void packet_recv(int fd, packet_t *p, int flags)
{
  recv_exactly(fd, (char *)p, sizeof(packet_t), flags);
  packet_ntoh(p);
}
