mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-22 05:23:01 +03:00
add transcoded live streams and stream ordering for auto mode
Cameras can now add lower quality live streams that go2rtc transcodes to H.264 on demand. `live.transcode` takes a source stream and a list of heights and bitrates, and each quality becomes a `{camera}_transcode_{height}p` stream. The config validator adds them to `live.streams` without moving any the user already placed, and drops them when transcoding is disabled or a height changes. `create_config.py` writes them into go2rtc's generated config at startup, and saving the config or deleting a camera syncs them through go2rtc's API, so no restart is needed. They use `#hardware`, so go2rtc picks a hardware encoder and falls back to the CPU when there isn't one.
The Live playback settings stream list can be reordered by drag, since its order is the auto ladder. Auto order sorts it by bitrate, measuring native streams through a new admin-only `/go2rtc/streams/{name}/bitrate` endpoint and using the configured bitrate for transcoded ones. A pure reorder wasn't saved before because RJSF, the settings form, and `update_yaml` all ignore map key order. Sections can now mark a map with `orderedMaps`, which sends the whole map with `replace_paths` so `config_set` rewrites it in order.
Transcoded streams aren't in `go2rtc.streams`, which only lists yaml streams, so the frontend treated them as not restreamed and fell back to jsmpeg. Every restream check now goes through `isRestreamedStream`.
Auto treated any stall with no bytes in the last 2 seconds as a dead camera and handed it to the error fallback, which went straight to jsmpeg. Heavy congestion can stop delivery completely, so congested viewers skipped every lower stream. Auto now declines only when stats show the camera offline, and a stall on a live camera steps down. The stream picker also has a Try highest quality button that sends auto back to the top stream.
This commit is contained in:
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -134,6 +134,43 @@ test.describe("Auto live stream @mobile", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Transcoded live stream @mobile", () => {
|
||||
test("a pinned transcoded stream plays over MSE", async ({ frigateApp }) => {
|
||||
// go2rtc.streams lists only yaml streams; transcoded ones are generated
|
||||
await frigateApp.installDefaults({
|
||||
config: {
|
||||
...CONFIG,
|
||||
cameras: {
|
||||
front_door: {
|
||||
live: {
|
||||
streams: {
|
||||
Sub: "front_door_sub",
|
||||
"720p": "front_door_transcode_720p",
|
||||
},
|
||||
transcode: {
|
||||
enabled: true,
|
||||
source: "front_door",
|
||||
qualities: [{ height: 720, bitrate: 1200 }],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const opened = await mockGo2rtc(frigateApp.page);
|
||||
|
||||
await frigateApp.goto("/");
|
||||
await writeIdb(frigateApp.page, {
|
||||
[STREAM_KEY]: "front_door_transcode_720p",
|
||||
});
|
||||
await frigateApp.goto("/#front_door");
|
||||
|
||||
await expect
|
||||
.poll(() => opened, { timeout: 10_000 })
|
||||
.toContain("front_door_transcode_720p");
|
||||
});
|
||||
});
|
||||
|
||||
test.describe("Auto live stream selector", () => {
|
||||
test.beforeEach(({ frigateApp }) => {
|
||||
test.skip(frigateApp.isMobile, "Desktop dropdown only");
|
||||
@@ -168,6 +205,26 @@ test.describe("Auto live stream selector", () => {
|
||||
).toBeVisible();
|
||||
});
|
||||
|
||||
test("trying the highest quality retries the top stream", async ({
|
||||
frigateApp,
|
||||
}) => {
|
||||
await frigateApp.installDefaults({ config: CONFIG });
|
||||
const opened = await mockGo2rtc(frigateApp.page, ["front_door"]);
|
||||
|
||||
await frigateApp.goto("/#front_door");
|
||||
|
||||
await expect
|
||||
.poll(() => opened, { timeout: 10_000 })
|
||||
.toContain("front_door_sub");
|
||||
const menu = await openDesktopSettings(frigateApp.page);
|
||||
const beforeRetry = opened.length;
|
||||
await menu.getByRole("button", { name: "Try highest quality" }).click();
|
||||
|
||||
await expect
|
||||
.poll(() => opened.slice(beforeRetry), { timeout: 10_000 })
|
||||
.toContain("front_door");
|
||||
});
|
||||
|
||||
test("a pinned main takes the legacy fallback instead of stepping down", async ({
|
||||
frigateApp,
|
||||
}) => {
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
/**
|
||||
* Live playback stream order and transcoded streams -- MEDIUM tier.
|
||||
*
|
||||
* The stream list order is the Auto ladder, so the form saves it with
|
||||
* replace_paths. Transcoded streams are generated from live.transcode and
|
||||
* appear in the list as soon as the switch flips.
|
||||
*/
|
||||
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { test, expect } from "../../fixtures/frigate-test";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { configFactory } from "../../fixtures/mock-data/config";
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const CONFIG_SCHEMA = JSON.parse(
|
||||
readFileSync(
|
||||
resolve(__dirname, "../../fixtures/mock-data/config-schema.json"),
|
||||
"utf-8",
|
||||
),
|
||||
);
|
||||
|
||||
const GO2RTC_STREAMS = {
|
||||
front_door_main: ["rtsp://user:pass@192.168.0.20:554/main"],
|
||||
front_door_sub: ["rtsp://user:pass@192.168.0.20:554/sub"],
|
||||
};
|
||||
|
||||
const TRANSCODE = {
|
||||
enabled: false,
|
||||
qualities: [
|
||||
{ height: 720, bitrate: 1200 },
|
||||
{ height: 480, bitrate: 500 },
|
||||
],
|
||||
};
|
||||
|
||||
const SETTINGS_URL = "/settings?page=cameraLivePlayback&camera=front_door";
|
||||
|
||||
type RouteOptions = {
|
||||
go2rtcStreams?: Record<string, string[]>;
|
||||
streams?: Record<string, string>;
|
||||
bitrates?: Record<string, number>;
|
||||
};
|
||||
|
||||
async function installRoutes(page: Page, options: RouteOptions = {}) {
|
||||
const go2rtcStreams = options.go2rtcStreams ?? GO2RTC_STREAMS;
|
||||
const streams = options.streams ?? {
|
||||
Sub: "front_door_sub",
|
||||
Main: "front_door_main",
|
||||
};
|
||||
const live = { streams, transcode: TRANSCODE };
|
||||
const config = configFactory({
|
||||
go2rtc: { streams: go2rtcStreams },
|
||||
cameras: { front_door: { live } },
|
||||
});
|
||||
// configFactory's deepMerge adds override keys onto the base fixture's
|
||||
// streams map instead of replacing it (they share no key names here), so
|
||||
// pin the streams map to exactly what this test wants.
|
||||
config.cameras.front_door.live.streams = streams;
|
||||
|
||||
let lastSaved: Record<string, unknown> | null = null;
|
||||
|
||||
await page.route("**/api/config/schema.json", (route) =>
|
||||
route.fulfill({ json: CONFIG_SCHEMA }),
|
||||
);
|
||||
await page.route("**/api/config", (route) => {
|
||||
if (route.request().method() === "GET") {
|
||||
return route.fulfill({ json: config });
|
||||
}
|
||||
return route.fulfill({ json: { success: true } });
|
||||
});
|
||||
await page.route("**/api/config/raw_paths", (route) =>
|
||||
route.fulfill({
|
||||
json: {
|
||||
go2rtc: { streams: go2rtcStreams },
|
||||
cameras: { front_door: { live } },
|
||||
},
|
||||
}),
|
||||
);
|
||||
await page.route("**/api/config/set", async (route) => {
|
||||
lastSaved = route.request().postDataJSON();
|
||||
await route.fulfill({ json: { success: true, go2rtc_synced: true } });
|
||||
});
|
||||
await page.route("**/api/go2rtc/streams/*/bitrate", (route) => {
|
||||
const name = decodeURIComponent(
|
||||
new URL(route.request().url()).pathname.split("/").slice(-2)[0],
|
||||
);
|
||||
const kbps = options.bitrates?.[name];
|
||||
return kbps === undefined
|
||||
? route.fulfill({ status: 502, json: { success: false } })
|
||||
: route.fulfill({ json: { success: true, kbps } });
|
||||
});
|
||||
|
||||
return { saved: () => lastSaved };
|
||||
}
|
||||
|
||||
function streamNames(page: Page) {
|
||||
return page
|
||||
.getByRole("textbox", { name: "Stream name" })
|
||||
.evaluateAll((inputs) =>
|
||||
inputs.map((input) => (input as HTMLInputElement).value),
|
||||
);
|
||||
}
|
||||
|
||||
async function dragRow(page: Page, from: number, to: number) {
|
||||
const handles = page.getByRole("button", { name: "Drag to reorder" });
|
||||
const start = await handles.nth(from).boundingBox();
|
||||
const end = await handles.nth(to).boundingBox();
|
||||
|
||||
if (!start || !end) throw new Error("drag handle not visible");
|
||||
|
||||
await page.mouse.move(start.x + start.width / 2, start.y + start.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(
|
||||
end.x + end.width / 2,
|
||||
end.y + end.height / 2 + (to > from ? 12 : -12),
|
||||
{ steps: 15 },
|
||||
);
|
||||
await page.mouse.up();
|
||||
}
|
||||
|
||||
test.describe("live stream order and transcoded streams @medium", () => {
|
||||
test.skip(({ frigateApp }) => frigateApp.isMobile, "desktop drag");
|
||||
|
||||
test("dragging a stream saves the new order", async ({ frigateApp }) => {
|
||||
const capture = await installRoutes(frigateApp.page);
|
||||
await frigateApp.goto(SETTINGS_URL);
|
||||
|
||||
await expect
|
||||
.poll(() => streamNames(frigateApp.page))
|
||||
.toEqual(["Sub", "Main"]);
|
||||
|
||||
await dragRow(frigateApp.page, 1, 0);
|
||||
await expect
|
||||
.poll(() => streamNames(frigateApp.page))
|
||||
.toEqual(["Main", "Sub"]);
|
||||
|
||||
await frigateApp.page.getByRole("button", { name: "Save" }).click();
|
||||
|
||||
await expect.poll(() => capture.saved()).not.toBeNull();
|
||||
const saved = capture.saved() as {
|
||||
replace_paths: string[];
|
||||
config_data: {
|
||||
cameras: { front_door: { live: { streams: Record<string, string> } } };
|
||||
};
|
||||
};
|
||||
expect(saved.replace_paths).toEqual(["cameras.front_door.live.streams"]);
|
||||
expect(
|
||||
Object.keys(saved.config_data.cameras.front_door.live.streams),
|
||||
).toEqual(["Main", "Sub"]);
|
||||
});
|
||||
|
||||
test("enabling transcoding saves the shown source", async ({
|
||||
frigateApp,
|
||||
}) => {
|
||||
const capture = await installRoutes(frigateApp.page);
|
||||
await frigateApp.goto(SETTINGS_URL);
|
||||
|
||||
await frigateApp.page
|
||||
.getByRole("switch", { name: "Enable transcoded streams" })
|
||||
.click();
|
||||
await frigateApp.page.getByRole("button", { name: "Save" }).click();
|
||||
|
||||
await expect.poll(() => capture.saved()).not.toBeNull();
|
||||
const saved = capture.saved() as {
|
||||
config_data: {
|
||||
cameras: {
|
||||
front_door: { live: { transcode: Record<string, unknown> } };
|
||||
};
|
||||
};
|
||||
};
|
||||
// pinned, so dragging another stream to the top can't change it
|
||||
expect(saved.config_data.cameras.front_door.live.transcode).toMatchObject({
|
||||
enabled: true,
|
||||
source: "front_door_sub",
|
||||
});
|
||||
});
|
||||
|
||||
test("the transcode switch adds and removes transcoded rows", async ({
|
||||
frigateApp,
|
||||
}) => {
|
||||
await installRoutes(frigateApp.page);
|
||||
await frigateApp.goto(SETTINGS_URL);
|
||||
|
||||
const toggle = frigateApp.page.getByRole("switch", {
|
||||
name: "Enable transcoded streams",
|
||||
});
|
||||
const save = frigateApp.page.getByRole("button", { name: "Save" });
|
||||
|
||||
await toggle.click();
|
||||
await expect
|
||||
.poll(() => streamNames(frigateApp.page))
|
||||
.toEqual(["Sub", "Main", "720p", "480p"]);
|
||||
await expect(
|
||||
frigateApp.page.getByText("Transcoded", { exact: true }),
|
||||
).toHaveCount(2);
|
||||
await expect(save).toBeEnabled();
|
||||
|
||||
await toggle.click();
|
||||
await expect
|
||||
.poll(() => streamNames(frigateApp.page))
|
||||
.toEqual(["Sub", "Main"]);
|
||||
await expect(save).toBeDisabled();
|
||||
});
|
||||
|
||||
test("auto order sorts measured and set bitrates", async ({ frigateApp }) => {
|
||||
await installRoutes(frigateApp.page, {
|
||||
bitrates: { front_door_main: 4000, front_door_sub: 800 },
|
||||
});
|
||||
await frigateApp.goto(SETTINGS_URL);
|
||||
|
||||
await frigateApp.page
|
||||
.getByRole("switch", { name: "Enable transcoded streams" })
|
||||
.click();
|
||||
await frigateApp.page.getByRole("button", { name: "Auto order" }).click();
|
||||
|
||||
await expect
|
||||
.poll(() => streamNames(frigateApp.page))
|
||||
.toEqual(["Main", "720p", "Sub", "480p"]);
|
||||
await expect(frigateApp.page.getByText("4000 kbps")).toBeVisible();
|
||||
await expect(frigateApp.page.getByText("1200 kbps (set)")).toBeVisible();
|
||||
});
|
||||
|
||||
test("an unmeasurable stream sorts last", async ({ frigateApp }) => {
|
||||
await installRoutes(frigateApp.page, {
|
||||
bitrates: { front_door_main: 4000 },
|
||||
});
|
||||
await frigateApp.goto(SETTINGS_URL);
|
||||
|
||||
await frigateApp.page.getByRole("button", { name: "Auto order" }).click();
|
||||
|
||||
await expect
|
||||
.poll(() => streamNames(frigateApp.page))
|
||||
.toEqual(["Main", "Sub"]);
|
||||
await expect(frigateApp.page.getByText("Couldn't measure")).toBeVisible();
|
||||
});
|
||||
|
||||
test("transcoding needs a go2rtc stream", async ({ frigateApp }) => {
|
||||
await installRoutes(frigateApp.page, {
|
||||
go2rtcStreams: {},
|
||||
streams: { front_door: "front_door" },
|
||||
});
|
||||
await frigateApp.goto(SETTINGS_URL);
|
||||
|
||||
await expect(
|
||||
frigateApp.page.getByRole("switch", {
|
||||
name: "Enable transcoded streams",
|
||||
}),
|
||||
).toBeDisabled();
|
||||
await expect(
|
||||
frigateApp.page.getByText(/need a go2rtc stream to read from/),
|
||||
).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -238,6 +238,30 @@
|
||||
"label": "Live stream names",
|
||||
"description": "Mapping of configured stream names to restream/go2rtc names used for live playback."
|
||||
},
|
||||
"transcode": {
|
||||
"label": "Transcoded streams",
|
||||
"description": "Lower-quality live streams transcoded on demand by go2rtc.",
|
||||
"enabled": {
|
||||
"label": "Enable transcoded streams",
|
||||
"description": "Add lower-quality live streams that go2rtc transcodes in real time while someone is watching."
|
||||
},
|
||||
"source": {
|
||||
"label": "Source stream",
|
||||
"description": "go2rtc stream to transcode. Defaults to the first live stream."
|
||||
},
|
||||
"qualities": {
|
||||
"label": "Qualities",
|
||||
"description": "One transcoded stream is added per quality.",
|
||||
"height": {
|
||||
"label": "Height",
|
||||
"description": "Output height in pixels; width follows the source aspect ratio."
|
||||
},
|
||||
"bitrate": {
|
||||
"label": "Bitrate",
|
||||
"description": "Target and maximum video bitrate in kbps."
|
||||
}
|
||||
}
|
||||
},
|
||||
"height": {
|
||||
"label": "Live height",
|
||||
"description": "Height (pixels) to render the jsmpeg live stream in the Web UI; must be <= detect stream height."
|
||||
|
||||
@@ -594,6 +594,30 @@
|
||||
"label": "Live stream names",
|
||||
"description": "Mapping of configured stream names to restream/go2rtc names used for live playback."
|
||||
},
|
||||
"transcode": {
|
||||
"label": "Transcoded streams",
|
||||
"description": "Lower-quality live streams transcoded on demand by go2rtc.",
|
||||
"enabled": {
|
||||
"label": "Enable transcoded streams",
|
||||
"description": "Add lower-quality live streams that go2rtc transcodes in real time while someone is watching."
|
||||
},
|
||||
"source": {
|
||||
"label": "Source stream",
|
||||
"description": "go2rtc stream to transcode. Defaults to the first live stream."
|
||||
},
|
||||
"qualities": {
|
||||
"label": "Qualities",
|
||||
"description": "One transcoded stream is added per quality.",
|
||||
"height": {
|
||||
"label": "Height",
|
||||
"description": "Output height in pixels; width follows the source aspect ratio."
|
||||
},
|
||||
"bitrate": {
|
||||
"label": "Bitrate",
|
||||
"description": "Target and maximum video bitrate in kbps."
|
||||
}
|
||||
}
|
||||
},
|
||||
"height": {
|
||||
"label": "Live height",
|
||||
"description": "Height (pixels) to render the jsmpeg live stream in the Web UI; must be <= detect stream height."
|
||||
|
||||
@@ -137,6 +137,7 @@
|
||||
"tips": "Switches streams to match your connection",
|
||||
"selected": "Auto · {{stream}}",
|
||||
"floorLabel": "Low bandwidth",
|
||||
"retry": "Try highest quality",
|
||||
"reason": {
|
||||
"bandwidth": "Playing {{stream}} because the connection couldn't keep up with a higher-quality stream",
|
||||
"codec": "Playing {{stream}} because this browser can't play a higher-quality stream",
|
||||
|
||||
@@ -1553,7 +1553,27 @@
|
||||
"noGo2rtcStreams": "No go2rtc streams configured",
|
||||
"availableStreams": "Available streams",
|
||||
"useCustom": "Use \"{{value}}\"",
|
||||
"addStream": "Add stream"
|
||||
"addStream": "Add stream",
|
||||
"reorderHandle": "Drag to reorder",
|
||||
"transcodedBadge": "Transcoded",
|
||||
"autoOrder": "Auto order",
|
||||
"autoOrderTips": "Measure each stream's bitrate and sort highest first",
|
||||
"measuring": "Measuring…",
|
||||
"rate": "{{kbps}} kbps",
|
||||
"rateSet": "{{kbps}} kbps (set)",
|
||||
"rateFailed": "Couldn't measure"
|
||||
},
|
||||
"liveTranscode": {
|
||||
"title": "Transcoded streams",
|
||||
"description": "Adds lower-quality streams that go2rtc transcodes in real time while someone is watching.",
|
||||
"unavailable": "Transcoded streams need a go2rtc stream to read from. Add one under go2rtc streams first.",
|
||||
"enable": "Enable transcoded streams",
|
||||
"source": "Source stream",
|
||||
"height": "Height",
|
||||
"heightOption": "{{height}}p",
|
||||
"bitrate": "Bitrate (kbps)",
|
||||
"addQuality": "Add quality",
|
||||
"removeQuality": "Remove quality"
|
||||
},
|
||||
"timezone": {
|
||||
"defaultOption": "Use browser timezone"
|
||||
@@ -1788,6 +1808,7 @@
|
||||
"toast": {
|
||||
"success": "Settings saved successfully",
|
||||
"applied": "Settings applied successfully",
|
||||
"go2rtcSyncFailed": "Saved, but go2rtc couldn't be updated. Restart Frigate to apply.",
|
||||
"successRestartRequired": "Settings saved successfully. Restart Frigate to apply your changes.",
|
||||
"error": "Failed to save settings",
|
||||
"validationError": "Validation failed: {{message}}",
|
||||
|
||||
@@ -4,17 +4,18 @@ const live: SectionConfigOverrides = {
|
||||
base: {
|
||||
sectionDocs: "/configuration/live",
|
||||
restartRequired: [],
|
||||
fieldOrder: ["streams", "height", "quality"],
|
||||
fieldOrder: ["streams", "transcode", "height", "quality"],
|
||||
fieldGroups: {},
|
||||
hiddenFields: ["enabled_in_config"],
|
||||
advancedFields: ["height", "quality"],
|
||||
},
|
||||
global: {
|
||||
restartRequired: ["streams", "height", "quality"],
|
||||
hiddenFields: ["streams"],
|
||||
hiddenFields: ["streams", "transcode"],
|
||||
},
|
||||
camera: {
|
||||
restartRequired: ["height", "quality"],
|
||||
orderedMaps: ["streams"],
|
||||
uiSchema: {
|
||||
streams: {
|
||||
"ui:field": "LiveStreamsField",
|
||||
@@ -23,6 +24,13 @@ const live: SectionConfigOverrides = {
|
||||
suppressDescription: true,
|
||||
},
|
||||
},
|
||||
transcode: {
|
||||
"ui:field": "LiveTranscodeField",
|
||||
"ui:options": {
|
||||
label: false,
|
||||
suppressDescription: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
@@ -66,6 +66,8 @@ import {
|
||||
cameraUpdateTopicMap,
|
||||
globalCameraDefaultSections,
|
||||
buildOverrides,
|
||||
applyOrderedMaps,
|
||||
changedOrderedMapPaths,
|
||||
buildConfigDataForPath,
|
||||
flattenOverrides,
|
||||
getBaseCameraSectionValue,
|
||||
@@ -121,6 +123,8 @@ export interface SectionConfig {
|
||||
messages?: ConditionalMessage[];
|
||||
/** Conditional messages displayed inline with specific fields */
|
||||
fieldMessages?: FieldConditionalMessage[];
|
||||
/** Maps whose key order is saved (e.g. live stream ladder order) */
|
||||
orderedMaps?: string[];
|
||||
}
|
||||
|
||||
export interface BaseSectionProps {
|
||||
@@ -488,6 +492,18 @@ export function ConfigSection({
|
||||
[rawFormData, sanitizeSectionData],
|
||||
);
|
||||
|
||||
const orderedMaps = sectionConfig.orderedMaps;
|
||||
const buildSectionOverrides = useCallback(
|
||||
(current: unknown, base: unknown, defaults: unknown) =>
|
||||
applyOrderedMaps(
|
||||
buildOverrides(current, base, defaults),
|
||||
current,
|
||||
base,
|
||||
orderedMaps ?? [],
|
||||
),
|
||||
[orderedMaps],
|
||||
);
|
||||
|
||||
// Clear pendingData whenever the section/camera key changes (e.g., switching
|
||||
// cameras) or when there is no pending data yet (initialization).
|
||||
// This prevents RJSF's initial onChange call from being treated as a user edit.
|
||||
@@ -528,10 +544,12 @@ export function ConfigSection({
|
||||
// Track if there are unsaved changes
|
||||
const hasChanges = useMemo(() => {
|
||||
const pendingChanged = pendingData
|
||||
? !isEqual(formData, pendingData)
|
||||
? !isEqual(formData, pendingData) ||
|
||||
changedOrderedMapPaths(pendingData, formData, orderedMaps ?? [])
|
||||
.length > 0
|
||||
: false;
|
||||
return pendingChanged || extraHasChanges;
|
||||
}, [formData, pendingData, extraHasChanges]);
|
||||
}, [formData, pendingData, extraHasChanges, orderedMaps]);
|
||||
|
||||
useEffect(() => {
|
||||
onStatusChange?.({
|
||||
@@ -564,7 +582,7 @@ export function ConfigSection({
|
||||
}
|
||||
const sanitizedData = sanitizeSectionData(data as ConfigSectionData);
|
||||
const nextBaselineFormData = baselineSnapshot;
|
||||
const overrides = buildOverrides(
|
||||
const overrides = buildSectionOverrides(
|
||||
sanitizedData,
|
||||
compareBaseData,
|
||||
effectiveSchemaDefaults,
|
||||
@@ -579,7 +597,7 @@ export function ConfigSection({
|
||||
return;
|
||||
}
|
||||
}
|
||||
const dirty = buildOverrides(
|
||||
const dirty = buildSectionOverrides(
|
||||
sanitizedData,
|
||||
nextBaselineFormData,
|
||||
undefined,
|
||||
@@ -602,12 +620,24 @@ export function ConfigSection({
|
||||
setPendingOverrides,
|
||||
setDirtyOverrides,
|
||||
baselineSnapshot,
|
||||
buildSectionOverrides,
|
||||
],
|
||||
);
|
||||
|
||||
const currentFormData = pendingData || formData;
|
||||
const effectiveBaselineFormData = baselineSnapshot;
|
||||
|
||||
// RJSF memoizes fields with an order-blind deep compare, so a pure reorder
|
||||
// of an ordered map would not re-render; the key order breaks the tie
|
||||
const orderedMapsKeyOrder = useMemo(
|
||||
() =>
|
||||
(orderedMaps ?? []).map((path) => {
|
||||
const value = get(currentFormData, path);
|
||||
return value && typeof value === "object" ? Object.keys(value) : [];
|
||||
}),
|
||||
[currentFormData, orderedMaps],
|
||||
);
|
||||
|
||||
// Build context for conditional messages
|
||||
const messageContext = useMemo<MessageConditionContext | undefined>(() => {
|
||||
if (!config || !currentFormData) return undefined;
|
||||
@@ -636,7 +666,7 @@ export function ConfigSection({
|
||||
const sanitizedData = sanitizeSectionData(
|
||||
currentFormData as ConfigSectionData,
|
||||
);
|
||||
return buildOverrides(
|
||||
return buildSectionOverrides(
|
||||
sanitizedData,
|
||||
compareBaseData,
|
||||
effectiveSchemaDefaults,
|
||||
@@ -646,6 +676,7 @@ export function ConfigSection({
|
||||
sanitizeSectionData,
|
||||
compareBaseData,
|
||||
effectiveSchemaDefaults,
|
||||
buildSectionOverrides,
|
||||
]);
|
||||
|
||||
const effectiveOverrides = pendingData
|
||||
@@ -684,7 +715,12 @@ export function ConfigSection({
|
||||
? `cameras.${cameraName}.${effectiveSectionPath}`
|
||||
: effectiveSectionPath;
|
||||
const rawData = sanitizeSectionData(rawFormData);
|
||||
const overrides = buildOverrides(
|
||||
const replacePaths = changedOrderedMapPaths(
|
||||
pendingData,
|
||||
rawData,
|
||||
orderedMaps ?? [],
|
||||
).map((path) => `${basePath}.${path}`);
|
||||
const overrides = buildSectionOverrides(
|
||||
pendingData,
|
||||
rawData,
|
||||
effectiveSchemaDefaults,
|
||||
@@ -711,10 +747,11 @@ export function ConfigSection({
|
||||
: requiresRestartForOverrides(sanitizedOverrides);
|
||||
|
||||
const configData = buildConfigDataForPath(basePath, sanitizedOverrides);
|
||||
await axios.put("config/set", {
|
||||
const response = await axios.put("config/set", {
|
||||
requires_restart: needsRestart ? 1 : 0,
|
||||
update_topic: updateTopic,
|
||||
config_data: configData,
|
||||
...(replacePaths.length > 0 ? { replace_paths: replacePaths } : {}),
|
||||
...(skipSave ? { skip_save: true } : {}),
|
||||
});
|
||||
|
||||
@@ -752,6 +789,8 @@ export function ConfigSection({
|
||||
),
|
||||
},
|
||||
);
|
||||
} else if (response.data?.go2rtc_synced === false) {
|
||||
toast.warning(t("toast.go2rtcSyncFailed", { ns: "views/settings" }));
|
||||
} else {
|
||||
toast.success(
|
||||
t("toast.success", {
|
||||
@@ -823,6 +862,8 @@ export function ConfigSection({
|
||||
requiresRestartForOverrides,
|
||||
skipSave,
|
||||
onSavingChange,
|
||||
orderedMaps,
|
||||
buildSectionOverrides,
|
||||
]);
|
||||
|
||||
// Handle reset to global/defaults - removes camera-level override or resets global to defaults
|
||||
@@ -1030,6 +1071,7 @@ export function ConfigSection({
|
||||
setExtraHasChanges,
|
||||
overrides: uiOverrides as JsonValue | undefined,
|
||||
formData: currentFormData as ConfigSectionData,
|
||||
orderedMapsKeyOrder,
|
||||
baselineFormData: effectiveBaselineFormData as ConfigSectionData,
|
||||
pendingDataBySection,
|
||||
onPendingDataChange,
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import type { FieldPathList, FieldProps, RJSFSchema } from "@rjsf/utils";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import axios from "axios";
|
||||
import { Reorder, useDragControls } from "framer-motion";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Command,
|
||||
@@ -16,16 +20,35 @@ import {
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import ActivityIndicator from "@/components/indicators/activity-indicator";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Check, ChevronsUpDown, Plus } from "lucide-react";
|
||||
import { LuPlus, LuTrash2 } from "react-icons/lu";
|
||||
import {
|
||||
LuArrowDownWideNarrow,
|
||||
LuGripVertical,
|
||||
LuPlus,
|
||||
LuTrash2,
|
||||
} from "react-icons/lu";
|
||||
import { MapKeyInput } from "../components";
|
||||
import type { ConfigFormContext } from "@/types/configForm";
|
||||
import type { LiveTranscodeConfig } from "@/types/frigateConfig";
|
||||
import get from "lodash/get";
|
||||
import isEqual from "lodash/isEqual";
|
||||
import { isSubtreeModified } from "../utils";
|
||||
import {
|
||||
isTranscodeStreamName,
|
||||
transcodeBitrateFor,
|
||||
} from "@/utils/liveTranscode";
|
||||
|
||||
type LiveStreamsData = Record<string, string>;
|
||||
|
||||
// kbps measured by the server, or configured for a transcoded stream
|
||||
type StreamRate = { kbps: number; set: boolean } | { failed: true };
|
||||
|
||||
function rateValue(rate: StreamRate | undefined): number {
|
||||
return rate && "kbps" in rate ? rate.kbps : -1;
|
||||
}
|
||||
|
||||
type StreamValueComboboxProps = {
|
||||
id: string;
|
||||
value: string;
|
||||
@@ -156,6 +179,154 @@ function StreamValueCombobox({
|
||||
);
|
||||
}
|
||||
|
||||
type StreamRowProps = {
|
||||
entryKey: string;
|
||||
value: string;
|
||||
entryId: string;
|
||||
data: LiveStreamsData;
|
||||
generated: boolean;
|
||||
rate?: StreamRate;
|
||||
options: string[];
|
||||
disabled?: boolean;
|
||||
readonly?: boolean;
|
||||
onRename: (oldKey: string, newKey: string) => void;
|
||||
onUpdateValue: (key: string, value: string) => void;
|
||||
onRemove: (key: string) => void;
|
||||
onDragEnd: () => void;
|
||||
};
|
||||
|
||||
function StreamRow({
|
||||
entryKey,
|
||||
value,
|
||||
entryId,
|
||||
data,
|
||||
generated,
|
||||
rate,
|
||||
options,
|
||||
disabled,
|
||||
readonly,
|
||||
onRename,
|
||||
onUpdateValue,
|
||||
onRemove,
|
||||
onDragEnd,
|
||||
}: StreamRowProps) {
|
||||
const { t } = useTranslation(["views/settings", "common"]);
|
||||
const controls = useDragControls();
|
||||
const locked = disabled || readonly;
|
||||
|
||||
const deleteLabel = t("button.delete", {
|
||||
ns: "common",
|
||||
defaultValue: "Delete",
|
||||
});
|
||||
|
||||
let rateLabel: string | undefined;
|
||||
if (rate && "failed" in rate) {
|
||||
rateLabel = t("configForm.liveStreams.rateFailed", {
|
||||
ns: "views/settings",
|
||||
});
|
||||
} else if (rate?.set) {
|
||||
rateLabel = t("configForm.liveStreams.rateSet", {
|
||||
ns: "views/settings",
|
||||
kbps: rate.kbps,
|
||||
});
|
||||
} else if (rate) {
|
||||
rateLabel = t("configForm.liveStreams.rate", {
|
||||
ns: "views/settings",
|
||||
kbps: rate.kbps,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<Reorder.Item
|
||||
as="div"
|
||||
value={entryKey}
|
||||
dragListener={false}
|
||||
dragControls={controls}
|
||||
onDragEnd={onDragEnd}
|
||||
className="grid grid-cols-12 items-end gap-2 rounded-md border bg-background p-3"
|
||||
>
|
||||
<div className="col-span-12 flex items-end gap-1 md:col-span-5">
|
||||
<button
|
||||
type="button"
|
||||
disabled={locked}
|
||||
onPointerDown={(e) => controls.start(e)}
|
||||
className="mb-2 cursor-grab touch-none rounded p-1 text-muted-foreground hover:text-primary active:cursor-grabbing disabled:cursor-not-allowed"
|
||||
aria-label={t("configForm.liveStreams.reorderHandle", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
>
|
||||
<LuGripVertical className="size-4" />
|
||||
</button>
|
||||
<div className="flex-1 space-y-2">
|
||||
<Label htmlFor={`${entryId}-key`}>
|
||||
{t("configForm.liveStreams.streamNameLabel", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</Label>
|
||||
<MapKeyInput
|
||||
id={`${entryId}-key`}
|
||||
value={entryKey}
|
||||
placeholder={t("configForm.liveStreams.streamNamePlaceholder", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
disabled={locked}
|
||||
onCommit={(next) => onRename(entryKey, next)}
|
||||
isKeyTaken={(next) =>
|
||||
next !== entryKey &&
|
||||
Object.prototype.hasOwnProperty.call(data, next)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="col-span-10 space-y-2 md:col-span-6">
|
||||
<Label htmlFor={`${entryId}-value`} className="flex items-center gap-2">
|
||||
{t("configForm.liveStreams.go2rtcStreamLabel", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
{generated && (
|
||||
<Badge variant="secondary">
|
||||
{t("configForm.liveStreams.transcodedBadge", {
|
||||
ns: "views/settings",
|
||||
})}
|
||||
</Badge>
|
||||
)}
|
||||
</Label>
|
||||
{generated ? (
|
||||
<Input id={`${entryId}-value`} value={value} disabled readOnly />
|
||||
) : (
|
||||
<StreamValueCombobox
|
||||
id={`${entryId}-value`}
|
||||
value={value}
|
||||
options={options}
|
||||
disabled={disabled}
|
||||
readonly={readonly}
|
||||
onChange={(next) => onUpdateValue(entryKey, next)}
|
||||
/>
|
||||
)}
|
||||
{rateLabel && (
|
||||
<p className="text-xs text-muted-foreground">{rateLabel}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="col-span-2 flex justify-end md:col-span-1">
|
||||
{!generated && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => onRemove(entryKey)}
|
||||
disabled={locked}
|
||||
aria-label={deleteLabel}
|
||||
title={deleteLabel}
|
||||
className="shrink-0"
|
||||
>
|
||||
<LuTrash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</Reorder.Item>
|
||||
);
|
||||
}
|
||||
|
||||
export function LiveStreamsField(props: FieldProps) {
|
||||
const { schema, formData, onChange, idSchema, disabled, readonly } = props;
|
||||
const formContext = props.registry?.formContext as
|
||||
@@ -166,6 +337,7 @@ export function LiveStreamsField(props: FieldProps) {
|
||||
(formContext?.level === "camera" ? "config/cameras" : "config/global");
|
||||
const { t: fallbackT } = useTranslation(["common", configNamespace]);
|
||||
const t = formContext?.t ?? fallbackT;
|
||||
const { t: tSettings } = useTranslation(["views/settings"]);
|
||||
|
||||
const data: LiveStreamsData = useMemo(() => {
|
||||
if (!formData || typeof formData !== "object" || Array.isArray(formData)) {
|
||||
@@ -175,6 +347,7 @@ export function LiveStreamsField(props: FieldProps) {
|
||||
}, [formData]);
|
||||
|
||||
const entries = useMemo(() => Object.entries(data), [data]);
|
||||
const keys = useMemo(() => entries.map(([key]) => key), [entries]);
|
||||
|
||||
const id = idSchema?.$id ?? props.name;
|
||||
const sectionPrefix = formContext?.sectionI18nPrefix;
|
||||
@@ -185,12 +358,22 @@ export function LiveStreamsField(props: FieldProps) {
|
||||
t(`${sectionPrefix}.${id}.description`) ??
|
||||
(schema as RJSFSchema).description;
|
||||
|
||||
const camera = formContext?.cameraName ?? "";
|
||||
const transcode = formContext?.formData?.transcode as
|
||||
LiveTranscodeConfig | undefined;
|
||||
|
||||
const go2rtcStreamNames = useMemo<string[]>(() => {
|
||||
const streams = formContext?.fullConfig?.go2rtc?.streams;
|
||||
if (!streams || typeof streams !== "object") return [];
|
||||
return Object.keys(streams).sort();
|
||||
}, [formContext?.fullConfig?.go2rtc?.streams]);
|
||||
|
||||
const isGenerated = useCallback(
|
||||
(name: string) =>
|
||||
isTranscodeStreamName(camera, name) && !go2rtcStreamNames.includes(name),
|
||||
[camera, go2rtcStreamNames],
|
||||
);
|
||||
|
||||
const emptyPath = useMemo(() => [] as FieldPathList, []);
|
||||
const fieldPath =
|
||||
(props as { fieldPathId?: { path?: FieldPathList } }).fieldPathId?.path ??
|
||||
@@ -210,6 +393,51 @@ export function LiveStreamsField(props: FieldProps) {
|
||||
);
|
||||
}, [fieldPath, formContext, data]);
|
||||
|
||||
const commitOrder = useCallback(
|
||||
(order: string[]) => {
|
||||
const next: LiveStreamsData = {};
|
||||
order.forEach((key) => {
|
||||
next[key] = data[key];
|
||||
});
|
||||
onChange(next, fieldPath);
|
||||
},
|
||||
[data, fieldPath, onChange],
|
||||
);
|
||||
|
||||
// rows keep one React key through renames, so the name input stays mounted
|
||||
const rowIdsRef = useRef(new Map<string, number>());
|
||||
const nextRowIdRef = useRef(0);
|
||||
|
||||
const rowIdFor = (key: string) => {
|
||||
let id = rowIdsRef.current.get(key);
|
||||
|
||||
if (id === undefined) {
|
||||
id = nextRowIdRef.current++;
|
||||
rowIdsRef.current.set(key, id);
|
||||
}
|
||||
|
||||
return id;
|
||||
};
|
||||
|
||||
// local order while dragging; committed to the form on drop
|
||||
const [dragOrder, setDragOrder] = useState<string[] | null>(null);
|
||||
const dragOrderRef = useRef<string[] | null>(null);
|
||||
|
||||
const handleReorder = useCallback((next: string[]) => {
|
||||
dragOrderRef.current = next;
|
||||
setDragOrder(next);
|
||||
}, []);
|
||||
|
||||
const handleDragEnd = useCallback(() => {
|
||||
const next = dragOrderRef.current;
|
||||
dragOrderRef.current = null;
|
||||
setDragOrder(null);
|
||||
|
||||
if (next && !isEqual(next, keys)) {
|
||||
commitOrder(next);
|
||||
}
|
||||
}, [commitOrder, keys]);
|
||||
|
||||
const handleAddEntry = useCallback(() => {
|
||||
const next = { ...data, "": "" };
|
||||
onChange(next, fieldPath);
|
||||
@@ -227,6 +455,13 @@ export function LiveStreamsField(props: FieldProps) {
|
||||
const handleRenameKey = useCallback(
|
||||
(oldKey: string, newKey: string) => {
|
||||
if (oldKey === newKey) return;
|
||||
|
||||
const id = rowIdsRef.current.get(oldKey);
|
||||
if (id !== undefined) {
|
||||
rowIdsRef.current.delete(oldKey);
|
||||
rowIdsRef.current.set(newKey, id);
|
||||
}
|
||||
|
||||
const next: LiveStreamsData = {};
|
||||
for (const [k, v] of Object.entries(data)) {
|
||||
if (k === oldKey) {
|
||||
@@ -248,24 +483,76 @@ export function LiveStreamsField(props: FieldProps) {
|
||||
[data, fieldPath, onChange],
|
||||
);
|
||||
|
||||
// Auto order commits after measuring, so edits made meanwhile must survive
|
||||
const dataRef = useRef(data);
|
||||
useEffect(() => {
|
||||
dataRef.current = data;
|
||||
}, [data]);
|
||||
|
||||
const [measurement, setMeasurement] = useState<{
|
||||
data: LiveStreamsData;
|
||||
transcode: LiveTranscodeConfig | undefined;
|
||||
rates: Record<string, StreamRate>;
|
||||
} | null>(null);
|
||||
const [measuring, setMeasuring] = useState(false);
|
||||
|
||||
// rates describe the streams as measured; a later edit hides them, while a
|
||||
// reorder alone keeps them since isEqual ignores key order
|
||||
const rates =
|
||||
measurement &&
|
||||
isEqual(measurement.data, data) &&
|
||||
isEqual(measurement.transcode, transcode)
|
||||
? measurement.rates
|
||||
: {};
|
||||
|
||||
const handleAutoOrder = useCallback(async () => {
|
||||
setMeasuring(true);
|
||||
|
||||
const measured = await Promise.all(
|
||||
entries.map(async ([, name]): Promise<[string, StreamRate]> => {
|
||||
const setRate = transcodeBitrateFor(camera, name, transcode);
|
||||
|
||||
if (setRate !== undefined) {
|
||||
return [name, { kbps: setRate, set: true }];
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`go2rtc/streams/${encodeURIComponent(name)}/bitrate`,
|
||||
);
|
||||
return [name, { kbps: response.data.kbps, set: false }];
|
||||
} catch {
|
||||
return [name, { failed: true }];
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
const next = Object.fromEntries(measured);
|
||||
const latest = dataRef.current;
|
||||
setMeasurement({ data: latest, transcode, rates: next });
|
||||
setMeasuring(false);
|
||||
|
||||
// stable sort, so ties and unmeasured rows keep their order; rows added
|
||||
// or renamed while measuring go last
|
||||
const sorted = [...entries]
|
||||
.sort(([, a], [, b]) => rateValue(next[b]) - rateValue(next[a]))
|
||||
.map(([key]) => key)
|
||||
.filter((key) => key in latest);
|
||||
const order = [
|
||||
...sorted,
|
||||
...Object.keys(latest).filter((key) => !sorted.includes(key)),
|
||||
];
|
||||
|
||||
if (!isEqual(order, Object.keys(latest))) {
|
||||
onChange(
|
||||
Object.fromEntries(order.map((key) => [key, latest[key]])),
|
||||
fieldPath,
|
||||
);
|
||||
}
|
||||
}, [camera, entries, fieldPath, onChange, transcode]);
|
||||
|
||||
const baseId = idSchema?.$id || "live_streams";
|
||||
const deleteLabel = t("button.delete", {
|
||||
ns: "common",
|
||||
defaultValue: "Delete",
|
||||
});
|
||||
const streamNameLabel = t("configForm.liveStreams.streamNameLabel", {
|
||||
ns: "views/settings",
|
||||
});
|
||||
const streamNamePlaceholder = t(
|
||||
"configForm.liveStreams.streamNamePlaceholder",
|
||||
{ ns: "views/settings" },
|
||||
);
|
||||
const go2rtcStreamLabel = t("configForm.liveStreams.go2rtcStreamLabel", {
|
||||
ns: "views/settings",
|
||||
});
|
||||
const addStreamLabel = t("configForm.liveStreams.addStream", {
|
||||
ns: "views/settings",
|
||||
});
|
||||
const order = dragOrder ?? keys;
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
@@ -278,57 +565,34 @@ export function LiveStreamsField(props: FieldProps) {
|
||||
)}
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3 p-4 pt-0">
|
||||
{entries.map(([key, value], entryIndex) => {
|
||||
const entryId = `${baseId}-${entryIndex}`;
|
||||
return (
|
||||
<div
|
||||
key={entryIndex}
|
||||
className="grid grid-cols-12 items-end gap-2 rounded-md border p-3"
|
||||
>
|
||||
<div className="col-span-12 space-y-2 md:col-span-5">
|
||||
<Label htmlFor={`${entryId}-key`}>{streamNameLabel}</Label>
|
||||
<MapKeyInput
|
||||
id={`${entryId}-key`}
|
||||
value={key}
|
||||
placeholder={streamNamePlaceholder}
|
||||
disabled={disabled || readonly}
|
||||
onCommit={(next) => handleRenameKey(key, next)}
|
||||
isKeyTaken={(next) =>
|
||||
next !== key &&
|
||||
Object.prototype.hasOwnProperty.call(data, next)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-10 space-y-2 md:col-span-6">
|
||||
<Label htmlFor={`${entryId}-value`}>{go2rtcStreamLabel}</Label>
|
||||
<StreamValueCombobox
|
||||
id={`${entryId}-value`}
|
||||
value={value}
|
||||
options={go2rtcStreamNames}
|
||||
disabled={disabled}
|
||||
readonly={readonly}
|
||||
onChange={(next) => handleUpdateValue(key, next)}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 flex justify-end md:col-span-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleRemoveEntry(key)}
|
||||
disabled={disabled || readonly}
|
||||
aria-label={deleteLabel}
|
||||
title={deleteLabel}
|
||||
className="shrink-0"
|
||||
>
|
||||
<LuTrash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<Reorder.Group
|
||||
as="div"
|
||||
axis="y"
|
||||
values={order}
|
||||
onReorder={handleReorder}
|
||||
className="space-y-3"
|
||||
>
|
||||
{order.map((key, entryIndex) => (
|
||||
<StreamRow
|
||||
key={rowIdFor(key)}
|
||||
entryKey={key}
|
||||
value={data[key] ?? ""}
|
||||
entryId={`${baseId}-${entryIndex}`}
|
||||
data={data}
|
||||
generated={isGenerated(data[key] ?? "")}
|
||||
rate={rates[data[key] ?? ""]}
|
||||
options={go2rtcStreamNames}
|
||||
disabled={disabled}
|
||||
readonly={readonly}
|
||||
onRename={handleRenameKey}
|
||||
onUpdateValue={handleUpdateValue}
|
||||
onRemove={handleRemoveEntry}
|
||||
onDragEnd={handleDragEnd}
|
||||
/>
|
||||
))}
|
||||
</Reorder.Group>
|
||||
|
||||
<div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
@@ -338,7 +602,25 @@ export function LiveStreamsField(props: FieldProps) {
|
||||
className="gap-2"
|
||||
>
|
||||
<LuPlus className="h-4 w-4" />
|
||||
{addStreamLabel}
|
||||
{tSettings("configForm.liveStreams.addStream")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleAutoOrder}
|
||||
disabled={disabled || readonly || measuring || entries.length < 2}
|
||||
title={tSettings("configForm.liveStreams.autoOrderTips")}
|
||||
className="gap-2"
|
||||
>
|
||||
{measuring ? (
|
||||
<ActivityIndicator className="size-4" />
|
||||
) : (
|
||||
<LuArrowDownWideNarrow className="h-4 w-4" />
|
||||
)}
|
||||
{measuring
|
||||
? tSettings("configForm.liveStreams.measuring")
|
||||
: tSettings("configForm.liveStreams.autoOrder")}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
import type { FieldPathList, FieldProps } from "@rjsf/utils";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import get from "lodash/get";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LuPlus, LuTrash2 } from "react-icons/lu";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import type { ConfigFormContext } from "@/types/configForm";
|
||||
import type {
|
||||
LiveTranscodeConfig,
|
||||
LiveTranscodeQuality,
|
||||
} from "@/types/frigateConfig";
|
||||
import {
|
||||
TRANSCODE_HEIGHTS,
|
||||
defaultTranscodeBitrate,
|
||||
reconcileTranscodeStreams,
|
||||
} from "@/utils/liveTranscode";
|
||||
|
||||
const EMPTY_TRANSCODE: LiveTranscodeConfig = {
|
||||
enabled: false,
|
||||
source: null,
|
||||
qualities: [],
|
||||
};
|
||||
|
||||
// presets plus a height set in yaml, minus heights other rows use
|
||||
function heightOptions(current: number, used: number[]): number[] {
|
||||
return [...new Set([...TRANSCODE_HEIGHTS, current])]
|
||||
.filter((height) => height === current || !used.includes(height))
|
||||
.sort((a, b) => b - a);
|
||||
}
|
||||
|
||||
export function LiveTranscodeField(props: FieldProps) {
|
||||
const { formData, onChange, idSchema, disabled, readonly } = props;
|
||||
const formContext = props.registry?.formContext as
|
||||
ConfigFormContext | undefined;
|
||||
const { t } = useTranslation(["views/settings"]);
|
||||
|
||||
const transcode =
|
||||
(formData as LiveTranscodeConfig | undefined) ?? EMPTY_TRANSCODE;
|
||||
|
||||
const emptyPath = useMemo(() => [] as FieldPathList, []);
|
||||
const fieldPath =
|
||||
(props as { fieldPathId?: { path?: FieldPathList } }).fieldPathId?.path ??
|
||||
emptyPath;
|
||||
|
||||
const camera = formContext?.cameraName ?? "";
|
||||
const streams = useMemo(
|
||||
() => (formContext?.formData?.streams ?? {}) as Record<string, string>,
|
||||
[formContext?.formData?.streams],
|
||||
);
|
||||
const go2rtcStreams = useMemo(
|
||||
() => Object.keys(formContext?.fullConfig?.go2rtc?.streams ?? {}),
|
||||
[formContext?.fullConfig?.go2rtc?.streams],
|
||||
);
|
||||
const sources = useMemo(
|
||||
() =>
|
||||
[...new Set(Object.values(streams))].filter((name) =>
|
||||
go2rtcStreams.includes(name),
|
||||
),
|
||||
[streams, go2rtcStreams],
|
||||
);
|
||||
|
||||
const savedSource = get(formContext?.baselineFormData, [
|
||||
...fieldPath,
|
||||
"source",
|
||||
]) as string | null | undefined;
|
||||
|
||||
const available = sources.length > 0;
|
||||
const locked = disabled || readonly || !available;
|
||||
const baseId = idSchema?.$id || "live_transcode";
|
||||
|
||||
// the stream list follows the transcode config in the same form change
|
||||
const update = useCallback(
|
||||
(next: LiveTranscodeConfig) => {
|
||||
onChange(next, fieldPath);
|
||||
onChange(
|
||||
reconcileTranscodeStreams(camera, streams, next, go2rtcStreams),
|
||||
[...fieldPath.slice(0, -1), "streams"],
|
||||
);
|
||||
},
|
||||
[camera, fieldPath, go2rtcStreams, onChange, streams],
|
||||
);
|
||||
|
||||
const updateQuality = useCallback(
|
||||
(index: number, quality: LiveTranscodeQuality) => {
|
||||
const qualities = [...transcode.qualities];
|
||||
qualities[index] = quality;
|
||||
update({ ...transcode, qualities });
|
||||
},
|
||||
[transcode, update],
|
||||
);
|
||||
|
||||
const addQuality = useCallback(() => {
|
||||
const used = new Set(transcode.qualities.map((q) => q.height));
|
||||
const height = TRANSCODE_HEIGHTS.find((h) => !used.has(h));
|
||||
|
||||
if (height === undefined) return;
|
||||
|
||||
update({
|
||||
...transcode,
|
||||
qualities: [
|
||||
...transcode.qualities,
|
||||
{ height, bitrate: defaultTranscodeBitrate(height) },
|
||||
],
|
||||
});
|
||||
}, [transcode, update]);
|
||||
|
||||
const removeQuality = useCallback(
|
||||
(index: number) =>
|
||||
update({
|
||||
...transcode,
|
||||
qualities: transcode.qualities.filter((_, i) => i !== index),
|
||||
}),
|
||||
[transcode, update],
|
||||
);
|
||||
|
||||
const usedHeights = transcode.qualities.map((q) => q.height);
|
||||
|
||||
return (
|
||||
<Card className="w-full">
|
||||
<CardHeader className="p-4">
|
||||
<CardTitle className="text-sm">
|
||||
{t("configForm.liveTranscode.title")}
|
||||
</CardTitle>
|
||||
<p className="mt-1 text-xs text-muted-foreground">
|
||||
{available
|
||||
? t("configForm.liveTranscode.description")
|
||||
: t("configForm.liveTranscode.unavailable")}
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4 p-4 pt-0">
|
||||
<div className="flex items-center gap-3">
|
||||
<Switch
|
||||
id={`${baseId}-enabled`}
|
||||
checked={transcode.enabled}
|
||||
disabled={locked}
|
||||
onCheckedChange={(enabled) =>
|
||||
update({
|
||||
...transcode,
|
||||
enabled,
|
||||
// pin the shown source so reordering streams can't change it;
|
||||
// turning off drops the pin
|
||||
source: enabled
|
||||
? (transcode.source ?? sources[0])
|
||||
: savedSource,
|
||||
})
|
||||
}
|
||||
/>
|
||||
<Label htmlFor={`${baseId}-enabled`}>
|
||||
{t("configForm.liveTranscode.enable")}
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{transcode.enabled && available && (
|
||||
<>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor={`${baseId}-source`}>
|
||||
{t("configForm.liveTranscode.source")}
|
||||
</Label>
|
||||
<Select
|
||||
value={transcode.source ?? sources[0]}
|
||||
disabled={locked}
|
||||
onValueChange={(source) => update({ ...transcode, source })}
|
||||
>
|
||||
<SelectTrigger id={`${baseId}-source`} className="w-full">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{sources.map((source) => (
|
||||
<SelectItem key={source} value={source}>
|
||||
{source}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{transcode.qualities.map((quality, index) => (
|
||||
<div
|
||||
key={quality.height}
|
||||
className="grid grid-cols-12 items-end gap-2 rounded-md border p-3"
|
||||
>
|
||||
<div className="col-span-5 space-y-2">
|
||||
<Label htmlFor={`${baseId}-${index}-height`}>
|
||||
{t("configForm.liveTranscode.height")}
|
||||
</Label>
|
||||
<Select
|
||||
value={String(quality.height)}
|
||||
disabled={locked}
|
||||
onValueChange={(value) =>
|
||||
updateQuality(index, {
|
||||
height: Number(value),
|
||||
bitrate: defaultTranscodeBitrate(Number(value)),
|
||||
})
|
||||
}
|
||||
>
|
||||
<SelectTrigger id={`${baseId}-${index}-height`}>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{heightOptions(quality.height, usedHeights).map(
|
||||
(height) => (
|
||||
<SelectItem key={height} value={String(height)}>
|
||||
{t("configForm.liveTranscode.heightOption", {
|
||||
height,
|
||||
})}
|
||||
</SelectItem>
|
||||
),
|
||||
)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="col-span-5 space-y-2">
|
||||
<Label htmlFor={`${baseId}-${index}-bitrate`}>
|
||||
{t("configForm.liveTranscode.bitrate")}
|
||||
</Label>
|
||||
<Input
|
||||
id={`${baseId}-${index}-bitrate`}
|
||||
type="number"
|
||||
min={64}
|
||||
value={quality.bitrate}
|
||||
disabled={locked}
|
||||
onChange={(e) => {
|
||||
// an empty input would save 0, which the backend rejects
|
||||
if (e.target.value === "") return;
|
||||
|
||||
updateQuality(index, {
|
||||
...quality,
|
||||
bitrate: Number(e.target.value),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="col-span-2 flex justify-end">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={locked}
|
||||
onClick={() => removeQuality(index)}
|
||||
aria-label={t("configForm.liveTranscode.removeQuality")}
|
||||
title={t("configForm.liveTranscode.removeQuality")}
|
||||
>
|
||||
<LuTrash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="gap-2"
|
||||
disabled={
|
||||
locked || usedHeights.length >= TRANSCODE_HEIGHTS.length
|
||||
}
|
||||
onClick={addQuality}
|
||||
>
|
||||
<LuPlus className="h-4 w-4" />
|
||||
{t("configForm.liveTranscode.addQuality")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
export default LiveTranscodeField;
|
||||
@@ -3,3 +3,4 @@ export { LayoutGridField } from "./LayoutGridField";
|
||||
export { ModelsField } from "./ModelsField";
|
||||
export { ReplaceRulesField } from "./ReplaceRulesField";
|
||||
export { LiveStreamsField } from "./LiveStreamsField";
|
||||
export { LiveTranscodeField } from "./LiveTranscodeField";
|
||||
|
||||
@@ -57,6 +57,7 @@ import { CameraInputsField } from "./fields/CameraInputsField";
|
||||
import { DictAsYamlField } from "./fields/DictAsYamlField";
|
||||
import { KnownPlatesField } from "./fields/KnownPlatesField";
|
||||
import { LiveStreamsField } from "./fields/LiveStreamsField";
|
||||
import { LiveTranscodeField } from "./fields/LiveTranscodeField";
|
||||
|
||||
export interface FrigateTheme {
|
||||
widgets: RegistryWidgetsType;
|
||||
@@ -121,5 +122,6 @@ export const frigateTheme: FrigateTheme = {
|
||||
DictAsYamlField: DictAsYamlField,
|
||||
KnownPlatesField: KnownPlatesField,
|
||||
LiveStreamsField: LiveStreamsField,
|
||||
LiveTranscodeField: LiveTranscodeField,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -19,8 +19,6 @@ import type {
|
||||
|
||||
// go2rtc bursts its GOP cache when a consumer attaches
|
||||
const WARMUP_MS = 3000;
|
||||
// bytes this recent mean a stall is congestion rather than a dead source
|
||||
const BYTES_RECENT_MS = 2000;
|
||||
// media per wall second below this is a low sample. Low samples reset
|
||||
// the upswitch clock and feed the chronic window
|
||||
const LOW_RATE = 0.85;
|
||||
@@ -63,7 +61,6 @@ export class LiveStreamGovernor {
|
||||
|
||||
private rungStartTs: number;
|
||||
private cleanSinceTs: number;
|
||||
private lastBytesTs = Number.NEGATIVE_INFINITY;
|
||||
// every sample, signed, for the sustained window
|
||||
private shortfalls: Shortfall[] = [];
|
||||
// low samples only, for the chronic window
|
||||
@@ -99,7 +96,6 @@ export class LiveStreamGovernor {
|
||||
}
|
||||
|
||||
const now = this.now();
|
||||
this.lastBytesTs = now;
|
||||
|
||||
if (now - this.rungStartTs < WARMUP_MS) {
|
||||
return;
|
||||
@@ -133,7 +129,7 @@ export class LiveStreamGovernor {
|
||||
* A player error. Returns true when auto handled it by stepping down,
|
||||
* false to hand it to the error fallback.
|
||||
*/
|
||||
playerError(error: LivePlayerError): boolean {
|
||||
playerError(error: LivePlayerError, sourceOnline: boolean): boolean {
|
||||
const { rung } = this.snapshot;
|
||||
if (rung === this.floor) {
|
||||
return false;
|
||||
@@ -150,9 +146,9 @@ export class LiveStreamGovernor {
|
||||
return this.stepDown();
|
||||
}
|
||||
|
||||
// without recent bytes the source is dead rather than congested,
|
||||
// and a lower stream from the same camera would fail the same way
|
||||
if (this.now() - this.lastBytesTs > BYTES_RECENT_MS) {
|
||||
// an offline camera fails every stream alike; a stall on a live camera
|
||||
// is the viewer's link, even when congestion stops delivery outright
|
||||
if (!sourceOnline) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -204,7 +200,6 @@ export class LiveStreamGovernor {
|
||||
const now = this.now();
|
||||
this.rungStartTs = now;
|
||||
this.cleanSinceTs = now;
|
||||
this.lastBytesTs = Number.NEGATIVE_INFINITY;
|
||||
this.shortfalls = [];
|
||||
this.deficits = [];
|
||||
}
|
||||
|
||||
@@ -10,6 +10,8 @@ import { LiveAutoReason } from "@/types/live";
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { LuInfo } from "react-icons/lu";
|
||||
import { MdOutlineRestartAlt } from "react-icons/md";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
// Radix Select needs a non-empty value. Auto itself is stored as the
|
||||
// absence of a pinned stream
|
||||
@@ -24,6 +26,8 @@ type LiveStreamSelectProps = {
|
||||
autoReason?: LiveAutoReason;
|
||||
// undefined selects auto
|
||||
onSelect: (stream: string | undefined) => void;
|
||||
// sends auto back to the top of the ladder
|
||||
onRetry: () => void;
|
||||
disabled: boolean;
|
||||
};
|
||||
|
||||
@@ -34,6 +38,7 @@ export default function LiveStreamSelect({
|
||||
autoAvailable,
|
||||
autoReason,
|
||||
onSelect,
|
||||
onRetry,
|
||||
disabled,
|
||||
}: LiveStreamSelectProps) {
|
||||
const { t } = useTranslation(["views/live"]);
|
||||
@@ -91,13 +96,31 @@ export default function LiveStreamSelect({
|
||||
</Select>
|
||||
|
||||
{auto && autoReason && !disabled && (
|
||||
<div className="flex flex-row items-center gap-1 text-sm text-muted-foreground">
|
||||
<LuInfo className="size-4 shrink-0" />
|
||||
<div>
|
||||
{t(`stream.auto.reason.${autoReason}`, {
|
||||
stream: labelFor(playingStream),
|
||||
})}
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="flex flex-row items-center gap-1 text-sm text-muted-foreground">
|
||||
<LuInfo className="size-4 shrink-0" />
|
||||
<div>
|
||||
{t(`stream.auto.reason.${autoReason}`, {
|
||||
stream: labelFor(playingStream),
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* data saver pins the lowest stream, so there is no higher one to try */}
|
||||
{autoReason !== "saveData" && (
|
||||
<Button
|
||||
className="flex items-center gap-2.5 rounded-lg"
|
||||
aria-label={t("stream.auto.retry")}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onRetry}
|
||||
>
|
||||
<MdOutlineRestartAlt className="size-5 text-primary-variant" />
|
||||
<div className="text-primary-variant">
|
||||
{t("stream.auto.retry")}
|
||||
</div>
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -35,6 +35,7 @@ import { Trans, useTranslation } from "react-i18next";
|
||||
import { useDocDomain } from "@/hooks/use-doc-domain";
|
||||
import { useCameraFriendlyName } from "@/hooks/use-camera-friendly-name";
|
||||
import { detectCameraAudioFeatures } from "@/utils/cameraUtil";
|
||||
import { isRestreamedStream } from "@/utils/liveTranscode";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { useWebRTCAvailableForStream } from "@/hooks/use-webrtc-availability";
|
||||
import StreamTechnologySelect from "@/components/player/StreamTechnologySelect";
|
||||
@@ -82,9 +83,7 @@ export function CameraStreamingDialog({
|
||||
// metadata
|
||||
|
||||
const isRestreamed = useMemo(
|
||||
() =>
|
||||
config &&
|
||||
Object.keys(config.go2rtc.streams || {}).includes(streamName ?? ""),
|
||||
() => isRestreamedStream(config, streamName),
|
||||
[config, streamName],
|
||||
);
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { LiveStreamGovernor } from "@/components/player/LiveStreamGovernor";
|
||||
import { isCameraOffline } from "@/hooks/use-camera-activity";
|
||||
import { useAutoFrigateStats } from "@/hooks/use-stats";
|
||||
import {
|
||||
LiveAutoReason,
|
||||
LiveHealthSample,
|
||||
@@ -57,6 +59,9 @@ export function useAutoLiveStream({
|
||||
);
|
||||
const active = selected && !paused;
|
||||
|
||||
const stats = useAutoFrigateStats();
|
||||
const offline = isCameraOffline(stats, cameraName);
|
||||
|
||||
// evidence from before a pin, a pause, or a remount does not count
|
||||
useEffect(() => {
|
||||
if (active) {
|
||||
@@ -102,8 +107,8 @@ export function useAutoLiveStream({
|
||||
);
|
||||
|
||||
const handleError = useCallback(
|
||||
(error: LivePlayerError) => active && governor.playerError(error),
|
||||
[active, governor],
|
||||
(error: LivePlayerError) => active && governor.playerError(error, !offline),
|
||||
[active, governor, offline],
|
||||
);
|
||||
|
||||
const reset = useCallback(() => governor.reset(), [governor]);
|
||||
|
||||
@@ -13,6 +13,7 @@ import { useTimelineUtils } from "./use-timeline-utils";
|
||||
import useDeepMemo from "./use-deep-memo";
|
||||
import { isEqual } from "lodash";
|
||||
import { useAutoFrigateStats } from "./use-stats";
|
||||
import { FrigateStats } from "@/types/stats";
|
||||
import useSWR from "swr";
|
||||
import { getAttributeLabels } from "@/utils/iconUtil";
|
||||
|
||||
@@ -30,6 +31,19 @@ type useCameraActivityReturn = {
|
||||
offline: boolean;
|
||||
};
|
||||
|
||||
export function isCameraOffline(
|
||||
stats: FrigateStats | undefined,
|
||||
cameraName: string | undefined,
|
||||
): boolean {
|
||||
if (!stats?.cameras || !cameraName) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
stats.cameras[cameraName]?.camera_fps == 0 && stats.service.uptime > 60
|
||||
);
|
||||
}
|
||||
|
||||
export function useCameraActivity(
|
||||
camera: CameraConfig | undefined,
|
||||
revalidateOnFocus: boolean = true,
|
||||
@@ -167,25 +181,10 @@ export function useCameraActivity(
|
||||
|
||||
const stats = useAutoFrigateStats();
|
||||
|
||||
const offline = useMemo(() => {
|
||||
if (!stats) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const cameras = stats["cameras"];
|
||||
|
||||
if (!cameras) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!camera?.name) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (
|
||||
cameras[camera.name]?.camera_fps == 0 && stats["service"].uptime > 60
|
||||
);
|
||||
}, [camera, stats]);
|
||||
const offline = useMemo(
|
||||
() => isCameraOffline(stats, camera?.name),
|
||||
[camera, stats],
|
||||
);
|
||||
|
||||
const isCameraEnabled = cameraEnabled ? cameraEnabled === "ON" : true;
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import useSWR from "swr";
|
||||
import { LivePlayerMode } from "@/types/live";
|
||||
import useDeferredStreamMetadata from "./use-deferred-stream-metadata";
|
||||
import { detectCameraAudioFeatures } from "@/utils/cameraUtil";
|
||||
import { isRestreamedStream } from "@/utils/liveTranscode";
|
||||
import {
|
||||
evaluateStreamWebRTCAvailability,
|
||||
useWebRTCGloballyAvailable,
|
||||
@@ -51,18 +52,14 @@ export default function useCameraLiveMode(
|
||||
cameras.forEach((camera) => {
|
||||
if (activeStreams && activeStreams[camera.name]) {
|
||||
const selectedStreamName = activeStreams[camera.name];
|
||||
const isRestreamed = Object.keys(config.go2rtc.streams || {}).includes(
|
||||
selectedStreamName,
|
||||
);
|
||||
const isRestreamed = isRestreamedStream(config, selectedStreamName);
|
||||
|
||||
if (isRestreamed) {
|
||||
streamNames.add(selectedStreamName);
|
||||
}
|
||||
} else {
|
||||
Object.values(camera.live.streams).forEach((streamName) => {
|
||||
const isRestreamed = Object.keys(
|
||||
config.go2rtc.streams || {},
|
||||
).includes(streamName);
|
||||
const isRestreamed = isRestreamedStream(config, streamName);
|
||||
|
||||
if (isRestreamed) {
|
||||
streamNames.add(streamName);
|
||||
@@ -125,9 +122,7 @@ export default function useCameraLiveMode(
|
||||
cameras.forEach((camera) => {
|
||||
const selectedStreamName =
|
||||
activeStreams?.[camera.name] ?? Object.values(camera.live.streams)[0];
|
||||
const isRestreamed =
|
||||
config &&
|
||||
Object.keys(config.go2rtc.streams || {}).includes(selectedStreamName);
|
||||
const isRestreamed = isRestreamedStream(config, selectedStreamName);
|
||||
|
||||
newIsRestreamedStates[camera.name] = isRestreamed ?? false;
|
||||
|
||||
@@ -181,9 +176,7 @@ export default function useCameraLiveMode(
|
||||
(cameraConfig
|
||||
? Object.values(cameraConfig.live.streams)[0]
|
||||
: cameraName);
|
||||
const isRestreamed =
|
||||
config &&
|
||||
Object.keys(config.go2rtc.streams || {}).includes(selectedStreamName);
|
||||
const isRestreamed = isRestreamedStream(config, selectedStreamName);
|
||||
|
||||
setPreferredLiveModes((prevModes) => ({
|
||||
...prevModes,
|
||||
|
||||
@@ -39,6 +39,8 @@ export type ConfigFormContext = {
|
||||
extraHasChanges?: boolean;
|
||||
setExtraHasChanges?: (hasChanges: boolean) => void;
|
||||
formData?: JsonObject;
|
||||
/** Key order of each ordered map, so reorders re-render fields */
|
||||
orderedMapsKeyOrder?: string[][];
|
||||
pendingDataBySection?: Record<string, ConfigSectionData>;
|
||||
onPendingDataChange?: (
|
||||
sectionKey: string,
|
||||
|
||||
@@ -36,6 +36,17 @@ export interface FaceRecognitionConfig {
|
||||
export type SearchModel = "jinav1" | "jinav2" | (string & NonNullable<unknown>);
|
||||
export type SearchModelSize = "small" | "large";
|
||||
|
||||
export type LiveTranscodeQuality = {
|
||||
height: number;
|
||||
bitrate: number;
|
||||
};
|
||||
|
||||
export type LiveTranscodeConfig = {
|
||||
enabled: boolean;
|
||||
source?: string | null;
|
||||
qualities: LiveTranscodeQuality[];
|
||||
};
|
||||
|
||||
export interface CameraConfig {
|
||||
friendly_name: string;
|
||||
audio: {
|
||||
@@ -109,6 +120,7 @@ export interface CameraConfig {
|
||||
height: number;
|
||||
quality: number;
|
||||
streams: { [key: string]: string };
|
||||
transcode: LiveTranscodeConfig;
|
||||
};
|
||||
lpr: {
|
||||
enabled: boolean;
|
||||
|
||||
@@ -306,6 +306,49 @@ export function buildOverrides(
|
||||
return current;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Ordered maps: config maps whose key order is meaningful
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// lodash isEqual ignores key order, so ordered maps compare entry lists.
|
||||
export function changedOrderedMapPaths(
|
||||
current: unknown,
|
||||
base: unknown,
|
||||
paths: string[],
|
||||
): string[] {
|
||||
return paths.filter((path) => {
|
||||
const value = get(current, path);
|
||||
|
||||
if (!isJsonObject(value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const baseValue = get(base, path);
|
||||
return !isEqual(
|
||||
Object.entries(value),
|
||||
isJsonObject(baseValue) ? Object.entries(baseValue) : undefined,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// Send a changed ordered map whole; per-key overrides cannot carry order.
|
||||
export function applyOrderedMaps(
|
||||
overrides: unknown,
|
||||
current: unknown,
|
||||
base: unknown,
|
||||
paths: string[],
|
||||
): unknown {
|
||||
const changed = changedOrderedMapPaths(current, base, paths);
|
||||
|
||||
if (changed.length === 0) {
|
||||
return overrides;
|
||||
}
|
||||
|
||||
const result = isJsonObject(overrides) ? cloneDeep(overrides) : {};
|
||||
changed.forEach((path) => set(result, path, cloneDeep(get(current, path))));
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// flattenOverrides — turn an overrides object into a list of leaf paths
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { FrigateConfig, LiveTranscodeConfig } from "@/types/frigateConfig";
|
||||
|
||||
// Mirrors frigate/util/live_streams.py and apply_live_transcode_streams.
|
||||
|
||||
export const TRANSCODE_HEIGHTS = [1080, 720, 480, 360, 240];
|
||||
|
||||
const DEFAULT_BITRATES: Record<number, number> = {
|
||||
1080: 2500,
|
||||
720: 1200,
|
||||
480: 500,
|
||||
360: 250,
|
||||
240: 150,
|
||||
};
|
||||
|
||||
export function defaultTranscodeBitrate(height: number): number {
|
||||
return DEFAULT_BITRATES[height] ?? 500;
|
||||
}
|
||||
|
||||
export function transcodeStreamName(camera: string, height: number): string {
|
||||
return `${camera}_transcode_${height}p`;
|
||||
}
|
||||
|
||||
export function isTranscodeStreamName(camera: string, name: string): boolean {
|
||||
const prefix = `${camera}_transcode_`;
|
||||
return name.startsWith(prefix) && /^\d+p$/.test(name.slice(prefix.length));
|
||||
}
|
||||
|
||||
/** A generated stream's configured bitrate, or undefined for other streams. */
|
||||
export function transcodeBitrateFor(
|
||||
camera: string,
|
||||
name: string,
|
||||
transcode: LiveTranscodeConfig | undefined,
|
||||
): number | undefined {
|
||||
if (!transcode?.enabled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return transcode.qualities.find(
|
||||
(quality) => transcodeStreamName(camera, quality.height) === name,
|
||||
)?.bitrate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop transcoded entries that are no longer generated and append generated
|
||||
* streams that are missing. Placed entries keep their position and label.
|
||||
*/
|
||||
export function reconcileTranscodeStreams(
|
||||
camera: string,
|
||||
streams: Record<string, string>,
|
||||
transcode: LiveTranscodeConfig,
|
||||
go2rtcStreams: string[],
|
||||
): Record<string, string> {
|
||||
const generated = transcode.enabled
|
||||
? transcode.qualities.map((quality) => ({
|
||||
label: `${quality.height}p`,
|
||||
name: transcodeStreamName(camera, quality.height),
|
||||
}))
|
||||
: [];
|
||||
const generatedNames = new Set(generated.map(({ name }) => name));
|
||||
|
||||
const kept = Object.entries(streams).filter(
|
||||
([, name]) =>
|
||||
generatedNames.has(name) ||
|
||||
go2rtcStreams.includes(name) ||
|
||||
!isTranscodeStreamName(camera, name),
|
||||
);
|
||||
const placed = new Set(kept.map(([, name]) => name));
|
||||
const labels = new Set(kept.map(([label]) => label));
|
||||
|
||||
generated.forEach(({ label, name }) => {
|
||||
// a taken label is left for the backend to reject on save
|
||||
if (!placed.has(name) && !labels.has(label)) {
|
||||
kept.push([label, name]);
|
||||
}
|
||||
});
|
||||
|
||||
return Object.fromEntries(kept);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether go2rtc serves a live stream. config.go2rtc.streams lists only the
|
||||
* yaml streams, so transcoded streams of enabled cameras count too.
|
||||
*/
|
||||
export function isRestreamedStream(
|
||||
config: FrigateConfig | undefined,
|
||||
name: string | undefined,
|
||||
): boolean {
|
||||
if (!config || !name) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (Object.keys(config.go2rtc.streams || {}).includes(name)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return Object.values(config.cameras).some(
|
||||
(camera) =>
|
||||
camera.live.transcode?.enabled &&
|
||||
isTranscodeStreamName(camera.name, name),
|
||||
);
|
||||
}
|
||||
@@ -105,6 +105,7 @@ import { useIsAdmin } from "@/hooks/use-is-admin";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDocDomain } from "@/hooks/use-doc-domain";
|
||||
import { detectCameraAudioFeatures } from "@/utils/cameraUtil";
|
||||
import { isRestreamedStream } from "@/utils/liveTranscode";
|
||||
import PtzControlPanel from "@/components/overlay/PtzControlPanel";
|
||||
import ObjectSettingsView from "../settings/ObjectSettingsView";
|
||||
import { useSearchEffect } from "@/hooks/use-overlay-state";
|
||||
@@ -215,9 +216,7 @@ export default function LiveCameraView({
|
||||
);
|
||||
|
||||
const isRestreamed = useMemo(
|
||||
() =>
|
||||
config &&
|
||||
Object.keys(config.go2rtc.streams || {}).includes(streamName ?? ""),
|
||||
() => isRestreamedStream(config, streamName),
|
||||
[config, streamName],
|
||||
);
|
||||
|
||||
@@ -1416,6 +1415,7 @@ function FrigateCameraFeatures({
|
||||
autoAvailable={autoAvailable}
|
||||
autoReason={autoReason}
|
||||
onSelect={onSelectStream}
|
||||
onRetry={onResetStream}
|
||||
disabled={debug || forceLowBandwidth}
|
||||
/>
|
||||
|
||||
@@ -1807,6 +1807,7 @@ function FrigateCameraFeatures({
|
||||
autoAvailable={autoAvailable}
|
||||
autoReason={autoReason}
|
||||
onSelect={onSelectStream}
|
||||
onRetry={onResetStream}
|
||||
disabled={debug || forceLowBandwidth}
|
||||
/>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user