feat(web): FFmpeg profile, filler preset, watermark editors (#143)

Three new SPA list+editor surfaces, closing the Blazor-only gap found in the
#91 phase-(b) recon:

- FFmpeg Profiles (System group): list with resolution/video/audio summary +
  add/copy/delete; full General/Video/Audio editor. Per-hwaccel video-format
  and profile rules ported from FFmpegProfileEditViewModelValidator; video
  preset list ported from FFmpegLibraryHelper.PresetsForFFmpegProfile /
  AvailablePresets.ForAccelAndFormat (cited in code). Resolutions from
  /api/settings/resolutions, hwaccel kinds from the new lookup endpoint.
  Copy = client-side clone into the create form (no server copy endpoint).
- Filler Presets (Media group): list + editor with the Blazor VM interlocks
  (Fallback/Tail force mode None; non-MidRoll clears expression; Fallback
  disables chapters; Playlist collection type forces Count mode; duration/
  count/pad fields gated by mode). Collection pickers use the existing
  /api/library/browse client for all seven collection types incl. Playlist.
- Watermarks (System group): list + editor with mode-driven field enabling,
  ChannelLogo vs Custom image source, upload via /api/artwork/uploads
  (target=watermark) and preview via /artwork/watermarks/{path}.
- App.tsx: ScreenIds/routes (sub-paths /add + /{id}) and nav registration;
  api modules ffmpegProfiles/fillerPresets/watermarks with URL-assert tests;
  SettingsScreen Classic-UI help text updated (these are no longer
  Blazor-only) and the FFmpeg-profiles card now links to the new screen.
- Regenerated web/src/api/generated/v1.d.ts from the #159 OpenAPI changes.

web verification: typecheck clean; vitest 188/188 (14 files); vite build OK;
eslint clean on touched files.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-07 14:33:01 +02:00
co-authored by Claude Fable 5
parent 46c8c2e2dc
commit e95eed11dd
14 changed files with 2805 additions and 16 deletions
+2 -2
View File
@@ -2712,7 +2712,7 @@ describe('Settings screen (#93)', () => {
expect(screen.queryByRole('button', { name: 'Delete 1920×1080' })).not.toBeInTheDocument();
});
it('renders FFmpeg profiles and media sources as read-only cards with a Legacy UI callout', async () => {
it('renders FFmpeg profiles read-only with a link to the FFmpeg Profiles editor, and media sources', async () => {
mockDashboardApi({
ffmpegProfiles: [ffmpegProfile({ id: 1, name: '1080p H.264' }), ffmpegProfile({ id: 2, name: '720p H.264' })],
mediaSources: [mediaSource({ id: 30, kind: 'Local', name: 'Local' })]
@@ -2722,7 +2722,7 @@ describe('Settings screen (#93)', () => {
expect((await screen.findAllByText('1080p H.264')).length).toBeGreaterThan(0);
expect(screen.getAllByText('720p H.264').length).toBeGreaterThan(0);
expect(screen.getAllByText('Legacy UI').length).toBeGreaterThan(0);
expect(screen.getByRole('button', { name: /Manage FFmpeg profiles/ })).toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /^System/ }));
expect(await screen.findByText('Local')).toBeInTheDocument();
+58 -2
View File
@@ -45,7 +45,9 @@ import {
Server,
Settings,
Shuffle,
SlidersHorizontal,
Sparkles,
Stamp,
Stethoscope,
Timer,
Trash2,
@@ -56,7 +58,10 @@ import chicoryMarkUrl from '../../design-system/assets/chicory-mark.svg';
import { ChannelBuilderScreen } from './builder/ChannelBuilder';
import { ChannelEditScreen } from './screens/ChannelEditScreen';
import { CollectionsScreen } from './screens/CollectionsScreen';
import { FFmpegProfilesScreen } from './screens/FFmpegProfilesScreen';
import { FillerPresetsScreen } from './screens/FillerPresetsScreen';
import { SettingsScreen } from './screens/SettingsScreen';
import { WatermarksScreen } from './screens/WatermarksScreen';
import { navigateToPath } from './routing';
import {
Badge,
@@ -131,7 +136,10 @@ type ScreenId =
| 'schedules'
| 'playouts'
| 'collections'
| 'fillerPresets'
| 'libraries'
| 'ffmpegProfiles'
| 'watermarks'
| 'settings';
interface ScreenRoute {
@@ -244,6 +252,18 @@ const routes: ScreenRoute[] = [
primaryAction: 'Add Collection',
placeholder: 'Collections workspace'
},
{
id: 'fillerPresets',
path: '/app/filler-presets',
label: 'Filler Presets',
title: 'Filler Presets',
kicker: 'Media',
description: 'Pre/mid/post-roll, tail and fallback filler presets used by schedules.',
icon: <Film aria-hidden="true" size={16} />,
primaryAction: 'Add Filler Preset',
placeholder: 'Filler presets workspace',
allowSubPaths: true
},
{
id: 'libraries',
path: '/app/libraries',
@@ -255,6 +275,30 @@ const routes: ScreenRoute[] = [
primaryAction: 'Scan',
placeholder: 'Libraries workspace'
},
{
id: 'ffmpegProfiles',
path: '/app/ffmpeg-profiles',
label: 'FFmpeg Profiles',
title: 'FFmpeg Profiles',
kicker: 'System',
description: 'Transcoding profiles: resolution, video/audio formats, hardware acceleration.',
icon: <SlidersHorizontal aria-hidden="true" size={16} />,
primaryAction: 'Add Profile',
placeholder: 'FFmpeg profiles workspace',
allowSubPaths: true
},
{
id: 'watermarks',
path: '/app/watermarks',
label: 'Watermarks',
title: 'Watermarks',
kicker: 'System',
description: 'Channel watermark overlays: image, position, size and opacity.',
icon: <Stamp aria-hidden="true" size={16} />,
primaryAction: 'Add Watermark',
placeholder: 'Watermarks workspace',
allowSubPaths: true
},
{
id: 'settings',
path: '/app/settings',
@@ -279,8 +323,8 @@ const primaryNavIds: ScreenId[] = [
'schedules',
'playouts'
];
const mediaNavIds: ScreenId[] = ['collections', 'libraries'];
const systemNavIds: ScreenId[] = ['settings'];
const mediaNavIds: ScreenId[] = ['collections', 'fillerPresets', 'libraries'];
const systemNavIds: ScreenId[] = ['ffmpegProfiles', 'watermarks', 'settings'];
function normalizePath(pathname: string): string {
return pathname.replace(/\/+$/, '') || '/app';
@@ -2887,6 +2931,18 @@ function ScreenContent({
return <CollectionsScreen />;
}
if (route.id === 'fillerPresets') {
return <FillerPresetsScreen />;
}
if (route.id === 'ffmpegProfiles') {
return <FFmpegProfilesScreen />;
}
if (route.id === 'watermarks') {
return <WatermarksScreen />;
}
return <PlaceholderScreen route={route} />;
}
+105
View File
@@ -0,0 +1,105 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
createFFmpegProfile,
deleteFFmpegProfile,
getFFmpegProfile,
getHardwareAccelerationKinds,
updateFFmpegProfile,
type CreateFFmpegProfileRequest
} from './ffmpegProfiles';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
function noContent(): Response {
return new Response(null, { status: 204 });
}
const sampleRequest: CreateFFmpegProfileRequest = {
allowBFrames: false,
audioBitrate: 192,
audioBufferSize: 384,
audioChannels: 2,
audioFormat: 'Aac',
audioSampleRate: 48,
bitDepth: 'EightBit',
deinterlaceVideo: false,
hardwareAcceleration: 'None',
name: 'New',
normalizeAudio: true,
normalizeColors: true,
normalizeFramerate: false,
normalizeLoudnessMode: 'Off',
normalizeVideo: true,
padMode: 'Software',
qsvExtraHardwareFrames: null,
resolutionId: 1,
scalingBehavior: 'ScaleAndPad',
tonemapAlgorithm: 'Linear',
targetLoudness: null,
threadCount: 0,
vaapiDevice: '',
vaapiDisplay: '',
vaapiDriver: 'Default',
videoBitrate: 2000,
videoBufferSize: 4000,
videoFormat: 'H264',
videoPreset: '',
videoProfile: 'high'
};
describe('ffmpeg profiles api client', () => {
beforeEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
});
it('getFFmpegProfile fetches a profile by id', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4, name: 'Default' }));
await expect(getFFmpegProfile(4)).resolves.toMatchObject({ id: 4 });
expect(fetchMock).toHaveBeenCalledWith('/api/ffmpeg/profiles/4', expect.objectContaining({ method: 'GET' }));
});
it('createFFmpegProfile POSTs the request body', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 7, name: 'New' }, 201));
await expect(createFFmpegProfile(sampleRequest)).resolves.toMatchObject({ id: 7 });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/ffmpeg/profiles');
expect(init).toMatchObject({ method: 'POST' });
expect(JSON.parse(String(init?.body)).resolutionId).toBe(1);
});
it('updateFFmpegProfile PUTs to the id route', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 3, name: 'Edited' }));
await updateFFmpegProfile(3, sampleRequest);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/ffmpeg/profiles/3');
expect(init).toMatchObject({ method: 'PUT' });
});
it('deleteFFmpegProfile issues a DELETE and resolves on 204', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await expect(deleteFFmpegProfile(9)).resolves.toBeUndefined();
expect(fetchMock).toHaveBeenCalledWith('/api/ffmpeg/profiles/9', expect.objectContaining({ method: 'DELETE' }));
});
it('getHardwareAccelerationKinds fetches the lookup', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse(['None', 'Nvenc']));
await expect(getHardwareAccelerationKinds()).resolves.toEqual(['None', 'Nvenc']);
expect(fetchMock).toHaveBeenCalledWith(
'/api/ffmpeg/hardware-acceleration-kinds',
expect.objectContaining({ method: 'GET' })
);
});
});
+43
View File
@@ -0,0 +1,43 @@
import { ApiError, request } from './client';
import type { components } from './generated/v1';
// The list endpoint (GET /api/ffmpeg/profiles) is already provided by pickers.ts as
// getFFmpegProfiles() returning FFmpegProfile (= FFmpegFullProfileResponseModel). This
// module adds the by-id read, the mutations, and the hardware-acceleration lookup.
export type FFmpegProfileDetail = components['schemas']['FFmpegFullProfileResponseModel'];
export type CreateFFmpegProfileRequest = components['schemas']['CreateFFmpegProfileRequest'];
export type UpdateFFmpegProfileRequest = components['schemas']['UpdateFFmpegProfileRequest'];
export type HardwareAccelerationKind = components['schemas']['HardwareAccelerationKind'];
export function getFFmpegProfile(id: number): Promise<FFmpegProfileDetail> {
return request<FFmpegProfileDetail>(`/api/ffmpeg/profiles/${id}`);
}
export function createFFmpegProfile(body: CreateFFmpegProfileRequest): Promise<FFmpegProfileDetail> {
return request<FFmpegProfileDetail>('/api/ffmpeg/profiles', { body, method: 'POST' });
}
export function updateFFmpegProfile(id: number, body: UpdateFFmpegProfileRequest): Promise<FFmpegProfileDetail> {
return request<FFmpegProfileDetail>(`/api/ffmpeg/profiles/${id}`, { body, method: 'PUT' });
}
export function deleteFFmpegProfile(id: number): Promise<void> {
return request<void>(`/api/ffmpeg/profiles/${id}`, { method: 'DELETE' });
}
export function getHardwareAccelerationKinds(): Promise<HardwareAccelerationKind[]> {
return request<HardwareAccelerationKind[]>('/api/ffmpeg/hardware-acceleration-kinds');
}
export function messageFromFFmpegProfileError(error: unknown, fallback = 'Unable to load FFmpeg profiles'): string {
if (error instanceof ApiError) {
return error.detail ?? error.message;
}
if (error instanceof Error) {
return error.message;
}
return fallback;
}
+79
View File
@@ -0,0 +1,79 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
createFillerPreset,
deleteFillerPreset,
getFillerPreset,
updateFillerPreset,
type CreateFillerPresetRequest
} from './fillerPresets';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
function noContent(): Response {
return new Response(null, { status: 204 });
}
const sampleRequest: CreateFillerPresetRequest = {
allowWatermarks: true,
collectionId: 5,
collectionType: 'Collection',
count: 3,
duration: null,
expression: null,
fillerKind: 'PreRoll',
fillerMode: 'Count',
mediaItemId: null,
multiCollectionId: null,
name: 'Intro',
padToNearestMinute: null,
playlistId: null,
smartCollectionId: null,
useChaptersAsMediaItems: false
};
describe('filler presets api client', () => {
beforeEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
});
it('getFillerPreset fetches a preset by id', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4, name: 'Intro' }));
await expect(getFillerPreset(4)).resolves.toMatchObject({ id: 4 });
expect(fetchMock).toHaveBeenCalledWith('/api/filler-presets/4', expect.objectContaining({ method: 'GET' }));
});
it('createFillerPreset POSTs the request body', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 7, name: 'Intro' }, 201));
await expect(createFillerPreset(sampleRequest)).resolves.toMatchObject({ id: 7 });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/filler-presets');
expect(init).toMatchObject({ method: 'POST' });
expect(JSON.parse(String(init?.body)).fillerKind).toBe('PreRoll');
});
it('updateFillerPreset PUTs to the id route', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 3, name: 'Intro' }));
await updateFillerPreset(3, sampleRequest);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/filler-presets/3');
expect(init).toMatchObject({ method: 'PUT' });
});
it('deleteFillerPreset issues a DELETE and resolves on 204', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await expect(deleteFillerPreset(9)).resolves.toBeUndefined();
expect(fetchMock).toHaveBeenCalledWith('/api/filler-presets/9', expect.objectContaining({ method: 'DELETE' }));
});
});
+38
View File
@@ -0,0 +1,38 @@
import { ApiError, request } from './client';
import type { components } from './generated/v1';
// The list endpoint (GET /api/filler-presets) is picker-grade (id + name) and is already
// provided by pickers.ts as getFillerPresets(). This module adds the by-id read (full
// model) and the mutations.
export type FillerPresetDetail = components['schemas']['FillerPresetFullResponseModel'];
export type CreateFillerPresetRequest = components['schemas']['CreateFillerPresetRequest'];
export type UpdateFillerPresetRequest = components['schemas']['UpdateFillerPresetRequest'];
export function getFillerPreset(id: number): Promise<FillerPresetDetail> {
return request<FillerPresetDetail>(`/api/filler-presets/${id}`);
}
export function createFillerPreset(body: CreateFillerPresetRequest): Promise<FillerPresetDetail> {
return request<FillerPresetDetail>('/api/filler-presets', { body, method: 'POST' });
}
export function updateFillerPreset(id: number, body: UpdateFillerPresetRequest): Promise<FillerPresetDetail> {
return request<FillerPresetDetail>(`/api/filler-presets/${id}`, { body, method: 'PUT' });
}
export function deleteFillerPreset(id: number): Promise<void> {
return request<void>(`/api/filler-presets/${id}`, { method: 'DELETE' });
}
export function messageFromFillerPresetError(error: unknown, fallback = 'Unable to load filler presets'): string {
if (error instanceof ApiError) {
return error.detail ?? error.message;
}
if (error instanceof Error) {
return error.message;
}
return fallback;
}
+122 -9
View File
@@ -303,6 +303,23 @@ export interface components {
"normalizeFramerate": boolean;
"normalizeColors": boolean;
"deinterlaceVideo": boolean;
};
"CreateFillerPresetRequest": {
"name": string;
"fillerKind": components["schemas"]["FillerKind"];
"fillerMode": components["schemas"]["FillerMode"];
"duration": null | string;
"count": null | number;
"padToNearestMinute": null | number;
"allowWatermarks": boolean;
"collectionType": components["schemas"]["CollectionType"];
"collectionId": null | number;
"mediaItemId": null | number;
"multiCollectionId": null | number;
"smartCollectionId": null | number;
"playlistId": null | number;
"expression": null | string;
"useChaptersAsMediaItems": boolean;
};
"CreatePlayoutRequest": {
"channelId": number;
@@ -323,21 +340,43 @@ export interface components {
"CreateSmartCollectionRequest": {
"name": null | string;
"query": null | string;
};
"CreateWatermarkRequest": {
"name": string;
"mode": components["schemas"]["ChannelWatermarkMode"];
"imageSource": components["schemas"]["ChannelWatermarkImageSource"];
"image": null | string;
"imageContentType": null | string;
"location": components["schemas"]["WatermarkLocation"];
"size": components["schemas"]["WatermarkSize"];
"width": number;
"horizontalMargin": number;
"verticalMargin": number;
"frequencyMinutes": number;
"durationSeconds": number;
"opacity": number;
"opacityExpression": null | string;
"zIndex": number;
"placeWithinSourceContent": boolean;
};
"FFmpegFullProfileResponseModel": {
"id": number;
"name": null | string;
"name": string;
"threadCount": number;
"normalizeAudio": boolean;
"normalizeVideo": boolean;
"hardwareAcceleration": components["schemas"]["HardwareAccelerationKind"];
"vaapiDisplay": null | string;
"vaapiDisplay": string;
"vaapiDriver": components["schemas"]["VaapiDriver"];
"vaapiDevice": null | string;
"vaapiDevice": string;
"qsvExtraHardwareFrames": null | number;
"resolution": null | string;
"resolutionId": number;
"resolution": string;
"scalingBehavior": components["schemas"]["ScalingBehavior"];
"padMode": components["schemas"]["FilterMode"];
"videoFormat": components["schemas"]["FFmpegProfileVideoFormat"];
"videoProfile": null | string;
"videoPreset": null | string;
"videoProfile": string;
"videoPreset": string;
"allowBFrames": boolean;
"bitDepth": components["schemas"]["FFmpegProfileBitDepth"];
"videoBitrate": number;
@@ -347,10 +386,12 @@ export interface components {
"audioBitrate": number;
"audioBufferSize": number;
"normalizeLoudnessMode": components["schemas"]["NormalizeLoudnessMode"];
"targetLoudness": null | number;
"audioChannels": number;
"audioSampleRate": number;
"normalizeFramerate": boolean;
"deinterlaceVideo": null | boolean;
"normalizeColors": boolean;
"deinterlaceVideo": boolean;
};
"FFmpegProfileAudioFormat": "None" | "Aac" | "Ac3" | "AacLatm" | "Copy";
"FFmpegProfileBitDepth": "EightBit" | "TenBit";
@@ -375,6 +416,24 @@ export interface components {
};
"FillerKind": "None" | "PreRoll" | "MidRoll" | "PostRoll" | "Tail" | "Fallback" | "GuideMode" | "DecoDefault";
"FillerMode": "None" | "Duration" | "Count" | "Pad" | "RandomCount";
"FillerPresetFullResponseModel": {
"id": number;
"name": string;
"fillerKind": components["schemas"]["FillerKind"];
"fillerMode": components["schemas"]["FillerMode"];
"duration": null | string;
"count": null | number;
"padToNearestMinute": null | number;
"allowWatermarks": boolean;
"collectionType": components["schemas"]["CollectionType"];
"collectionId": null | number;
"mediaItemId": null | number;
"multiCollectionId": null | number;
"smartCollectionId": null | number;
"playlistId": null | number;
"expression": null | string;
"useChaptersAsMediaItems": boolean;
};
"FillerPresetResponseModel": {
"id": number;
"name": null | string;
@@ -832,6 +891,23 @@ export interface components {
"initialSegmentCount": number;
"hlsDirectOutputFormat": components["schemas"]["OutputFormatKind"];
"defaultMpegTsScript": null | string;
};
"UpdateFillerPresetRequest": {
"name": string;
"fillerKind": components["schemas"]["FillerKind"];
"fillerMode": components["schemas"]["FillerMode"];
"duration": null | string;
"count": null | number;
"padToNearestMinute": null | number;
"allowWatermarks": boolean;
"collectionType": components["schemas"]["CollectionType"];
"collectionId": null | number;
"mediaItemId": null | number;
"multiCollectionId": null | number;
"smartCollectionId": null | number;
"playlistId": null | number;
"expression": null | string;
"useChaptersAsMediaItems": boolean;
};
"UpdateHdhrSettingsRequest": {
"tunerCount": number;
@@ -867,6 +943,24 @@ export interface components {
"UpdateUiSettingsRequest": {
"isDarkMode": boolean;
"language": null | string;
};
"UpdateWatermarkRequest": {
"name": string;
"mode": components["schemas"]["ChannelWatermarkMode"];
"imageSource": components["schemas"]["ChannelWatermarkImageSource"];
"image": null | string;
"imageContentType": null | string;
"location": components["schemas"]["WatermarkLocation"];
"size": components["schemas"]["WatermarkSize"];
"width": number;
"horizontalMargin": number;
"verticalMargin": number;
"frequencyMinutes": number;
"durationSeconds": number;
"opacity": number;
"opacityExpression": null | string;
"zIndex": number;
"placeWithinSourceContent": boolean;
};
"UpdateXmltvSettingsRequest": {
"daysToBuild": number;
@@ -874,12 +968,31 @@ export interface components {
"blockBehavior": components["schemas"]["XmltvBlockBehavior"];
};
"VaapiDriver": "Default" | "iHD" | "i965" | "RadeonSI" | "Nouveau";
"WatermarkLocation": number;
"WatermarkFullResponseModel": {
"id": number;
"name": string;
"mode": components["schemas"]["ChannelWatermarkMode"];
"imageSource": components["schemas"]["ChannelWatermarkImageSource"];
"image": null | string;
"imageContentType": null | string;
"location": components["schemas"]["WatermarkLocation"];
"size": components["schemas"]["WatermarkSize"];
"width": number;
"horizontalMargin": number;
"verticalMargin": number;
"frequencyMinutes": number;
"durationSeconds": number;
"opacity": number;
"opacityExpression": null | string;
"zIndex": number;
"placeWithinSourceContent": boolean;
};
"WatermarkLocation": "BottomRight" | "BottomLeft" | "TopRight" | "TopLeft" | "TopMiddle" | "RightMiddle" | "BottomMiddle" | "LeftMiddle" | "MiddleCenter";
"WatermarkResponseModel": {
"id": number;
"name": null | string;
};
"WatermarkSize": number;
"WatermarkSize": "Scaled" | "ActualSize";
"WatermarkViewModel": {
"id": number;
"image": components["schemas"]["ArtworkContentTypeModel"];
+3
View File
@@ -5,6 +5,8 @@ export * from './channelTemplates';
export * from './client';
export * from './collections';
export * from './dashboard';
export * from './ffmpegProfiles';
export * from './fillerPresets';
export * from './guide';
export * from './libraries';
export * from './libraryBrowse';
@@ -13,3 +15,4 @@ export * from './playouts';
export * from './schedules';
export * from './settings';
export * from './useChannelsQuery';
export * from './watermarks';
+86
View File
@@ -0,0 +1,86 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
createWatermark,
deleteWatermark,
getWatermark,
updateWatermark,
watermarkImageUrl,
type CreateWatermarkRequest
} from './watermarks';
function jsonResponse(body: unknown, status = 200): Response {
return new Response(JSON.stringify(body), {
headers: { 'Content-Type': 'application/json' },
status
});
}
function noContent(): Response {
return new Response(null, { status: 204 });
}
const sampleRequest: CreateWatermarkRequest = {
durationSeconds: 15,
frequencyMinutes: 15,
horizontalMargin: 5,
image: 'abc.png',
imageContentType: 'image/png',
imageSource: 'Custom',
location: 'BottomRight',
mode: 'Permanent',
name: 'Corner Logo',
opacity: 100,
opacityExpression: null,
placeWithinSourceContent: false,
size: 'Scaled',
verticalMargin: 5,
width: 15,
zIndex: 0
};
describe('watermarks api client', () => {
beforeEach(() => {
window.localStorage.clear();
vi.restoreAllMocks();
});
it('getWatermark fetches a watermark by id', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 4, name: 'Corner Logo' }));
await expect(getWatermark(4)).resolves.toMatchObject({ id: 4 });
expect(fetchMock).toHaveBeenCalledWith('/api/watermarks/4', expect.objectContaining({ method: 'GET' }));
});
it('createWatermark POSTs the request body', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 7, name: 'Corner Logo' }, 201));
await expect(createWatermark(sampleRequest)).resolves.toMatchObject({ id: 7 });
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/watermarks');
expect(init).toMatchObject({ method: 'POST' });
expect(JSON.parse(String(init?.body)).mode).toBe('Permanent');
});
it('updateWatermark PUTs to the id route', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(jsonResponse({ id: 3, name: 'Corner Logo' }));
await updateWatermark(3, sampleRequest);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe('/api/watermarks/3');
expect(init).toMatchObject({ method: 'PUT' });
});
it('deleteWatermark issues a DELETE and resolves on 204', async () => {
const fetchMock = vi.spyOn(window, 'fetch').mockResolvedValue(noContent());
await expect(deleteWatermark(9)).resolves.toBeUndefined();
expect(fetchMock).toHaveBeenCalledWith('/api/watermarks/9', expect.objectContaining({ method: 'DELETE' }));
});
it('watermarkImageUrl encodes the content type query', () => {
expect(watermarkImageUrl('abc.png', 'image/png')).toBe('/artwork/watermarks/abc.png?contentType=image%2Fpng');
expect(watermarkImageUrl('abc.png')).toBe('/artwork/watermarks/abc.png');
});
});
+47
View File
@@ -0,0 +1,47 @@
import { ApiError, request } from './client';
import type { components } from './generated/v1';
// The list endpoint (GET /api/watermarks) is picker-grade (id + name) and is already
// provided by pickers.ts as getWatermarks(). This module adds the by-id read (full model)
// and the mutations. Image upload is handled by artwork.ts (uploadArtwork(file,'watermark')).
export type WatermarkDetail = components['schemas']['WatermarkFullResponseModel'];
export type CreateWatermarkRequest = components['schemas']['CreateWatermarkRequest'];
export type UpdateWatermarkRequest = components['schemas']['UpdateWatermarkRequest'];
export function getWatermark(id: number): Promise<WatermarkDetail> {
return request<WatermarkDetail>(`/api/watermarks/${id}`);
}
export function createWatermark(body: CreateWatermarkRequest): Promise<WatermarkDetail> {
return request<WatermarkDetail>('/api/watermarks', { body, method: 'POST' });
}
export function updateWatermark(id: number, body: UpdateWatermarkRequest): Promise<WatermarkDetail> {
return request<WatermarkDetail>(`/api/watermarks/${id}`, { body, method: 'PUT' });
}
export function deleteWatermark(id: number): Promise<void> {
return request<void>(`/api/watermarks/${id}`, { method: 'DELETE' });
}
// Preview URL for a custom watermark image. Mirrors the Blazor editor
// (WatermarkEditor.razor) which renders `artwork/watermarks/{path}?contentType=...` via
// ArtworkContentTypeModel.UrlWithContentType.
export function watermarkImageUrl(path: string, contentType?: null | string): string {
return contentType
? `/artwork/watermarks/${path}?contentType=${encodeURIComponent(contentType)}`
: `/artwork/watermarks/${path}`;
}
export function messageFromWatermarkError(error: unknown, fallback = 'Unable to load watermarks'): string {
if (error instanceof ApiError) {
return error.detail ?? error.message;
}
if (error instanceof Error) {
return error.message;
}
return fallback;
}
+846
View File
@@ -0,0 +1,846 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { ArrowLeft, Check, Copy, Plus, SlidersHorizontal, Trash2, TriangleAlert } from 'lucide-react';
import { navigateToPath } from '../routing';
import { Badge, Button, Card, Checkbox, ConfirmDialog, IconButton, Input, Select, Spinner } from '../components';
import {
createFFmpegProfile,
deleteFFmpegProfile,
getFFmpegProfile,
getFFmpegProfiles,
getHardwareAccelerationKinds,
getResolutions,
messageFromFFmpegProfileError,
updateFFmpegProfile,
type CreateFFmpegProfileRequest,
type FFmpegProfile,
type HardwareAccelerationKind,
type Resolution
} from '../api';
const BASE_PATH = '/app/ffmpeg-profiles';
type Draft = CreateFFmpegProfileRequest;
/* ---------- enum option lists (mirror ErsatzTV/Pages/FFmpegEditor.razor) ---------- */
const SCALING_OPTIONS = [
{ label: 'Scale and Pad', value: 'ScaleAndPad' },
{ label: 'Stretch', value: 'Stretch' },
{ label: 'Crop', value: 'Crop' }
];
const PAD_MODE_OPTIONS = [
{ label: 'Hardware If Possible', value: 'HardwareIfPossible' },
{ label: 'Software', value: 'Software' }
];
const BIT_DEPTH_OPTIONS = [
{ label: '8-bit', value: 'EightBit' },
{ label: '10-bit', value: 'TenBit' }
];
const AUDIO_FORMAT_OPTIONS = [
{ label: 'aac', value: 'Aac' },
{ label: 'ac3', value: 'Ac3' },
{ label: 'aac (latm)', value: 'AacLatm' }
];
const LOUDNESS_OPTIONS = [
{ label: 'Off', value: 'Off' },
{ label: 'loudnorm', value: 'LoudNorm' }
];
const TONEMAP_OPTIONS = ['Linear', 'Clip', 'Gamma', 'Reinhard', 'Mobius', 'Hable'];
const VAAPI_DRIVER_OPTIONS = ['Default', 'iHD', 'i965', 'RadeonSI', 'Nouveau'];
// av1 is only offered for Nvenc / Vaapi / Qsv (see FFmpegEditor.razor)
function videoFormatOptions(hwaccel: HardwareAccelerationKind): Array<{ label: string; value: string }> {
const base = [
{ label: 'h264', value: 'H264' },
{ label: 'hevc', value: 'Hevc' },
{ label: 'mpeg-2', value: 'Mpeg2Video' }
];
if (hwaccel === 'Nvenc' || hwaccel === 'Vaapi' || hwaccel === 'Qsv') {
base.push({ label: 'av1', value: 'Av1' });
}
return base;
}
// main / high plus high444p (nvenc) or high10 (everything else), matching the Blazor select.
function videoProfileOptions(hwaccel: HardwareAccelerationKind): Array<{ label: string; value: string }> {
const base = [
{ label: 'main', value: 'main' },
{ label: 'high', value: 'high' }
];
base.push(hwaccel === 'Nvenc' ? { label: 'high444p', value: 'high444p' } : { label: 'high10', value: 'high10' });
return base;
}
// Ported from ErsatzTV.Core/FFmpeg/FFmpegLibraryHelper.cs -> PresetsForFFmpegProfile and
// ErsatzTV.FFmpeg/Preset/AvailablePresets.cs -> ForAccelAndFormat. Keep in sync with those.
function presetsFor(
hwaccel: HardwareAccelerationKind,
videoFormat: string,
bitDepth: string
): string[] {
const bits = bitDepth === 'TenBit' ? 10 : 8;
// 10-bit h264 always uses libx264
if (videoFormat === 'H264' && bits === 10) {
return ['veryfast'];
}
if (hwaccel === 'Nvenc' && videoFormat === 'H264' && bits === 8) {
return ['llhp', 'llhq'];
}
if (hwaccel === 'Nvenc' && videoFormat === 'Hevc') {
return ['llhp', 'llhq'];
}
if (hwaccel === 'Qsv' && (videoFormat === 'H264' || videoFormat === 'Hevc')) {
return ['veryfast'];
}
if (hwaccel === 'None' && (videoFormat === 'H264' || videoFormat === 'Hevc')) {
return ['veryfast'];
}
return [];
}
function hwaccelSupportsH264Profile(hwaccel: HardwareAccelerationKind): boolean {
return (
hwaccel === 'None' ||
hwaccel === 'Nvenc' ||
hwaccel === 'Qsv' ||
hwaccel === 'Vaapi' ||
hwaccel === 'VideoToolbox'
);
}
const ALLOWED_FORMATS: Partial<Record<HardwareAccelerationKind, string[]>> = {
Amf: ['H264', 'Hevc'],
Nvenc: ['H264', 'Hevc', 'Av1'],
Qsv: ['H264', 'Hevc', 'Mpeg2Video', 'Av1'],
Rkmpp: ['H264', 'Hevc'],
V4l2m2m: ['H264', 'Hevc'],
Vaapi: ['H264', 'Hevc', 'Mpeg2Video', 'Av1'],
VideoToolbox: ['H264', 'Hevc']
};
// Mirrors FFmpegProfileEditViewModelValidator. Returns the first blocking message, or null.
function validate(draft: Draft): null | string {
if (!draft.name?.trim()) {
return 'Name is required';
}
if (draft.threadCount < 0) {
return 'Thread count must be 0 or greater';
}
if (draft.normalizeVideo) {
if (draft.videoBitrate <= 0) {
return 'Video bitrate must be greater than 0';
}
if (draft.videoBufferSize <= 0) {
return 'Video buffer size must be greater than 0';
}
const allowed = ALLOWED_FORMATS[draft.hardwareAcceleration];
if (allowed && !allowed.includes(draft.videoFormat)) {
return `${draft.hardwareAcceleration} supports formats (${allowed.join(', ').toLowerCase()})`;
}
if (draft.videoFormat === 'Mpeg2Video' && draft.bitDepth === 'TenBit') {
return 'Mpeg2Video does not support 10-bit content';
}
if (draft.videoFormat === 'H264' && draft.bitDepth === 'TenBit') {
if (draft.hardwareAcceleration !== 'Nvenc' && draft.videoProfile !== 'high10') {
return 'VideoProfile must be high10 with 10-bit h264';
}
if (draft.hardwareAcceleration === 'Nvenc' && draft.videoProfile !== 'high444p') {
return 'VideoProfile must be high444p with NVIDIA 10-bit h264';
}
}
if (draft.videoFormat === 'H264' && draft.bitDepth === 'EightBit' && draft.videoProfile === 'high10') {
return 'VideoProfile cannot be high10 with 8-bit h264';
}
}
if (draft.normalizeAudio) {
if (draft.audioBitrate <= 0) {
return 'Audio bitrate must be greater than 0';
}
if (draft.audioChannels <= 0) {
return 'Audio channels must be greater than 0';
}
}
return null;
}
function defaultDraft(resolutionId: number): Draft {
return {
allowBFrames: false,
audioBitrate: 192,
audioBufferSize: 384,
audioChannels: 2,
audioFormat: 'Aac',
audioSampleRate: 48,
bitDepth: 'EightBit',
deinterlaceVideo: true,
hardwareAcceleration: 'None',
name: '',
normalizeAudio: true,
normalizeColors: true,
normalizeFramerate: false,
normalizeLoudnessMode: 'Off',
normalizeVideo: true,
padMode: 'Software',
qsvExtraHardwareFrames: 64,
resolutionId,
scalingBehavior: 'ScaleAndPad',
targetLoudness: null,
threadCount: 0,
tonemapAlgorithm: 'Linear',
vaapiDevice: '/dev/dri/renderD128',
vaapiDisplay: 'drm',
vaapiDriver: 'Default',
videoBitrate: 2000,
videoBufferSize: 4000,
videoFormat: 'H264',
videoPreset: '',
videoProfile: 'high'
};
}
// A full profile response carries every request field (round-trip complete) plus id +
// resolution name; drop those two to get the mutation body.
function draftFromProfile(profile: FFmpegProfile): Draft {
return {
allowBFrames: profile.allowBFrames,
audioBitrate: profile.audioBitrate,
audioBufferSize: profile.audioBufferSize,
audioChannels: profile.audioChannels,
audioFormat: profile.audioFormat,
audioSampleRate: profile.audioSampleRate,
bitDepth: profile.bitDepth,
deinterlaceVideo: profile.deinterlaceVideo,
hardwareAcceleration: profile.hardwareAcceleration,
name: profile.name,
normalizeAudio: profile.normalizeAudio,
normalizeColors: profile.normalizeColors,
normalizeFramerate: profile.normalizeFramerate,
normalizeLoudnessMode: profile.normalizeLoudnessMode,
normalizeVideo: profile.normalizeVideo,
padMode: profile.padMode,
qsvExtraHardwareFrames: profile.qsvExtraHardwareFrames,
resolutionId: profile.resolutionId,
scalingBehavior: profile.scalingBehavior,
targetLoudness: profile.targetLoudness,
threadCount: profile.threadCount,
tonemapAlgorithm: profile.tonemapAlgorithm,
vaapiDevice: profile.vaapiDevice,
vaapiDisplay: profile.vaapiDisplay,
vaapiDriver: profile.vaapiDriver,
videoBitrate: profile.videoBitrate,
videoBufferSize: profile.videoBufferSize,
videoFormat: profile.videoFormat,
videoPreset: profile.videoPreset,
videoProfile: profile.videoProfile
};
}
/* ---------- form row helper (mirrors ChannelEditScreen) ---------- */
function Row({
children,
control = 320,
first = false,
help,
label
}: {
children: ReactNode;
control?: number;
first?: boolean;
help?: string;
label: string;
}) {
return (
<div className="ctv-settings-row" style={first ? { borderTop: 'none' } : undefined}>
<div className="ctv-settings-row-main">
<div className="ctv-settings-row-label">{label}</div>
{help && <div className="ctv-settings-row-help">{help}</div>}
</div>
<div className="ctv-settings-row-control" style={{ flex: `0 0 ${control}px` }}>{children}</div>
</div>
);
}
function NumberField({
disabled,
onChange,
unit,
value
}: {
disabled?: boolean;
onChange: (next: number) => void;
unit?: string;
value: number;
}) {
return (
<Input
disabled={disabled}
onChange={(event) => onChange(Number(event.target.value))}
size="sm"
trailing={unit}
type="number"
value={String(value)}
/>
);
}
/* ---------- routing ---------- */
type Mode = { kind: 'add'; from: null | number } | { kind: 'edit'; id: number } | { kind: 'list' };
function modeFromPath(pathname: string): Mode {
const normalized = pathname.replace(/\/+$/, '');
if (normalized === BASE_PATH || !normalized.startsWith(`${BASE_PATH}/`)) {
return { kind: 'list' };
}
const suffix = normalized.slice(BASE_PATH.length + 1).split('/')[0];
if (suffix === 'add') {
const from = new URLSearchParams(window.location.search).get('from');
return { from: from ? Number(from) : null, kind: 'add' };
}
const id = Number(suffix);
return Number.isInteger(id) && id > 0 ? { id, kind: 'edit' } : { kind: 'list' };
}
/* ---------- screen ---------- */
export function FFmpegProfilesScreen() {
const [pathname, setPathname] = useState(() => window.location.pathname + window.location.search);
useEffect(() => {
const onPop = () => setPathname(window.location.pathname + window.location.search);
window.addEventListener('popstate', onPop);
return () => window.removeEventListener('popstate', onPop);
}, []);
const mode = modeFromPath(window.location.pathname);
if (mode.kind === 'list') {
return <ProfileList key={pathname} />;
}
return <ProfileEditor key={pathname} mode={mode} />;
}
/* ---------- list ---------- */
function ProfileList() {
const [profiles, setProfiles] = useState<FFmpegProfile[] | null>(null);
const [error, setError] = useState<null | string>(null);
const [deleteTarget, setDeleteTarget] = useState<FFmpegProfile | null>(null);
const [busy, setBusy] = useState(false);
const activeRef = useRef(true);
const load = useCallback(() => {
getFFmpegProfiles()
.then((data) => {
if (activeRef.current) {
setProfiles(data);
setError(null);
}
})
.catch((loadError: unknown) => {
if (activeRef.current) {
setError(messageFromFFmpegProfileError(loadError));
}
});
}, []);
useEffect(() => {
activeRef.current = true;
load();
return () => {
activeRef.current = false;
};
}, [load]);
const confirmDelete = async () => {
if (!deleteTarget) {
return;
}
setBusy(true);
try {
await deleteFFmpegProfile(deleteTarget.id);
setDeleteTarget(null);
load();
} catch (deleteError) {
setError(messageFromFFmpegProfileError(deleteError, 'Unable to delete profile'));
} finally {
setBusy(false);
}
};
if (error && !profiles) {
return (
<div className="ctv-collections">
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
<span className="ctv-channels-spacer" />
<Button onClick={load} size="sm" variant="secondary">
Retry
</Button>
</div>
</div>
);
}
if (!profiles) {
return (
<div className="ctv-collections-loading" role="status">
<Spinner size={18} />
<span>Loading FFmpeg profiles…</span>
</div>
);
}
const sorted = [...profiles].sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Badge tone="neutral">{profiles.length} profiles</Badge>
<span className="ctv-channels-spacer" />
<Button
onClick={() => navigateToPath(`${BASE_PATH}/add`)}
size="sm"
startIcon={<Plus aria-hidden="true" size={14} />}
>
New profile
</Button>
</div>
{error && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
</div>
)}
<Card padded={false}>
{sorted.length === 0 ? (
<div className="ctv-collections-empty">No FFmpeg profiles yet.</div>
) : (
sorted.map((profile, index) => (
<div
className="ctv-settings-flush-row"
key={profile.id}
style={index === 0 ? { borderTop: 'none' } : undefined}
>
<SlidersHorizontal aria-hidden="true" color="var(--ctv-accent)" size={15} />
<button
className="ctv-settings-flush-row-main ctv-settings-flush-row-title ctv-collections-linkbtn"
onClick={() => navigateToPath(`${BASE_PATH}/${profile.id}`)}
type="button"
>
{profile.name}
</button>
<Badge tone="neutral">{profile.resolution}</Badge>
<Badge tone="neutral">{`${profile.videoFormat.toLowerCase()} / ${profile.audioFormat.toLowerCase()}`}</Badge>
<IconButton
onClick={() => navigateToPath(`${BASE_PATH}/add?from=${profile.id}`)}
size="sm"
title={`Copy ${profile.name}`}
variant="ghost"
>
<Copy aria-hidden="true" size={14} />
</IconButton>
<IconButton onClick={() => setDeleteTarget(profile)} size="sm" title="Delete" variant="ghost">
<Trash2 aria-hidden="true" size={14} />
</IconButton>
</div>
))
)}
</Card>
<ConfirmDialog
busy={busy}
confirmLabel="Delete"
message={deleteTarget ? `Delete "${deleteTarget.name}"? This cannot be undone.` : ''}
onCancel={() => setDeleteTarget(null)}
onConfirm={() => void confirmDelete()}
open={deleteTarget !== null}
title="Delete FFmpeg profile"
tone="danger"
/>
</div>
);
}
/* ---------- editor ---------- */
function ProfileEditor({ mode }: { mode: { kind: 'add'; from: null | number } | { kind: 'edit'; id: number } }) {
const [resolutions, setResolutions] = useState<Resolution[]>([]);
const [hwaccelKinds, setHwaccelKinds] = useState<HardwareAccelerationKind[]>(['None']);
const [draft, setDraft] = useState<Draft | null>(null);
const [loadError, setLoadError] = useState<null | string>(null);
const [saveError, setSaveError] = useState<null | string>(null);
const [saving, setSaving] = useState(false);
const isEdit = mode.kind === 'edit';
// Captured once at mount (the screen keys this editor by pathname, so a route change
// remounts rather than mutates) — mirrors ChannelEditScreen's stable-id pattern.
const [loadEditId] = useState(() => (mode.kind === 'edit' ? mode.id : null));
const [loadCopyFrom] = useState(() => (mode.kind === 'add' ? mode.from : null));
useEffect(() => {
let active = true;
const hydrate = async () => {
try {
const [resolutionList, kinds] = await Promise.all([getResolutions(), getHardwareAccelerationKinds()]);
let nextDraft: Draft;
if (loadEditId != null) {
nextDraft = draftFromProfile(await getFFmpegProfile(loadEditId));
} else if (loadCopyFrom != null) {
const source = await getFFmpegProfile(loadCopyFrom);
nextDraft = { ...draftFromProfile(source), name: `${source.name} (copy)` };
} else {
nextDraft = defaultDraft(resolutionList[0]?.id ?? 0);
}
if (!kinds.includes(nextDraft.hardwareAcceleration)) {
nextDraft = { ...nextDraft, hardwareAcceleration: 'None' };
}
if (active) {
setResolutions(resolutionList);
setHwaccelKinds(kinds);
setDraft(nextDraft);
}
} catch (error) {
if (active) {
setLoadError(messageFromFFmpegProfileError(error, 'Unable to load profile'));
}
}
};
void hydrate();
return () => {
active = false;
};
}, [loadEditId, loadCopyFrom]);
if (loadError) {
return (
<div className="ctv-settings-error" role="alert">
<TriangleAlert aria-hidden="true" size={16} />
<span>{loadError}</span>
<Button onClick={() => navigateToPath(BASE_PATH)} size="sm" variant="secondary">
Back to profiles
</Button>
</div>
);
}
if (!draft) {
return (
<div className="ctv-settings-loading">
<Spinner size={18} />
<span>Loading profile…</span>
</div>
);
}
const set = (patch: Partial<Draft>) => {
setDraft((current) => (current ? { ...current, ...patch } : current));
};
const validationError = validate(draft);
const presets = presetsFor(draft.hardwareAcceleration, draft.videoFormat, draft.bitDepth);
const save = async () => {
if (validationError || saving) {
return;
}
setSaving(true);
setSaveError(null);
try {
if (mode.kind === 'edit') {
await updateFFmpegProfile(mode.id, draft);
} else {
await createFFmpegProfile(draft);
}
navigateToPath(BASE_PATH);
} catch (error) {
setSaveError(messageFromFFmpegProfileError(error, 'Unable to save profile'));
} finally {
setSaving(false);
}
};
const resolutionOptions = resolutions.map((resolution) => ({
label: resolution.name ?? `${resolution.width}×${resolution.height}`,
value: String(resolution.id)
}));
const profileDisabled = draft.videoFormat !== 'H264' || !hwaccelSupportsH264Profile(draft.hardwareAcceleration);
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Button
onClick={() => navigateToPath(BASE_PATH)}
size="sm"
startIcon={<ArrowLeft aria-hidden="true" size={14} />}
variant="ghost"
>
All profiles
</Button>
<span className="ctv-collections-detail-title">{isEdit ? 'Edit FFmpeg profile' : 'New FFmpeg profile'}</span>
<span className="ctv-channels-spacer" />
{saveError && <span className="ctv-settings-savebar-error">{saveError}</span>}
{validationError && <Badge tone="neutral">{validationError}</Badge>}
<Button
disabled={validationError !== null || saving}
loading={saving}
onClick={() => void save()}
size="sm"
startIcon={<Check aria-hidden="true" size={14} />}
>
{isEdit ? 'Save profile' : 'Add profile'}
</Button>
</div>
<Card padded={false} title="General">
<Row control={360} first label="Name">
<Input
error={draft.name?.trim() ? null : 'Name is required'}
onChange={(event) => set({ name: event.target.value })}
size="sm"
value={draft.name ?? ''}
/>
</Row>
<Row control={200} label="Thread count">
<NumberField onChange={(threadCount) => set({ threadCount })} value={draft.threadCount} />
</Row>
<Row control={200} label="Normalize audio">
<Checkbox checked={draft.normalizeAudio} onChange={(normalizeAudio) => set({ normalizeAudio })} />
</Row>
<Row control={200} label="Normalize video">
<Checkbox checked={draft.normalizeVideo} onChange={(normalizeVideo) => set({ normalizeVideo })} />
</Row>
<Row control={360} label="Preferred resolution">
<Select
onChange={(event) => set({ resolutionId: Number(event.target.value) })}
options={resolutionOptions}
value={String(draft.resolutionId)}
/>
</Row>
{draft.normalizeVideo && (
<>
<Row control={360} label="Scaling behavior">
<Select
onChange={(event) => set({ scalingBehavior: event.target.value as Draft['scalingBehavior'] })}
options={SCALING_OPTIONS}
value={draft.scalingBehavior}
/>
</Row>
<Row
control={360}
help="Hardware padding only applies with VAAPI; otherwise software padding is used."
label="Pad mode"
>
<Select
disabled={draft.hardwareAcceleration !== 'Vaapi'}
onChange={(event) => set({ padMode: event.target.value as Draft['padMode'] })}
options={PAD_MODE_OPTIONS}
value={draft.padMode}
/>
</Row>
</>
)}
</Card>
<Card padded={false} title="Video">
{draft.normalizeVideo ? (
<>
<Row control={360} first label="Format">
<Select
onChange={(event) => set({ videoFormat: event.target.value as Draft['videoFormat'] })}
options={videoFormatOptions(draft.hardwareAcceleration)}
value={draft.videoFormat}
/>
</Row>
<Row control={360} label="Profile">
<Select
disabled={profileDisabled}
onChange={(event) => set({ videoProfile: event.target.value })}
options={videoProfileOptions(draft.hardwareAcceleration)}
value={draft.videoProfile ?? ''}
/>
</Row>
<Row control={360} label="Preset">
<Select
disabled={presets.length === 0}
onChange={(event) => set({ videoPreset: event.target.value })}
options={[{ label: '(none)', value: '' }, ...presets]}
value={draft.videoPreset ?? ''}
/>
</Row>
<Row control={200} label="Allow B-frames">
<Checkbox checked={draft.allowBFrames} onChange={(allowBFrames) => set({ allowBFrames })} />
</Row>
<Row control={360} label="Bit depth">
<Select
onChange={(event) => set({ bitDepth: event.target.value as Draft['bitDepth'] })}
options={BIT_DEPTH_OPTIONS}
value={draft.bitDepth}
/>
</Row>
<Row control={220} label="Bitrate">
<NumberField onChange={(videoBitrate) => set({ videoBitrate })} unit="kBit/s" value={draft.videoBitrate} />
</Row>
<Row control={220} label="Buffer size">
<NumberField onChange={(videoBufferSize) => set({ videoBufferSize })} unit="kBit" value={draft.videoBufferSize} />
</Row>
<Row control={360} label="Hardware acceleration">
<Select
onChange={(event) => set({ hardwareAcceleration: event.target.value as HardwareAccelerationKind })}
options={hwaccelKinds}
value={draft.hardwareAcceleration}
/>
</Row>
{draft.hardwareAcceleration === 'Vaapi' && (
<>
<Row control={360} label="VAAPI driver">
<Select
onChange={(event) => set({ vaapiDriver: event.target.value as Draft['vaapiDriver'] })}
options={VAAPI_DRIVER_OPTIONS}
value={draft.vaapiDriver}
/>
</Row>
<Row control={360} help="Rendering display, e.g. drm." label="VAAPI display">
<Input onChange={(event) => set({ vaapiDisplay: event.target.value })} size="sm" value={draft.vaapiDisplay ?? ''} />
</Row>
</>
)}
{(draft.hardwareAcceleration === 'Vaapi' || draft.hardwareAcceleration === 'Qsv') && (
<Row
control={360}
help="Render device, e.g. /dev/dri/renderD128."
label={draft.hardwareAcceleration === 'Vaapi' ? 'VAAPI device' : 'QSV device'}
>
<Input onChange={(event) => set({ vaapiDevice: event.target.value })} size="sm" value={draft.vaapiDevice ?? ''} />
</Row>
)}
{draft.hardwareAcceleration === 'Qsv' ? (
<Row control={200} label="QSV extra hardware frames">
<NumberField
onChange={(qsvExtraHardwareFrames) => set({ qsvExtraHardwareFrames })}
value={draft.qsvExtraHardwareFrames ?? 0}
/>
</Row>
) : (
<Row control={360} label="Tonemap algorithm">
<Select
onChange={(event) => set({ tonemapAlgorithm: event.target.value as Draft['tonemapAlgorithm'] })}
options={TONEMAP_OPTIONS}
value={draft.tonemapAlgorithm}
/>
</Row>
)}
<Row control={200} label="Normalize frame rate">
<Checkbox checked={draft.normalizeFramerate} onChange={(normalizeFramerate) => set({ normalizeFramerate })} />
</Row>
<Row control={200} label="Normalize colors">
<Checkbox checked={draft.normalizeColors} onChange={(normalizeColors) => set({ normalizeColors })} />
</Row>
<Row control={200} label="Auto deinterlace video">
<Checkbox checked={draft.deinterlaceVideo} onChange={(deinterlaceVideo) => set({ deinterlaceVideo })} />
</Row>
</>
) : (
<div className="ctv-settings-callout" style={{ margin: 16 }}>
<TriangleAlert aria-hidden="true" size={14} />
<span>Video will be copied as-is, including timestamps, which will cause issues with most clients.</span>
</div>
)}
</Card>
<Card padded={false} title="Audio">
{draft.normalizeAudio ? (
<>
<Row control={360} first label="Format">
<Select
onChange={(event) => set({ audioFormat: event.target.value as Draft['audioFormat'] })}
options={AUDIO_FORMAT_OPTIONS}
value={draft.audioFormat}
/>
</Row>
<Row control={220} label="Bitrate">
<NumberField onChange={(audioBitrate) => set({ audioBitrate })} unit="kBit/s" value={draft.audioBitrate} />
</Row>
<Row control={220} label="Buffer size">
<NumberField onChange={(audioBufferSize) => set({ audioBufferSize })} unit="kBit" value={draft.audioBufferSize} />
</Row>
<Row control={200} label="Channels">
<NumberField onChange={(audioChannels) => set({ audioChannels })} value={draft.audioChannels} />
</Row>
<Row control={220} label="Sample rate">
<NumberField onChange={(audioSampleRate) => set({ audioSampleRate })} unit="kHz" value={draft.audioSampleRate} />
</Row>
<Row control={360} label="Normalize loudness">
<Select
onChange={(event) => set({ normalizeLoudnessMode: event.target.value as Draft['normalizeLoudnessMode'] })}
options={LOUDNESS_OPTIONS}
value={draft.normalizeLoudnessMode}
/>
</Row>
{draft.normalizeLoudnessMode === 'LoudNorm' && (
<Row control={220} label="Target loudness">
<NumberField
onChange={(targetLoudness) => set({ targetLoudness })}
unit="LUFS"
value={draft.targetLoudness ?? 0}
/>
</Row>
)}
</>
) : (
<div className="ctv-settings-callout" style={{ margin: 16 }}>
<TriangleAlert aria-hidden="true" size={14} />
<span>Audio will be copied as-is, including timestamps, which will cause issues with most clients.</span>
</div>
)}
</Card>
</div>
);
}
+738
View File
@@ -0,0 +1,738 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { ArrowLeft, Check, Film, Plus, Trash2, TriangleAlert } from 'lucide-react';
import { navigateToPath } from '../routing';
import { Badge, Button, Card, Checkbox, ConfirmDialog, IconButton, Input, Select, Spinner } from '../components';
import {
createFillerPreset,
deleteFillerPreset,
getFillerPreset,
getFillerPresets,
getLibraryBrowseItems,
messageFromFillerPresetError,
updateFillerPreset,
type CreateFillerPresetRequest,
type FillerPreset,
type LibraryBrowseItem,
type LibraryBrowseMediaType
} from '../api';
const BASE_PATH = '/app/filler-presets';
type Draft = CreateFillerPresetRequest;
type FillerKind = Draft['fillerKind'];
type FillerMode = Draft['fillerMode'];
type CollectionType = Draft['collectionType'];
const KIND_OPTIONS = [
{ label: 'Pre-Roll', value: 'PreRoll' },
{ label: 'Mid-Roll', value: 'MidRoll' },
{ label: 'Post-Roll', value: 'PostRoll' },
{ label: 'Tail', value: 'Tail' },
{ label: 'Fallback', value: 'Fallback' }
];
const MODE_OPTIONS = [
{ label: 'Duration', value: 'Duration' },
{ label: 'Count', value: 'Count' },
{ label: 'Pad', value: 'Pad' },
{ label: 'Random Count', value: 'RandomCount' }
];
const PAD_OPTIONS = [5, 10, 15, 30].map((minutes) => ({ label: String(minutes), value: String(minutes) }));
// CollectionType -> the library-browse media type + which request id field it fills.
const COLLECTION_TYPES: Array<{
browse: LibraryBrowseMediaType;
field: 'collectionId' | 'mediaItemId' | 'multiCollectionId' | 'playlistId' | 'smartCollectionId';
itemId: (item: LibraryBrowseItem) => null | number | undefined;
label: string;
playlistOnly?: boolean;
value: CollectionType;
}> = [
{ browse: 'Collection', field: 'collectionId', itemId: (item) => item.collectionId, label: 'Collection', value: 'Collection' },
{ browse: 'TelevisionShow', field: 'mediaItemId', itemId: (item) => item.mediaItemId ?? item.id, label: 'Television Show', value: 'TelevisionShow' },
{ browse: 'TelevisionSeason', field: 'mediaItemId', itemId: (item) => item.mediaItemId ?? item.id, label: 'Television Season', value: 'TelevisionSeason' },
{ browse: 'Artist', field: 'mediaItemId', itemId: (item) => item.mediaItemId ?? item.id, label: 'Artist', value: 'Artist' },
{ browse: 'MultiCollection', field: 'multiCollectionId', itemId: (item) => item.multiCollectionId, label: 'Multi Collection', value: 'MultiCollection' },
{ browse: 'SmartCollection', field: 'smartCollectionId', itemId: (item) => item.smartCollectionId, label: 'Smart Collection', value: 'SmartCollection' },
{ browse: 'Playlist', field: 'playlistId', itemId: (item) => item.playlistId, label: 'Playlist', playlistOnly: true, value: 'Playlist' }
];
const COLLECTION_ID_FIELDS = ['collectionId', 'mediaItemId', 'multiCollectionId', 'smartCollectionId', 'playlistId'] as const;
/* ---------- TimeSpan (constant "c" format) helpers ---------- */
function timeSpanToParts(value: null | string | undefined): { hours: number; minutes: number; seconds: number } {
if (!value) {
return { hours: 0, minutes: 0, seconds: 0 };
}
const body = value.replace(/^-/, '');
const segments = body.split(':');
let hoursSegment = segments[0] ?? '0';
let days = 0;
if (hoursSegment.includes('.')) {
const [d, h] = hoursSegment.split('.');
days = Number(d);
hoursSegment = h;
}
return {
hours: days * 24 + Number(hoursSegment),
minutes: Number(segments[1] ?? 0),
seconds: Math.trunc(Number(segments[2] ?? 0))
};
}
function partsToTimeSpan(hours: number, minutes: number, seconds: number): null | string {
if (!hours && !minutes && !seconds) {
return null;
}
const days = Math.floor(hours / 24);
const hh = hours % 24;
const mm = String(minutes).padStart(2, '0');
const ss = String(seconds).padStart(2, '0');
return days > 0 ? `${days}.${String(hh).padStart(2, '0')}:${mm}:${ss}` : `${hh}:${mm}:${ss}`;
}
/* ---------- validation (mirrors FillerPresetEditViewModelValidator) ---------- */
function validate(draft: Draft): null | string {
if (!draft.name.trim()) {
return 'Name is required';
}
if (draft.fillerKind !== 'Fallback' && draft.fillerKind !== 'Tail' && draft.fillerMode === 'None') {
return 'Mode is required';
}
if (draft.fillerMode === 'Count' && (draft.count == null || draft.count < 0)) {
return 'Count is required';
}
if (draft.fillerMode === 'Duration' && draft.duration == null) {
return 'Duration is required';
}
if (draft.fillerMode === 'Pad' && draft.padToNearestMinute == null) {
return 'Pad-to-nearest-minute is required';
}
if (draft.fillerKind === 'Fallback' && draft.useChaptersAsMediaItems) {
return 'Fallback filler cannot use chapters as media items';
}
if (draft.collectionType === 'Collection' && draft.collectionId == null) {
return 'A collection is required';
}
if (draft.collectionType === 'MultiCollection' && draft.multiCollectionId == null) {
return 'A multi collection is required';
}
if (draft.collectionType === 'SmartCollection' && draft.smartCollectionId == null) {
return 'A smart collection is required';
}
if (
(draft.collectionType === 'Artist' ||
draft.collectionType === 'TelevisionShow' ||
draft.collectionType === 'TelevisionSeason') &&
draft.mediaItemId == null
) {
return 'A media item is required';
}
if (draft.collectionType === 'Playlist' && draft.playlistId == null) {
return 'A playlist is required';
}
return null;
}
function defaultDraft(): Draft {
return {
allowWatermarks: false,
collectionId: null,
collectionType: 'Collection',
count: null,
duration: null,
expression: null,
fillerKind: 'PreRoll',
fillerMode: 'Count',
mediaItemId: null,
multiCollectionId: null,
name: '',
padToNearestMinute: null,
playlistId: null,
smartCollectionId: null,
useChaptersAsMediaItems: false
};
}
function draftFromPreset(preset: FillerPreset & Draft): Draft {
return {
allowWatermarks: preset.allowWatermarks,
collectionId: preset.collectionId,
collectionType: preset.collectionType,
count: preset.count,
duration: preset.duration,
expression: preset.expression,
fillerKind: preset.fillerKind,
fillerMode: preset.fillerMode,
mediaItemId: preset.mediaItemId,
multiCollectionId: preset.multiCollectionId,
name: preset.name,
padToNearestMinute: preset.padToNearestMinute,
playlistId: preset.playlistId,
smartCollectionId: preset.smartCollectionId,
useChaptersAsMediaItems: preset.useChaptersAsMediaItems
};
}
// Apply the kind-driven interlocks from FillerPresetEditViewModel's setters.
function applyKind(draft: Draft, fillerKind: FillerKind): Draft {
const next: Draft = { ...draft, fillerKind };
if (fillerKind === 'Fallback' || fillerKind === 'Tail') {
next.fillerMode = 'None';
}
if (fillerKind !== 'MidRoll') {
next.expression = null;
}
if (fillerKind === 'Fallback') {
next.useChaptersAsMediaItems = false;
// Playlist is not offered for Fallback/Tail; fall back to Collection if it was selected.
if (next.collectionType === 'Playlist') {
next.collectionType = 'Collection';
}
}
if ((fillerKind === 'Tail') && next.collectionType === 'Playlist') {
next.collectionType = 'Collection';
}
return next;
}
function clearCollectionRefs(draft: Draft): Draft {
const next = { ...draft };
for (const field of COLLECTION_ID_FIELDS) {
next[field] = null;
}
return next;
}
/* ---------- form row helper ---------- */
function Row({
children,
control = 320,
first = false,
help,
label
}: {
children: ReactNode;
control?: number;
first?: boolean;
help?: string;
label: string;
}) {
return (
<div className="ctv-settings-row" style={first ? { borderTop: 'none' } : undefined}>
<div className="ctv-settings-row-main">
<div className="ctv-settings-row-label">{label}</div>
{help && <div className="ctv-settings-row-help">{help}</div>}
</div>
<div className="ctv-settings-row-control" style={{ flex: `0 0 ${control}px` }}>{children}</div>
</div>
);
}
/* ---------- routing ---------- */
type Mode = { id: number; kind: 'edit' } | { kind: 'add' } | { kind: 'list' };
function modeFromPath(pathname: string): Mode {
const normalized = pathname.replace(/\/+$/, '');
if (normalized === BASE_PATH || !normalized.startsWith(`${BASE_PATH}/`)) {
return { kind: 'list' };
}
const suffix = normalized.slice(BASE_PATH.length + 1).split('/')[0];
if (suffix === 'add') {
return { kind: 'add' };
}
const id = Number(suffix);
return Number.isInteger(id) && id > 0 ? { id, kind: 'edit' } : { kind: 'list' };
}
export function FillerPresetsScreen() {
const [pathname, setPathname] = useState(() => window.location.pathname);
useEffect(() => {
const onPop = () => setPathname(window.location.pathname);
window.addEventListener('popstate', onPop);
return () => window.removeEventListener('popstate', onPop);
}, []);
const mode = modeFromPath(pathname);
if (mode.kind === 'list') {
return <FillerList key={pathname} />;
}
return <FillerEditor key={pathname} mode={mode} />;
}
/* ---------- list ---------- */
function FillerList() {
const [presets, setPresets] = useState<FillerPreset[] | null>(null);
const [error, setError] = useState<null | string>(null);
const [deleteTarget, setDeleteTarget] = useState<FillerPreset | null>(null);
const [busy, setBusy] = useState(false);
const activeRef = useRef(true);
const load = useCallback(() => {
getFillerPresets()
.then((data) => {
if (activeRef.current) {
setPresets(data);
setError(null);
}
})
.catch((loadError: unknown) => {
if (activeRef.current) {
setError(messageFromFillerPresetError(loadError));
}
});
}, []);
useEffect(() => {
activeRef.current = true;
load();
return () => {
activeRef.current = false;
};
}, [load]);
const confirmDelete = async () => {
if (!deleteTarget) {
return;
}
setBusy(true);
try {
await deleteFillerPreset(deleteTarget.id);
setDeleteTarget(null);
load();
} catch (deleteError) {
setError(messageFromFillerPresetError(deleteError, 'Unable to delete filler preset'));
} finally {
setBusy(false);
}
};
if (error && !presets) {
return (
<div className="ctv-collections">
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
<span className="ctv-channels-spacer" />
<Button onClick={load} size="sm" variant="secondary">
Retry
</Button>
</div>
</div>
);
}
if (!presets) {
return (
<div className="ctv-collections-loading" role="status">
<Spinner size={18} />
<span>Loading filler presets…</span>
</div>
);
}
const sorted = [...presets].sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Badge tone="neutral">{presets.length} presets</Badge>
<span className="ctv-channels-spacer" />
<Button
onClick={() => navigateToPath(`${BASE_PATH}/add`)}
size="sm"
startIcon={<Plus aria-hidden="true" size={14} />}
>
New filler preset
</Button>
</div>
{error && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
</div>
)}
<Card padded={false}>
{sorted.length === 0 ? (
<div className="ctv-collections-empty">No filler presets yet.</div>
) : (
sorted.map((preset, index) => (
<div
className="ctv-settings-flush-row"
key={preset.id}
style={index === 0 ? { borderTop: 'none' } : undefined}
>
<Film aria-hidden="true" color="var(--ctv-accent)" size={15} />
<button
className="ctv-settings-flush-row-main ctv-settings-flush-row-title ctv-collections-linkbtn"
onClick={() => navigateToPath(`${BASE_PATH}/${preset.id}`)}
type="button"
>
{preset.name}
</button>
<IconButton onClick={() => setDeleteTarget(preset)} size="sm" title="Delete" variant="ghost">
<Trash2 aria-hidden="true" size={14} />
</IconButton>
</div>
))
)}
</Card>
<ConfirmDialog
busy={busy}
confirmLabel="Delete"
message={deleteTarget ? `Delete "${deleteTarget.name}"? This cannot be undone.` : ''}
onCancel={() => setDeleteTarget(null)}
onConfirm={() => void confirmDelete()}
open={deleteTarget !== null}
title="Delete filler preset"
tone="danger"
/>
</div>
);
}
/* ---------- editor ---------- */
function FillerEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: 'add' } }) {
const [draft, setDraft] = useState<Draft | null>(mode.kind === 'add' ? defaultDraft : null);
const [loadError, setLoadError] = useState<null | string>(null);
const [saveError, setSaveError] = useState<null | string>(null);
const [saving, setSaving] = useState(false);
const [pickerItems, setPickerItems] = useState<LibraryBrowseItem[]>([]);
const [pickerError, setPickerError] = useState<null | string>(null);
const isEdit = mode.kind === 'edit';
// Captured once at mount; the screen keys this editor by pathname (see ChannelEditScreen).
const [loadEditId] = useState(() => (mode.kind === 'edit' ? mode.id : null));
useEffect(() => {
if (loadEditId == null) {
return;
}
let active = true;
getFillerPreset(loadEditId)
.then((preset) => {
if (active) {
setDraft(draftFromPreset(preset as FillerPreset & Draft));
}
})
.catch((error: unknown) => {
if (active) {
setLoadError(messageFromFillerPresetError(error, 'Unable to load filler preset'));
}
});
return () => {
active = false;
};
}, [loadEditId]);
const collectionType = draft?.collectionType;
// Load the browse items for the active collection type so the picker can show names. All
// resets happen in the async callbacks (never synchronously in the effect body).
useEffect(() => {
const config = COLLECTION_TYPES.find((entry) => entry.value === collectionType);
if (!config) {
return;
}
let active = true;
getLibraryBrowseItems({ mediaType: config.browse, pageSize: 500 })
.then((result) => {
if (active) {
setPickerItems(result.page ?? []);
setPickerError(null);
}
})
.catch((error: unknown) => {
if (active) {
setPickerItems([]);
setPickerError(messageFromFillerPresetError(error, 'Unable to load picker items'));
}
});
return () => {
active = false;
};
}, [collectionType]);
if (loadError) {
return (
<div className="ctv-settings-error" role="alert">
<TriangleAlert aria-hidden="true" size={16} />
<span>{loadError}</span>
<Button onClick={() => navigateToPath(BASE_PATH)} size="sm" variant="secondary">
Back to filler presets
</Button>
</div>
);
}
if (!draft) {
return (
<div className="ctv-settings-loading">
<Spinner size={18} />
<span>Loading filler preset…</span>
</div>
);
}
const set = (patch: Partial<Draft>) => setDraft((current) => (current ? { ...current, ...patch } : current));
const setKind = (fillerKind: FillerKind) => setDraft((current) => (current ? applyKind(current, fillerKind) : current));
const setCollectionType = (type: CollectionType) => {
setDraft((current) => {
if (!current) {
return current;
}
const cleared = clearCollectionRefs(current);
cleared.collectionType = type;
// Playlist collection type forces Count mode (matches the Blazor VM).
if (type === 'Playlist') {
cleared.fillerMode = 'Count';
}
return cleared;
});
};
const validationError = validate(draft);
const modeLocked = draft.fillerKind === 'Fallback' || draft.fillerKind === 'Tail' || draft.collectionType === 'Playlist';
const durationParts = timeSpanToParts(draft.duration);
const activeConfig = COLLECTION_TYPES.find((entry) => entry.value === draft.collectionType);
const setDurationPart = (patch: Partial<{ hours: number; minutes: number; seconds: number }>) => {
const next = { ...durationParts, ...patch };
set({ duration: partsToTimeSpan(next.hours, next.minutes, next.seconds) });
};
const pickerValue = activeConfig ? String((draft[activeConfig.field] as null | number) ?? '') : '';
const pickerOptions = [
{ label: '(none)', value: '' },
...pickerItems.flatMap((item) => {
const id = activeConfig?.itemId(item);
return id == null ? [] : [{ label: item.title ?? `#${id}`, value: String(id) }];
})
];
const collectionTypeOptions = COLLECTION_TYPES.filter(
(entry) => !entry.playlistOnly || (draft.fillerKind !== 'Fallback' && draft.fillerKind !== 'Tail')
).map((entry) => ({ label: entry.label, value: entry.value }));
const save = async () => {
if (validationError || saving) {
return;
}
setSaving(true);
setSaveError(null);
try {
if (mode.kind === 'edit') {
await updateFillerPreset(mode.id, draft);
} else {
await createFillerPreset(draft);
}
navigateToPath(BASE_PATH);
} catch (error) {
setSaveError(messageFromFillerPresetError(error, 'Unable to save filler preset'));
} finally {
setSaving(false);
}
};
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Button
onClick={() => navigateToPath(BASE_PATH)}
size="sm"
startIcon={<ArrowLeft aria-hidden="true" size={14} />}
variant="ghost"
>
All filler presets
</Button>
<span className="ctv-collections-detail-title">{isEdit ? 'Edit filler preset' : 'New filler preset'}</span>
<span className="ctv-channels-spacer" />
{saveError && <span className="ctv-settings-savebar-error">{saveError}</span>}
{validationError && <Badge tone="neutral">{validationError}</Badge>}
<Button
disabled={validationError !== null || saving}
loading={saving}
onClick={() => void save()}
size="sm"
startIcon={<Check aria-hidden="true" size={14} />}
>
{isEdit ? 'Save filler preset' : 'Add filler preset'}
</Button>
</div>
<Card padded={false} title="Filler preset">
<Row control={360} first label="Name">
<Input
error={draft.name.trim() ? null : 'Name is required'}
onChange={(event) => set({ name: event.target.value })}
size="sm"
value={draft.name}
/>
</Row>
<Row control={360} help={isEdit ? 'Kind cannot be changed after creation.' : undefined} label="Kind">
<Select
disabled={isEdit}
onChange={(event) => setKind(event.target.value as FillerKind)}
options={KIND_OPTIONS}
value={draft.fillerKind}
/>
</Row>
<Row control={360} label="Mode">
<Select
disabled={modeLocked}
onChange={(event) => set({ fillerMode: event.target.value as FillerMode })}
options={MODE_OPTIONS}
value={draft.fillerMode === 'None' ? '' : draft.fillerMode}
/>
</Row>
<Row control={360} label="Duration">
<div style={{ display: 'flex', gap: 8 }}>
<Input
disabled={draft.fillerMode !== 'Duration'}
onChange={(event) => setDurationPart({ hours: Number(event.target.value) })}
size="sm"
trailing="h"
type="number"
value={String(durationParts.hours)}
/>
<Input
disabled={draft.fillerMode !== 'Duration'}
onChange={(event) => setDurationPart({ minutes: Number(event.target.value) })}
size="sm"
trailing="m"
type="number"
value={String(durationParts.minutes)}
/>
<Input
disabled={draft.fillerMode !== 'Duration'}
onChange={(event) => setDurationPart({ seconds: Number(event.target.value) })}
size="sm"
trailing="s"
type="number"
value={String(durationParts.seconds)}
/>
</div>
</Row>
<Row control={200} label="Count">
<Input
disabled={draft.fillerMode !== 'Count' && draft.fillerMode !== 'RandomCount'}
onChange={(event) => set({ count: event.target.value === '' ? null : Number(event.target.value) })}
size="sm"
type="number"
value={draft.count == null ? '' : String(draft.count)}
/>
</Row>
<Row control={360} label="Pad to nearest minute">
<Select
disabled={draft.fillerMode !== 'Pad'}
onChange={(event) =>
set({ padToNearestMinute: event.target.value === '' ? null : Number(event.target.value) })
}
options={[{ label: '(none)', value: '' }, ...PAD_OPTIONS]}
value={draft.padToNearestMinute == null ? '' : String(draft.padToNearestMinute)}
/>
</Row>
<Row control={200} label="Allow watermarks">
<Checkbox checked={draft.allowWatermarks} onChange={(allowWatermarks) => set({ allowWatermarks })} />
</Row>
<Row control={360} label="Collection type">
<Select
onChange={(event) => setCollectionType(event.target.value as CollectionType)}
options={collectionTypeOptions}
value={draft.collectionType}
/>
</Row>
{activeConfig && (
<Row control={360} help={pickerError ?? undefined} label={activeConfig.label}>
<Select
onChange={(event) =>
set({ [activeConfig.field]: event.target.value === '' ? null : Number(event.target.value) })
}
options={pickerOptions}
value={pickerValue}
/>
</Row>
)}
<Row
control={200}
help="Schedule individual chapters instead of entire files."
label="Use chapters as media items"
>
<Checkbox
checked={draft.useChaptersAsMediaItems}
disabled={draft.fillerKind === 'Fallback'}
onChange={(useChaptersAsMediaItems) => set({ useChaptersAsMediaItems })}
/>
</Row>
<Row
control={360}
help="Mid-roll only: add filler only when this expression is true for a mid-roll point."
label="Expression"
>
<Input
disabled={draft.fillerKind !== 'MidRoll'}
onChange={(event) => set({ expression: event.target.value })}
size="sm"
value={draft.expression ?? ''}
/>
</Row>
</Card>
</div>
);
}
+10 -3
View File
@@ -603,8 +603,15 @@ function StreamingPane({
</div>
))
)}
<div className="ctv-settings-flush-footer">
<LegacyCallout>Profile editing (hardware acceleration, bitrates, tonemapping) stays in the legacy UI for now.</LegacyCallout>
<div className="ctv-settings-flush-footer" style={{ display: 'flex', justifyContent: 'flex-end' }}>
<Button
endIcon={<ArrowRight aria-hidden="true" size={13} />}
onClick={() => navigateToPath('/app/ffmpeg-profiles')}
size="sm"
variant="secondary"
>
Manage FFmpeg profiles
</Button>
</div>
</Card>
</Pane>
@@ -854,7 +861,7 @@ function SystemPane({
Open Dashboard
</Button>
</Row>
<Row control={220} help="Collections, media browse/search, trakt, filler, watermarks, ffmpeg profiles, blocks/decos/templates, playout editors, logs and troubleshooting still live here." label="Classic UI">
<Row control={220} help="Media browse/search, trakt, blocks/decos/templates, playout editors, logs and troubleshooting still live here." label="Classic UI">
<a className="ctv-button ctv-button-secondary ctv-button-sm" href="/system/health">
<span>Open Classic UI</span>
<ExternalLink aria-hidden="true" size={13} />
+628
View File
@@ -0,0 +1,628 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { ArrowLeft, Check, Image as ImageIcon, Plus, Trash2, TriangleAlert, Upload } from 'lucide-react';
import { navigateToPath } from '../routing';
import { Badge, Button, Card, Checkbox, ConfirmDialog, IconButton, Input, Select, Spinner } from '../components';
import {
createWatermark,
deleteWatermark,
getWatermark,
getWatermarks,
messageFromWatermarkError,
updateWatermark,
uploadArtwork,
watermarkImageUrl,
type CreateWatermarkRequest,
type Watermark
} from '../api';
const BASE_PATH = '/app/watermarks';
type Draft = CreateWatermarkRequest;
const MODE_OPTIONS = [
{ label: 'None', value: 'None' },
{ label: 'Permanent', value: 'Permanent' },
{ label: 'Intermittent', value: 'Intermittent' },
{ label: 'Opacity Expression', value: 'OpacityExpression' }
];
const IMAGE_SOURCE_OPTIONS = [
{ label: 'Custom', value: 'Custom' },
{ label: 'Channel Logo', value: 'ChannelLogo' }
];
// Blazor location order (WatermarkEditor.razor); MiddleCenter is intentionally not offered.
const LOCATION_OPTIONS = [
{ label: 'Bottom Right', value: 'BottomRight' },
{ label: 'Bottom Middle', value: 'BottomMiddle' },
{ label: 'Bottom Left', value: 'BottomLeft' },
{ label: 'Left Middle', value: 'LeftMiddle' },
{ label: 'Top Left', value: 'TopLeft' },
{ label: 'Top Middle', value: 'TopMiddle' },
{ label: 'Top Right', value: 'TopRight' },
{ label: 'Right Middle', value: 'RightMiddle' }
];
const SIZE_OPTIONS = [
{ label: 'Scaled', value: 'Scaled' },
{ label: 'Actual Size', value: 'ActualSize' }
];
const FREQUENCY_OPTIONS = [5, 10, 15, 20, 30, 60].map((minutes) => ({
label: `${minutes} minutes`,
value: String(minutes)
}));
// Mirrors WatermarkEditViewModelValidator. Returns the first blocking message, or null.
function validate(draft: Draft): null | string {
if (!draft.name.trim()) {
return 'Name is required';
}
if (draft.imageSource === 'Custom' && !draft.image) {
return 'Watermark image is required';
}
if (draft.mode === 'None') {
return null;
}
if (draft.size === 'Scaled' && (draft.width <= 0 || draft.width > 100)) {
return 'Width must be between 0 and 100';
}
if (draft.horizontalMargin < 0 || draft.horizontalMargin > 50) {
return 'Horizontal margin must be between 0 and 50';
}
if (draft.verticalMargin < 0 || draft.verticalMargin > 50) {
return 'Vertical margin must be between 0 and 50';
}
if (draft.durationSeconds <= 0 || draft.durationSeconds >= draft.frequencyMinutes * 60) {
return 'Duration must be greater than 0 and less than the frequency';
}
if (draft.opacity <= 0 || draft.opacity > 100) {
return 'Opacity must be between 0 and 100';
}
return null;
}
function defaultDraft(): Draft {
return {
durationSeconds: 15,
frequencyMinutes: 15,
horizontalMargin: 5,
image: null,
imageContentType: null,
imageSource: 'Custom',
location: 'BottomRight',
mode: 'Permanent',
name: '',
opacity: 100,
opacityExpression: null,
placeWithinSourceContent: false,
size: 'Scaled',
verticalMargin: 5,
width: 15,
zIndex: 0
};
}
function draftFromWatermark(watermark: Watermark & Draft): Draft {
return {
durationSeconds: watermark.durationSeconds,
frequencyMinutes: watermark.frequencyMinutes,
horizontalMargin: watermark.horizontalMargin,
image: watermark.image,
imageContentType: watermark.imageContentType,
imageSource: watermark.imageSource,
location: watermark.location,
mode: watermark.mode,
name: watermark.name,
opacity: watermark.opacity,
opacityExpression: watermark.opacityExpression,
placeWithinSourceContent: watermark.placeWithinSourceContent,
size: watermark.size,
verticalMargin: watermark.verticalMargin,
width: watermark.width,
zIndex: watermark.zIndex
};
}
function Row({
children,
control = 320,
first = false,
help,
label
}: {
children: ReactNode;
control?: number;
first?: boolean;
help?: string;
label: string;
}) {
return (
<div className="ctv-settings-row" style={first ? { borderTop: 'none' } : undefined}>
<div className="ctv-settings-row-main">
<div className="ctv-settings-row-label">{label}</div>
{help && <div className="ctv-settings-row-help">{help}</div>}
</div>
<div className="ctv-settings-row-control" style={{ flex: `0 0 ${control}px` }}>{children}</div>
</div>
);
}
type Mode = { id: number; kind: 'edit' } | { kind: 'add' } | { kind: 'list' };
function modeFromPath(pathname: string): Mode {
const normalized = pathname.replace(/\/+$/, '');
if (normalized === BASE_PATH || !normalized.startsWith(`${BASE_PATH}/`)) {
return { kind: 'list' };
}
const suffix = normalized.slice(BASE_PATH.length + 1).split('/')[0];
if (suffix === 'add') {
return { kind: 'add' };
}
const id = Number(suffix);
return Number.isInteger(id) && id > 0 ? { id, kind: 'edit' } : { kind: 'list' };
}
export function WatermarksScreen() {
const [pathname, setPathname] = useState(() => window.location.pathname);
useEffect(() => {
const onPop = () => setPathname(window.location.pathname);
window.addEventListener('popstate', onPop);
return () => window.removeEventListener('popstate', onPop);
}, []);
const mode = modeFromPath(pathname);
if (mode.kind === 'list') {
return <WatermarkList key={pathname} />;
}
return <WatermarkEditor key={pathname} mode={mode} />;
}
function WatermarkList() {
const [watermarks, setWatermarks] = useState<Watermark[] | null>(null);
const [error, setError] = useState<null | string>(null);
const [deleteTarget, setDeleteTarget] = useState<Watermark | null>(null);
const [busy, setBusy] = useState(false);
const activeRef = useRef(true);
const load = useCallback(() => {
getWatermarks()
.then((data) => {
if (activeRef.current) {
setWatermarks(data);
setError(null);
}
})
.catch((loadError: unknown) => {
if (activeRef.current) {
setError(messageFromWatermarkError(loadError));
}
});
}, []);
useEffect(() => {
activeRef.current = true;
load();
return () => {
activeRef.current = false;
};
}, [load]);
const confirmDelete = async () => {
if (!deleteTarget) {
return;
}
setBusy(true);
try {
await deleteWatermark(deleteTarget.id);
setDeleteTarget(null);
load();
} catch (deleteError) {
setError(messageFromWatermarkError(deleteError, 'Unable to delete watermark'));
} finally {
setBusy(false);
}
};
if (error && !watermarks) {
return (
<div className="ctv-collections">
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
<span className="ctv-channels-spacer" />
<Button onClick={load} size="sm" variant="secondary">
Retry
</Button>
</div>
</div>
);
}
if (!watermarks) {
return (
<div className="ctv-collections-loading" role="status">
<Spinner size={18} />
<span>Loading watermarks…</span>
</div>
);
}
const sorted = [...watermarks].sort((a, b) => (a.name ?? '').localeCompare(b.name ?? ''));
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Badge tone="neutral">{watermarks.length} watermarks</Badge>
<span className="ctv-channels-spacer" />
<Button
onClick={() => navigateToPath(`${BASE_PATH}/add`)}
size="sm"
startIcon={<Plus aria-hidden="true" size={14} />}
>
New watermark
</Button>
</div>
{error && (
<div className="ctv-channels-error" role="alert">
<TriangleAlert aria-hidden="true" size={15} />
<span>{error}</span>
</div>
)}
<Card padded={false}>
{sorted.length === 0 ? (
<div className="ctv-collections-empty">No watermarks yet.</div>
) : (
sorted.map((watermark, index) => (
<div
className="ctv-settings-flush-row"
key={watermark.id}
style={index === 0 ? { borderTop: 'none' } : undefined}
>
<ImageIcon aria-hidden="true" color="var(--ctv-accent)" size={15} />
<button
className="ctv-settings-flush-row-main ctv-settings-flush-row-title ctv-collections-linkbtn"
onClick={() => navigateToPath(`${BASE_PATH}/${watermark.id}`)}
type="button"
>
{watermark.name}
</button>
<IconButton onClick={() => setDeleteTarget(watermark)} size="sm" title="Delete" variant="ghost">
<Trash2 aria-hidden="true" size={14} />
</IconButton>
</div>
))
)}
</Card>
<ConfirmDialog
busy={busy}
confirmLabel="Delete"
message={deleteTarget ? `Delete "${deleteTarget.name}"? This cannot be undone.` : ''}
onCancel={() => setDeleteTarget(null)}
onConfirm={() => void confirmDelete()}
open={deleteTarget !== null}
title="Delete watermark"
tone="danger"
/>
</div>
);
}
function WatermarkEditor({ mode }: { mode: { id: number; kind: 'edit' } | { kind: 'add' } }) {
const [draft, setDraft] = useState<Draft | null>(mode.kind === 'add' ? defaultDraft : null);
const [loadError, setLoadError] = useState<null | string>(null);
const [saveError, setSaveError] = useState<null | string>(null);
const [uploadError, setUploadError] = useState<null | string>(null);
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const fileRef = useRef<HTMLInputElement>(null);
const isEdit = mode.kind === 'edit';
// Captured once at mount; the screen keys this editor by pathname (see ChannelEditScreen).
const [loadEditId] = useState(() => (mode.kind === 'edit' ? mode.id : null));
useEffect(() => {
if (loadEditId == null) {
return;
}
let active = true;
getWatermark(loadEditId)
.then((watermark) => {
if (active) {
setDraft(draftFromWatermark(watermark as Watermark & Draft));
}
})
.catch((error: unknown) => {
if (active) {
setLoadError(messageFromWatermarkError(error, 'Unable to load watermark'));
}
});
return () => {
active = false;
};
}, [loadEditId]);
if (loadError) {
return (
<div className="ctv-settings-error" role="alert">
<TriangleAlert aria-hidden="true" size={16} />
<span>{loadError}</span>
<Button onClick={() => navigateToPath(BASE_PATH)} size="sm" variant="secondary">
Back to watermarks
</Button>
</div>
);
}
if (!draft) {
return (
<div className="ctv-settings-loading">
<Spinner size={18} />
<span>Loading watermark…</span>
</div>
);
}
const set = (patch: Partial<Draft>) => {
setDraft((current) => (current ? { ...current, ...patch } : current));
};
const validationError = validate(draft);
const modeNone = draft.mode === 'None';
const custom = draft.imageSource === 'Custom';
const upload = async (file: File) => {
if (!file.type.startsWith('image/')) {
setUploadError('Choose an image file.');
return;
}
setUploading(true);
setUploadError(null);
try {
const uploaded = await uploadArtwork(file, 'watermark');
set({ image: uploaded.path, imageContentType: uploaded.contentType });
} catch (error) {
setUploadError(messageFromWatermarkError(error, 'Unable to upload image'));
} finally {
setUploading(false);
}
};
const save = async () => {
if (validationError || saving) {
return;
}
setSaving(true);
setSaveError(null);
try {
if (mode.kind === 'edit') {
await updateWatermark(mode.id, draft);
} else {
await createWatermark(draft);
}
navigateToPath(BASE_PATH);
} catch (error) {
setSaveError(messageFromWatermarkError(error, 'Unable to save watermark'));
} finally {
setSaving(false);
}
};
return (
<div className="ctv-collections">
<div className="ctv-channels-actionbar">
<Button
onClick={() => navigateToPath(BASE_PATH)}
size="sm"
startIcon={<ArrowLeft aria-hidden="true" size={14} />}
variant="ghost"
>
All watermarks
</Button>
<span className="ctv-collections-detail-title">{isEdit ? 'Edit watermark' : 'New watermark'}</span>
<span className="ctv-channels-spacer" />
{saveError && <span className="ctv-settings-savebar-error">{saveError}</span>}
{validationError && <Badge tone="neutral">{validationError}</Badge>}
<Button
disabled={validationError !== null || saving}
loading={saving}
onClick={() => void save()}
size="sm"
startIcon={<Check aria-hidden="true" size={14} />}
>
{isEdit ? 'Save watermark' : 'Add watermark'}
</Button>
</div>
<Card padded={false} title="Watermark">
<Row control={360} first label="Name">
<Input
error={draft.name.trim() ? null : 'Name is required'}
onChange={(event) => set({ name: event.target.value })}
size="sm"
value={draft.name}
/>
</Row>
<Row control={360} label="Mode">
<Select
onChange={(event) => set({ mode: event.target.value as Draft['mode'] })}
options={MODE_OPTIONS}
value={draft.mode}
/>
</Row>
<Row control={360} label="Image source">
<Select
disabled={modeNone}
onChange={(event) => set({ imageSource: event.target.value as Draft['imageSource'] })}
options={IMAGE_SOURCE_OPTIONS}
value={draft.imageSource}
/>
</Row>
<Row control={360} help="Only used with a custom image source." label="Image">
<input
accept="image/*"
onChange={(event) => {
const file = event.target.files?.[0];
if (file) {
void upload(file);
}
}}
ref={fileRef}
style={{ display: 'none' }}
type="file"
/>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<Button
disabled={!custom}
loading={uploading}
onClick={() => fileRef.current?.click()}
size="sm"
startIcon={<Upload aria-hidden="true" size={14} />}
variant="secondary"
>
Upload image
</Button>
{custom && draft.image && (
<img
alt="Watermark preview"
src={watermarkImageUrl(draft.image, draft.imageContentType)}
style={{ maxHeight: 60, maxWidth: 200, objectFit: 'contain' }}
/>
)}
{uploadError && (
<span className="ctv-field-error" role="alert">
{uploadError}
</span>
)}
</div>
</Row>
<Row control={360} label="Location">
<Select
disabled={modeNone}
onChange={(event) => set({ location: event.target.value as Draft['location'] })}
options={LOCATION_OPTIONS}
value={draft.location}
/>
</Row>
<Row control={200} label="Place within source content">
<Checkbox
checked={draft.placeWithinSourceContent}
disabled={modeNone}
onChange={(placeWithinSourceContent) => set({ placeWithinSourceContent })}
/>
</Row>
<Row control={360} label="Size">
<Select
disabled={modeNone}
onChange={(event) => set({ size: event.target.value as Draft['size'] })}
options={SIZE_OPTIONS}
value={draft.size}
/>
</Row>
<Row control={220} label="Width">
<Input
disabled={modeNone || draft.size === 'ActualSize'}
onChange={(event) => set({ width: Number(event.target.value) })}
size="sm"
trailing="%"
type="number"
value={String(draft.width)}
/>
</Row>
<Row control={220} label="Horizontal margin">
<Input
disabled={modeNone}
onChange={(event) => set({ horizontalMargin: Number(event.target.value) })}
size="sm"
trailing="%"
type="number"
value={String(draft.horizontalMargin)}
/>
</Row>
<Row control={220} label="Vertical margin">
<Input
disabled={modeNone}
onChange={(event) => set({ verticalMargin: Number(event.target.value) })}
size="sm"
trailing="%"
type="number"
value={String(draft.verticalMargin)}
/>
</Row>
<Row control={360} label="Frequency">
<Select
disabled={draft.mode !== 'Intermittent'}
onChange={(event) => set({ frequencyMinutes: Number(event.target.value) })}
options={FREQUENCY_OPTIONS}
value={String(draft.frequencyMinutes)}
/>
</Row>
<Row control={220} label="Duration">
<Input
disabled={draft.mode !== 'Intermittent'}
onChange={(event) => set({ durationSeconds: Number(event.target.value) })}
size="sm"
trailing="seconds"
type="number"
value={String(draft.durationSeconds)}
/>
</Row>
<Row control={220} label="Opacity">
<Input
disabled={modeNone || draft.mode === 'OpacityExpression'}
onChange={(event) => set({ opacity: Number(event.target.value) })}
size="sm"
trailing="%"
type="number"
value={String(draft.opacity)}
/>
</Row>
<Row control={360} label="Opacity expression">
<Input
disabled={draft.mode !== 'OpacityExpression'}
onChange={(event) => set({ opacityExpression: event.target.value })}
size="sm"
value={draft.opacityExpression ?? ''}
/>
</Row>
<Row control={200} label="Z-index">
<Input
onChange={(event) => set({ zIndex: Number(event.target.value) })}
size="sm"
type="number"
value={String(draft.zIndex)}
/>
</Row>
</Card>
</div>
);
}