#include "machineClock.h"
#include "hardware/structs/usb.h"

// an edge is only used if we know when it happened to within this (us)
#define CLOCK_MAX_EDGE_UNCERTAINTY_US   15
// a phase error beyond this means something went badly wrong: re-anchor
#define CLOCK_RELOCK_NS                 500000
// no SOF for this long: report not ok (we keep free-running on the last rate)
#define CLOCK_TIMEOUT_US                100000
// time to settle after first lock before machine time is trusted
#define CLOCK_SETTLE_US                 1000000
// rate trim limit: 0.2 ns/us = 200 ppm, in Q32
#define CLOCK_TRIM_LIMIT_Q32            ((int64_t)858993459)

// PLL gains, per SOF update (~1 ms):
//   phase: base += err / 64                        (a = 1/64)
//   rate:  trim += err / dl / 16384  (ns per us)   (b = a^2/4: critically damped)
// -> settles in ~0.3 s; 3.5 us of edge jitter is filtered to well under 1 us
#define CLOCK_PHASE_DIV                 64
#define CLOCK_RATE_SHIFT                18      // 32 - log2(16384)

// ---- model: machine_ns = base + dl*1000 + (dl*trim) >> 32,  dl = local_us - local0
// written only by the main loop (interrupts off), read by ISR and main
static volatile int64_t  _base = 0;
static volatile uint64_t _local0 = 0;
static volatile int64_t  _trim = 0;

static bool     _locked = false;
static float    _lastErr = 0;
static uint32_t _relocks = 0;
static uint32_t _rejected = 0;
static uint64_t _lastEdgeUs = 0;
static uint64_t _lockedAtUs = 0;

// ---- SOF observation
static uint16_t _sofLastRaw = 0xFFFF;
static uint32_t _sofCount = 0;
static uint64_t _sofEdgeUs = 0;
static uint32_t _sofSkips = 0;
static uint64_t _lastPollUs = 0;
static uint32_t _maxPollGapUs = 0;

static inline int64_t model_at(uint64_t local_us){
  int64_t dl = (int64_t)(local_us - _local0);
  return _base + dl * 1000 + ((dl * _trim) >> 32);
}

uint64_t clock_machineTimeNs(void){
  return (uint64_t)model_at(time_us_64());
}

bool clock_ok(void){
  uint64_t now = time_us_64();
  return _locked && (now - _lastEdgeUs < CLOCK_TIMEOUT_US) && (now - _lockedAtUs > CLOCK_SETTLE_US);
}

static void set_model(int64_t base, uint64_t local0, int64_t trim){
  noInterrupts();
  _base = base;
  _local0 = local0;
  _trim = trim;
  interrupts();
}

static void clock_onEdge(uint32_t count, uint64_t edgeUs, uint32_t uncertaintyUs){
  _lastEdgeUs = edgeUs;
  int64_t actual = (int64_t)count * 1000000LL;
  if(uncertaintyUs > CLOCK_MAX_EDGE_UNCERTAINTY_US){
    _rejected ++;
    return;
  }
  if(!_locked){
    set_model(actual, edgeUs, 0);
    _locked = true;
    _lockedAtUs = edgeUs;
    return;
  }
  int64_t dl = (int64_t)(edgeUs - _local0);
  if(dl <= 0) return;
  int64_t pred = model_at(edgeUs);
  int64_t err = actual - pred;
  _lastErr = (float)err;
  if(err > CLOCK_RELOCK_NS || err < -CLOCK_RELOCK_NS){
    // something went badly wrong (USB reset, a bogus edge...): re-anchor and
    // don't trust machine time again until it has settled
    set_model(actual, edgeUs, _trim);
    _lockedAtUs = edgeUs;
    _relocks ++;
    return;
  }
  int64_t trim = _trim + (err * (1LL << CLOCK_RATE_SHIFT)) / dl;
  if(trim > CLOCK_TRIM_LIMIT_Q32) trim = CLOCK_TRIM_LIMIT_Q32;
  if(trim < -CLOCK_TRIM_LIMIT_Q32) trim = -CLOCK_TRIM_LIMIT_Q32;
  set_model(pred + err / CLOCK_PHASE_DIV, edgeUs, trim);
}

void clock_poll(void){
  uint64_t now = time_us_64();
  uint32_t gap = _lastPollUs ? (uint32_t)(now - _lastPollUs) : 0xFFFFFFFF;
  if(_lastPollUs && gap > _maxPollGapUs) _maxPollGapUs = gap;

  uint16_t raw = usb_hw->sof_rd & USB_SOF_RD_COUNT_BITS;
  if(_sofLastRaw == 0xFFFF){
    // very first read: we don't know when this frame started (and before USB
    // is up the register just reads 0), so it is not an edge -- only a start
    _sofLastRaw = raw;
    _sofCount = raw;
  } else if(raw != _sofLastRaw){
    uint16_t diff = (raw - _sofLastRaw) & USB_SOF_RD_COUNT_BITS;
    if(diff > 1 && _locked) _sofSkips += diff - 1;
    _sofCount += diff;
    _sofLastRaw = raw;
    // the frame started somewhere between the previous poll and now:
    // take the midpoint, uncertain by half the gap
    _sofEdgeUs = _lastPollUs + (now - _lastPollUs) / 2;
    clock_onEdge(_sofCount, _sofEdgeUs, (uint32_t)((now - _lastPollUs) / 2));
  }
  _lastPollUs = now;
}

void clock_getStatus(clockStatus_t* s){
  clock_poll();
  s->now_us = time_us_64();
  s->sof_raw = _sofLastRaw;
  s->sof_count = _sofCount;
  s->sof_edge_us = _sofEdgeUs;
  s->sof_skips = _sofSkips;
  s->max_poll_gap_us = _maxPollGapUs;
  _maxPollGapUs = 0;
  s->machine_ns = clock_machineTimeNs();
  s->ok = clock_ok() ? 1 : 0;
  s->trim_ppm = (float)_trim / 4294967296.0F * 1000.0F;
  s->phase_err_ns = _lastErr;
  s->relocks = _relocks;
  s->rejected = _rejected;
}
