惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
P
Proofpoint News Feed
WordPress大学
WordPress大学
P
Proofpoint News Feed
宝玉的分享
宝玉的分享
腾讯CDC
罗磊的独立博客
P
Privacy International News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
Latest news
Latest news
C
Cisco Blogs
Project Zero
Project Zero
Apple Machine Learning Research
Apple Machine Learning Research
The GitHub Blog
The GitHub Blog
博客园 - 叶小钗
Spread Privacy
Spread Privacy
博客园 - 三生石上(FineUI控件)
Blog — PlanetScale
Blog — PlanetScale
C
Check Point Blog
博客园 - 聂微东
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Tenable Blog
Know Your Adversary
Know Your Adversary
Security Latest
Security Latest
T
The Blog of Author Tim Ferriss
云风的 BLOG
云风的 BLOG
L
Lohrmann on Cybersecurity
IT之家
IT之家
T
Tor Project blog
S
SegmentFault 最新的问题
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
月光博客
月光博客
L
LINUX DO - 热门话题
C
CERT Recently Published Vulnerability Notes
T
Threat Research - Cisco Blogs
A
Arctic Wolf
D
DataBreaches.Net
C
Cybersecurity and Infrastructure Security Agency CISA
博客园 - 【当耐特】
T
The Exploit Database - CXSecurity.com
T
Threatpost
Hacker News - Newest:
Hacker News - Newest: "LLM"
Scott Helme
Scott Helme
博客园 - 司徒正美
Vercel News
Vercel News
H
Help Net Security
N
News and Events Feed by Topic
MyScale Blog
MyScale Blog
Simon Willison's Weblog
Simon Willison's Weblog
P
Privacy & Cybersecurity Law Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Build a per-title bitrate ladder in 80 lines of FFmpeg + VMAF
Mason K · 2026-05-14 · via DEV Community

📦 Code: github.com/USER/per-title-ladder — replace before publishing.

TL;DR

We'll take any source video, run a probe pass at six bitrate-resolution points, score each with VMAF, build a per-title ladder from the convex hull, and compare the bandwidth bill against a static 2019 ladder. End-to-end, ~80 lines of Python orchestrating FFmpeg 7.0 and libvmaf.

What we're building

A small CLI that you can run as:

python3 ladder.py samples/talking-head.mp4

Enter fullscreen mode Exit fullscreen mode

…and that produces:

  1. A per-title ladder, tuned for that specific file.
  2. A side-by-side bandwidth comparison vs a static ladder.
  3. A ladder.json you can feed to your HLS packaging step.

You'll need FFmpeg 7.0+ built with libvmaf, Python 3.11+, and a source MP4. We're not training a perceptual model — VMAF's stock model is fine for a first cut.

1. Why one ladder doesn't fit everything

A static ladder picks the same bitrate-resolution rungs for every video. For a talking-head with no motion, those rungs are overkill at the top and oddly placed in the middle. For a sports clip, they're too sparse at the high end.

The idea behind per-title is: probe the content first, then place the rungs where they actually buy you visible quality. Same workflow Fraunhofer's "video-dev" group documents, same one Streaming Learning Center's recent piece on the evolving ladder walks through. The math gets fancy in production; for one file, you just need to score a handful of points and pick the best ones.

2. Install the toolchain 🧰

# Build FFmpeg 7.0 with libvmaf, on macOS:
brew install ffmpeg

# Verify
ffmpeg -version | head -1
# ffmpeg version 7.0 "Dijkstra" ...

ffmpeg -filters | grep vmaf
# libvmaf            VV->V      Calculate the VMAF score

Enter fullscreen mode Exit fullscreen mode

If your distro ships an older FFmpeg, get a 7.0+ static build from the official site or codexffmpeg on GitHub. The release notes for 7.0 ("Dijkstra") matter for this kind of work — the major transcoding components (demuxers, decoders, filters, encoders, muxers) all run in parallel now, so probe passes complete materially faster on multi-core machines.

pip install --break-system-packages click ffmpeg-python
mkdir samples renditions

Enter fullscreen mode Exit fullscreen mode

3. Define the test grid 🧪

Pick a small grid that spans the resolution/bitrate space:

