#version 330 core

// inputz
in vec2 UV;

uniform vec2 iResolution;
uniform float iTime;
uniform sampler2D iChannel0;
uniform float Decimate;
uniform float DCTglitch;

// outputz
out vec4 fragColor;

#define DCTf 16.0
#define DCTi 16
#define M_PI 3.14159

#define GC 0.9
#define TC 23.976

const uint k = 1103515245U;
vec3 hash(uvec3 x){
    x = ((x>>8U)^x.yzx)*k;
    x = ((x>>8U)^x.yzx)*k;
    x = ((x>>8U)^x.yzx)*k;
    
    return vec3(x)*(1.0/float(0xffffffffU));
}

float hash1(uint n){
	n = (n << 13U) ^ n;
    n = n * (n * n * 15731U + 789221U) + 1376312589U;
    return float( n & uvec3(0x7fffffffU))/float(0x7fffffff);
}

vec3 rgbToYCbCr(in vec3 rgb){
	float y = dot(rgb, vec3(0.299, 0.587, 0.114));
	float cb = 0.5 + dot(rgb, vec3(-0.168736, -0.331264, 0.5));
	float cr = 0.5 + dot(rgb, vec3(0.5, -0.418688, -0.081312));
	return vec3(y, cb, cr);
}

vec3 yCbCrToRgb(in vec3 ycbcr){
	float cb = ycbcr.y - 0.5;
	float cr = ycbcr.z - 0.5;
	float y = ycbcr.x;
	float r = 1.402 * cr;
	float g = -0.344 * cb - 0.714 * cr;
	float b = 1.772 * cb;
	return vec3(r, g, b) + y;
}

vec4 disc(vec2 uv, vec4 c)
{
    vec2 size = iResolution.xy;
    int intx = int(uv.x*size.x);
    int inty = int(uv.y*size.y);
    int xj = int(mod(float(intx), DCTf));
    int yj = int(mod(float(inty), DCTf));
    float dist = float(xj+yj+1);
    vec4 color = c*2.-1.;
    color *= Decimate;
    color /= dist;
    color = round(color);
    color *= dist;
    color /= Decimate;
    return color*0.5+0.5;
}

void main()
{
    vec2 fragCoord = gl_FragCoord.xy;
    vec2 uv = UV;
	vec2 size = vec2(iResolution.xy);
    int inty = int(uv.y*size.y);
    int j = int(mod(float(inty), DCTf)); 
    float y = float(inty - j);
    y /= size.y;
    vec4 array1[DCTi];
	for(int i = 0; i < DCTi; i++)  
		array1[i] = texture(iChannel0, vec2(uv.x, y+(float(i)+0.5)/size.y))*2.-1.; 
    
	vec4 color = vec4(0);
	for(int i = 0; i < DCTi; i++){
		color.rgb += array1[i].rgb*cos(M_PI/DCTf*(float(i)+0.5)*float(j));
	}
	color *= sqrt(2.0/DCTf);
	fragColor = color*0.5+0.5;
    
    //Decimate = 20.0*vec4(1);
    fragColor = disc(uv, fragColor);
    
    vec3 hv = hash( uvec3(fragCoord, iTime*TC*0.5));
    float tv = 0.00005*pow( hash1( uint(iTime*TC*0.25)), 6.0);
    fragColor.rgb -= mix(vec3(0.0), mix(vec3(0),hv,25.*step(0.999995+tv,pow(hash(uvec3(128.0*hv)),vec3(20)))), DCTglitch);
    
}