Skip to content

Production-ready animations, transitions, backgrounds, and scenes for Remotion

26.9 KB
Raw Blame
{
  "type": "remotion-element",
  "version": 1,
  "element": {
    "assets": [],
    "dependencies": [
      {
        "name": "@remotion/transitions",
        "version": null
      }
    ],
    "dimensions": null,
    "displayName": "TV Power Off",
    "initialProps": null,
    "slug": "tv-power-off",
    "sourceCode": "import { AbsoluteFill, isHtmlInCanvasSupported, useCurrentFrame, useDelayRender, useVideoConfig } from \"remotion\";\nimport React from \"react\";\nimport { type TransitionPresentation, type TransitionPresentationComponentProps } from \"@remotion/transitions\";\n\nconst QUAD = new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]);\n\nconst VERTEX_SHADER = `#version 300 es\nin vec2 a_pos;\nout vec2 v_uv;\nvoid main() {\n  v_uv = vec2(a_pos.x * 0.5 + 0.5, 0.5 - a_pos.y * 0.5);\n  gl_Position = vec4(a_pos, 0.0, 1.0);\n}`;\n\nconst LAYER: React.CSSProperties = {\n  position: \"absolute\",\n  inset: 0,\n  width: \"100%\",\n  height: \"100%\",\n};\n\nconst OUTPUT_LAYER: React.CSSProperties = { ...LAYER, pointerEvents: \"none\" };\n\nconst isCanvasTransitionSupported = (): boolean =>\n  isHtmlInCanvasSupported();\n\nconst isCanvasFilterSupported = (): boolean => isHtmlInCanvasSupported();\n\ntype SceneShaderFrame<Props> = {\n  gl: WebGL2RenderingContext;\n  uniform: (name: string) => WebGLUniformLocation | null;\n  width: number;\n  height: number;\n  progress: number;\n  passedProps: Props;\n};\n\ntype SceneShaderDrawParams<Props> = {\n  from: OffscreenCanvas | null;\n  to: OffscreenCanvas | null;\n  width: number;\n  height: number;\n  progress: number;\n  passedProps: Props;\n};\n\ntype SceneShaderInstance<Props> = {\n  draw: (params: SceneShaderDrawParams<Props>) => void;\n  clear: () => void;\n  cleanup: () => void;\n};\n\ntype SceneShader<Props> = (\n  canvas: OffscreenCanvas,\n) => SceneShaderInstance<Props>;\n\ntype SceneFilterFrame<Props> = {\n  gl: WebGL2RenderingContext;\n  uniform: (name: string) => WebGLUniformLocation | null;\n  width: number;\n  height: number;\n  frame: number;\n  time: number;\n  passedProps: Props;\n};\n\ntype SceneFilterDrawParams<Props> = {\n  scene: OffscreenCanvas | null;\n  width: number;\n  height: number;\n  frame: number;\n  time: number;\n  passedProps: Props;\n};\n\ntype SceneFilterInstance<Props> = {\n  draw: (params: SceneFilterDrawParams<Props>) => void;\n  clear: () => void;\n  cleanup: () => void;\n};\n\ntype SceneFilter<Props> = (\n  canvas: OffscreenCanvas,\n) => SceneFilterInstance<Props>;\n\nfunction compileShader(\n  gl: WebGL2RenderingContext,\n  source: string,\n  type: GLenum,\n): WebGLShader {\n  const shader = gl.createShader(type);\n  if (!shader) {\n    throw new Error(\"canvas-presentation: failed to create shader\");\n  }\n  gl.shaderSource(shader, source);\n  gl.compileShader(shader);\n  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n    const log = gl.getShaderInfoLog(shader);\n    gl.deleteShader(shader);\n    throw new Error(`canvas-presentation: failed to compile shader: ${log}`);\n  }\n  return shader;\n}\n\nfunction createProgram(\n  gl: WebGL2RenderingContext,\n  fragment: string,\n): WebGLProgram {\n  const program = gl.createProgram();\n  if (!program) {\n    throw new Error(\"canvas-presentation: failed to create program\");\n  }\n  const vs = compileShader(gl, VERTEX_SHADER, gl.VERTEX_SHADER);\n  const fs = compileShader(gl, fragment, gl.FRAGMENT_SHADER);\n  gl.attachShader(program, vs);\n  gl.attachShader(program, fs);\n  gl.linkProgram(program);\n  gl.deleteShader(vs);\n  gl.deleteShader(fs);\n  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {\n    const log = gl.getProgramInfoLog(program);\n    gl.deleteProgram(program);\n    throw new Error(`canvas-presentation: failed to link program: ${log}`);\n  }\n  return program;\n}\n\nfunction createSceneTexture(gl: WebGL2RenderingContext): WebGLTexture {\n  const texture = gl.createTexture();\n  if (!texture) {\n    throw new Error(\"canvas-presentation: failed to create texture\");\n  }\n  gl.bindTexture(gl.TEXTURE_2D, texture);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n  gl.texImage2D(\n    gl.TEXTURE_2D,\n    0,\n    gl.RGBA,\n    1,\n    1,\n    0,\n    gl.RGBA,\n    gl.UNSIGNED_BYTE,\n    new Uint8Array([0, 0, 0, 0]),\n  );\n  return texture;\n}\n\nfunction createQuadSurface(canvas: OffscreenCanvas, fragment: string) {\n  const gl = canvas.getContext(\"webgl2\", { premultipliedAlpha: true });\n  if (!gl) {\n    throw new Error(\"canvas-presentation: WebGL2 is unavailable\");\n  }\n\n  const program = createProgram(gl, fragment);\n  const vao = gl.createVertexArray();\n  gl.bindVertexArray(vao);\n  const buffer = gl.createBuffer();\n  gl.bindBuffer(gl.ARRAY_BUFFER, buffer);\n  gl.bufferData(gl.ARRAY_BUFFER, QUAD, gl.STATIC_DRAW);\n  const aPos = gl.getAttribLocation(program, \"a_pos\");\n  gl.enableVertexAttribArray(aPos);\n  gl.vertexAttribPointer(aPos, 2, gl.FLOAT, false, 0, 0);\n\n  const locations = new Map<string, WebGLUniformLocation | null>();\n  const uniform = (name: string) => {\n    const cached = locations.get(name);\n    if (cached !== undefined) {\n      return cached;\n    }\n    const location = gl.getUniformLocation(program, name);\n    locations.set(name, location);\n    return location;\n  };\n\n  const clear = () => {\n    gl.clearColor(0, 0, 0, 0);\n    gl.clear(gl.COLOR_BUFFER_BIT);\n  };\n\n  const textures: WebGLTexture[] = [];\n  const createTexture = () => {\n    const texture = createSceneTexture(gl);\n    textures.push(texture);\n    return texture;\n  };\n\n  const begin = (width: number, height: number) => {\n    gl.viewport(0, 0, width, height);\n    clear();\n    gl.useProgram(program);\n    gl.bindVertexArray(vao);\n  };\n\n  const bindScene = (\n    image: OffscreenCanvas | null,\n    texture: WebGLTexture,\n    unit: number,\n    name: string,\n  ) => {\n    gl.activeTexture(gl.TEXTURE0 + unit);\n    gl.bindTexture(gl.TEXTURE_2D, texture);\n    if (image) {\n      gl.texImage2D(\n        gl.TEXTURE_2D,\n        0,\n        gl.RGBA,\n        gl.RGBA,\n        gl.UNSIGNED_BYTE,\n        image,\n      );\n    }\n    gl.uniform1i(uniform(name), unit);\n  };\n\n  const draw = () => gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);\n\n  const cleanup = () => {\n    gl.deleteProgram(program);\n    for (const texture of textures) {\n      gl.deleteTexture(texture);\n    }\n    gl.deleteBuffer(buffer);\n    gl.deleteVertexArray(vao);\n  };\n\n  return {\n    gl,\n    uniform,\n    clear,\n    createTexture,\n    begin,\n    bindScene,\n    draw,\n    cleanup,\n  };\n}\n\nfunction makeSceneShader<Props extends Record<string, unknown>>(\n  fragment: string,\n  setUniforms?: (frame: SceneShaderFrame<Props>) => void,\n): SceneShader<Props> {\n  return (canvas) => {\n    const surface = createQuadSurface(canvas, fragment);\n    const fromTexture = surface.createTexture();\n    const toTexture = surface.createTexture();\n\n    return {\n      clear: surface.clear,\n      cleanup: surface.cleanup,\n      draw: ({ from, to, width, height, progress, passedProps }) => {\n        surface.begin(width, height);\n        surface.bindScene(from, fromTexture, 0, \"u_from\");\n        surface.bindScene(to, toTexture, 1, \"u_to\");\n\n        surface.gl.uniform1f(surface.uniform(\"u_progress\"), progress);\n        surface.gl.uniform1f(surface.uniform(\"u_aspect\"), width / height);\n        setUniforms?.({\n          gl: surface.gl,\n          uniform: surface.uniform,\n          width,\n          height,\n          progress,\n          passedProps,\n        });\n\n        surface.draw();\n      },\n    };\n  };\n}\n\nfunction makeFilterShader<Props extends Record<string, unknown>>(\n  fragment: string,\n  setUniforms?: (frame: SceneFilterFrame<Props>) => void,\n): SceneFilter<Props> {\n  return (canvas) => {\n    const surface = createQuadSurface(canvas, fragment);\n    const sceneTexture = surface.createTexture();\n\n    return {\n      clear: surface.clear,\n      cleanup: surface.cleanup,\n      draw: ({ scene, width, height, frame, time, passedProps }) => {\n        surface.begin(width, height);\n        surface.bindScene(scene, sceneTexture, 0, \"u_scene\");\n\n        surface.gl.uniform1f(surface.uniform(\"u_frame\"), frame);\n        surface.gl.uniform1f(surface.uniform(\"u_time\"), time);\n        surface.gl.uniform1f(surface.uniform(\"u_aspect\"), width / height);\n        setUniforms?.({\n          gl: surface.gl,\n          uniform: surface.uniform,\n          width,\n          height,\n          frame,\n          time,\n          passedProps,\n        });\n\n        surface.draw();\n      },\n    };\n  };\n}\n\nconst transferred = new WeakMap<HTMLCanvasElement, OffscreenCanvas>();\n\nfunction takeOffscreen(canvas: HTMLCanvasElement): OffscreenCanvas {\n  const existing = transferred.get(canvas);\n  if (existing) {\n    return existing;\n  }\n  const created = canvas.transferControlToOffscreen();\n  transferred.set(canvas, created);\n  return created;\n}\n\nfunction makeCanvasComponent<Props extends Record<string, unknown>>(\n  shader: SceneShader<Props>,\n): React.FC<TransitionPresentationComponentProps<Props>> {\n  return function CanvasScenePresentation({\n    children,\n    presentationProgress,\n    presentationDirection,\n    passedProps,\n    onElementImage,\n    onUnmount,\n    bothEnteringAndExiting,\n  }) {\n    const layoutRef = React.useRef<HTMLCanvasElement | null>(null);\n    const outputRef = React.useRef<HTMLCanvasElement | null>(null);\n    const captureRef = React.useRef<OffscreenCanvas | null>(null);\n    const captureContextRef =\n      React.useRef<OffscreenCanvasRenderingContext2D | null>(null);\n    const outputSurfaceRef = React.useRef<OffscreenCanvas | null>(null);\n    const instanceRef = React.useRef<SceneShaderInstance<Props> | null>(null);\n    const passedPropsRef = React.useRef(passedProps);\n    passedPropsRef.current = passedProps;\n    const onElementImageRef = React.useRef(onElementImage);\n    onElementImageRef.current = onElementImage;\n    const onUnmountRef = React.useRef(onUnmount);\n    onUnmountRef.current = onUnmount;\n\n    const { delayRender, continueRender } = useDelayRender();\n    const passThrough =\n      bothEnteringAndExiting && presentationDirection === \"exiting\";\n\n    const drawRef = React.useRef<\n      (\n        prevImage: OffscreenCanvas | null,\n        nextImage: OffscreenCanvas | null,\n        progress: number,\n      ) => void\n    >(() => undefined);\n    drawRef.current = (prevImage, nextImage, progress) => {\n      const instance = instanceRef.current;\n      if (!instance) {\n        return;\n      }\n      const handle = delayRender(\"canvas-presentation: paint\");\n      const to = prevImage;\n      const from = nextImage;\n      const width = from?.width ?? to?.width ?? 0;\n      const height = from?.height ?? to?.height ?? 0;\n      if (width === 0 || height === 0) {\n        instance.clear();\n        continueRender(handle);\n        return;\n      }\n      instance.draw({\n        from,\n        to,\n        width,\n        height,\n        progress: !to ? 0 : !from ? 1 : progress,\n        passedProps: passedPropsRef.current,\n      });\n      continueRender(handle);\n    };\n\n    const draw = React.useCallback(\n      (\n        prevImage: OffscreenCanvas | null,\n        nextImage: OffscreenCanvas | null,\n        progress: number,\n      ) => drawRef.current(prevImage, nextImage, progress),\n      [],\n    );\n\n    React.useLayoutEffect(() => {\n      if (passThrough) {\n        return;\n      }\n      const layout = layoutRef.current;\n      const output = outputRef.current;\n      if (!layout || !output) {\n        return;\n      }\n      const capture = takeOffscreen(layout);\n      const context = capture.getContext(\"2d\");\n      if (!context) {\n        throw new Error(\"canvas-presentation: failed to acquire a 2D context\");\n      }\n      const surface = takeOffscreen(output);\n      captureRef.current = capture;\n      captureContextRef.current = context;\n      outputSurfaceRef.current = surface;\n      instanceRef.current = shader(surface);\n\n      return () => {\n        instanceRef.current?.cleanup();\n        instanceRef.current = null;\n        captureRef.current = null;\n        captureContextRef.current = null;\n        outputSurfaceRef.current = null;\n      };\n    }, [passThrough, shader]);\n\n    React.useLayoutEffect(() => {\n      if (passThrough) {\n        return;\n      }\n      const layout = layoutRef.current;\n      if (!layout) {\n        return;\n      }\n      layout.layoutSubtree = true;\n      const handlePaint = () => {\n        const scene = layout.firstElementChild;\n        const capture = captureRef.current;\n        const context = captureContextRef.current;\n        if (!scene || !capture || !context) {\n          return;\n        }\n        const elementImage = layout.captureElementImage(scene);\n        try {\n          context.reset();\n          context.drawElementImage(elementImage, 0, 0);\n        } finally {\n          elementImage.close();\n        }\n        onElementImageRef.current(capture, draw);\n      };\n      layout.addEventListener(\"paint\", handlePaint);\n      return () => layout.removeEventListener(\"paint\", handlePaint);\n    }, [passThrough, draw]);\n\n    React.useLayoutEffect(() => {\n      if (passThrough) {\n        return;\n      }\n      const layout = layoutRef.current;\n      if (!layout) {\n        return;\n      }\n      const observer = new ResizeObserver(([entry]) => {\n        const capture = captureRef.current;\n        const surface = outputSurfaceRef.current;\n        if (!capture || !surface) {\n          return;\n        }\n        const width = entry.devicePixelContentBoxSize[0].inlineSize;\n        const height = entry.devicePixelContentBoxSize[0].blockSize;\n        capture.width = width;\n        capture.height = height;\n        surface.width = width;\n        surface.height = height;\n        layout.requestPaint?.();\n      });\n      observer.observe(layout, { box: \"device-pixel-content-box\" });\n      return () => observer.disconnect();\n    }, [passThrough]);\n\n    // biome-ignore lint/correctness/useExhaustiveDependencies: presentationProgress is the intentional trigger — a new progress value is what schedules the next paint\n    React.useLayoutEffect(() => {\n      if (passThrough) {\n        return;\n      }\n      layoutRef.current?.requestPaint?.();\n    }, [passThrough, presentationProgress]);\n\n    React.useLayoutEffect(() => {\n      if (passThrough) {\n        return;\n      }\n      return () => onUnmountRef.current();\n    }, [passThrough]);\n\n    if (passThrough) {\n      return <>{children}</>;\n    }\n\n    return (\n      <AbsoluteFill>\n        <canvas ref={layoutRef} style={LAYER}>\n          {children}\n        </canvas>\n        <canvas ref={outputRef} style={OUTPUT_LAYER} />\n      </AbsoluteFill>\n    );\n  };\n}\n\ntype CanvasFilterProps = {\n  children: React.ReactNode;\n};\n\nfunction makeFilterComponent<Props extends Record<string, unknown>>(\n  shader: SceneFilter<Props>,\n): React.FC<Props & CanvasFilterProps> {\n  return function CanvasSceneFilter(props) {\n    const frame = useCurrentFrame();\n    const { fps } = useVideoConfig();\n    const { delayRender, continueRender } = useDelayRender();\n\n    const layoutRef = React.useRef<HTMLCanvasElement | null>(null);\n    const outputRef = React.useRef<HTMLCanvasElement | null>(null);\n    const captureRef = React.useRef<OffscreenCanvas | null>(null);\n    const captureContextRef =\n      React.useRef<OffscreenCanvasRenderingContext2D | null>(null);\n    const outputSurfaceRef = React.useRef<OffscreenCanvas | null>(null);\n    const instanceRef = React.useRef<SceneFilterInstance<Props> | null>(null);\n\n    const passedPropsRef = React.useRef(props);\n    passedPropsRef.current = props;\n    const frameRef = React.useRef(frame);\n    frameRef.current = frame;\n    const timeRef = React.useRef(frame / fps);\n    timeRef.current = frame / fps;\n\n    React.useLayoutEffect(() => {\n      const layout = layoutRef.current;\n      const output = outputRef.current;\n      if (!layout || !output) {\n        return;\n      }\n      const capture = takeOffscreen(layout);\n      const context = capture.getContext(\"2d\");\n      if (!context) {\n        throw new Error(\"canvas-presentation: failed to acquire a 2D context\");\n      }\n      const surface = takeOffscreen(output);\n      captureRef.current = capture;\n      captureContextRef.current = context;\n      outputSurfaceRef.current = surface;\n      instanceRef.current = shader(surface);\n\n      return () => {\n        instanceRef.current?.cleanup();\n        instanceRef.current = null;\n        captureRef.current = null;\n        captureContextRef.current = null;\n        outputSurfaceRef.current = null;\n      };\n    }, [shader]);\n\n    React.useLayoutEffect(() => {\n      const layout = layoutRef.current;\n      if (!layout) {\n        return;\n      }\n      layout.layoutSubtree = true;\n      const handlePaint = () => {\n        const scene = layout.firstElementChild;\n        const capture = captureRef.current;\n        const context = captureContextRef.current;\n        const instance = instanceRef.current;\n        if (!scene || !capture || !context || !instance) {\n          return;\n        }\n        const elementImage = layout.captureElementImage(scene);\n        try {\n          context.reset();\n          context.drawElementImage(elementImage, 0, 0);\n        } finally {\n          elementImage.close();\n        }\n        if (capture.width === 0 || capture.height === 0) {\n          instance.clear();\n          return;\n        }\n        instance.draw({\n          scene: capture,\n          width: capture.width,\n          height: capture.height,\n          frame: frameRef.current,\n          time: timeRef.current,\n          passedProps: passedPropsRef.current,\n        });\n      };\n      layout.addEventListener(\"paint\", handlePaint);\n      return () => layout.removeEventListener(\"paint\", handlePaint);\n    }, []);\n\n    React.useLayoutEffect(() => {\n      const layout = layoutRef.current;\n      if (!layout) {\n        return;\n      }\n      const observer = new ResizeObserver(([entry]) => {\n        const capture = captureRef.current;\n        const surface = outputSurfaceRef.current;\n        if (!capture || !surface) {\n          return;\n        }\n        const width = entry.devicePixelContentBoxSize[0].inlineSize;\n        const height = entry.devicePixelContentBoxSize[0].blockSize;\n        capture.width = width;\n        capture.height = height;\n        surface.width = width;\n        surface.height = height;\n        layout.requestPaint?.();\n      });\n      observer.observe(layout, { box: \"device-pixel-content-box\" });\n      return () => observer.disconnect();\n    }, []);\n\n    React.useLayoutEffect(() => {\n      const layout = layoutRef.current;\n      if (!layout) {\n        return;\n      }\n      const handle = delayRender(\"canvas-presentation: filter paint\");\n      const settle = () => continueRender(handle);\n      layout.addEventListener(\"paint\", settle, { once: true });\n      layout.requestPaint?.();\n      return () => {\n        layout.removeEventListener(\"paint\", settle);\n        continueRender(handle);\n      };\n    });\n\n    return (\n      <AbsoluteFill>\n        <canvas ref={layoutRef} style={LAYER}>\n          {props.children}\n        </canvas>\n        <canvas ref={outputRef} style={OUTPUT_LAYER} />\n      </AbsoluteFill>\n    );\n  };\n}\n\ntype CanvasPresentationOptions<Props extends Record<string, unknown>> = {\n  shader: SceneShader<Props>;\n  fallback: React.FC<TransitionPresentationComponentProps<Props>>;\n};\n\nfunction makeCanvasPresentation<Props extends Record<string, unknown>>({\n  shader,\n  fallback: Fallback,\n}: CanvasPresentationOptions<Props>): (\n  props: Props,\n) => TransitionPresentation<Props> {\n  const Canvas = makeCanvasComponent(shader);\n\n  const Presentation: React.FC<TransitionPresentationComponentProps<Props>> = (\n    props,\n  ) =>\n    isCanvasTransitionSupported() ? (\n      <Canvas {...props} />\n    ) : (\n      <Fallback {...props} />\n    );\n\n  return (props) => ({ component: Presentation, props });\n}\n\ntype CanvasFilterOptions<Props extends Record<string, unknown>> = {\n  shader: SceneFilter<Props>;\n  fallback: React.FC<Props & CanvasFilterProps>;\n};\n\nfunction makeCanvasFilter<Props extends Record<string, unknown>>({\n  shader,\n  fallback: Fallback,\n}: CanvasFilterOptions<Props>): React.FC<Props & CanvasFilterProps> {\n  const Canvas = makeFilterComponent(shader);\n\n  return function CanvasFilter(props) {\n    return isCanvasFilterSupported() ? (\n      <Canvas {...props} />\n    ) : (\n      <Fallback {...props} />\n    );\n  };\n}\n\nexport type TvPowerOffProps = {\n  durationInFrames?: number;\n  delay?: number;\n  gain?: number;\n  afterglow?: number;\n  phosphor?: string;\n};\n\nconst DEFAULTS = {\n  durationInFrames: 18,\n  delay: 0,\n  gain: 1,\n  afterglow: 1,\n  phosphor: \"#d8ecff\",\n};\n\nconst COLLAPSE_END = 0.6;\nconst PINCH_END = 0.82;\nconst MIN_SQUASH = 0.0055;\nconst MIN_PINCH = 0.004;\nconst CONCENTRATION = 0.3;\nconst DECAY_CURVE = 2.6;\nconst BLACKOUT_IN = 0.06;\n\nconst FRAGMENT_SHADER = `#version 300 es\nprecision highp float;\n\nuniform sampler2D u_scene;\nuniform vec2 u_resolution;\nuniform float u_aspect;\nuniform float u_progress;\nuniform float u_gain;\nuniform float u_afterglow;\nuniform vec3 u_phosphor;\n\nin vec2 v_uv;\nout vec4 outColor;\n\nconst int TAPS = 32;\nconst int COLUMN_TAPS = 8;\nconst float GOLDEN = 0.6180339887;\nconst float COLLAPSE_END = ${COLLAPSE_END.toFixed(4)};\nconst float PINCH_END = ${PINCH_END.toFixed(4)};\nconst float MIN_SQUASH = ${MIN_SQUASH.toFixed(5)};\nconst float MIN_PINCH = ${MIN_PINCH.toFixed(5)};\nconst float CONCENTRATION = ${CONCENTRATION.toFixed(4)};\nconst float DECAY_CURVE = ${DECAY_CURVE.toFixed(4)};\nconst float BLACKOUT_IN = ${BLACKOUT_IN.toFixed(4)};\n\nvoid main() {\n  float p = u_progress;\n\n  if (p <= 0.0) {\n    outColor = texture(u_scene, v_uv);\n    return;\n  }\n  if (p >= 1.0) {\n    outColor = vec4(0.0, 0.0, 0.0, 1.0);\n    return;\n  }\n\n  float collapse = clamp(p / COLLAPSE_END, 0.0, 1.0);\n  float pinch = clamp((p - COLLAPSE_END) / (PINCH_END - COLLAPSE_END), 0.0, 1.0);\n  float decayed = clamp((p - PINCH_END) / (1.0 - PINCH_END), 0.0, 1.0);\n\n  vec2 scale = vec2(pow(MIN_PINCH, pinch), pow(MIN_SQUASH, collapse));\n  vec2 centered = (v_uv - 0.5) / scale + 0.5;\n  vec2 span = 1.0 / (scale * u_resolution);\n\n  vec3 sum = vec3(0.0);\n  for (int i = 0; i < TAPS; i++) {\n    float fi = float(i);\n    vec2 at = centered + vec2(\n      (fract(fi * GOLDEN + 0.5) - 0.5) * span.x,\n      ((fi + 0.5) / float(TAPS) - 0.5) * span.y\n    );\n    vec2 inside = step(vec2(0.0), at) * step(at, vec2(1.0));\n    sum += texture(u_scene, at).rgb * inside.x * inside.y;\n  }\n\n  float concentrate = pow(1.0 / (scale.x * scale.y), CONCENTRATION);\n  vec3 light =\n    (sum / float(TAPS)) * (1.0 + (concentrate - 1.0) * max(u_gain, 0.0));\n\n  float glow = max(u_afterglow, 0.0);\n  float bleed = smoothstep(0.2, 0.8, collapse) * (1.0 - pinch) * glow;\n\n  if (bleed > 0.0) {\n    vec3 column = vec3(0.0);\n    float cx = clamp(centered.x, 0.0, 1.0);\n    for (int i = 0; i < COLUMN_TAPS; i++) {\n      column +=\n        texture(u_scene, vec2(cx, (float(i) + 0.5) / float(COLUMN_TAPS))).rgb;\n    }\n    column /= float(COLUMN_TAPS);\n\n    float dy = v_uv.y - 0.5;\n    float reach = 0.02 + 0.03 * collapse;\n    light +=\n      column *\n      mix(vec3(1.0), u_phosphor, 0.65) *\n      exp(-(dy * dy) / (reach * reach)) *\n      bleed *\n      0.9;\n  }\n\n  if (pinch > 0.0) {\n    vec2 d = (v_uv - 0.5) * vec2(u_aspect, 1.0);\n    float radius = max(0.045 * glow, 0.0005);\n    light +=\n      u_phosphor *\n      exp(-dot(d, d) / (radius * radius)) *\n      smoothstep(0.0, 0.5, pinch) *\n      1.15;\n  }\n\n  light *= pow(max(1.0 - decayed, 0.0001), DECAY_CURVE);\n\n  float blackout = smoothstep(0.0, BLACKOUT_IN, p);\n  outColor = vec4(\n    clamp(light, 0.0, 1.0),\n    mix(texture(u_scene, v_uv).a, 1.0, blackout)\n  );\n}`;\n\nconst clamp = (value: number, min: number, max: number) =>\n  Math.min(max, Math.max(min, value));\n\nfunction toRgb(hex: string): [number, number, number] {\n  const value = hex.replace(\"#\", \"\");\n  const full =\n    value.length === 3\n      ? value\n          .split(\"\")\n          .map((c) => c + c)\n          .join(\"\")\n      : value;\n  const int = Number.parseInt(full, 16);\n  if (Number.isNaN(int)) return [1, 1, 1];\n  return [\n    ((int >> 16) & 255) / 255,\n    ((int >> 8) & 255) / 255,\n    (int & 255) / 255,\n  ];\n}\n\nfunction powerProgress(props: TvPowerOffProps, frame: number): number {\n  const {\n    durationInFrames = DEFAULTS.durationInFrames,\n    delay = DEFAULTS.delay,\n  } = props;\n  return clamp((frame - delay) / Math.max(1, durationInFrames), 0, 1);\n}\n\nconst shader = makeFilterShader<TvPowerOffProps>(\n  FRAGMENT_SHADER,\n  ({ gl, uniform, width, height, frame, passedProps }) => {\n    const {\n      gain = DEFAULTS.gain,\n      afterglow = DEFAULTS.afterglow,\n      phosphor = DEFAULTS.phosphor,\n    } = passedProps;\n    gl.uniform1f(uniform(\"u_progress\"), powerProgress(passedProps, frame));\n    gl.uniform2f(uniform(\"u_resolution\"), width, height);\n    gl.uniform1f(uniform(\"u_gain\"), gain);\n    gl.uniform1f(uniform(\"u_afterglow\"), afterglow);\n    gl.uniform3fv(uniform(\"u_phosphor\"), toRgb(phosphor));\n  },\n);\n\nconst TvPowerOffFallback: React.FC<TvPowerOffProps & CanvasFilterProps> = (\n  props,\n) => {\n  const frame = useCurrentFrame();\n  const {\n    children,\n    gain = DEFAULTS.gain,\n    afterglow = DEFAULTS.afterglow,\n    phosphor = DEFAULTS.phosphor,\n  } = props;\n\n  const p = powerProgress(props, frame);\n  const collapse = clamp(p / COLLAPSE_END, 0, 1);\n  const pinch = clamp((p - COLLAPSE_END) / (PINCH_END - COLLAPSE_END), 0, 1);\n  const decayed = clamp((p - PINCH_END) / (1 - PINCH_END), 0, 1);\n\n  const squash = MIN_SQUASH ** collapse;\n  const pinchX = MIN_PINCH ** pinch;\n  const concentrate = (1 / (squash * pinchX)) ** CONCENTRATION;\n  const fade = (1 - decayed) ** DECAY_CURVE;\n\n  return (\n    <AbsoluteFill>\n      <AbsoluteFill\n        style={{\n          background: \"#000000\",\n          opacity: clamp(p / BLACKOUT_IN, 0, 1),\n        }}\n      />\n      <AbsoluteFill\n        style={{\n          scale: `${pinchX} ${squash}`,\n          filter: `brightness(${1 + (concentrate - 1) * Math.max(gain, 0)})`,\n          opacity: fade,\n        }}\n      >\n        {children}\n      </AbsoluteFill>\n      <AbsoluteFill\n        style={{\n          background: `radial-gradient(circle at 50% 50%, ${phosphor} 0%, transparent 55%)`,\n          opacity: clamp(pinch * afterglow, 0, 1) * fade,\n        }}\n      />\n    </AbsoluteFill>\n  );\n};\n\nexport const TvPowerOff = makeCanvasFilter<TvPowerOffProps>({\n  shader,\n  fallback: TvPowerOffFallback,\n});",
    "durationInFrames": 18,
    "installationMode": "wrapped"
  },
  "durationInFrames": 18
}