LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.
C cdebiandesktop-environmentebpffirewalllandlocklinuxlinux-distributionopen-sourceprivacyquickjsraspberry-pi-5reactsecuritywaylandwayland-compositor
Video in the browser without hardware decoding (0.8.2)
Federico Pereira7c152e43c860
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d5e2d3d..7f6f0ba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,27 @@ suffix (`-beta`) and are published on GitHub as pre-releases. Each section belowof the matching [GitHub release](https://github.com/lordbasex/LordOS/releases), generated by`tools/release/release-notes.sh` (see [docs/RELEASING.md](docs/RELEASING.md)).+## [0.8.2] - Unreleased++### Added++- **Smooth video in the browser without hardware decoding.** Video sites that send VP9 or AV1+ make the browser decode them on the processor when the graphics card can't (virtual machines,+ older PCs, the Raspberry Pi 5), and the video stutters. LordOS now checks at every boot what the+ hardware decodes (VA-API profiles through `lord-media`, V4L2 memory-to-memory decoders on ARM,+ virtual graphics cards count as "no"; cached per boot) and, when VP9 or AV1 is missing, asks the+ browsers for H.264 instead, which is far lighter to decode. Settings → Displays → Video in the+ browser: "Optimize video for this computer" (Automatic by default, Always, Never) and "Lower+ quality automatically when video stutters" (off by default). Nothing is sent anywhere+ ([docs/VIDEO.md](docs/VIDEO.md)).+- **Our own small browser extension** (`/usr/share/chromium/extensions/lordos-video`, MIT), loaded+ by Debian's Chromium: on YouTube it reports VP9/AV1 as unsupported so the site sends H.264, and+ when a video keeps dropping frames it shows a small notice that offers a lower quality (or lowers+ it by itself, if enabled). Its settings come from a managed policy written by the closed admin+ action `video-optimize` (fixed text, no user text). Firefox ESR only loads signed extensions, so+ for now it gets AV1 turned off through a default preference (it then uses VP9); the extension+ for Firefox waits for signing.+## [Unreleased]## [0.8.1-beta] - 2026-10-19diff --git a/apps/settings/Displays.jsx b/apps/settings/Displays.jsxindex b7e10eb..52333be 100644--- a/apps/settings/Displays.jsx+++ b/apps/settings/Displays.jsx@@ -1,5 +1,6 @@// Settings → Displays: arrangement of several displays (extend or mirror), resolution, refresh rate,-// rotation, scale (100–200 %, sharp), the main display, brightness and Night Light (docs/SETTINGS.md,+// rotation, scale (100–200 %, sharp), the main display, brightness, Night Light and video in the+// browser (Video.jsx, docs/VIDEO.md) (docs/SETTINGS.md,// "Displays", and docs/DISPLAYS.md). Changes apply live with the system's 15-second "Keep these// display settings?" countdown (sdk/hardware.jsx) and are saved per display (EDID identity).// Layout: the arrangement on top, then the selected display's@@ -11,6 +12,7 @@ import {} from '@lordos/sdk';import { useEffect, useRef, useState } from 'react';import { Section, SettingRow, PopUp, Note, Stack, TimeField } from './ui.jsx';+import { BrowserVideo } from './Video.jsx';const hz = (mhz) => {const v = mhz / 1000;@@ -251,6 +253,7 @@ export function DisplaysSettings() {<Stack><Note>{tr('prefs.display.notOnMonitor')}</Note><NightShift />+ <BrowserVideo /></Stack>);}@@ -327,6 +330,7 @@ export function DisplaysSettings() {<NightShift />{d.softTint ? <Note style={{ marginTop: -12 }}>{tr('prefs.night.software')}</Note> : null}+ <BrowserVideo /></Stack>);}diff --git a/apps/settings/Video.jsx b/apps/settings/Video.jsxnew file mode 100644index 0000000..0dd5b0a--- /dev/null+++ b/apps/settings/Video.jsx@@ -0,0 +1,36 @@+// Settings → Displays → Video in the browser: "Optimize video for this computer" (Automatic, Always,+// Never) and "Lower quality automatically when video stutters" (docs/VIDEO.md). The SDK (sdk/video.js)+// finds out what the hardware decodes and writes the browsers' settings with the closed admin+// action video-optimize.+import { useLocale, useStore, Toggle, videoPrefs, setVideoPrefs, videoHardware, videoError, videoOptimizing, useSettings } from '@lordos/sdk';+import { Section, SettingRow, PopUp, Note } from './ui.jsx';++function statusText(tr, prefs, hw) {+ if (prefs.mode === 'always') return tr('prefs.video.statusAlways');+ if (prefs.mode === 'never') return tr('prefs.video.statusNever');+ if (!hw) return tr('prefs.video.checking');+ if (!videoOptimizing(prefs, hw)) return tr('prefs.video.statusHardware');+ const which = !hw.vp9 && !hw.av1 ? tr('prefs.video.codecsBoth') : !hw.vp9 ? 'VP9' : 'AV1';+ const why = tr(`prefs.video.reason.${hw.reason === 'virtualGpu' ? 'virtualGpu' : hw.reason === 'noDriver' ? 'noDriver' : 'noProfiles'}`);+ return tr('prefs.video.statusAuto', { codecs: which, reason: why });+}++export function BrowserVideo() {+ const { t: tr } = useLocale();+ const [s] = useSettings();+ const prefs = videoPrefs(s);+ const hw = useStore(videoHardware);+ const err = useStore(videoError);+ const modes = [['auto', tr('prefs.video.mode.auto')], ['always', tr('prefs.video.mode.always')], ['never', tr('prefs.video.mode.never')]];+ return (+ <Section title={tr('prefs.video.title')} footer={tr('prefs.video.footer')}>+ <SettingRow label={tr('prefs.video.optimize')} hint={statusText(tr, prefs, hw)}>+ <PopUp width={170} value={prefs.mode} onChange={(mode) => setVideoPrefs({ mode })} options={modes} />+ </SettingRow>+ <SettingRow label={tr('prefs.video.autoLower')} hint={tr('prefs.video.autoLowerHint')}>+ <Toggle small on={prefs.autoLower} onChange={(autoLower) => setVideoPrefs({ autoLower })} />+ </SettingRow>+ {err ? <Note tone="warn">{err}</Note> : null}+ </Section>+ );+}diff --git a/assets/browser/video/_locales/en/messages.json b/assets/browser/video/_locales/en/messages.jsonnew file mode 100644index 0000000..225b00d--- /dev/null+++ b/assets/browser/video/_locales/en/messages.json@@ -0,0 +1,9 @@+{+ "name": { "message": "LordOS video" },+ "description": { "message": "Smoother video on computers without hardware decoding: video sites send H.264, and you get a notice when a video stutters. Set up in LordOS Settings." },+ "stutter": { "message": "This video is stuttering. A lower quality may play smoothly." },+ "lower": { "message": "Lower quality" },+ "lowered": { "message": "Quality lowered to $Q$ so the video plays smoothly.", "placeholders": { "q": { "content": "$1" } } },+ "lowerManual": { "message": "Choose a lower quality in the player's settings." },+ "dismiss": { "message": "Dismiss" }+}diff --git a/assets/browser/video/_locales/es/messages.json b/assets/browser/video/_locales/es/messages.jsonnew file mode 100644index 0000000..1c3cccc--- /dev/null+++ b/assets/browser/video/_locales/es/messages.json@@ -0,0 +1,9 @@+{+ "name": { "message": "Video de LordOS" },+ "description": { "message": "Video más fluido en computadoras sin decodificación por hardware: los sitios de video envían H.264, y un aviso te avisa cuando un video se traba. Se configura en Ajustes de LordOS." },+ "stutter": { "message": "Este video se está trabando. Con una calidad más baja puede verse fluido." },+ "lower": { "message": "Bajar calidad" },+ "lowered": { "message": "Calidad bajada a $Q$ para que el video se vea fluido.", "placeholders": { "q": { "content": "$1" } } },+ "lowerManual": { "message": "Elegí una calidad más baja en los ajustes del reproductor." },+ "dismiss": { "message": "Cerrar" }+}diff --git a/assets/browser/video/_locales/pt/messages.json b/assets/browser/video/_locales/pt/messages.jsonnew file mode 100644index 0000000..c93479d--- /dev/null+++ b/assets/browser/video/_locales/pt/messages.json@@ -0,0 +1,9 @@+{+ "name": { "message": "Vídeo do LordOS" },+ "description": { "message": "Vídeo mais fluido em computadores sem decodificação por hardware: os sites de vídeo enviam H.264, e um aviso aparece quando um vídeo trava. Configurado nos Ajustes do LordOS." },+ "stutter": { "message": "Este vídeo está travando. Uma qualidade mais baixa pode rodar sem travar." },+ "lower": { "message": "Baixar qualidade" },+ "lowered": { "message": "Qualidade reduzida para $Q$ para o vídeo rodar sem travar.", "placeholders": { "q": { "content": "$1" } } },+ "lowerManual": { "message": "Escolha uma qualidade mais baixa nas configurações do player." },+ "dismiss": { "message": "Fechar" }+}diff --git a/assets/browser/video/icon128.png b/assets/browser/video/icon128.pngnew file mode 100644index 0000000..886935bBinary files /dev/null and b/assets/browser/video/icon128.png differdiff --git a/assets/browser/video/icon48.png b/assets/browser/video/icon48.pngnew file mode 100644index 0000000..9dad605Binary files /dev/null and b/assets/browser/video/icon48.png differdiff --git a/assets/browser/video/manifest.firefox.json b/assets/browser/video/manifest.firefox.jsonnew file mode 100644index 0000000..6fe2584--- /dev/null+++ b/assets/browser/video/manifest.firefox.json@@ -0,0 +1,56 @@+{+ "manifest_version": 3,+ "name": "__MSG_name__",+ "description": "__MSG_description__",+ "version": "1.0.0",+ "default_locale": "en",+ "browser_specific_settings": {+ "gecko": {+ "id": "[email protected]",+ "strict_min_version": "128.0"+ }+ },+ "permissions": [+ "storage"+ ],+ "host_permissions": [+ "https://www.youtube.com/*",+ "https://m.youtube.com/*",+ "https://music.youtube.com/*",+ "https://www.youtube-nocookie.com/*"+ ],+ "content_scripts": [+ {+ "matches": [+ "https://www.youtube.com/*",+ "https://m.youtube.com/*",+ "https://music.youtube.com/*",+ "https://www.youtube-nocookie.com/*"+ ],+ "js": [+ "page.js"+ ],+ "run_at": "document_start",+ "all_frames": true,+ "world": "MAIN"+ },+ {+ "matches": [+ "https://www.youtube.com/*",+ "https://m.youtube.com/*",+ "https://music.youtube.com/*",+ "https://www.youtube-nocookie.com/*"+ ],+ "js": [+ "policy.js",+ "stutter.js"+ ],+ "run_at": "document_start",+ "all_frames": true+ }+ ],+ "icons": {+ "48": "icon48.png",+ "128": "icon128.png"+ }+}diff --git a/assets/browser/video/manifest.json b/assets/browser/video/manifest.jsonnew file mode 100644index 0000000..aee5328--- /dev/null+++ b/assets/browser/video/manifest.json@@ -0,0 +1,54 @@+{+ "manifest_version": 3,+ "name": "__MSG_name__",+ "description": "__MSG_description__",+ "version": "1.0.0",+ "default_locale": "en",+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxa5oje2B7tq1K0FxP9Viwaq58r7wpHO+mZJKEJVaqb6yTxOtQlatHDREPfNIaVlmkU2/qsQgH7e8LP7YObNsatQiwXdgFxIlLJFbHb51Fo+HL5TATKhmAUh2LRM7I8i7zTg41CgGmOnkcyqsm+FdWkvffv43M8NXPVmZ2xJwdsi070fOTIrEztRO7imLSOhN0NS1KFADPpvQTIBJEwqY0N0insTqMWjvgj+eUDsmX7pL4HXPlpYbcBHTGEfUC8lBx1rQo8BqqylLx9RyrYV7goebVjhzoNhdDP8p3oGI6BIfEYxqHOIBAi4KqDmAZLdM7ieGJiUxWGIukw+1Whhy8wIDAQAB",+ "permissions": [+ "storage"+ ],+ "host_permissions": [+ "https://www.youtube.com/*",+ "https://m.youtube.com/*",+ "https://music.youtube.com/*",+ "https://www.youtube-nocookie.com/*"+ ],+ "storage": {+ "managed_schema": "schema.json"+ },+ "content_scripts": [+ {+ "matches": [+ "https://www.youtube.com/*",+ "https://m.youtube.com/*",+ "https://music.youtube.com/*",+ "https://www.youtube-nocookie.com/*"+ ],+ "js": [+ "page.js"+ ],+ "run_at": "document_start",+ "all_frames": true,+ "world": "MAIN"+ },+ {+ "matches": [+ "https://www.youtube.com/*",+ "https://m.youtube.com/*",+ "https://music.youtube.com/*",+ "https://www.youtube-nocookie.com/*"+ ],+ "js": [+ "policy.js",+ "stutter.js"+ ],+ "run_at": "document_start",+ "all_frames": true+ }+ ],+ "icons": {+ "48": "icon48.png",+ "128": "icon128.png"+ }+}diff --git a/assets/browser/video/page.js b/assets/browser/video/page.jsnew file mode 100644index 0000000..2bae6e8--- /dev/null+++ b/assets/browser/video/page.js@@ -0,0 +1,79 @@+// page.js — runs in the page itself (the page's world), before the site's own scripts (docs/VIDEO.md).+//+// 1. Holds back VP9 and/or AV1: the media element, MediaSource and the Media Capabilities API answer+// "not supported" for them, so the site's player picks H.264, which costs far less to decode in+// software. Which ones arrives from stutter.js (which can read the policy; this world can't) as a+// 'lordos-video-codecs' event on the document, detail "vp9,av1", "vp9", "av1" or "", a few+// milliseconds after the page starts: long before the site's player loads and asks.+// 2. Lowers the player's quality one step when stutter.js asks for it (a 'lordos-video-lower' event)+// and answers with 'lordos-video-lowered' (detail: the new quality, or '').+// The page itself could send those events too; it would only change what it is told about itself.+(() => {+ const patterns = [];+ document.addEventListener('lordos-video-codecs', (e) => {+ const list = typeof e.detail === 'string' ? e.detail.split(',') : [];+ patterns.length = 0;+ if (list.includes('vp9')) patterns.push(/vp0?9/i);+ if (list.includes('av1')) patterns.push(/av0?1/i);+ });+ const held = (type) => patterns.length > 0 && typeof type === 'string' && patterns.some((re) => re.test(type));++ const wrapStatic = (cls) => {+ if (!cls || typeof cls.isTypeSupported !== 'function') return;+ const orig = cls.isTypeSupported.bind(cls);+ Object.defineProperty(cls, 'isTypeSupported', {+ configurable: true, writable: true,+ value: function isTypeSupported(type) { return held(type) ? false : orig(type); },+ });+ };+ wrapStatic(globalThis.MediaSource);+ wrapStatic(globalThis.ManagedMediaSource);+ wrapStatic(globalThis.WebKitMediaSource);++ const proto = globalThis.HTMLMediaElement && HTMLMediaElement.prototype;+ if (proto && typeof proto.canPlayType === 'function') {+ const orig = proto.canPlayType;+ Object.defineProperty(proto, 'canPlayType', {+ configurable: true, writable: true,+ value: function canPlayType(type) { return held(type) ? '' : orig.call(this, type); },+ });+ }++ const mc = globalThis.navigator && navigator.mediaCapabilities;+ if (mc && typeof mc.decodingInfo === 'function') {+ const orig = mc.decodingInfo.bind(mc);+ Object.defineProperty(mc, 'decodingInfo', {+ configurable: true, writable: true,+ value: function decodingInfo(cfg) {+ const type = cfg && cfg.video && cfg.video.contentType;+ if (held(type)) return Promise.resolve({ supported: false, smooth: false, powerEfficient: false, configuration: cfg });+ return orig(cfg);+ },+ });+ }++ // The player's quality steps, highest first (the names its own API uses).+ const STEPS = ['highres', 'hd2880', 'hd2160', 'hd1440', 'hd1080', 'hd720', 'large', 'medium', 'small', 'tiny'];+ const LABEL = { highres: '4320p', hd2880: '2880p', hd2160: '2160p', hd1440: '1440p', hd1080: '1080p', hd720: '720p', large: '480p', medium: '360p', small: '240p', tiny: '144p' };+ const FLOOR = STEPS.indexOf('medium'); // never below 360p by itself++ function lower() {+ const p = document.getElementById('movie_player') || document.querySelector('.html5-video-player');+ if (!p || typeof p.getAvailableQualityLevels !== 'function') return '';+ const avail = p.getAvailableQualityLevels().filter((q) => STEPS.includes(q));+ if (!avail.length) return '';+ let cur = typeof p.getPlaybackQuality === 'function' ? p.getPlaybackQuality() : '';+ if (!STEPS.includes(cur)) cur = avail[0];+ const next = avail.find((q) => STEPS.indexOf(q) > STEPS.indexOf(cur) && STEPS.indexOf(q) <= FLOOR);+ if (!next) return '';+ if (typeof p.setPlaybackQualityRange === 'function') p.setPlaybackQualityRange(next, next);+ if (typeof p.setPlaybackQuality === 'function') p.setPlaybackQuality(next);+ return LABEL[next] || next;+ }++ document.addEventListener('lordos-video-lower', () => {+ let q = '';+ try { q = lower(); } catch (e) { q = ''; }+ document.dispatchEvent(new CustomEvent('lordos-video-lowered', { detail: q }));+ });+})();diff --git a/assets/browser/video/policy.js b/assets/browser/video/policy.jsnew file mode 100644index 0000000..0cfdad1--- /dev/null+++ b/assets/browser/video/policy.js@@ -0,0 +1,46 @@+// policy.js — reads the settings LordOS writes for this extension (docs/VIDEO.md).+//+// LordOS writes them as the browser's managed policy for this extension (Chromium:+// /etc/chromium/policies/managed/lordos-video.json, "3rdparty" → "extensions" → this id), so the+// extension never touches the network or the user's files and nothing is reported anywhere.+//+// mode "auto" (default): hold back only the codecs this computer can't decode in hardware+// "always": hold back VP9 and AV1 everywhere the extension runs+// "never": do nothing (the stutter notice stays)+// autoLower lower the quality one step by itself when the video keeps dropping frames+// hwVp9, hwAv1 what LordOS found at boot (VA-API profiles, V4L2 stateless decoders, virtual GPU)+//+// Without a policy (another distribution, or LordOS hasn't written it yet) nothing is held back.+/* global chrome, browser */+var lordosVideo = (() => {+ const api = typeof browser !== 'undefined' ? browser : chrome;+ const DEFAULTS = { mode: 'auto', autoLower: false, hwVp9: true, hwAv1: true, managed: false };++ function normalize(p) {+ const o = { ...DEFAULTS };+ if (!p || typeof p !== 'object') return o;+ if (['auto', 'always', 'never'].includes(p.mode)) { o.mode = p.mode; o.managed = true; }+ if (typeof p.autoLower === 'boolean') o.autoLower = p.autoLower;+ if (typeof p.hwVp9 === 'boolean') o.hwVp9 = p.hwVp9;+ if (typeof p.hwAv1 === 'boolean') o.hwAv1 = p.hwAv1;+ return o;+ }++ // The codecs to hold back: ['vp9', 'av1'], one of them or none.+ function blocked(o) {+ if (o.mode === 'never') return [];+ if (o.mode === 'always') return ['vp9', 'av1'];+ return [!o.hwVp9 && 'vp9', !o.hwAv1 && 'av1'].filter(Boolean);+ }++ async function read() {+ try {+ const p = await api.storage.managed.get(['mode', 'autoLower', 'hwVp9', 'hwAv1']);+ return normalize(p);+ } catch (e) {+ return normalize(null); // no managed storage (no policy file): defaults+ }+ }++ return { api, read, blocked, normalize };+})();diff --git a/assets/browser/video/schema.json b/assets/browser/video/schema.jsonnew file mode 100644index 0000000..fccaa7a--- /dev/null+++ b/assets/browser/video/schema.json@@ -0,0 +1,9 @@+{+ "type": "object",+ "properties": {+ "mode": { "type": "string", "enum": ["auto", "always", "never"] },+ "autoLower": { "type": "boolean" },+ "hwVp9": { "type": "boolean" },+ "hwAv1": { "type": "boolean" }+ }+}diff --git a/assets/browser/video/stutter.js b/assets/browser/video/stutter.jsnew file mode 100644index 0000000..64e783a--- /dev/null+++ b/assets/browser/video/stutter.js@@ -0,0 +1,138 @@+// stutter.js — notices when a video keeps dropping frames (docs/VIDEO.md).+//+// Every 2 s, while a video plays in a visible tab, it reads video.getVideoPlaybackQuality(). If more+// than 15 % of the frames of the last 2 s were dropped, three samples in a row (6 s), the video is+// stuttering: with "Lower quality automatically" (autoLower, off by default) the quality goes one+// step down by itself and a short notice says so; otherwise a small notice offers to do it. The+// notice can be dismissed, and then it doesn't come back in this tab. Nothing leaves the browser.+/* global lordosVideo */+(() => {+ if (window.__lordosStutter) return;+ window.__lordosStutter = true;+ const api = lordosVideo.api;+ const msg = (k, subs) => api.i18n.getMessage(k, subs) || k;++ const SAMPLE_MS = 2000;+ const DROP_RATIO = 0.15;+ const SAMPLES = 3;+ const MIN_FRAMES = 20; // per sample: a paused or tiny video doesn't count+ const SETTLE_MS = 6000; // after play, seek or a quality change: the player is rebuffering+ const AUTO_COOLDOWN_MS = 20000;++ // The policy, also for page.js: which codecs to hold back (it runs in the page's world, which can't+ // read the extension's storage). A change made while the page is open counts from the next video.+ let policy = lordosVideo.normalize(null);+ const load = () => lordosVideo.read().then((p) => {+ policy = p;+ document.dispatchEvent(new CustomEvent('lordos-video-codecs', { detail: lordosVideo.blocked(p).join(',') }));+ });+ load();+ api.storage.onChanged.addListener((_c, area) => { if (area === 'managed') load(); });++ let dismissed = false;+ let last = null; // { video, total, dropped }+ let bad = 0;+ let quietUntil = Date.now() + SETTLE_MS;+ let lastAuto = 0;+ let host = null;++ const settle = () => { quietUntil = Date.now() + SETTLE_MS; bad = 0; last = null; };+ for (const ev of ['play', 'seeking', 'ratechange', 'loadstart', 'resize']) document.addEventListener(ev, settle, true);++ function playing() {+ let best = null;+ for (const v of document.querySelectorAll('video')) {+ if (v.paused || v.ended || v.readyState < 3 || typeof v.getVideoPlaybackQuality !== 'function') continue;+ if (!best || v.videoWidth * v.videoHeight > best.videoWidth * best.videoHeight) best = v;+ }+ return best;+ }++ function lowerOnce() {+ return new Promise((resolve) => {+ const done = (e) => { document.removeEventListener('lordos-video-lowered', done); clearTimeout(t); resolve(typeof e?.detail === 'string' ? e.detail : ''); };+ const t = setTimeout(done, 1500);+ document.addEventListener('lordos-video-lowered', done);+ document.dispatchEvent(new CustomEvent('lordos-video-lower'));+ });+ }++ function hide() { if (host) { host.remove(); host = null; } }++ // A small card at the bottom of the page (or of the player in fullscreen), in a closed shadow+ // root so the site's styles don't reach it.+ function show(text, actions) {+ hide();+ host = document.createElement('div');+ const root = host.attachShadow({ mode: 'closed' });+ // built node by node: the site's Trusted Types policy refuses HTML strings+ const style = document.createElement('style');+ style.textContent = `+ .card { position: fixed; inset-inline-start: 16px; bottom: 16px; z-index: 2147483647; max-width: 360px;+ display: flex; gap: 10px; align-items: center; flex-wrap: wrap; padding: 10px 12px;+ background: rgba(28, 28, 32, .94); color: #f2f2f7; border-radius: 12px;+ font: 13px/1.35 system-ui, sans-serif; box-shadow: 0 6px 24px rgba(0, 0, 0, .35); }+ .text { flex: 1 1 200px; }+ button { font: inherit; border: 0; border-radius: 8px; padding: 5px 10px; cursor: pointer;+ background: rgba(255, 255, 255, .14); color: inherit; }+ button.main { background: #0a84ff; color: #fff; }+ button:focus-visible { outline: 2px solid #64d2ff; outline-offset: 1px; }`;+ const card = document.createElement('div');+ card.className = 'card';+ card.setAttribute('role', 'status');+ card.setAttribute('aria-live', 'polite');+ const span = document.createElement('span');+ span.className = 'text';+ span.textContent = text;+ card.appendChild(span);+ root.append(style, card);+ for (const a of actions) {+ const b = document.createElement('button');+ b.textContent = a.label;+ if (a.main) b.className = 'main';+ b.addEventListener('click', a.run);+ card.appendChild(b);+ }+ (document.fullscreenElement || document.documentElement).appendChild(host);+ }++ const dismiss = { label: msg('dismiss'), run: () => { dismissed = true; hide(); } };++ async function stuttering() {+ if (policy.autoLower) {+ if (Date.now() - lastAuto < AUTO_COOLDOWN_MS) return;+ lastAuto = Date.now();+ const q = await lowerOnce();+ settle();+ if (q && !dismissed) {+ show(msg('lowered', [q]), [dismiss]);+ setTimeout(hide, 8000);+ }+ return;+ }+ if (dismissed || host) return;+ show(msg('stutter'), [+ { label: msg('lower'), main: true, run: async () => {+ const q = await lowerOnce();+ settle();+ if (q) { show(msg('lowered', [q]), [dismiss]); setTimeout(hide, 6000); } else show(msg('lowerManual'), [dismiss]);+ } },+ dismiss,+ ]);+ }++ setInterval(() => {+ if (document.visibilityState !== 'visible') { last = null; return; }+ const v = playing();+ if (!v) { last = null; bad = 0; return; }+ const q = v.getVideoPlaybackQuality();+ const now = { video: v, total: q.totalVideoFrames, dropped: q.droppedVideoFrames };+ const prev = last;+ last = now;+ if (!prev || prev.video !== v || Date.now() < quietUntil) return;+ const total = now.total - prev.total, dropped = now.dropped - prev.dropped;+ if (total < MIN_FRAMES || dropped < 0) return;+ bad = dropped / total > DROP_RATIO ? bad + 1 : 0;+ if (bad >= SAMPLES) { bad = 0; stuttering(); }+ }, SAMPLE_MS);+})();diff --git a/assets/locales/en/prefs.json b/assets/locales/en/prefs.jsonindex 6f19f29..69d0816 100644--- a/assets/locales/en/prefs.json+++ b/assets/locales/en/prefs.json@@ -243,5 +243,22 @@"time.synced": "Synchronized with the network time servers (systemd-timesyncd).","time.syncing": "Waiting for the first synchronization…","time.zone": "Time zone",- "time.zoneFooter": "Chosen by hand: LordOS never looks up your location on the network."+ "time.zoneFooter": "Chosen by hand: LordOS never looks up your location on the network.",+ "video.autoLower": "Lower quality automatically when video stutters",+ "video.autoLowerHint": "Without it, the browser shows a small notice offering to lower it.",+ "video.checking": "Checking what this computer decodes in hardware…",+ "video.codecsBoth": "VP9 or AV1",+ "video.footer": "H.264 takes far less work to decode without a hardware decoder, so video plays smoothly. Applies to every user of this computer and to pages opened from now on (some browsers only after a restart). Nothing is sent anywhere.",+ "video.mode.always": "Always",+ "video.mode.auto": "Automatic",+ "video.mode.never": "Never",+ "video.optimize": "Optimize video for this computer",+ "video.reason.noDriver": "no video decoding driver",+ "video.reason.noProfiles": "the graphics card doesn’t support them",+ "video.reason.virtualGpu": "virtual graphics card",+ "video.statusAlways": "On: video sites are asked for H.264 on this computer.",+ "video.statusAuto": "On: this computer can’t decode {codecs} in hardware ({reason}), so video sites are asked for H.264.",+ "video.statusHardware": "Off: this computer decodes VP9 and AV1 video in hardware.",+ "video.statusNever": "Off: video sites choose the format, even when the computer has to decode it without help.",+ "video.title": "Video in the browser"}diff --git a/assets/locales/en/settings.json b/assets/locales/en/settings.jsonindex 1af155a..eeaa22c 100644--- a/assets/locales/en/settings.json+++ b/assets/locales/en/settings.json@@ -242,7 +242,7 @@"section.notifications": "Notifications","section.datetime": "Date & Time","section.defaultapps": "Default Apps",- "keywords.displays": "display monitor screen resolution refresh rate hz rotation brightness night shift color temperature edid",+ "keywords.displays": "display monitor screen resolution refresh rate hz rotation brightness night shift color temperature edid video browser codec h264 vp9 av1 stutter","keywords.bluetooth": "bluetooth pair pairing headphones headset speaker keyboard mouse wireless","keywords.power": "battery energy power profile low power performance sleep suspend lid power button screen off","keywords.notifications": "notifications alerts banners do not disturb focus sound",diff --git a/assets/locales/es/prefs.json b/assets/locales/es/prefs.jsonindex fbc0dac..d7ead97 100644--- a/assets/locales/es/prefs.json+++ b/assets/locales/es/prefs.json@@ -243,5 +243,22 @@"time.synced": "Sincronizada con los servidores de hora de la red (systemd-timesyncd).","time.syncing": "Esperando la primera sincronización…","time.zone": "Zona horaria",- "time.zoneFooter": "Se elige a mano: LordOS nunca busca tu ubicación en la red."+ "time.zoneFooter": "Se elige a mano: LordOS nunca busca tu ubicación en la red.",+ "video.autoLower": "Bajar la calidad automáticamente cuando el video se traba",+ "video.autoLowerHint": "Si está apagado, el navegador muestra un aviso chico que ofrece bajarla.",+ "video.checking": "Viendo qué decodifica esta computadora por hardware…",+ "video.codecsBoth": "VP9 ni AV1",+ "video.footer": "H.264 cuesta mucho menos de decodificar sin un decodificador por hardware, así el video se ve fluido. Vale para todos los usuarios de esta computadora y para las páginas que se abran desde ahora (algunos navegadores, recién al reiniciarse). No se envía nada a ningún lado.",+ "video.mode.always": "Siempre",+ "video.mode.auto": "Automático",+ "video.mode.never": "Nunca",+ "video.optimize": "Optimizar el video para esta computadora",+ "video.reason.noDriver": "no hay un controlador de decodificación de video",+ "video.reason.noProfiles": "la tarjeta gráfica no los soporta",+ "video.reason.virtualGpu": "tarjeta gráfica virtual",+ "video.statusAlways": "Encendido: en esta computadora se les pide H.264 a los sitios de video.",+ "video.statusAuto": "Encendido: esta computadora no puede decodificar {codecs} por hardware ({reason}), así que se les pide H.264 a los sitios de video.",+ "video.statusHardware": "Apagado: esta computadora decodifica video VP9 y AV1 por hardware.",+ "video.statusNever": "Apagado: los sitios de video eligen el formato, aunque la computadora lo tenga que decodificar sin ayuda.",+ "video.title": "Video en el navegador"}diff --git a/assets/locales/es/settings.json b/assets/locales/es/settings.jsonindex 0cc086f..7302e27 100644--- a/assets/locales/es/settings.json+++ b/assets/locales/es/settings.json@@ -242,7 +242,7 @@"section.notifications": "Notificaciones","section.datetime": "Fecha y hora","section.defaultapps": "Apps por defecto",- "keywords.displays": "pantalla monitor resolución frecuencia hz rotación girar brillo night shift noche temperatura color edid",+ "keywords.displays": "pantalla monitor resolución frecuencia hz rotación girar brillo night shift noche temperatura color edid video navegador códec h264 vp9 av1 trabado","keywords.bluetooth": "bluetooth vincular emparejar auriculares parlante teclado mouse inalámbrico","keywords.power": "batería energía perfil ahorro rendimiento suspender reposo tapa botón de encendido apagar pantalla","keywords.notifications": "notificaciones avisos alertas carteles no molestar concentración sonido",diff --git a/assets/locales/pt/prefs.json b/assets/locales/pt/prefs.jsonindex 81167c1..b2c251d 100644--- a/assets/locales/pt/prefs.json+++ b/assets/locales/pt/prefs.json@@ -243,5 +243,22 @@"time.synced": "Sincronizado com os servidores de hora da rede (systemd-timesyncd).","time.syncing": "Aguardando a primeira sincronização…","time.zone": "Fuso horário",- "time.zoneFooter": "Escolhido manualmente: o LordOS nunca busca sua localização na rede."+ "time.zoneFooter": "Escolhido manualmente: o LordOS nunca busca sua localização na rede.",+ "video.autoLower": "Baixar a qualidade automaticamente quando o vídeo travar",+ "video.autoLowerHint": "Se estiver desligado, o navegador mostra um pequeno aviso oferecendo baixá-la.",+ "video.checking": "Verificando o que este computador decodifica por hardware…",+ "video.codecsBoth": "VP9 nem AV1",+ "video.footer": "O H.264 dá muito menos trabalho para decodificar sem um decodificador por hardware, então o vídeo roda sem travar. Vale para todos os usuários deste computador e para as páginas abertas daqui em diante (alguns navegadores, só depois de reiniciar). Nada é enviado para lugar nenhum.",+ "video.mode.always": "Sempre",+ "video.mode.auto": "Automático",+ "video.mode.never": "Nunca",+ "video.optimize": "Otimizar o vídeo para este computador",+ "video.reason.noDriver": "não há driver de decodificação de vídeo",+ "video.reason.noProfiles": "a placa de vídeo não os suporta",+ "video.reason.virtualGpu": "placa de vídeo virtual",+ "video.statusAlways": "Ligado: neste computador os sites de vídeo recebem o pedido de H.264.",+ "video.statusAuto": "Ligado: este computador não consegue decodificar {codecs} por hardware ({reason}), então os sites de vídeo recebem o pedido de H.264.",+ "video.statusHardware": "Desligado: este computador decodifica vídeo VP9 e AV1 por hardware.",+ "video.statusNever": "Desligado: os sites de vídeo escolhem o formato, mesmo quando o computador precisa decodificá-lo sem ajuda.",+ "video.title": "Vídeo no navegador"}diff --git a/assets/locales/pt/settings.json b/assets/locales/pt/settings.jsonindex 335f1d1..f59be48 100644--- a/assets/locales/pt/settings.json+++ b/assets/locales/pt/settings.json@@ -242,7 +242,7 @@"section.notifications": "Notificações","section.datetime": "Data e hora","section.defaultapps": "Apps padrão",- "keywords.displays": "tela monitor resolução taxa hz rotação brilho night shift noite temperatura cor edid",+ "keywords.displays": "tela monitor resolução taxa hz rotação brilho night shift noite temperatura cor edid vídeo navegador codec h264 vp9 av1 travando","keywords.bluetooth": "bluetooth parear fones alto-falante teclado mouse sem fio","keywords.power": "bateria energia perfil economia desempenho repouso suspender tampa botão liga desliga tela","keywords.notifications": "notificações avisos alertas faixas não perturbe foco som",diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex c9939e9..537e83a 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -51,6 +51,7 @@ like React Native but on top of our display server.| `server/src/print/`, `js_print.c`, `sdk/printdialog.jsx`, `apps/scanner` | **M9** | Printing: our own IPP client against CUPS, our own mDNS, eSCL scanners, the system print dialog (see `PRINTING.md`) || `server/src/media/`, `js_media.c`, `sdk/media.js`, `apps/{photos,player,screenshots,camera,recorder}` | **M9** | Media: the sandboxed helper `lord-media` (FFmpeg, libva) and the Photos, Player, Screenshots, Camera and Recorder apps; `media` node, audio over shared memory with the PipeWire stream in lord-server, protected windows in screenshots, recording and remote desktop (see `MEDIA.md`) || `server/src/netperm/`, `server/src/fw/`, `js_fw.c` | **M8** | Per-app firewall: the root service `lord-netperm` enforces the rules with cgroup BPF in the sessions; Rule column in the Monitor and Trusted / Restricted apps in Settings (see `FIREWALL.md`) |+| `server/src/media/hwdec.c`, `sdk/video.js`, `assets/browser/video/` | **0.8.2** | Video in the browser without hardware decoding: per-boot VP9/AV1 decoding probe, the closed admin action `video-optimize` and LordOS's own Chromium extension that asks YouTube for H.264 and offers a lower quality when video stutters (see `VIDEO.md`) || `server/src/fan/`, `js_fan.c`, `sdk/cooling.jsx` | **M8** | Fans: the root service `lord-fand` drives them by temperature; Settings → Cooling and Monitor → Cooling (see `FANS.md`) || `server/src/monitor/`, `js_monitor.c`, `apps/monitor/` | **M8** | Monitor: CPU, memory, network, disks, processes and per-app connections with a map; its own thread only while the app is open, sock_diag and country by IP from a local database (see `MONITOR.md`) || `server/src/vault/`, `js_vault.c`, `sdk/vault.js`, `apps/passwords` | **M9** | Passwords and the system keyring: the sandboxed helper `lord-vault` (Monocypher: XChaCha20-Poly1305, Argon2id), own `.lvault` format, FIDO2/CTAP2 client, session keyring opened at login, Secret Service on D-Bus with own code (see `PASSWORDS.md`) |diff --git a/docs/MEDIA.md b/docs/MEDIA.mdindex 98cd301..01087cb 100644--- a/docs/MEDIA.md+++ b/docs/MEDIA.md@@ -75,7 +75,9 @@ We took the way the apps of popular desktop systems work, never their logos or tothers. It takes no arguments, the environment is minimal and the socket goes on fd 3. There isone per player, camera or recording, and two *workers* for short jobs (thumbnails and probes inthe background; images, edits and exports in the foreground). Workers exit on their own after- 20 s without work.+ 20 s without work. A one-shot `MK_HWPROBE` helper lists, once per boot, which codecs VA-API+ decodes on the render nodes it gets (`lm_hwprobe.c`, for "Video in the browser": see+ [VIDEO.md](VIDEO.md)).- **It never receives a path.** lord-server validates each path with the same rules as `lord.fs`(home folder and the user's mounts), opens the file and passes it the fd.- Outputs are created as temporary files next to the destination. When they finish well they'rediff --git a/docs/SETTINGS.md b/docs/SETTINGS.mdindex 7c03c1d..012b30b 100644--- a/docs/SETTINGS.md+++ b/docs/SETTINGS.md@@ -44,7 +44,7 @@ the time fields keep `direction: 'ltr'`.│▼ root work: closed admin actions (hw/hw_admin.c)admin.c ─ display-brightness, power-profile, power-suspend, power-buttons, time-ntp, time-set,- bt-unblock, rpi-case+ bt-unblock, rpi-case, video-optimizeCooling: lord.fan (ui/js_fan.c) ── /run/lordos/fand.sock ── lord-fand (root service, src/fan)```@@ -121,6 +121,11 @@ timer that sleeps until the next change (30 s steps only during the 30-minute fa+- **Video in the browser.** "Optimize video for this computer" (Automatic, Always, Never) and+ "Lower quality automatically when video stutters": when the hardware can't decode VP9 or AV1,+ the browsers are asked for H.264 (`Video.jsx`, `sdk/video.js`, the closed admin action+ `video-optimize`). See [VIDEO.md](VIDEO.md).+Schedule: off, **sunset to sunrise** or **custom hours**, with a 30-minute fade, plus "Turn onnow" (until the end of tonight's schedule, or 07:00). Sunrise and sunset come from the Almanacfor Computers algorithm (`night_sun_times`, within ±4 min of NOAA in the tests) at thediff --git a/docs/VIDEO.md b/docs/VIDEO.mdnew file mode 100644index 0000000..a35661a--- /dev/null+++ b/docs/VIDEO.md@@ -0,0 +1,217 @@+# Video in the browser without hardware decoding++Video sites send VP9 or AV1 when the browser says it can play them. Without a hardware decoder+for those codecs the browser decodes them on the processor, and on a slow or shared processor the+video stutters. The real case that started this: a LordOS virtual machine on VMware, YouTube at+1080p in AV1, decoded by Chromium in software (`media-internals`: `kIsPlatformVideoDecoder` false,+`Dav1dVideoDecoder`), the tab at about 68 % CPU and the video choppy. The Raspberry Pi 5 has no+hardware decoder for H.264, VP9 or AV1 (only HEVC), and many older PCs lack VP9 or AV1 decoding.++H.264 costs far less to decode in software. Since 0.8.2 LordOS finds out at every boot what the+hardware decodes and, when VP9 or AV1 is missing, asks the browsers for H.264 instead. When a video+still drops frames, a small notice offers a lower quality.++| Settings → Displays → Video in the browser | The notice when a video stutters | After "Lower quality" |+|---|---|---|+|  |  |  |++Nothing here touches the network or reports anything: the decision is made on the computer and the+browsers read it from local files.++## How it fits together++```+ boot ──▶ lord-server (session) lord-media (sandboxed helper)+ media/hwdec.c ── render nodes (open fds) ──▶ lm_hwprobe.c: VA-API profiles with the+ · virtual GPU? (DRM driver name) decode (VLD) entrypoint → JSON+ · V4L2 m2m decoders (/dev/videoN)+ · cache ~/.cache/lordos/video-hw.json (per boot_id)+ │ lord.media.hwDecode()+ ▼+ sdk/video.js (at login and when the setting changes)+ │ admin.run('video-optimize', '<mode> <on|off> <vp9 yes|no> <av1 yes|no>')+ ▼+ admin helper (root, hw/hw_admin.c): fixed text only+ /etc/chromium/policies/managed/lordos-video.json ── managed storage of the extension+ /etc/firefox-esr/lordos-video.js ── a default pref (AV1 off)+ │+ ▼+ Chromium + /usr/share/chromium/extensions/lordos-video (Debian loads every folder there)+ stutter.js (extension world) ── reads the policy ── tells page.js which codecs to hold back+ page.js (page world) ── MediaSource / canPlayType / mediaCapabilities say "no"+```++## 1. Detecting hardware decoding (`server/src/media/hwdec.c`)++Asked once per boot (the first `lord.media.hwDecode()` call starts it; `sdk/video.js` makes that+call at login) and cached in `~/.cache/lordos/video-hw.json` with `/proc/sys/kernel/random/boot_id`,+because a live USB boots on a different computer each time.++1. **Virtual GPU:** each `/dev/dri/renderD*` is opened and its DRM driver asked with+ `DRM_IOCTL_VERSION`. `virtio_gpu`, `vmwgfx`, `qxl`, `bochs-drm`, `cirrus`, `hyperv_drm`,+ `vboxvideo`, `simpledrm`, `vkms` are virtual: no hardware decoding, without asking further. A+ virtual machine with a real GPU passed through (`i915`, `amdgpu`, …) is probed like any other+ computer. The machine's own name (DMI vendor and product, the CPU `hypervisor` flag) is only+ reported (`"vm"`), not used for the decision.+2. **VA-API:** the real render nodes (up to four) go as open descriptors to `lord-media` (job+ `MK_HWPROBE`, `server/src/media/helper/lm_hwprobe.c`), the only binary that links libva. It+ locks itself in its usual sandbox first (`sandbox_apply_helper`, with the DRM ioctls), then+ lists the profiles and keeps those with the `VAEntrypointVLD` (decode) entrypoint: VP9 profile+ 0/2, AV1 profile 0, H.264 and HEVC. A helper that doesn't answer within 5 s counts as "no".+3. **V4L2 (ARM boards):** every `/dev/videoN` with the memory-to-memory capability is asked for+ the formats of its OUTPUT queue: `VP9F`/`AV1F`/`S264`/`S265` (stateless) and+ `VP90`/`AV01`/`H264`/`HEVC` (stateful). On the Raspberry Pi 5 only HEVC shows up. Cameras and+ other capture devices don't have that capability and are closed right away.++The answer (`lord.media.hwDecode()`):++```json+{"boot":"f31202b8-…","vm":"qemu","gpu":"virtio_gpu","virtualGpu":true,"vaapi":false,"vendor":"",+ "v4l2":false,"vp9":false,"av1":false,"h264":false,"hevc":false,"reason":"virtualGpu"}+```++`reason` is `ok`, `virtualGpu`, `noDriver` (no VA-API driver and no V4L2 decoder) or `noProfiles`.+`LORD_MEDIA_HW=0` (no hardware decoding for LordOS's own player) also makes this answer "no".++`build/hwdec-test` checks the virtual GPU list and the virtual machine names.++## 2. The setting (Settings → Displays → Video in the browser)++- **Optimize video for this computer:** **Automatic** (default: on only for the codecs the+ hardware can't decode), **Always** (hold back VP9 and AV1), **Never**. The line under it says+ what is happening and why ("On: this computer can't decode VP9 or AV1 in hardware (virtual+ graphics card), so video sites are asked for H.264").+- **Lower quality automatically when video stutters:** off by default; without it the browser+ only shows the notice.++Stored per user in `settings.json` as `video: { mode, autoLower }` (`sdk/video.js`). The browsers'+files are system-wide, so the setting applies to every user of the computer; the last session to+log in or change it wins. Code: `apps/settings/Video.jsx`.++### The admin action `video-optimize`++`video-optimize <auto|always|never> <on|off> <yes|no> <yes|no>` (the last two: hardware VP9 and AV1+decoding found this boot), marked `A_ANYONE` like `power-profile`: it only chooses between fixed+texts, so it needs no administrator. Every value is checked against its closed list on the root side+(`hw_video_files` in `server/src/hw/hw_admin.c`, tested in `build/settings-hw-test`), and it writes,+through a temporary file and `rename`, only when the text changes:++- `/etc/chromium/policies/managed/lordos-video.json`: the extension's managed storage+ (`"3rdparty" → "extensions" → kadhcpnkalbaminbojfmbmlgoheicmjo`): `mode`, `autoLower`, `hwVp9`,+ `hwAv1`. The extension makes the decision.+- `/etc/firefox-esr/lordos-video.js` (only if `/etc/firefox-esr` exists): `pref("media.av1.enabled",+ false);` when AV1 is held back, nothing otherwise.++Neither is a conffile: the package doesn't ship them, and its `postrm` removes them.++## 3. The extension (`assets/browser/video/`)++Written for LordOS (MIT), no third-party code. Installed by the `lordos` package into+`/usr/share/chromium/extensions/lordos-video/`; Debian's Chromium wrapper (`/etc/chromium.d/extensions`)+passes every folder there to `--load-extension`, the same way Debian's own `webext-*` packages+work. The manifest carries a public `key`, so its id is always `kadhcpnkalbaminbojfmbmlgoheicmjo`+(the id the policy names). No background page, no network permission, only `storage`.++| File | World | What it does |+|---|---|---|+| `page.js` | the page's, at `document_start` | wraps `MediaSource.isTypeSupported` (and `ManagedMediaSource`), `HTMLMediaElement.canPlayType` and `navigator.mediaCapabilities.decodingInfo` so they answer "not supported" for the held-back codecs (`vp09`/`vp9`, `av01`/`av1`); lowers the player's quality one step when asked |+| `policy.js` | the extension's | reads the managed policy and decides: Never → nothing, Always → VP9 and AV1, Automatic → the codecs with `hwVp9`/`hwAv1` false; without a policy (another system) → nothing |+| `stutter.js` | the extension's, at `document_start` | tells `page.js` the decision (a `lordos-video-codecs` event: the page's world can't read the policy), then watches the playing video's `getVideoPlaybackQuality()` |++**Scope: YouTube only** (`www.`, `m.`, `music.` and `youtube-nocookie.com`, also embedded in other+sites through its iframe). It is where the problem shows up most and where we can test it; the+quality can only be lowered where the player has an API for it. Other sites can be added to the+manifest's `matches` once tested.++The decision reaches `page.js` a few milliseconds after the page starts, long before the site's+player script loads and asks; tested by starting Chromium straight on a YouTube address. A policy+change is picked up by Chromium while it runs (it watches its policy folder) and counts from the+next page load; tested going from Always to Never within 5 s.++**Stutter detection.** Every 2 s, while a video plays in a visible tab: if more than 15 % of the+frames of the last 2 s were dropped, three samples in a row (6 s), and at least 20 frames went by+per sample, the video stutters. Playing, seeking or a size change (a new quality) restarts the+count after 6 s. Then:++- **Lower quality automatically off (default):** a small card at the bottom of the page (or of the+ player in fullscreen), "This video is stuttering. A lower quality may play smoothly." with+ **Lower quality** and **Dismiss**. Dismissed, it doesn't come back in that tab.+- **On:** the quality goes one step down by itself (at most every 20 s, never below 360p) and a+ short card says "Quality lowered to 720p so the video plays smoothly."++The card is built node by node in a closed shadow root (the site's Trusted Types policy refuses+HTML strings, and the site's styles don't reach it). Its texts come from the extension's own+`_locales/{en,es,pt}`, following the browser's language.++## 4. Firefox ESR++Debian's `firefox-esr` only installs signed extensions. Tested on VM 122 with Firefox ESR 153:+the same extension (`manifest.firefox.json`, id `[email protected]`) forced through+`/usr/lib/firefox-esr/distribution/policies.json` (`ExtensionSettings`, `force_installed`, a local+`file://` XPI) is refused, and+`about:policies` shows "Not fully applied"; with `xpinstall.signatures.required` set to false it+installs and runs. LordOS doesn't turn signature checking off for every extension to get this.++So for now Firefox gets only what a preference can do: `media.av1.enabled = false` (a default+pref in `/etc/firefox-esr/lordos-video.js`, which the user can still change in `about:config`).+YouTube then sends VP9, which costs less than AV1. VP9 has no switch of its own in Firefox:+`media.mediasource.vp9.enabled` doesn't change what `MediaSource.isTypeSupported` answers for WebM,+and `media.webm.enabled` would turn off every WebM video. There is no stutter notice in Firefox.++**Follow-up:** sign the extension on addons.mozilla.org as an unlisted add-on (self-distribution;+needs the maintainer's account), ship the signed XPI and force it with Firefox's `policies.json`+(`ExtensionSettings` with a local `install_url`; the distribution folder above is the one this+Firefox was seen reading), and its+settings with `"3rdparty": {"Extensions": {"[email protected]": {…}}}` in the same file (the root+action would then write that file). To build the XPI to sign:++```sh+cd assets/browser/video && mkdir -p /tmp/xpi && cp -r _locales *.js *.png schema.json /tmp/xpi/ &&+ cp manifest.firefox.json /tmp/xpi/manifest.json && (cd /tmp/xpi && zip -r ../lordos-video.xpi .)+```++## Measurements (VM 122)++Proxmox q35 VM, 4 vCPUs of a Xeon Silver 4108 (1.8 GHz), virtio-gpu without 3D (so: no hardware+decoding, `reason: virtualGpu`), LordOS compositing on the CPU, the browser window not maximized. YouTube, quality+forced through the player. CPU is the whole browser process tree over 20 s, in % of one core+(400 % = all four). Decoder names from Chromium's media-internals (DevTools `Media` domain), codecs+from the player's own statistics. The host is shared with other VMs, so runs vary; each cell lists+every run.++| Browser | Video | Without (Never) | With (Automatic) |+|---|---|---|---|+| Chromium 155 | 1080p60 (Big Buck Bunny) | AV1, `Dav1dVideoDecoder`: 147, 143, 125, 98 % | H.264, `FFmpegVideoDecoder`: 108, 99, 92 % |+| Chromium 155 | 1080p25 (music video) | AV1, `Dav1dVideoDecoder`: 88, 74, 73 % | H.264, `FFmpegVideoDecoder`: 64, 61, 59 % |+| Firefox ESR 153 | 1080p60 | AV1: 112 % | VP9: 88 % |+| Firefox ESR 153 | 1080p25 | AV1: 64 % | VP9: 47 % |++`kIsPlatformVideoDecoder` is false in every case (there is no hardware decoder here). On this+processor (AVX-512, where dav1d is fast) H.264 saves about a fifth to a quarter of the browser's CPU;+the gain is larger on older processors without wide vector units, where AV1 in software is much+slower. At 1080p60 this VM drops 40–55 % of the frames with either codec, because the composition of+a full-HD 60 fps window on the CPU is the bigger cost there: that is where the notice and "Lower+quality automatically" help (tested: the notice appears within about 15 s, and "Lower quality" and+the automatic mode both go from 1080p to 720p). At 25 fps both play smoothly (1–2 % dropped).++## Limitations++- Only YouTube. Other sites keep VP9/AV1 until they are added and tested.+- Firefox: AV1 off only (VP9 stays, no notice) until the extension is signed.+- Automatic trusts the system probe: if VA-API lists VP9/AV1 but the browser doesn't actually use+ the hardware decoder, the video is still decoded in software; choose **Always** there.+ Not tested on a machine with real hardware decoding (no GPU on the test host).+- H.264 on YouTube stops at 1080p; with the optimization on, higher resolutions aren't offered.+- The setting is system-wide (the browsers read system files); several users share it.+- A policy change counts from the next page load; Firefox needs a restart.++## Testing++```sh+make -C server test # settings-hw-test (video-optimize), hwdec-test+node tools/i18n-check.mjs+```++On a VM: log in, then `cat ~/.cache/lordos/video-hw.json` and the two files above. On a YouTube+page in Chromium, `MediaSource.isTypeSupported('video/webm; codecs="vp9"')` answers false when VP9+is held back.diff --git a/docs/video-lowered.png b/docs/video-lowered.pngnew file mode 100644index 0000000..dff75a2Binary files /dev/null and b/docs/video-lowered.png differdiff --git a/docs/video-notice.png b/docs/video-notice.pngnew file mode 100644index 0000000..f1b1d2eBinary files /dev/null and b/docs/video-notice.png differdiff --git a/docs/video-settings.png b/docs/video-settings.pngnew file mode 100644index 0000000..ce9ebb3Binary files /dev/null and b/docs/video-settings.png differdiff --git a/sdk/index.js b/sdk/index.jsindex 8827657..da17311 100644--- a/sdk/index.js+++ b/sdk/index.js@@ -36,6 +36,8 @@ import { askPower, canPower } from './power.jsx';export { PowerDialog, powerAsk, POWER_SECONDS } from './power.jsx';import { EmojiPanel } from './emoji.jsx';export { admin } from './admin.js';+export { videoPrefs, setVideoPrefs, videoHardware, videoError, videoOptimizing, VIDEO_MODES, VIDEO_DEFAULTS } from './video.js'; // docs/VIDEO.md+import { startVideo } from './video.js';export { errorText, statusText, codeError, parseCode } from './errors.js';export { logs } from './logs.js';export { LordOSLogo, LordOSGlyph, LordOSWordmark } from './logo.js';@@ -172,6 +174,7 @@ export function startShell(element) {startReminders(); // calendar and reminder alarms, with the apps closedmaybeStartTour(); // "Welcome to LordOS", the first timestartHardware(); // Night Light, idle timers, battery in the menu bar (hardware.jsx)+ startVideo(); // browser video without hardware decoding (video.js, docs/VIDEO.md)}// Changing the language remounts the whole interface (windows, tabs anddiff --git a/sdk/video.js b/sdk/video.jsnew file mode 100644index 0000000..83a532c--- /dev/null+++ b/sdk/video.js@@ -0,0 +1,70 @@+// video.js — "Optimize video for this computer" (Settings → Displays; docs/VIDEO.md).+//+// When the computer can't decode VP9 or AV1 in hardware (most virtual machines, older PCs, the+// Raspberry Pi 5), video sites that send those codecs make the browser decode them on the CPU and+// the video stutters. LordOS then asks the browsers for H.264 instead:+// - lord.media.hwDecode() says what the hardware decodes (src/media/hwdec.c, once per boot);+// - the closed admin action video-optimize writes the browsers' settings from fixed text+// (Chromium: the managed policy of LordOS's own extension, assets/browser/video; Firefox ESR:+// a default pref), at login and whenever the setting changes.+// settings.video = { mode: 'auto' | 'always' | 'never', autoLower: false }. Nothing leaves the computer.+import { settings } from './settings.js';+import { admin } from './admin.js';+import { createStore } from './store.js';++export const VIDEO_DEFAULTS = { mode: 'auto', autoLower: false };+export const VIDEO_MODES = ['auto', 'always', 'never'];++// What lord.media.hwDecode() answered (null while it is being found out).+export const videoHardware = createStore(null);+// The last error of video-optimize (a translated message) or ''.+export const videoError = createStore('');++export function videoPrefs(s = settings.get()) {+ const v = s.video || {};+ return {+ mode: VIDEO_MODES.includes(v.mode) ? v.mode : VIDEO_DEFAULTS.mode,+ autoLower: typeof v.autoLower === 'boolean' ? v.autoLower : VIDEO_DEFAULTS.autoLower,+ };+}++export function setVideoPrefs(patch) {+ settings.set((s) => ({ ...s, video: { ...videoPrefs(s), ...patch } }));+}++// The admin action's argument: "<mode> <on|off> <vp9 yes|no> <av1 yes|no>".+export function videoArg(prefs, hw) {+ return `${prefs.mode} ${prefs.autoLower ? 'on' : 'off'} ${hw?.vp9 ? 'yes' : 'no'} ${hw?.av1 ? 'yes' : 'no'}`;+}++// Is the optimization on right now? With Automatic, only when VP9 or AV1 lacks hardware decoding.+export function videoOptimizing(prefs, hw) {+ if (prefs.mode === 'always') return true;+ if (prefs.mode === 'never') return false;+ return !!hw && !(hw.vp9 && hw.av1);+}++let applied = '';+function apply() {+ const hw = videoHardware.get();+ if (!hw) return;+ const arg = videoArg(videoPrefs(), hw);+ if (arg === applied) return;+ applied = arg;+ admin.run('video-optimize', arg, undefined, { quiet: true }).then(() => videoError.set(''), (e) => {+ applied = '';+ videoError.set(e.message);+ });+}++export function startVideo() {+ if (!lord.media?.hwDecode || !lord.admin?.available()) return;+ let tries = 0;+ const poll = () => {+ const hw = lord.media.hwDecode();+ if (hw) { videoHardware.set(hw); apply(); return; }+ if (++tries < 40) setTimeout(poll, 250); // lord-media answers in well under a second+ };+ poll();+ settings.subscribe(apply);+}diff --git a/server/Makefile b/server/Makefileindex 832ff4f..b172b48 100644--- a/server/Makefile+++ b/server/Makefile@@ -50,7 +50,7 @@ QJS_OBJ := $(patsubst %,build/qjs/%.o,quickjs libregexp libunicode cutils dtoa)# Monitor: metrics, connections and the country of an IP (src/monitor, see docs/MONITOR.md)MON_SRC := src/monitor/mon.c src/monitor/conn.c src/monitor/procctl.c src/monitor/proc_admin.c src/monitor/mmdb.c src/monitor/map.c src/ui/js_monitor.c# Media (src/media, docs/MEDIA.md): only the lord-server side. Only lord-media links FFmpeg.-MEDIA_SRC := src/media/media.c src/media/mview.c src/media/capture.c src/media/annot.c src/media/maudio.c src/media/mpulse.c src/media/proto.c src/ui/js_media.c+MEDIA_SRC := src/media/media.c src/media/hwdec.c src/media/mview.c src/media/capture.c src/media/annot.c src/media/maudio.c src/media/mpulse.c src/media/proto.c src/ui/js_media.cSEC_SRC := src/sec/json.c src/sec/sign.c src/sec/pkgstate.c src/sec/perms.c src/sec/cgroup.c src/sec/sandbox.c src/sec/brokersrv.c src/sec/brokercam.c src/sec/brokerkr.c src/sec/restrict.c src/sec/appid.c src/sec/pwguard.c# App mode: lord-server --app <id> runs an .lpk app as an isolated Wayland client (src/app)APP_SRC := src/app/appclient.c src/app/appspawn.c src/ui/js_broker.c src/ui/js_brokercam.c@@ -504,3 +504,9 @@ build/homedirs-test: tests/homedirs_test.c src/users/homedirs.c src/users/homedi@mkdir -p build$(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/homedirs_test.c src/users/homedirs.c./$@ || { rm -f $@; exit 1; }+# hardware video decoding probe (src/media/hwdec.c, docs/VIDEO.md): virtual GPUs and virtual machines+test: build/hwdec-test+build/hwdec-test: tests/hwdec_test.c src/media/hwdec.c src/media/hwdec.h src/media/media_int.h src/media/proto.c src/media/proto.h+ @mkdir -p build+ $(CC) $(CPPFLAGS) $(CFLAGS) $(WARN) -std=c11 -o $@ tests/hwdec_test.c src/media/hwdec.c src/media/proto.c+ ./$@ || { rm -f $@; exit 1; }diff --git a/server/src/hw/hw_admin.c b/server/src/hw/hw_admin.cindex 8dc5e26..466a7f9 100644--- a/server/src/hw/hw_admin.c+++ b/server/src/hw/hw_admin.c@@ -258,3 +258,73 @@ void hw_act_rpi_case(const AdminReq *r, const char *arg, size_t len) {if (!ok || rename(tmp, dst)) { unlink(tmp); admin_err("hw.caseFailed", "errno", lerr_errno(errno), NULL); return; }admin_ok("hw.caseSet", "case", id, NULL);}++/* ---- video in the browser (docs/VIDEO.md) ---- */++int hw_video_files(const char *arg, char *chromium, size_t cn, char *firefox, size_t fn) {+ char a[64], mode[16], lower[8], vp9[8], av1[8], extra[2];+ if (!arg || strlen(arg) >= sizeof a) return -1;+ snprintf(a, sizeof a, "%s", arg);+ a[strcspn(a, "\n")] = 0;+ if (sscanf(a, "%15s %7s %7s %7s %1s", mode, lower, vp9, av1, extra) != 4) return -1;+ if (strcmp(mode, "auto") && strcmp(mode, "always") && strcmp(mode, "never")) return -1;+ if (strcmp(lower, "on") && strcmp(lower, "off")) return -1;+ if ((strcmp(vp9, "yes") && strcmp(vp9, "no")) || (strcmp(av1, "yes") && strcmp(av1, "no"))) return -1;+ int hw_vp9 = !strcmp(vp9, "yes"), hw_av1 = !strcmp(av1, "yes");+ /* Chromium: the extension's managed storage ("3rdparty" policy); the extension decides */+ snprintf(chromium, cn,+ "{\n \"3rdparty\": {\n \"extensions\": {\n \"%s\": {\n"+ " \"mode\": \"%s\",\n \"autoLower\": %s,\n \"hwVp9\": %s,\n \"hwAv1\": %s\n"+ " }\n }\n }\n}\n",+ HW_VIDEO_EXT_ID, mode, !strcmp(lower, "on") ? "true" : "false", hw_vp9 ? "true" : "false", hw_av1 ? "true" : "false");+ /* Firefox ESR (no extension: it only loads signed ones): AV1 can be turned off on its own; VP9+ * has no such switch without turning off all of WebM, so it stays */+ int no_av1 = !strcmp(mode, "always") || (!strcmp(mode, "auto") && !hw_av1);+ snprintf(firefox, fn,+ "// Written by LordOS (Settings → Displays → Video in the browser). Changes here are overwritten.\n"+ "// See docs/VIDEO.md.\n%s",+ no_av1 ? "pref(\"media.av1.enabled\", false);\n" : "");+ return 0;+}++/* Writes text to path through a temporary file and rename (nothing if it is already there). */+static int write_atomic(const char *path, const char *text) {+ char cur[2048];+ int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);+ if (fd >= 0) {+ ssize_t n = read(fd, cur, sizeof cur - 1);+ close(fd);+ if (n >= 0) { cur[n] = 0; if (!strcmp(cur, text)) return 0; }+ }+ char tmp[PATH_MAX];+ snprintf(tmp, sizeof tmp, "%s.lordos-tmp", path);+ fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0644);+ if (fd < 0) return -1;+ int ok = write(fd, text, strlen(text)) == (ssize_t)strlen(text);+ ok = fsync(fd) == 0 && ok;+ fchmod(fd, 0644);+ close(fd);+ if (!ok || rename(tmp, path)) { unlink(tmp); return -1; }+ return 0;+}++void hw_act_video(const AdminReq *r, const char *arg, size_t len) {+ (void)r;+ char a[64], chromium[1024], firefox[512];+ if (arg_copy(arg, len, a, sizeof a) || hw_video_files(a, chromium, sizeof chromium, firefox, sizeof firefox)) {+ admin_err("admin.invalidArgument", NULL);+ return;+ }+ const char *cp = "/etc/chromium/policies/managed/lordos-video.json";+ mkdir("/etc/chromium", 0755);+ mkdir("/etc/chromium/policies", 0755);+ mkdir("/etc/chromium/policies/managed", 0755);+ if (write_atomic(cp, chromium)) { admin_err("sys.writeFailed", "path", cp, NULL); return; }+ struct stat st;+ const char *fp = "/etc/firefox-esr/lordos-video.js";+ if (stat("/etc/firefox-esr", &st) == 0 && S_ISDIR(st.st_mode) && write_atomic(fp, firefox)) {+ admin_err("sys.writeFailed", "path", fp, NULL);+ return;+ }+ admin_say("OK", "%s", a); /* i18n-ok */+}diff --git a/server/src/hw/hw_admin.h b/server/src/hw/hw_admin.hindex e4b4476..4023906 100644--- a/server/src/hw/hw_admin.h+++ b/server/src/hw/hw_admin.h@@ -13,6 +13,11 @@* rpi-case none|argon-one-v5 Raspberry Pi 5 only: writes /boot/firmware/lordos-case.txt* (fixed text, included from config.txt; takes effect* after a restart) admin+ * video-optimize <mode> <lower> <vp9> <av1> auto|always|never, on|off, yes|no, yes|no (the+ * last two: hardware VP9/AV1 decoding found this boot).+ * Writes the browsers' video settings from fixed text:+ * /etc/chromium/policies/managed/lordos-video.json and+ * /etc/firefox-esr/lordos-video.js (docs/VIDEO.md) anyone*/#ifndef LORD_HW_ADMIN_H#define LORD_HW_ADMIN_H@@ -28,6 +33,10 @@ void hw_act_time_set(const AdminReq *r, const char *arg, size_t len);void hw_act_bt_unblock(const AdminReq *r, const char *arg, size_t len);void hw_act_rpi_case(const AdminReq *r, const char *arg, size_t len);const char *hw_rpi_case_text(const char *id); /* fixed file text of a known case, NULL otherwise */+void hw_act_video(const AdminReq *r, const char *arg, size_t len);+/* The two files video-optimize writes, from its argument; 0 if the argument is valid. */+int hw_video_files(const char *arg, char *chromium, size_t cn, char *firefox, size_t fn);+#define HW_VIDEO_EXT_ID "kadhcpnkalbaminbojfmbmlgoheicmjo" /* assets/browser/video (manifest "key") *//* Validators, exposed for tests. */int hw_button_action_valid(const char *a, int lid);@@ -42,6 +51,7 @@ int hw_backlight_name_valid(const char *n);{ "time-ntp", hw_act_ntp, 0 }, \{ "time-set", hw_act_time_set, 0 }, \{ "bt-unblock", hw_act_bt_unblock, A_ANYONE }, \- { "rpi-case", hw_act_rpi_case, 0 },+ { "rpi-case", hw_act_rpi_case, 0 }, \+ { "video-optimize", hw_act_video, A_ANYONE },#endifdiff --git a/server/src/media/helper/lm.h b/server/src/media/helper/lm.hindex efbf6aa..c7176c4 100644--- a/server/src/media/helper/lm.h+++ b/server/src/media/helper/lm.h@@ -99,5 +99,6 @@ void lm_player(const char *params, int fd, int pulse, int render); /* lm_plvoid lm_screenrec(const char *params, int out, int pulse, int render); /* lm_rec.c */void lm_camera(const char *params, int dev, int render); /* lm_cam.c */void lm_audiorec(const char *params, int out, int pulse); /* lm_rec.c */+void lm_hwprobe(const int *render, int n_render); /* lm_hwprobe.c */#endifdiff --git a/server/src/media/helper/lm_hwprobe.c b/server/src/media/helper/lm_hwprobe.cnew file mode 100644index 0000000..5aad2e1--- /dev/null+++ b/server/src/media/helper/lm_hwprobe.c@@ -0,0 +1,67 @@+/* lm_hwprobe.c — which video codecs the GPU decodes through VA-API (MK_HWPROBE; docs/VIDEO.md).+ *+ * lord-server passes the render nodes it opened (up to four, virtual GPUs left out); the sandbox+ * (with the DRM ioctls) is already on. The answer is one MM_RESULT with JSON: a codec counts if one+ * of the nodes' drivers lists one of its profiles with the VLD (decode) entrypoint. No driver, no+ * profiles: everything false. */+#include "lm.h"++#include <string.h>++#ifdef LM_VAAPI+#include <va/va.h>+#include <va/va_drm.h>++static void va_quiet(void *ctx, const char *msg) { (void)ctx; LM_DBG("va: %s", msg); }++static int decodes(VADisplay d, VAProfile p) {+ VAEntrypoint eps[32];+ int n = 0;+ if (vaMaxNumEntrypoints(d) > 32 || vaQueryConfigEntrypoints(d, p, eps, &n) != VA_STATUS_SUCCESS) return 0;+ for (int i = 0; i < n; i++) if (eps[i] == VAEntrypointVLD) return 1;+ return 0;+}+#endif++void lm_hwprobe(const int *render, int n_render) {+ int vaapi = 0, vp9 = 0, av1 = 0, h264 = 0, hevc = 0;+ char vendor[128] = "";+#ifdef LM_VAAPI+ for (int r = 0; r < n_render; r++) {+ VADisplay d = render[r] >= 0 ? vaGetDisplayDRM(render[r]) : NULL;+ int maj = 0, min = 0;+ if (d) {+ vaSetErrorCallback(d, va_quiet, NULL);+ vaSetInfoCallback(d, va_quiet, NULL);+ }+ if (d && vaInitialize(d, &maj, &min) == VA_STATUS_SUCCESS) {+ vaapi = 1;+ const char *v = vaQueryVendorString(d);+ if (v && !vendor[0]) snprintf(vendor, sizeof vendor, "%s", v);+ int max = vaMaxNumProfiles(d), n = 0;+ VAProfile ps[128];+ if (max > 0 && max <= 128 && vaQueryConfigProfiles(d, ps, &n) == VA_STATUS_SUCCESS) {+ for (int i = 0; i < n; i++) {+ VAProfile p = ps[i];+ if (!decodes(d, p)) continue;+ if (p == VAProfileVP9Profile0 || p == VAProfileVP9Profile2) vp9 = 1;+ if (p == VAProfileAV1Profile0) av1 = 1;+ if (p == VAProfileH264Main || p == VAProfileH264High || p == VAProfileH264ConstrainedBaseline) h264 = 1;+ if (p == VAProfileHEVCMain || p == VAProfileHEVCMain10) hevc = 1;+ }+ }+ vaTerminate(d);+ } else if (d) vaTerminate(d);+ }+#else+ (void)render;+ (void)n_render;+#endif+ LmBuf b = { 0 };+ lm_buf_printf(&b, "{\"vaapi\":%s,\"vendor\":", vaapi ? "true" : "false");+ lm_buf_str(&b, vendor);+ lm_buf_printf(&b, ",\"vp9\":%s,\"av1\":%s,\"h264\":%s,\"hevc\":%s}", vp9 ? "true" : "false", av1 ? "true" : "false",+ h264 ? "true" : "false", hevc ? "true" : "false");+ lm_result(0, 0, b.d ? b.d : "{}", -1);+ lm_buf_free(&b);+}diff --git a/server/src/media/helper/lm_main.c b/server/src/media/helper/lm_main.cindex ba62b21..6315e97 100644--- a/server/src/media/helper/lm_main.c+++ b/server/src/media/helper/lm_main.c@@ -66,6 +66,7 @@ int main(int argc, char **argv) {-1 };int ioctls = 0;if ((m.v[0] == MK_PLAY || m.v[0] == MK_SCREENREC) && fds[2] >= 0) ioctls |= SANDBOX_IOCTL_DRM | SANDBOX_IOCTL_DMABUF;+ if (m.v[0] == MK_HWPROBE && fds[0] >= 0) ioctls |= SANDBOX_IOCTL_DRM;if (m.v[0] == MK_CAMERA) ioctls |= SANDBOX_IOCTL_V4L2 | (fds[1] >= 0 ? SANDBOX_IOCTL_DRM | SANDBOX_IOCTL_DMABUF : 0);SandboxHelperCfg cfg = { .name = "app-lordos-media", .ro_paths = ro, .extra_syscalls = extra, .allow_ioctl_classes = ioctls,.mem_max_mb = m.v[0] == MK_WORKER ? 1024 : 1536 };@@ -82,6 +83,7 @@ int main(int argc, char **argv) {case MK_SCREENREC: lm_screenrec(payload, fds[0], fds[1], fds[2]); break;case MK_CAMERA: lm_camera(payload, fds[0], fds[1]); break;case MK_AUDIOREC: lm_audiorec(payload, fds[0], fds[1]); break;+ case MK_HWPROBE: lm_hwprobe(fds, MP_MAX_FDS); break;default: LM_LOG("unknown kind %lld", (long long)m.v[0]); return 1;}return 0;diff --git a/server/src/media/hwdec.c b/server/src/media/hwdec.cnew file mode 100644index 0000000..cec3838--- /dev/null+++ b/server/src/media/hwdec.c@@ -0,0 +1,292 @@+/* hwdec.c — can this computer decode VP9 and AV1 video in hardware? (docs/VIDEO.md)+ *+ * The answer drives "Optimize video for this computer" (Settings → Displays): with Automatic,+ * the browsers are asked for H.264 instead of the codecs the hardware can't decode. Asked once per+ * boot and cached in ~/.cache/lordos/video-hw.json (keyed by /proc/sys/kernel/random/boot_id), since+ * a live USB boots on a different computer every time.+ *+ * 1. Virtual GPU (virtio-gpu, VMware SVGA, QXL, Bochs, Hyper-V, VirtualBox): no, without asking.+ * A virtual machine with a real GPU passed through is probed like any other computer.+ * 2. VA-API: lord-media (the only binary that links libva) receives the render nodes already open+ * and lists the profiles with a decode entrypoint (lm_hwprobe.c, MK_HWPROBE).+ * 3. V4L2 memory-to-memory decoders (ARM boards): VP9/AV1/H.264/HEVC as stateless (VP9F, AV1F,+ * S264, S265) or stateful (VP90, AV01, H264, HEVC) formats on the OUTPUT queue. The Raspberry+ * Pi 5 only lists HEVC there, so VP9 and AV1 come out "no".+ * No driver, no profiles or a helper that doesn't answer within 5 s: "no". */+#include "hwdec.h"+#include "media_int.h"++#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <linux/videodev2.h>+#include <signal.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/ioctl.h>+#include <sys/stat.h>+#include <sys/wait.h>+#include <time.h>+#include <unistd.h>+#include <drm/drm.h>++#define PROBE_TIMEOUT_MS 5000++static struct {+ int state; /* 0 not asked, 1 probing, 2 done */+ int sock;+ pid_t pid;+ double deadline;+ char boot[40], vm[64], gpu[48], vendor[128];+ int virt; /* the only GPU is a virtual one */+ int vaapi, va_vp9, va_av1, va_h264, va_hevc;+ int v4l2, v4_vp9, v4_av1, v4_h264, v4_hevc;+ char json[1024];+} H = { .sock = -1 };++static double mono_ms(void) {+ struct timespec t;+ clock_gettime(CLOCK_MONOTONIC, &t);+ return t.tv_sec * 1e3 + t.tv_nsec / 1e6;+}++static void read_line(const char *path, char *out, size_t n) {+ out[0] = 0;+ int fd = open(path, O_RDONLY | O_CLOEXEC);+ if (fd < 0) return;+ ssize_t r = read(fd, out, n - 1);+ close(fd);+ if (r <= 0) { out[0] = 0; return; }+ out[r] = 0;+ out[strcspn(out, "\n")] = 0;+}++int hwdec_virtual_gpu(const char *driver) {+ static const char *const v[] = { "virtio_gpu", "vmwgfx", "qxl", "bochs-drm", "bochs", "cirrus", "cirrus-qemu",+ "hyperv_drm", "vboxvideo", "simpledrm", "vkms", "xlnx", NULL };+ if (!driver || !*driver) return 1;+ for (int i = 0; v[i]; i++) if (!strcmp(driver, v[i])) return 1;+ return 0;+}++int hwdec_vm_name(const char *vendor, const char *product, int hypervisor_flag, char *out, size_t n) {+ static const struct { const char *needle, *name; } k[] = {+ { "QEMU", "qemu" }, { "VMware", "vmware" }, { "innotek", "virtualbox" }, { "VirtualBox", "virtualbox" },+ { "Xen", "xen" }, { "Parallels", "parallels" }, { "Bochs", "bochs" }, { "KVM", "kvm" },+ { "Virtual Machine", "hyperv" }, { NULL, NULL } };+ out[0] = 0;+ for (int i = 0; k[i].needle; i++)+ if ((vendor && strstr(vendor, k[i].needle)) || (product && strstr(product, k[i].needle))) { snprintf(out, n, "%s", k[i].name); return 1; }+ if (hypervisor_flag) { snprintf(out, n, "other"); return 1; }+ return 0;+}++static int cpu_hypervisor_flag(void) {+ FILE *f = fopen("/proc/cpuinfo", "r");+ if (!f) return 0;+ char line[4096];+ int yes = 0;+ while (!yes && fgets(line, sizeof line, f))+ if (!strncmp(line, "flags", 5) && strstr(line, " hypervisor")) yes = 1;+ fclose(f);+ return yes;+}++static void drm_driver(int fd, char *out, size_t n) {+ char name[48] = "";+ struct drm_version v;+ memset(&v, 0, sizeof v);+ v.name = name;+ v.name_len = sizeof name - 1;+ if (ioctl(fd, DRM_IOCTL_VERSION, &v) == 0) name[v.name_len < sizeof name ? v.name_len : sizeof name - 1] = 0;+ else name[0] = 0;+ snprintf(out, n, "%s", name);+}++/* ---- V4L2 decoders ---- */++#define FOURCC(a, b, c, d) ((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))++static void v4l2_probe(void) {+ for (int i = 0; i < 64; i++) {+ char p[32];+ snprintf(p, sizeof p, "/dev/video%d", i);+ int fd = open(p, O_RDWR | O_CLOEXEC | O_NONBLOCK);+ if (fd < 0) continue;+ struct v4l2_capability cap;+ memset(&cap, 0, sizeof cap);+ if (ioctl(fd, VIDIOC_QUERYCAP, &cap)) { close(fd); continue; }+ uint32_t caps = (cap.capabilities & V4L2_CAP_DEVICE_CAPS) ? cap.device_caps : cap.capabilities;+ if (!(caps & (V4L2_CAP_VIDEO_M2M | V4L2_CAP_VIDEO_M2M_MPLANE))) { close(fd); continue; }+ static const uint32_t types[] = { V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, V4L2_BUF_TYPE_VIDEO_OUTPUT };+ for (int t = 0; t < 2; t++) {+ for (uint32_t k = 0; k < 64; k++) {+ struct v4l2_fmtdesc f;+ memset(&f, 0, sizeof f);+ f.index = k;+ f.type = types[t];+ if (ioctl(fd, VIDIOC_ENUM_FMT, &f)) break;+ uint32_t pf = f.pixelformat;+ if (pf == FOURCC('V', 'P', '9', 'F') || pf == FOURCC('V', 'P', '9', '0')) H.v4_vp9 = 1;+ else if (pf == FOURCC('A', 'V', '1', 'F') || pf == FOURCC('A', 'V', '0', '1')) H.v4_av1 = 1;+ else if (pf == FOURCC('S', '2', '6', '4') || pf == FOURCC('H', '2', '6', '4')) H.v4_h264 = 1;+ else if (pf == FOURCC('S', '2', '6', '5') || pf == FOURCC('H', 'E', 'V', 'C')) H.v4_hevc = 1;+ else continue;+ H.v4l2 = 1;+ }+ }+ close(fd);+ }+}++/* ---- result ---- */++static const char *b(int v) { return v ? "true" : "false"; }++static void build_json(void) {+ char vm[80], gpu[64], vendor[200];+ media_json_str(vm, sizeof vm, H.vm);+ media_json_str(gpu, sizeof gpu, H.gpu);+ media_json_str(vendor, sizeof vendor, H.vendor);+ int vp9 = !H.virt && (H.va_vp9 || H.v4_vp9), av1 = !H.virt && (H.va_av1 || H.v4_av1);+ int h264 = !H.virt && (H.va_h264 || H.v4_h264), hevc = !H.virt && (H.va_hevc || H.v4_hevc);+ const char *why = H.virt ? "virtualGpu" : (vp9 && av1) ? "ok" : (!H.vaapi && !H.v4l2) ? "noDriver" : "noProfiles";+ snprintf(H.json, sizeof H.json,+ "{\"boot\":\"%s\",\"vm\":%s,\"gpu\":%s,\"virtualGpu\":%s,\"vaapi\":%s,\"vendor\":%s,\"v4l2\":%s,"+ "\"vp9\":%s,\"av1\":%s,\"h264\":%s,\"hevc\":%s,\"reason\":\"%s\"}",+ H.boot, vm, gpu, b(H.virt), b(H.vaapi), vendor, b(H.v4l2), b(vp9), b(av1), b(h264), b(hevc), why);+}++static void cache_path(char *out, size_t n) { snprintf(out, n, "%s/.cache/lordos/video-hw.json", media_home()); }++static void save_cache(void) {+ char dir[4096], path[4200], tmp[4300];+ snprintf(dir, sizeof dir, "%s/.cache", media_home());+ mkdir(dir, 0700);+ snprintf(dir, sizeof dir, "%s/.cache/lordos", media_home());+ mkdir(dir, 0700);+ cache_path(path, sizeof path);+ snprintf(tmp, sizeof tmp, "%s.%d.part", path, (int)getpid());+ int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW, 0600);+ if (fd < 0) return;+ size_t len = strlen(H.json);+ int ok = write(fd, H.json, len) == (ssize_t)len;+ close(fd);+ if (!ok || rename(tmp, path)) unlink(tmp);+}++/* The cached answer if it was written in this boot (and looks like ours). */+static int load_cache(void) {+ char path[4200];+ cache_path(path, sizeof path);+ int fd = open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);+ if (fd < 0) return 0;+ char buf[sizeof H.json];+ ssize_t r = read(fd, buf, sizeof buf - 1);+ close(fd);+ if (r <= 0) return 0;+ buf[r] = 0;+ char want[64];+ snprintf(want, sizeof want, "{\"boot\":\"%s\",", H.boot);+ if (!H.boot[0] || strncmp(buf, want, strlen(want)) || buf[r - 1] != '}' || strchr(buf, '\n')) return 0;+ memcpy(H.json, buf, (size_t)r + 1);+ return 1;+}++static void finish(void) {+ if (H.sock >= 0) { close(H.sock); H.sock = -1; }+ if (H.pid > 0) {+ if (waitpid(H.pid, NULL, WNOHANG) != H.pid) { kill(H.pid, SIGKILL); waitpid(H.pid, NULL, 0); }+ H.pid = 0;+ }+ build_json();+ save_cache();+ H.state = 2;+ fprintf(stderr, "video: hardware decoding %s\n", H.json);+}++static void start(void) {+ H.state = 1;+ read_line("/proc/sys/kernel/random/boot_id", H.boot, sizeof H.boot);+ for (char *p = H.boot; *p; p++) if (!strchr("0123456789abcdef-", *p)) { H.boot[0] = 0; break; }+ if (load_cache()) { H.state = 2; return; }++ char vendor[128], product[128];+ read_line("/sys/class/dmi/id/sys_vendor", vendor, sizeof vendor);+ read_line("/sys/class/dmi/id/product_name", product, sizeof product);+ hwdec_vm_name(vendor, product, cpu_hypervisor_flag(), H.vm, sizeof H.vm);++ /* the render nodes that belong to a real GPU go to lord-media */+ int fds[MP_MAX_FDS], nfds = 0, any = 0;+ int allow = strcmp(media_hwaccel(), "none") != 0;+ for (int i = 128; i < 136 && nfds < MP_MAX_FDS; i++) {+ char p[32], drv[48];+ snprintf(p, sizeof p, "/dev/dri/renderD%d", i);+ int fd = open(p, O_RDWR | O_CLOEXEC);+ if (fd < 0) continue;+ drm_driver(fd, drv, sizeof drv);+ if (!any++) snprintf(H.gpu, sizeof H.gpu, "%s", drv);+ if (hwdec_virtual_gpu(drv) || !allow) { close(fd); continue; }+ if (nfds == 0) snprintf(H.gpu, sizeof H.gpu, "%s", drv);+ fds[nfds++] = fd;+ }+ H.virt = any && !nfds && allow;+ v4l2_probe();+ if (!nfds) { finish(); return; }+ H.sock = media_spawn(MK_HWPROBE, NULL, fds, nfds, &H.pid);+ for (int i = 0; i < nfds; i++) close(fds[i]);+ if (H.sock < 0) { finish(); return; }+ H.deadline = mono_ms() + PROBE_TIMEOUT_MS;+}++/* "vp9":true inside lord-media's JSON (fixed keys, written by lm_hwprobe.c). */+static int jbool(const char *json, const char *key) {+ char k[32];+ snprintf(k, sizeof k, "\"%s\":true", key);+ return strstr(json, k) != NULL;+}++void hwdec_dispatch(void) {+ if (H.state != 1 || H.sock < 0) return;+ static char payload[MP_PAYLOAD_MAX + 1];+ MediaMsg m;+ int fds[MP_MAX_FDS];+ int r = mp_recv(H.sock, &m, payload, sizeof payload, fds, 0);+ for (int i = 0; r > 0 && i < MP_MAX_FDS; i++) if (fds[i] >= 0) close(fds[i]);+ if (r < 0) return; /* nothing yet */+ if (r > 0 && m.type == MM_RESULT && payload[0] == '{') {+ H.vaapi = jbool(payload, "vaapi");+ H.va_vp9 = jbool(payload, "vp9");+ H.va_av1 = jbool(payload, "av1");+ H.va_h264 = jbool(payload, "h264");+ H.va_hevc = jbool(payload, "hevc");+ const char *v = strstr(payload, "\"vendor\":\"");+ if (v) {+ v += 10;+ size_t n = 0;+ while (v[n] && v[n] != '"' && v[n] != '\\' && n < sizeof H.vendor - 1) n++;+ memcpy(H.vendor, v, n);+ H.vendor[n] = 0;+ }+ }+ finish();+}++int hwdec_pollfd(void) {+ if (H.state == 1 && H.sock >= 0 && mono_ms() > H.deadline) {+ fprintf(stderr, "video: the decoder probe didn't answer; taking \"no\"\n");+ finish();+ }+ return H.state == 1 ? H.sock : -1;+}++const char *hwdec_result(void) {+ if (H.state == 0) start();+ if (H.state == 1) hwdec_pollfd(); /* the timeout, also without main loop events */+ return H.state == 2 ? H.json : NULL;+}++void hwdec_shutdown(void) {+ if (H.state == 1) { H.state = 0; if (H.sock >= 0) close(H.sock); H.sock = -1; if (H.pid > 0) { kill(H.pid, SIGKILL); waitpid(H.pid, NULL, 0); } H.pid = 0; }+}diff --git a/server/src/media/hwdec.h b/server/src/media/hwdec.hnew file mode 100644index 0000000..5c9de44--- /dev/null+++ b/server/src/media/hwdec.h@@ -0,0 +1,18 @@+/* hwdec.h — hardware VP9/AV1 decoding probe, once per boot (see hwdec.c and docs/VIDEO.md). */+#ifndef LORD_MEDIA_HWDEC_H+#define LORD_MEDIA_HWDEC_H++#include <stddef.h>++/* JSON with the answer, or NULL while lord-media is still probing (the first call starts it):+ * {"boot","vm","gpu","virtualGpu","vaapi","vendor","v4l2","vp9","av1","h264","hevc","reason"} */+const char *hwdec_result(void);+int hwdec_pollfd(void); /* -1 when nothing is pending (main loop, via media_pollfds) */+void hwdec_dispatch(void);+void hwdec_shutdown(void);++/* Pure helpers, exposed for tests. */+int hwdec_virtual_gpu(const char *drm_driver); /* virtio_gpu, vmwgfx, qxl… (or empty) */+int hwdec_vm_name(const char *sys_vendor, const char *product, int hypervisor_flag, char *out, size_t n);++#endifdiff --git a/server/src/media/media.c b/server/src/media/media.cindex 1d2a169..7fcd718 100644--- a/server/src/media/media.c+++ b/server/src/media/media.c@@ -13,6 +13,7 @@* (F_SEAL_SHRINK): otherwise, a compromised helper could bring down lord-server with* SIGBUS by truncating it. */#include "media_int.h"+#include "hwdec.h"#include "../fsops.h"#include "../pkg/crypto.h"#include "../ui/ui.h"@@ -808,6 +809,8 @@ int media_cameras(char *json, size_t n) {int media_pollfds(struct pollfd *p, int max) {int n = 0;for (int i = 0; i < 2 && n < max; i++) if (workers[i].sock >= 0) p[n++] = (struct pollfd){ workers[i].sock, POLLIN, 0 };+ int hw = hwdec_pollfd(); /* the hardware decoding probe (hwdec.c), once per boot */+ if (hw >= 0 && n < max) p[n++] = (struct pollfd){ hw, POLLIN, 0 };for (int i = 0; i < MEDIA_MAX_SRC && n < max; i++) if (srcs[i].used && srcs[i].sock >= 0) p[n++] = (struct pollfd){ srcs[i].sock, POLLIN, 0 };for (int i = 0; i < MEDIA_MAX_SRC && n < max; i++) {if (!srcs[i].used) continue;@@ -825,6 +828,7 @@ void media_dispatch(const struct pollfd *p, int n) {for (int k = 0; k < n; k++) {if (!p[k].revents) continue;int fd = p[k].fd;+ if (fd == hwdec_pollfd()) { hwdec_dispatch(); continue; }for (int i = 0; i < 2; i++) if (workers[i].sock == fd) worker_dispatch(i);for (int i = 0; i < MEDIA_MAX_SRC; i++) {if (!srcs[i].used) continue;@@ -848,5 +852,6 @@ void media_shutdown(void) {if (workers[b].sock >= 0) { close(workers[b].sock); workers[b].sock = -1; bury(workers[b].pid, 1000); }}thumb_n = 0;+ hwdec_shutdown();media_events(NULL);}diff --git a/server/src/media/proto.h b/server/src/media/proto.hindex 1043e59..da3c5f5 100644--- a/server/src/media/proto.h+++ b/server/src/media/proto.h@@ -31,6 +31,8 @@ enum {MK_SCREENREC, /* screen recording: fds = mp4 output, microphone ring (or -1), render node */MK_CAMERA, /* V4L2 camera: fds = /dev/videoN, render node */MK_AUDIOREC, /* audio recorder: fds = wav output, microphone ring */+ MK_HWPROBE, /* which video codecs VA-API decodes: fds = render node → one MM_RESULT+ with JSON {"vaapi":bool,"vendor":"…","vp9":bool,"av1":bool,"h264":bool,"hevc":bool} */};/* Jobs of the MK_WORKER helper (MM_JOB with v[0] = MW_*). */diff --git a/server/src/ui/js_media.c b/server/src/ui/js_media.cindex c97a03d..fdd4c9c 100644--- a/server/src/ui/js_media.c+++ b/server/src/ui/js_media.c@@ -15,6 +15,7 @@#include "js_media.h"#include "../media/media_int.h"#include "../media/proto.h"+#include "../media/hwdec.h"#include "../sec/perms.h"#include "../sec/restrict.h"#include "../fw/rules.h"@@ -673,6 +674,14 @@ static JSValue f_hwaccel(JSContext *c, JSValueConst t, int argc, JSValueConst *areturn JS_NewString(c, media_hwaccel());}+/* hwDecode(): can this computer decode VP9/AV1 in hardware? The object from media/hwdec.c, or null+ * while it is being found out (the first call starts it; cached per boot). docs/VIDEO.md */+static JSValue f_hwdecode(JSContext *c, JSValueConst t, int argc, JSValueConst *argv) {+ (void)t; (void)argc; (void)argv;+ const char *j = hwdec_result();+ return j ? JS_ParseJSON(c, j, strlen(j), "<hwdec>") : JS_NULL;+}+static const JSCFunctionListEntry media_funcs[] = {JS_CFUNC_DEF("play", 3, f_play),JS_CFUNC_DEF("control", 3, f_control),@@ -701,6 +710,7 @@ static const JSCFunctionListEntry media_funcs[] = {JS_CFUNC_DEF("cameraRecord", 3, f_camera_record),JS_CFUNC_DEF("protectedCount", 0, f_protected),JS_CFUNC_DEF("hwaccel", 0, f_hwaccel),+ JS_CFUNC_DEF("hwDecode", 0, f_hwdecode),};/* A restriction was just added to the built-in apps: what it covers stops now, like revoking thediff --git a/server/tests/hwdec_test.c b/server/tests/hwdec_test.cnew file mode 100644index 0000000..bb0ccb0--- /dev/null+++ b/server/tests/hwdec_test.c@@ -0,0 +1,33 @@+/* hwdec_test.c — the pure parts of the hardware decoding probe (src/media/hwdec.c, docs/VIDEO.md):+ * which DRM drivers are virtual GPUs and how a virtual machine is recognized. Run by `make test`. */+#include "media/hwdec.h"+#include "media/media_int.h"++#include <stdio.h>+#include <string.h>++/* hwdec.c's other neighbours in lord-server, not used by these tests */+int media_spawn(int kind, const char *params, const int *fds, int nfds, pid_t *pid) { (void)kind; (void)params; (void)fds; (void)nfds; (void)pid; return -1; }+const char *media_home(void) { return "/nonexistent"; }+const char *media_hwaccel(void) { return "vaapi"; }+void media_json_str(char *out, size_t n, const char *s) { snprintf(out, n, "\"%s\"", s); }++static int fails, checks;+#define CHECK(c) do { checks++; if (!(c)) { fails++; fprintf(stderr, "%s:%d: failed: %s\n", __FILE__, __LINE__, #c); } } while (0)++int main(void) {+ CHECK(hwdec_virtual_gpu("virtio_gpu") && hwdec_virtual_gpu("vmwgfx") && hwdec_virtual_gpu("qxl") && hwdec_virtual_gpu(""));+ CHECK(hwdec_virtual_gpu(NULL) && hwdec_virtual_gpu("hyperv_drm") && hwdec_virtual_gpu("vboxvideo"));+ CHECK(!hwdec_virtual_gpu("i915") && !hwdec_virtual_gpu("xe") && !hwdec_virtual_gpu("amdgpu") && !hwdec_virtual_gpu("nouveau"));+ CHECK(!hwdec_virtual_gpu("v3d") && !hwdec_virtual_gpu("vc4") && !hwdec_virtual_gpu("panfrost"));+ char n[32];+ CHECK(hwdec_vm_name("QEMU", "Standard PC (Q35 + ICH9, 2009)", 1, n, sizeof n) && !strcmp(n, "qemu"));+ CHECK(hwdec_vm_name("VMware, Inc.", "VMware20,1", 1, n, sizeof n) && !strcmp(n, "vmware"));+ CHECK(hwdec_vm_name("innotek GmbH", "VirtualBox", 1, n, sizeof n) && !strcmp(n, "virtualbox"));+ CHECK(hwdec_vm_name("Microsoft Corporation", "Virtual Machine", 1, n, sizeof n) && !strcmp(n, "hyperv"));+ CHECK(hwdec_vm_name("Some Cloud", "Instance", 1, n, sizeof n) && !strcmp(n, "other"));+ CHECK(!hwdec_vm_name("LENOVO", "20XW", 0, n, sizeof n) && !n[0]);+ CHECK(!hwdec_vm_name("", "", 0, n, sizeof n)); /* Raspberry Pi: no DMI, no flag */+ printf("hwdec: %d/%d passed\n", checks - fails, checks);+ return fails != 0;+}diff --git a/server/tests/settings_hw_test.c b/server/tests/settings_hw_test.cindex 05b039e..c273cf5 100644--- a/server/tests/settings_hw_test.c+++ b/server/tests/settings_hw_test.c@@ -363,6 +363,18 @@ static void test_admin(void) {CHECK(!hw_rpi_case_text("") && !hw_rpi_case_text("argon") && !hw_rpi_case_text("none ") && !hw_rpi_case_text("../x"));CHECK(hw_backlight_name_valid("intel_backlight") && hw_backlight_name_valid("amdgpu_bl1") && hw_backlight_name_valid("acpi_video0"));CHECK(!hw_backlight_name_valid("../x") && !hw_backlight_name_valid(".x") && !hw_backlight_name_valid("a/b") && !hw_backlight_name_valid(""));+ /* video-optimize: closed values only, fixed text out */+ char cr[1024], ff[512];+ CHECK(!hw_video_files("auto off no no", cr, sizeof cr, ff, sizeof ff));+ CHECK(strstr(cr, "\"" HW_VIDEO_EXT_ID "\"") && strstr(cr, "\"mode\": \"auto\"") && strstr(cr, "\"hwVp9\": false") && strstr(cr, "\"autoLower\": false"));+ CHECK(strstr(ff, "pref(\"media.av1.enabled\", false);"));+ CHECK(!hw_video_files("auto on yes yes", cr, sizeof cr, ff, sizeof ff) && strstr(cr, "\"autoLower\": true") && !strstr(ff, "pref("));+ CHECK(!hw_video_files("never off no no", cr, sizeof cr, ff, sizeof ff) && !strstr(ff, "pref("));+ CHECK(!hw_video_files("always off yes yes", cr, sizeof cr, ff, sizeof ff) && strstr(ff, "media.av1.enabled"));+ CHECK(hw_video_files("auto off no", cr, sizeof cr, ff, sizeof ff) && hw_video_files("auto off no no x", cr, sizeof cr, ff, sizeof ff));+ CHECK(hw_video_files("sometimes off no no", cr, sizeof cr, ff, sizeof ff) && hw_video_files("auto maybe no no", cr, sizeof cr, ff, sizeof ff));+ CHECK(hw_video_files("auto off true no", cr, sizeof cr, ff, sizeof ff) && hw_video_files("auto\" off no no", cr, sizeof cr, ff, sizeof ff));+ CHECK(hw_video_files("", cr, sizeof cr, ff, sizeof ff) && hw_video_files(NULL, cr, sizeof cr, ff, sizeof ff));}int main(void) {diff --git a/tools/iso/mkdeb.sh b/tools/iso/mkdeb.shindex 4541b9e..0ffdf61 100755--- a/tools/iso/mkdeb.sh+++ b/tools/iso/mkdeb.sh@@ -24,6 +24,10 @@# /usr/share/keyrings/lordos-archive-keyring.gpg the key that signs that repository# /usr/lib/lordos/migrate, migrations/ version-to-version system migrations, run by postinst# /etc/kernel/postinst.d/zz-lordos-reboot-required "restart required" after a kernel update+# /usr/share/chromium/extensions/lordos-video/ LordOS's own browser extension for smooth video without+# hardware decoding (Debian's chromium loads every folder there;+# docs/VIDEO.md). Its settings are written at login by the+# admin action video-optimize, not shipped (postrm removes them)set -euOUT=${1:?uso: mkdeb.sh salida.deb}ROOT=$(pwd)@@ -97,6 +101,13 @@ install -d "$PKG/usr/lib/sysctl.d"printf '%s\n' '# LordOS: ptrace only of descendants (docs/FIREWALL.md, "Linux apps")' 'kernel.yama.ptrace_scope = 1' > "$PKG/usr/lib/sysctl.d/50-lordos-ptrace.conf"chmod 644 "$PKG/usr/lib/sysctl.d/50-lordos-ptrace.conf"install -m 644 tools/iso/rootfs/etc/systemd/system/lordos.service "$PKG/usr/lib/systemd/system/lordos.service"+# smooth video in Chromium without hardware decoding (docs/VIDEO.md); the Firefox manifest stays out+X="$PKG/usr/share/chromium/extensions/lordos-video"+install -d "$X"+(cd assets/browser/video && find . -type f ! -name manifest.firefox.json ! -name '.*' -print) | while read -r f; do+ install -D -m 644 "assets/browser/video/$f" "$X/$f"+done+find "$PKG/usr/share/chromium" -type d -exec chmod 755 {} +# boot splash (docs/brand/README.md, "Boot splash"): the Plymouth theme and the hand-off to LordOSinstall -m 755 tools/boot/lordos-splash "$L/lordos-splash"install -m 644 tools/boot/systemd/lordos-splash-quit.service "$PKG/usr/lib/systemd/system/lordos-splash-quit.service"@@ -256,6 +267,8 @@ cat > "$PKG/DEBIAN/postrm" <<'C'#!/bin/shset -eif [ "$1" = remove ] || [ "$1" = purge ]; then rm -f /etc/apt/sources.list.d/lordos.sources; fi+# the browsers' video settings written by Settings (video-optimize, docs/VIDEO.md)+if [ "$1" = remove ] || [ "$1" = purge ]; then rm -f /etc/chromium/policies/managed/lordos-video.json /etc/firefox-esr/lordos-video.js; fiif [ "$1" = purge ]; then rm -rf /var/lib/lordos/migrations; fiCchmod 755 "$PKG/DEBIAN/postrm"diff --git a/web/content/faq/faq.json b/web/content/faq/faq.jsonindex 6fc6b58..55cbbb9 100644--- a/web/content/faq/faq.json+++ b/web/content/faq/faq.json@@ -668,6 +668,19 @@"es": "Las placas de sonido emuladas dependen de los tiempos del equipo anfitrión, y si está muy cargado se quedan sin datos; en la 0.8.0 se notaba sobre todo en los primeros minutos después de iniciar sesión. Desde la 0.8.1, cuando LordOS corre en una máquina virtual le da a la placa emulada un búfer mucho más grande (unos 170 ms de margen), y la sincronización del correo y las miniaturas corren con baja prioridad para no competir con el sonido después de iniciar sesión; en hardware real no cambia nada y la latencia sigue baja. También ayuda darle a la máquina virtual el dispositivo **HD Audio** del hipervisor en lugar de una placa emulada más vieja, 2 a 4 procesadores, y no sobrecargar el anfitrión. En la 0.8.0 ayuda ejecutar `pw-metadata -n settings 0 clock.force-quantum 1024` en la Terminal (dura hasta que cerrás la sesión).","pt": "Placas de som emuladas dependem do tempo do computador hospedeiro, e um hospedeiro muito ocupado as deixa sem dados; no 0.8.0 isso aparecia principalmente nos primeiros minutos depois de entrar na sessão. Desde o 0.8.1, quando o LordOS roda numa máquina virtual ele dá à placa emulada um buffer bem maior (cerca de 170 ms de folga), e a sincronização do e-mail e as miniaturas rodam com baixa prioridade para não competir com o som depois do login; em hardware real nada muda e a latência continua baixa. Também ajuda dar à máquina virtual o dispositivo **HD Audio** do hipervisor em vez de uma placa emulada mais antiga, 2 a 4 processadores, e não sobrecarregar o hospedeiro. No 0.8.0, rodar `pw-metadata -n settings 0 clock.force-quantum 1024` no Terminal ajuda (vale até você sair da sessão)."}+ },+ {+ "id": "video-stutters",+ "q": {+ "en": "Video stutters in the browser. What can I do?",+ "es": "El video se traba en el navegador. ¿Qué puedo hacer?",+ "pt": "O vídeo trava no navegador. O que posso fazer?"+ },+ "a": {+ "en": "Many video sites (YouTube, for example) send VP9 or AV1 video, which takes a lot of processor time to decode when the graphics card can't do it: virtual machines, older PCs and the Raspberry Pi 5 decode them in software. Since 0.8.2 LordOS checks at every boot what your hardware decodes and, if VP9 or AV1 is missing, asks the browser for H.264 instead, which is much lighter. It's in Settings → Displays → Video in the browser: **Automatic** (the default), **Always** or **Never**. When a video still drops frames, the browser shows a small notice offering a lower quality; turn on **Lower quality automatically when video stutters** to have it done for you. In Chromium both parts work through a small extension of our own that comes with LordOS; Firefox only gets AV1 turned off for now (it then uses VP9), because it only loads signed extensions. Nothing is sent anywhere. If video still stutters, choose 720p or 480p in the player, and in a virtual machine give it more processors.",+ "es": "Muchos sitios de video (YouTube, por ejemplo) mandan video VP9 o AV1, que cuesta mucho procesador decodificar cuando la placa de video no puede hacerlo: las máquinas virtuales, las PC viejas y la Raspberry Pi 5 los decodifican por software. Desde la 0.8.2 LordOS revisa en cada arranque qué decodifica tu hardware y, si le falta VP9 o AV1, le pide H.264 al navegador, que es mucho más liviano. Está en Ajustes → Pantallas → Video en el navegador: **Automático** (de fábrica), **Siempre** o **Nunca**. Si igual un video pierde cuadros, el navegador muestra un aviso chico que ofrece bajar la calidad; activá **Bajar la calidad automáticamente cuando el video se traba** para que lo haga solo. En Chromium las dos partes funcionan con una extensión chica propia que viene con LordOS; Firefox por ahora solo recibe AV1 desactivado (entonces usa VP9), porque solo carga extensiones firmadas. No se envía nada a ningún lado. Si el video se sigue trabando, elegí 720p o 480p en el reproductor y, en una máquina virtual, dale más procesadores.",+ "pt": "Muitos sites de vídeo (o YouTube, por exemplo) enviam vídeo VP9 ou AV1, que exige muito do processador para decodificar quando a placa de vídeo não consegue: máquinas virtuais, PCs antigos e o Raspberry Pi 5 os decodificam por software. Desde o 0.8.2 o LordOS verifica a cada inicialização o que o seu hardware decodifica e, se faltar VP9 ou AV1, pede H.264 ao navegador, que é muito mais leve. Fica em Ajustes → Telas → Vídeo no navegador: **Automático** (o padrão), **Sempre** ou **Nunca**. Se mesmo assim um vídeo perder quadros, o navegador mostra um pequeno aviso oferecendo uma qualidade mais baixa; ative **Baixar a qualidade automaticamente quando o vídeo travar** para isso acontecer sozinho. No Chromium as duas partes funcionam por uma pequena extensão própria que vem com o LordOS; o Firefox por enquanto só recebe o AV1 desativado (e então usa VP9), porque só carrega extensões assinadas. Nada é enviado para lugar nenhum. Se o vídeo continuar travando, escolha 720p ou 480p no player e, numa máquina virtual, dê mais processadores a ela."+ }}]},