mirror of
https://github.com/redphx/better-xcloud.git
synced 2025-08-06 13:18:27 +02:00
Show stats in the Guide menu & refactor
This commit is contained in:
@@ -1,71 +1,91 @@
|
||||
import { t } from "@utils/translation";
|
||||
import { BxEvent } from "@utils/bx-event";
|
||||
import { CE } from "@utils/html";
|
||||
import { BxEvent, XcloudGuideWhere } from "@utils/bx-event";
|
||||
import { CE, createSvgIcon } from "@utils/html";
|
||||
import { STATES } from "@utils/global";
|
||||
import { BxLogger } from "@/utils/bx-logger";
|
||||
import { BxIcon } from "@/utils/bx-icon";
|
||||
|
||||
enum StreamBadge {
|
||||
PLAYTIME = 'playtime',
|
||||
BATTERY = 'battery',
|
||||
IN = 'in',
|
||||
OUT = 'out',
|
||||
DOWNLOAD = 'in',
|
||||
UPLOAD = 'out',
|
||||
|
||||
SERVER = 'server',
|
||||
VIDEO = 'video',
|
||||
AUDIO = 'audio',
|
||||
}
|
||||
|
||||
BREAK = 'break',
|
||||
const StreamBadgeIcon: Partial<{[key in StreamBadge]: any}> = {
|
||||
[StreamBadge.PLAYTIME]: BxIcon.PLAYTIME,
|
||||
[StreamBadge.VIDEO]: BxIcon.DISPLAY,
|
||||
[StreamBadge.BATTERY]: BxIcon.BATTERY,
|
||||
[StreamBadge.DOWNLOAD]: BxIcon.DOWNLOAD,
|
||||
[StreamBadge.UPLOAD]: BxIcon.UPLOAD,
|
||||
[StreamBadge.SERVER]: BxIcon.SERVER,
|
||||
[StreamBadge.AUDIO]: BxIcon.AUDIO,
|
||||
}
|
||||
|
||||
export class StreamBadges {
|
||||
static ipv6 = false;
|
||||
static resolution?: {width: number, height: number} | null = null;
|
||||
static video?: {codec: string, profile?: string | null} | null = null;
|
||||
static audio?: {codec: string, bitrate: number} | null = null;
|
||||
static fps = 0;
|
||||
static region = '';
|
||||
|
||||
static startBatteryLevel = 100;
|
||||
static startTimestamp = 0;
|
||||
|
||||
static #cachedDoms: {[index: string]: HTMLElement} = {};
|
||||
|
||||
static #interval?: number | null;
|
||||
static readonly #REFRESH_INTERVAL = 3000;
|
||||
|
||||
static #renderBadge(name: StreamBadge, value: string, color: string) {
|
||||
if (name === StreamBadge.BREAK) {
|
||||
return CE('div', {'style': 'display: block'});
|
||||
private static instance: StreamBadges;
|
||||
public static getInstance(): StreamBadges {
|
||||
if (!StreamBadges.instance) {
|
||||
StreamBadges.instance = new StreamBadges();
|
||||
}
|
||||
|
||||
return StreamBadges.instance;
|
||||
}
|
||||
|
||||
#ipv6 = false;
|
||||
#resolution?: {width: number, height: number} | null = null;
|
||||
#video?: {codec: string, profile?: string | null} | null = null;
|
||||
#audio?: {codec: string, bitrate: number} | null = null;
|
||||
#region = '';
|
||||
|
||||
startBatteryLevel = 100;
|
||||
startTimestamp = 0;
|
||||
|
||||
#$container: HTMLElement | undefined;
|
||||
#cachedDoms: Partial<{[key in StreamBadge]: HTMLElement}> = {};
|
||||
|
||||
#interval?: number | null;
|
||||
readonly #REFRESH_INTERVAL = 3000;
|
||||
|
||||
setRegion(region: string) {
|
||||
this.#region = region;
|
||||
}
|
||||
|
||||
#renderBadge(name: StreamBadge, value: string, color: string) {
|
||||
let $badge;
|
||||
if (StreamBadges.#cachedDoms[name]) {
|
||||
$badge = StreamBadges.#cachedDoms[name];
|
||||
if (this.#cachedDoms[name]) {
|
||||
$badge = this.#cachedDoms[name]!;
|
||||
$badge.lastElementChild!.textContent = value;
|
||||
return $badge;
|
||||
}
|
||||
|
||||
$badge = CE('div', {'class': 'bx-badge'},
|
||||
CE('span', {'class': 'bx-badge-name'}, t(`badge-${name}`)),
|
||||
CE('span', {'class': 'bx-badge-value', 'style': `background-color: ${color}`}, value));
|
||||
$badge = CE('div', {'class': 'bx-badge', 'title': t(`badge-${name}`)},
|
||||
CE('span', {'class': 'bx-badge-name'}, createSvgIcon(StreamBadgeIcon[name])),
|
||||
CE('span', {'class': 'bx-badge-value', 'style': `background-color: ${color}`}, value),
|
||||
);
|
||||
|
||||
if (name === StreamBadge.BATTERY) {
|
||||
$badge.classList.add('bx-badge-battery');
|
||||
}
|
||||
|
||||
StreamBadges.#cachedDoms[name] = $badge;
|
||||
this.#cachedDoms[name] = $badge;
|
||||
return $badge;
|
||||
}
|
||||
|
||||
static async #updateBadges(forceUpdate: boolean) {
|
||||
if (!forceUpdate && !document.querySelector('.bx-badges')) {
|
||||
StreamBadges.#stop();
|
||||
async #updateBadges(forceUpdate = false) {
|
||||
if (!this.#$container || (!forceUpdate && !this.#$container.isConnected)) {
|
||||
this.#stop();
|
||||
return;
|
||||
}
|
||||
|
||||
// Playtime
|
||||
let now = +new Date;
|
||||
const diffSeconds = Math.ceil((now - StreamBadges.startTimestamp) / 1000);
|
||||
const playtime = StreamBadges.#secondsToHm(diffSeconds);
|
||||
const diffSeconds = Math.ceil((now - this.startTimestamp) / 1000);
|
||||
const playtime = this.#secondsToHm(diffSeconds);
|
||||
|
||||
// Battery
|
||||
let batteryLevel = '100%';
|
||||
@@ -78,8 +98,8 @@ export class StreamBadges {
|
||||
batteryLevelInt = Math.round(bm.level * 100);
|
||||
batteryLevel = `${batteryLevelInt}%`;
|
||||
|
||||
if (batteryLevelInt != StreamBadges.startBatteryLevel) {
|
||||
const diffLevel = Math.round(batteryLevelInt - StreamBadges.startBatteryLevel);
|
||||
if (batteryLevelInt != this.startBatteryLevel) {
|
||||
const diffLevel = Math.round(batteryLevelInt - this.startBatteryLevel);
|
||||
const sign = diffLevel > 0 ? '+' : '';
|
||||
batteryLevel += ` (${sign}${diffLevel}%)`;
|
||||
}
|
||||
@@ -97,8 +117,8 @@ export class StreamBadges {
|
||||
});
|
||||
|
||||
const badges = {
|
||||
[StreamBadge.IN]: totalIn ? StreamBadges.#humanFileSize(totalIn) : null,
|
||||
[StreamBadge.OUT]: totalOut ? StreamBadges.#humanFileSize(totalOut) : null,
|
||||
[StreamBadge.DOWNLOAD]: totalIn ? this.#humanFileSize(totalIn) : null,
|
||||
[StreamBadge.UPLOAD]: totalOut ? this.#humanFileSize(totalOut) : null,
|
||||
[StreamBadge.PLAYTIME]: playtime,
|
||||
[StreamBadge.BATTERY]: batteryLevel,
|
||||
};
|
||||
@@ -110,28 +130,34 @@ export class StreamBadges {
|
||||
continue;
|
||||
}
|
||||
|
||||
const $elm = StreamBadges.#cachedDoms[name];
|
||||
const $elm = this.#cachedDoms[name]!;
|
||||
$elm && ($elm.lastElementChild!.textContent = value);
|
||||
|
||||
if (name === StreamBadge.BATTERY) {
|
||||
// Show charging status
|
||||
$elm.setAttribute('data-charging', isCharging.toString());
|
||||
|
||||
if (StreamBadges.startBatteryLevel === 100 && batteryLevelInt === 100) {
|
||||
$elm.style.display = 'none';
|
||||
if (this.startBatteryLevel === 100 && batteryLevelInt === 100) {
|
||||
// Hide battery badge when the battery is 100%
|
||||
$elm.classList.add('bx-gone');
|
||||
} else {
|
||||
$elm.removeAttribute('style');
|
||||
// Show charging status
|
||||
$elm.dataset.charging = isCharging.toString()
|
||||
$elm.classList.remove('bx-gone');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static #stop() {
|
||||
StreamBadges.#interval && clearInterval(StreamBadges.#interval);
|
||||
StreamBadges.#interval = null;
|
||||
async #start() {
|
||||
await this.#updateBadges(true);
|
||||
this.#stop();
|
||||
this.#interval = window.setInterval(this.#updateBadges.bind(this), this.#REFRESH_INTERVAL);
|
||||
}
|
||||
|
||||
static #secondsToHm(seconds: number) {
|
||||
#stop() {
|
||||
this.#interval && clearInterval(this.#interval);
|
||||
this.#interval = null;
|
||||
}
|
||||
|
||||
#secondsToHm(seconds: number) {
|
||||
const h = Math.floor(seconds / 3600);
|
||||
const m = Math.floor(seconds % 3600 / 60) + 1;
|
||||
|
||||
@@ -141,25 +167,32 @@ export class StreamBadges {
|
||||
}
|
||||
|
||||
// https://stackoverflow.com/a/20732091
|
||||
static #humanFileSize(size: number) {
|
||||
const units = ['B', 'kB', 'MB', 'GB', 'TB'];
|
||||
#humanFileSize(size: number) {
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||
|
||||
let i = size == 0 ? 0 : Math.floor(Math.log(size) / Math.log(1024));
|
||||
return (size / Math.pow(1024, i)).toFixed(2) + ' ' + units[i];
|
||||
}
|
||||
|
||||
static async render() {
|
||||
// Video
|
||||
let video = '';
|
||||
if (StreamBadges.resolution) {
|
||||
video = `${StreamBadges.resolution.height}p`;
|
||||
async render() {
|
||||
if (this.#$container) {
|
||||
this.#start();
|
||||
return this.#$container;
|
||||
}
|
||||
|
||||
if (StreamBadges.video) {
|
||||
await this.#getServerStats();
|
||||
|
||||
// Video
|
||||
let video = '';
|
||||
if (this.#resolution) {
|
||||
video = `${this.#resolution.height}p`;
|
||||
}
|
||||
|
||||
if (this.#video) {
|
||||
video && (video += '/');
|
||||
video += StreamBadges.video.codec;
|
||||
if (StreamBadges.video.profile) {
|
||||
const profile = StreamBadges.video.profile;
|
||||
video += this.#video.codec;
|
||||
if (this.#video.profile) {
|
||||
const profile = this.#video.profile;
|
||||
|
||||
let quality = profile;
|
||||
if (profile.startsWith('4d')) {
|
||||
@@ -176,9 +209,9 @@ export class StreamBadges {
|
||||
|
||||
// Audio
|
||||
let audio;
|
||||
if (StreamBadges.audio) {
|
||||
audio = StreamBadges.audio.codec;
|
||||
const bitrate = StreamBadges.audio.bitrate / 1000;
|
||||
if (this.#audio) {
|
||||
audio = this.#audio.codec;
|
||||
const bitrate = this.#audio.bitrate / 1000;
|
||||
audio += ` (${bitrate} kHz)`;
|
||||
}
|
||||
|
||||
@@ -189,53 +222,133 @@ export class StreamBadges {
|
||||
}
|
||||
|
||||
// Server + Region
|
||||
let server = StreamBadges.region;
|
||||
server += '@' + (StreamBadges.ipv6 ? 'IPv6' : 'IPv4');
|
||||
let server = this.#region;
|
||||
server += '@' + (this.#ipv6 ? 'IPv6' : 'IPv4');
|
||||
|
||||
const BADGES = [
|
||||
[StreamBadge.PLAYTIME, '1m', '#ff004d'],
|
||||
[StreamBadge.BATTERY, batteryLevel, '#00b543'],
|
||||
[StreamBadge.IN, StreamBadges.#humanFileSize(0), '#29adff'],
|
||||
[StreamBadge.OUT, StreamBadges.#humanFileSize(0), '#ff77a8'],
|
||||
[StreamBadge.BREAK],
|
||||
[StreamBadge.DOWNLOAD, this.#humanFileSize(0), '#29adff'],
|
||||
[StreamBadge.UPLOAD, this.#humanFileSize(0), '#ff77a8'],
|
||||
[StreamBadge.SERVER, server, '#ff6c24'],
|
||||
video ? [StreamBadge.VIDEO, video, '#742f29'] : null,
|
||||
audio ? [StreamBadge.AUDIO, audio, '#5f574f'] : null,
|
||||
];
|
||||
|
||||
const $wrapper = CE('div', {'class': 'bx-badges'});
|
||||
const $container = CE('div', {'class': 'bx-badges'});
|
||||
BADGES.forEach(item => {
|
||||
if (!item) {
|
||||
return;
|
||||
}
|
||||
|
||||
const $badge = StreamBadges.#renderBadge(...(item as [StreamBadge, string, string]));
|
||||
$wrapper.appendChild($badge);
|
||||
const $badge = this.#renderBadge(...(item as [StreamBadge, string, string]));
|
||||
$container.appendChild($badge);
|
||||
});
|
||||
|
||||
await StreamBadges.#updateBadges(true);
|
||||
StreamBadges.#stop();
|
||||
StreamBadges.#interval = window.setInterval(StreamBadges.#updateBadges, StreamBadges.#REFRESH_INTERVAL);
|
||||
this.#$container = $container;
|
||||
await this.#start();
|
||||
|
||||
return $wrapper;
|
||||
return $container;
|
||||
}
|
||||
|
||||
async #getServerStats() {
|
||||
const stats = await STATES.currentStream.peerConnection!.getStats();
|
||||
|
||||
const allVideoCodecs: {[index: string]: RTCBasicStat} = {};
|
||||
let videoCodecId;
|
||||
|
||||
const allAudioCodecs: {[index: string]: RTCBasicStat} = {};
|
||||
let audioCodecId;
|
||||
|
||||
const allCandidates: {[index: string]: string} = {};
|
||||
let candidateId;
|
||||
|
||||
stats.forEach((stat: RTCBasicStat) => {
|
||||
if (stat.type === 'codec') {
|
||||
const mimeType = stat.mimeType.split('/')[0];
|
||||
if (mimeType === 'video') {
|
||||
// Store all video stats
|
||||
allVideoCodecs[stat.id] = stat;
|
||||
} else if (mimeType === 'audio') {
|
||||
// Store all audio stats
|
||||
allAudioCodecs[stat.id] = stat;
|
||||
}
|
||||
} else if (stat.type === 'inbound-rtp' && stat.packetsReceived > 0) {
|
||||
// Get the codecId of the video/audio track currently being used
|
||||
if (stat.kind === 'video') {
|
||||
videoCodecId = stat.codecId;
|
||||
} else if (stat.kind === 'audio') {
|
||||
audioCodecId = stat.codecId;
|
||||
}
|
||||
} else if (stat.type === 'candidate-pair' && stat.packetsReceived > 0 && stat.state === 'succeeded') {
|
||||
candidateId = stat.remoteCandidateId;
|
||||
} else if (stat.type === 'remote-candidate') {
|
||||
allCandidates[stat.id] = stat.address;
|
||||
}
|
||||
});
|
||||
|
||||
// Get video codec from codecId
|
||||
if (videoCodecId) {
|
||||
const videoStat = allVideoCodecs[videoCodecId];
|
||||
const video: any = {
|
||||
codec: videoStat.mimeType.substring(6),
|
||||
};
|
||||
|
||||
if (video.codec === 'H264') {
|
||||
const match = /profile-level-id=([0-9a-f]{6})/.exec(videoStat.sdpFmtpLine);
|
||||
video.profile = match ? match[1] : null;
|
||||
}
|
||||
|
||||
this.#video = video;
|
||||
}
|
||||
|
||||
// Get audio codec from codecId
|
||||
if (audioCodecId) {
|
||||
const audioStat = allAudioCodecs[audioCodecId];
|
||||
this.#audio = {
|
||||
codec: audioStat.mimeType.substring(6),
|
||||
bitrate: audioStat.clockRate,
|
||||
}
|
||||
}
|
||||
|
||||
// Get server type
|
||||
if (candidateId) {
|
||||
BxLogger.info('candidate', candidateId, allCandidates);
|
||||
this.#ipv6 = allCandidates[candidateId].includes(':');
|
||||
}
|
||||
}
|
||||
|
||||
static setupEvents() {
|
||||
window.addEventListener(BxEvent.STREAM_PLAYING, e => {
|
||||
const $video = (e as any).$video;
|
||||
const streamBadges = StreamBadges.getInstance();
|
||||
|
||||
StreamBadges.resolution = {
|
||||
streamBadges.#resolution = {
|
||||
width: $video.videoWidth,
|
||||
height: $video.videoHeight
|
||||
height: $video.videoHeight,
|
||||
};
|
||||
StreamBadges.startTimestamp = +new Date;
|
||||
streamBadges.startTimestamp = +new Date;
|
||||
|
||||
// Get battery level
|
||||
try {
|
||||
'getBattery' in navigator && (navigator as NavigatorBattery).getBattery().then(bm => {
|
||||
StreamBadges.startBatteryLevel = Math.round(bm.level * 100);
|
||||
streamBadges.startBatteryLevel = Math.round(bm.level * 100);
|
||||
});
|
||||
} catch(e) {}
|
||||
});
|
||||
|
||||
window.addEventListener(BxEvent.XCLOUD_GUIDE_SHOWN, async e => {
|
||||
const where = (e as any).where as XcloudGuideWhere;
|
||||
|
||||
if (where === XcloudGuideWhere.HOME && STATES.isPlaying) {
|
||||
const $btnQuit = document.querySelector('#gamepass-dialog-root a[class*=QuitGameButton]');
|
||||
if (!$btnQuit) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Add badges
|
||||
$btnQuit.insertAdjacentElement('beforebegin', await StreamBadges.getInstance().render());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user