feat(torrents): unsupported-codec handling + animated preload border

Detect the /gst transcoder's 502 "unsupported video codec/container"
response, surface a clear in-player message instead of an endless
spinner, and grey out Play for releases that already failed (persisted
by infohash). Replace the buffering spinner with a rounded player and
an animated conic border sweep.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
nerandClaude Opus 4.8 committed 2026-08-07 15:16:18 +03:00
1 parent 526f0c24e0
commit 204acef185
8 files changed
+193 -28

No files matched your search

@@ -30,9 +30,10 @@ interface Props {
magnet: string;
subtitles: Source[];
playlist: Source[];
onStreamError?: (reason?: string) => void;
}
const Player: FC<Props> = ({ magnet, playlist, subtitles }) => {
const Player: FC<Props> = ({ magnet, playlist, subtitles, onStreamError }) => {
const setCanPlay = useSetCanPlay();
const { index, setIndex } = useSource({ magnet });
@@ -50,7 +51,7 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles }) => {
const source = playlist[index];
const { tracks: audioTracks, audio, setAudio, resolvedSrc } = useGstAudio(source?.src);
const { tracks: audioTracks, audio, setAudio, resolvedSrc, error } = useGstAudio(source?.src);
const resumeTime = useRef(0);
@@ -59,7 +60,15 @@ const Player: FC<Props> = ({ magnet, playlist, subtitles }) => {
setAudio(track);
};
const playerSrc = useMemo(() => (source ? ({ ...source, src: resolvedSrc } as VideoSrc) : []), [source, resolvedSrc]);
// report the transcoder rejection up to the modal and stop hls.js from retrying a dead stream
useEffect(() => {
onStreamError?.(error);
}, [error, onStreamError]);
const playerSrc = useMemo(
() => (source && !error ? ({ ...source, src: resolvedSrc } as VideoSrc) : []),
[source, resolvedSrc, error]
);
const onProviderChange = (provider: MediaProviderAdapter | null) => {
if (isHLSProvider(provider)) {
@@ -1,6 +1,8 @@
import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import useUnplayable from '@/components/Preview/components/Torrents/useUnplayable';
export interface GstAudioTrack {
index: number;
label: string;
@@ -23,26 +25,42 @@ export const useGstAudio = (src?: string) => {
const match = src?.match(GST_RE);
const [base, hash, index] = match ? [match[1], match[2], match[3]] : [];
const { markUnplayable } = useUnplayable();
const [audio, setAudio] = useState(0);
useEffect(() => {
setAudio(0);
}, [hash, index]);
const { data: tracks = [] } = useQuery<GstAudioTrack[]>({
const { data: tracks = [], error } = useQuery<GstAudioTrack[]>({
enabled: Boolean(hash && index),
// a rejected codec/container won't change on retry
retry: false,
queryKey: ['gst-audio', hash, index],
queryFn: () =>
fetch(`${base}/gst/${hash}/probe?index=${index}`)
.then((response) => response.json())
.then((data: { Tracks?: ProbeTrack[] }) =>
(data.Tracks ?? [])
.filter((track) => track.Type === 'audio')
.map((track) => ({ index: track.Index, label: label(track) }))
)
queryFn: async () => {
const response = await fetch(`${base}/gst/${hash}/probe?index=${index}`);
// the transcoder answers 5xx with a plain-text reason, e.g. "unsupported video codec"
if (!response.ok) throw new Error((await response.text()).trim() || `stream error ${response.status}`);
const data: { Tracks?: ProbeTrack[] } = await response.json();
return (data.Tracks ?? [])
.filter((track) => track.Type === 'audio')
.map((track) => ({ index: track.Index, label: label(track) }));
}
});
const reason = error instanceof Error ? error.message : undefined;
// codec/container rejections are permanent for this backend — remember them to grey out Play
useEffect(() => {
if (reason && /unsupported (video codec|container)/i.test(reason)) markUnplayable(hash, reason);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [reason, hash]);
const resolvedSrc = match ? `${src}&audio=${audio}` : src;
return { tracks, audio, setAudio, resolvedSrc };
return { tracks, audio, setAudio, resolvedSrc, error: reason };
};
@@ -1,5 +1,5 @@
import { useState } from 'react';
import { create, InstanceProps } from 'react-modal-promise';
import { Loader } from 'lucide-react';
import Player from '@/components/Preview/components/Torrents/components/Player';
import { Modal } from '@/components/ui/dialog';
@@ -22,6 +22,8 @@ const showPlayerModal = create(({ onResolve, hash, backdrop, title, magnet }: Pr
const sources = useFiles({ magnet });
const [streamError, setStreamError] = useState<string>();
const handleClose = () => {
setCanPlay(false);
onResolve();
@@ -29,22 +31,39 @@ const showPlayerModal = create(({ onResolve, hash, backdrop, title, magnet }: Pr
return (
<Modal className='overflow-hidden border-none bg-black p-0' onClose={handleClose}>
<div className='relative w-full overflow-hidden pt-[56.25%]'>
<div className='relative w-full overflow-hidden rounded-xl pt-[56.25%]'>
<div className='absolute left-0 top-0 size-full'>
{sources && <Player magnet={magnet} playlist={sources.playlist} subtitles={sources.subtitles} />}
{sources && (
<Player
magnet={magnet}
playlist={sources.playlist}
subtitles={sources.subtitles}
onStreamError={setStreamError}
/>
)}
</div>
{(!isReady || !canPlay) && (
<div className='absolute left-0 top-0 size-full'>
{streamError && (
<div className='absolute left-0 top-0 flex size-full flex-col items-center justify-center gap-3 bg-black p-6 text-center text-white/90'>
<p className='text-base font-medium'>This release can’t be played in the browser</p>
<p className='text-sm text-white/60'>{streamError}</p>
<p className='max-w-sm text-sm text-white/70'>
The server can’t transcode this video. Use the playlist or VLC option to open it externally, or pick
another release.
</p>
</div>
)}
{!streamError && (!isReady || !canPlay) && (
<div className='absolute left-0 top-0 size-full overflow-hidden rounded-xl'>
<img src={backdrop} className='absolute left-0 top-0 size-full' alt={title} />
{/* dark cover recedes from the centre out to the top and bottom edges as it preloads */}
<div
className='absolute left-0 top-0 flex size-full items-center justify-center bg-black/60 transition-all'
style={{ width: `${100 - (canPlay ? 100 : preloadingProgress)}%` }}
className='absolute inset-x-0 top-0 bg-black/60 transition-[height] duration-700 ease-out'
style={{ height: `${(100 - (canPlay ? 100 : preloadingProgress)) / 2}%` }}
/>
<div
className='absolute inset-x-0 bottom-0 bg-black/60 transition-[height] duration-700 ease-out'
style={{ height: `${(100 - (canPlay ? 100 : preloadingProgress)) / 2}%` }}
/>
<div className='absolute left-0 top-0 flex size-full items-center justify-center'>
<div className='animate-spin'>
<Loader color='white' />
</div>
</div>
<div className='absolute left-0 top-0 flex size-full flex-col items-center justify-between text-sm text-white/90'>
<div className='grid w-full items-center bg-black/80 p-2 text-center'>
<p>Buffering: {preloadingProgress.toFixed()}%</p>
@@ -53,6 +72,31 @@ const showPlayerModal = create(({ onResolve, hash, backdrop, title, magnet }: Pr
<p>Download speed: {downloadSpeed || '0 B/s'}</p>
</div>
</div>
{/* a highlight sweeps around the block's 2px border while it preloads */}
<style>{`
@property --preload-angle { syntax: '<angle>'; initial-value: 0deg; inherits: false; }
@keyframes preloadBorderAngle { to { --preload-angle: 360deg; } }
.preload-block-border {
position: absolute;
inset: 0;
padding: 2px;
border-radius: 0.75rem;
pointer-events: none;
background: conic-gradient(from var(--preload-angle),
transparent 0deg,
transparent 30deg,
rgba(255, 255, 255, 0.7) 75deg,
transparent 120deg,
transparent 360deg);
-webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
-webkit-mask-composite: xor;
mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0);
mask-composite: exclude;
filter: drop-shadow(0 0 4px rgba(255, 255, 255, 0.45));
animation: preloadBorderAngle 7s linear infinite;
}
`}</style>
<div className='preload-block-border' />
</div>
)}
</div>
@@ -11,6 +11,7 @@ import { useStreamUrl } from '@/hooks/useStreamUrl';
import { cn, detectSafari, getMagnetHash, isStandaloneApp, torrentKey } from '@/lib/utils';
import usePinnedTorrents from '../../../../usePinnedTorrents';
import useUnplayable from '../../../../useUnplayable';
import showPlayerModal from './components/Player';
import useMagnet from './useMagnet';
@@ -46,6 +47,7 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
const fetchMagnet = useMagnet(torrent);
const { pin, toggle, isPinned, savedMagnet, rememberMagnet } = usePinnedTorrents();
const { reasonFor } = useUnplayable();
const key = torrentKey(torrent);
const pinned = isPinned(key);
@@ -55,6 +57,9 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
const hash = getMagnetHash(magnet);
// a release that already failed transcoding stays greyed out so we don't hit the same 502 twice
const unplayable = reasonFor(hash);
// persist the fetched magnet while pinned; only Toloka needs it (others carry it in the result)
useEffect(() => {
if (pinned && magnet && !torrent.magnet) rememberMagnet(key, magnet);
@@ -101,16 +106,19 @@ const Actions: FC<Props> = ({ torrent, title, provider, show }) => {
{supportedForStream && (
<Button
variant='destructive'
disabled={Boolean(unplayable)}
className={cn(
'flex-grow-0 px-3 bg-red-600',
'hover:shadow-lg hover:shadow-red-600/60 duration-200 transition-all hover:bg-red-600',
'flex-grow-0 px-3',
unplayable
? 'bg-muted text-muted-foreground hover:bg-muted'
: 'bg-red-600 hover:shadow-lg hover:shadow-red-600/60 duration-200 transition-all hover:bg-red-600',
{ invisible: !magnet || fetchMagnet.isPending }
)}
onClick={() => {
pinPlayed();
showPlayerModal({ backdrop: show.backdrop, title, hash, magnet });
}}
title='Play'
title={unplayable ? `Can’t stream in browser: ${unplayable}` : 'Play'}
>
<Play size={15} />
</Button>
@@ -0,0 +1,34 @@
import { useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
// Some releases use a video codec/container the TorrServer transcoder can't handle
// (e.g. VC-1 remuxes, AVI). Those fail with a 502 only when you actually press Play, so
// remember them by infohash to grey out Play instead of hitting the same dead-end again.
const unplayableAtom = atomWithStorage<Record<string, string>>('unplayable-torrents', {}, undefined, {
unstable_getOnInit: true
});
// getMagnetHash uppercases, the /gst URL hash is lowercase — normalise so both sides match
const normalize = (hash?: string) => hash?.toLowerCase();
const useUnplayable = () => {
const [unplayable, setUnplayable] = useAtom(unplayableAtom);
const reasonFor = (hash?: string) => {
const key = normalize(hash);
return key ? unplayable[key] : undefined;
};
const markUnplayable = (hash?: string, reason?: string) => {
const key = normalize(hash);
if (!key || !reason) return;
setUnplayable((current) => (current[key] === reason ? current : { ...current, [key]: reason }));
};
return { reasonFor, markUnplayable };
};
export default useUnplayable;