# ladder.py
import json
import subprocess
from pathlib import Path
from dataclasses import dataclass

@dataclass(frozen=True)
class TestPoint:
    width: int
    height: int
    bitrate_kbps: int

    @property
    def label(self) -> str:
        return f"{self.height}p_{self.bitrate_kbps}k"

# A small grid — six points across width x bitrate.
TEST_GRID = [
    TestPoint(640, 360, 400),
    TestPoint(640, 360, 700),
    TestPoint(1280, 720, 1500),
    TestPoint(1280, 720, 2500),
    TestPoint(1920, 1080, 3500),
    TestPoint(1920, 1080, 5500),
]

Enter fullscreen mode Exit fullscreen mode

For a production system you'd want more points (12–20 is typical). For a first pass, six is enough to demonstrate the technique.

4. Encode each test point 🎞️

The encode is plain H.264 with a fixed maxrate/bufsize — what most production HLS ladders use today:

def encode_point(src: Path, point: TestPoint, out_dir: Path) -> Path:
    out = out_dir / f"{point.label}.mp4"
    if out.exists():
        return out
    subprocess.run([
        "ffmpeg", "-y", "-i", str(src),
        "-vf", f"scale={point.width}:{point.height}",
        "-c:v", "libx264",
        "-preset", "medium",
        "-b:v", f"{point.bitrate_kbps}k",
        "-maxrate", f"{point.bitrate_kbps}k",
        "-bufsize", f"{point.bitrate_kbps * 2}k",
        "-c:a", "aac", "-b:a", "96k",
        str(out),
    ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return out

Enter fullscreen mode Exit fullscreen mode

💡 Tip: -preset medium is the right balance for a probe pass. Going slower buys you a small quality gain but multiplies probe time. Going faster muddles the VMAF readings.

5. Score with VMAF 📐

VMAF compares each encoded point against the source and gives you a single number from 0 to 100:

def vmaf_score(src: Path, encoded: Path) -> float:
    # libvmaf in FFmpeg 7.x: emit JSON via the `log_path` parameter.
    log_path = encoded.with_suffix(".vmaf.json")
    cmd = [
        "ffmpeg", "-i", str(encoded), "-i", str(src),
        "-lavfi",
        f"[0:v]scale=1920:1080:flags=bicubic[main];"
        f"[1:v]scale=1920:1080:flags=bicubic[ref];"
        f"[main][ref]libvmaf=log_path={log_path}:log_fmt=json",
        "-f", "null", "-",
    ]
    subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    data = json.loads(log_path.read_text())
    return float(data["pooled_metrics"]["vmaf"]["mean"])

Enter fullscreen mode Exit fullscreen mode

Two notes here. First, we upscale both inputs to 1080p before comparing — VMAF compares same-size frames, so the encoded rendition gets scaled back up. Second, the JSON shape is the standard libvmaf output; the pooled_metrics.vmaf.mean field is the per-clip average.

⚠️ Note: VMAF scores aren't directly comparable across very different content types. Animation vs sports vs talking-head produce different score distributions for the same bitrate. The relative ranking within a single source video is what matters here.

6. Pick the convex hull 📈

The convex hull is the set of "best quality per bit" points across the bitrate-VMAF plane. Anything dominated by another point at lower bitrate gets dropped:

def convex_hull(points: list[tuple[int, float]]) -> list[tuple[int, float]]:
    """Pick points on the upper-left convex hull: lower bitrate, higher VMAF wins."""
    sorted_points = sorted(points)  # by bitrate ascending
    hull = []
    for bitrate, vmaf in sorted_points:
        # Drop any prior point we now dominate
        while hull and hull[-1][1] <= vmaf:
            hull.pop()
        hull.append((bitrate, vmaf))
    return hull

Enter fullscreen mode Exit fullscreen mode

A real implementation would also enforce a quality floor (don't ship a 35-VMAF rung even if it's "on the hull") and resolution sanity (don't put two 360p rungs back to back). For the tutorial version, the math above is enough.

7. Build the final ladder 🏗️

Now wire it all together:

import click

@click.command()
@click.argument("src", type=click.Path(exists=True, path_type=Path))
def main(src: Path):
    out_dir = Path("renditions") / src.stem
    out_dir.mkdir(parents=True, exist_ok=True)

    scored = []
    for point in TEST_GRID:
        print(f"encoding {point.label}...")
        encoded = encode_point(src, point, out_dir)
        vmaf = vmaf_score(src, encoded)
        scored.append((point, vmaf))
        print(f"  VMAF: {vmaf:.1f}")

    hull_input = [(p.bitrate_kbps, v) for p, v in scored]
    hull = convex_hull(hull_input)

    ladder = []
    for bitrate, vmaf in hull:
        chosen = next(p for p in TEST_GRID if p.bitrate_kbps == bitrate)
        ladder.append({
            "height": chosen.height,
            "width": chosen.width,
            "bitrate_kbps": chosen.bitrate_kbps,
            "vmaf": round(vmaf, 1),
        })

    out_json = src.with_suffix(".ladder.json")
    out_json.write_text(json.dumps({"src": str(src), "ladder": ladder}, indent=2))
    print(f"\nwrote {out_json}")
    for rung in ladder:
        print(f"  {rung['height']}p @ {rung['bitrate_kbps']}k → VMAF {rung['vmaf']}")

if __name__ == "__main__":
    main()

Enter fullscreen mode Exit fullscreen mode

Run it on a talking-head video:

python3 ladder.py samples/talking-head.mp4

Enter fullscreen mode Exit fullscreen mode

Expect output like:

encoding 360p_400k...
  VMAF: 71.4
encoding 360p_700k...
  VMAF: 82.1
encoding 720p_1500k...
  VMAF: 91.7
encoding 720p_2500k...
  VMAF: 94.2
encoding 1080p_3500k...
  VMAF: 95.1
encoding 1080p_5500k...
  VMAF: 95.3

wrote samples/talking-head.ladder.json
  360p @ 400k → VMAF 71.4
  360p @ 700k → VMAF 82.1
  720p @ 1500k → VMAF 91.7
  720p @ 2500k → VMAF 94.2
  1080p @ 3500k → VMAF 95.1

Enter fullscreen mode Exit fullscreen mode

Notice the 5500k rung dropped off the hull — it cost more bits but barely moved VMAF. That's the savings.

8. Compare against a static ladder 📊

The "Apple-style" static ladder for 1080p sources typically looks like:

Rung Resolution Bitrate
1 416×234 145k
2 640×360 365k
3 768×432 730k
4 960×540 2,000k
5 1280×720 3,000k
6 1920×1080 4,500k
7 1920×1080 6,000k

Sum the top-rung bitrate for a static ladder vs your per-title ladder, multiply by minutes streamed, and the egress delta falls out. For talking-head content, you'll routinely see the top-rung drop from 6,000k to 3,500k — a roughly 40% savings at the same perceived quality.

For high-motion content, the savings shrink and sometimes invert. Per-title isn't a magic bullet — it's a tool that pays off most for uniform low-motion content and long-tail mixed catalogs. Run it on three different titles and you'll feel the variance.

9. Where to go from here ➡️

A few honest follow-ups:

  1. Add more test points. Six is enough to show the technique. Twelve to twenty is closer to production.
  2. Constrain the ladder. Add a minimum VMAF (e.g., 70) and a maximum number of rungs (e.g., 5).
  3. Move to live. The Christian Doppler ATHENA group has a patent (US20230388511A1) on perceptually-aware online per-title for live streaming — the technique generalizes, with engineering.
  4. Skip the build, buy the result. Several managed video APIs now do context-aware encoding by default. If you're not in the "tens of thousands of minutes per month" range, just use one of those — the engineering math doesn't work in your favor below that volume.

The point of the tutorial isn't to convince you to build a production per-title system. It's to give you the numbers to argue about. Once you can run the probe on five titles from your own library and see the bandwidth delta, you'll know whether the engineering investment is worth it.

Wrapping up

Per-title encoding is one of those topics where the marketing copy makes it sound magical and the implementation is honestly pretty boring. Probe, score, pick the hull, ship. The hardest part is convincing the team that the static ladder they copy-pasted in 2019 is silently costing them money in 2026.

If you run this on your own catalog and find that it doesn't move the needle — great, that's also a result. Static ladders work fine for uniform content. The point is that you'll have data instead of vibes.