Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

feat(media-server): redesign the session details popup (#7228)

Bergasha1b4ada15718e
diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.json
index de562736d..fe555b85c 100644
--- a/packages/translation/src/lang/en.json
+++ b/packages/translation/src/lang/en.json
@@ -3936,11 +3936,28 @@
"paused": "Paused",
"remaining": "{minutes} min left",
"seasonEpisode": "S{season} E{episode}",
+ "state": {
+ "playing": "Playing",
+ "buffering": "Buffering"
+ },
+ "details": {
+ "device": "Device",
+ "location": "Location",
+ "sessionId": "Session ID",
+ "bitrate": "Bitrate",
+ "audioHandling": "Audio handling",
+ "direct": "Direct",
+ "transcode": "Transcoding to {target}",
+ "containerChanged": "{container} (remux)",
+ "position": "{position} / {duration}",
+ "unknown": "unknown format"
+ },
"metadata": {
"title": "Stats for nerds",
"video": {
"title": "Video",
- "resolution": "Resolution"
+ "resolution": "Resolution",
+ "frameRate": "Frame rate"
},
"audio": {
"title": "Audio",
diff --git a/packages/widgets/src/media-server/component.spec.tsx b/packages/widgets/src/media-server/component.spec.tsx
index 55557b8b2..ded17840c 100644
--- a/packages/widgets/src/media-server/component.spec.tsx
+++ b/packages/widgets/src/media-server/component.spec.tsx
@@ -10,6 +10,10 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import type { StreamSession } from "@homarr/integrations";
import {
+ formatChannelLayout,
+ formatCodec,
+ formatFrameRate,
+ formatPlaybackTime,
getMediaServerColumnVisibility,
getResolutionLabel,
getSeasonEpisodeParams,
@@ -103,6 +107,88 @@ describe("SessionDetailsPopover", () => {
});
expect(target?.getAttribute("aria-expanded")).toBe("false");
});
+
+ test("shows the stream stats and never prints a null codec", async () => {
+ const transcodingSession = {
+ sessionId: "session-2",
+ sessionName: "Plezy (SHIELD)",
+ user: { username: "Alex", profilePictureUrl: null },
+ currentlyPlaying: {
+ type: "tv",
+ name: "Example show",
+ episodeName: "Pilot",
+ seasonName: "Season 1",
+ seasonNumber: 1,
+ episodeNumber: 2,
+ playback: { state: "playing", positionMs: 600_000, durationMs: 2_400_000 },
+ location: "wan",
+ metadata: {
+ video: { resolution: { width: 1920, height: 1080 }, frameRate: 23.976023 },
+ audio: { channelCount: 6, codec: "aac" },
+ transcoding: {
+ container: "mp4",
+ resolution: null,
+ target: { audioCodec: null, videoCodec: null },
+ isVideoDirect: true,
+ isAudioDirect: false,
+ containerChanged: true,
+ },
+ bitrateKbps: 8200,
+ },
+ },
+ } as unknown as StreamSession;
+
+ await act(() =>
+ root.render(
+ <MantineProvider env="test">
+ <SessionDetailsPopover item={transcodingSession} opened onChange={() => undefined}>
+ Open session
+ </SessionDetailsPopover>
+ </MantineProvider>,
+ ),
+ );
+
+ const text = document.body.textContent;
+ expect(text).toContain("Example show");
+ expect(text).toContain("1920×1080 (1080p)");
+ expect(text).toContain("23.976 fps");
+ expect(text).toContain("5.1");
+ expect(text).toContain("AAC");
+ expect(text).toContain("8.2 Mb/s");
+ expect(text).not.toContain("null");
+ expect(text).not.toContain("undefined");
+ });
+});
+
+describe("session detail formatters", () => {
+ test("formats playback time with and without hours", () => {
+ expect(formatPlaybackTime(0)).toBe("0:00");
+ expect(formatPlaybackTime(65_000)).toBe("1:05");
+ expect(formatPlaybackTime(3_725_000)).toBe("1:02:05");
+ expect(formatPlaybackTime(null)).toBeNull();
+ expect(formatPlaybackTime(-1)).toBeNull();
+ });
+
+ test("names common channel layouts", () => {
+ expect(formatChannelLayout(2)).toBe("2.0");
+ expect(formatChannelLayout(6)).toBe("5.1");
+ expect(formatChannelLayout(8)).toBe("7.1");
+ expect(formatChannelLayout(null)).toBeNull();
+ expect(formatChannelLayout(0)).toBeNull();
+ });
+
+ test("trims frame rates and ignores missing values", () => {
+ expect(formatFrameRate(23.976023)).toBe("23.976 fps");
+ expect(formatFrameRate(25)).toBe("25 fps");
+ expect(formatFrameRate(null)).toBeNull();
+ expect(formatFrameRate(0)).toBeNull();
+ });
+
+ test("upper-cases codecs and ignores empty ones", () => {
+ expect(formatCodec("hevc")).toBe("HEVC");
+ expect(formatCodec(null)).toBeNull();
+ expect(formatCodec("")).toBeNull();
+ });
});
describe("getMediaServerColumnVisibility", () => {
diff --git a/packages/widgets/src/media-server/component.tsx b/packages/widgets/src/media-server/component.tsx
index 90741861a..7a934129c 100644
--- a/packages/widgets/src/media-server/component.tsx
+++ b/packages/widgets/src/media-server/component.tsx
@@ -32,7 +32,7 @@ import {
} from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
-import { formatBitRate, objectEntries } from "@homarr/common";
+import { formatBitRate } from "@homarr/common";
import { getIconUrl } from "@homarr/definitions";
import type { StreamSession } from "@homarr/integrations";
import { useI18n } from "@homarr/translation/client";
@@ -566,11 +566,12 @@ export function SessionDetailsPopover({
opened={opened}
onChange={onChange}
position="bottom-start"
- width="min(26.25rem, calc(100vw - 1.5rem))"
+ width="min(26rem, calc(100vw - 1.5rem))"
shadow="md"
withArrow
withinPortal
returnFocus
+ middlewares={{ flip: true, shift: { padding: 8 } }}
>
<Popover.Target>
<UnstyledButton
@@ -584,130 +585,225 @@ export function SessionDetailsPopover({
{children}
</UnstyledButton>
</Popover.Target>
- <Popover.Dropdown>
+ <Popover.Dropdown p="sm" style={{ maxHeight: "calc(100vh - 1.5rem)", overflowY: "auto" }}>
<SessionDetails item={item} />
</Popover.Dropdown>
</Popover>
);
}
+export const formatPlaybackTime = (ms: number | null | undefined): string | null => {
+ if (ms === null || ms === undefined || !Number.isFinite(ms) || ms < 0) return null;
+ const totalSeconds = Math.floor(ms / 1000);
+ const hours = Math.floor(totalSeconds / 3600);
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
+ const seconds = String(totalSeconds % 60).padStart(2, "0");
+ if (hours > 0) return `${hours}:${String(minutes).padStart(2, "0")}:${seconds}`;
+ return `${minutes}:${seconds}`;
+};
+
+export const formatChannelLayout = (channelCount: number | null | undefined): string | null => {
+ if (!channelCount || channelCount <= 0) return null;
+ if (channelCount === 6) return "5.1";
+ if (channelCount === 8) return "7.1";
+ return `${channelCount}.0`;
+};
+
+export const formatFrameRate = (frameRate: number | null | undefined): string | null => {
+ if (!frameRate || !Number.isFinite(frameRate) || frameRate <= 0) return null;
+ return `${Number(frameRate.toFixed(3))} fps`;
+};
+
+export const formatCodec = (codec: string | null | undefined): string | null => (codec ? codec.toUpperCase() : null);
+
+const formatResolution = (resolution: { width: number; height: number } | null | undefined): string | null => {
+ if (!resolution) return null;
+ return `${resolution.width}×${resolution.height} (${getResolutionLabel(resolution.width, resolution.height)})`;
+};
+
+interface DetailEntry {
+ key: string;
+ label: string;
+ value: ReactNode;
+ fullWidth: boolean;
+}
+
+const createEntry = (
+ key: string,
+ label: string,
+ value: ReactNode | null | undefined,
+ fullWidth = false,
+): DetailEntry | null =>
+ value === null || value === undefined || value === "" ? null : { key, label, value, fullWidth };
+
+const DetailGrid = ({ entries }: { entries: (DetailEntry | null)[] }) => {
+ const visible = entries.filter((entry): entry is DetailEntry => entry !== null);
+ if (visible.length === 0) return null;
+
+ return (
+ <SimpleGrid cols={3} spacing="xs" verticalSpacing={6}>
+ {visible.map((entry) => (
+ <Stack key={entry.key} gap={0} style={{ minWidth: 0, gridColumn: entry.fullWidth ? "1 / -1" : undefined }}>
+ <Text fz={11} c="dimmed" truncate>
+ {entry.label}
+ </Text>
+ <Text component="div" size="xs" fw={500} truncate>
+ {entry.value}
+ </Text>
+ </Stack>
+ ))}
+ </SimpleGrid>
+ );
+};
+
function SessionDetails({ item }: { item: StreamSession }) {
const t = useI18n("widget.mediaServer.items");
- const Icon = item.currentlyPlaying ? mediaTypeIconMap[item.currentlyPlaying.type] : null;
+ const playing = item.currentlyPlaying;
+ const Icon = playing ? mediaTypeIconMap[playing.type] : null;
+ const metadata = playing?.metadata ?? null;
+ const transcoding = metadata?.transcoding;
+ const status = playing ? getPlaybackStatus(transcoding) : null;
+ const playbackState = playing?.playback?.state ?? null;
+ let playbackStateLabel: string | null = null;
+ if (playbackState === "paused") {
+ playbackStateLabel = t("paused");
+ } else if (playbackState) {
+ playbackStateLabel = t(`state.${playbackState}`);
+ }
+ const positionMs = playing?.playback?.positionMs ?? null;
+ const durationMs = playing?.playback?.durationMs ?? null;
+ const progress =
+ positionMs !== null && durationMs !== null && durationMs > 0
+ ? Math.min(100, (positionMs / durationMs) * 100)
+ : null;
+ const position = formatPlaybackTime(positionMs);
+ const duration = formatPlaybackTime(durationMs);
+ const remainingMinutes =
+ positionMs !== null && durationMs !== null ? Math.max(0, Math.round((durationMs - positionMs) / 60_000)) : null;
+ const seasonEpisode = playing ? getSeasonEpisodeParams(playing.seasonNumber, playing.episodeNumber) : null;
+ let subtitle = "";
+ if (playing) {
+ const parts = seasonEpisode
+ ? [t("seasonEpisode", seasonEpisode), playing.episodeName]
+ : [playing.episodeName, playing.seasonName, playing.albumName];
+ subtitle = parts.filter(Boolean).join(" · ");
+ }
- const metadata = item.currentlyPlaying?.metadata ? constructMetadata(item.currentlyPlaying.metadata) : null;
+ let videoHandling: string | null = null;
+ let audioHandling: string | null = null;
+ if (transcoding) {
+ const videoTarget = [formatCodec(transcoding.target.videoCodec), formatResolution(transcoding.resolution)]
+ .filter(Boolean)
+ .join(" · ");
+ videoHandling = transcoding.isVideoDirect
+ ? t("details.direct")
+ : t("details.transcode", { target: videoTarget || t("details.unknown") });
+ audioHandling = transcoding.isAudioDirect
+ ? t("details.direct")
+ : t("details.transcode", { target: formatCodec(transcoding.target.audioCodec) ?? t("details.unknown") });
+ }
+
+ let container: string | null = null;
+ if (transcoding?.container) {
+ const containerName = transcoding.container.toUpperCase();
+ container = transcoding.containerChanged
+ ? t("details.containerChanged", { container: containerName })
+ : containerName;
+ }
+ const location = playing?.location?.toUpperCase() ?? null;
+ const audioFormat = metadata
+ ? [formatCodec(metadata.audio.codec), formatChannelLayout(metadata.audio.channelCount)].filter(Boolean).join(" ")
+ : "";
return (
- <Stack gap="sm" style={{ minWidth: 0 }}>
- {Icon && item.currentlyPlaying && (
- <Group gap="sm" align="flex-start" wrap="nowrap">
- <Icon size={22} style={{ flexShrink: 0 }} />
- <Stack gap={2} style={{ minWidth: 0 }}>
- <Text fw={600} lineClamp={2}>
- {item.currentlyPlaying.name}
- </Text>
- {item.currentlyPlaying.episodeName && (
- <Text size="xs" c="dimmed" lineClamp={2}>
- {[item.currentlyPlaying.episodeName, item.currentlyPlaying.seasonName].filter(Boolean).join(" · ")}
+ <Stack gap={8} style={{ minWidth: 0 }}>
+ {Icon && playing && (
+ <Stack gap={6} style={{ minWidth: 0 }}>
+ <Group gap="xs" align="flex-start" wrap="nowrap">
+ <Icon size={20} style={{ flexShrink: 0, marginTop: 2 }} />
+ <Stack gap={0} style={{ minWidth: 0, flex: 1 }}>
+ <Text fw={600} size="sm" lineClamp={1}>
+ {playing.name}
</Text>
+ {subtitle && (
+ <Text fz={11} c="dimmed" lineClamp={1}>
+ {subtitle}
+ </Text>
+ )}
+ </Stack>
+ {status && (
+ <Badge size="xs" variant="light" color={playbackStatusColorMap[status]} style={{ flexShrink: 0 }}>
+ {t(status)}
+ </Badge>
)}
- </Stack>
- </Group>
- )}
- <NormalizedLine
- itemKey={t("user")}
- value={
- <Group gap="xs" align="center" wrap="nowrap">
- <Avatar size="xs" src={item.user?.profilePictureUrl} />
- <Text size="sm" truncate>
- {item.user?.username ?? t("unknownUser")}
- </Text>
</Group>
- }
- />
- <NormalizedLine
- itemKey={t("name")}
- value={
- <Text size="sm" truncate>
- {item.sessionName}
- </Text>
- }
- />
- <NormalizedLine
- itemKey={t("id")}
- value={
- <Text size="xs" ff="monospace" truncate>
- {item.sessionId}
- </Text>
- }
- />
-
- {metadata ? (
- <Stack gap="xs">
- <Divider label={t("metadata.title")} labelPosition="left" />
- <SimpleGrid cols={{ base: 1, xs: 2 }} spacing="sm" verticalSpacing="xs">
- {objectEntries(metadata).map(([key, entries]) => (
- <Stack key={key} gap={4} style={{ minWidth: 0 }}>
- <Text fw={600} size="xs">
- {t(`metadata.${key}.title`)}
+ {progress !== null && (
+ <Stack gap={2}>
+ <Progress value={progress} size={4} color={playbackState === "paused" ? "yellow" : undefined} />
+ <Group justify="space-between" gap="xs" wrap="nowrap">
+ <Text fz={11} c="dimmed">
+ {position && duration ? t("details.position", { position, duration }) : null}
+ </Text>
+ <Text fz={11} c="dimmed">
+ {[
+ playbackStateLabel,
+ remainingMinutes !== null ? t("remaining", { minutes: remainingMinutes.toString() }) : null,
+ ]
+ .filter(Boolean)
+ .join(" · ")}
</Text>
- {Object.entries(entries)
- .filter(([_, entryValue]) => Boolean(entryValue))
- .map(([innerKey, entryValue]) => (
- <Group justify="space-between" gap="xs" key={innerKey} wrap="nowrap">
- <Text size="xs" c="dimmed">
- {t(`metadata.${key}.${innerKey}` as never)}
- </Text>
- <Text size="xs" ta="right" truncate>
- {entryValue}
- </Text>
- </Group>
- ))}
- </Stack>
- ))}
- </SimpleGrid>
+ </Group>
+ </Stack>
+ )}
</Stack>
- ) : null}
+ )}
+ <Divider />
+ <DetailGrid
+ entries={[
+ createEntry(
+ "user",
+ t("user"),
+ <Group gap={6} align="center" wrap="nowrap">
+ <Avatar size={16} src={item.user?.profilePictureUrl} />
+ <Text size="xs" fw={500} truncate>
+ {item.user?.username ?? t("unknownUser")}
+ </Text>
+ </Group>,
+ ),
+ createEntry("device", t("details.device"), item.sessionName),
+ createEntry("location", t("details.location"), location),
+ createEntry(
+ "resolution",
+ t("metadata.video.resolution"),
+ metadata ? formatResolution(metadata.video.resolution) : null,
+ ),
+ createEntry(
+ "frameRate",
+ t("metadata.video.frameRate"),
+ metadata ? formatFrameRate(metadata.video.frameRate) : null,
+ ),
+ createEntry("bitrate", t("details.bitrate"), metadata ? formatBitrate(metadata.bitrateKbps) : null),
+ createEntry("video", t("metadata.video.title"), videoHandling),
+ createEntry("audio", t("metadata.audio.title"), audioFormat),
+ createEntry("audioHandling", t("details.audioHandling"), audioHandling),
+ createEntry("container", t("metadata.transcoding.container"), container),
+ createEntry(
+ "id",
+ t("details.sessionId"),
+ <Text component="span" fz={11} ff="monospace" truncate>
+ {item.sessionId}
+ </Text>,
+ true,
+ ),
+ ]}
+ />
</Stack>
);
}
-const NormalizedLine = ({ itemKey, value }: { itemKey: string; value: ReactNode }) => {
- return (
- <Group w="100%" gap="md" align="flex-start" justify="space-between" wrap="nowrap">
- <Text size="sm" c="dimmed" style={{ flexShrink: 0 }}>
- {itemKey}:
- </Text>
- <Stack gap={0} align="flex-end" style={{ minWidth: 0 }}>
- {value}
- </Stack>
- </Group>
- );
-};
-
const mediaTypeIconMap = {
movie: IconMovie,
tv: IconDeviceTv,
video: IconVideo,
audio: IconHeadphones,
} satisfies Record<Exclude<StreamSession["currentlyPlaying"], null>["type"], TablerIcon>;
-
-const constructMetadata = (metadata: Exclude<Exclude<StreamSession["currentlyPlaying"], null>["metadata"], null>) => ({
- video: {
- resolution: metadata.video.resolution
- ? `${metadata.video.resolution.width}x${metadata.video.resolution.height}`
- : null,
- frameRate: metadata.video.frameRate,
- },
- audio: {
- channelCount: metadata.audio.channelCount,
- codec: metadata.audio.codec,
- },
- transcoding: {
- container: metadata.transcoding.container,
- resolution: metadata.transcoding.resolution
- ? `${metadata.transcoding.resolution.width}x${metadata.transcoding.resolution.height}`
- : null,
- target: `${metadata.transcoding.target.videoCodec} ${metadata.transcoding.target.audioCodec}`.trim(),
- },
-});