# Live playback

Play a video while it renders, from its first frames, in a browser or any player.

## Watch a video while it renders

A job's video can play from its first frames, before the job has finished. For a sentence the first frame usually arrives about 2.5 seconds after you submit; the rest arrives several times faster than it plays, so playback does not wait.

Live playback adds a way to read a job; it changes nothing else. Integrations that wait for `succeeded` and download the MP4 keep working as they are, and the stream does not change what you pay: only delivered video time is billed.

## Open the stream

Submit the job as usual, then read its stream with a key that has `jobs:read` and `artifacts:read`.

```
GET /v1/jobs/{job_id}/stream?format=fmp4   fragmented MP4: browsers, ffplay, VLC
GET /v1/jobs/{job_id}/stream?format=ts     MPEG-TS (the default): players, servers, transcoders
```

- `fmp4` sends an initialization segment, then fragments of at most a quarter second. Browsers play it with Media Source Extensions.
- `ts` sends the MPEG-TS stream as it is rendered, for tools that read TS.
- The video is H.264 (`avc1.64002a`, High profile) at the size and frame rate you requested, with no audio track.

### What the stream answers

- `409 stream_not_ready`: the job is still queued. Ask again after about 250 ms. A job that failed or was cancelled also answers 409.
- `200`: the video, from its first frame to its last. While the job runs the response grows as frames are rendered; it continues into the final video once the job succeeds, without a gap or a repeated byte. Opened after success, it is the whole final video (with `fmp4`, the bytes of the MP4 file).
- `410 artifact_expired`: the finished video has expired. Generate it again.
- `429 stream_limit`: too many open streams. Close unused ones and retry.

A successful response carries `X-Preview-Only: true` and `X-Job-Status-Url`. If a job fails while it streams, the stream stops early and the job is not billed; read the job's status for the outcome.

## Try it from a terminal

```bash
curl -sN "https://signapi.fingerdance.ai/v1/jobs/$JOB_ID/stream" \
  -H "Authorization: Bearer $FINGERDANCE_API_KEY" | ffplay -autoexit -i -
```

## Play it in a browser

API keys stay on your server, so a browser reads the stream through a route of yours that checks the signed-in user may watch the job and relays the bytes as they arrive. Turn off response buffering and compression for that route (for nginx: `proxy_buffering off`).

```javascript
// Your server, any Fetch-style runtime: GET /videos/:jobId/live
export async function GET(request, { params }) {
  // Check here that the signed-in user may watch this job.
  const upstream = await fetch(
    `https://signapi.fingerdance.ai/v1/jobs/${params.jobId}/stream?format=fmp4`,
    { headers: { Authorization: `Bearer ${process.env.FINGERDANCE_API_KEY}` } },
  );
  return new Response(upstream.body, {
    status: upstream.status,
    headers: {
      "Content-Type": upstream.headers.get("Content-Type") ?? "application/json",
      "Cache-Control": "no-store",
    },
  });
}
```

```javascript
// Browser
async function playLive(video, streamUrl) {
  // A queued job answers 409 until it starts: ask again shortly.
  let response;
  for (;;) {
    response = await fetch(streamUrl);
    if (response.status !== 409) break;
    await new Promise((resolve) => setTimeout(resolve, 250));
  }
  if (!response.ok) throw new Error("Stream unavailable: " + response.status);

  // Safari on iPhone (17.1+) offers ManagedMediaSource.
  const MediaSourceClass = window.ManagedMediaSource || window.MediaSource;
  const source = new MediaSourceClass();
  video.disableRemotePlayback = true;
  video.muted = true; // no audio track; muted video may start on its own
  video.src = URL.createObjectURL(source);
  await new Promise((resolve) => source.addEventListener("sourceopen", resolve, { once: true }));
  const buffer = source.addSourceBuffer('video/mp4; codecs="avc1.64002a"');

  const queue = [];
  let ended = false;
  const pump = () => {
    if (buffer.updating) return;
    if (queue.length) buffer.appendBuffer(queue.shift());
    else if (ended && source.readyState === "open") source.endOfStream();
  };
  buffer.addEventListener("updateend", () => {
    if (video.paused && video.buffered.length) video.play().catch(() => {});
    pump();
  });

  const reader = response.body.getReader();
  for (;;) {
    const { value, done } = await reader.read();
    if (done) break;
    queue.push(value);
    pump();
  }
  ended = true;
  pump();
}

playLive(document.querySelector("video"), "/videos/JOB_ID/live");
```

Without Media Source Extensions, wait for `succeeded` and play the MP4 from its download URL.
