

precision highp float;

layout(location = 0, index = 0) out vec4 outcol0;

uniform sampler2D tex0;
uniform vec4 parms;
//uniform vec4 resolution;

in vec2 texcoord_nm;

float sat( float t ) {
	return clamp( t, 0.0f, 1.0f );
}
vec2 sat( vec2 t ) {
	return clamp( t, 0.0f, 1.0f );
}
// vec3 sat( vec3 v ) {
	// return clamp( v, 0.0f, 1.0f );
// }

//remaps inteval [a;b] to [0;1]
float remap( float t, float a, float b ) {
	return sat( (t - a) / (b - a) );
}

//note: /\ t=[0;0.5;1], y=[0;1;0]
float linterp( float t ) {
	return sat( 1 - abs( 2*t - 1 ) );
}

//note: [0;1]
float rand( vec2 n ) {
  return fract(sin(dot(n.xy, vec2(12.9898, 78.233)))* 43758.5453);
}

//note: [-1;1]
float srand( vec2 n ) {
	return rand(n) * 2 - 1;
}

float trunc( float x, float num_levels )
{
	return floor(x*num_levels) / num_levels;
}
vec2 trunc( vec2 x, vec2 num_levels )
{
	return floor(x*num_levels) / num_levels;
}

vec3 rgb2yuv( vec3 rgb )
{
	vec3 yuv;
	yuv.x = dot( rgb, vec3(0.299,0.587,0.114) );
	yuv.y = dot( rgb, vec3(-0.14713, -0.28886, 0.436) );
	yuv.z = dot( rgb, vec3(0.615, -0.51499, -0.10001) );
	return yuv;
 }
 vec3 yuv2rgb( vec3 yuv )
 {
	vec3 rgb;
	rgb.r = yuv.x + yuv.z * 1.13983f;
	rgb.g = yuv.x + dot( vec2(-0.39465f, -0.58060f), yuv.yz );
	rgb.b = yuv.x + yuv.y * 2.03211f;
	return rgb;
 }

void main()
{
	float time_s = mod( parms.x, 32 );

	float glitch_threshold = 1.0f - parms.y;
	const float max_ofs_siz = 0.1f; //TOOD: input
	const float yuv_threshold = 0.5f; //TODO: input, >1.0f == no distort
	const float time_frq = 16.0f;

	const float min_change_frq = 4.0f;
	float ct = trunc( time_s, min_change_frq );
	float change_rnd = rand( trunc(texcoord_nm.yy,vec2(16)) + 150.0f * ct );

	float tf = time_frq*change_rnd;

	float t = 5.0f * trunc( time_s, tf );
	float vt_rnd = 0.5f*rand( trunc(texcoord_nm.yy + t, vec2(11)) );
	vt_rnd += 0.5f*rand(trunc(texcoord_nm.yy + t, vec2(7)));
	vt_rnd = vt_rnd*2.0f - 1.0f;
	vt_rnd = sign(vt_rnd) * sat( ( abs(vt_rnd) - glitch_threshold) / (1.0f-glitch_threshold) );

// outcol0 = vec4( vec3(0.5f + 0.5f*vt_rnd), 1);
// return;

	vec2 uv_nm = texcoord_nm;
	uv_nm = sat( uv_nm + vec2(max_ofs_siz*vt_rnd, 0) );

	float rnd = rand( vec2( trunc( time_s, 8 )) );
	uv_nm.y = (rnd>mix(1.0f, 0.975f, sat(parms.y))) ? 1.0f-uv_nm.y : uv_nm.y;

// outcol0 = vec4( uv_nm.xy, 0, 1 );
// return;


	vec4 sample = texture( tex0, uv_nm );
	vec3 sample_yuv = rgb2yuv( sample.rgb );
	sample_yuv.y /= 1-3*abs(vt_rnd) * sat( yuv_threshold - vt_rnd );
	sample_yuv.z += 0.125f * vt_rnd * sat( vt_rnd - yuv_threshold );
	outcol0 = vec4( yuv2rgb(sample_yuv), sample.a );
}
