diff --git a/ui/src/components/CustomTooltip.tsx b/ui/src/components/CustomTooltip.tsx index a27f607..5b8848f 100644 --- a/ui/src/components/CustomTooltip.tsx +++ b/ui/src/components/CustomTooltip.tsx @@ -1,25 +1,25 @@ import Card from "@components/Card"; export interface CustomTooltipProps { - payload: { payload: { date: number; stat: number }; unit: string }[]; + payload: { payload: { date: number; metric: number }; unit: string }[]; } export default function CustomTooltip({ payload }: CustomTooltipProps) { if (payload?.length) { const toolTipData = payload[0]; - const { date, stat } = toolTipData.payload; + const { date, metric } = toolTipData.payload; return ( -
-
+
+
{new Date(date * 1000).toLocaleTimeString()}
- - {stat} {toolTipData?.unit} + + {metric} {toolTipData?.unit}
diff --git a/ui/src/components/Metric.tsx b/ui/src/components/Metric.tsx new file mode 100644 index 0000000..bd367ac --- /dev/null +++ b/ui/src/components/Metric.tsx @@ -0,0 +1,170 @@ +import { ComponentProps } from "react"; +import { cva, cx } from "cva"; + +import { someIterable } from "../utils"; + +import { GridCard } from "./Card"; +import MetricsChart from "./MetricsChart"; + +interface ChartPoint { + date: number; + metric: number | null; +} + +interface MetricProps { + title: string; + description: string; + stream?: Map; + metric?: K; + data?: ChartPoint[]; + gate?: Map; + supported?: boolean; + map?: (p: { date: number; metric: number | null }) => ChartPoint; + domain?: [number, number]; + unit: string; + heightClassName?: string; + referenceValue?: number; + badge?: ComponentProps["badge"]; + badgeTheme?: ComponentProps["badgeTheme"]; +} + +/* eslint-disable-next-line */ +export function createChartArray( + metrics: Map, + metricName: K, +) { + const result: { date: number; metric: number | null }[] = []; + const iter = metrics.entries(); + let next = iter.next() as IteratorResult<[number, T]>; + const now = Math.floor(Date.now() / 1000); + + // We want 120 data points, in the chart. + const firstDate = Math.min(next.value?.[0] ?? now, now - 120); + + for (let t = firstDate; t < now; t++) { + while (!next.done && next.value[0] < t) next = iter.next(); + const has = !next.done && next.value[0] === t; + + let metric = null; + if (has) metric = next.value[1][metricName] as number; + result.push({ date: t, metric }); + + if (has) next = iter.next(); + } + + return result; +} + +const theme = { + light: + "bg-white text-black border border-slate-800/20 dark:border dark:border-slate-700 dark:bg-slate-800 dark:text-slate-300", + danger: "bg-red-500 dark:border-red-700 dark:bg-red-800 dark:text-red-50", + primary: "bg-blue-500 dark:border-blue-700 dark:bg-blue-800 dark:text-blue-50", +}; + +interface SettingsItemProps { + readonly title: string; + readonly description: string | React.ReactNode; + readonly badge?: string; + readonly className?: string; + readonly children?: React.ReactNode; + readonly badgeTheme?: keyof typeof theme; +} + +export function MetricHeader(props: SettingsItemProps) { + const { title, description, badge } = props; + const badgeVariants = cva({ variants: { theme: theme } }); + + return ( +
+
+
+ {title} + {badge && ( + + {badge} + + )} +
+
+
{description}
+
+ ); +} + +export function Metric({ + title, + description, + stream, + metric, + data, + gate, + supported, + map, + domain = [0, 600], + unit = "", + heightClassName = "h-[127px]", + badge, + badgeTheme, +}: MetricProps) { + const ready = gate ? gate.size > 0 : stream ? stream.size > 0 : true; + const supportedFinal = + supported ?? + (stream && metric ? someIterable(stream, ([, s]) => s[metric] !== undefined) : true); + + // Either we let the consumer provide their own chartArray, or we create one from the stream and metric. + const raw = data ?? ((stream && metric && createChartArray(stream, metric)) || []); + + // If the consumer provides a map function, we apply it to the raw data. + const dataFinal: ChartPoint[] = map ? raw.map(map) : raw; + const recent = dataFinal + .slice(-(raw.length - 1)) + .filter(x => x.metric != null) as ChartPoint[]; + + // Average the recent values + const computedReferenceValue = + recent.length > 0 + ? Math.round( + recent.reduce((sum, x) => sum + (x.metric as number), 0) / recent.length, + ) + : undefined; + + return ( +
+ + + +
+ {!ready ? ( +
+

Waiting for data...

+
+ ) : supportedFinal ? ( + + ) : ( +
+

Metric not supported

+
+ )} +
+
+
+ ); +} diff --git a/ui/src/components/StatChart.tsx b/ui/src/components/MetricsChart.tsx similarity index 91% rename from ui/src/components/StatChart.tsx rename to ui/src/components/MetricsChart.tsx index 2c403e3..853bcf3 100644 --- a/ui/src/components/StatChart.tsx +++ b/ui/src/components/MetricsChart.tsx @@ -12,13 +12,13 @@ import { import CustomTooltip, { CustomTooltipProps } from "@components/CustomTooltip"; -export default function StatChart({ +export default function MetricsChart({ data, domain, unit, referenceValue, }: { - data: { date: number; stat: number | null | undefined }[]; + data: { date: number; metric: number | null | undefined }[]; domain?: [string | number, string | number]; unit?: string; referenceValue?: number; @@ -33,7 +33,7 @@ export default function StatChart({ strokeLinecap="butt" stroke="rgba(30, 41, 59, 0.1)" /> - {referenceValue && ( + {referenceValue !== undefined && ( x.date)} /> ( - stream: Map, - metric: K, -): { date: number; stat: T[K] | null }[] { - const stat = Array.from(stream).map(([key, stats]) => { - return { date: key, stat: stats[metric] }; - }); - - // Sort the dates to ensure they are in chronological order - const sortedStat = stat.map(x => x.date).sort((a, b) => a - b); - - // Determine the earliest statistic date - const earliestStat = sortedStat[0]; - - // Current time in seconds since the Unix epoch - const now = Math.floor(Date.now() / 1000); - - // Determine the starting point for the chart data - const firstChartDate = earliestStat ? Math.min(earliestStat, now - 120) : now - 120; - - // Generate the chart array for the range between 'firstChartDate' and 'now' - return Array.from({ length: now - firstChartDate }, (_, i) => { - const currentDate = firstChartDate + i; - return { - date: currentDate, - // Find the statistic for 'currentDate', or use the last known statistic if none exists for that date - stat: stat.find(x => x.date === currentDate)?.stat ?? null, - }; - }); -} +import { createChartArray, Metric } from "../Metric"; +import { SettingsSectionHeader } from "../SettingsSectionHeader"; +import { someIterable } from "../../utils"; export default function ConnectionStatsSidebar() { - const inboundRtpStats = useRTCStore(state => state.inboundRtpStats); - - const candidatePairStats = useRTCStore(state => state.candidatePairStats); + const inboundVideoRtpStats = useRTCStore(state => state.inboundRtpStats); + const iceCandidatePairStats = useRTCStore(state => state.candidatePairStats); const setSidebarView = useUiStore(state => state.setSidebarView); - function isMetricSupported( - stream: Map, - metric: K, - ): boolean { - return Array.from(stream).some(([, stat]) => stat[metric] !== undefined); - } - - const appendInboundRtpStats = useRTCStore(state => state.appendInboundRtpStats); + const appendInboundVideoRtpStats = useRTCStore(state => state.appendInboundRtpStats); const appendIceCandidatePair = useRTCStore(state => state.appendCandidatePairStats); const appendDiskDataChannelStats = useRTCStore( state => state.appendDiskDataChannelStats, @@ -66,15 +29,13 @@ export default function ConnectionStatsSidebar() { useInterval(function collectWebRTCStats() { (async () => { if (!mediaStream) return; - const videoTrack = mediaStream.getVideoTracks()[0]; - if (!videoTrack) return; const stats = await peerConnection?.getStats(); let successfulLocalCandidateId: string | null = null; let successfulRemoteCandidateId: string | null = null; stats?.forEach(report => { - if (report.type === "inbound-rtp") { - appendInboundRtpStats(report); + if (report.type === "inbound-rtp" && report.kind === "video") { + appendInboundVideoRtpStats(report); } else if (report.type === "candidate-pair" && report.nominated) { if (report.state === "succeeded") { successfulLocalCandidateId = report.localCandidateId; @@ -98,144 +59,133 @@ export default function ConnectionStatsSidebar() { })(); }, 500); + const jitterBufferDelay = createChartArray(inboundVideoRtpStats, "jitterBufferDelay"); + const jitterBufferEmittedCount = createChartArray( + inboundVideoRtpStats, + "jitterBufferEmittedCount", + ); + + const jitterBufferAvgDelayData = jitterBufferDelay.map((d, idx) => { + if (idx === 0) return { date: d.date, metric: null }; + const prevDelay = jitterBufferDelay[idx - 1]?.metric as number | null | undefined; + const currDelay = d.metric as number | null | undefined; + const prevEmitted = + (jitterBufferEmittedCount[idx - 1]?.metric as number | null | undefined) ?? null; + const currEmitted = + (jitterBufferEmittedCount[idx]?.metric as number | null | undefined) ?? null; + + if ( + prevDelay == null || + currDelay == null || + prevEmitted == null || + currEmitted == null + ) { + return { date: d.date, metric: null }; + } + + const deltaDelay = currDelay - prevDelay; + const deltaEmitted = currEmitted - prevEmitted; + + // Guard counter resets or no emitted frames + if (deltaDelay < 0 || deltaEmitted <= 0) { + return { date: d.date, metric: null }; + } + + const valueMs = Math.round((deltaDelay / deltaEmitted) * 1000); + return { date: d.date, metric: valueMs }; + }); + return (
- {/* - The entire sidebar component is always rendered, with a display none when not visible - The charts below, need a height and width, otherwise they throw. So simply don't render them unless the thing is visible - */} {sidebarView === "connection-stats" && ( -
-
-
-

- Packets Lost -

-

- Number of data packets lost during transmission. -

-
- -
- {inboundRtpStats.size === 0 ? ( -
-

Waiting for data...

-
- ) : isMetricSupported(inboundRtpStats, "packetsLost") ? ( - - ) : ( -
-

Metric not supported

-
- )} -
-
+
+ {/* Connection Group */} +
+ + ({ + date: x.date, + metric: x.metric != null ? Math.round(x.metric * 1000) : null, + })} + domain={[0, 600]} + unit=" ms" + />
-
-
-

- Round-Trip Time -

-

- Time taken for data to travel from source to destination and back -

-
- -
- {inboundRtpStats.size === 0 ? ( -
-

Waiting for data...

-
- ) : isMetricSupported(candidatePairStats, "currentRoundTripTime") ? ( - { - return { - date: x.date, - stat: x.stat ? Math.round(x.stat * 1000) : null, - }; - })} - domain={[0, 600]} - unit=" ms" - /> - ) : ( -
-

Metric not supported

-
- )} -
-
-
-
-
-

- Jitter -

-

- Variation in packet delay, affecting video smoothness.{" "} -

-
- -
- {inboundRtpStats.size === 0 ? ( -
-

Waiting for data...

-
- ) : ( - { - return { - date: x.date, - stat: x.stat ? Math.round(x.stat * 1000) : null, - }; - })} - domain={[0, 300]} - unit=" ms" - /> - )} -
-
-
-
-
-

- Frames per second -

-

- Number of video frames displayed per second. -

-
- -
- {inboundRtpStats.size === 0 ? ( -
-

Waiting for data...

-
- ) : ( - { - return { - date: x.date, - stat: x.stat ? x.stat : null, - }; - }, - )} - domain={[0, 80]} - unit=" fps" - /> - )} -
-
+ + {/* Video Group */} +
+ + + {/* RTP Jitter */} + ({ + date: x.date, + metric: x.metric != null ? Math.round(x.metric * 1000) : null, + })} + domain={[0, 10]} + unit=" ms" + /> + + {/* Playback Delay */} + x.jitterBufferDelay != null, + ) && + someIterable( + inboundVideoRtpStats, + ([, x]) => x.jitterBufferEmittedCount != null, + ) + } + domain={[0, 30]} + unit=" ms" + /> + + {/* Packets Lost */} + + + {/* Frames Per Second */} +
)} diff --git a/ui/src/routes/devices.$id.tsx b/ui/src/routes/devices.$id.tsx index 1017eb4..e79134c 100644 --- a/ui/src/routes/devices.$id.tsx +++ b/ui/src/routes/devices.$id.tsx @@ -736,7 +736,7 @@ export default function KvmIdRoute() { send("getUpdateStatus", {}, (resp: JsonRpcResponse) => { if ("error" in resp) { notifications.error(`Failed to get device version: ${resp.error}`); - return + return } const result = resp.result as SystemVersionInfo; diff --git a/ui/src/utils.ts b/ui/src/utils.ts index 99c1a50..9e36133 100644 --- a/ui/src/utils.ts +++ b/ui/src/utils.ts @@ -94,6 +94,17 @@ export const formatters = { }, }; +export function someIterable( + iterable: Iterable, + predicate: (item: T) => boolean, +): boolean { + for (const item of iterable) { + if (predicate(item)) return true; + } + + return false; +} + export const VIDEO = new Blob( [ new Uint8Array([