09.8 Video Understanding

Agents & multimodalLesson 8 of 1014,611 wordsOptional8 parts
Module 09 · 0 of 3 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

A video is the most expensive thing you can hand to an LLM: a one-hour clip can cost hundreds of thousands of input tokens, and "the model watched the video" hides a dozen engineering decisions about frames, audio, timestamps, budgets and fallbacks. This lesson is the complete engineering reference for building products that understand video as of November 2026: what native video input is (and which providers actually have it), the provider-neutral frame-sampling pipeline that works everywhere, map-reduce over long videos, the tasks and recipes people actually ship, the cost and latency arithmetic, the quality limits nobody advertises, a short awareness section on video generation, and the privacy duties that come with filming people. The running example is a video Q&A tool: upload a video, get chapters, ask questions, get timestamped answers.

What you'll learn

  • What "video understanding" means to a model: frames sampled at a frame rate, an audio track, and timestamps — and what that costs per second of footage
  • The two architectures (native video input vs frame sampling), the cost shape of video, and a decision table for choosing the route — native input, frame sampling, specialised service or indexing
  • The provider landscape as of November 2026, verified: Gemini's native video input (Files API, inline, YouTube URLs, clipping, FPS, media resolution, static vs agentic processing), OpenAI's frames-only approach, Anthropic's frames-only approach, OpenRouter's video passthrough, open-weight video models, and specialised video-AI services
  • Gemini's video API end to end: upload and poll until ACTIVE, generate_content with video_metadata clipping and FPS, the Interactions API with processing modes and background execution, MM:SS timestamp references, and context caching for repeated questions
  • The provider-neutral frame-sampling pipeline: extracting frames with ffmpeg, PyAV and OpenCV; uniform, keyframe and scene-change sampling with PySceneDetect; frame budgets against token costs; timestamp labelling; combining frames with a transcript; batching and ordering
  • Map-reduce over long videos: segment, describe, aggregate — with a complete, runnable implementation and hierarchical summaries
  • Indexing instead of stuffing for videos measured in hours
  • The tasks and recipes: summarisation and chaptering, Q&A with timestamp citations, event detection, lecture and slide extraction, meeting video notes, screen-recording bug reports, content moderation, accessibility audio description, and video search
  • Cost and latency arithmetic: tokens per second × duration × price, every lever that cuts it, and a calculator with prices as parameters
  • Quality and limits: temporal reasoning, fast action at low FPS, counting over time, text legibility, audio-visual alignment, hallucinated events, needle tests, and evaluating with timestamped ground truth (interval IoU)
  • Video generation at awareness level: what exists as of November 2026 (Gemini Omni Flash, Veo on the enterprise platform, OpenRouter's video endpoint, Runway Dev), the async job pattern, and provenance
  • Privacy, consent and safety for video: faces, minors, workplace recording, retention, and provider terms

What you don't need

  • API keys. Every part has something you can run for free: pure-Python frame and timestamp logic, a scene-change detector on synthetic frames, the map-reduce pipeline with a scripted describer, and the cost calculator. Provider samples are labelled and their output marked as illustrative.
  • How images, PDFs and files are sent in a request. Lesson 03.6 owns the request mechanics (base64, file IDs, size limits, preflight checks); this lesson builds on it and links back rather than re-teaching it.
  • How to transcribe audio. Lesson 09.4 owns speech-to-text; this lesson shows where a transcript plugs into a video pipeline.
  • How to embed media for search. Lesson 09.9 owns multimodal embeddings and retrieval; this lesson previews it where video search comes up.
  • Video generation in depth. Part 7 is an awareness section: enough to recognise the landscape and the async job pattern, not a tutorial.

Setup

The pure-local parts need only Python 3.11+ and NumPy:

bash
uv add numpy        # or: pip install numpy

First time? Create a project with uv init video-understanding --bare --python 3.13 and run scripts with uv run python file.py (see lesson 03.1, Part 4).

The frame-extraction samples use three optional tools plus Pillow for image handling. The samples were written and checked against av 19.0.2, opencv-python 5.0.0.93, scenedetect 0.7.2 and pillow 13.0.0 as of November 2026, and a plain install gives you the newest release of each:

bash
uv add av opencv-python scenedetect pillow
# or: pip install av opencv-python scenedetect pillow

PyAV bundles FFmpeg in its wheels, so import av works without a separate FFmpeg install on Linux, macOS and Windows. OpenCV's wheel is self-contained too. PySceneDetect needs opencv-python (already above) and optionally av for its moviepy/pyav extras — the samples use its OpenCV-based detectors. Pillow (13.0.0, the same version lesson 03.6 was checked against) backs PyAV's frame.to_image() and provides the Image/ImageDraw imports in the timestamp-overlay sample (3.5). The ffmpeg command-line tool itself is a system package (brew install ffmpeg, apt install ffmpeg, or winget install ffmpeg); samples that shell out to it are labelled.

The provider samples use the module's provider SDKs (openai, anthropic, google-genai; checked against the versions in 09.1's Setup) and a .env file (see lesson 03.1, Part 4):

bash
uv add openai anthropic google-genai python-dotenv
bash
# .env  (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...   # optional
OPENROUTER_API_KEY=...   # optional gateway

Only the Gemini samples are needed for native video; the OpenAI, Anthropic and OpenRouter samples show the frames approach. Everything marked "Try it free" or with real output runs with no key and no network.


What you must be able to do after this lesson#

  • Explain how a model sees video as frames, audio and timestamps
  • Choose between native video input and frame sampling
  • Send a video to a model and get timestamped answers
  • Extract frames and summarise a long video with map-reduce
  • Estimate the cost of a video task

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Gemini can watch the whole video natively." Part 2: Native video input on Gemini
"That hour of footage will cost a fortune in tokens." 1.4 The cost shape of video and Part 5: Cost and latency arithmetic
"Why not just send frames to GPT or Claude?" 3.1 Why sample frames yourself
"Use scene detection so we don't send static frames." 3.3 Sampling strategies
"The model missed the goal because it sampled at 1 FPS." 6.2 Temporal reasoning and fast action
"Can it answer 'what happened at 04:32'?" 2.5 Timestamps and clipping
"We have 500 hours of lecture video." 3.8 Indexing instead of stuffing
"Let's cache the video and ask follow-up questions." 2.7 Context caching for video
"Should we use Veo/Sora to generate the video instead?" Part 7: Video generation (awareness)
"Is it OK to film the factory floor and send it to an API?" Part 8: Privacy, consent and safety
"The timestamps in the answer are wrong." 6.6 Evaluating with timestamped ground truth

Part 1: What "video understanding" means to a model#

1.1 A video is three streams pretending to be one#

Strip the container format away and a video file is at most three things:

  • A sequence of still images (frames) at some frame rate — 24, 25 or 30 per second is typical. Each frame is exactly the kind of image input lesson 03.6 already covers.
  • An audio track, usually speech or music mixed with sound effects, sampled tens of thousands of times per second.
  • Timestamps that say which frame and which audio sample belong to which moment. Every useful video answer ("the goal was scored at 04:32") is really a claim about this timeline.

A model can't ingest "a video" the way a person watches one. It ingests a representation: either a native video pipeline that samples frames and folds in the audio server-side, or a set of still images you extracted yourself. The engineering of video understanding is the engineering of choosing, budgeting and labelling that representation.

1.2 The two architectures#

There are exactly two ways a product gets video understanding today:

Approach How it works Who offers it (Nov 2026)
Native video input You upload or reference the video file; the provider samples frames, processes the audio track and aligns timestamps internally Google Gemini (the only major chat-API provider with true native video input as of November 2026); OpenRouter passes it through to whichever provider supports it
Frame sampling (you do it) You extract frames with ffmpeg/PyAV/OpenCV, optionally transcribe the audio separately, and send images plus text to any vision model Works on every vision model: OpenAI, Anthropic, Gemini, OpenRouter video-capable models, and open-weight models

Native input is less code and preserves the audio track, but it locks you to one provider's sampling behaviour and pricing. Frame sampling is provider-neutral and gives you control over exactly which moments the model sees — at the cost of doing the extraction, budgeting and labelling yourself, and losing the audio track unless you transcribe it separately (lesson 09.4). Most production systems end up hybrid: native video where it's available and good enough, frame sampling where you need control or portability.

1.3 What video costs a model's context#

Lesson 02.2, Part 11 explains that media becomes tokens in the same context window as text. For video the numbers are stark because video is long: a model doesn't see "a video", it sees a token stream proportional to duration.

On Gemini's native video input (verified on the video understanding docs, as of November 2026), static processing — the default on every Gemini model — samples 1 frame per second, adds a timestamp every second, processes the audio track at about 1 Kbps mono, and bills roughly:

Media resolution Tokens per frame Approx. tokens per second of video
low 66 ~100
anything else (medium, high, ultra_high) 258 ~300

So one hour of video is about 360,000 tokens at low resolution or ~1.1 million at high — most of a 1M-token context window on its own. Google's own token guide confirms the ~100/~300 figures for static mode (tokens guide, as of November 2026). Google's older pages still quote "263 tokens per second" for video in one spot; treat token counts as estimates and measure with count_tokens before you budget — the same lesson Module 03 learned about audio rates (03.6, 2.4).

1.4 The cost shape of video#

Video is expensive in a specific way: cost scales with duration × sampling rate × resolution, not with how much "content" is in it. A one-hour static shot of a wall costs the same tokens as a one-hour action sequence. That shapes every decision in this lesson:

  • Trim before you send. Dead air, intros and outros are pure token waste.
  • Sample smarter, not denser. Fewer frames on static stretches, more on busy ones.
  • Drop resolution where the task allows. Reading on-screen text needs high; "what is this video about" doesn't.
  • Cache repeated video. Asking five questions about the same hour-long recording shouldn't cost five hours of tokens.
  • Chunk long videos and aggregate. A 10-hour archive can't fit in any context window; it needs indexing and retrieval (09.9).

Part 5 turns this into arithmetic you can run.

1.5 Choosing the video route#

Four routes cover almost every video-understanding product. Choose by task shape first, provider second:

Route Best for Cost shape Latency shape When NOT to use
Gemini native video input Gemini-only stacks; clips within the duration/size limits; repeated questions on the same video (context caching amortises the tokens) ~100–300 tokens per second of footage — duration-proportional Upload + PROCESSING wait + long prefill; streaming and async patterns mitigate Non-Gemini providers; provider-neutral requirements; tight budgets on long footage
Frame-sampling pipeline Provider-neutral products; cost control via FPS, resolution and trimming; hour-plus videos via map-reduce n_frames × per-frame tokens — you control the multiplier Extraction plus one call per segment/batch; parallelisable When the audio track is essential and you won't add a separate STT stage; when true motion understanding is needed
Specialised video-AI service (Twelve Labs, Rekognition, Video Indexer) Search and indexing at scale; moderation pipelines; fixed task APIs (labels, faces, shots) Per-minute indexing or per-query pricing; index once, query cheaply Async index build, then fast queries One-off Q&A on a handful of clips — a second vendor for no benefit
Indexing instead of stuffing Libraries and archives measured in hours (lectures, meeting backlogs, broadcast) Offline describe pass up front, then cheap retrieval queries Query latency ≈ text RAG; the build cost is paid once Single clips or small batches — a plain pipeline is simpler

Most production systems end up hybrid — native video where it's available and good enough, frame sampling where you need control or portability (1.2). This lesson takes the first two routes in depth (Parts 2–3), covers specialised services at awareness level (2.9), and builds the indexing pattern in 3.8–3.9.


Part 2: Native video input on Gemini#

Gemini is the only major chat-API provider with true native video input as of November 2026: you hand it the video file (or a YouTube link) and it samples frames, folds in the audio track and aligns timestamps internally. This part covers the whole surface — upload routes, both APIs, processing modes, timestamps, limits and caching — because nearly every fact here is volatile and worth pinning down.

2.1 Four ways to give Gemini a video#

