Skip to content

Commit 14eb29a

Browse files
committed
fix: renew the YouTube identity before its hourly player limit
1 parent 90829b3 commit 14eb29a

3 files changed

Lines changed: 155 additions & 2 deletions

File tree

‎src/youtube-identity-budget.ts‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
// YouTube stops playing anything to one visitor identity after roughly 900 player requests in an hour: it answers
2+
// UNPLAYABLE "Video unavailable" until its window resets, while a fresh identity on the same address plays at once
3+
// (measured on 2026-11-25). The budget renews the identity in the background well before that point, and right away
4+
// when several different videos are refused in a row with no success between them.
5+
export const ROTATE_AFTER_PLAYER_CALLS = 500;
6+
export const REFUSALS_BEFORE_ROTATION = 3;
7+
export const REFUSAL_WINDOW_MS = 60_000;
8+
const KEPT_IDENTITIES = 8;
9+
10+
export function isIdentityRefusal(status?: string, reason?: string): boolean {
11+
return status === "UNPLAYABLE" && (reason?.toLowerCase().includes("unavailable") ?? false);
12+
}
13+
14+
export class YoutubeIdentityBudget {
15+
private readonly calls = new Map<string, number>();
16+
private readonly refusals = new Map<string, Map<string, number>>();
17+
18+
constructor(private readonly now: () => number = Date.now) {}
19+
20+
/** Counts one player request; true from the limit on, until a new identity is in use. */
21+
notePlayerCall(visitorData: string): boolean {
22+
const calls = (this.calls.get(visitorData) ?? 0) + 1;
23+
this.calls.set(visitorData, calls);
24+
trim(this.calls);
25+
return calls >= ROTATE_AFTER_PLAYER_CALLS;
26+
}
27+
28+
noteSuccess(visitorData: string): void {
29+
this.refusals.delete(visitorData);
30+
}
31+
32+
/** Records a refused video; true when the identity looks used up and must be renewed before retrying. */
33+
noteRefusal(visitorData: string, videoId: string): boolean {
34+
const now = this.now();
35+
const recent = this.refusals.get(visitorData) ?? new Map<string, number>();
36+
for (const [id, at] of recent) {
37+
if (now - at > REFUSAL_WINDOW_MS) recent.delete(id);
38+
}
39+
recent.set(videoId, now);
40+
this.refusals.set(visitorData, recent);
41+
trim(this.refusals);
42+
return recent.size >= REFUSALS_BEFORE_ROTATION;
43+
}
44+
45+
forget(visitorData: string): void {
46+
this.calls.delete(visitorData);
47+
this.refusals.delete(visitorData);
48+
}
49+
}
50+
51+
function trim<V>(byIdentity: Map<string, V>): void {
52+
for (const identity of byIdentity.keys()) {
53+
if (byIdentity.size <= KEPT_IDENTITIES) return;
54+
byIdentity.delete(identity);
55+
}
56+
}
57+
58+
export const youtubeIdentityBudget = new YoutubeIdentityBudget();

‎src/youtube-sabr-session.ts‎

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@ import { buildSabrFormat } from "googlevideo/utils";
22
import { type IPlayerResponse, YTNodes } from "youtubei.js";
33
import { KeyedSingleFlight } from "./keyed-single-flight.ts";
44
import { type PlaybackTraceContext, playbackTraceEvent } from "./playback-diagnostics.ts";
5-
import { fetchPoToken } from "./token-service.ts";
5+
import { fetchPoToken, getOrRefreshSession } from "./token-service.ts";
66
import { findYoutubeChannelAvatarUrl } from "./youtube-channel-avatar.ts";
77
import {
88
cacheYoutubeChannelAvatar,
99
getCachedYoutubeChannelAvatar,
1010
} from "./youtube-channel-avatar-cache.ts";
1111
import { decipherHlsManifestUrl } from "./youtube-hls-manifest-url.ts";
12+
import { isIdentityRefusal, youtubeIdentityBudget } from "./youtube-identity-budget.ts";
1213
import {
1314
getYoutubeInnertube,
1415
isRejectedAnonymousSession,
@@ -63,8 +64,14 @@ async function loadYoutubeSabrSession(
6364
reloadPlaybackParamsToken,
6465
),
6566
);
67+
notePlayerCall(tokens.visitorData);
6668
const playability = videoInfo.playability_status;
67-
if (isRejectedAnonymousSession(playability?.status, playability?.reason)) {
69+
const usedUp =
70+
isIdentityRefusal(playability?.status, playability?.reason) &&
71+
youtubeIdentityBudget.noteRefusal(tokens.visitorData, videoId);
72+
if (usedUp || isRejectedAnonymousSession(playability?.status, playability?.reason)) {
73+
if (usedUp) console.log(`[identity] renewing after refusals, videoId=${videoId}`);
74+
youtubeIdentityBudget.forget(tokens.visitorData);
6875
const refreshed = await perf.measure("identityRefresh", () =>
6976
youtubeSabrIdentityRefresher.refresh(videoId, client, tokens.visitorData, innertube, trace),
7077
);
@@ -78,13 +85,15 @@ async function loadYoutubeSabrSession(
7885
reloadPlaybackParamsToken,
7986
),
8087
);
88+
notePlayerCall(tokens.visitorData);
8189
}
8290
if (videoInfo.playability_status?.status !== "OK") {
8391
throw new Error(
8492
`YouTube ${client} player response is ${videoInfo.playability_status?.status ?? "missing"}: ${videoInfo.playability_status?.reason ?? "no reason"}`,
8593
);
8694
}
8795

