videos: codec download preferences with transcode and strict-fail options (#701)
Some checks failed
CodeQL / Analyze (push) Has been cancelled
Controller Tests / controller-tests (push) Has been cancelled
Jest Tests / jest-tests (push) Has been cancelled

* videos: codec download preferences with transcode and strict-fail options

Add video_codecs/audio_codecs ordered preference lists to the video,
channel, and RSS downloaders, alongside the existing resolution
selector.  Codec preference is codec-major: a preferred codec at a
lower resolution beats another codec at a higher resolution.

When 'transcode' is enabled, a downloaded file whose streams do not
match the preferences is re-encoded with ffmpeg after download (only
the mismatching stream; targets are extensible maps, currently h264
and aac/opus/mp3).  When 'strict_codecs' is enabled and transcode is
not, a download with no matching format fails permanently instead of
falling back.

Empty codec lists produce a byte-identical yt-dlp command to before.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* videos: honor strict_codecs when transcode cannot produce the preference

Review fixes:
- strict_codecs is now suppressed only when transcoding can produce a
  preferred codec for every non-empty preference list (new
  transcode_can_satisfy_codecs); av1-only preferences with transcode
  enabled fail under strict instead of silently keeping the file.
- No partial transcode: an unfixable video mismatch blocks an
  audio-only conversion (and vice versa); the mismatch falls through
  to strict/keep.
- fsync the transcode output before rename, and the directory after,
  so power loss on a Pi cannot leave a truncated final file.
- mp3 yt-dlp pattern matches mp4a.6B as well as mp4a.6b.
- ffmpeg maps use 0:V:0 (excludes attached pictures) and 0🅰️0?
  (tolerates missing audio).
- Strict toggle is no longer disabled by transcode in the UI; popup
  wording corrected.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* videos: serialize transcodes machine-wide via shared_ctx lock

Sanic runs multiple worker processes, so an asyncio primitive cannot
serialize transcodes across download workers.  A multiprocessing.Lock
in shared_ctx now guarantees only one ffmpeg transcode runs at a time
on the machine; waiting workers poll the lock asynchronously so the
event loop stays responsive while a transcode holds it for hours.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* videos: transcode-lock review fixes

- Document that a crashed lock holder requires an API restart; this is
  accepted rather than adding owner-death recovery.
- Move the 'Transcoding' user notification to after the lock is
  acquired, so it fires when work begins rather than before a
  potentially hours-long wait.
- Soften the lock test docstring to what it measures (in-process
  wait/release); trim the acquire docstring to the polling rationale.
- Give transcode_lock its own section header in contexts.py.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
lrnselfreliance 2026-09-07 09:11:39 -06:00 • committed by Roland
parent e0ae71048a
commit 0b61d3ab08
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
13 changed files with 1101 additions and 9 deletions

View file

@ -0,0 +1,53 @@
import React from 'react';
import {screen} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {CodecSettingsForm} from './Download';
import {createTestForm, renderUI} from '../test-utils';
/** createTestForm implements getCustomProps but not getSelectionProps (used by
* MultiSelectField); the shapes are compatible for these tests. */
const createCodecForm = (initialData) => {
const form = createTestForm(initialData);
form.getSelectionProps = form.getCustomProps;
return form;
};
describe('CodecSettingsForm', () => {
it('renders codec selectors and toggles', () => {
const form = createCodecForm({settings: {video_codecs: ['h264'], audio_codecs: []}});
renderUI(<CodecSettingsForm form={form}/>);
expect(screen.getByText('Video Codecs')).toBeInTheDocument();
expect(screen.getByText('Audio Codecs')).toBeInTheDocument();
expect(screen.getByText('Transcode to preferred codecs')).toBeInTheDocument();
expect(screen.getByText('Fail if codecs unavailable')).toBeInTheDocument();
});
it('keeps the strict toggle usable while transcode is enabled', () => {
// Strict still matters with transcode on: a preference with no transcode target
// (e.g. av1) cannot be fixed by transcoding, so the backend honors strict then.
const form = createCodecForm({settings: {transcode: true, strict_codecs: true}});
renderUI(<CodecSettingsForm form={form}/>);
const toggles = screen.getAllByTestId('toggle');
const [transcodeToggle, strictToggle] = toggles.map(i => i.querySelector('input') || i);
expect(transcodeToggle).toBeChecked();
expect(strictToggle).toBeChecked();
expect(strictToggle).not.toBeDisabled();
});
it('toggling strict updates the form', async () => {
const form = createCodecForm({settings: {transcode: false, strict_codecs: false}});
renderUI(<CodecSettingsForm form={form}/>);
const toggles = screen.getAllByTestId('toggle');
const [, strictToggle] = toggles.map(i => i.querySelector('input') || i);
expect(strictToggle).not.toBeDisabled();
await userEvent.click(strictToggle);
expect(form.formData.settings.strict_codecs).toBe(true);
});
});

View file

@ -186,7 +186,10 @@ describe('<EditRSSDownloadForm />', () => {
"720p",
"480p",
"maximum"
]
],
video_codecs: ["h264"],
audio_codecs: ["aac"],
transcode: true,
},
sub_downloader: "video",
tag_names: ['Automotive'],
@ -265,6 +268,9 @@ describe('<EditRSSDownloadForm />', () => {
video_format: 'mp4',
minimum_duration: null,
maximum_duration: null,
video_codecs: ['h264'],
audio_codecs: ['aac'],
transcode: true,
});
});
});

View file

