Keep /api/health instant, isolate ffmpeg cgroups, defer clip encodes while live push runs, and align dy.live systemd with dylive. README covers the hang root cause and /yt-revenue. Co-authored-by: Cursor <cursoragent@cursor.com>
339 lines
11 KiB
JavaScript
339 lines
11 KiB
JavaScript
const LIVE_HUB_MIN_INTERVAL_MS = 4000;
|
||
let lastSentAt = 0;
|
||
let lastSignature = "";
|
||
let observerQueued = false;
|
||
|
||
function cleanText(value, max = 260) {
|
||
return String(value || "")
|
||
.replace(/\s+/g, " ")
|
||
.trim()
|
||
.slice(0, max);
|
||
}
|
||
|
||
/** Pause Studio preview videos / mute — biggest RAM leak on livestreaming page. */
|
||
function tameMedia() {
|
||
try {
|
||
document.querySelectorAll("video, audio").forEach((el) => {
|
||
try {
|
||
el.muted = true;
|
||
el.pause();
|
||
// Keep element for UI, but stop decoding frames.
|
||
if (typeof el.disablePictureInPicture === "boolean") el.disablePictureInPicture = true;
|
||
} catch (_) {}
|
||
});
|
||
} catch (_) {}
|
||
}
|
||
|
||
function injectMemCss() {
|
||
if (document.getElementById("livehub-mem-css")) return;
|
||
const style = document.createElement("style");
|
||
style.id = "livehub-mem-css";
|
||
style.textContent = `
|
||
/* Shrink heavy Live Control Room surfaces on low-RAM Neko hosts */
|
||
ytls-live-dashboard-section-renderer video,
|
||
ytls-stream-preview-section-renderer video,
|
||
#preview-player video,
|
||
.html5-video-player video {
|
||
max-height: 180px !important;
|
||
object-fit: contain !important;
|
||
}
|
||
ytls-live-dashboard-chart,
|
||
ytcp-ve[class*="chart"],
|
||
[class*="analytics-chart"] {
|
||
max-height: 120px !important;
|
||
overflow: hidden !important;
|
||
}
|
||
`;
|
||
(document.head || document.documentElement).appendChild(style);
|
||
}
|
||
|
||
function pageText() {
|
||
return cleanText(document.body?.innerText || "", 6000);
|
||
}
|
||
|
||
function parseCompactNumber(raw) {
|
||
const text = cleanText(raw, 40).replace(/,/g, "");
|
||
const match = text.match(/(\d+(?:\.\d+)?)([kKmMwW万]*)/);
|
||
if (!match) return null;
|
||
let value = Number(match[1]);
|
||
const unit = match[2].toLowerCase();
|
||
if (unit === "k") value *= 1000;
|
||
if (unit === "m") value *= 1000000;
|
||
if (unit === "w" || unit === "万") value *= 10000;
|
||
return Number.isFinite(value) ? Math.round(value) : null;
|
||
}
|
||
|
||
function firstNumberByPatterns(text, patterns) {
|
||
for (const pattern of patterns) {
|
||
const match = text.match(pattern);
|
||
if (match) {
|
||
const parsed = parseCompactNumber(match[1]);
|
||
if (parsed != null) return parsed;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function detectNodata(text) {
|
||
const lower = text.toLowerCase();
|
||
// Studio encoder badge: "No data" / NODATA / 无数据
|
||
return /(?:^|[^a-z])no\s*data(?:[^a-z]|$)|nodata|无数据|尚未收到数据|没有数据/.test(lower);
|
||
}
|
||
|
||
/** YouTube Live session already started (LIVE pill + timer / End Stream). */
|
||
function detectSessionLive(text) {
|
||
const lower = text.toLowerCase();
|
||
const hasTimer =
|
||
/\blive\b[\s\S]{0,48}\d{1,2}:\d{2}(?::\d{2})?/.test(lower) ||
|
||
/(?:直播时长|已直播)\s*[::]?\s*\d{1,2}:\d{2}/.test(text);
|
||
const hasEnd =
|
||
/end stream|stop streaming|结束直播|停止直播/.test(lower);
|
||
return Boolean(hasTimer && hasEnd) || Boolean(hasTimer && /\blive\b/.test(lower));
|
||
}
|
||
|
||
/** Encoder dropped while session still live — 断播 (not 待开播). */
|
||
function detectEncoderLost(text) {
|
||
const lower = text.toLowerCase();
|
||
if (/will end shortly|restart it in your streaming software|unless you restart/.test(lower)) {
|
||
return true;
|
||
}
|
||
if (/(?:即将结束|请重新|重新启动|推流软件|编码器.*断开|断流)/.test(text)) {
|
||
return true;
|
||
}
|
||
return detectSessionLive(text) && detectNodata(text);
|
||
}
|
||
|
||
/**
|
||
* Studio states we must not confuse:
|
||
* - waiting / 待开播: control room open, broadcast not started
|
||
* - live / 开播: session live + encoder has data
|
||
* - encoder_lost / 断播: session still live, encoder NODATA / will end shortly
|
||
* - ended / 停播: stream ended
|
||
*/
|
||
function detectLiveStatus(text) {
|
||
const lower = text.toLowerCase();
|
||
if (/stream ended|直播已结束|未在直播/.test(lower) && !detectSessionLive(text)) {
|
||
return "ended";
|
||
}
|
||
const sessionLive = detectSessionLive(text);
|
||
const nodata = detectNodata(text);
|
||
if (sessionLive && (detectEncoderLost(text) || nodata)) {
|
||
return "encoder_lost";
|
||
}
|
||
if (sessionLive) {
|
||
return "live";
|
||
}
|
||
// True 待开播: no LIVE session yet
|
||
if (
|
||
nodata ||
|
||
/connect your encoder|stream offline|not streaming|waiting for you to start|待开播|等待你开始|start sending us your video/.test(
|
||
lower
|
||
)
|
||
) {
|
||
return "waiting";
|
||
}
|
||
if (
|
||
/you'?re live|you are live|excellent connection|stream is healthy|concurrent viewers|watching now|直播中|正在直播|已开始直播/.test(
|
||
lower
|
||
)
|
||
) {
|
||
return "live";
|
||
}
|
||
if (/waiting|preview|scheduled|等待|预定|未开始/.test(lower)) return "waiting";
|
||
if (/error|failed|copyright|policy|异常|错误|受限|违规/.test(lower)) return "attention";
|
||
return "";
|
||
}
|
||
|
||
function detectHealth(text) {
|
||
const lower = text.toLowerCase();
|
||
if (/excellent connection|stream is healthy|health excellent|连接状况极佳|状况良好/.test(lower)) return "excellent";
|
||
if (/good connection|healthy|良好/.test(lower)) return "good";
|
||
if (/unstable|poor|buffer|warning|警告|不稳定|不佳|卡顿/.test(lower)) return "warning";
|
||
if (/error|failed|disconnect|异常|错误|断开/.test(lower)) return "error";
|
||
return "";
|
||
}
|
||
|
||
/** LIVE pill duration e.g. "37:06" or "1:19:36" → seconds */
|
||
function parseLiveDuration(text) {
|
||
const match =
|
||
text.match(/\bLIVE\b\s*(\d{1,2}:\d{2}(?::\d{2})?)/i) ||
|
||
text.match(/(?:直播时长|已直播)\s*[::]?\s*(\d{1,2}:\d{2}(?::\d{2})?)/i);
|
||
if (!match) return { live_duration: "", live_duration_sec: null };
|
||
const raw = match[1];
|
||
const parts = raw.split(":").map((x) => Number(x));
|
||
let sec = null;
|
||
if (parts.length === 3 && parts.every((n) => Number.isFinite(n))) {
|
||
sec = parts[0] * 3600 + parts[1] * 60 + parts[2];
|
||
} else if (parts.length === 2 && parts.every((n) => Number.isFinite(n))) {
|
||
sec = parts[0] * 60 + parts[1];
|
||
}
|
||
return { live_duration: raw, live_duration_sec: sec };
|
||
}
|
||
|
||
/** Analytics tab cumulative Views (not concurrent). */
|
||
function parseTotalViews(text) {
|
||
// Prefer labeled "Views" / 观看次数, avoid "Concurrent viewers"
|
||
const patterns = [
|
||
/(?:^|\n)\s*Views\s*\n\s*([\d,.]+[kKmMwW万]?)/i,
|
||
/\bViews\b(?!\s*per)\s*[::]?\s*([\d,.]+[kKmMwW万]?)/i,
|
||
/(?:总观看|观看次数|观看量)\s*[::]?\s*([\d,.]+[kKmMwW万]?)/,
|
||
];
|
||
for (const pattern of patterns) {
|
||
const match = text.match(pattern);
|
||
if (!match) continue;
|
||
// Reject if this is clearly the concurrent line
|
||
const around = text.slice(Math.max(0, (match.index || 0) - 24), (match.index || 0) + 40).toLowerCase();
|
||
if (/concurrent/.test(around)) continue;
|
||
const parsed = parseCompactNumber(match[1]);
|
||
if (parsed != null) return parsed;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function collectPopupTexts() {
|
||
const selectors = [
|
||
"[role='dialog']",
|
||
"[aria-live='assertive']",
|
||
"[aria-live='polite']",
|
||
"ytcp-toast",
|
||
"tp-yt-paper-toast",
|
||
"paper-dialog",
|
||
"ytcp-alert",
|
||
"ytcp-ve",
|
||
];
|
||
const out = [];
|
||
for (const node of document.querySelectorAll(selectors.join(","))) {
|
||
const rect = node.getBoundingClientRect?.();
|
||
if (rect && rect.width === 0 && rect.height === 0) continue;
|
||
const text = cleanText(node.innerText || node.textContent || "", 500);
|
||
if (text && !out.includes(text)) out.push(text);
|
||
if (out.length >= 8) break;
|
||
}
|
||
return out;
|
||
}
|
||
|
||
function collectStreamTitle() {
|
||
const selectors = [
|
||
"input[aria-label*='Title']",
|
||
"textarea[aria-label*='Title']",
|
||
"ytcp-social-suggestions-textbox",
|
||
"ytcp-video-title",
|
||
"h1",
|
||
];
|
||
for (const selector of selectors) {
|
||
const node = document.querySelector(selector);
|
||
const value = node?.value || node?.innerText || node?.textContent;
|
||
const text = cleanText(value, 180);
|
||
if (text) return text;
|
||
}
|
||
return cleanText(document.title, 180);
|
||
}
|
||
|
||
function collectTelemetry() {
|
||
const text = pageText();
|
||
const viewerCount = firstNumberByPatterns(text, [
|
||
/([\d,.]+[kKmMwW万]?)\s*(?:watching|concurrent viewers)/i,
|
||
/(?:concurrent viewers|watching now|同时观看)\s*[::]?\s*([\d,.]+[kKmMwW万]?)/i,
|
||
/([\d,.]+[kKmMwW万]?)\s*(?:人正在观看|正在观看)/,
|
||
]);
|
||
const likeCount = firstNumberByPatterns(text, [
|
||
/([\d,.]+[kKmMwW万]?)\s*(?:likes|like count)/i,
|
||
/([\d,.]+[kKmMwW万]?)\s*(?:点赞|赞)/,
|
||
]);
|
||
const dur = parseLiveDuration(text);
|
||
const totalViews = parseTotalViews(text);
|
||
const popups = collectPopupTexts();
|
||
const liveStatus = detectLiveStatus(text);
|
||
const nodata = detectNodata(text);
|
||
const sessionLive = detectSessionLive(text) || liveStatus === "live" || liveStatus === "encoder_lost";
|
||
const encoderLost = liveStatus === "encoder_lost" || detectEncoderLost(text);
|
||
const health = detectHealth(text);
|
||
// 开播中且有码流;绿点 preview(未点 Go Live)不算 live
|
||
const encoderReceiving =
|
||
!nodata &&
|
||
!encoderLost &&
|
||
(liveStatus === "live" ||
|
||
Boolean(health) ||
|
||
/starting|receiving|connecting|正在接收|连接中|缓冲/.test(text.toLowerCase()));
|
||
const pendingGoLive = liveStatus === "waiting" && !sessionLive && !encoderLost;
|
||
const payload = {
|
||
captured_at: Date.now() / 1000,
|
||
source: "chrome_extension",
|
||
url: location.href,
|
||
page_title: document.title,
|
||
stream_title: collectStreamTitle(),
|
||
live_status: liveStatus,
|
||
health,
|
||
viewer_count: viewerCount,
|
||
like_count: likeCount,
|
||
total_views: totalViews,
|
||
live_duration: dur.live_duration,
|
||
live_duration_sec: dur.live_duration_sec,
|
||
popups,
|
||
text: text.slice(0, 2200),
|
||
signals: {
|
||
has_dialog: popups.length > 0,
|
||
visibility: document.visibilityState,
|
||
focused: document.hasFocus(),
|
||
path: location.pathname,
|
||
nodata,
|
||
encoder_receiving: encoderReceiving,
|
||
encoder_lost: encoderLost,
|
||
session_live: sessionLive,
|
||
pending_go_live: pendingGoLive,
|
||
},
|
||
};
|
||
return payload;
|
||
}
|
||
|
||
function signatureOf(payload) {
|
||
return JSON.stringify([
|
||
payload.url,
|
||
payload.live_status,
|
||
payload.health,
|
||
payload.viewer_count,
|
||
payload.like_count,
|
||
payload.total_views,
|
||
payload.live_duration,
|
||
payload.popups,
|
||
payload.stream_title,
|
||
]);
|
||
}
|
||
|
||
function sendTelemetry(force = false) {
|
||
const now = Date.now();
|
||
if (!force && now - lastSentAt < LIVE_HUB_MIN_INTERVAL_MS) return;
|
||
const payload = collectTelemetry();
|
||
const sig = signatureOf(payload);
|
||
if (!force && sig === lastSignature && now - lastSentAt < 10000) return;
|
||
lastSentAt = now;
|
||
lastSignature = sig;
|
||
if (/studio\.youtube\.com\/.*\/livestreaming/.test(location.href)) {
|
||
chrome.storage.local.set({ lastLiveStudioUrl: location.href });
|
||
}
|
||
chrome.runtime.sendMessage({ type: "live-hub-youtube-telemetry", payload }, () => {
|
||
void chrome.runtime.lastError;
|
||
});
|
||
}
|
||
|
||
const observer = new MutationObserver(() => {
|
||
if (observerQueued) return;
|
||
observerQueued = true;
|
||
setTimeout(() => {
|
||
observerQueued = false;
|
||
sendTelemetry(false);
|
||
}, 2500);
|
||
});
|
||
// characterData on Studio Live fires constantly (viewer ticks) and burns RAM/CPU.
|
||
observer.observe(document.documentElement, { subtree: true, childList: true });
|
||
window.addEventListener("focus", () => sendTelemetry(true));
|
||
document.addEventListener("visibilitychange", () => sendTelemetry(true));
|
||
injectMemCss();
|
||
tameMedia();
|
||
setInterval(() => {
|
||
injectMemCss();
|
||
tameMedia();
|
||
sendTelemetry(false);
|
||
}, 12000);
|
||
sendTelemetry(true);
|