// Uniforms for spectrogram frame count, texture
uniform float totalFrames;
uniform float framesPerSecond;

// Signed distance from point p to the line segment from a to b
float sdSegment( in vec2 p, in vec2 a, in vec2 b )
{
    vec2 pa = p - a, ba = b - a;
    float h = clamp(dot(pa,ba) / dot(ba,ba), 0.0, 1.0);
    return length(pa - ba * h);
}

void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
    vec2 uv = fragCoord / iResolution.xy;
    vec3 color = vec3(0.0);

    // Compute the current frame index from time (animation speed: 30 fps)
    float frameIdx = mod(iTime * framesPerSecond, totalFrames);

    const int NUM_BANDS = 5;
    // Loop over each band to create a vertical line segment per band
    for (int i = 0; i < NUM_BANDS; i++)
    {
        // Horizontal position: evenly spaced across the screen
        float lineX = (float(i) + 0.5) / float(NUM_BANDS);
        
        // Fetch the amplitude from the spectrogram texture:
        // X coordinate uses current frame; Y coordinate is the band's center (0.5 of the band’s slice)
        float amplitude = texture(iChannel0, vec2(frameIdx / totalFrames, (float(i) + 0.5) / float(NUM_BANDS))).r;
        
        // Determine vertical extent: center the segment vertically at 0.5 and scale by amplitude.
        float halfHeight = amplitude * 0.4; // Adjust scale factor as needed.
        float y0 = 0.5 - halfHeight;
        float y1 = 0.5 + halfHeight;
        
        // Define the endpoints of the vertical line segment.
        vec2 a = vec2(lineX, y0);
        vec2 b = vec2(lineX, y1);
        
        // Calculate distance from the current fragment to the line segment.
        float d = sdSegment(uv, a, b);
        
        // Define the line thickness in UV space; a smaller value means thinner lines.
        float thickness = 0.075;
        
        // Create a smooth mask for anti-aliasing the line segment.
        float lineMask = 1.0 - smoothstep(thickness, thickness + 0.0001, d);
        
        // Combine the drawn lines (using max so that overlapping lines stay bright).
        color = max(color, vec3(lineMask));
    }

    fragColor = vec4(color, 1.0);
}
