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

推荐订阅源

大猫的无限游戏
大猫的无限游戏
Security Archives - TechRepublic
Security Archives - TechRepublic
T
Threat Research - Cisco Blogs
A
Arctic Wolf
S
Securelist
O
OpenAI News
T
Threatpost
Forbes - Security
Forbes - Security
N
News and Events Feed by Topic
S
Secure Thoughts
H
Heimdal Security Blog
S
Security Affairs
P
Privacy International News Feed
C
Cisco Blogs
C
CERT Recently Published Vulnerability Notes
Cyberwarzone
Cyberwarzone
N
News and Events Feed by Topic
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Palo Alto Networks Blog
S
Security @ Cisco Blogs
Hacker News - Newest:
Hacker News - Newest: "LLM"
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
T
Tailwind CSS Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
S
SegmentFault 最新的问题
腾讯CDC
V
Visual Studio Blog
Last Week in AI
Last Week in AI
H
Hacker News: Front Page
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Project Zero
Project Zero
WordPress大学
WordPress大学
NISL@THU
NISL@THU
博客园 - 【当耐特】
博客园 - Franky
Webroot Blog
Webroot Blog
博客园_首页
T
Tenable Blog
雷峰网
雷峰网
Google Online Security Blog
Google Online Security Blog
阮一峰的网络日志
阮一峰的网络日志
V2EX - 技术
V2EX - 技术
Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
Lohrmann on Cybersecurity
The Hacker News
The Hacker News

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
Add real video QoE telemetry to your player in an afternoon
Mason K · 2026-05-15 · via DEV Community

📦 Code: github.com/USER/video-qoe-starter — replace before publishing.

TL;DR

We'll instrument an HLS.js player to emit the three QoE metrics that actually correlate with viewer abandonment — startup time, rebuffering ratio, and playback failure rate — ship them to a tiny Fastify endpoint, store them in SQLite, and render a dashboard. End to end in one file each: a React component, a Node endpoint, and a SQL view.

What we're building

A minimum-viable telemetry rig that answers the three questions every video team gets asked the day after launch:

  1. How long is it taking for a video to start playing?
  2. How often is the player stalling mid-playback?
  3. How often is playback failing outright?

We'll use HLS.js 1.6.x (the current stable line, with LL-HLS support), a Node 22 + Fastify backend, and SQLite for storage. No queue, no warehouse, no Grafana. The point is to ship a working baseline; you can swap parts later.

1. Set up the project 🛠️

mkdir video-qoe-starter && cd video-qoe-starter
npm init -y
npm install hls.js fastify better-sqlite3
npm install -D typescript @types/node @types/better-sqlite3
mkdir client server

Enter fullscreen mode Exit fullscreen mode

Your package.json scripts block:

{
  "scripts": {
    "server": "node --experimental-strip-types server/index.ts",
    "build": "tsc"
  }
}

Enter fullscreen mode Exit fullscreen mode

💡 Tip: Node 22 ships with --experimental-strip-types for TypeScript files, so you can run .ts directly without ts-node for prototypes like this.

2. Instrument the player 🎯

The HLS.js event surface is the same shape across every modern player — MANIFEST_PARSED, MEDIA_ATTACHED, FRAG_BUFFERED, ERROR, plus the standard HTML video events (play, waiting, playing, ended).

// client/qoe.ts
import Hls, { Events, ErrorData } from 'hls.js';

type QoeSession = {
  session_id: string;
  video_id: string;
  player: string;
  user_agent: string;
  startup_time_ms: number | null;
  total_watch_time_ms: number;
  total_stall_time_ms: number;
  rebuffer_count: number;
  error_codes: string[];
};

