#version 450
#extension GL_GOOGLE_include_directive : enable

#include "d3d9_convert_common.h"

layout(
  local_size_x = 8,
  local_size_y = 8,
  local_size_z = 1) in;

layout(binding = 0)
writeonly uniform image2D dst;

layout(binding = 1) uniform usamplerBuffer src;

layout(push_constant)
uniform u_info_t {
  uvec2 extent;
} u_info;

// Format is:
// YYYYYYYY...
// VVVV...
// UUUU...

float fetchUnorm(usamplerBuffer source, uint offset) {
  return unpackUnorm(texelFetch(src, int(offset)).r);
}

void main() {
  ivec3 thread_id = ivec3(gl_GlobalInvocationID);

  if (all(lessThan(thread_id.xy, u_info.extent))) {
    uvec2 pitch = uvec2(u_info.extent.x, u_info.extent.y);

    uint offset = thread_id.x
                + thread_id.y * pitch.x;

    // Fetch a Y, luminance sample.
    float y = fetchUnorm(src, offset) - (16 / 255.0);        

    // Go into the second plane to get a V, chroma sample
    offset = (thread_id.x / 2)
           + (thread_id.y / 2) * (pitch.x / 2)
           + pitch.x * pitch.y;

    float v = fetchUnorm(src, offset) - (128 / 255.0);

    // Go into the third plane to get a U, chroma sample
    offset += (pitch.x / 2) * (pitch.y / 2);
    float u = fetchUnorm(src, offset) - (128 / 255.0);

    // TODO: Is this the right color space?
    vec4 color = convertBT_709(vec3(y, u, v));

    imageStore(dst, thread_id.xy, color);
  }
}
