#version 330 core

// inputz
in vec2 UV;

uniform vec2 iResolution;
uniform float iTime;
uniform sampler2D iChannel0;
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 12

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;
}

void main()
{
    float T = floor(iTime);
    vec2 fragCoord = gl_FragCoord.xy;
    float gv = smoothstep(0.9,0.95,hash1(4626u+uint(T*TC*0.125)));
    float yp = round(fragCoord.y/(1.0+iResolution.y*gv))*(1.0+iResolution.y*gv);
    float rv = 80.0*pow(hash1(uint(yp+T*TC*0.5)), 8.0)*
        step(0.8,pow(hash1(uint( yp )),8.0-7.9*gv));
    float divc = 0.5+step(2.5,rv)*rv;
    fragCoord = mix(fragCoord, vec2(round(fragCoord/divc)*divc), DCTglitch);
    
    vec2 uv = fragCoord/iResolution.xy;
    
    vec2 size = vec2(iResolution.xy);
    int intx = int(uv.x*size.x); 
    int j = int(mod(float(intx), DCTf));  
    float x = float(intx - j);
    x /= size.x;
    vec4 array1[DCTi];
    for(int i = 0; i < DCTi; i++){
        array1[i] = texture(iChannel0, vec2(x+(float(i)+0.5)/size.x, uv.y))*2.-1.;
    }
    
    vec4 color = vec4(0);
    color += array1[0]/2.;
    for(int i = 1; i < DCTi; i++){
        color.rgb += array1[i].rgb*cos(M_PI/DCTf*(float(i))*float(j));
    }
    
    color *= sqrt(2.0/DCTf);
    fragColor = color*0.5+0.5;
}