export function instrument(video: HTMLVideoElement, hls: Hls, videoId: string) {
  const session: QoeSession = {
    session_id: crypto.randomUUID(),
    video_id: videoId,
    player: `hls.js@${Hls.version}`,
    user_agent: navigator.userAgent,
    startup_time_ms: null,
    total_watch_time_ms: 0,
    total_stall_time_ms: 0,
    rebuffer_count: 0,
    error_codes: [],
  };

  let playRequestedAt: number | null = null;
  let lastPlayingAt: number | null = null;
  let stallStartedAt: number | null = null;
  let firstPlayingFired = false;

  video.addEventListener('play', () => {
    if (playRequestedAt === null) playRequestedAt = performance.now();
  });

  video.addEventListener('playing', () => {
    const now = performance.now();
    if (!firstPlayingFired && playRequestedAt !== null) {
      session.startup_time_ms = now - playRequestedAt;
      firstPlayingFired = true;
    }
    if (stallStartedAt !== null) {
      session.total_stall_time_ms += now - stallStartedAt;
      stallStartedAt = null;
    }
    lastPlayingAt = now;
  });

  video.addEventListener('waiting', () => {
    // 'waiting' is the rebuffer signal — buffer underrun, fetching more segments.
    if (firstPlayingFired) {
      session.rebuffer_count += 1;
      stallStartedAt = performance.now();
    }
  });

  video.addEventListener('pause', () => {
    if (lastPlayingAt !== null) {
      session.total_watch_time_ms += performance.now() - lastPlayingAt;
      lastPlayingAt = null;
    }
  });

  hls.on(Events.ERROR, (_, data: ErrorData) => {
    session.error_codes.push(`${data.type}:${data.details}`);
  });

  const flush = () => {
    if (lastPlayingAt !== null) {
      session.total_watch_time_ms += performance.now() - lastPlayingAt;
      lastPlayingAt = null;
    }
    navigator.sendBeacon('/qoe', JSON.stringify(session));
  };

  // Flush on tab close, route change, or page unload.
  window.addEventListener('pagehide', flush);
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'hidden') flush();
  });

  return { session, flush };
}

Enter fullscreen mode Exit fullscreen mode

A few decisions baked in here worth calling out:

  • navigator.sendBeacon is the right transport for telemetry on unload. fetch gets aborted when the tab closes; sendBeacon is best-effort but fire-and-forget.
  • First playing event is the only honest signal for "first frame painted." loadedmetadata and canplay fire too early — they fire when the player could play, not when it did.
  • waiting is the rebuffer signal, but only after the first playing. Before the first playing, waiting is part of startup.

⚠️ Note: Don't trust client-side derived metrics. Ship raw event data (start, playing, waiting, error timestamps) and compute rebuffer ratio server-side. We're shipping aggregates in this tutorial for simplicity — for production, do raw events.

3. Wire the player to the instrumentation 🔌

// client/Player.tsx
import { useEffect, useRef } from 'react';
import Hls from 'hls.js';
import { instrument } from './qoe';

export function Player({ src, videoId }: { src: string; videoId: string }) {
  const videoRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    if (!videoRef.current) return;
    const hls = new Hls({ enableWorker: true });
    hls.loadSource(src);
    hls.attachMedia(videoRef.current);
    const { flush } = instrument(videoRef.current, hls, videoId);

    return () => {
      flush();
      hls.destroy();
    };
  }, [src, videoId]);

  return <video ref={videoRef} controls playsInline width="800" />;
}

Enter fullscreen mode Exit fullscreen mode

That's the whole client side.

4. Build the ingestion endpoint 📥

The simplest thing that could possibly work — Fastify, JSON in, SQLite out:

// server/index.ts
import Fastify from 'fastify';
import Database from 'better-sqlite3';

const db = new Database('qoe.db');
db.exec(`
  CREATE TABLE IF NOT EXISTS sessions (
    session_id TEXT PRIMARY KEY,
    video_id TEXT NOT NULL,
    player TEXT,
    user_agent TEXT,
    startup_time_ms REAL,
    total_watch_time_ms REAL,
    total_stall_time_ms REAL,
    rebuffer_count INTEGER,
    error_codes TEXT,
    created_at INTEGER NOT NULL
  );
`);