Route Size limit Best for Notes (verified Nov 2026)
Files API 20 GB per file on paid tier, 2 GB on free; ~20 GB per project (⚠️ the Files API page still says "20 GB per project, 2 GB per file" — the pages disagree, so design for 2 GB per file until they agree) Anything real: long videos, reusable files, anything over ~100 MB Upload → poll until ACTIVE → reference by URI. Files are deleted automatically after 48 hours (03.6, 5.5). Video can sit in PROCESSING for minutes.
Inline data Under ~100 MB total request (Google's pages say 20 MB total in places — design for 20 MB) Clips under a minute, one-off questions Raw bytes in the request; re-sent on every turn of the conversation, so it costs tokens every time.
Cloud Storage registration 2 GB per file, no storage limit Persistent large files in GCS Register a gs:// URI; the file must be in a bucket the API can read.
YouTube URL N/A Public YouTube videos only Preview feature, no charge, but free tier caps at 8 hours of YouTube video per day; max 10 videos per request on Gemini 2.5+; public videos only — no private or unlisted.

Sources: video understanding and file input methods, as of November 2026. The Files API limits and 48-hour retention come from the Files API page, quoted in 03.6.

The canonical flow is upload → poll → reference:

python
# s2_1_gemini_video_upload.py
"""Upload a video to Gemini's Files API and wait until it is ACTIVE (needs a key)."""
import time
from pathlib import Path

from dotenv import load_dotenv
from google import genai

load_dotenv()
client = genai.Client()

# 1. Upload. For anything but a tiny clip this is the right route: the file is
#    stored once and referenced by URI in every later request.
video_file = client.files.upload(file="lecture.mp4")   # your own video

# 2. Poll until the file is usable. Video can spend minutes in PROCESSING;
#    sending a request against a PROCESSING file fails.
deadline = time.monotonic() + 600          # give up after 10 minutes
while video_file.state and video_file.state.name == "PROCESSING":
    if time.monotonic() > deadline:
        raise TimeoutError(f"{video_file.name} still PROCESSING after 10 min")
    time.sleep(5)
    video_file = client.files.get(name=video_file.name)

if video_file.state and video_file.state.name == "FAILED":
    raise RuntimeError(f"{video_file.name} failed processing")

print(f"{video_file.name}: {video_file.state.name}, uri={video_file.uri}")
# Now reference video_file.uri in a request, as the next sample shows.
Example output · illustrative1 line
files/abc123def456: ACTIVE, uri=https://generativelanguage.googleapis.com/v1beta/files/abc123def456

Two operational notes. First, the URI is what you send, not the local path — the model never sees your filesystem. Second, files expire: the 48-hour auto-delete means a stored URI is a short-lived handle, not an archive. If you need the video again next week, re-upload it or keep it in your own object storage and re-upload on demand. For a product, treat the upload as part of the request pipeline, not a one-time setup.

2.2 generate_content: video as a part, with clipping and FPS#

On generate_content, a video is a Part built from raw bytes (from_bytes) or a file reference (file_data with a file_uri). Per-part options live in video_metadata (types.VideoMetadata), verified on the generate-content video docs and the SDK reference:

VideoMetadata field Type Meaning
start_offset string, e.g. "1250s", "10.5s" Clip the video to start here (seconds, must end in s)
end_offset string, e.g. "1570s" Clip the video to end here
fps number, range (0.0, 24.0], default 1.0 Custom frame sampling rate: 0.5 = one frame every 2 seconds
python
# s2_2_gemini_generate_content_video.py
"""Ask Gemini about a clipped section of a video via generate_content (needs a key)."""
from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()

# Reuse the uploaded file from s2_1 (or upload inline bytes for a <1min clip:
# types.Part.from_bytes(data=mp4_bytes, mime_type="video/mp4"))
video_file = client.files.get(name="files/abc123def456")

response = client.models.generate_content(
    model="gemini-3.8-flash",
    contents=types.Content(parts=[
        # Video first: Google's docs say to put the text prompt AFTER the video part.
        types.Part(
            file_data=types.FileData(file_uri=video_file.uri),
            video_metadata=types.VideoMetadata(
                start_offset="1250s",     # only analyse 20:50 -> 26:10
                end_offset="1570s",
                fps=0.5,                  # half the default sampling: cheaper
            ),
        ),
        types.Part(text="Summarise this section in three sentences, with timestamps."),
    ]),
)
print(response.text)
Example output · illustrative1 line
At 21:03 the speaker introduces the three evaluation criteria. From 22:15 to 23:40 she walks through the first criterion, accuracy, using the invoice example. The section closes at 25:58 with a summary of the rubric.

Two details worth internalising. First, clipping is cheap: a 300-second start_offset/end_offset window is tokenised as if the video were only that long — you pay for the clip, not the file. That's the single most useful cost lever on this API. Second, lowering fps below 1 trades temporal detail for tokens linearly-ish: half the frames roughly halves the frame-token share (audio tokens stay). Use it on static content — lectures, slide decks, talking heads — and keep 1 FPS (or higher, up to 24) for action.

2.3 The Interactions API: typed blocks and processing#

Google's newer Interactions API (client.interactions.create) is where video gets its richer controls. A video is a typed {"type": "video", ...} block, and per-video options live in a processing field (verified on the video understanding docs, as of November 2026):

python
# s2_3_gemini_interactions_video.py
"""The same clipped question through the Interactions API (needs a key)."""
from dotenv import load_dotenv
from google import genai

load_dotenv()
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3.8-flash",
    input=[
        {
            "type": "video",
            "uri": "https://generativelanguage.googleapis.com/v1beta/files/abc123def456",
            "mime_type": "video/mp4",
            "processing": {
                "type": "static",          # or "agentic" — see 2.4
                "start_offset": "1250s",
                "end_offset": "1570s",
                "fps": 0.5,
            },
        },
        {"type": "text", "text": "Summarise this section in three sentences, with timestamps."},
    ],
)
print(interaction.output_text)
print("usage:", interaction.usage)

The processing object accepts type ("static" or "agentic"), start_offset, end_offset (strings ending in s) and fps — the same controls as video_metadata, in the Interactions shape. processing and media_resolution are independent per-part settings: you can ask for agentic processing and low media resolution on the same video. Note the shape difference: video_metadata is a typed SDK object on generate_content; processing is a dict on the Interactions input array. Clipping and FPS are documented as static-mode only.

The Interactions response also gives you structured usage worth logging: total_input_tokens, total_output_tokens, total_thought_tokens, total_cached_tokens, total_tool_use_tokens, total_tokens (tokens guide). For video work, log these per request — they are the only trustworthy cost signal, and agentic mode reports its navigation cost across thought and tool_use fields rather than a single input number.

2.4 Static vs agentic processing#

This is the biggest recent change in Gemini video understanding, and it changes the cost model completely. Verified on the video understanding docs, as of November 2026:

