///|
#derive(Eq, Debug)
pub(all) suberror RtpError {
  Truncated
  BadVersion(Int32)
}

///|
pub impl Show for RtpError with fn output(self, logger) {
  match self {
    Truncated => logger.write_string("Truncated")
    BadVersion(v) => logger.write_string("BadVersion(" + v.to_string() + ")")
  }
}

///|
#derive(Eq, Debug)
pub(all) struct Header {
  marker : Bool
  payload_type : Int32
  seq : Int32
  timestamp : UInt32
  ssrc : UInt32
  csrc : Array[UInt32]
}

///|
#derive(Eq, Debug)
pub(all) struct Packet {
  header : Header
  payload : Bytes
}

///|
#derive(Eq, Debug)
pub(all) enum RtcpPacket {
  SenderReport(
    ssrc~ : UInt32,
    ntp_hi~ : UInt32,
    ntp_lo~ : UInt32,
    rtp_ts~ : UInt32,
    packets~ : UInt32,
    octets~ : UInt32,
  )
  ReceiverReport(ssrc~ : UInt32)
  Bye(ssrcs~ : Array[UInt32])
  Pli(sender_ssrc~ : UInt32, media_ssrc~ : UInt32)
  Nack(sender_ssrc~ : UInt32, media_ssrc~ : UInt32, pid~ : Int32, blp~ : Int32)
}

///|
fn put_u16(out : Array[Byte], v : Int32) -> Unit {
  out.push(((v >> 8) & 0xff).to_byte())
  out.push((v & 0xff).to_byte())
}

///|
fn put_u32(out : Array[Byte], v : UInt32) -> Unit {
  out.push(((v >> 24) & 0xffU).to_byte())
  out.push(((v >> 16) & 0xffU).to_byte())
  out.push(((v >> 8) & 0xffU).to_byte())
  out.push((v & 0xffU).to_byte())
}

///|
fn get_u16(b : BytesView, off : Int32) -> Int32 {
  (b[off].to_int() << 8) | b[off + 1].to_int()
}

///|
fn get_u32(b : BytesView, off : Int32) -> UInt32 {
  (b[off].to_uint() << 24) |
  (b[off + 1].to_uint() << 16) |
  (b[off + 2].to_uint() << 8) |
  b[off + 3].to_uint()
}

///|
/// Compute the byte length of the fixed + CSRC + optional extension RTP header.
pub fn header_len(packet : BytesView) -> Int32 raise RtpError {
  if packet.length() < 12 {
    raise Truncated
  }
  let v = (packet[0].to_int() >> 6) & 3
  if v != 2 {
    raise BadVersion(v)
  }
  let cc = packet[0].to_int() & 0x0f
  let has_ext = (packet[0].to_int() & 0x10) != 0
  let mut off = 12 + cc * 4
  if off > packet.length() {
    raise Truncated
  }
  if has_ext {
    if off + 4 > packet.length() {
      raise Truncated
    }
    let ext_words = get_u16(packet, off + 2)
    off += 4 + ext_words * 4
    if off > packet.length() {
      raise Truncated
    }
  }
  off
}

///|
pub fn Packet::encode(self : Packet) -> Bytes {
  let out : Array[Byte] = []
  let cc = self.header.csrc.length() & 0x0f
  out.push((0x80 | cc).to_byte())
  let m = if self.header.marker { 0x80 } else { 0 }
  out.push((m | (self.header.payload_type & 0x7f)).to_byte())
  put_u16(out, self.header.seq)
  put_u32(out, self.header.timestamp)
  put_u32(out, self.header.ssrc)
  for i = 0; i < cc; i = i + 1 {
    put_u32(out, self.header.csrc[i])
  }
  for b in self.payload {
    out.push(b)
  }
  Bytes::from_array(out)
}

///|
pub fn Packet::decode(packet : BytesView) -> Packet raise RtpError {
  let hlen = header_len(packet)
  let cc = packet[0].to_int() & 0x0f
  let csrc : Array[UInt32] = []
  for i = 0; i < cc; i = i + 1 {
    csrc.push(get_u32(packet, 12 + i * 4))
  }
  let header : Header = {
    marker: (packet[1].to_int() & 0x80) != 0,
    payload_type: packet[1].to_int() & 0x7f,
    seq: get_u16(packet, 2),
    timestamp: get_u32(packet, 4),
    ssrc: get_u32(packet, 8),
    csrc,
  }
  { header, payload: packet[hlen:].to_owned(), }
}