@ -26,11 +26,13 @@ import {
defaultAudioFormatOption,
defaultVideoFormatOption,
defaultVideoResolutionOptions,
downloadAudioCodecOptions,
downloadAudioFormatOptions,
Downloaders,
downloadFormatOptions,
downloadOrderOptions,
downloadResolutionOptions,
downloadVideoCodecOptions,
extendedFrequencyOptions,
frequencyOptions,
weeklyOption
@ -434,6 +436,71 @@ export function AudioFormatSelectorForm({form, name = 'audio_format', path = 'se
</div>
}
export function VideoCodecSelectorForm({form, name = 'video_codecs', path = 'settings.video_codecs'}) {
return <div>
<InfoHeader
headerSize='h5'
headerContent='Video Codecs'
popupContent='Prefer these video codecs, in order. A preferred codec at a lower resolution is
chosen over other codecs at a higher resolution. Leave empty to accept any codec.'
for_='video_codecs_input'
/>
<MultiSelectField
form={form}
name={name}
path={path}
options={downloadVideoCodecOptions}
/>
</div>
}
export function AudioCodecSelectorForm({form, name = 'audio_codecs', path = 'settings.audio_codecs'}) {
return <div>
<InfoHeader
headerSize='h5'
headerContent='Audio Codecs'
popupContent='Prefer these audio codecs, in order. Leave empty to accept any codec.'
for_='audio_codecs_input'
/>
<MultiSelectField
form={form}
name={name}
path={path}
options={downloadAudioCodecOptions}
/>
</div>
}
/** Codec preference selectors with the transcode/strict toggles. */
export function CodecSettingsForm({form, codecsPathPrefix = 'settings.'}) {
const [transcodeProps] = form.getCustomProps({name: 'transcode', path: `${codecsPathPrefix}transcode`});
const [strictProps] = form.getCustomProps({name: 'strict_codecs', path: `${codecsPathPrefix}strict_codecs`});
return <Stack gap='md'>
<Group grow align='flex-start' wrap='wrap'>
<VideoCodecSelectorForm form={form} path={`${codecsPathPrefix}video_codecs`}/>
<AudioCodecSelectorForm form={form} path={`${codecsPathPrefix}audio_codecs`}/>
</Group>
<Group grow align='flex-start' wrap='wrap'>
<Toggle
label='Transcode to preferred codecs'
checked={!!transcodeProps.value}
disabled={form.disabled}
onChange={transcodeProps.onChange}
info='If no preferred codec is available, convert the video after downloading.
Transcoding is slow and slightly reduces quality.'
/>
<Toggle
label='Fail if codecs unavailable'
checked={!!strictProps.value}
disabled={form.disabled}
onChange={strictProps.onChange}
info='Fail the download when no preferred codec is available, instead of falling
back to any codec. Ignored when transcoding can produce a preferred codec.'
/>
</Group>
</Stack>
}
function VideoDurationLimit({form, name, path, label, helpContent, placeholder, helpPosition}) {
return <NumberField
form={form}
@ -478,6 +545,7 @@ function AdvancedVideoSettings({form, isVideoLevel = false, isConfigLoaded = tru
return <SimpleAccordion title='Advanced Settings'>
<Stack gap='md'>
<CodecSettingsForm form={form}/>
<Group grow align='flex-start' wrap='wrap'>
<AudioOnlyToggleLikeVideoSetting form={form} name='writesubtitles' path='settings.writesubtitles'
label='Download subtitles' icon='closed captioning'/>

View file

@ -143,6 +143,21 @@ export const downloadAudioFormatOptions = [
export const defaultAudioFormatOption = 'mp3';
export const downloadVideoCodecOptions = [
{key: 'h264', text: 'h264 (avc1)', value: 'h264'},
{key: 'vp9', text: 'vp9', value: 'vp9'},
{key: 'av1', text: 'av1', value: 'av1'},
{key: 'vp8', text: 'vp8', value: 'vp8'},
{key: 'hevc', text: 'hevc (h265)', value: 'hevc'},
];
export const downloadAudioCodecOptions = [
{key: 'aac', text: 'aac', value: 'aac'},
{key: 'opus', text: 'opus', value: 'opus'},
{key: 'mp3', text: 'mp3', value: 'mp3'},
{key: 'vorbis', text: 'vorbis', value: 'vorbis'},
];
export const Downloaders = {
Archive: 'archive',
File: 'file',

View file

@ -64,7 +64,7 @@ import {QueryContext} from "../contexts/contexts";
import _ from "lodash";
import {defaultFileOrder, defaultSearchOrder} from "./Vars";
import {InputForm, ToggleForm, useForm} from "../hooks/useForm";
import {VideoFormatSelectorForm, VideoResolutionSelectorForm} from "./Download";
import {CodecSettingsForm, VideoFormatSelectorForm, VideoResolutionSelectorForm} from "./Download";
import {BatchReorganizeModal} from "./collections/BatchReorganizeModal";
export function VideoWrapper() {
@ -350,6 +350,10 @@ export function VideosSettingsPage() {
download_missing_video_comments: false,
user_agent: '',
sleep_requests: 0.75,
video_codecs: [],
audio_codecs: [],
transcode: false,
strict_codecs: false,
};
const configSubmitter = async () => {
@ -396,6 +400,7 @@ export function VideosSettingsPage() {
/>
<VideoFileNameForm form={configForm}/>
</div>
<CodecSettingsForm form={configForm} codecsPathPrefix=''/>
<div style={settingsGridStyle}>
<ToggleForm
form={configForm}