Static (default) Agentic
How it works Extracts frames at a fixed rate (1 FPS) and places them into context in a single pass; timestamps added every second The model dynamically navigates the timeline, loading only the transcript, frames and/or audio it needs, adapting frame rate and resolution on the fly
Supported models All Gemini models Gemini 4 Carbon (generally available since 10 November 2026, per the Gemini changelog; see 02.9, 2.3), Gemini 4 Argon, 3.8 Flash, 3.6 Flash, 3.5 Flash Lite
Token cost ~100/sec at low res, ~300/sec at high Variable; up to 88% fewer tokens on long-form content (typically ~1,500–3,000 tokens for a 60-second clip per the tokens guide)
Quality Full coverage; best for short clips and frame-level precision Google's docs claim ~7% higher quality on long-form; adds thought tokens and tool-call round-trips
Latency Predictable Higher TTFT and total time on short clips (<5 min) or broad queries; can take minutes on long videos
How you ask Default — do nothing "processing": "agentic" on the video part (Interactions API, as Google's video-understanding page shows; its clipping and fps options sit in the same processing object and apply only to static mode). In the google-genai SDK's generate_content types, types.Part carries a separate media_processing field (MediaProcessing.AGENTIC or STATIC) next to video_metadata (start_offset, end_offset, fps); this is confirmed in types.Part of google-genai 2.34.0 (the pinned version; source read on 12 November 2026), but Google's docs page only shows the Interactions form, so check your SDK version

Google's own guidance on when to use which: static for clips under ~5 minutes, broad full-video summaries, latency-sensitive queries, or frame-level precision; agentic for videos over ~5–10 minutes, needle-in-a-haystack retrieval, or questions targeting specific moments. For long agentic jobs, use background=True on interactions.create and poll client.interactions.get(id) while status == "in_progress" — synchronous requests can hit timeouts or even 401s on long videos (video docs).

You can verify agentic mode actually ran by inspecting interaction.steps: look for processing_call / processing_result step types (the model loading a segment) interleaved with thought steps. Video context is preserved across turns of a conversation — but on agentic mode, subsequent requests must include the step_list from prior responses or the video context is silently lost (the docs warn it won't error, just degrade). Treat that as a state-management bug waiting to happen: persist the step list with the session.

2.5 Timestamps: asking about moments#

Gemini's video pipeline adds a timestamp every second, and you refer to moments in prompts with MM:SS format (verified on the video docs). Two directions:

  • Point queries: "What are the examples given at 00:05 and 00:10 supposed to show us?" — the model maps MM:SS onto its internal timeline.
  • Timestamped answers: ask for them explicitly — "Describe the key events, providing both audio and visual details. Include timestamps for salient moments." — and you get citations you can seek to in a player.

The catch, covered in Part 6: the timestamp is only as good as the model's temporal grounding. Ask for timestamps and then verify them on your eval set before trusting them in production (6.6).

2.6 Limits that will bite you#

All verified on the video understanding docs and file input methods, as of November 2026:

Limit Value
Context window vs duration Models with a 1M-token context process up to 3 hours at low media resolution, or 1 hour at high
Supported formats video/mp4, video/mpeg, video/mov, video/avi, video/x-flv, video/mpg, video/webm, video/wmv, video/3gpp
File size Files API: 20 GB paid / 2 GB free per file; inline: keep total request under ~20 MB
Files API retention 48 hours, then auto-deleted
YouTube Public only; ≤10 videos/request on Gemini 2.5+; free tier 8 h/day; preview, no charge
Audio track Processed at ~1 Kbps, single channel, 32 tokens/sec
Prompt placement Text prompt goes after the video part in the input array
Long requests Use streaming or background=True; sync requests risk timeouts/401s

Two practical consequences. First, duration is bounded by tokens, not seconds: at ~100 tokens/sec low-res, a 3-hour video is ~1.08M tokens, which is already at the edge of a 1M-token window (Google's "3 hours" is a rounded figure, and you also need room for the prompt and the answer); clip or use agentic mode well before that ceiling. Second, the 48-hour file expiry means your pipeline should upload per-job (or cache the file ID with a re-upload fallback), not assume yesterday's URI still works.

2.7 Context caching for video#

When users ask several questions about the same recording — the natural shape of a video Q&A product — you don't want to pay for the video's tokens on every question. Gemini's answer is context caching (caching docs, as of November 2026):

  • Explicit caching (Beta, v1beta): you create a CachedContent resource holding the video file (and optionally a system instruction), get a cache name back, and reference it in later requests instead of re-sending the file. Cache cost is a storage fee on top of normal token pricing; the default TTL is 1 hour, settable via ttl/expire_time. The caching page lists "repetitive analysis of lengthy video files" as a typical use case, and its example caches a video together with a system instruction. (Google's video page itself does not mention caching; it recommends the Files API for long videos of 10 minutes or more and for files you reuse across requests, which is a different thing: the Files API stores the file, caching stores its processed tokens.)
  • Availability caveat: explicit caching is supported on Gemini 3 and 2.5 models but not on Gemini 4 Argon and onward — those use implicit caching (automatic, best-effort, no guaranteed saving). Check the current model's row on the caching page before relying on it.
  • What you cache: the video part itself plus any system instruction or rubric that will be identical across questions. Per-question text stays out of the cache.

The engineering pattern: on first question for a video, upload + create the cache; store cache_name + video hash in your own DB with the TTL; subsequent questions within the hour reference the cache. After expiry, recreate it — a cache miss just costs you the creation call again, so the failure mode is money, not correctness.

2.8 The other providers: a quick honest tour#

Before building the provider-neutral pipeline, know exactly what you're bypassing:

  • OpenAI: no native video input as of November 2026. The GPT-6 models accept text and image inputs only (changelog; the video-generation guide documents the Sora shutdown). OpenAI's own cookbook demonstrates the workaround: extract frames with OpenCV and send them as input_image parts — "GPT-4.1-mini doesn't take videos as input directly, we can use vision and the 1M token context window to describe the static frames of a whole video at once" (cookbook). That is Part 3 of this lesson.
  • Anthropic: no video input either. The Messages API accepts image blocks (JPEG, PNG, GIF, WebP — and only the first frame of an animated GIF), up to 600 images per request (100 on 200k-context models), max 8000×8000 px (vision docs, as of November 2026). Frames-as-images is the only route.
  • OpenRouter: video input exists as a passthrough — video_url content parts in Chat Completions or input_video in the Responses API (the Messages API doesn't accept video inputs) — but support is per-provider: e.g. Gemini on AI Studio only accepts YouTube links, not arbitrary URLs (OpenRouter video docs, as of November 2026). OpenRouter also passes through Gemini's processing field (agentic/static) on the video part: it routes the request to an endpoint that supports the mode, and other providers ignore the field. Find video-capable models by filtering the catalogue on the video input modality.
  • Open-weight models: the Qwen-VL family (e.g. Qwen2.5/3-VL-class models) and LLaVA-Video-style models accept native video in research/hobby deployments — awareness only; running them needs GPU infrastructure this path doesn't cover.
  • Specialised video-AI services: a different product category — search and indexing rather than chat Q&A. Covered in 2.9.

2.9 Specialised video-AI services#

When the task is "find every moment X happens in 10,000 hours of footage" rather than "answer my question about this clip", dedicated video platforms beat prompting a chat model. Verified as of November 2026:

Service What it does Status/notes
Twelve Labs Video-native platform: Marengo models produce embeddings for search (text, image, composed queries → moment-level results); Pegasus generates text from video (summaries, captions, event timestamps). API at api.twelvelabs.io; latest listed models Marengo 3.5, Pegasus 1.6 The category leader for "search inside video"; you index videos once, then query cheaply
AWS Rekognition Video Task-specific async APIs: labels, faces, face search, celebrities, text detection, content moderation, segments. H.264 in MP4/MOV up to 10 GB; billed per minute per feature Person Pathing ended Oct 31, 2025; Streaming Video and Bulk Image Analysis closed to new customers April 30, 2026 (existing customers keep access) — check the current feature list before designing around it
Azure AI Video Indexer Managed index of many models: scene segmentation, shot types, OCR, transcription, speaker enumeration, audio effects; runs cloud-side or at the edge via Azure Arc Face identification and celebrity recognition are limited-access features
Google Cloud Video Intelligence API The old label/shot/OCR API Reported deprecated September 14, 2026; shuts down September 14, 2027 — see the caveat below. Google's stated migration path is the Gemini family — i.e. this lesson's Part 2

The pattern to notice: the industry is consolidating from fixed-vocabulary annotation APIs (labels, shots, OCR) toward prompt-driven multimodal models (Gemini) plus video-native embedding platforms (Twelve Labs). If you're choosing today, the decision is usually "Gemini for understanding + Twelve Labs-style indexing for search at scale" vs "Rekognition/Video Indexer if you're already deep in AWS/Azure and need their specific features".


Part 3: The frame-sampling approach#

Everything in Part 3 is provider-neutral: it works on OpenAI, Anthropic, Gemini, OpenRouter and local models alike, because at the end of the day you're just sending images and text — the thing lesson 03.6 already teaches exhaustively. This part is about the video-specific engineering on top: getting the right frames, at the right times, with the right labels, for the right price.

3.1 Why sample frames yourself#

You already know the trade-off from Part 1. Frame sampling wins when:

  • Portability matters. The same pipeline feeds GPT, Claude, Gemini or a local model — swap the describer, keep the sampler.
  • You need control. Scene-aware sampling, custom timestamps, cropping to regions of interest, or dropping frames the native sampler would waste tokens on.
  • Cost at scale. A 30-minute static lecture at 0.2 FPS effective sampling might need 360 frames, not 1,800 — and you choose which.
  • The audio matters more than the pixels. Transcribe separately with a dedicated STT model (09.4) — usually cheaper and more accurate than letting a vision model infer speech from frames it never hears.

It loses when: the audio track is essential and you don't want a second pipeline; you need true motion understanding (optical flow, precise action timing) that stills can't give; or the video is short enough that native input's simplicity wins.

flowchart TD
    V["Video file"] --> R{"Route?"}
    R -->|"Gemini native"| U["Upload via Files API / inline / YouTube"]
    U --> P["Poll until ACTIVE"]
    P --> N["generate_content or Interactions<br/>static or agentic processing"]
    R -->|"Frames approach"| F["Extract frames<br/>ffmpeg / PyAV / OpenCV"]
    F --> S{"Sampling strategy"}
    S --> U1["Uniform"]
    S --> K["Keyframe"]
    S --> C["Scene-change"]
    U1 & K & C --> L["Label frames with timestamps<br/>+ transcript from STT"]
    L --> M["Map-reduce over segments<br/>describe then aggregate"]
    N --> A["Chapters / Q&A with MM:SS citations"]
    M --> A

3.2 Extracting frames: ffmpeg, PyAV, OpenCV#

Three tools, three levels of control:

Tool What it is Use when
ffmpeg CLI The universal media swiss-army knife; every serious video pipeline ends here Batch extraction, format conversion, trimming, audio extraction. It's a system binary, not a pip package.
PyAV (av) Python bindings to FFmpeg's libraries; av bundles FFmpeg in its wheels (as of November 2026, av 19.0.2 needs Python ≥3.12; BSD-3-Clause) Frame-accurate seeking, per-frame iteration, audio decoding — when you need the frames as data, not just files on disk
OpenCV (opencv-python) Computer-vision library cv2.VideoCapture for simple sequential reads, and it's what PySceneDetect uses for its detectors

The canonical extraction — "one frame every N seconds, as JPEGs" — is one ffmpeg command:

bash
# s3_2_extract_frames.sh  (illustrative command shape; run on your own video)
mkdir -p frames          # ffmpeg does not create the output folder; it fails without it
ffmpeg -i lecture.mp4 -vf "fps=1/5,scale=1280:-2" -q:v 3 frames/frame_%04d.jpg
#   fps=1/5        -> one frame every 5 seconds (0.2 FPS effective)
#   scale=...      -> downscale so the longest edge is 1280px (saves upload + tokens)
#   -q:v 3         -> JPEG quality; lower = smaller files, less detail

The same tool covers the other chores a video pipeline needs. These are the one-liners you will reach for most (illustrative command shapes; run them on your own files, not on user-supplied names):

bash
# s3_2_ffmpeg_chores.sh  (illustrative; run on your own video)

# 1. How long is it? (seconds, for budgeting before you send anything)
ffprobe -v error -show_entries format=duration -of default=nw=1:nk=1 lecture.mp4

# 2. Cut a clip: start at 1250 s, keep 320 s. -ss BEFORE -i seeks fast;
#    re-encoding (no "-c copy") keeps the cut frame-accurate.
ffmpeg -ss 1250 -t 320 -i lecture.mp4 -c:v libx264 -c:a aac clip.mp4

# 3. Pull the audio track for a speech-to-text model (mono, 16 kHz WAV, 09.4)
ffmpeg -i lecture.mp4 -vn -ac 1 -ar 16000 -c:a pcm_s16le audio.wav

# 4. Keyframes only (the encoder's I-frames, see 3.3)
ffmpeg -i lecture.mp4 -vf "select='eq(pict_type,I)'" -fps_mode vfr -q:v 3 frames/key_%04d.jpg

# 5. Built-in scene-change sampling: keep frames where the scene score exceeds 0.3
ffmpeg -i lecture.mp4 -vf "select='gt(scene,0.3)',showinfo" -fps_mode vfr -q:v 3 frames/scene_%04d.jpg

# 6. A cheaper copy to upload: 480p, 1 frame per second, no audio
#    (only when the task needs neither sound nor small text)
ffmpeg -i lecture.mp4 -vf "fps=1,scale=-2:480" -an small.mp4

Recipe 5 prints each kept frame's timestamp (pts_time:) in ffmpeg's log through showinfo; capture it if you need the time of every extracted frame, because the JPEG file names only carry a counter. -fps_mode vfr is the current spelling of the older -vsync vfr flag (ffmpeg 5.1 and later). Re-encoding and dropping audio change what the model can hear and read, so test the downscaled copy on your own questions before adopting recipe 6.

In Python, PyAV gives you the same control with seeking — important because decoding a 2-hour video frame-by-frame just to sample is wasteful; you seek to each target timestamp:

python
# s3_2b_pyav_seek.py
"""Extract one JPEG per sample time from an MP4 using PyAV (needs av + Pillow)."""
from pathlib import Path

import av


def extract_frames(path: str, sample_times_s: list[float], out_prefix: str) -> list[str]:
    """Grab the frame nearest each requested timestamp. Real output on any video you own."""
    container = av.open(path)
    video = next(s for s in container.streams if s.type == "video")
    time_base = video.time_base                 # e.g. 1/15360: ticks per second
    saved = []
    for i, t in enumerate(sample_times_s):
        # seek to just before the target, then decode forward a little
        container.seek(int(t / time_base), stream=video, backward=True, any_frame=False)
        frame = None
        for f in container.decode(video):
            if float(f.pts * time_base) >= t - 0.5:
                frame = f
                break
        if frame is None:
            continue
        img = frame.to_image()                 # PIL Image
        out = f"{out_prefix}_{i:04d}_{int(t):05d}s.jpg"
        img.save(out, quality=90)
        saved.append(out)
    container.close()
    return saved


if __name__ == "__main__":
    # Needs a real video file; on your own footage this prints the saved paths.
    Path("frames").mkdir(exist_ok=True)       # the JPEGs below go in ./frames
    print(extract_frames("lecture.mp4", [0.0, 30.0, 60.0], "frames/frame"))

The OpenCV route is simpler but decodes sequentially — fine for short clips:

python
# s3_2c_opencv_frames.py
"""Uniform frame sampling with OpenCV (needs opencv-python; run on your own video)."""
import math

import cv2


def sample_uniform(path: str, fps: float, max_frames: int = 60) -> list[tuple[float, object]]:
    """Return (timestamp_seconds, BGR frame) pairs, capped at max_frames."""
    cap = cv2.VideoCapture(path)
    src_fps = cap.get(cv2.CAP_PROP_FPS) or 25.0
    duration = cap.get(cv2.CAP_PROP_FRAME_COUNT) / src_fps
    step = max(1, round(src_fps / fps))
    stride = max(1, math.ceil(duration * fps / max_frames))   # round up so the cap holds
    out = []
    idx = 0
    while True:
        ok, frame = cap.read()
        if not ok:
            break
        if idx % (step * stride) == 0:
            out.append((idx / src_fps, frame))
            if len(out) >= max_frames:
                break
        idx += 1
    cap.release()
    return out

3.3 Sampling strategies#

Uniform sampling is the baseline; the interesting engineering is sampling adaptively:

Strategy How it works Best for Cost
Uniform Fixed interval (e.g. every 5s) General-purpose, predictable budgets Fixed: duration/interval frames
Keyframe sampling Extract only the video's own keyframes (I-frames) — the frames the encoder chose as scene references Cheap first pass; roughly scene-change-aligned already Fewer frames, but count varies per video
Scene-change sampling Detect shot boundaries (histogram difference, edge change, or a learned model) and take one frame per shot plus a few within long shots Editing-heavy content, lectures with slides, sports Near-optimal frame count for the content
Hybrid Scene detection for boundaries + uniform fill inside long static shots Production default Best quality-per-token

Scene detection, concretely. PySceneDetect (scenedetect) is the standard tool — it wraps OpenCV and offers AdaptiveDetector, ContentDetector, ThresholdDetector and friends, plus a scenedetect CLI (scenedetect -i video.mp4 detect-content list-scenes). Its Python API:

python
# s3_3_scenedetect.py
"""Detect shot boundaries with PySceneDetect (needs scenedetect + opencv-python)."""
from scenedetect import detect, ContentDetector, split_video_ffmpeg

scene_list = detect("lecture.mp4", ContentDetector())
for scene in scene_list:
    print(f"{scene[0].get_seconds():7.1f}s -> {scene[1].get_seconds():7.1f}s")
# split_video_ffmpeg("lecture.mp4", scene_list)   # or: keep boundaries, sample inside each

The catch for this lesson: PySceneDetect needs a real video file and OpenCV — it can't run in a keyless exercise. So here's the same idea in pure NumPy on synthetic frames: compute a per-frame histogram, measure the difference between consecutive frames, and cut where the difference spikes. This runs anywhere and teaches you exactly what the detector is doing:

python
# s3_3_scene_detect_numpy.py
"""A minimal scene-change detector on frame arrays — pure NumPy, real output.

Each 'frame' is a small grayscale array. We histogram it, take the L1 distance
between consecutive histograms, and cut a scene where the distance exceeds a
threshold relative to the running mean. This is the same family of signal
PySceneDetect's ContentDetector uses, at toy scale.
"""
import numpy as np


def frame_histogram(frame: np.ndarray, bins: int = 16) -> np.ndarray:
    """Normalised intensity histogram of a 2-D grayscale frame."""
    hist, _ = np.histogram(frame, bins=bins, range=(0, 256))
    return hist / hist.sum()


def detect_scenes(frames: list[np.ndarray], threshold: float = 3.0) -> list[tuple[int, int]]:
    """Return [(start_idx, end_idx)] scene spans from a list of frames."""
    hists = [frame_histogram(f) for f in frames]
    diffs = [float(np.abs(hists[i] - hists[i - 1]).sum()) for i in range(1, len(hists))]
    if not diffs:
        return [(0, len(frames))]
    baseline = float(np.mean(diffs)) + 1e-9
    cuts = [i + 1 for i, d in enumerate(diffs) if d > threshold * baseline]
    bounds = [0] + cuts + [len(frames)]
    return [(bounds[i], bounds[i + 1]) for i in range(len(bounds) - 1)]


if __name__ == "__main__":
    rng = np.random.default_rng(7)
    # Synthetic "video": 4 static scenes of 10 frames each, brightness stepping up
    frames = []
    for level in (30, 90, 160, 60):
        base = np.full((48, 64), level, dtype=np.uint8)
        frames += [base + rng.integers(-4, 5, base.shape, dtype=np.int16).astype(np.uint8)
                   for _ in range(10)]
    scenes = detect_scenes(frames)
    print("scenes:", scenes)
    # Expect ~[(0,10),(10,20),(20,30),(30,40)]: one cut per brightness change.
Output · real — this runs with only NumPy1 line
scenes: [(0, 10), (10, 20), (20, 30), (30, 40)]

That's the whole idea: measure visual change, spend frames where the picture changes, skip the static stretches. On real footage you'd use PySceneDetect's tuned detectors; the principle — sample proportional to information, not time — is identical.

3.4 Frame budgets vs token cost#

Every frame you send is an image token cost (03.6, Part 3). The budget question is: how many frames can I afford, and at what resolution?

Provider Image token cost (typical, as of Nov 2026 — verify per model) What it means for video
Gemini Two different regimes, don't mix them: frames sent as image parts pay the media_resolution image budget — 280/560/1,120/2,240 tokens at low/medium/high/ultra_high; native video tokenises ~66 tokens/frame at low, ~258 otherwise, plus ~32/sec audio (1.3) 360 image-part frames at low ≈ 360 × 280 ≈ 100k tokens. Or native video at fps=0.2, low res: 360 frames × ~66 ≈ 24k frame tokens + ~58k audio ≈ 82k. fps exists only on video parts — never apply it to image-part arithmetic
OpenAI Patch-based, model- and detail-dependent (e.g. ~1,100–1,500+ tokens per image at high detail) 60 frames at high detail ≈ 60–90k tokens; use detail: "low" for overview passes
Anthropic 28×28 patches: ⌈w/28⌉×⌈h/28⌉ per image; a 1000×1000 image ≈ 1,296 tokens Downscale aggressively: 560×560 ≈ 400 tokens/frame
OpenRouter Whatever the underlying provider charges Check architecture.input_modalities and the provider's image rules

Two bounds sit alongside the per-frame price. First, per-request frame-count caps limit dense sampling before the context window does: OpenAI allows up to 1,500 images per request, Anthropic 600 (100 on 200k-context models), Gemini 3,600, and OpenRouter defers to the upstream provider — all as of November 2026, verified in 03.6's limits table. Second, Google's pages disagree on per-frame video counts — the video page's 66/258 for native video, the media-resolution table's 70/280 video-frame budgets, and a flat "263 tokens/second" on the tokens page — so count_tokens on your exact request settles it, the same advice as 1.3.

The working formula for a frame-sampling budget:

text
frames_affordable ≈ token_budget_for_video ÷ tokens_per_frame
sample_interval_s ≈ duration_s ÷ frames_affordable   (for uniform sampling)

For a 30-minute video with a 100k-token video budget at ~1,000 tokens/frame (Anthropic, mid-size image): ~100 frames → one frame every 18 seconds. That's coarse — which is exactly why scene-aware sampling and two-pass strategies (3.7) exist. 03.6's media-token estimator computes per-provider image costs; reuse it rather than re-deriving.

3.5 Labelling frames with timestamps#

A bare sequence of images loses when each was taken. Two labelling strategies:

  1. Text labels in the prompt: send frames in order with an explicit manifest — "Frame 1: 00:00, Frame 2: 00:05, ..." — and instruct the model to cite frame numbers or times. Cheap, works everywhere, but long manifests eat tokens and the model can miscount on long sequences.
  2. Burned-in timestamps: overlay a timestamp onto each frame with Pillow before sending — MM:SS, switching to H:MM:SS past the hour mark so hour-plus videos stay unambiguous (same format as 3.9's mmss and the parse_timestamps reader in 3.10). Costs nothing extra in tokens (the timestamp rides inside the image), is unambiguous to the model, and produces answers you can map straight back to the timeline. Downside: covers a few pixels of content.
python
# s3_5_timestamp_overlay.py
"""Burn a timestamp into a frame with Pillow (pure-local, real output)."""
from PIL import Image, ImageDraw


def mmss(seconds: float) -> str:
    """MM:SS under an hour, H:MM:SS above it — '61:01' would be ambiguous."""
    s = int(round(seconds))
    return f"{s // 3600}:{(s % 3600) // 60:02d}:{s % 60:02d}" if s >= 3600 else f"{s // 60:02d}:{s % 60:02d}"


def label_frame(img: Image.Image, t: float) -> Image.Image:
    """Return a copy with a timestamp burned into the bottom-left corner."""
    out = img.copy()
    draw = ImageDraw.Draw(out)
    text = mmss(t)
    # Simple box so the text reads on any background
    x, y = 8, out.height - 26
    draw.rectangle([x - 2, y - 2, x + 8 * len(text) + 4, y + 18], fill=(0, 0, 0))
    draw.text((x, y), text, fill=(255, 255, 60))
    return out


if __name__ == "__main__":
    # On any image: label_frame(Image.open("frame.jpg"), 252.0) -> "04:12" overlay
    print(mmss(252.0), mmss(3661.0))
Output · real1 line
04:12 1:01:01

The prompt then just says: "These frames are from a video, sampled every 5 seconds, with timestamps burned in. Answer with timestamps." Combining text manifest + burned-in time is belt-and-braces; pick one per pipeline and be consistent — mixed signals confuse citation.

3.6 Combining frames with the transcript#

Frames alone miss everything said but not shown (and audio carries half the meaning in lectures, meetings, demos). The standard hybrid:

  1. Transcribe the audio track separately — dedicated STT (09.4) or Gemini's audio understanding — into timestamped segments.
  2. Send frames + aligned transcript in one prompt: interleave "at 04:32 the speaker says X" with the frame at 04:30, or give the transcript as a block the model can cross-reference.
  3. For long videos, align by time, not order: build a Timeline of {t, transcript_segment, frame_paths} and let the describer see both modalities at each window.

The transcript is also your cheapest indexing signal for Part 3.8's search: you can BM25-search the transcript text to find candidate moments before spending any vision tokens (Module 06, 09.9).

3.7 Two-pass "locate then zoom"#

The cost-optimal pattern for anything beyond a short clip:

  • Pass 1 (cheap, wide): sample sparsely (0.1–0.2 FPS or scene-keyframes only) at low detail/resolution + the full transcript. Ask: where are the relevant moments? Get back candidate time ranges.
  • Pass 2 (expensive, narrow): clip to those ranges (Gemini's start_offset/end_offset, or ffmpeg -ss/-to before re-sampling) and re-ask at higher FPS/resolution for the detail pass.

You pay dense-sampling prices only for the 10% of the video that matters. This is exactly what Gemini's agentic mode does internally (2.4) — doing it yourself makes it portable and observable.

3.8 Indexing instead of stuffing#

For videos measured in hours — lecture archives, meeting backlogs, broadcast monitoring — no context window and no per-request budget works. The pattern that does:

  1. Offline pass: transcribe (STT), scene-detect, and generate a per-segment description (frames + transcript → short structured summary with timestamps). Store {start, end, summary, transcript, frame thumbnails} per segment.
  2. Index: embed the summaries/transcripts (and later the frames — 09.9) into a vector store; keep the timeline metadata as filters.
  3. Query time: retrieve the top segments, fetch their frames/clips, and send only those to the VLM with the question.

This is retrieval-augmented video understanding — the video analogue of RAG (Module 07). It turns "impossible: 500 hours won't fit" into "cheap: search first, look second". 09.9 builds the embedding side properly; this lesson gives you the segment-description pipeline that feeds it.

3.9 Map-reduce over long videos#

Between "one clip" and "an archive" sits the middle case: videos of 30–120 minutes that exceed a comfortable single-request budget but aren't worth a full index. The pattern is map-reduce: split into overlapping segments, describe each (the map), then aggregate the segment descriptions into a whole-video answer (the reduce). This is also how you build chapters.

Here's the complete, runnable core — pure Python, no keys, with an injectable describe_segment so the same code drives a real VLM call or a test double:

python
# s3_9_mapreduce.py
"""Map-reduce over a long video: segment -> describe -> aggregate.

Pure Python (stdlib only). `describe_segment` is injectable: in production it
calls your VLM with the segment's frames + transcript slice; here it's a
scripted fake so the whole control flow runs with real output.
"""
from __future__ import annotations

import re
from collections.abc import Callable, Sequence
from dataclasses import dataclass


@dataclass
class Segment:
    index: int
    start_s: float
    end_s: float
    # In production: frame paths + transcript slice for this window.
    payload: object = None


@dataclass
class SegmentSummary:
    segment: Segment
    text: str


def segment_video(duration_s: float, segment_s: float = 300.0,
                  overlap_s: float = 15.0) -> list[Segment]:
    """Split [0, duration_s) into overlapping windows. Overlap catches action
    that straddles a boundary; 15s on 5min segments is a typical choice."""
    step = segment_s - overlap_s
    segs = []
    i = 0
    start = 0.0
    while start < duration_s:
        segs.append(Segment(i, start, min(start + segment_s, duration_s)))
        i += 1
        start += step
    return segs


def mmss(seconds: float) -> str:
    s = int(round(seconds))
    return f"{s // 3600}:{(s % 3600) // 60:02d}:{s % 60:02d}" if s >= 3600 else f"{s // 60:02d}:{s % 60:02d}"


def map_segments(segments: Sequence[Segment],
                 describe: Callable[[Segment], str]) -> list[SegmentSummary]:
    """The 'map' stage: one model call per segment. Parallelise with a thread
    or task pool in production (link 03.9); keep order for the reduce."""
    return [SegmentSummary(seg, describe(seg)) for seg in segments]


def reduce_summaries(summaries: Sequence[SegmentSummary],
                     aggregate: Callable[[str], str]) -> str:
    """The 'reduce' stage: concatenate timestamped segment summaries and ask
    for the whole-video answer. For very long videos, reduce hierarchically:
    group ~10 summaries per call, then aggregate those."""
    joined = "\n\n".join(
        f"[{mmss(s.segment.start_s)} - {mmss(s.segment.end_s)}] {s.text}"
        for s in summaries
    )
    return aggregate(joined)


def chapters_from_summaries(summaries: Sequence[SegmentSummary]) -> list[tuple[str, str]]:
    """Cheap chaptering: take the first sentence of each segment summary as a
    chapter title at its start time. Good enough for navigation; refine with a
    dedicated pass if titles matter."""
    out = []
    for s in summaries:
        first = re.split(r"(?<=[.!?])\s", s.text.strip(), maxsplit=1)[0]
        out.append((mmss(s.segment.start_s), first[:80]))
    return out


# --- A scripted describer so the pipeline runs with no model and no key ---
SCENE_SCRIPT = {
    # segment index -> what "happens" (stands in for VLM output)
    0: "The host introduces the product and its three features.",
    1: "Feature one: dashboard walkthrough with sample charts.",
    2: "Feature two: the reporting API, with a code example.",
    3: "Feature three: integrations and pricing tiers.",
    4: "Q&A: the host answers audience questions about rollout.",
}


def fake_describe(seg: Segment) -> str:
    return SCENE_SCRIPT.get(seg.index, "Miscellaneous content.")


def fake_aggregate(joined: str) -> str:
    return ("Whole-video summary built from segment summaries. "
            f"Covered {joined.count('[')} segments.")


if __name__ == "__main__":
    segs = segment_video(duration_s=1500, segment_s=300, overlap_s=15)
    print(f"{len(segs)} segments covering 25 minutes")
    summaries = map_segments(segs, fake_describe)
    print("\nChapters:")
    for t, title in chapters_from_summaries(summaries):
        print(f"  {t}  {title}")
    print("\nFinal answer:")
    print(reduce_summaries(summaries, fake_aggregate))
Output · real — stdlib only, no model12 lines
6 segments covering 25 minutes

Chapters:
  00:00  The host introduces the product and its three features.
  04:45  Feature one: dashboard walkthrough with sample charts.
  09:30  Feature two: the reporting API, with a code example.
  14:15  Feature three: integrations and pricing tiers.
  19:00  Q&A: the host answers audience questions about rollout.
  23:45  Miscellaneous content.

Final answer:
Whole-video summary built from segment summaries. Covered 6 segments.

Production wiring: describe becomes a function that reads each segment's payload — the frame paths and transcript slice you populate at ingest time — and calls your VLM with them (on Gemini you can even skip frame extraction and pass the video with start_offset/end_offset per segment; on OpenAI/Anthropic it's your frames plus the transcript text). aggregate becomes the same call with the joined summaries. Segment size is a cost/quality dial: 2–5 minutes is typical; overlap of 10–30 seconds prevents boundary-straddling events being described twice or missed. For the reduce on hour-plus videos, go hierarchical — summarise groups of ~10 segment summaries, then summarise those — because stuffing 60 segment summaries plus frames can itself blow the context.

3.10 The running example: video Q&A tool#

Putting Parts 2–3 together as a product skeleton — upload → chapters → Q&A with timestamps. The design is deliberately provider-pluggable:

python
# s3_10_video_qa.py
"""Video Q&A tool skeleton: ingest -> chapters -> ask.

Provider-agnostic: a `VideoBackend` protocol hides whether the model sees the
video natively (Gemini) or as sampled frames (everyone else). Only the backend
implementation changes; the Q&A flow, timestamp handling and chaptering are
shared. Illustrative provider calls; pure-local parts are real.
"""
from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import Protocol


@dataclass
class VideoRef:
    """A video in your system: where the bytes live and how long it is."""
    video_id: str
    path: str
    duration_s: float
    # For Gemini native: the Files API URI once uploaded. For frames: nothing.
    provider_uri: str | None = None


@dataclass
class Chapter:
    start_s: float
    title: str


@dataclass
class Answer:
    text: str
    timestamps: list[float] = field(default_factory=list)  # parsed MM:SS -> seconds


class VideoBackend(Protocol):
    """What a provider must offer for this tool."""
    def describe_segments(self, video: VideoRef, segments: list[tuple[float, float]]) -> list[str]: ...
    def ask(self, video: VideoRef, question: str,
            clip: tuple[float, float] | None = None) -> Answer: ...


def parse_timestamps(text: str) -> list[float]:
    """Pull MM:SS (and H:MM:SS) timestamps out of an answer, in order."""
    out = []
    for m in re.finditer(r"\b(\d{1,2}):(\d{2})(?::(\d{2}))?\b", text):
        if m.group(3):                       # H:MM:SS
            out.append(int(m.group(1)) * 3600 + int(m.group(2)) * 60 + int(m.group(3)))
        else:                                # MM:SS
            out.append(int(m.group(1)) * 60 + int(m.group(2)))
    return out


def ask_with_clipping(backend: VideoBackend, video: VideoRef, question: str,
                      clip: tuple[float, float] | None = None) -> Answer:
    """The Q&A flow: ask for timestamps in the prompt, then parse them back
    into seconds so the UI can render 'jump to 04:32' links."""
    prompt = (f"{question}\n\nAnswer using the video. Whenever you refer to a "
              f"moment, cite it as [MM:SS].")
    # clip=None -> whole video (or the provider's agentic mode); a (start,end)
    # clip focuses the question on one chapter.
    answer = backend.ask(video, prompt, clip=clip)
    # Parse the citations back into seconds, and drop any that fall outside the
    # video: a timestamp past the end is a hallucination marker (Part 6).
    answer.timestamps = [t for t in parse_timestamps(answer.text)
                         if 0 <= t <= video.duration_s]
    return answer


def make_chapters(backend: VideoBackend, video: VideoRef,
                  segment_s: float = 300.0) -> list[Chapter]:
    """Chaptering = map-reduce's reduce step at chapter granularity."""
    segs = [(i * segment_s, min((i + 1) * segment_s, video.duration_s))
            for i in range(int(video.duration_s // segment_s) + 1)]
    segs = [(s, e) for s, e in segs if e > s]
    summaries = backend.describe_segments(video, segs)
    return [Chapter(s, re.split(r"(?<=[.!?])\s", t.strip(), maxsplit=1)[0][:80])
            for (s, _), t in zip(segs, summaries)]


# A Gemini-native backend would upload -> cache -> call interactions with
# processing={"type": "static"|"agentic"}; a frames backend would run the
# Part 3 sampler + a vision call per segment. Both satisfy the protocol.

The timestamp parser is real and runs now:

python
# (continued — pure local, real output)
if __name__ == "__main__":
    sample = "The demo starts at 04:32 and pricing is explained at 12:05. " \
             "For the long version see 1:02:11."
    print(parse_timestamps(sample))
Output1 line
[272, 725, 3731]

That's the skeleton: swap VideoBackend implementations per provider, keep the timestamp plumbing and chaptering identical. The failure modes it must handle — missing timestamps, timestamps beyond duration, contradictory times — are Part 6's job.


Part 4: Tasks and recipes#

4.1 The task → approach table#

Task Recommended approach Why
Summarise a short clip (<5 min) Native video (Gemini) or dense frame sampling Whole clip fits comfortably; audio matters
Summarise / chapter a long video Map-reduce (3.9) or Gemini agentic mode Context can't hold it; aggregation beats stuffing
Q&A with timestamps Native video + MM:SS citations, or frames + burned-in timestamps + transcript Timestamps are the product; verify them (6.6)
Find every occurrence of an event across a library Index first (3.8) — Twelve Labs-class or your own segment index Retrieval, not prompting
Read on-screen text / slides / UI High media_resolution or high-detail frames + targeted clipping Text needs pixels; crop to the text region
"What was said?" Dedicated STT (09.4) + text LLM — not vision frames Audio is cheaper and far more accurate via STT
Detect specific actions/objects at scale Specialised models (Rekognition, Video Indexer, Twelve Labs) or dedicated detectors Fixed-vocabulary APIs beat VLM prompting for known classes
Screen-recording bug reports Frames at high FPS around the repro + transcript of narration UI text and timing both matter
Sports / broadcast highlights Audio-event anchors + scene boundaries, then two-pass dense sampling; dedicated OCR for score bugs Fast action, hard cuts and overlay text defeat naive uniform sampling; audio marks events better than pixels
Content moderation Dedicated moderation APIs + VLM spot-checks; never rely on one signal Recall matters more than elegance
Accessibility audio description Dense-enough frames + script → TTS narration (09.5) Needs scene-level descriptions, not summaries

4.2 Summarisation and chaptering#

The bread-and-butter recipe. For a single clip: native video (or sampled frames + transcript) with a prompt that demands structure. For a long video: the map-reduce pipeline (3.9) where each segment produces a summary with timestamps, then a reduce pass produces chapters.

Prompt pattern that works across providers (illustrative shape; wording is Module 04's domain):

text
You are given {N} frames sampled every {k} seconds from a {duration} video,
each with its timestamp burned in, plus the transcript below.

1. Summarise the whole video in <= {m} sentences.
2. Produce chapters: for each distinct topic, give [MM:SS] start and a title.
3. List the 3 most important moments with [MM:SS] and why they matter.
4. If audio and video disagree (e.g. narration says X but screen shows Y), say so.

Transcript:
{transcript}

Chapter quality depends on segment granularity: 3–5 minute segments give coarse chapters; for finer chapters run a second pass that asks "where does the topic change?" within each segment summary. Expect chapter timestamps to be approximate — they're derived from segment boundaries, not detected cuts. If precise chapter points matter, have the reduce step ask for them explicitly and then verify against the frames.

4.3 Q&A with timestamp citations#

This is the running example's core loop (3.10). The engineering points:

  • Ask for citations in the prompt, in a parseable format: [MM:SS] inline or a JSON field {"answer": ..., "cites": ["04:32", "11:07"]} via structured output (03.4).
  • Parse and validate them — the parse_timestamps function in 3.10 plus range checks (0 ≤ t ≤ duration). Drop or flag citations outside the video; they're hallucination markers.
  • Render them as deep links: t= parameters or your player's seek API. A timestamp that doesn't seek is worse than none.
  • Citation quality is an eval problem, owned by Module 10A and previewed by 07.5 citations. The video-specific wrinkle: a citation can be temporally wrong (right event, wrong second) — your eval needs timestamped ground truth (6.6).

4.4 Action and event detection#

"Detect every time X happens" splits three ways:

  • Known, countable events (goal scored, door opened, logo appears): dedicated detectors or specialised APIs (Rekognition labels, Video Indexer) beat VLM prompting — they're cheaper per hour and give timestamps natively. Use a VLM to verify ambiguous hits.
  • Semantic events ("when the speaker changes topic", "when the demo goes wrong"): map-reduce where each segment answers a yes/no + timestamp question, then merge adjacent hits. Overlap segments so boundary events aren't missed.
  • Open-ended "find moments like this": embed segment descriptions/thumbnails (09.9) and retrieve — the VLM only sees the top candidates.

Whatever the route, define "event" precisely in the prompt or schema — "a scene change" and "the presenter changes slides" are different detectors with different false-positive profiles.

Sports and broadcast footage are the stress test for every technique in this lesson. The failure modes stack up: fast action that 1 FPS misses entirely (6.2), hard camera cuts that make scene detection fire constantly, score bugs and ticker overlays that need OCR-grade resolution rather than VLM glance-and-describe, and audio cues — whistles, crowd swells, the commentary itself — that mark events more reliably than the pixels do. The recipe that works: transcribe the audio track and detect its event anchors first (commentary spikes, whistle-like onsets), use shot boundaries to segment plays, then run two-pass — a sparse pass finds candidate highlight windows and a dense pass (higher effective FPS, cropped to the play area rather than the whole frame including crowds and ads) describes them. Score-bug and stat-overlay text comes from a dedicated OCR pass on high-resolution frames, not from asking the VLM to read small overlay text. Expect the VLM to be weakest exactly where sports demands most — precise timing and counting — so put deterministic detectors and the transcript in charge of when and how many, and use the VLM for the what happened description layer.

4.5 Lecture and slide extraction#

Two sub-problems: getting the slide content and getting the narration.

  • Slides: detect slide-change boundaries (scene detection works well — slides are hard cuts), extract one clean frame per slide, then OCR or VLM-read each. For text-heavy decks, high media_resolution/detail matters; crop to the slide area if there's a talking-head inset. Deduplicate near-identical frames (perceptual hash — 09.9 covers it).
  • Narration: the audio track via STT gives you the transcript; align transcript segments to slide boundaries by timestamp to get "slide 12 was discussed at 14:02–16:40". That alignment is the product.

Failure mode to design for: slide content that isn't spoken (dense tables, code) — the transcript won't cover it, so the frame-reading pass must carry that weight. And the reverse: spoken content with no slide (tangents, Q&A) — the transcript carries it.

4.6 Meeting video notes#

Recorded meetings (Zoom/Meet/Teams exports) are videos with speech dominant. Pipeline: STT with diarization (09.4) → transcript cleanup → LLM summary/action-items (04.8 territory) → optional visual pass only for shared-screen segments (detect via scene analysis or the platform's active-speaker layout). Most of the value is in the transcript; the visual pass earns its tokens only when screen content matters (slides, demos, whiteboards). Cost note: an hour of meeting audio transcribes for a fraction of what an hour of video tokens costs — route audio to STT, reserve vision for the segments that need it.

4.7 Screen-recording bug reports#

User-submitted screen recordings ("it broke when I clicked export") are the highest-value-per-token video use case: short, UI-dense, timestamp-critical.

  • Sample at higher FPS (2–5 FPS equivalent) around the repro — UI state changes faster than 1 FPS catches.
  • Burn in timestamps (3.5) — the engineer needs "it glitched at 00:47".
  • Combine with the user's narration transcript; the repro moment is usually where narration and pixels disagree ("I clicked save" vs the screen showing a spinner).
  • Crop to the app window if the recording has desktop chrome — smaller frames, lower tokens, more legible UI text.

4.8 Content moderation#

Video moderation is a recall-critical, high-volume task — the wrong frame of a violation is a miss. Design:

  • First pass, cheap and wide: dedicated moderation APIs (cloud provider content-moderation endpoints, Rekognition/Video Indexer explicit-content features) scan every frame/audio segment at low cost.
  • Second pass, narrow: flagged segments go to a VLM with a precise policy prompt ("does this segment show X?") for adjudication.
  • Never single-signal: a VLM alone misses fast flashes; a frame-sampler alone misses audio-only violations. Layer them.
  • Human review queue for the uncertain middle — moderation errors are asymmetric (false negatives are worse than false positives for most policies, but both have costs; tune the threshold on labelled data, Module 10A).

This is awareness-level here; Module 12 owns the policy and safety engineering.

4.9 Accessibility: audio description#

Audio description (AD) narrates visual content for blind/low-vision viewers — a real product category, and a nice illustration of "video understanding as generation input". Pipeline: scene-detect → per-scene frame description ("a woman in a red coat crosses the street") → script editing (fit description into dialogue gaps, don't talk over speech) → TTS (09.5) → mux back into the video with ffmpeg. The VLM's job is dense scene description, not summary — prompt for what a sighted viewer would notice, in present tense, timed to scene boundaries. Quality bar is high (wrong descriptions are worse than none) and the domain has style guides (e.g. broadcaster AD conventions) worth encoding in the prompt.

"Find the moment where X happens" across a library is the flagship video-AI product — and it's fundamentally a retrieval problem, previewed properly in 09.9. The two routes:

  • Multimodal embeddings: Twelve Labs' Marengo-class models embed video into a searchable space natively (text/image/composed queries → moment hits); open models and Gemini multimodal embeddings offer DIY versions (09.9).
  • Text-first: transcript + segment summaries indexed in a vector store; query retrieves candidate segments, VLM verifies with frames. Cheaper to build on what you already have; weaker on purely-visual queries ("the red car").

For one-off search over a modest library, the text-first route on top of the 3.8 segment index is the pragmatic start.

Patterns that recur across the recipes (wording itself is Module 04's domain; these are video-specific shapes):

Goal Prompt skeleton
Timestamped summary "Summarise this video in N sentences. Give [MM:SS] timestamps for each major topic change."
Moment Q&A "Answer the question using only what is visible or audible in the video. Cite every claim with [MM:SS]. If the video doesn't show it, say 'not visible'."
Chaptering "Divide this video into chapters. For each: [MM:SS] start, title (<=8 words), one-sentence summary."
Event hunt "Does {event} occur in this segment? Answer YES/NO, the [MM:SS] it occurs, and a one-line description. If unsure, answer UNSURE."
Slide read "Transcribe all readable text on the slide shown at [MM:SS]. Preserve layout order; mark illegible text [illegible]."
Describe-for-AD "Describe what a sighted viewer sees in this 5-second clip for audio description: present tense, concrete visual details, no interpretation."
A/V conflict "The transcript says '{quote}' around {time}. Does the video show what is described? Answer MATCH / MISMATCH / UNCLEAR with [MM:SS] evidence."
Failure What it looks like Likely cause Mitigation
Missed fast action "Nothing happens at 03:12" but a goal was scored 1 FPS sampling too coarse Raise FPS on that segment; two-pass locate-then-zoom
Wrong timestamp Answer cites 05:00, event was at 05:20 Temporal grounding error Ask for evidence frames; verify on eval set
Invented event Confident description of something absent Hallucination on ambiguous frames "Not visible" permission; lower temp isn't the fix — better prompts + verification are
Transcript/pixel mismatch Summary describes narration, ignores on-screen demo Frames and audio processed separately Explicit A/V-conflict prompt; check both modalities
Illegible text "The slide says something about Q3" Resolution too low for text media_resolution/detail up; crop to region
Boundary misses Event at a segment seam described twice or never Map-reduce without overlap 10–30s overlap; merge adjacent hits
Cost blowout Bill 10× estimate Frames × high detail × long video Count tokens first (3.4); clip; lower FPS
Silent audio loss Model "hears" nothing Frames-only route (OpenAI, Anthropic) never receives the audio track; or a native pipeline processes it at ~1 Kbps mono, too coarse for quiet or overlapping speech Route speech to dedicated STT; don't rely on VLM audio
Expired file URI 404 on files/... URI 48h Files API expiry Re-upload on miss; store hash + upload time

Part 5: Cost and latency arithmetic#

5.1 The formulas#

Video cost is multiplication, not addition. Write it once, parameterise it, and every decision in this lesson becomes arithmetic:

text
native_video_tokens ≈ duration_s × tokens_per_second(resolution, provider)
frame_tokens      ≈ n_frames × tokens_per_frame(provider, detail/resolution)
total_input_cost  ≈ (video_tokens + text_tokens) × input_price_per_token

Where tokens_per_second is ~100 (Gemini low) to ~300 (Gemini high) natively, or n_frames × per-frame for your own sampling — and input_price_per_token comes from 03.7's price table (as of Nov 2026, gemini-3.8-flash input is $0.75/MTok, rising to $1.50/MTok on 2027-01-01 per that table — always re-check the pricing page, which also lists whether audio input is priced differently from image/video input on your model; the calculator below uses one blended input price for simplicity).

5.2 A worked example#

A 30-minute (1,800 s) product-demo video, three ways:

Approach Tokens (approx.) Cost at $0.75/MTok input
Gemini native, low res (~100 tok/s) ~180,000 ~$0.14
Gemini native, high res (~300 tok/s) ~540,000 ~$0.41
Your frames: 0.2 FPS uniform → 360 frames @ ~1,000 tok (Anthropic mid) ~360,000 + transcript ~$0.27 + STT cost
Your frames: scene-aware → ~120 frames @ ~1,000 tok ~120,000 + transcript ~$0.09 + STT cost
Map-reduce: 6×5-min segments @ low res each ~180,000 total + reduce ~$0.14 + reduce call

The pattern: the same video costs 2–5× depending on sampling choices, and scene-aware or two-pass sampling routinely beats naive dense sampling by 3×+. Prices are per-token and volatile — the calculator below takes them as parameters, per 03.7's convention.

5.3 The calculator#

python
# s5_3_video_cost.py
"""Video understanding cost calculator — prices as parameters (pure local)."""
from dataclasses import dataclass


@dataclass
class VideoCostParams:
    duration_s: float
    # Native video: provider's tokens/second at your chosen resolution.
    native_tokens_per_s: float = 100.0
    # Frame sampling: how many frames and what each costs.
    sample_fps: float = 0.2                 # effective frames per second
    tokens_per_frame: float = 1000.0
    # Text side: prompt + transcript + output.
    prompt_tokens: float = 2000.0
    transcript_tokens_per_min: float = 900.0  # rough English speech rate
    output_tokens: float = 1500.0
    input_price_per_mtok: float = 0.75      # e.g. gemini-3.8-flash, Nov 2026
    output_price_per_mtok: float = 3.75     # example; check the pricing page
    # Optional: agentic-mode discount on long videos (up to ~88% fewer tokens).
    agentic_saving: float = 0.0             # 0.0-0.88


def estimate(p: VideoCostParams) -> dict:
    native_tokens = p.duration_s * p.native_tokens_per_s * (1 - p.agentic_saving)
    frame_tokens = p.duration_s * p.sample_fps * p.tokens_per_frame
    transcript_tokens = (p.duration_s / 60) * p.transcript_tokens_per_min

    def cost(media_tokens: float) -> float:
        return ((media_tokens + p.prompt_tokens + transcript_tokens)
                * p.input_price_per_mtok / 1e6
                + p.output_tokens * p.output_price_per_mtok / 1e6)

    return {
        "native_video_usd": round(cost(native_tokens), 4),
        "frame_sampling_usd": round(cost(frame_tokens), 4),
        # round(), not int(): 7200*100*(1-0.8) is 143999.99... in floats,
        # and int() would truncate it to 143999 instead of 144000.
        "native_tokens": round(native_tokens),
        "frame_tokens": round(frame_tokens),
        "note": "Prices are parameters; swap in your provider's current rates "
                "(03.7 price table / provider pricing page).",
    }


if __name__ == "__main__":
    demo = VideoCostParams(duration_s=1800)                    # 30-minute video
    lecture = VideoCostParams(duration_s=3600, sample_fps=0.1) # 1-hour lecture, sparse
    long_agentic = VideoCostParams(duration_s=7200, native_tokens_per_s=100,
                                   agentic_saving=0.8)        # 2h video, agentic
    for name, p in [("30-min demo", demo), ("1h lecture", lecture), ("2h agentic", long_agentic)]:
        print(name, estimate(p))
Output · real — pure Python, prices are the illustrative defaults above3 lines
30-min demo {'native_video_usd': 0.1624, 'frame_sampling_usd': 0.2974, 'native_tokens': 180000, 'frame_tokens': 360000, 'note': "Prices are parameters; swap in your provider's current rates (03.7 price table / provider pricing page)."}
1h lecture {'native_video_usd': 0.3176, 'frame_sampling_usd': 0.3176, 'native_tokens': 360000, 'frame_tokens': 360000, 'note': "Prices are parameters; swap in your provider's current rates (03.7 price table / provider pricing page)."}
2h agentic {'native_video_usd': 0.1961, 'frame_sampling_usd': 1.1681, 'native_tokens': 144000, 'frame_tokens': 1440000, 'note': "Prices are parameters; swap in your provider's current rates (03.7 price table / provider pricing page)."}

Run it yourself with your provider's real prices — the numbers move, the structure doesn't.

5.4 Latency#

Video understanding is slow in ways text isn't:

  • Upload + processing: Files API video can sit in PROCESSING for minutes before the first token.
  • Prefill: thousands of frame/audio tokens must be ingested before the first output token — TTFT on a 30-min video is seconds-to-tens-of-seconds, not milliseconds.
  • Agentic mode: navigation adds thought tokens and tool round-trips — higher TTFT by design.
  • Your sampling: frame extraction is I/O + decode bound; a 2-hour 4K file takes real time even at 0.2 FPS effective sampling (you still decode or seek through it).

Design response: async job pattern everywhere (03.9 — submit, poll/webhook, notify), streaming answers where supported, progress indicators that reflect pipeline stages (upload → process → analyse → answer), and per-stage latency logging so you know whether the bottleneck is your ffmpeg, the upload, the prefill or the decode.

5.5 The levers, ranked#

Lever Rough saving (depends on your footage) Cost
Clip to the relevant range (start_offset/end_offset, ffmpeg -ss) 50–90% on targeted questions None — pure win when you know the range
Lower FPS / sparser sampling Linear in frame share Missed fast action (6.2)
Lower media_resolution/detail ~3× on Gemini (300→100 tok/s) Small-text legibility loss
Downscale frames before sending Fewer image tokens on patch-based providers Legibility floor exists
Trim dead air/static intros 10–30% on typical footage Needs a silence/static detector
Two-pass locate-then-zoom 60–80% vs dense sampling Extra round-trip latency
Agentic mode (Gemini) Up to ~88% on long-form Less control; higher TTFT
Context caching for repeat questions Video tokens paid once per TTL Cache storage fee; 1h default TTL
Batch API for offline jobs ~50% on supported providers Hours-not-seconds latency (03.9)
Map-reduce + retrieve instead of whole-video Orders of magnitude on archives Index build cost upfront

Part 6: Quality and limits#

Deep-dive

6.1 What video models are genuinely bad at#

Being honest about limits is the difference between a demo and a product. As of November 2026, across native and frame-sampled approaches:

  • Temporal reasoning is shallow. Models describe what frames show far better than how things unfold over time. "Did the ball enter the goal before or after the whistle?" is a coin flip at 1 FPS. Precise ordering, duration estimation and speed judgement are unreliable.
  • Fast action is invisible at low sampling. At 1 FPS, anything shorter than a second can be missed entirely — a hand gesture, a quick UI state change, a ball hit. Google's own docs warn "fast action sequences might lose detail due to the 1 FPS sampling rate".
  • Counting over time fails. "How many times did she say 'um'?" or "how many goals?" — models lose count across long inputs. Count in post-processing (transcript regex, detector counts), not in the VLM.
  • Text legibility has a floor. Small UI text, dense slides, lower-thirds and timestamps-on-video need high resolution and often still fail. Crop and zoom (two-pass) before asking.
  • Audio-visual alignment is approximate. The model knows roughly when speech and visuals co-occur, not sample-accurately. Don't ask "what was the speaker pointing at at 04:32.5".
  • Long-video recall degrades. Even within the context window, recall for specific moments decays with video length — the "needle in a haystack" problem applies to video. Agentic mode and map-reduce exist precisely because of this.
  • Hallucinated events are confident. A model will describe plausible-but-absent events with the same confidence as real ones. There is no uncertainty channel unless you build one (ask for confidence, verify with a second pass, or check citations).

6.2 Temporal reasoning and fast action#

The mitigation ladder, cheapest first:

  1. Raise effective FPS on the relevant window — you don't need 10 FPS everywhere; you need it where action is. Two-pass: sparse pass finds "something happens around 04:00", dense pass examines 03:30–04:30 at 5 FPS.
  2. Give the model adjacent frames explicitly — "frames at 04:00, 04:01, 04:02, 04:03" reads very differently from "1 frame per second throughout". Dense local sampling around the question beats uniform global sampling.
  3. Use the transcript as the clock — speech anchors time better than pixels do. "When she says 'and then it crashes'" is a findable moment; align frames to it.
  4. Accept the limit for genuinely temporal questions — "is the car accelerating?" may need actual video understanding a frame-sampler can't provide; say so rather than ship a wrong answer.

6.3 Counting, text and alignment#

  • Counting: never ask the VLM to count occurrences across a long input. Count deterministically — regex on transcript, detector outputs, OCR hits — and use the VLM only to classify candidates.
  • Text: if the text matters, assume you need high/ultra_high media resolution or high-detail frames and a crop. Test on your actual footage — a 1080p screen recording and a 720p phone video have different legibility floors.
  • Alignment: treat audio and video timestamps as independently approximate. When you fuse them (transcript + frames), align by window (±5–15s), not by exact second, unless you've verified precision on your data.

6.4 Hallucinated events and verification#

The production pattern for any answer that drives an action (moderation, alerting, clipping):

  • Ask for evidence: require the model to cite timestamps and quote what it saw/heard. An answer with no evidence is a flag, not a pass.
  • Second-pass verification: for high-stakes claims, re-ask on just the cited window at higher resolution — "look again at 04:28–04:36, is X actually there?"
  • Cross-check modalities: if the claim is visual, the transcript shouldn't be the only support; if it's spoken, a frame citation is suspicious.
  • Measure, don't assume: hallucination rate on video tasks is model- and prompt-dependent; your eval set (6.6) is the only truth.

6.5 Needle tests and long-video recall#

To know whether your pipeline can find a moment in a long video, plant needles: insert a distinctive, brief event ("at 47:12 the presenter holds up a red mug") into test footage, then measure whether the system retrieves it. Vary needle salience (obvious visual vs subtle audio mention) and position (beginning/middle/end — recall often degrades toward the middle and end of long inputs, the "lost in the middle" effect from 02.7 applied to time). Track recall@k over needles as your regression metric; Module 10A owns the formal eval harness.

6.6 Evaluating with timestamped ground truth#

Video answers need temporal evaluation, not just text eval. The primitive: interval IoU — treat each claimed event as a time interval [start, end] and each ground-truth event likewise; IoU = overlap ÷ union. Here's the real, runnable implementation:

python
# s6_6_interval_iou.py
"""Temporal IoU for timestamped event detection — pure Python, real output."""
from __future__ import annotations


def iou(a: tuple[float, float], b: tuple[float, float]) -> float:
    """Intersection-over-union of two time intervals [start, end]."""
    start, end = max(a[0], b[0]), min(a[1], b[1])
    inter = max(0.0, end - start)
    union = (a[1] - a[0]) + (b[1] - b[0]) - inter
    return inter / union if union > 0 else 0.0


def match_events(predicted: list[tuple[float, float]],
                 truth: list[tuple[float, float]],
                 threshold: float = 0.5) -> dict:
    """Greedy one-to-one matching at IoU>=threshold.

    Returns precision/recall/F1 plus the matched pairs. Greedy is fine for
    eval-scale sets; for production metrics use Hungarian matching."""
    pairs = []
    used_p, used_t = set(), set()
    # Best matches first
    candidates = sorted(
        ((iou(p, t), i, j) for i, p in enumerate(predicted)
         for j, t in enumerate(truth)),
        reverse=True)
    for score, i, j in candidates:
        if score >= threshold and i not in used_p and j not in used_t:
            pairs.append((i, j, score))
            used_p.add(i)
            used_t.add(j)
    tp = len(pairs)
    fp = len(predicted) - tp
    fn = len(truth) - tp
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
    return {"tp": tp, "fp": fp, "fn": fn,
            "precision": round(precision, 3), "recall": round(recall, 3),
            "f1": round(f1, 3), "pairs": pairs}


if __name__ == "__main__":
    # A 10-minute clip: truth has events at [120,150] and [400,430];
    # predictions are close but imperfect.
    truth = [(120.0, 150.0), (400.0, 430.0)]
    predicted = [(118.0, 148.0), (390.0, 425.0), (500.0, 520.0)]  # third is a false positive
    print("iou demo:", round(iou((118, 148), (120, 150)), 3))
    print(match_events(predicted, truth))
Output · real2 lines
iou demo: 0.875
{'tp': 2, 'fp': 1, 'fn': 0, 'precision': 0.667, 'recall': 1.0, 'f1': 0.8, 'pairs': [(0, 0, 0.875), (1, 1, 0.625)]}

Use this for: event-detection evals, chapter boundary accuracy (treat each chapter start as a point interval), and citation correctness (does the cited [MM:SS] fall inside the ground-truth event window ± tolerance?). Build the labelled set from footage you have rights to, with consent (Part 8) — and include the failure modes from the failure gallery, not just clean successes.


Part 7: Video generation (awareness)#

Reference

This lesson is about understanding video, but the two collide in products (generate a clip, then analyse it; analyse real footage, then generate a fix). One short section so you recognise the landscape as of November 2026 — this is awareness, not a tutorial, and it is the most volatile part of the lesson.

7.1 What exists as of November 2026#

Route What it is Status
Gemini Omni Flash (gemini-omni-1.2-flash) Google's current GA video generation and editing model via the Interactions API: text/image/video input (video up to 15s for editing, 10s lookback for extension), output 3–15s at 360p/720p/1080p/4K, 24fps, native audio GA on the paid tier of the Gemini API (latest update November 2026); ~$0.10/sec effective at 720p per the pricing page. Previous stable gemini-omni-1.1-flash (video input ≤10s, output 3–10s) still works but routes to 1.2 on December 3, 2026
Veo 3.1 The dedicated video model family (8s clips, native audio, extension up to ~148s) Veo 3.1 Preview IDs in the Gemini API were shut down October 22, 2026; GA access is via the Gemini Enterprise Agent Platform
OpenAI Sora 2 / sora-2-pro via POST /v1/videos Shut down September 24, 2026 — no one-to-one replacement; OpenAI's guide is retained for historical reference
OpenRouter /api/v1/videos Async video-generation endpoint aggregating many models: google/veo-3.1*, runway/gen-4.5, bytedance/seedance-*, kwaivgi/kling-*, alibaba/wan-*, x-ai/grok-imagine-video*, minimax/*, heygen/*, black-forest-labs/flux-video-* Live; GET /api/v1/videos/models lists each model's durations, resolutions, aspect ratios and pricing_skus
Runway Dev (dev.runway.com) Multi-model media API (own Gen-4.5 plus Kling, Seedance, Wan, Gemini Omni Flash and others) billed in credits (1 credit = $0.01); e.g. Gen-4.5 ~$0.12/sec at 720p Live commercial API

7.2 The async job pattern (same everywhere)#

Video generation is never a synchronous call — it's a job:

  1. Submit: POST prompt + params (duration, resolution, aspect ratio, references) → job ID + polling URL.
  2. Poll or webhook: GET status until completed/failed, or register a callback (OpenRouter supports a callback_url; OpenAI's old API had webhooks).
  3. Download: fetch the MP4 from a content endpoint or URL. Files are typically retained briefly (Veo docs: generated videos stored ~2 days server-side — download immediately).

On Gemini's Interactions API the same shape appears as background=True + polling interactions.get — identical to 2.4's agentic pattern. On OpenRouter it's POST /api/v1/videos → poll the returned URL. Design your storage and webhook handling once; the providers differ only in field names.

7.3 Costs, policies, provenance#

  • Cost is per second of output, varying by model/resolution/audio — e.g. Runway Dev lists per-second credit rates per setting; OpenRouter exposes pricing_skus per model; Gemini Omni Flash bills per output token (~5,792 tokens/sec of 720p). An 8-second 1080p clip can cost dollars, not cents — budget retries and variations accordingly.
  • Duration caps are short: 3–15s output on Omni Flash 1.2 (3–10s on 1.1 and for first/last-frame interpolation and per-turn extension), 4/6/8s (Veo), ~20s max (historical Sora). Longer videos mean chaining generations or extension APIs.
  • Policies: content filters block prompts and outputs (Veo doesn't charge for blocked generations); person-generation controls exist (personGeneration: allow_all vs allow_adult, region-restricted); real-person likeness is restricted on most platforms.
  • Provenance: generated video carries machine-readable watermarks — Google's SynthID for Veo/Omni-class outputs, plus C2PA (Coalition for Content Provenance and Authenticity)-style content credentials on some pipelines. If your product generates video, disclose it and preserve the provenance metadata; if you consume video, a "is this AI-generated?" check may become a requirement — the verification platforms exist (e.g. Google's SynthID verification).

That's the awareness level this lesson needs. If video generation becomes your product, it earns its own deep-dive later — the concepts here (async jobs, per-second pricing, provenance) transfer directly.


Deep-dive

Video is the most privacy-sensitive modality this module covers: it captures faces (biometric data in many jurisdictions), bodies, surroundings, bystanders who never consented, and audio of real conversations. The engineering duties:

  • Recording consent laws vary by jurisdiction — one-party vs two-party consent for audio, workplace recording rules, bystander rights. This is awareness, not legal advice; your product's jurisdiction matrix is a legal question to answer per market.
  • Notice at capture: if your product records (support calls with video, field-service footage, meeting recordings), the notice/consent UX is part of the feature — a banner, a verbal prompt, a written policy. "The user clicked upload" is not consent for the people in the video.
  • Minors: extra caution; many platforms and laws treat children's data specially. Don't build features that identify or track children without specific legal basis.

8.2 What you're sending to providers#

  • Provider terms apply to video like any media: retention, training-use and region rules from 02.9, Part 9. Gemini's free tier explicitly allows human review of uploads — never send sensitive footage through a free tier.
  • Gemini Files API: auto-deletes after 48 hours — good for retention, but means your "we store it for you" promise must live in your storage, not Google's.
  • Context caches and agentic state: cached video and agentic step_list state persist for their TTLs — factor them into your retention story.
  • Third-party video services (Twelve Labs, Rekognition, Video Indexer) have their own retention and region terms; index pipelines that copy frames/thumbnails into your store inherit your retention obligations for those derivatives.

8.3 Data minimisation techniques#

  • Blur or mask faces before upload when identity isn't needed (Pillow/OpenCV pipelines; some cloud APIs offer redaction).
  • Crop to the relevant region — a bug-report crop to the app window drops the user's desktop, notifications and other tabs.
  • Strip metadata (EXIF/GPS) — video files carry location metadata; 03.6, Part 6 covers the stripping toolkit.
  • Audio redaction for PII spoken in recordings (bleep/regenerate via STT→TTS where lawful).
  • Retention schedule: define how long you keep video, frames, transcripts and embeddings; delete on request; remember embeddings can leak information about deleted media.

8.4 High-risk uses — awareness#

  • Workplace surveillance: analysing employee video at scale is legally and ethically fraught in many places; treat as a product/legal decision, not just an engineering one.
  • Face recognition / identification: several services offer it (Rekognition face search, Twelve Labs entity search beta); biometric regulation (e.g. US state laws such as Illinois's BIPA — the Biometric Information Privacy Act) may apply. Avoid building identification features casually.
  • Deepfake-adjacent: if your product generates video (Part 7), the provenance/watermark and impersonation duties from 09.3 apply a fortiori — a fake video is worse than a fake image.
  • Safety routing: prompt injection via on-screen text or spoken audio is a real attack surface — a video can contain instructions ("ignore previous directions" on a slide). Treat all video-derived text as untrusted input (Module 12, 02.10).

Common misconceptions#

Misconception Reality
"The model watches the video like a person does." It sees sampled frames (1 FPS by default on Gemini) plus a compressed audio track — anything faster than the sampling interval can be invisible (1.1, 6.2).
"Native video input is always better than sending frames." Only Gemini has it; it costs ~100–300 tokens/sec and locks you to one provider. Frame sampling is portable, controllable and often cheaper (1.2, 3.1).
"An hour of video costs about the same as an hour of audio." Video is roughly 3–12× audio per second: ~100–300 tokens/sec vs ~25–32 for audio on Gemini (1.3).
"Upload once, reference the file URI forever." Gemini Files API entries auto-delete after 48 hours; re-upload or keep your own copy (2.1).
"Lower FPS always saves money with no downside." It saves frame tokens linearly but misses fast action — match sampling density to content, not just budget (3.3, 6.2).
"Timestamps in answers are reliable citations." They're model-generated claims about time; verify against ground truth with interval IoU before trusting them in production (6.6).
"Agentic mode is strictly better for long videos." It's up to ~88% cheaper on long-form but adds TTFT and can cost more on short clips or broad queries (2.4).
"Context caching makes repeat questions free." It pays the video tokens once per TTL (default 1h) plus a storage fee — and isn't supported on Gemini 4 Argon+ (2.7).
"OpenAI/Anthropic can take video files now." As of November 2026 neither accepts native video; frames-as-images is the only route (2.8).
"Veo/Sora APIs are stable choices for video generation." Both shifted recently: Sora's Videos API shut down September 24, 2026 and Veo 3.1 Preview IDs shut down October 22, 2026 — check current IDs before building (Part 7).
"If the video shows it, the model will describe it accurately." Hallucinated events are confident; require evidence citations and verify high-stakes claims (6.4).
"Sending user video to an API is fine if the user clicked upload." Bystanders, faces and audio in the video have their own consent/biometric issues; notice and retention duties apply to everyone in frame (Part 8).

Key takeaways#

  • Video = frames + audio + timestamps. Every approach is a choice of representation: native video pipelines sample server-side; you can sample frames yourself on any vision model.
  • Gemini is the only major provider with native video input (as of Nov 2026): Files API/inline/Cloud Storage/YouTube routes, video_metadata clipping and FPS on generate_content, processing modes on Interactions, MM:SS timestamps, static (~100–300 tok/s) vs agentic (up to ~88% cheaper on long-form) processing.
  • OpenAI and Anthropic are frames-only; OpenRouter passes video through per-provider; specialised services (Twelve Labs, Rekognition, Video Indexer) cover search/annotation; Google Video Intelligence API is reported deprecated (shutdown 2027) → Gemini.
  • The frame-sampling pipeline is the portable skill: extract with ffmpeg/PyAV/OpenCV, sample uniformly/keyframe/scene-change, label with timestamps, budget frames against image-token costs, fuse with a transcript.
  • Map-reduce for the middle case, indexing for archives: segment → describe → aggregate scales to hour-plus videos; embedding the segments turns it into searchable video.
  • Cost is arithmetic: tokens/sec × duration × price; clip, lower FPS/resolution, two-pass, cache and batch are the levers — measure with count_tokens/usage, never guess.
  • Quality has hard edges: temporal reasoning, fast action, counting and long-video recall are weak; timestamps need verification; "not visible" permissions reduce hallucination.
  • Video generation is awareness-level here: async job pattern everywhere; Gemini Omni Flash is Google's GA path; Sora's API is gone; provenance/watermarking matters.
  • Privacy is part of the feature: consent, bystanders, biometric data, retention and provider terms apply to every frame you send.

Terms introduced in this lesson#

Term One-line definition
Native video input Passing a video file/URL to a model that samples frames and processes audio internally (Gemini)
Frame sampling Extracting still frames yourself and sending them as image inputs
video_metadata Gemini generate_content per-part options: start_offset, end_offset, fps
processing (Interactions) Gemini Interactions per-video config: type static/agentic plus clipping and FPS
Static processing Gemini's default video mode: fixed 1 FPS frame extraction into context
Agentic processing Gemini's opt-in mode where the model navigates the timeline and loads content on demand
media_resolution Gemini setting for max tokens per image/video frame/PDF page
Scene-change detection Finding shot boundaries via frame-difference signals (PySceneDetect or DIY)
Keyframe sampling Extracting only the encoder's I-frames as the sample set
Map-reduce (video) Segment a long video, describe each segment, aggregate into a whole-video answer
Timestamp grounding The model's ability to map events to correct MM:SS positions — often weak
Interval IoU Temporal overlap metric for evaluating timestamped predictions against ground truth
Needle test Planting a known brief event in footage to measure retrieval recall
Two-pass locate-then-zoom Cheap wide pass to find relevant ranges, then dense inspection of just those
Video Q&A tool Product pattern: upload → chapters → questions answered with timestamp citations
SynthID Google's watermark/provenance system embedded in generated video
Audio description (AD) Narrated visual description for accessibility, generated from video understanding
Variable frame rate (VFR) Footage whose real frame timestamps drift from the container's nominal rate; breaks naive "every N seconds" sampling and frame-index scene detection

All terms are also collected in the glossary.


Exercises#

  1. Timestamp plumbing (3.10): extend parse_timestamps to also return the text span each timestamp was found in, and write a test asserting [272, 725, 3731] for the sample answer plus correct spans.
  2. Scene detection (3.3): modify detect_scenes to use edge-difference (gradient magnitude) instead of histograms, and construct synthetic frames where two scenes share a histogram but differ in edges — does your detector still cut?
  3. Map-reduce (3.9): add hierarchical reduce — group SegmentSummary objects in tens, summarise each group, then summarise the group summaries. Prove it runs on the scripted fake for a 10-hour duration_s.
  4. Frame budget (3.4/5.3): compute frames_affordable for a 45-minute video on Anthropic (~1,300 tok/frame) with a 150k-token video budget, then choose a uniform interval and a scene-aware estimate; compare total cost in s5_3_video_cost.py.
  5. Interval IoU (6.6): add point_iou for chapter-boundary evaluation (treat boundaries as zero-width intervals with a tolerance window) and evaluate three predicted chapter lists.
  6. Keyless pipeline (3.9/3.10): wire fake_describe to emit per-segment JSON {"summary": ..., "events": [{"t": "MM:SS", "what": ...}]} and extend chapters_from_summaries to use event times when present.
  7. Provider check (2.8): write a video_capable(model_entry) function that inspects an OpenRouter /models entry's architecture.input_modalities for "video", and test it against three fixture entries.
  8. Cost levers (5.5): take a real video length you know (e.g. a 20-min talk), compute cost under native-low, native-high, uniform-0.2FPS-frames, and agentic-with-80%-saving; rank the levers for your use case.
  9. Prompt iteration (4.11): take the "Moment Q&A" skeleton and add three variants testing "not visible" permission, evidence requirements, and structured-output citations; predict which fails least on ambiguous footage.
  10. Privacy audit (8.3): list every place a frame, transcript, embedding or cache entry derived from a user's video could persist in your own system, and write the deletion path for each.
Hints and worked answers
  1. Use m.span() from re.finditer and return (seconds, text_span) pairs; for the sample, the spans are "04:32", "12:05" and "1:02:11". Assert both the seconds list and that sample[start:end] equals the matched text.
  2. Compute np.gradient along both axes, take the mean magnitude per frame, and cut on the jump in that value. Build two frames with the same pixel values in a different arrangement (a vertical-stripe pattern and its shuffled copy): histograms are identical, edge energy is not.
  3. Group with summaries[i:i+10], call reduce_summaries on each group, wrap each group result in a new SegmentSummary (first group start, last group end), and repeat until one result remains. A 10-hour video at 285 s steps is about 127 segments, so the grouping loop runs three times (127 summaries, then 13 group summaries, then 2, then the final one).
  4. 45 min = 2,700 s. 150,000 ÷ 1,300 ≈ 115 frames, so the interval is 2,700 ÷ 115 ≈ 23.5 s; round up to 25 s (108 frames, about 140,000 tokens, sample_fps=0.04). A scene-aware pass that finds roughly 60 distinct shots needs about 78,000 tokens.
  5. A boundary is a point (t, t); widen each to (t - tol, t + tol) before calling iou, or simply count a prediction as correct when abs(pred - truth) <= tol. Compare the three lists by precision and recall at a 5 s and a 15 s tolerance.
  6. Have fake_describe return json.dumps({...}), parse it with json.loads inside chapters_from_summaries, and fall back to the first sentence of summary when events is empty.
  7. return "video" in entry.get("architecture", {}).get("input_modalities", []). Fixtures: one with ["text", "image"], one with ["text", "image", "video"], and one with no architecture key (expect False, no exception).
  8. 20 min = 1,200 s: native low about 120,000 tokens, native high about 360,000, uniform 0.2 FPS at 1,000 tokens/frame is 240 frames = 240,000, agentic at 80% saving on native low is about 24,000. Run them through estimate() and rank by cost, then by what each gives up (fast action, text legibility, TTFT).
  9. There is no single right answer: write the three variants, state your prediction first, then run them on 5-10 clips where the answer is not in the video. The variant with the "not visible" permission should produce the fewest invented timestamps, which you can count with parse_timestamps plus a range check.
  10. A checklist to start from: the uploaded original, extracted frames and thumbnails, audio files, transcripts, segment summaries, embeddings and vector-store rows, caches (provider context caches, your own response caches), logs and traces that contain prompts or answers, evaluation sets, and backups. For each, write who deletes it, when, and how you prove it is gone.

Check yourself#

  1. What three things make up the representation a model gets from a video?
  2. Which providers have native video input as of November 2026, and what are the others' options?
  3. What are Gemini's four ways to supply a video, and which is recommended for large files?
  4. What does video_metadata control on generate_content, and what are its valid ranges?
  5. What's the difference between static and agentic processing, and when does each win?
  6. Why might an agentic-mode request cost more than static on a short clip?
  7. How many tokens does one hour of video cost on Gemini at low vs high media resolution?
  8. Name three sampling strategies and when each beats uniform sampling.
  9. Why is "count occurrences in the video" a bad VLM task, and what do you do instead?
  10. What is interval IoU used for in video evaluation?
  11. What happened to OpenAI's Sora API and Veo 3.1 Preview, and what's the current Google path?
  12. Give two reasons a timestamped answer might be wrong even when the answer text is right.
  13. What privacy duties does video create beyond those of text or images?
  14. When would you choose indexing/map-reduce over sending the whole video?

Further resources#


← 09.7 — Realtime Voice Agents | Module 09 overview | 09.9 — Multimodal Embeddings and Retrieval →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close