///|
pub fn RtcpPacket::encode(self : RtcpPacket) -> Bytes {
  let out : Array[Byte] = []
  match self {
    SenderReport(ssrc~, ntp_hi~, ntp_lo~, rtp_ts~, packets~, octets~) => {
      out.push(b'\x80')
      out.push(b'\xc8') // PT=200
      put_u16(out, 6)
      put_u32(out, ssrc)
      put_u32(out, ntp_hi)
      put_u32(out, ntp_lo)
      put_u32(out, rtp_ts)
      put_u32(out, packets)
      put_u32(out, octets)
    }
    ReceiverReport(ssrc~) => {
      out.push(b'\x80')
      out.push(b'\xc9') // PT=201
      put_u16(out, 1)
      put_u32(out, ssrc)
    }
    Bye(ssrcs~) => {
      let sc = ssrcs.length() & 0x1f
      out.push((0x80 | sc).to_byte())
      out.push(b'\xcb') // PT=203
      put_u16(out, sc)
      for s in ssrcs {
        put_u32(out, s)
      }
    }
    Pli(sender_ssrc~, media_ssrc~) => {
      out.push(b'\x81') // FMT=1
      out.push(b'\xce') // PT=206 PSFB
      put_u16(out, 2)
      put_u32(out, sender_ssrc)
      put_u32(out, media_ssrc)
    }
    Nack(sender_ssrc~, media_ssrc~, pid~, blp~) => {
      out.push(b'\x81') // FMT=1
      out.push(b'\xcd') // PT=205 RTPFB
      put_u16(out, 3)
      put_u32(out, sender_ssrc)
      put_u32(out, media_ssrc)
      put_u16(out, pid)
      put_u16(out, blp)
    }
  }
  Bytes::from_array(out)
}

///|
pub fn RtcpPacket::decode(packet : BytesView) -> RtcpPacket raise RtpError {
  if packet.length() < 8 {
    raise Truncated
  }
  let v = (packet[0].to_int() >> 6) & 3
  if v != 2 {
    raise BadVersion(v)
  }
  let pt = packet[1].to_int()
  let rc = packet[0].to_int() & 0x1f
  match pt {
    200 => {
      if packet.length() < 28 {
        raise Truncated
      }
      SenderReport(
        ssrc=get_u32(packet, 4),
        ntp_hi=get_u32(packet, 8),
        ntp_lo=get_u32(packet, 12),
        rtp_ts=get_u32(packet, 16),
        packets=get_u32(packet, 20),
        octets=get_u32(packet, 24),
      )
    }
    201 => ReceiverReport(ssrc=get_u32(packet, 4))
    203 => {
      let ssrcs : Array[UInt32] = []
      for i = 0; i < rc && 4 + (i + 1) * 4 <= packet.length(); i = i + 1 {
        ssrcs.push(get_u32(packet, 4 + i * 4))
      }
      Bye(ssrcs~)
    }
    205 => {
      if packet.length() < 16 {
        raise Truncated
      }
      Nack(
        sender_ssrc=get_u32(packet, 4),
        media_ssrc=get_u32(packet, 8),
        pid=get_u16(packet, 12),
        blp=get_u16(packet, 14),
      )
    }
    206 => {
      if packet.length() < 12 {
        raise Truncated
      }
      Pli(sender_ssrc=get_u32(packet, 4), media_ssrc=get_u32(packet, 8))
    }
    _ => raise Truncated
  }
}

///|
/// Track RTP sequence wrap-around (RFC 3711 ยง3.3.1 ROC estimation).
pub struct SeqTracker {
  mut initialized : Bool
  mut max_seq : Int32
  mut roc : UInt32
}

///|
pub fn SeqTracker::new() -> SeqTracker {
  { initialized: false, max_seq: 0, roc: 0U, }
}

///|
/// Estimate the 48-bit packet index `(roc << 16) | seq` for `seq`.
pub fn SeqTracker::estimate_index(self : SeqTracker, seq : Int32) -> UInt64 {
  if !self.initialized {
    self.initialized = true
    self.max_seq = seq
    return seq.to_uint64()
  }
  let mut guess_roc = self.roc
  if self.max_seq < 32768 {
    if seq - self.max_seq > 32768 {
      if guess_roc > 0U {
        guess_roc -= 1U
      }
    }
  } else if self.max_seq - 32768 > seq {
    guess_roc += 1U
  }
  (guess_roc.to_uint64() << 16) | seq.to_uint64()
}

///|
pub fn SeqTracker::update(self : SeqTracker, seq : Int32) -> UInt64 {
  let idx = self.estimate_index(seq)
  let new_roc = (idx >> 16).to_uint()
  if new_roc > self.roc || (new_roc == self.roc && seq > self.max_seq) {
    self.roc = new_roc
    self.max_seq = seq
  }
  idx
}