96+
youtubeIdentityBudget.noteSuccess(tokens.visitorData);
8897
const channelAvatarUrl = getCachedYoutubeChannelAvatar(videoId) ?? "";
8998
if (!channelAvatarUrl) prefetchYoutubeChannelAvatar(videoId, innertube);
9099
const session = await perf.measure("sessionBuild", () =>
@@ -97,6 +106,17 @@ async function loadYoutubeSabrSession(
97106
}
98107
}
99108

109+
function notePlayerCall(visitorData: string): void {
110+
if (!youtubeIdentityBudget.notePlayerCall(visitorData)) return;
111+
void getOrRefreshSession(true)
112+
.then((session) => {
113+
if (session.visitorData === visitorData) return;
114+
youtubeIdentityBudget.forget(visitorData);
115+
console.log("[identity] renewed in the background before YouTube's hourly limit");
116+
})
117+
.catch(() => undefined);
118+
}
119+
100120
async function fetchYoutubeResponses(
101121
videoId: string,
102122
innertube: YoutubeInnertube,
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { describe, expect, test } from "bun:test";
2+
import {
3+
isIdentityRefusal,
4+
REFUSAL_WINDOW_MS,
5+
ROTATE_AFTER_PLAYER_CALLS,
6+
YoutubeIdentityBudget,
7+
} from "../src/youtube-identity-budget.ts";
8+
9+
describe("YoutubeIdentityBudget", () => {
10+
test("asks for a background renewal on every call from the limit on", () => {
11+
const budget = new YoutubeIdentityBudget();
12+
const signals: number[] = [];
13+
for (let call = 1; call <= ROTATE_AFTER_PLAYER_CALLS + 2; call += 1) {
14+
if (budget.notePlayerCall("visitor-a")) signals.push(call);
15+
}
16+
expect(signals).toEqual([
17+
ROTATE_AFTER_PLAYER_CALLS,
18+
ROTATE_AFTER_PLAYER_CALLS + 1,
19+
ROTATE_AFTER_PLAYER_CALLS + 2,
20+
]);
21+
expect(budget.notePlayerCall("visitor-b")).toBe(false);
22+
});
23+
24+
test("renews after three different refused videos in a minute", () => {
25+
let now = 0;
26+
const budget = new YoutubeIdentityBudget(() => now);
27+
expect(budget.noteRefusal("visitor", "one")).toBe(false);
28+
now += 1_000;
29+
expect(budget.noteRefusal("visitor", "one")).toBe(false);
30+
expect(budget.noteRefusal("visitor", "two")).toBe(false);
31+
expect(budget.noteRefusal("visitor", "three")).toBe(true);
32+
});
33+
34+
test("a success between refusals means the videos were really unavailable", () => {
35+
const budget = new YoutubeIdentityBudget(() => 0);
36+
budget.noteRefusal("visitor", "one");
37+
budget.noteRefusal("visitor", "two");
38+
budget.noteSuccess("visitor");
39+
expect(budget.noteRefusal("visitor", "three")).toBe(false);
40+
});
41+
42+
test("old refusals fall out of the window", () => {
43+
let now = 0;
44+
const budget = new YoutubeIdentityBudget(() => now);
45+
budget.noteRefusal("visitor", "one");
46+
budget.noteRefusal("visitor", "two");
47+
now += REFUSAL_WINDOW_MS + 1;
48+
expect(budget.noteRefusal("visitor", "three")).toBe(false);
49+
});
50+
51+
test("refusals are counted per identity", () => {
52+
const budget = new YoutubeIdentityBudget(() => 0);
53+
budget.noteRefusal("old", "one");
54+
budget.noteRefusal("old", "two");
55+
expect(budget.noteRefusal("new", "three")).toBe(false);
56+
});
57+
58+
test("keeps counters for the last identities only", () => {
59+
const budget = new YoutubeIdentityBudget();
60+
for (let call = 1; call < ROTATE_AFTER_PLAYER_CALLS; call += 1) budget.notePlayerCall("first");
61+
for (let identity = 0; identity < 8; identity += 1) budget.notePlayerCall(`other-${identity}`);
62+
expect(budget.notePlayerCall("first")).toBe(false);
63+
});
64+
65+
test("only an unavailable answer counts as a refusal", () => {
66+
expect(isIdentityRefusal("UNPLAYABLE", "Video unavailable")).toBe(true);
67+
expect(isIdentityRefusal("UNPLAYABLE", "This video is unavailable")).toBe(true);
68+
expect(isIdentityRefusal("LOGIN_REQUIRED", "Sign in to confirm your age")).toBe(false);
69+
expect(isIdentityRefusal("UNPLAYABLE", "This live event will begin in a few moments.")).toBe(
70+
false,
71+
);
72+
expect(isIdentityRefusal("ERROR", "Video unavailable")).toBe(false);
73+
expect(isIdentityRefusal("OK")).toBe(false);
74+
});
75+
});

0 commit comments

Comments
 (0)