const insert = db.prepare(`
  INSERT OR REPLACE INTO sessions
  (session_id, video_id, player, user_agent, startup_time_ms,
   total_watch_time_ms, total_stall_time_ms, rebuffer_count, error_codes, created_at)
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);

const app = Fastify({ logger: true });

app.post('/qoe', async (req, reply) => {
  const s = req.body as Record<string, unknown>;
  insert.run(
    s.session_id, s.video_id, s.player, s.user_agent,
    s.startup_time_ms ?? null,
    s.total_watch_time_ms ?? 0,
    s.total_stall_time_ms ?? 0,
    s.rebuffer_count ?? 0,
    JSON.stringify(s.error_codes ?? []),
    Date.now(),
  );
  reply.send({ ok: true });
});

app.get('/metrics', async () => {
  return db.prepare(`
    SELECT
      COUNT(*) as sessions,
      AVG(startup_time_ms) as avg_startup_ms,
      SUM(total_stall_time_ms) * 1.0 / NULLIF(SUM(total_watch_time_ms), 0) as rebuffer_ratio,
      SUM(CASE WHEN error_codes != '[]' THEN 1 ELSE 0 END) * 1.0 / COUNT(*) as failure_rate
    FROM sessions
    WHERE created_at > unixepoch() * 1000 - 86400000
  `).get();
});

app.listen({ port: 3000, host: '0.0.0.0' });

Enter fullscreen mode Exit fullscreen mode

Run it:

npm run server

Enter fullscreen mode Exit fullscreen mode

Expect:

{"level":30,"time":...,"msg":"Server listening at http://0.0.0.0:3000"}

Enter fullscreen mode Exit fullscreen mode

5. The three queries that earn their keep 📊

Once you have data flowing, three queries answer most of the questions you'll be asked.

Startup time, p50/p95, by day:

SELECT
  date(created_at / 1000, 'unixepoch') as day,
  COUNT(*) as sessions,
  -- p50 / p95 in SQLite via window functions:
  -- use a CTE in production; the simple AVG below is fine for a starter dashboard
  AVG(startup_time_ms) as avg_startup_ms
FROM sessions
WHERE startup_time_ms IS NOT NULL
GROUP BY day
ORDER BY day DESC
LIMIT 14;

Enter fullscreen mode Exit fullscreen mode

Rebuffer ratio over the last 24h:

SELECT
  SUM(total_stall_time_ms) * 1.0 / NULLIF(SUM(total_watch_time_ms), 0) as rebuffer_ratio
FROM sessions
WHERE created_at > unixepoch() * 1000 - 86400000;

Enter fullscreen mode Exit fullscreen mode

You want this under 1%. Mux's blog calls 0.5% the strong-platform target; npaw's writeup uses the 1% / 3% bands. Past 3%, viewers are noticing. Past 5%, they're leaving.

Failure rate by player version:

SELECT
  player,
  COUNT(*) as sessions,
  SUM(CASE WHEN error_codes != '[]' THEN 1 ELSE 0 END) * 1.0 / COUNT(*) as failure_rate
FROM sessions
GROUP BY player
ORDER BY failure_rate DESC;

Enter fullscreen mode Exit fullscreen mode

This is the query that catches the one specific combination of player + browser + device where playback is silently broken for 4% of your users. There's always one.

6. What we deliberately didn't build ⏭️

A starter rig isn't a production analytics platform. Things this tutorial skips:

  • Real event-level storage. We ship session aggregates. A production system ships raw events so the metric definitions can change without re-instrumenting.
  • Queueing. A POST per session is fine until your traffic doubles. Then you want a queue between the endpoint and the database.
  • Alerting. Querying SQLite is not an alerting strategy.
  • Cross-session viewer journeys. We track session, not viewer. If your product question is "did the same viewer hit a rebuffer last week and abandon this week?", you need a viewer-stable ID.

The decision tree is the point. If you're going to outgrow this rig in a quarter, that's the trigger to either invest in real telemetry infrastructure or pick up a managed analytics SDK that gives you a richer baseline by default.

Wrapping up

Most teams ship video before they ship video telemetry. That order is backwards. The cost of being blind to your QoE numbers is paid in customer trust — the support ticket you can't diagnose, the regression you don't notice for two weeks — and it compounds.

The rig above is the lowest-effort version that gets you the three core metrics. If it's enough, great. If you outgrow it, the move is either a real internal pipeline or a managed analytics product. Both are reasonable answers; either one is better than continuing to operate without data.

What's next

  • Swap SQLite for ClickHouse or Postgres + TimescaleDB once you cross ~1M sessions/week.
  • Add a quality_change event listener and track ABR down-switches per session.
  • Add a small heatmap of rebuffer events by playback position — surprisingly useful for finding bad keyframe placement at scene cuts.
  • If you outgrow rolling your own: any of the managed analytics SDKs (Mux Data, the analytics layer in api.video, or other comparable products) drop into this same player with one extra script tag. The metric definitions converge across products — you're paying for the storage and the dashboards, not for the metric.

Sources used to ground the metric definitions:

  • Mux, "Quality of Experience (QoE) in Video Streaming."
  • Mux, "The Four Elements of Video Performance."
  • Mux, "Video Analytics Series Part 1: Rebuffering."
  • NPAW, "Exploring Video QoE & QoS."
  • HLS.js release notes — github.com/video-dev/hls.js/releases (1.6.x current stable, 1.7.0-alpha pre-release).