// Port of jxl-render vardct/generic/mod.rs: adaptive LF smoothing.

///|
const SCALE_SELF : Float = 0.052262735

///|
const SCALE_SIDE : Float = 0.2034514

///|
const SCALE_DIAG : Float = 0.03348292

///|
fn absf(x : Float) -> Float {
  if x < 0.0 {
    -x
  } else {
    x
  }
}

///|
/// `f32::max` (returns the non-NaN operand if one is NaN).
fn maxf(a : Float, b : Float) -> Float {
  if a.is_nan() {
    b
  } else if b.is_nan() {
    a
  } else if a > b {
    a
  } else {
    b
  }
}

///|
fn adaptive_lf_smoothing_impl(
  width : Int32,
  height : Int32,
  shifts : FixedArray[@modular.ChannelShift],
  in_xyb : FixedArray[FixedArray[Float]],
  lf_xyb : FixedArray[Float],
  tracker : @grid.AllocTracker?,
) -> Unit raise @bitstream.JxlError {
  if width <= 2 || height <= 2 {
    // Nothing to do
    return
  }
  let mut subsampled = false
  for s in shifts {
    if s.hshift() + s.vshift() != 0 {
      subsampled = true
    }
  }
  if subsampled {
    return adaptive_lf_smoothing_subsampled_impl(
      width, height, shifts, in_xyb, lf_xyb, tracker,
    )
  }
  let in_x = in_xyb[0]
  let in_y = in_xyb[1]
  let in_b = in_xyb[2]
  let lf_x = lf_xyb[0]
  let lf_y = lf_xyb[1]
  let lf_b = lf_xyb[2]
  let udsum = FixedArray::makei(3, _ => {
    @grid.Grid::with_alloc_tracker(width, height - 2, (0.0 : Float), tracker)
  })
  for c in 0..<3 {
    let g = in_xyb[c]
    let out = udsum[c].buf()
    for y in 0..<(height - 2) {
      for x in 0.. Unit raise @bitstream.JxlError {
  let dims = FixedArray::makei(3, c => shifts[c].shift_size((width, height)))
  for d in dims {
    let (w, h) = d
    if w <= 2 || h <= 2 {
      return
    }
  }
  let wa = FixedArray::makei(3, c => {
    let (w, h) = dims[c]
    @grid.Grid::with_alloc_tracker(w - 2, h - 2, (0.0 : Float), tracker)
  })
  for c in 0..<3 {
    let (w, h) = dims[c]
    let g = in_xyb[c]
    let out = wa[c].buf()
    for y in 0..<(h - 2) {
      let up = y * w
      let center = (y + 1) * w
      let down = (y + 2) * w
      for x in 0..<(w - 2) {
        let me = g[center + x + 1]
        let side = g[up + x + 1] +
          g[center + x] +
          g[center + x + 2] +
          g[down + x + 1]
        let diag = g[up + x] + g[up + x + 2] + g[down + x] + g[down + x + 2]
        out[y * (w - 2) + x] = me * SCALE_SELF +
          side * SCALE_SIDE +
          diag * SCALE_DIAG
      }
    }
  }
  let last_coords_y = FixedArray::make(3, 0)
  let current_row = FixedArray::makei(3, c => {
    FixedArray::make(dims[c].0, (0.0 : Float))
  })
  let coords_y = FixedArray::make(3, 0)
  let coords_x = FixedArray::make(3, 0)
  for row in 0..> shifts[c].vshift()
      if coords_y[c] == 0 || coords_y[c] == dims[c].1 - 1 {
        skip_row = true
      }
    }
    if skip_row {
      continue
    }
    for c in 0..<3 {
      if last_coords_y[c] != coords_y[c] {
        let w = dims[c].0
        FixedArray::blit_to(
          in_xyb[c],
          current_row[c],
          len=w,
          src_offset=coords_y[c] * w,
        )
      }
      last_coords_y[c] = coords_y[c]
    }
    for col in 0..> shifts[c].hshift()
        if coords_x[c] == 0 || coords_x[c] == dims[c].0 - 1 {
          skip_col = true
        }
      }
      if skip_col {
        continue
      }
      let selfs = FixedArray::make(3, (0.0 : Float))
      let was = FixedArray::make(3, (0.0 : Float))
      let mut gap : Float = 0.5
      for c in 0..<3 {
        let s = current_row[c][coords_x[c]]
        let w = wa[c].get(coords_x[c] - 1, coords_y[c] - 1)
        selfs[c] = s
        was[c] = w
        gap = maxf(gap, absf(w - s) / lf_xyb[c])
      }
      let gap_scale = maxf(3.0 - 4.0 * gap, 0.0)
      for c in 0..<3 {
        let shift = shifts[c]
        let skip_update = coords_y[c] << shift.vshift() != row ||
          coords_x[c] << shift.hshift() != col
        if !skip_update {
          in_xyb[c][coords_y[c] * dims[c].0 + coords_x[c]] = (was[c] - selfs[c]) *
            gap_scale +
            selfs[c]
        }
      }
    }
  }
}