Jobs queue and video transcode from the video page

Add an in-memory FIFO Job queue (wrolpi/jobs.py): functions register by
name, callers enqueue by name with JSON kwargs, and the perpetual-tasks
owner runs them one at a time.  Logging emitted inside a Job and the
output of its subprocesses are captured into a per-Job log; Jobs report
progress and can be cancelled (a running Job's subprocess is killed).
Jobs are not persisted; an API restart forgets them.

Add a transcode Job and POST /api/videos/<id>/transcode.  ffmpeg reports
progress via -progress pipe:1.  The existing FileGroup is pointed at the
new file before the refresh so tags and history survive a container
change.

Replace the video page Refresh button with an Edit dropdown (Refresh,
Transcode).  The Transcode modal pre-fills from the preferred codecs in
the Videos settings and shows the Job's progress, log tail and Cancel.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Roland 2026-09-14 18:19:51 -06:00
parent c2ffc9286e
commit e480a386d0
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
15 changed files with 1535 additions and 14 deletions

View file

@ -16,6 +16,7 @@ import {
IconStack,
MediaFilterToggle,
MediaGate,
Menu,
Message,
MultiSelect,
NumberInput,
@ -382,6 +383,25 @@ export function ThemeSamplePage() {
</div>)}
</Row>
</div>
<div style={{marginTop: 12}}>
<Header as='h5'>A dropdown of actions</Header>
{/* The video page's Edit button: one labelled button opens a menu of the
rarer actions, so the row stays short. The trailing chevron is what
says "menu" rather than "does the thing"; a disabled item stays listed
so the user learns it exists. */}
<Row>
<Menu position='bottom-start' withinPortal>
<Menu.Target>
<Button role='primary' icon='edit' iconAfter='dropdown'>Edit</Button>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item leftSection={<Icon name='refresh'/>}>Refresh</Menu.Item>
<Menu.Item leftSection={<Icon name='film'/>}>Transcode...</Menu.Item>
<Menu.Item leftSection={<Icon name='trash'/>} disabled>Unavailable</Menu.Item>
</Menu.Dropdown>
</Menu>
</Row>
</div>
<div style={{marginTop: 12}}>
<Header as='h5'>A row of actions</Header>
{/* `.wrolpi-button-row` is how a page lists the actions on a thing -- the

View file

@ -158,6 +158,24 @@ export const downloadAudioCodecOptions = [
{key: 'vorbis', text: 'vorbis', value: 'vorbis'},
];
// Codecs WROLPi's ffmpeg step can produce. Mirrors TRANSCODE_VIDEO_TARGETS / TRANSCODE_AUDIO_TARGETS /
// TRANSCODE_CONTAINERS in modules/videos/transcode.py; the API rejects anything else.
export const TRANSCODE_COPY = 'copy';
export const transcodeVideoCodecOptions = [
{value: TRANSCODE_COPY, label: 'Keep (copy)'},
{value: 'h264', label: 'h264 (avc1)'},
];
export const transcodeAudioCodecOptions = [
{value: TRANSCODE_COPY, label: 'Keep (copy)'},
{value: 'aac', label: 'aac'},
{value: 'opus', label: 'opus'},
{value: 'mp3', label: 'mp3'},
];
export const transcodeContainerOptions = [
{value: 'mp4', label: 'mp4'},
{value: 'mkv', label: 'mkv'},
];
export const Downloaders = {
Archive: 'archive',
File: 'file',

View file

@ -0,0 +1,323 @@
import React, {useEffect, useRef, useState} from 'react';
import {cancelJob, fetchVideoDownloadDefaults, getJob, transcodeVideo} from '../api';
import {useWROLMode} from '../hooks/customHooks';
import {Button, Group, Icon, Menu, Modal, Progress, Select, Stack, Status, Text, toast} from './ui';
import {
TRANSCODE_COPY,
transcodeAudioCodecOptions,
transcodeContainerOptions,
transcodeVideoCodecOptions,
} from './Vars';
// How often the modal asks the API about the running Job.
const JOB_POLL_MS = 2000;
const FINISHED_STATUSES = ['complete', 'failed', 'cancelled'];
// Embedded thumbnails are "video" streams to ffprobe, but not codecs a user chooses.
const THUMBNAIL_CODECS = ['mjpeg', 'png', 'bmp', 'gif'];
/** The codec names of a Video's real streams, from the `codec_names`/`codec_types` the API sends. */
export function currentCodecs(video) {
const names = video?.codec_names || [];
const types = video?.codec_types || [];
const video_ = names.filter((name, i) => types[i] === 'video' && !THUMBNAIL_CODECS.includes(name));
const audio = names.filter((name, i) => types[i] === 'audio');
return {video: video_, audio};
}
/**
* The transcode target implied by the user's ordered codec preferences: the first preferred codec
* that ffmpeg can produce (the same rule the downloader uses). `copy` when none can be.
*/
export function preferredTarget(preferences, options) {
const producible = options.map(i => i.value).filter(i => i !== TRANSCODE_COPY);
for (const codec of preferences || []) {
if (producible.includes(codec)) {
return codec;
}
}
return TRANSCODE_COPY;
}
const statusKind = (status) => {
if (status === 'complete') return 'complete';
if (status === 'running') return 'active';
if (status === 'failed' || status === 'cancelled') return 'failed';
return 'pending';
}
/** Progress, status and log tail of one Job, polled until it finishes. */
export function JobProgress({jobId, onFinished}) {
const [job, setJob] = useState(null);
const [cancelling, setCancelling] = useState(false);
const timer = useRef(null);
const finishedRef = useRef(false);
useEffect(() => {
finishedRef.current = false;
let cancelled = false;
const poll = async () => {
let latest;
try {
latest = await getJob(jobId);
} catch (e) {
console.error(e);
return;
}
if (cancelled) return;
setJob(latest);
if (FINISHED_STATUSES.includes(latest.status)) {
if (!finishedRef.current) {
finishedRef.current = true;
if (onFinished) onFinished(latest);
}
return;
}
timer.current = window.setTimeout(poll, JOB_POLL_MS);
};
poll();
return () => {
cancelled = true;
clearTimeout(timer.current);
};
// Only a new Job restarts polling; `onFinished` may be a fresh closure on every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [jobId]);
const handleCancel = async () => {
setCancelling(true);
try {
const latest = await cancelJob(jobId);
setJob(latest);
} catch (e) {
console.error(e);
} finally {
setCancelling(false);
}
};
if (!job) {
return <Progress indeterminate showPercent={false} label='Starting...'/>;
}
const finished = FINISHED_STATUSES.includes(job.status);
const percent = job.progress ?? 0;
const logTail = (job.log || []).slice(-8);
return <Stack gap='sm'>
<Group justify='space-between' wrap='wrap'>
<Status kind={statusKind(job.status)}>{job.status}</Status>
{!finished && <Button
role='danger'
size='small'
icon='stop'
onClick={handleCancel}
loading={cancelling}
disabled={cancelling || job.cancel_requested}
>
{job.cancel_requested ? 'Cancelling...' : 'Cancel'}
</Button>}
</Group>
<Progress
percent={percent}
indeterminate={!finished && job.progress === null}
color={job.status === 'failed' ? 'red' : job.status === 'complete' ? 'green' : 'blue'}
/>
{job.error && <Text c='var(--danger)' size='sm'>{job.error}</Text>}
{logTail.length > 0 && <pre
data-testid='job-log'
style={{
margin: 0,
maxHeight: '10em',
overflow: 'auto',
fontSize: '0.75em',
whiteSpace: 'pre-wrap',
wordBreak: 'break-all',
background: 'var(--surface-2, var(--surface))',
padding: '0.5em',
borderRadius: 'var(--radius, 4px)',
}}
>{logTail.join('\n')}</pre>}
</Stack>
}
/**
* Choose target codecs for one Video, queue the transcode Job, then watch it.
*
* The selects start at the user's preferred codecs from the Videos settings (the same preference
* lists the downloader honors), so the common case is a glance and a click.
*/
export function TranscodeModal({open, onClose, fileGroupId, video, onComplete}) {
const wrolModeEnabled = useWROLMode();
const [videoCodec, setVideoCodec] = useState(TRANSCODE_COPY);
const [audioCodec, setAudioCodec] = useState(TRANSCODE_COPY);
const [container, setContainer] = useState('mp4');
const [defaultsLoaded, setDefaultsLoaded] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [jobId, setJobId] = useState(null);
const current = currentCodecs(video);
useEffect(() => {
if (!open) {
return;
}
// Each opening starts over: a finished Job's progress must not linger on the next open.
setJobId(null);
setDefaultsLoaded(false);
let stale = false;
const load = async () => {
try {
const defaults = await fetchVideoDownloadDefaults();
if (stale) return;
setVideoCodec(preferredTarget(defaults?.video_codecs, transcodeVideoCodecOptions));
setAudioCodec(preferredTarget(defaults?.audio_codecs, transcodeAudioCodecOptions));
} catch (e) {
console.error(e);
} finally {
if (!stale) setDefaultsLoaded(true);
}
};
load();
return () => {
stale = true;
};
}, [open]);
const nothingToDo = videoCodec === TRANSCODE_COPY && audioCodec === TRANSCODE_COPY;
const handleStart = async () => {
setSubmitting(true);
try {
const id = await transcodeVideo(fileGroupId, {
video_codec: videoCodec === TRANSCODE_COPY ? null : videoCodec,
audio_codec: audioCodec === TRANSCODE_COPY ? null : audioCodec,
container,
});
setJobId(id);
} catch (e) {
// transcodeVideo already toasted.
console.error(e);
} finally {
setSubmitting(false);
}
};
const handleFinished = (job) => {
if (job.status === 'complete') {
toast({type: 'success', title: 'Transcode complete', description: job.description, time: 5000});
if (onComplete) onComplete(job);
}
};
const describe = (codecs) => codecs.length ? codecs.join(', ') : 'unknown';
return <Modal open={open} onClose={onClose} size='small'>
<Modal.Header>Transcode Video</Modal.Header>
<Modal.Content>
<Stack gap='md'>
<Text size='sm' c='var(--muted)'>
Current codecs: video {describe(current.video)}, audio {describe(current.audio)}.
Streams set to Keep are copied without re-encoding. Transcoding is slow and slightly
reduces quality; the original file is replaced when it finishes.
</Text>
{!jobId && <>
<Select
label='Video codec'
data={transcodeVideoCodecOptions}
value={videoCodec}
onChange={value => setVideoCodec(value || TRANSCODE_COPY)}
disabled={!defaultsLoaded}
allowDeselect={false}
/>
<Select
label='Audio codec'
data={transcodeAudioCodecOptions}
value={audioCodec}
onChange={value => setAudioCodec(value || TRANSCODE_COPY)}
disabled={!defaultsLoaded}
allowDeselect={false}
/>
<Select
label='Container'
data={transcodeContainerOptions}
value={container}
onChange={value => setContainer(value || 'mp4')}
allowDeselect={false}
/>
{nothingToDo && defaultsLoaded && <Text size='sm' c='var(--muted)'>
Choose at least one codec to convert.
</Text>}
</>}
{jobId && <JobProgress jobId={jobId} onFinished={handleFinished}/>}
</Stack>
</Modal.Content>
<Modal.Actions>
<Button role='cancel' onClick={onClose}>{jobId ? 'Close' : 'Cancel'}</Button>
{!jobId && <Button
role='primary'
icon='film'
onClick={handleStart}
loading={submitting}
disabled={submitting || nothingToDo || !defaultsLoaded || !!wrolModeEnabled}
>
Transcode
</Button>}
</Modal.Actions>
</Modal>
}
/**
* The "Edit" dropdown on the Video page: Refresh (re-download metadata) and Transcode.
*
* `onRefresh` is awaited; `onTranscodeComplete` is called after the file was replaced so the
* page can fetch the Video again (its path and codecs changed).
*/
export function VideoEditMenu({videoFile, video, onRefresh, onTranscodeComplete}) {
const wrolModeEnabled = useWROLMode();
const [transcodeOpen, setTranscodeOpen] = useState(false);
const [refreshing, setRefreshing] = useState(false);
const handleRefresh = async () => {
setRefreshing(true);
try {
await onRefresh();
} finally {
setRefreshing(false);
}
};
const isVideo = !!videoFile?.mimetype?.startsWith('video/');
return <>
<Menu position='bottom-start' withinPortal>
<Menu.Target>
<Button role='primary' icon='edit' iconAfter='dropdown' loading={refreshing}>Edit</Button>
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
leftSection={<Icon name='refresh'/>}
onClick={handleRefresh}
disabled={!videoFile?.url || !!wrolModeEnabled || refreshing}
>
Refresh
</Menu.Item>
<Menu.Item
leftSection={<Icon name='film'/>}
onClick={() => setTranscodeOpen(true)}
disabled={!isVideo || !!wrolModeEnabled}
>
Transcode...
</Menu.Item>
</Menu.Dropdown>
</Menu>
<TranscodeModal
open={transcodeOpen}
onClose={() => setTranscodeOpen(false)}
fileGroupId={videoFile?.id}
video={video}
onComplete={onTranscodeComplete}
/>
</>
}

View file

@ -0,0 +1,194 @@
import React from 'react';
import {act, fireEvent, screen, waitFor} from '@testing-library/react';
import {renderWithProviders} from '../test-utils';
import {currentCodecs, JobProgress, preferredTarget, TranscodeModal, VideoEditMenu} from './VideoEditMenu';
import {TRANSCODE_COPY, transcodeAudioCodecOptions, transcodeVideoCodecOptions} from './Vars';
jest.mock('../api', () => ({
cancelJob: jest.fn(),
fetchVideoDownloadDefaults: jest.fn(),
getJob: jest.fn(),
transcodeVideo: jest.fn(),
}));
import {cancelJob, fetchVideoDownloadDefaults, getJob, transcodeVideo} from '../api';
const video = {
codec_names: ['vp9', 'mjpeg', 'opus'],
codec_types: ['video', 'video', 'audio'],
video_path: 'videos/movie.webm',
};
const videoFile = {id: 7, url: 'https://example.com/watch?v=1', mimetype: 'video/webm', video};
// Mantine's Select renders a hidden input next to the visible one, both tied to the label.
const selectInput = (label) => screen.getAllByLabelText(label).find(i => i.type !== 'hidden');
// `renderWithProviders`' `settings` option replaces the SettingsContext value; the WROL flag lives
// one level down in its `settings`.
const wrolMode = {settings: {settings: {wrol_mode: true}}};
const pendingJob = {
id: 'transcode_video-abc', status: 'pending', progress: null, log: [], error: null, cancel_requested: false,
description: 'Transcode movie.webm',
};
describe('helpers', () => {
test('currentCodecs ignores embedded thumbnail streams', () => {
expect(currentCodecs(video)).toEqual({video: ['vp9'], audio: ['opus']});
expect(currentCodecs(null)).toEqual({video: [], audio: []});
});
test('preferredTarget picks the first preference ffmpeg can produce', () => {
expect(preferredTarget(['vp9', 'h264'], transcodeVideoCodecOptions)).toBe('h264');
expect(preferredTarget(['vp9', 'av1'], transcodeVideoCodecOptions)).toBe(TRANSCODE_COPY);
expect(preferredTarget(['opus', 'aac'], transcodeAudioCodecOptions)).toBe('opus');
expect(preferredTarget([], transcodeAudioCodecOptions)).toBe(TRANSCODE_COPY);
expect(preferredTarget(undefined, transcodeAudioCodecOptions)).toBe(TRANSCODE_COPY);
});
});
describe('TranscodeModal', () => {
beforeEach(() => {
jest.clearAllMocks();
fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: ['h264'], audio_codecs: ['vorbis', 'aac']});
transcodeVideo.mockResolvedValue('transcode_video-abc');
getJob.mockResolvedValue(pendingJob);
});
test('pre-populates from the preferred codecs and queues the Job', async () => {
renderWithProviders(<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video}/>);
expect(screen.getByText(/Current codecs: video vp9, audio opus/)).toBeInTheDocument();
// The defaults arrive: h264 is producible, vorbis is not, so aac is the audio target.
await waitFor(() => expect(selectInput('Video codec')).toHaveValue('h264 (avc1)'));
expect(selectInput('Audio codec')).toHaveValue('aac');
expect(selectInput('Container')).toHaveValue('mp4');
fireEvent.click(screen.getByRole('button', {name: /Transcode/}));
await waitFor(() => expect(transcodeVideo).toHaveBeenCalledWith(7, {
video_codec: 'h264', audio_codec: 'aac', container: 'mp4',
}));
// The form is replaced by the Job's progress.
await waitFor(() => expect(getJob).toHaveBeenCalledWith('transcode_video-abc'));
expect(screen.queryAllByLabelText('Video codec')).toHaveLength(0);
expect(await screen.findByText('pending')).toBeInTheDocument();
});
test('refuses to start when every stream is kept', async () => {
fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: [], audio_codecs: []});
renderWithProviders(<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video}/>);
await waitFor(() => expect(screen.getByText('Choose at least one codec to convert.')).toBeInTheDocument());
expect(screen.getByRole('button', {name: /Transcode/})).toBeDisabled();
expect(transcodeVideo).not.toHaveBeenCalled();
});
test('WROL Mode disables starting a transcode', async () => {
renderWithProviders(
<TranscodeModal open={true} onClose={jest.fn()} fileGroupId={7} video={video}/>,
wrolMode,
);
await waitFor(() => expect(selectInput('Video codec')).toHaveValue('h264 (avc1)'));
expect(screen.getByRole('button', {name: /Transcode/})).toBeDisabled();
});
});
describe('JobProgress', () => {
beforeEach(() => {
jest.clearAllMocks();
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
test('polls until the Job finishes, then reports once', async () => {
const onFinished = jest.fn();
getJob
.mockResolvedValueOnce({...pendingJob, status: 'running', progress: 40, log: ['out_time_us=1']})
.mockResolvedValueOnce({...pendingJob, status: 'complete', progress: 100, log: ['done']});
renderWithProviders(<JobProgress jobId='transcode_video-abc' onFinished={onFinished}/>);
await waitFor(() => expect(screen.getByText('running')).toBeInTheDocument());
expect(screen.getByRole('progressbar')).toHaveAttribute('aria-valuenow', '40');
expect(screen.getByTestId('job-log')).toHaveTextContent('out_time_us=1');
expect(screen.getByRole('button', {name: 'Cancel'})).toBeInTheDocument();
await act(async () => {
jest.advanceTimersByTime(2000);
});
await waitFor(() => expect(screen.getByText('complete')).toBeInTheDocument());
expect(onFinished).toHaveBeenCalledTimes(1);
expect(onFinished.mock.calls[0][0].status).toBe('complete');
// A finished Job is not polled again, and cannot be cancelled.
expect(getJob).toHaveBeenCalledTimes(2);
expect(screen.queryByRole('button', {name: 'Cancel'})).not.toBeInTheDocument();
});
test('Cancel asks the API to cancel the Job', async () => {
getJob.mockResolvedValue({...pendingJob, status: 'running', progress: 10});
cancelJob.mockResolvedValue({...pendingJob, status: 'running', progress: 10, cancel_requested: true});
renderWithProviders(<JobProgress jobId='transcode_video-abc'/>);
await waitFor(() => expect(screen.getByRole('button', {name: 'Cancel'})).toBeInTheDocument());
fireEvent.click(screen.getByRole('button', {name: 'Cancel'}));
await waitFor(() => expect(cancelJob).toHaveBeenCalledWith('transcode_video-abc'));
await waitFor(() => expect(screen.getByRole('button', {name: 'Cancelling...'})).toBeDisabled());
});
test('shows the error of a failed Job', async () => {
getJob.mockResolvedValue({...pendingJob, status: 'failed', error: 'ffmpeg exited with 1', log: ['boom']});
renderWithProviders(<JobProgress jobId='transcode_video-abc'/>);
await waitFor(() => expect(screen.getByText('failed')).toBeInTheDocument());
expect(screen.getByText('ffmpeg exited with 1')).toBeInTheDocument();
});
});
describe('VideoEditMenu', () => {
beforeEach(() => {
jest.clearAllMocks();
fetchVideoDownloadDefaults.mockResolvedValue({video_codecs: [], audio_codecs: []});
});
test('Refresh calls onRefresh; Transcode opens the modal', async () => {
const onRefresh = jest.fn().mockResolvedValue(undefined);
renderWithProviders(<VideoEditMenu videoFile={videoFile} video={video} onRefresh={onRefresh}/>);
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
fireEvent.click(await screen.findByRole('menuitem', {name: /Refresh/}));
await waitFor(() => expect(onRefresh).toHaveBeenCalledTimes(1));
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
fireEvent.click(await screen.findByRole('menuitem', {name: /Transcode/}));
await waitFor(() => expect(screen.getByText('Transcode Video')).toBeInTheDocument());
});
test('Refresh is unavailable without a URL, Transcode for non-video files', async () => {
const audioFile = {...videoFile, url: null, mimetype: 'audio/mpeg'};
renderWithProviders(<VideoEditMenu videoFile={audioFile} video={video} onRefresh={jest.fn()}/>);
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
const refresh = await screen.findByRole('menuitem', {name: /Refresh/});
expect(refresh).toBeDisabled();
expect(screen.getByRole('menuitem', {name: /Transcode/})).toBeDisabled();
});
test('WROL Mode disables both items', async () => {
renderWithProviders(
<VideoEditMenu videoFile={videoFile} video={video} onRefresh={jest.fn()}/>,
wrolMode,
);
fireEvent.click(screen.getByRole('button', {name: /Edit/}));
expect(await screen.findByRole('menuitem', {name: /Refresh/})).toBeDisabled();
expect(screen.getByRole('menuitem', {name: /Transcode/})).toBeDisabled();
});
});

View file

@ -24,6 +24,7 @@ import {VideoCard} from "./Videos";
import {TagsSelector} from "../Tags";
import {AddToPlaylistButton} from "./AddToPlaylist";
import {TaggedDeleteConfirmModal} from "./TaggedDeleteConfirmModal";
import {VideoEditMenu} from "./VideoEditMenu";
import {IconPlayerPause, IconPlayerPlay} from "@tabler/icons-react";
const MEDIA_PATH = '/media';
@ -495,12 +496,12 @@ function VideoPage({videoFile, prevFile, nextFile, fetchVideo, ...props}) {
onClick={async () => await handleDeleteVideo(videoFile.id)}
obeyWROLMode={true}
>Delete</APIButton>
<APIButton
role='primary'
onClick={handleRefresh}
obeyWROLMode={true}
disabled={!videoFile.url}
>Refresh</APIButton>
<VideoEditMenu
videoFile={videoFile}
video={video}
onRefresh={handleRefresh}
onTranscodeComplete={fetchVideo}
/>
<AddToPlaylistButton fileGroupId={videoFile.id}/>
</div>
</Panel>