mirror of
https://github.com/blakeblackshear/frigate.git
synced 2026-11-25 06:47:07 +03:00
Add Auto live view option with transcoding options (#24519)
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
CI / AMD64 Build (push) Canceled after 0s
CI / AMD64 Smoke Test (push) Canceled after 0s
CI / ARM Build (push) Canceled after 0s
CI / Jetson Jetpack 6 (push) Canceled after 0s
CI / AMD64 Extra Build (push) Canceled after 0s
CI / ARM Extra Build (push) Canceled after 0s
CI / Synaptics Build (push) Canceled after 0s
CI / Assemble and push default build (push) Canceled after 0s
* implement auto mode for single camera live view
* 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.
* fixes
This commit is contained in:
@@ -10,6 +10,7 @@ import { MdCircle } from "react-icons/md";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "../ui/tooltip";
|
||||
import { useCameraActivity } from "@/hooks/use-camera-activity";
|
||||
import {
|
||||
LiveHealthSample,
|
||||
LivePlayerError,
|
||||
TwoWayTalkError,
|
||||
LivePlayerMode,
|
||||
@@ -52,6 +53,8 @@ type LivePlayerProps = {
|
||||
onClick?: () => void;
|
||||
setFullResolution?: React.Dispatch<React.SetStateAction<VideoResolutionType>>;
|
||||
onError?: (error: LivePlayerError) => void;
|
||||
onHealthSample?: (sample: LiveHealthSample) => void;
|
||||
streamAuto?: boolean;
|
||||
onMicrophoneError?: (error: TwoWayTalkError) => void;
|
||||
onResetLiveMode?: () => void;
|
||||
onLiveAspectChange?: (aspectRatio: number | undefined) => void;
|
||||
@@ -79,6 +82,8 @@ export default function LivePlayer({
|
||||
onClick,
|
||||
setFullResolution,
|
||||
onError,
|
||||
onHealthSample,
|
||||
streamAuto = false,
|
||||
onMicrophoneError,
|
||||
onResetLiveMode,
|
||||
onLiveAspectChange,
|
||||
@@ -109,6 +114,14 @@ export default function LivePlayer({
|
||||
droppedFrameRate: 0, // percentage
|
||||
});
|
||||
|
||||
const streamLabel = useMemo(
|
||||
() =>
|
||||
Object.keys(cameraConfig.live.streams).find(
|
||||
(label) => cameraConfig.live.streams[label] === streamName,
|
||||
),
|
||||
[cameraConfig.live.streams, streamName],
|
||||
);
|
||||
|
||||
// camera activity
|
||||
|
||||
const {
|
||||
@@ -230,21 +243,17 @@ export default function LivePlayer({
|
||||
}, [preferredLiveMode]);
|
||||
|
||||
const [key, setKey] = useState(0);
|
||||
const prevStreamNameRef = useRef(streamName);
|
||||
|
||||
const resetPlayer = () => {
|
||||
setLiveReady(false);
|
||||
setKey((prevKey) => prevKey + 1);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (prevStreamNameRef.current !== streamName) {
|
||||
prevStreamNameRef.current = streamName;
|
||||
if (streamName) {
|
||||
resetPlayer();
|
||||
}
|
||||
// the stream is part of the MSE and WebRTC keys, so a stream change
|
||||
// remounts them in the same render and the new player is hidden until it
|
||||
// plays. jsmpeg plays the camera, not the stream, and keeps playing
|
||||
const [renderedStream, setRenderedStream] = useState(streamName);
|
||||
if (renderedStream !== streamName) {
|
||||
setRenderedStream(streamName);
|
||||
if (preferredLiveMode !== "jsmpeg") {
|
||||
setLiveReady(false);
|
||||
}
|
||||
}, [streamName]);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (showStillWithoutActivity && !autoLive) {
|
||||
@@ -294,7 +303,7 @@ export default function LivePlayer({
|
||||
} else if (preferredLiveMode == "webrtc") {
|
||||
player = (
|
||||
<WebRtcPlayer
|
||||
key={"webrtc_" + key}
|
||||
key={`webrtc_${streamName}_${key}`}
|
||||
className={`size-full ${liveReady ? "" : "hidden"}`}
|
||||
camera={streamName}
|
||||
playbackEnabled={cameraActive || liveReady}
|
||||
@@ -308,6 +317,7 @@ export default function LivePlayer({
|
||||
onPlaying={playerIsPlaying}
|
||||
pip={pip}
|
||||
onError={onError}
|
||||
onHealthSample={onHealthSample}
|
||||
onMicrophoneError={onMicrophoneError}
|
||||
/>
|
||||
);
|
||||
@@ -315,7 +325,7 @@ export default function LivePlayer({
|
||||
if ("MediaSource" in window || "ManagedMediaSource" in window) {
|
||||
player = (
|
||||
<MSEPlayer
|
||||
key={"mse_" + key}
|
||||
key={`mse_${streamName}_${key}`}
|
||||
className={`size-full ${liveReady ? "" : "hidden"}`}
|
||||
camera={streamName}
|
||||
playbackEnabled={cameraActive || liveReady}
|
||||
@@ -328,6 +338,7 @@ export default function LivePlayer({
|
||||
pip={pip}
|
||||
setFullResolution={handleFullResolution}
|
||||
onError={onError}
|
||||
onHealthSample={onHealthSample}
|
||||
/>
|
||||
);
|
||||
} else {
|
||||
@@ -561,7 +572,12 @@ export default function LivePlayer({
|
||||
)}
|
||||
</div>
|
||||
{showStats && (
|
||||
<PlayerStats stats={stats} minimal={cameraRef !== undefined} />
|
||||
<PlayerStats
|
||||
stats={stats}
|
||||
minimal={cameraRef !== undefined}
|
||||
streamLabel={preferredLiveMode === "jsmpeg" ? undefined : streamLabel}
|
||||
streamAuto={streamAuto}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
/**
|
||||
* Policy engine for auto live stream selection.
|
||||
*
|
||||
* Rungs index the camera's live streams in config order, followed by
|
||||
* the jsmpeg floor. Evidence is media delivery falling behind wall
|
||||
* time while bytes still arrive, which separates congestion from a
|
||||
* dead camera or a go2rtc restart. No browser API reports spare
|
||||
* bandwidth, so upswitching is try-and-see with backoff.
|
||||
*
|
||||
* Time comes from an injected clock and the owner calls tick() once a
|
||||
* second, so the class holds no timers.
|
||||
*/
|
||||
|
||||
import type {
|
||||
LiveAutoReason,
|
||||
LiveHealthSample,
|
||||
LivePlayerError,
|
||||
} from "@/types/live";
|
||||
|
||||
// go2rtc bursts its GOP cache when a consumer attaches
|
||||
const WARMUP_MS = 3000;
|
||||
// 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;
|
||||
// net shortfall within the window that downswitches on sustained
|
||||
// under-delivery. Keyframes make per-second delivery bursty, so the
|
||||
// window lets a fast second offset a slow one
|
||||
const SUSTAINED_DEFICIT_S = 2;
|
||||
const SUSTAINED_WINDOW_MS = 10000;
|
||||
// low-sample deficit within the window that downswitches on repeated
|
||||
// short stalls
|
||||
const CHRONIC_DEFICIT_S = 6;
|
||||
const CHRONIC_WINDOW_MS = 60000;
|
||||
// clean time before trying one rung up, doubled after each failed try
|
||||
const UPSWITCH_WAIT_MS = 60000;
|
||||
const UPSWITCH_WAIT_MAX_MS = 600000;
|
||||
// a downswitch this soon after an upswitch counts as a failed try
|
||||
const PROBATION_MS = 30000;
|
||||
|
||||
export type LiveGovernorSnapshot = {
|
||||
rung: number;
|
||||
reason: LiveAutoReason | undefined;
|
||||
};
|
||||
|
||||
type Shortfall = {
|
||||
ts: number;
|
||||
seconds: number;
|
||||
};
|
||||
|
||||
const total = (entries: Shortfall[]) =>
|
||||
entries.reduce((sum, entry) => sum + entry.seconds, 0);
|
||||
|
||||
export class LiveStreamGovernor {
|
||||
private readonly floor: number;
|
||||
private readonly now: () => number;
|
||||
private readonly listeners = new Set<() => void>();
|
||||
private readonly unplayable = new Set<number>();
|
||||
|
||||
private snapshot: LiveGovernorSnapshot = { rung: 0, reason: undefined };
|
||||
private holdLow = false;
|
||||
|
||||
private rungStartTs: number;
|
||||
private cleanSinceTs: number;
|
||||
// every sample, signed, for the sustained window
|
||||
private shortfalls: Shortfall[] = [];
|
||||
// low samples only, for the chronic window
|
||||
private deficits: Shortfall[] = [];
|
||||
private upswitchWaitMs = UPSWITCH_WAIT_MS;
|
||||
private probationUntil = 0;
|
||||
|
||||
/** rungCount includes the jsmpeg floor. */
|
||||
constructor(rungCount: number, now: () => number = Date.now) {
|
||||
this.floor = rungCount - 1;
|
||||
this.now = now;
|
||||
this.rungStartTs = now();
|
||||
this.cleanSinceTs = this.rungStartTs;
|
||||
}
|
||||
|
||||
subscribe = (listener: () => void) => {
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
};
|
||||
|
||||
getSnapshot = (): LiveGovernorSnapshot => this.snapshot;
|
||||
|
||||
/**
|
||||
* One health sample from the playing transport. Zero-byte samples
|
||||
* belong to the stall watchdog, and warmup samples only prove that
|
||||
* bytes are arriving.
|
||||
*/
|
||||
sample({ bytes, mediaSeconds, wallSeconds }: LiveHealthSample) {
|
||||
if (bytes <= 0 || wallSeconds <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = this.now();
|
||||
|
||||
if (now - this.rungStartTs < WARMUP_MS) {
|
||||
return;
|
||||
}
|
||||
|
||||
// WebRTC reports a finished freeze in one sample, so media can be
|
||||
// negative and one sample can carry more shortfall than its wall time
|
||||
const shortfall = { ts: now, seconds: wallSeconds - mediaSeconds };
|
||||
this.shortfalls.push(shortfall);
|
||||
if (mediaSeconds / wallSeconds < LOW_RATE) {
|
||||
this.cleanSinceTs = now;
|
||||
this.deficits.push(shortfall);
|
||||
}
|
||||
|
||||
this.shortfalls = this.shortfalls.filter(
|
||||
(entry) => entry.ts > now - SUSTAINED_WINDOW_MS,
|
||||
);
|
||||
this.deficits = this.deficits.filter(
|
||||
(entry) => entry.ts > now - CHRONIC_WINDOW_MS,
|
||||
);
|
||||
|
||||
if (
|
||||
total(this.shortfalls) >= SUSTAINED_DEFICIT_S ||
|
||||
total(this.deficits) >= CHRONIC_DEFICIT_S
|
||||
) {
|
||||
this.stepDown();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A player error. Returns true when auto handled it by stepping down,
|
||||
* false to hand it to the error fallback.
|
||||
*/
|
||||
playerError(error: LivePlayerError, sourceOnline: boolean): boolean {
|
||||
const { rung } = this.snapshot;
|
||||
if (rung === this.floor) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// go2rtc's codec reply is proof, so the rung is not retried this session
|
||||
if (error === "mse-codec") {
|
||||
this.unplayable.add(rung);
|
||||
return this.stepDown();
|
||||
}
|
||||
|
||||
// the rung below played a moment ago, so a failed upswitch returns to it
|
||||
if (this.now() < this.probationUntil) {
|
||||
return this.stepDown();
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
return this.stepDown();
|
||||
}
|
||||
|
||||
/** Called once a second while auto is active and the page is visible. */
|
||||
tick() {
|
||||
const now = this.now();
|
||||
|
||||
// the higher rung survived probation, so backoff starts over
|
||||
if (this.probationUntil > 0 && now >= this.probationUntil) {
|
||||
this.probationUntil = 0;
|
||||
this.upswitchWaitMs = UPSWITCH_WAIT_MS;
|
||||
}
|
||||
|
||||
if (now - this.cleanSinceTs < this.upswitchWaitMs) {
|
||||
return;
|
||||
}
|
||||
|
||||
// data saver may climb out of the floor, but never past its stream
|
||||
const target = this.nextPlayableAbove(this.snapshot.rung);
|
||||
if (
|
||||
target === undefined ||
|
||||
(this.holdLow && target < this.lowestPlayable())
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.probationUntil = now + PROBATION_MS;
|
||||
this.moveTo(target);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data saver holds the lowest playable stream and never upswitches past
|
||||
* it, whatever the connection could carry.
|
||||
*/
|
||||
setHoldLow(hold: boolean) {
|
||||
this.holdLow = hold;
|
||||
this.moveTo(
|
||||
hold
|
||||
? Math.max(this.snapshot.rung, this.lowestPlayable())
|
||||
: this.snapshot.rung,
|
||||
);
|
||||
}
|
||||
|
||||
/** A remount or unpause on the same rung starts with clean evidence. */
|
||||
resetHistory() {
|
||||
const now = this.now();
|
||||
this.rungStartTs = now;
|
||||
this.cleanSinceTs = now;
|
||||
this.shortfalls = [];
|
||||
this.deficits = [];
|
||||
}
|
||||
|
||||
/** Returns to the top rung and clears every session fact. */
|
||||
reset() {
|
||||
this.unplayable.clear();
|
||||
this.upswitchWaitMs = UPSWITCH_WAIT_MS;
|
||||
this.probationUntil = 0;
|
||||
this.moveTo(this.holdLow ? this.lowestPlayable() : 0);
|
||||
}
|
||||
|
||||
private stepDown(): boolean {
|
||||
const target = this.nextPlayableBelow(this.snapshot.rung);
|
||||
if (target === undefined) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (this.now() < this.probationUntil) {
|
||||
this.upswitchWaitMs = Math.min(
|
||||
this.upswitchWaitMs * 2,
|
||||
UPSWITCH_WAIT_MAX_MS,
|
||||
);
|
||||
}
|
||||
this.probationUntil = 0;
|
||||
|
||||
this.moveTo(target);
|
||||
return true;
|
||||
}
|
||||
|
||||
private moveTo(rung: number) {
|
||||
this.resetHistory();
|
||||
|
||||
const reason = this.reasonAt(rung);
|
||||
if (rung === this.snapshot.rung && reason === this.snapshot.reason) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.snapshot = { rung, reason };
|
||||
this.listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
private reasonAt(rung: number): LiveAutoReason | undefined {
|
||||
if (rung === this.floor) {
|
||||
return "floor";
|
||||
}
|
||||
|
||||
if (this.nextPlayableAbove(rung) === undefined) {
|
||||
return [...this.unplayable].some((unplayable) => unplayable < rung)
|
||||
? "codec"
|
||||
: undefined;
|
||||
}
|
||||
|
||||
return this.holdLow ? "saveData" : "bandwidth";
|
||||
}
|
||||
|
||||
private nextPlayableAbove(rung: number): number | undefined {
|
||||
for (let candidate = rung - 1; candidate >= 0; candidate--) {
|
||||
if (!this.unplayable.has(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// the floor is always playable
|
||||
private nextPlayableBelow(rung: number): number | undefined {
|
||||
for (let candidate = rung + 1; candidate <= this.floor; candidate++) {
|
||||
if (candidate === this.floor || !this.unplayable.has(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private lowestPlayable(): number {
|
||||
for (let candidate = this.floor - 1; candidate >= 0; candidate--) {
|
||||
if (!this.unplayable.has(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return this.floor;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
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
|
||||
const AUTO_VALUE = "__frigate_auto__";
|
||||
|
||||
type LiveStreamSelectProps = {
|
||||
// friendly name to go2rtc stream name, in ladder order
|
||||
streams: Record<string, string>;
|
||||
pinnedStream: string | undefined;
|
||||
playingStream: string;
|
||||
autoAvailable: boolean;
|
||||
autoReason?: LiveAutoReason;
|
||||
// undefined selects auto
|
||||
onSelect: (stream: string | undefined) => void;
|
||||
// sends auto back to the top of the ladder
|
||||
onRetry: () => void;
|
||||
disabled: boolean;
|
||||
};
|
||||
|
||||
export default function LiveStreamSelect({
|
||||
streams,
|
||||
pinnedStream,
|
||||
playingStream,
|
||||
autoAvailable,
|
||||
autoReason,
|
||||
onSelect,
|
||||
onRetry,
|
||||
disabled,
|
||||
}: LiveStreamSelectProps) {
|
||||
const { t } = useTranslation(["views/live"]);
|
||||
|
||||
const labelFor = useCallback(
|
||||
(name: string) =>
|
||||
Object.keys(streams).find((label) => streams[label] === name) ?? name,
|
||||
[streams],
|
||||
);
|
||||
|
||||
const auto = autoAvailable && pinnedStream == undefined;
|
||||
const value = auto ? AUTO_VALUE : (pinnedStream ?? playingStream);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Select
|
||||
value={value}
|
||||
disabled={disabled}
|
||||
onValueChange={(next) =>
|
||||
onSelect(next === AUTO_VALUE ? undefined : next)
|
||||
}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue>
|
||||
{auto
|
||||
? t("stream.auto.selected", {
|
||||
stream:
|
||||
autoReason === "floor"
|
||||
? t("stream.auto.floorLabel")
|
||||
: labelFor(playingStream),
|
||||
})
|
||||
: labelFor(value)}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{autoAvailable && (
|
||||
<SelectItem className="cursor-pointer" value={AUTO_VALUE}>
|
||||
<span className="flex flex-col gap-0.5 whitespace-normal">
|
||||
<span>{t("stream.auto.label")}</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{t("stream.auto.tips")}
|
||||
</span>
|
||||
</span>
|
||||
</SelectItem>
|
||||
)}
|
||||
{Object.entries(streams).map(([label, name]) => (
|
||||
<SelectItem key={label} className="cursor-pointer" value={name}>
|
||||
{label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
{auto && autoReason && !disabled && (
|
||||
<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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { baseUrl } from "@/api/baseUrl";
|
||||
import { useUserPersistence } from "@/hooks/use-user-persistence";
|
||||
import {
|
||||
LiveHealthSample,
|
||||
LivePlayerError,
|
||||
PlayerStatsType,
|
||||
VideoResolutionType,
|
||||
@@ -28,6 +29,7 @@ type MSEPlayerProps = {
|
||||
onPlaying?: () => void;
|
||||
setFullResolution?: React.Dispatch<SetStateAction<VideoResolutionType>>;
|
||||
onError?: (error: LivePlayerError) => void;
|
||||
onHealthSample?: (sample: LiveHealthSample) => void;
|
||||
};
|
||||
|
||||
function MSEPlayer({
|
||||
@@ -43,6 +45,7 @@ function MSEPlayer({
|
||||
onPlaying,
|
||||
setFullResolution,
|
||||
onError,
|
||||
onHealthSample,
|
||||
}: MSEPlayerProps) {
|
||||
const RECONNECT_TIMEOUT: number = 10000;
|
||||
const BUFFERING_COOLDOWN_TIMEOUT: number = 5000;
|
||||
@@ -71,6 +74,7 @@ function MSEPlayer({
|
||||
const [bufferTimeout, setBufferTimeout] = useState<NodeJS.Timeout>();
|
||||
const [errorCount, setErrorCount] = useState<number>(0);
|
||||
const totalBytesLoaded = useRef(0);
|
||||
const appendingRef = useRef(false);
|
||||
|
||||
const [fallbackTimeout] = useUserPersistence<number>(
|
||||
"liveFallbackTimeout",
|
||||
@@ -95,6 +99,13 @@ function MSEPlayer({
|
||||
return `${baseUrl.replace(/^http/, "ws")}live/mse/api/ws?src=${camera}`;
|
||||
}, [camera]);
|
||||
|
||||
// socket handlers are bound once per connection, so they reach the
|
||||
// current onError through a ref
|
||||
const onErrorRef = useRef(onError);
|
||||
useEffect(() => {
|
||||
onErrorRef.current = onError;
|
||||
}, [onError]);
|
||||
|
||||
const handleError = useCallback(
|
||||
(error: LivePlayerError, description: string = "Unknown error") => {
|
||||
// eslint-disable-next-line no-console
|
||||
@@ -110,11 +121,11 @@ function MSEPlayer({
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`${camera} - Supported codecs: ${CODECS.join(", ")}`);
|
||||
}
|
||||
onError?.(error);
|
||||
onErrorRef.current?.(error);
|
||||
},
|
||||
// we know that these deps are correct
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[camera, onError],
|
||||
[camera],
|
||||
);
|
||||
|
||||
const handleLoadedMetadata = useCallback(() => {
|
||||
@@ -470,7 +481,12 @@ function MSEPlayer({
|
||||
const data = buf.slice(0, bufLen);
|
||||
bufLen = 0;
|
||||
sb.appendBuffer(data);
|
||||
} else if (sb.buffered && sb.buffered.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
appendingRef.current = false;
|
||||
|
||||
if (sb.buffered && sb.buffered.length) {
|
||||
const end = sb.buffered.end(sb.buffered.length - 1) - 15;
|
||||
const start = sb.buffered.start(0);
|
||||
if (end > start) {
|
||||
@@ -488,6 +504,7 @@ function MSEPlayer({
|
||||
|
||||
ondataRef.current = (data) => {
|
||||
totalBytesLoaded.current += data.byteLength;
|
||||
appendingRef.current = true;
|
||||
|
||||
if (sb?.updating || bufLen > 0) {
|
||||
const b = new Uint8Array(data);
|
||||
@@ -503,6 +520,19 @@ function MSEPlayer({
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// go2rtc answers a codec it cannot provide with an error message
|
||||
// instead of a negotiation reply
|
||||
onmessageRef.current["error"] = (msg) => {
|
||||
if (msg.type !== "error" || !msg.value?.includes("codecs not matched")) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (wsRef.current) {
|
||||
onDisconnect();
|
||||
}
|
||||
handleError("mse-codec", msg.value);
|
||||
};
|
||||
};
|
||||
|
||||
const getBufferedTime = (video: HTMLVideoElement | null) => {
|
||||
@@ -740,19 +770,38 @@ function MSEPlayer({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [playbackEnabled]);
|
||||
|
||||
// stats
|
||||
// stats and health samples
|
||||
|
||||
const onHealthSampleRef = useRef(onHealthSample);
|
||||
useEffect(() => {
|
||||
onHealthSampleRef.current = onHealthSample;
|
||||
}, [onHealthSample]);
|
||||
const sampleHealth = onHealthSample !== undefined;
|
||||
|
||||
useEffect(() => {
|
||||
const video = videoRef.current;
|
||||
let lastLoadedBytes = totalBytesLoaded.current;
|
||||
let lastTimestamp = Date.now();
|
||||
let healthBytes = lastLoadedBytes;
|
||||
let healthTimestamp = lastTimestamp;
|
||||
// a restart mid-stream must not count the existing buffer as new media
|
||||
let lastBufferedEnd =
|
||||
video && video.buffered.length > 0
|
||||
? video.buffered.end(video.buffered.length - 1)
|
||||
: 0;
|
||||
let deferred = false;
|
||||
|
||||
if (!getStats) return;
|
||||
if (!getStats && !sampleHealth) return;
|
||||
|
||||
const updateStats = () => {
|
||||
if (video) {
|
||||
const now = Date.now();
|
||||
const bytesLoaded = totalBytesLoaded.current;
|
||||
const update = () => {
|
||||
if (!video) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const bytesLoaded = totalBytesLoaded.current;
|
||||
|
||||
if (getStats) {
|
||||
const timeElapsed = (now - lastTimestamp) / 1000; // seconds
|
||||
const bandwidth = (bytesLoaded - lastLoadedBytes) / timeElapsed / 1000; // kBps
|
||||
|
||||
@@ -774,22 +823,64 @@ function MSEPlayer({
|
||||
droppedFrameRate,
|
||||
});
|
||||
}
|
||||
|
||||
if (!sampleHealth) {
|
||||
return;
|
||||
}
|
||||
|
||||
// a sample taken mid-append would count the bytes without their
|
||||
// media, so it waits one tick for the append to land
|
||||
if (appendingRef.current && !deferred) {
|
||||
deferred = true;
|
||||
return;
|
||||
}
|
||||
deferred = false;
|
||||
|
||||
// the buffered end tracks delivered media, so playback-rate
|
||||
// catch-up does not skew it
|
||||
const bufferedEnd =
|
||||
video.buffered.length > 0
|
||||
? video.buffered.end(video.buffered.length - 1)
|
||||
: 0;
|
||||
const mediaSeconds = bufferedEnd - lastBufferedEnd;
|
||||
const bytes = bytesLoaded - healthBytes;
|
||||
const wallSeconds = (now - healthTimestamp) / 1000;
|
||||
|
||||
lastBufferedEnd = bufferedEnd;
|
||||
healthBytes = bytesLoaded;
|
||||
healthTimestamp = now;
|
||||
|
||||
// a reconnect starts a new MediaSource timeline
|
||||
if (mediaSeconds < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
document.visibilityState !== "visible" ||
|
||||
(video.paused && bufferedEnd > 0)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
onHealthSampleRef.current?.({ bytes, mediaSeconds, wallSeconds });
|
||||
};
|
||||
|
||||
const interval = setInterval(updateStats, 1000); // Update every second
|
||||
const interval = setInterval(update, 1000);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
setStats?.({
|
||||
streamType: "-",
|
||||
bandwidth: 0,
|
||||
totalFrames: 0,
|
||||
droppedFrames: undefined,
|
||||
decodedFrames: 0,
|
||||
droppedFrameRate: 0,
|
||||
});
|
||||
if (getStats) {
|
||||
setStats?.({
|
||||
streamType: "-",
|
||||
bandwidth: 0,
|
||||
totalFrames: 0,
|
||||
droppedFrames: undefined,
|
||||
decodedFrames: 0,
|
||||
droppedFrameRate: 0,
|
||||
});
|
||||
}
|
||||
};
|
||||
}, [setStats, getStats]);
|
||||
}, [setStats, getStats, sampleHealth]);
|
||||
|
||||
return (
|
||||
<video
|
||||
|
||||
@@ -5,9 +5,16 @@ import { useTranslation } from "react-i18next";
|
||||
type PlayerStatsProps = {
|
||||
stats: PlayerStatsType;
|
||||
minimal: boolean;
|
||||
streamLabel?: string;
|
||||
streamAuto?: boolean;
|
||||
};
|
||||
|
||||
export function PlayerStats({ stats, minimal }: PlayerStatsProps) {
|
||||
export function PlayerStats({
|
||||
stats,
|
||||
minimal,
|
||||
streamLabel,
|
||||
streamAuto = false,
|
||||
}: PlayerStatsProps) {
|
||||
const { t } = useTranslation(["components/player", "views/live"]);
|
||||
const streamTypeLabel = t(
|
||||
`stream.technology.name.${stats.streamType.toLowerCase()}`,
|
||||
@@ -15,6 +22,16 @@ export function PlayerStats({ stats, minimal }: PlayerStatsProps) {
|
||||
);
|
||||
const fullStatsContent = (
|
||||
<>
|
||||
{streamLabel != undefined && (
|
||||
<p>
|
||||
<span className="text-white/70">{t("stats.stream")}</span>{" "}
|
||||
<span className="text-white">
|
||||
{streamAuto
|
||||
? t("stats.streamAuto", { stream: streamLabel })
|
||||
: streamLabel}
|
||||
</span>
|
||||
</p>
|
||||
)}
|
||||
<p>
|
||||
<span className="text-white/70">{t("stats.streamType.title")}</span>{" "}
|
||||
<span className="text-white">{streamTypeLabel}</span>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { baseUrl } from "@/api/baseUrl";
|
||||
import {
|
||||
LiveHealthSample,
|
||||
LivePlayerError,
|
||||
PlayerStatsType,
|
||||
TwoWayTalkError,
|
||||
@@ -24,6 +25,7 @@ type WebRtcPlayerProps = {
|
||||
setFullResolution?: React.Dispatch<React.SetStateAction<VideoResolutionType>>;
|
||||
onPlaying?: () => void;
|
||||
onError?: (error: LivePlayerError) => void;
|
||||
onHealthSample?: (sample: LiveHealthSample) => void;
|
||||
onMicrophoneError?: (error: TwoWayTalkError) => void;
|
||||
};
|
||||
|
||||
@@ -41,6 +43,7 @@ export default function WebRtcPlayer({
|
||||
setFullResolution,
|
||||
onPlaying,
|
||||
onError,
|
||||
onHealthSample,
|
||||
onMicrophoneError,
|
||||
}: WebRtcPlayerProps) {
|
||||
// metadata
|
||||
@@ -354,13 +357,20 @@ export default function WebRtcPlayer({
|
||||
onPlaying?.();
|
||||
};
|
||||
|
||||
// stats
|
||||
// stats and health samples
|
||||
|
||||
const onHealthSampleRef = useRef(onHealthSample);
|
||||
useEffect(() => {
|
||||
onHealthSampleRef.current = onHealthSample;
|
||||
}, [onHealthSample]);
|
||||
const sampleHealth = onHealthSample !== undefined;
|
||||
|
||||
useEffect(() => {
|
||||
if (!pcRef.current || !getStats) return;
|
||||
if (!pcRef.current || (!getStats && !sampleHealth)) return;
|
||||
|
||||
let lastBytesReceived = 0;
|
||||
let lastTimestamp = 0;
|
||||
let lastFreezeSeconds: number | undefined;
|
||||
|
||||
const interval = setInterval(async () => {
|
||||
if (pcRef.current && videoRef.current && !videoRef.current.paused) {
|
||||
@@ -369,6 +379,7 @@ export default function WebRtcPlayer({
|
||||
let timestamp = 0;
|
||||
let framesReceived = 0;
|
||||
let framesDecoded = 0;
|
||||
let freezeSeconds: number | undefined;
|
||||
|
||||
report.forEach((stat) => {
|
||||
if (stat.type === "inbound-rtp" && stat.kind === "video") {
|
||||
@@ -376,43 +387,72 @@ export default function WebRtcPlayer({
|
||||
timestamp = stat.timestamp;
|
||||
framesReceived = stat.framesReceived;
|
||||
framesDecoded = stat.framesDecoded;
|
||||
freezeSeconds = stat.totalFreezesDuration;
|
||||
}
|
||||
});
|
||||
|
||||
const timeDiff = (timestamp - lastTimestamp) / 1000; // in seconds
|
||||
const bitrate =
|
||||
timeDiff > 0
|
||||
? (bytesReceived - lastBytesReceived) / timeDiff / 1000
|
||||
: 0; // in kBps
|
||||
|
||||
setStats?.({
|
||||
streamType: "WebRTC",
|
||||
bandwidth: Math.round(bitrate),
|
||||
totalFrames: framesReceived,
|
||||
droppedFrames: undefined,
|
||||
decodedFrames: framesDecoded,
|
||||
droppedFrameRate: undefined,
|
||||
});
|
||||
if (getStats) {
|
||||
const bitrate =
|
||||
timeDiff > 0
|
||||
? (bytesReceived - lastBytesReceived) / timeDiff / 1000
|
||||
: 0; // in kBps
|
||||
|
||||
setStats?.({
|
||||
streamType: "WebRTC",
|
||||
bandwidth: Math.round(bitrate),
|
||||
totalFrames: framesReceived,
|
||||
droppedFrames: undefined,
|
||||
decodedFrames: framesDecoded,
|
||||
droppedFrameRate: undefined,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
sampleHealth &&
|
||||
lastTimestamp > 0 &&
|
||||
timeDiff > 0 &&
|
||||
document.visibilityState === "visible"
|
||||
) {
|
||||
// freeze time does not depend on the camera's frame rate. A
|
||||
// freeze is credited only when it ends, so media goes negative
|
||||
// to carry its full length. Browsers without the field report
|
||||
// full delivery and rely on the stall watchdog
|
||||
const frozen =
|
||||
freezeSeconds !== undefined && lastFreezeSeconds !== undefined
|
||||
? Math.max(0, freezeSeconds - lastFreezeSeconds)
|
||||
: 0;
|
||||
|
||||
onHealthSampleRef.current?.({
|
||||
bytes: bytesReceived - lastBytesReceived,
|
||||
mediaSeconds: timeDiff - frozen,
|
||||
wallSeconds: timeDiff,
|
||||
});
|
||||
}
|
||||
|
||||
lastBytesReceived = bytesReceived;
|
||||
lastTimestamp = timestamp;
|
||||
lastFreezeSeconds = freezeSeconds;
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
setStats?.({
|
||||
streamType: "-",
|
||||
bandwidth: 0,
|
||||
totalFrames: 0,
|
||||
droppedFrames: undefined,
|
||||
decodedFrames: 0,
|
||||
droppedFrameRate: 0,
|
||||
});
|
||||
if (getStats) {
|
||||
setStats?.({
|
||||
streamType: "-",
|
||||
bandwidth: 0,
|
||||
totalFrames: 0,
|
||||
droppedFrames: undefined,
|
||||
decodedFrames: 0,
|
||||
droppedFrameRate: 0,
|
||||
});
|
||||
}
|
||||
};
|
||||
// we need to listen on the value of the ref
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [pcRef, pcRef.current, getStats]);
|
||||
}, [pcRef, pcRef.current, getStats, sampleHealth]);
|
||||
|
||||
return (
|
||||
<video
|
||||
|
||||
Reference in New Issue
Block a user