# Video Encode Environment — CLAUDE.md Project-level context, architecture notes, development plans, and conventions for AI-assisted work. Update this file whenever significant context changes. --- ## Project Overview **What it is:** An RL (reinforcement learning) environment where an agent learns to choose optimal libx264 encoding parameters (`crf`, `preset`) for short video segments, balancing quality (VMAF/SSIM), file size (bitrate), and encoding speed. **OpenEnv framework:** Built on `openenv-core`, which provides the FastAPI HTTP/WebSocket server scaffolding, `Environment` base class, `Action`/`Observation` types, and the `EnvClient` + Docker deployment helpers. The project runs as a Docker container or Hugging Face Space. **Deployed at:** `https://keshav142-video-encode.hf.space` (default; override with `VIDEO_ENCODE_DEFAULT_HF_URL` or `VIDEO_ENCODE_HF_URL`). --- ## Repository Layout ``` video_encode_env/ ├── models.py # VideoEncodeAction, VideoEncodeObservation (Pydantic) ├── segment_utils.py # FFmpeg helpers: probe, extract, encode, VMAF, SSIM, bitrate ├── video_analysis.py # Whole-video & per-segment analysis (EY/h/LY complexity) ├── video_paths.py # Video file discovery (directory scan or list file) ├── data_collection.py # Offline grid-sweep dataset builder (CRF × preset × resolution) ├── inference.py # LLM agent inference loop (OpenAI-compat SDK → HF router) ├── __init__.py # Package re-exports: VideoEncodeAction, VideoEncodeEnv ├── server/ │ ├── app.py # FastAPI app (openenv create_app + video upload router) │ ├── video_encode_environment.py # Core Environment class: reset(), step(), _observation() │ ├── reward.py # compute_segment_reward() — pure function, no side effects │ ├── video_upload.py # POST /api/videos/upload, DELETE /api/videos/{filename} │ └── requirements.txt / pyproject.toml ├── videos/ # Default video directory (VIDEO_ENCODE_VIDEOS_DIR) ├── Dockerfile ├── openenv.yaml # OpenEnv Space config └── pyproject.toml # Package: openenv-video_encode, entry points: server, inference ``` --- ## Data Flow (one `step()`) ``` Agent sends VideoEncodeAction(crf, preset, video_index) │ ▼ VideoEncodeEnvironment.step() ├─ ffprobe_duration_sec(ref_video) [segment_utils.py] ├─ tempfile.TemporaryDirectory │ ├─ extract_segment(ref_video → ref_clip) [CRF-18 ultrafast reference extract] │ ├─ ffprobe_video_size(ref_clip) → ew, eh │ ├─ analyze_segment_clip(ref_clip) → seg_analysis ← RECENTLY ADDED │ ├─ encode_segment(ref_clip → enc_path, crf=action.crf, preset=action.preset) │ ├─ ffprobe_bitrate_kbps(enc_path) → bitrate │ ├─ vmaf_score(enc_path, ref_clip) → vmaf │ └─ ssim_score(enc_path, ref_clip) → ssim (only if vmaf is None) │ ├─ compute_segment_reward(vmaf, ssim, enc_time, bitrate, …) [server/reward.py] └─ _observation(…, segment_analysis=seg_analysis, …) → VideoEncodeObservation ``` **Segment advance logic:** Each timeline segment gets K encode attempts (`steps_per_segment`, default 10). After K steps, `_summarize_completed_segment()` builds `prev_segment_predictions` (means of all K steps), the timeline cursor advances by `segment_duration_sec`, and the sub-step counter resets. --- ## Action Schema ```python VideoEncodeAction: crf: int # 0–51; lower = higher quality + larger file. Typical range 18–28. preset: str # libx264 speed: ultrafast|superfast|veryfast|faster|fast|medium|slow|slower|veryslow video_index: int | None # 0..num_videos-1; None = use episode default from reset() ``` --- ## Observation Schema ```python VideoEncodeObservation: # Episode state echoed_message: str # "ok" on success; error text otherwise num_videos: int current_video_index: int reset_index: int # increments each reset() segment_index: int # timeline position (advances after K encodes) encode_step_index: int # 0..steps_per_segment-1 within current segment steps_per_segment: int # K # History prev_segment_predictions: dict | None # means over K steps of last completed segment # keys: vmaf_score, ssim_score, bitrate_kbps, encoding_time_sec, crf_avg, # presets_used, reward_avg, steps_per_segment, steps_averaged # Content analysis (static per video, cached at upload) whole_video_analysis: dict # duration_sec, width, height, fps, bitrate_kbps, # file_size_bytes, luma_spatial_texture_complexity_EY, # temporal_complexity_h, mean_luma_brightness_LY # Per-segment analysis on extracted ref_clip (RECENTLY ADDED) segment_analysis: dict # width, height, duration_sec, fps, bitrate_kbps, # file_size_bytes, luma_spatial_texture_complexity_EY, # temporal_complexity_h, mean_luma_brightness_LY # (empty dict before extraction / on pre-extraction error) # Current step metrics vmaf_score: float | None ssim_score: float | None # only when vmaf is None bitrate_kbps: float | None encoding_time_sec: float | None done: bool reward: float ``` --- ## Reward Function **Formula:** `R = λ_Q·Q̄ − λ_T·T̄ − λ_S·S̄ − λ_C·C̄` | Term | Variable | Formula | Env var | Default | |---|---|---|---|---| | Quality | Q̄ | `vmaf / vmaf_max` (or ssim raw) | `VIDEO_ENCODE_REWARD_VMAF_MAX` | 100 | | Encode time | T̄ | `min(time / time_max, 1)` | `VIDEO_ENCODE_REWARD_TIME_MAX_SEC` | `3 × seg_len` | | Bitrate | S̄ | `min(bitrate / bitrate_max, 1)` | `VIDEO_ENCODE_REWARD_BITRATE_MAX_KBPS` | 20000 | | CRF stability | C̄ | ramp when `|crf − prev_crf_avg|/prev_crf_avg > threshold` | — | 0 (disabled) | **Weights:** `λ_Q=1.0`, `λ_T=0.5`, `λ_S=0.3`, `λ_C=0.0` (all env vars: `VIDEO_ENCODE_REWARD_LAMBDA_*`) **Key file:** `server/reward.py` — pure function, no I/O, easy to unit-test. --- ## Environment Variables (complete reference) ### Video source | Variable | Default | Notes | |---|---|---| | `VIDEO_ENCODE_VIDEOS_DIR` | `videos` | Directory to scan for .mp4/.mkv/.mov/.webm | | `VIDEO_ENCODE_VIDEO_LIST_FILE` | (unset) | If set, overrides directory scan | | `VIDEO_ENCODE_UPLOAD_MAX_BYTES` | 2 GiB | Max upload size | | `VIDEO_ENCODE_UPLOAD_ANALYSIS_TIMEOUT_SEC` | 600 | ffmpeg budget for upload analysis | ### Episode parameters | Variable | Default | Notes | |---|---|---| | `VIDEO_ENCODE_SEGMENT_SEC` | 3.0 | Reference clip length per step | | `VIDEO_ENCODE_STEPS_PER_SEGMENT` | 10 | K encodes before timeline advances | | `VIDEO_ENCODE_FFMPEG_TIMEOUT_SEC` | 600 | Global subprocess timeout | ### Reward weights & normalization | Variable | Default | |---|---| | `VIDEO_ENCODE_REWARD_LAMBDA_Q` | 1.0 | | `VIDEO_ENCODE_REWARD_LAMBDA_T` | 0.5 | | `VIDEO_ENCODE_REWARD_LAMBDA_S` | 0.3 | | `VIDEO_ENCODE_REWARD_LAMBDA_C` | 0.1 | | `VIDEO_ENCODE_REWARD_VMAF_MAX` | 100 | | `VIDEO_ENCODE_REWARD_TIME_MAX_SEC` | (unset) | Optional override; default is `3 × segment_duration_sec` | | `VIDEO_ENCODE_REWARD_BITRATE_MAX_KBPS` | 20000 | ### Inference | Variable | Default | Notes | |---|---|---| | `HF_TOKEN` / `OPENAI_API_KEY` | — | HF user token (same value, two names) | | `API_BASE_URL` | `https://router.huggingface.co/v1` | OpenAI-compat endpoint | | `MODEL_NAME` | `Qwen/Qwen2.5-72B-Instruct` | Exact HF model id | | `MAX_STEPS` | 8 | Steps per episode in inference loop | | `INFERENCE_TEMPERATURE` | 0.3 | | | `MAX_TOKENS` | 4024 | | | `VIDEO_ENCODE_DEFAULT_HF_URL` | `https://keshav142-video-encode.hf.space` | Default Space URL | --- ## Development Commands ```bash # Install deps uv sync # Run server locally (port 8000) uv run server # or uvicorn server.app:app --reload --host 0.0.0.0 --port 8000 # Run inference against local server uv run inference --local # Run inference against HF Space export HF_TOKEN=hf_... uv run inference # Collect offline dataset (CRF × preset × resolution grid) uv run python -m video_encode.data_collection --videos-dir videos/ --data-root data/ # Build Docker image docker build -t video_encode-env:latest -f Dockerfile . # Deploy to HF Spaces openenv push ``` --- ## Key Patterns & Conventions ### Adding a new per-segment feature 1. Add a `compute_: bool = False` kwarg to `analyze_segment_clip()` in `video_analysis.py` 2. Add the computation inside an `if compute_:` block with try/except for graceful failure 3. Set the new kwarg to `True` in the `analyze_segment_clip(ref_clip, …)` call in `server/video_encode_environment.py` 4. Document the new key(s) in the `VideoEncodeObservation.segment_analysis` field description in `models.py` ### Adding a new reward term 1. Add a `normalized_()` function in `server/reward.py` 2. Add the term to `compute_segment_reward()` signature and formula 3. Add a `lambda_` key in `_reward_config_from_env()` in `video_encode_environment.py` 4. Add the `VIDEO_ENCODE_REWARD_LAMBDA_` env var with a sensible default ### Adding a new observation field 1. Add to `VideoEncodeObservation` in `models.py` with `default_factory=dict` or `default=None` 2. Add as a parameter to `_observation()` in `video_encode_environment.py` (keyword-only, with default) 3. Pass it through to `VideoEncodeObservation(...)` in `_observation()` body 4. Populate it in `step()` and/or `reset()` as appropriate ### Import dual-path pattern All server-side modules use a try/except import pattern to work both as a package (`from ..models import …`) and when run directly (`from models import …`). Always maintain both. --- ## Completed Work ### ✅ Wire `lambda_c` — CRF instability penalty **Date:** 2026-04-07 - `server/video_encode_environment.py`: Added `lambda_c` to `_reward_config_from_env()` reading `VIDEO_ENCODE_REWARD_LAMBDA_C` (default `0.1`). In `step()`, reads `prev_crf_avg` from `self._prev_segment_summary` and passes `crf=action.crf`, `prev_crf_avg`, `lambda_c` to `compute_segment_reward()`. The penalty was fully wired in `server/reward.py` already. ### ✅ Fix `time_max_sec` calibration (T̄ near-zero gradient) **Date:** 2026-04-07 - `server/video_encode_environment.py`: Removed `time_max_sec` from `_reward_config_from_env()`. In `step()`, computes `time_max_sec = 3.0 × seg_len` dynamically (or uses `VIDEO_ENCODE_REWARD_TIME_MAX_SEC` env var if explicitly set as an override). A 0.3 s encode of a 3 s segment now scores T̄ ≈ 0.033 (vs ≈ 0.005 before), giving the time term real gradient. ### ✅ Per-segment features on extracted clip (`segment_analysis`) **Date:** 2026-04-07 - `video_analysis.py`: Added `analyze_segment_clip(path, *, timeout, compute_complexity)` — computes per-segment width/height/fps/bitrate/file_size + EY/h/LY complexity on the already-extracted reference clip. Reuses `_run_ffmpeg_luma_complexity_metrics` (existing). Complexity capped at 30 s. Docstring names 3 future extension points: `compute_scene_cuts`, `compute_frame_types`, `compute_quality_baseline`. - `models.py`: Added `segment_analysis: Dict[str, Any]` field to `VideoEncodeObservation` (placed between `whole_video_analysis` and the metric fields). - `server/video_encode_environment.py`: Imports `analyze_segment_clip`; initializes `seg_analysis={}` before tmpdir; populates after `ffprobe_video_size(ref_clip)`; passes to all 4 post-extraction `_observation()` calls. Pre-extraction paths get `{}` via the `None` default on `_observation()`. --- ## Immediate Next Tasks (Priority Order) ### 1. Add `current_segment_history` to observation (remove partial observability) **Files:** `models.py`, `server/video_encode_environment.py` The agent sees `prev_segment_predictions` (last completed segment) but has no record of its own prior steps *within the current segment*. `_segment_step_metrics` (already maintained) holds this data. Add `current_segment_history: List[Dict[str, Any]]` to the observation. ### 2. Quality term shaping (gamma correction) **Files:** `server/reward.py` Linear Q̄ = vmaf/100 underweights the high-quality regime. Replace with `Q̄ = clip(vmaf/vmaf_max) ** (1/γ)` where γ=1.5 (concave). Also fix SSIM fallback scale: SSIM clusters 0.85–0.99 so use `(ssim − SSIM_MIN) / (1 − SSIM_MIN)` with `SSIM_MIN=0.70`. ### 3. Intra-segment Pareto summary in `prev_segment_predictions` **Files:** `server/video_encode_environment.py` `_summarize_completed_segment()` currently only reports means. Add `best_vmaf_step` and `most_efficient_step` (highest vmaf/bitrate ratio) so the agent gets supervised-style feedback on which actions were best in the last segment. --- ## Short-term Plans (next 2–4 sessions) - **Rate-distortion efficiency bonus:** Add RD term `Q̄ / (S̄ + ε)` as an optional reward component via `VIDEO_ENCODE_REWARD_LAMBDA_RD` (default 0). Rewards finding the Pareto frontier. - **Encode speed ratio in observation:** Expose `realtime_speed_ratio = segment_duration / enc_time` in step metadata. Values < 1.0 mean slower-than-realtime (undesirable for live streaming). - **Quality floor penalty:** Binary hard penalty when VMAF < threshold (e.g. 70), separate from the continuous Q̄ gradient. Controlled by `VIDEO_ENCODE_REWARD_VMAF_FLOOR` (default 0 = off). - **Future `analyze_segment_clip` passes** (already reserved in docstring): - `compute_scene_cuts` — scene change count via `ffprobe select='gt(scene,0.3)'` - `compute_frame_types` — I/P/B frame ratio via `ffprobe -show_frames` - `compute_quality_baseline` — PSNR/SSIM at CRF-18 as upper-bound reference --- ## Long-term Vision - **Resolution as action dimension:** Add `scale_factor: float` (0.25–1.0) to `VideoEncodeAction` for resolution-adaptive encoding (ABR streaming use case). - **Target bitrate mode (ABR):** Add `target_bitrate_kbps: int | None` — when set, use `-b:v` instead of `-crf`. Reward proximity to target bitrate. - **Codec variety:** Add `codec: str` (h264/h265/av1) to the action. Requires codec availability check in the environment at step time. - **Multi-pass encoding:** Optional two-pass encode for better rate control at target bitrates. - **Offline dataset integration:** `data_collection.py` builds a CRF × preset × resolution grid. Long-term goal: train a quality-prediction model from this data that the agent can query as an "oracle feature" (predicted VMAF before encoding). --- ## Known Issues / Technical Debt | Issue | Location | Priority | |---|---|---| | `ffprobe_duration_sec` and `ffprobe_video_size` duplicated in `segment_utils.py` and `video_analysis.py` | Both files | Low | | `max_concurrent_envs=1` hardcoded | `server/app.py:58` | Low | | `whole_video_analysis` deep-copied every step even when unchanged | `video_encode_environment.py` | Low | | SSIM only computed when VMAF fails; both have complementary diagnostic value | `video_encode_environment.py` | Medium |