// Port of jxl-render features/upsampling.rs (non-separable 2x/4x/8x
// upsampling with the weights from the image metadata).

///|
/// `upsample` on plain values: `up2_weight` (15), `up4_weight` (55) and
/// `up8_weight` (210) are `ImageMetadata`'s custom weights; `factor` is the
/// log2 upsampling factor. Returns `None` when `factor == 0`. The caller
/// upsamples its region by `factor` (`out_region.upsample(factor)`).
pub fn upsample_raw(
  grid : @grid.SubGrid[Float],
  up2_weight : FixedArray[Float],
  up4_weight : FixedArray[Float],
  up8_weight : FixedArray[Float],
  factor : Int32,
  tracker : @grid.AllocTracker?,
) -> @grid.Grid[Float]? raise @bitstream.JxlError {
  let mut out : @grid.Grid[Float]? = None
  let mut grid = grid
  let up8 = factor / 3
  let last_up = factor % 3
  for _ in 0.. Some(upsample_inner(grid, 2, up2_weight, tracker))
    2 => Some(upsample_inner(grid, 4, up4_weight, tracker))
    _ => out
  }
}

///|
/// `upsample_inner::`.
fn upsample_inner(
  grid : @grid.SubGrid[Float],
  k : Int32,
  weights : FixedArray[Float],
  tracker : @grid.AllocTracker?,
) -> @grid.Grid[Float] raise @bitstream.JxlError {
  let nw = weights.length()
  guard (k == 2 && nw == 15) || (k == 4 && nw == 55) || (k == 8 && nw == 210) else {
    abort("upsample: invalid weights")
  }
  let grid_width = grid.width
  let grid_height = grid.height
  let shift = k.ctz()
  let frame_width = grid_width << shift
  let frame_height = grid_height << shift

  // 5x5 kernel
  let padding = 2
  let padded_width = grid_width + padding * 2
  let padded = @grid.Grid::with_alloc_tracker(
    padded_width,
    grid_height + padding * 2,
    (0.0 : Float),
    tracker,
  )
  let padded_buf = padded.buf
  for y in 0..= mat_n
    for x in 0..= mat_n
      let kernel = (mat_y * mat_n + mat_x) * 25
      let mut sum : Float = 0.0
      let mut min : Float = @float.infinity
      let mut max : Float = @float.neg_infinity
      for iy in 0..<5 {
        let ky = if flip_v { 4 - iy } else { iy }
        for ix in 0..<5 {
          let kx = if flip_h { 4 - ix } else { ix }
          let sample = padded_buf[(ref_y + iy) * padded_width + (ref_x + ix)]
          sum = sum + weights_quarter[kernel + ky * 5 + kx] * sample
          min = min.min(sample)
          max = max.max(sample)
        }
      }
      grid_buf[y * frame_width + x] = if !min.is_finite() {
        // This happens if all samples are NaN.
        @float.not_a_number
      } else if sum < min {
        min
      } else if sum > max {
        max
      } else {
        sum
      }
    }
  }
  if tracker is Some(t) {
    t.free(padded.width * padded.height, 4)
  }
  out
}

///|
/// `PaddedGrid::mirror_edges_padding` (util.rs) on a padded buffer of width
/// `stride` holding `height` rows of samples between `padding` rows of padding.
fn upsampling_mirror_edges_padding(
  buf : FixedArray[Float],
  stride : Int32,
  height : Int32,
  padding : Int32,
) -> Unit {
  // Mirror horizontally.
  for y in padding..<(height + padding) {
    for x in 0..