fix hdr playback, lint warnings

This commit is contained in:
2026-06-04 22:50:46 +03:00
parent 2fce5dfb59
commit 6756bf9d40
10 changed files with 144 additions and 72 deletions
+3 -2
View File
@@ -124,14 +124,15 @@ export default function EndOfVideoCard({
} }
function RateAndLogRow({ itemId, itemName }: { itemId?: string; itemName: string }) { function RateAndLogRow({ itemId, itemName }: { itemId?: string; itemName: string }) {
if (!itemId || String(itemId).startsWith('tmdb-')) return null
const [hoverRating, setHoverRating] = useState(0) const [hoverRating, setHoverRating] = useState(0)
const personal = usePersonalData(s => s.entries[itemId]) const personal = usePersonalData(s => itemId ? s.entries[itemId] : undefined)
const setRating = usePersonalData(s => s.setRating) const setRating = usePersonalData(s => s.setRating)
const addDiary = useDiary(s => s.add) const addDiary = useDiary(s => s.add)
const current = personal?.rating || 0 const current = personal?.rating || 0
const [logged, setLogged] = useState(false) const [logged, setLogged] = useState(false)
if (!itemId || String(itemId).startsWith('tmdb-')) return null
return ( return (
<div className="flex items-center justify-center gap-3 mb-5"> <div className="flex items-center justify-center gap-3 mb-5">
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
+25 -3
View File
@@ -13,6 +13,7 @@ import {
videoRangeLabel, videoRangeLabel,
} from '../../lib/jellyfin-meta' } from '../../lib/jellyfin-meta'
import { formatBitrate } from '../../lib/format' import { formatBitrate } from '../../lib/format'
import { isHdrDisplayActive } from '../../lib/device-profile'
interface Props { interface Props {
item?: BaseItemDto | null item?: BaseItemDto | null
@@ -58,7 +59,7 @@ function readLiveStats(): LiveStats {
} }
} }
async function checkHwDecode(stream: { Codec?: string | null; Width?: number | null; Height?: number | null; BitRate?: number | null } | null): Promise<HwDecodeState> { async function checkHwDecode(stream: { Codec?: string | null; Width?: number | null; Height?: number | null; BitRate?: number | null; VideoRangeType?: string | null; VideoRange?: string | null } | null): Promise<HwDecodeState> {
if (!stream || typeof navigator.mediaCapabilities?.decodingInfo !== 'function') { if (!stream || typeof navigator.mediaCapabilities?.decodingInfo !== 'function') {
return { supported: null, hwAccelerated: null } return { supported: null, hwAccelerated: null }
} }
@@ -66,9 +67,15 @@ async function checkHwDecode(stream: { Codec?: string | null; Width?: number | n
const w = stream.Width ?? 1920 const w = stream.Width ?? 1920
const h = stream.Height ?? 1080 const h = stream.Height ?? 1080
const br = stream.BitRate ?? 8000000 const br = stream.BitRate ?? 8000000
// Map common Jellyfin codec names to MIME codec strings // Use the main10 profile codec string for HDR content so the
// MediaCapabilities query matches what the actual stream requires.
// The previous main (8-bit) string caused HDR sources to probe
// against the wrong profile.
const range = (stream.VideoRangeType || stream.VideoRange || '').toUpperCase()
const isHdr = range === 'HDR' || range === 'HDR10' || range === 'HLG' || range.startsWith('DOVI')
const mimeCodec = const mimeCodec =
codec === 'h264' ? 'avc1.640033' codec === 'h264' ? 'avc1.640033'
: codec === 'hevc' && isHdr ? 'hev1.2.4.L153.B0'
: codec === 'hevc' ? 'hev1.1.6.L150.90' : codec === 'hevc' ? 'hev1.1.6.L150.90'
: codec === 'av1' ? 'av01.0.05M.08' : codec === 'av1' ? 'av01.0.05M.08'
: codec === 'vp9' ? 'vp09.00.50.08' : codec === 'vp9' ? 'vp09.00.50.08'
@@ -164,7 +171,7 @@ export default function StreamInfo({ item, visible, playMethod }: Props) {
if (!visible) return if (!visible) return
const v = getVideoStream(item || {}) const v = getVideoStream(item || {})
checkHwDecode(v).then(setHw) checkHwDecode(v).then(setHw)
}, [visible, item?.Id]) }, [visible, item])
if (!visible || !item) return null if (!visible || !item) return null
const source = pickPrimarySource(item) const source = pickPrimarySource(item)
@@ -192,6 +199,21 @@ export default function StreamInfo({ item, visible, playMethod }: Props) {
const res = resolutionLabel(item) const res = resolutionLabel(item)
const range = videoRangeLabel(item) const range = videoRangeLabel(item)
// HDR display status - tells the user whether their display is actually
// in HDR mode. When the source is HDR but the display is SDR, the browser
// tone-maps the content. If the profile was built with HDR display off,
// the server did FFmpeg tone-mapping instead.
const hdrDisplay = isHdrDisplayActive()
if (range && range !== 'SDR') {
rows.push({
label: 'HDR display',
value: hdrDisplay ? 'Active' : 'Off (tone-mapped)',
accent: hdrDisplay,
warn: !hdrDisplay,
})
}
if (res) rows.push({ label: 'Resolution', value: range ? `${res} · ${range}` : res }) if (res) rows.push({ label: 'Resolution', value: range ? `${res} · ${range}` : res })
if (v) { if (v) {
rows.push({ label: 'Video', value: videoCodecLabel(v) }) rows.push({ label: 'Video', value: videoCodecLabel(v) })
+1 -1
View File
@@ -54,7 +54,7 @@ function parseVTT(raw: string): Cue[] {
// Accept both WebVTT dots and SRT commas for the milliseconds separator. // Accept both WebVTT dots and SRT commas for the milliseconds separator.
// Jellyfin sometimes serves SRT content even on the .vtt endpoint. // Jellyfin sometimes serves SRT content even on the .vtt endpoint.
const m = lines[tsLine].match( const m = lines[tsLine].match(
/(\d+:)?(\d+):(\d+)[\.,](\d+)\s+-->\s+(\d+:)?(\d+):(\d+)[\.,](\d+)/, /(\d+:)?(\d+):(\d+)[.,](\d+)\s+-->\s+(\d+:)?(\d+):(\d+)[.,](\d+)/,
) )
if (!m) continue if (!m) continue
const start = parseTimeStamp(m[1], m[2], m[3], m[4]) const start = parseTimeStamp(m[1], m[2], m[3], m[4])
+5 -4
View File
@@ -19,15 +19,16 @@ import type { BaseItemDto } from '../api/types'
*/ */
export function usePrebuffer(item: BaseItemDto | null | undefined, armed: boolean) { export function usePrebuffer(item: BaseItemDto | null | undefined, armed: boolean) {
const qc = useQueryClient() const qc = useQueryClient()
const itemId = item?.Id
const itemType = item?.Type
useEffect(() => { useEffect(() => {
if (!armed) return if (!armed) return
if (!item || !item.Id || String(item.Id).startsWith('tmdb-')) return if (!itemId || String(itemId).startsWith('tmdb-')) return
// Episodes / movies are the only item kinds that go through PlaybackInfo // Episodes / movies are the only item kinds that go through PlaybackInfo
// for streaming; series / seasons would need a child resolution first. // for streaming; series / seasons would need a child resolution first.
if (item.Type !== 'Movie' && item.Type !== 'Episode') return if (itemType !== 'Movie' && itemType !== 'Episode') return
const itemId = item.Id
let cancelled = false let cancelled = false
const key = ['jellyfin', 'playback-info', itemId, undefined, undefined, undefined] const key = ['jellyfin', 'playback-info', itemId, undefined, undefined, undefined]
@@ -76,5 +77,5 @@ export function usePrebuffer(item: BaseItemDto | null | undefined, armed: boolea
}).catch(() => { /* warm-only; ignore */ }) }).catch(() => { /* warm-only; ignore */ })
return () => { cancelled = true } return () => { cancelled = true }
}, [armed, item?.Id, item?.Type, qc]) }, [armed, itemId, itemType, qc])
} }
+61 -26
View File
@@ -48,33 +48,66 @@ function supportedVideoCodecs(): string[] {
} }
/** /**
* HDR support detection. Probes for the codec strings the major HDR * Check whether the display is in HDR mode. On Windows this means the
* formats use: * user has "Use HDR" turned on in Display Settings. The media query
* - HDR10 / HLG via HEVC main10 level 5.1 (`hvc1.2.4.L153.B0`) or VP9.2 * returns false on SDR-only panels and on HDR panels with HDR mode off.
* (`vp09.02.10.10.01.09.16.09.00`) *
* - Dolby Vision via the `dvh1.05.06` codec string * jellyfin-web uses browser-identification heuristics (hardcoding
* When a format is detected we add it to the `VideoRangeType` matrix on * `browser.chrome && !browser.mobile` etc.) because it doesn't control
* the corresponding CodecProfile so the server direct-plays HDR content * the shell. We control the Tauri shell so we can use the actual media
* instead of falling back to a tone-mapped SDR transcode. * query - same outcome, fewer moving parts.
*/
function displaySupportsHdr(): boolean {
try {
return window.matchMedia('(dynamic-range: high)').matches
} catch {
return false
}
}
/**
* HDR format detection. Two-stage gate:
* 1. Codec probe - does the browser's MSE stack understand the codec
* string for this HDR format?
* 2. Display check - is the user's display actually in HDR mode?
*
* Both must be true. Advertising HDR10/HLG/DOVI in VideoRangeType when
* the display is SDR causes the server to direct-play the file; the
* browser then tone-maps it to SDR, which works but bypasses the
* server's configurable FFmpeg tone-mapping and can produce different
* (often worse) results.
*
* Codec strings probed:
* - HDR10 / HDR10+ / HLG: HEVC main10 level 5.1 (`hvc1.2.4.L153.B0`)
* or VP9.2 (`vp09.02.10.10.01.09.16.09.00`)
* - Dolby Vision: `dvh1.05.06` / `dvhe.05.06`
*/ */
function supportedVideoRanges(): string { function supportedVideoRanges(): string {
const ranges = ['SDR'] const ranges = ['SDR']
if ( const hdrCodec =
canPlayInMse('video/mp4; codecs="hvc1.2.4.L153.B0"') || canPlayInMse('video/mp4; codecs="hvc1.2.4.L153.B0"') ||
canPlayInMse('video/mp4; codecs="hev1.2.4.L153.B0"') || canPlayInMse('video/mp4; codecs="hev1.2.4.L153.B0"') ||
canPlayInMse('video/webm; codecs="vp09.02.10.10.01.09.16.09.00"') canPlayInMse('video/webm; codecs="vp09.02.10.10.01.09.16.09.00"')
) { if (hdrCodec && displaySupportsHdr()) {
ranges.push('HDR10', 'HLG') ranges.push('HDR10', 'HDR10Plus', 'HLG')
} }
if ( const dvCodec =
canPlayInMse('video/mp4; codecs="dvh1.05.06"') || canPlayInMse('video/mp4; codecs="dvh1.05.06"') ||
canPlayInMse('video/mp4; codecs="dvhe.05.06"') canPlayInMse('video/mp4; codecs="dvhe.05.06"')
) { if (dvCodec && displaySupportsHdr()) {
ranges.push('DOVI', 'DOVIWithHDR10', 'DOVIWithHLG', 'DOVIWithSDR') ranges.push('DOVI', 'DOVIWithHDR10', 'DOVIWithHLG', 'DOVIWithSDR')
} }
return ranges.join('|') return ranges.join('|')
} }
/**
* Exported helper so StreamInfo and other diagnostics can show whether
* the display is in HDR mode without re-probing the codec strings.
*/
export function isHdrDisplayActive(): boolean {
return displaySupportsHdr()
}
export function browserDeviceProfile(audioPassthrough = false) { export function browserDeviceProfile(audioPassthrough = false) {
const videoCodecs = supportedVideoCodecs() const videoCodecs = supportedVideoCodecs()
const videoCodecsCsv = videoCodecs.join(',') const videoCodecsCsv = videoCodecs.join(',')
@@ -88,9 +121,12 @@ export function browserDeviceProfile(audioPassthrough = false) {
DirectPlayProfiles: [ DirectPlayProfiles: [
{ {
// MSE / hls.js can remux these on the fly - no need to force a // Chromium can natively play mp4/m4v. Everything else (mkv, avi, etc)
// server-side transcode just because the container isn't mp4. // goes through the HLS TranscodingProfile below, which remuxes into
Container: 'mp4,m4v,mkv,avi,mov,wmv,ts,mpeg,mpegts', // fMP4 that hls.js + MSE can handle. Listing mkv here would make the
// server return SupportsDirectPlay=true, but Chromium's <video> can't
// actually decode raw MKV - the player would just stall.
Container: 'mp4,m4v',
Type: 'Video', Type: 'Video',
VideoCodec: videoCodecsCsv, VideoCodec: videoCodecsCsv,
AudioCodec: audioPassthrough AudioCodec: audioPassthrough
@@ -156,8 +192,9 @@ export function browserDeviceProfile(audioPassthrough = false) {
}, },
// HEVC: cap at main / main10 + level 5.1 - matches what hardware // HEVC: cap at main / main10 + level 5.1 - matches what hardware
// decoders on most consumer GPUs can chew through. VideoRangeType // decoders on most consumer GPUs can chew through. VideoRangeType
// advertises whichever HDR formats the browser actually supports so // only advertises HDR when the display is actually in HDR mode, so
// the server direct-plays HDR sources instead of tone-mapping to SDR. // the server does FFmpeg tone-mapping for SDR displays instead of
// relying on the browser's built-in tone-mapping.
{ {
Type: 'Video', Type: 'Video',
Codec: 'hevc', Codec: 'hevc',
@@ -210,18 +247,16 @@ export function browserDeviceProfile(audioPassthrough = false) {
}, },
], ],
// Mirror jellyfin-web: only External delivery. The server decides
// whether to burn-in or deliver externally based on these profiles.
// With no Embed/Hls methods listed, the server won't try to mux
// subtitles into the transcode stream - it delivers them as separate
// files that the client loads via libass-wasm or native VTT tracks.
SubtitleProfiles: [ SubtitleProfiles: [
{ Format: 'vtt', Method: 'External' }, { Format: 'vtt', Method: 'External' },
{ Format: 'vtt', Method: 'Hls' },
{ Format: 'subrip', Method: 'External' },
{ Format: 'subrip', Method: 'Embed' },
{ Format: 'subrip', Method: 'Hls' },
{ Format: 'ass', Method: 'External' }, { Format: 'ass', Method: 'External' },
{ Format: 'ass', Method: 'Embed' },
{ Format: 'ass', Method: 'Hls' },
{ Format: 'ssa', Method: 'External' }, { Format: 'ssa', Method: 'External' },
{ Format: 'ssa', Method: 'Embed' }, { Format: 'subrip', Method: 'External' },
{ Format: 'ssa', Method: 'Hls' },
], ],
ResponseProfiles: [], ResponseProfiles: [],
+1 -1
View File
@@ -13,7 +13,7 @@ export default function DuplicatesPage() {
sortOrder: ['Ascending'], sortOrder: ['Ascending'],
limit: 5000, limit: 5000,
}) })
const items = data?.Items || [] const items = useMemo(() => data?.Items || [], [data?.Items])
const duplicates = useMemo(() => { const duplicates = useMemo(() => {
// Group by TMDB ID first (most reliable) // Group by TMDB ID first (most reliable)
+16 -11
View File
@@ -347,17 +347,19 @@ export default function PlayerPage() {
* the resume condition once per item, not re-trigger when item data * the resume condition once per item, not re-trigger when item data
* refreshes or prefs change mid-playback. */ * refreshes or prefs change mid-playback. */
const resumePromptShownRef = useRef<string | null>(null) const resumePromptShownRef = useRef<string | null>(null)
const resumeItemId = item?.Id
const resumePositionTicks = item?.UserData?.PlaybackPositionTicks
useEffect(() => { useEffect(() => {
if (!item || resumePromptShownRef.current === item.Id) return if (!resumeItemId || resumePromptShownRef.current === resumeItemId) return
const pos = Number(item.UserData?.PlaybackPositionTicks ?? 0) const pos = Number(resumePositionTicks ?? 0)
const thresholdSec = usePreferencesStore.getState().resumeThresholdSec ?? 5 const thresholdSec = usePreferencesStore.getState().resumeThresholdSec ?? 5
const threshold = thresholdSec * 10_000_000 const threshold = thresholdSec * 10_000_000
const fromQueue = searchParams.get('resume') === 'true' const fromQueue = searchParams.get('resume') === 'true'
if (showResumePromptPref && !fromQueue && pos > threshold) { if (showResumePromptPref && !fromQueue && pos > threshold) {
setResumePromptOpen(true) setResumePromptOpen(true)
resumePromptShownRef.current = item.Id ?? null resumePromptShownRef.current = resumeItemId
} }
}, [item?.Id, searchParams, showResumePromptPref]) }, [resumeItemId, resumePositionTicks, searchParams, showResumePromptPref])
/* Auto-rewatch counter: when an already-played item starts playing /* Auto-rewatch counter: when an already-played item starts playing
* again, record the rewatch. We trip it at most once per item-mount * again, record the rewatch. We trip it at most once per item-mount
@@ -645,23 +647,26 @@ export default function PlayerPage() {
const currentMarker: Marker | undefined = markers.find( const currentMarker: Marker | undefined = markers.find(
m => currentTime >= m.startSec && currentTime < m.endSec - 0.5, m => currentTime >= m.startSec && currentTime < m.endSec - 0.5,
) )
const currentMarkerType = currentMarker?.type
const currentMarkerStartSec = currentMarker?.startSec
const currentMarkerEndSec = currentMarker?.endSec
/* Auto-skip when entering a marker AND the corresponding pref is on. /* Auto-skip when entering a marker AND the corresponding pref is on.
* Also accumulate the skipped seconds into the per-series tally so the * Also accumulate the skipped seconds into the per-series tally so the
* detail page can surface a "you saved Xh Ym" badge. */ * detail page can surface a "you saved Xh Ym" badge. */
useEffect(() => { useEffect(() => {
if (!currentMarker || !playerRef.current) return if (!currentMarkerType || currentMarkerEndSec == null || !playerRef.current) return
const p = playerRef.current const p = playerRef.current
const from = p.currentTime const from = p.currentTime
if (currentMarker.type === 'intro' && skipIntros) { if (currentMarkerType === 'intro' && skipIntros) {
p.currentTime = currentMarker.endSec p.currentTime = currentMarkerEndSec
if (seriesId) recordSkippedSeconds(seriesId, 'intro', currentMarker.endSec - from) if (seriesId) recordSkippedSeconds(seriesId, 'intro', currentMarkerEndSec - from)
} else if (currentMarker.type === 'credits' && skipCredits && duration > 0) { } else if (currentMarkerType === 'credits' && skipCredits && duration > 0) {
const target = Math.max(currentMarker.endSec, duration - 0.5) const target = Math.max(currentMarkerEndSec, duration - 0.5)
p.currentTime = target p.currentTime = target
if (seriesId) recordSkippedSeconds(seriesId, 'credits', target - from) if (seriesId) recordSkippedSeconds(seriesId, 'credits', target - from)
} }
}, [currentMarker?.type, currentMarker?.startSec, skipIntros, skipCredits, duration, seriesId]) }, [currentMarkerType, currentMarkerStartSec, currentMarkerEndSec, skipIntros, skipCredits, duration, seriesId])
/* Imperatively switch the active subtitle track. We use 'hidden' rather /* Imperatively switch the active subtitle track. We use 'hidden' rather
* than 'showing' so the browser doesn't paint its own caption UI over our * than 'showing' so the browser doesn't paint its own caption UI over our
@@ -1,4 +1,4 @@
import { useMemo } from 'react' import { useEffect, useMemo, useState } from 'react'
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { Activity, MonitorPlay, Users, Server as ServerIcon, Clock } from '../../../lib/icons' import { Activity, MonitorPlay, Users, Server as ServerIcon, Clock } from '../../../lib/icons'
import { jellyfinClient, getSystemApi, getSessionApi } from '../../../api/jellyfin' import { jellyfinClient, getSystemApi, getSessionApi } from '../../../api/jellyfin'
@@ -10,6 +10,15 @@ function useApi() {
export function ServerDashboardSection() { export function ServerDashboardSection() {
const api = useApi() const api = useApi()
const [now, setNow] = useState(0)
useEffect(() => {
const update = () => setNow(Date.now())
update()
const id = window.setInterval(update, 60_000)
return () => window.clearInterval(id)
}, [])
const serverInfo = useQuery({ const serverInfo = useQuery({
queryKey: ['jellyfin', 'system-info'], queryKey: ['jellyfin', 'system-info'],
queryFn: async () => { queryFn: async () => {
@@ -37,13 +46,14 @@ export function ServerDashboardSection() {
const transcodes = activeSessions.filter(s => s.PlayState?.PlayMethod === 'Transcode') const transcodes = activeSessions.filter(s => s.PlayState?.PlayMethod === 'Transcode')
const uptime = useMemo(() => { const uptime = useMemo(() => {
if (!now) return null
const start = (info as { ServerStartTime?: string } | null | undefined)?.ServerStartTime const start = (info as { ServerStartTime?: string } | null | undefined)?.ServerStartTime
if (!start) return null if (!start) return null
const ms = Date.now() - new Date(start).getTime() const ms = now - new Date(start).getTime()
const days = Math.floor(ms / 86_400_000) const days = Math.floor(ms / 86_400_000)
const hrs = Math.floor((ms % 86_400_000) / 3_600_000) const hrs = Math.floor((ms % 86_400_000) / 3_600_000)
return days > 0 ? `${days}d ${hrs}h` : `${hrs}h` return days > 0 ? `${days}d ${hrs}h` : `${hrs}h`
}, [info]) }, [info, now])
return ( return (
<Section id="server-dashboard" title="Server dashboard" description="Live stats and activity"> <Section id="server-dashboard" title="Server dashboard" description="Live stats and activity">
+17 -18
View File
@@ -69,7 +69,21 @@ export function ShortcutsSection() {
const setPreference = usePreferencesStore(s => s.setPreference) const setPreference = usePreferencesStore(s => s.setPreference)
const [capturingId, setCapturingId] = useState<string | null>(null) const [capturingId, setCapturingId] = useState<string | null>(null)
function commit(id: string, binding: string) { function reset(id: string) {
const next = { ...overrides }
delete next[id]
setPreference('keyboardShortcuts', next)
}
function resetAll() {
setPreference('keyboardShortcuts', {})
toast('All shortcuts reset to defaults', 'success')
}
useEffect(() => {
if (!capturingId) return
const id = capturingId
function commit(binding: string) {
const conflict = Object.entries({ ...overrides }) const conflict = Object.entries({ ...overrides })
.filter(([k]) => k !== id) .filter(([k]) => k !== id)
.find(([, keys]) => (keys as string[]).some(k => normalizeBinding(k) === binding)) .find(([, keys]) => (keys as string[]).some(k => normalizeBinding(k) === binding))
@@ -86,21 +100,6 @@ export function ShortcutsSection() {
setPreference('keyboardShortcuts', { ...overrides, [id]: [binding] }) setPreference('keyboardShortcuts', { ...overrides, [id]: [binding] })
toast('Shortcut updated', 'success') toast('Shortcut updated', 'success')
} }
function reset(id: string) {
const next = { ...overrides }
delete next[id]
setPreference('keyboardShortcuts', next)
}
function resetAll() {
setPreference('keyboardShortcuts', {})
toast('All shortcuts reset to defaults', 'success')
}
useEffect(() => {
if (!capturingId) return
const id = capturingId
function onKey(e: KeyboardEvent) { function onKey(e: KeyboardEvent) {
e.preventDefault() e.preventDefault()
e.stopPropagation() e.stopPropagation()
@@ -113,11 +112,11 @@ export function ShortcutsSection() {
} }
const binding = eventToBinding(e) const binding = eventToBinding(e)
setCapturingId(null) setCapturingId(null)
commit(id, binding) commit(binding)
} }
window.addEventListener('keydown', onKey, true) window.addEventListener('keydown', onKey, true)
return () => window.removeEventListener('keydown', onKey, true) return () => window.removeEventListener('keydown', onKey, true)
}, [capturingId, overrides, commit]) }, [capturingId, overrides, setPreference])
return ( return (
<Section <Section
-1
View File
@@ -9,7 +9,6 @@ interface ImportMeta {
readonly env: ImportMetaEnv readonly env: ImportMetaEnv
} }
/* eslint-disable @typescript-eslint/no-empty-object-type */
declare module 'react' { declare module 'react' {
interface CSSProperties { interface CSSProperties {
WebkitUserSelect?: string WebkitUserSelect?: string