From e480a386d05e08af401c69b4f8f5e96105063f81 Mon Sep 17 00:00:00 2001 From: Roland Date: Mon, 14 Sep 2026 18:19:51 -0600 Subject: [PATCH] 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//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 --- app/src/api.js | 39 ++ app/src/components/ThemeSamplePage.js | 20 ++ app/src/components/Vars.js | 18 + app/src/components/VideoEditMenu.js | 323 +++++++++++++++++ app/src/components/VideoEditMenu.test.js | 194 ++++++++++ app/src/components/VideoPlayer.js | 13 +- modules/videos/schema.py | 12 + modules/videos/test/test_transcode_job.py | 138 ++++++++ modules/videos/transcode.py | 108 +++++- modules/videos/video/api.py | 30 +- wrolpi/contexts.py | 14 + wrolpi/errors.py | 12 + wrolpi/jobs.py | 414 ++++++++++++++++++++++ wrolpi/root_api.py | 2 + wrolpi/test/test_jobs.py | 212 +++++++++++ 15 files changed, 1535 insertions(+), 14 deletions(-) create mode 100644 app/src/components/VideoEditMenu.js create mode 100644 app/src/components/VideoEditMenu.test.js create mode 100644 modules/videos/test/test_transcode_job.py create mode 100644 wrolpi/jobs.py create mode 100644 wrolpi/test/test_jobs.py diff --git a/app/src/api.js b/app/src/api.js index 2d57e456..a08959fa 100644 --- a/app/src/api.js +++ b/app/src/api.js @@ -236,6 +236,45 @@ export async function getVideo(fileGroupId) { return [data['file_group'], data['prev'], data['next']]; } +export async function transcodeVideo(fileGroupId, {video_codec = null, audio_codec = null, container = 'mp4'}) { + // Queues a transcode Job; returns the job id. Watch it with `getJob`. + const body = {video_codec, audio_codec, container}; + const response = await apiPost(`${VIDEOS_API}/${fileGroupId}/transcode`, body); + if (!response.ok) { + const message = await getErrorMessage(response, 'Unable to queue the transcode. See server logs.'); + toast({type: 'error', title: 'Failed to transcode', description: message, time: 5000}); + throw new Error(message); + } + const data = await response.json(); + return data['job_id']; +} + +export async function getJobs() { + const response = await apiGet(`${API_URI}/jobs`); + const data = await response.json(); + return data['jobs']; +} + +export async function getJob(jobId) { + const response = await apiGet(`${API_URI}/jobs/${jobId}`); + if (!response.ok) { + throw new Error(await getErrorMessage(response, 'Unable to get the job')); + } + const data = await response.json(); + return data['job']; +} + +export async function cancelJob(jobId) { + const response = await apiDelete(`${API_URI}/jobs/${jobId}`); + if (!response.ok) { + const message = await getErrorMessage(response, 'Unable to cancel the job'); + toast({type: 'error', title: 'Failed to cancel', description: message, time: 5000}); + throw new Error(message); + } + const data = await response.json(); + return data['job']; +} + export async function getVideoComments(fileGroupId) { const response = await apiGet(`${VIDEOS_API}/${fileGroupId}/comments`); let data = await response.json(); diff --git a/app/src/components/ThemeSamplePage.js b/app/src/components/ThemeSamplePage.js index 7767a317..824f9e7e 100644 --- a/app/src/components/ThemeSamplePage.js +++ b/app/src/components/ThemeSamplePage.js @@ -16,6 +16,7 @@ import { IconStack, MediaFilterToggle, MediaGate, + Menu, Message, MultiSelect, NumberInput, @@ -382,6 +383,25 @@ export function ThemeSamplePage() { )} +
+
A dropdown of actions
+ {/* 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. */} + + + + + + + }>Refresh + }>Transcode... + } disabled>Unavailable + + + +
A row of actions
{/* `.wrolpi-button-row` is how a page lists the actions on a thing -- the diff --git a/app/src/components/Vars.js b/app/src/components/Vars.js index 02d293c3..60cac8b0 100644 --- a/app/src/components/Vars.js +++ b/app/src/components/Vars.js @@ -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', diff --git a/app/src/components/VideoEditMenu.js b/app/src/components/VideoEditMenu.js new file mode 100644 index 00000000..d84860a7 --- /dev/null +++ b/app/src/components/VideoEditMenu.js @@ -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 ; + } + + const finished = FINISHED_STATUSES.includes(job.status); + const percent = job.progress ?? 0; + const logTail = (job.log || []).slice(-8); + + return + + {job.status} + {!finished && } + + + {job.error && {job.error}} + {logTail.length > 0 &&
{logTail.join('\n')}
} +
+} + +/** + * 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 + Transcode Video + + + + 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. + + {!jobId && <> + setAudioCodec(value || TRANSCODE_COPY)} + disabled={!defaultsLoaded} + allowDeselect={false} + /> +