Skip to content

Commit 196f443

Browse files
committed
DRM: Second attempt to manage a maxSessionCacheSize on contents going over the limit
This is a retry of #1511 (I even re-used the same git branch) because I found the work in that PR to be too complex. If you already read the previous PR, you can skip the `The issue` below. The issue ========= Conditions ---------- This work is about a specific and for now never seen issue that has chance to pop up under the following conditions: - The current content make use of per-Period key rotation (NOTE: this is also possible without key rotation, but this is made much more probable by it). - The device on which we we play that content has a very limited number of key slots available simultaneously for decryption (sometimes **VERY** limited, e.g. `6`, so we can at most rely on 6 keys simultaneously. We for now know of four different set-top boxes with that type of limitation, from two constructors. The `maxSessionCacheSize` option --------------------------------------------- Theoretically, an application can rely there on the `keySystems[].maxSessionCacheSize` option to set a maximum number of `MediaKeySession` we may keep at at the same time. _Note that we prefer here to rely on a number of `MediaKeySession` and not of keys, because the RxPlayer is not able to predict how many keys it will find inside a license (NOTE: to simplify, let's just say that 1 `MediaKeySession` == 1 license here, as it's very predominantly the case) nor is it able to not communicate some keys that are found in a given license._ _Yet an application generally has a rough idea of how many keys it's going to find in a license a most, and can set up its `maxSessionCacheSize` accordingly (e.g. if there's max `10` key slots available on the device and `5` keys per license maximum, it could just communicate to us a `maxSessionCacheSize` of `2`)._ So problem solved right? WRONG! The RxPlayer, when exploiting the `maxSessionCacheSize` property, will when that limit is reached just close the `MediaKeySession` it has least recently seen the need for (basically, when the RxPlayer loads segment for a new Period/track/Representation, it asks our decryption logic to make sure it has the right key, this is how our decryption logic know that a `MediaKeySession` or more precizely a key it can make use of, has been needed recently). Example scenario ---------------- So let's just imagine a simple scenario: 1. we're currently loading a Period `A` with encrypted content and buffering a future Period `B` with content encrypted with a different key. 2. we're asking the decryption logic to make sure the key is loaded for future Period `B` 3. The decryption logic sees that it doesn't have the key yet, and thus has to create a new `MediaKeySession`. Yet, it sees that it cannot create a new `MediaKeySession` for that new key without closing an old one to respect the `keySystems[].maxSessionCacheSize` option, and it turns out one relied on to play Period A was the least recently needed for some reason. 4. The decryption logic closes a `MediaKeySession` for Period `A` that was currently relied on. 5. ??? I don't know what happens, the `MediaKeySession` closure may fail in which case we could be left with too many key slots used on the device and some random error, or content playback may just fail directly. In any case, I wouldn't bet on something good happening. Other types of scenarios are possible, e.g. we could be closing a `MediaKeySession` needed in the future and not think to re-create it when playing that future Period, potentially leading to a future infinite rebuffering. Solution I'm proposing here =========================== In a previous PR, I tried to handle all cases but that became too complex and I know think that doing it in multiple steps may be easier to architects: we handle first the "simple" cases (which sadly are not the most frequent ones), we'll then see the harder cases. The simpler case it to just close `MediaKeySession` that are known to not be needed anymore if we go over the `maxSessionCacheSize` limit on the current content. To have a vague non-perfect idea of what is currently needed, we look at all `Period`s from the current position onward, list their key ids, compare with the keys currently handled by our DRM logic, and just close the ones that haven't been found. How I'm implementing this ========================= Detecting the issue ------------------- As we now have a difference in our `MediaKeySession`-closing algorithm depending on if the `MediaKeySession` is linked to the current content or not, I chose in our `ContentDecryptor` module that: 1. `MediaKeySession` that are not linked to the current content keep being closed like they were before: least recently needed first. 2. `MediaKeySession` that are linked to the current content are never directly closed by the `ContentDecryptor`. Instead, the `ContentDecryptor` module basically signals a `tooMuchSessions` event when only left with `MediaKeySession` for the current content yet going over the `maxSessionCacheSize` limit. It also doesn't create the `MediaKeySession` in that case. Fixing the situation -------------------- The `ContentDecryptor` now exposes a new method, `freeKeyIds`. The idea is that you communicate to it the key id you don't need anymore, then the `ContentDecryptor` will see if can consequently close some `MediaKeySession`. It is the role of the `ContentInitializer` to call this `freeKeyIds` method on key ids it doesn't seem to have the use of anymore (all key ids are in the payload of the `tooMuchSessions` event). Note: the new `ActiveSessionsStore` ----------------------------------- To allow the `ContentDecryptor` to easily know when it can restart creating `MediaKeySession` after encountering this `tooMuchSessions` situation and then having its `freeKeyIds` method called, I replaced its simple `_currentSessions` private array into a new kind of "MediaKeySession store" (a third one after the `LoadedSessionsStore` and the `PersistentSessionsStore`), called the `ActiveSessionsStore`, which also keeps a `isFull` boolean around. This new store's difference with the `LoadedSessionsStore` may be unclear at first but there's one: - The `LoadedSessionsStore` stores information on all `MediaKeySession` currently attached to a `MediaKeys` (and also creates / close them). - The `ActiveSessionsStore` is technically just an array of `MediaKeySession` information and a `isFull` flag, and its intended semantic is to represent all `MediaKeySession` that are "actively-used" by the `ContentDecryptor` (in implementation, it basically means all `MediaKeySession` linked to the current content). If you followed, note that the session information stored by the `LoadedSessionsStore` is a superset of the ones stored by the `ActiveSessionsStore` (the former contains all information from the latter) as "active" sessions are all currently "loaded". Writing that, I'm still unsure if the `isFull` flag would have more its place on the `LoadedSessionsStore` instead. After all `maxSessionCacheSize` technically applies to all "loaded" sessions, not just the "active" ones which is a concept only relied on by RxPlayer internals. We may discuss on what makes the most sense here. Remaining issues ================ This PR only fixes a fraction of the issue, actually the simpler part where we can close older `MediaKeySession` linked to the current content that we don't need anymore, like for example for a previous DASH Period. But there's also the risk of encountering that limit while preloading future contents encrypted through a different keys, or when seeking back at a previous DASH Period with different keys. In all those scenarios (which actually seems more probable), there's currently no fix, just error logs and multiple FIXME mentions in the code. Fixing this issue while keeping a readable code is very hard right now, moreover for what is only a suite of theoretical problems that has never been observed for now. So I sometimes wonder if the best compromise would not be to just let it happen, and have an heuristic somewhere else detecting the issue and fixing it by slightly reducing the experience (e.g. by reloading + disabling future Period pre-loading)...
1 parent dac9f49 commit 196f443

12 files changed

Lines changed: 566 additions & 108 deletions

src/main_thread/decrypt/content_decryptor.ts

Lines changed: 202 additions & 86 deletions
Large diffs are not rendered by default.

src/main_thread/decrypt/create_or_load_session.ts

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,14 @@ import type { CancellationSignal } from "../../utils/task_canceller";
2020
import createSession from "./create_session";
2121
import type { IProcessedProtectionData, IMediaKeySessionStores } from "./types";
2222
import { MediaKeySessionLoadingType } from "./types";
23-
import cleanOldLoadedSessions from "./utils/clean_old_loaded_sessions";
23+
import cleanOldLoadedSessions, {
24+
NoSessionSpaceError,
25+
} from "./utils/clean_old_loaded_sessions";
2426
import isSessionUsable from "./utils/is_session_usable";
2527
import type KeySessionRecord from "./utils/key_session_record";
2628

29+
export { NoSessionSpaceError };
30+
2731
/**
2832
* Handle MediaEncryptedEvents sent by a HTMLMediaElement:
2933
* Either create a MediaKeySession, recuperate a previous MediaKeySession or
@@ -34,24 +38,34 @@ import type KeySessionRecord from "./utils/key_session_record";
3438
* `EME_MAX_SIMULTANEOUS_MEDIA_KEY_SESSIONS` config property.
3539
*
3640
* You can refer to the events emitted to know about the current situation.
37-
* @param {Object} initializationData
38-
* @param {Object} stores
39-
* @param {string} wantedSessionType
40-
* @param {number} maxSessionCacheSize
41+
* @param {Object} arg
42+
* @param {Object} arg.initializationData
43+
* @param {Object} arg.sessionStores
44+
* @param {string} arg.sessionType
45+
* @param {number} arg.maxSessionCacheSize
4146
* @param {Object} cancelSignal
4247
* @returns {Promise}
4348
*/
4449
export default async function createOrLoadSession(
45-
initializationData: IProcessedProtectionData,
46-
stores: IMediaKeySessionStores,
47-
wantedSessionType: MediaKeySessionType,
48-
maxSessionCacheSize: number,
50+
{
51+
initializationData,
52+
sessionStores,
53+
sessionType,
54+
activeRecords,
55+
maxSessionCacheSize,
56+
}: {
57+
initializationData: IProcessedProtectionData;
58+
sessionStores: IMediaKeySessionStores;
59+
sessionType: MediaKeySessionType;
60+
activeRecords: KeySessionRecord[];
61+
maxSessionCacheSize: number;
62+
},
4963
cancelSignal: CancellationSignal,
5064
): Promise<ICreateOrLoadSessionResult> {
5165
/** Store previously-loaded compatible MediaKeySession, if one. */
5266
let previousLoadedSession: IMediaKeySession | null = null;
5367

54-
const { loadedSessionsStore, persistentSessionsStore } = stores;
68+
const { loadedSessionsStore, persistentSessionsStore } = sessionStores;
5569
const entry = loadedSessionsStore.reuse(initializationData);
5670
if (entry !== null) {
5771
previousLoadedSession = entry.mediaKeySession;
@@ -84,6 +98,7 @@ export default async function createOrLoadSession(
8498

8599
await cleanOldLoadedSessions(
86100
loadedSessionsStore,
101+
activeRecords,
87102
// Account for the next session we will be creating
88103
// Note that `maxSessionCacheSize < 0 has special semantic (no limit)`
89104
maxSessionCacheSize <= 0 ? maxSessionCacheSize : maxSessionCacheSize - 1,
@@ -93,9 +108,9 @@ export default async function createOrLoadSession(
93108
}
94109

95110
const evt = await createSession(
96-
stores,
111+
sessionStores,
97112
initializationData,
98-
wantedSessionType,
113+
sessionType,
99114
cancelSignal,
100115
);
101116
return {

src/main_thread/decrypt/types.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ export interface IContentDecryptorEvent {
4141
*/
4242
warning: IPlayerError;
4343

44+
tooMuchSessions: {
45+
waitingKeyIds: Uint8Array[];
46+
activeKeyIds: Uint8Array[];
47+
};
48+
4449
/**
4550
* Event emitted when the `ContentDecryptor`'s state changed.
4651
* States are a central aspect of the `ContentDecryptor`, be sure to check the

src/main_thread/decrypt/utils/__tests__/clean_old_loaded_sessions.test.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,38 @@
11
import { describe, it, expect, vi } from "vitest";
22

33
import cleanOldLoadedSessions from "../clean_old_loaded_sessions";
4+
import InitDataValuesContainer from "../init_data_values_container";
5+
import KeySessionRecord from "../key_session_record";
46
import type LoadedSessionsStore from "../loaded_sessions_store";
57

68
const entry1 = {
79
initializationData: { data: new Uint8Array([1, 6, 9]), type: "test" },
810
mediaKeySession: { sessionId: "toto" },
911
sessionType: "",
12+
keySessionRecord: new KeySessionRecord({
13+
type: undefined,
14+
values: new InitDataValuesContainer([]),
15+
}),
1016
};
1117

1218
const entry2 = {
1319
initializationData: { data: new Uint8Array([4, 8]), type: "foo" },
1420
mediaKeySession: { sessionId: "titi" },
1521
sessionType: "",
22+
keySessionRecord: new KeySessionRecord({
23+
type: undefined,
24+
values: new InitDataValuesContainer([]),
25+
}),
1626
};
1727

1828
const entry3 = {
1929
initializationData: { data: new Uint8Array([7, 3, 121, 87]), type: "bar" },
2030
mediaKeySession: { sessionId: "tutu" },
2131
sessionType: "",
32+
keySessionRecord: new KeySessionRecord({
33+
type: undefined,
34+
values: new InitDataValuesContainer([]),
35+
}),
2236
};
2337

2438
function createLoadedSessionsStore(): LoadedSessionsStore {
@@ -64,7 +78,7 @@ async function checkNothingHappen(
6478
limit: number,
6579
): Promise<void> {
6680
const mockCloseSession = vi.spyOn(loadedSessionsStore, "closeSession");
67-
await cleanOldLoadedSessions(loadedSessionsStore, limit);
81+
await cleanOldLoadedSessions(loadedSessionsStore, [], limit);
6882
expect(mockCloseSession).not.toHaveBeenCalled();
6983
mockCloseSession.mockRestore();
7084
}
@@ -85,7 +99,7 @@ async function checkEntriesCleaned(
8599
entries: Array<{ sessionId: string }>,
86100
): Promise<void> {
87101
const mockCloseSession = vi.spyOn(loadedSessionsStore, "closeSession");
88-
const prom = cleanOldLoadedSessions(loadedSessionsStore, limit).then(() => {
102+
const prom = cleanOldLoadedSessions(loadedSessionsStore, [], limit).then(() => {
89103
expect(mockCloseSession).toHaveBeenCalledTimes(entries.length);
90104
mockCloseSession.mockRestore();
91105
});
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import type { BlacklistedSessionError } from "../session_events_listener";
2+
import type { MediaKeySessionLoadingType } from "../types";
3+
import type KeySessionRecord from "./key_session_record";
4+
5+
/**
6+
* Contains information about all key sessions loaded for the current
7+
* content.
8+
* This object is most notably used to check which keys are already obtained,
9+
* thus avoiding to perform new unnecessary license requests and CDM
10+
* interactions.
11+
*
12+
* It is important to create only one `ActiveSessionsStore` for a given
13+
* `MediaKeys` to prevent conflicts.
14+
*
15+
* An `ActiveSessionsStore` instance can also be "marked" as full with the
16+
* `markAsFull` method.
17+
* "Marking as full" this way does not change your ability do add new session,
18+
* but the `isFull` method will return `true` until at least a single session is
19+
* removed from this `ActiveSessionsInfo`.
20+
* This "full" flag allows to simplify the management of having too many
21+
* simultaneous `MediaKeySession` on the current device, by storing in a single
22+
* place whether this event has been encountered and whether it had chance to
23+
* be resolved since.
24+
*
25+
* @class ActiveSessionsInfo
26+
*/
27+
export default class ActiveSessionsStore {
28+
/** Metadata on each `MediaKeySession` stored here. */
29+
private _sessions: IActiveSessionInfo[];
30+
31+
/**
32+
* `true` after the `markAsFull` method has been called, until `removeSession`
33+
* is called **and** led to a `MediaKeySession` has been removed.
34+
*
35+
* This boolean has no impact on the creation of new `MediaKeySession`, it is
36+
* only here as a flag to indicate that a surplus of `MediaKeySession`
37+
* linked to this `ActiveSessionsStore` has been detected and only resets to
38+
* `false` when it has chances to be resolved (when a `MediaKeySession` has
39+
* since been removed).
40+
*/
41+
private _isFull: boolean;
42+
43+
constructor() {
44+
this._sessions = [];
45+
this._isFull = false;
46+
}
47+
48+
/**
49+
* Set the `isFull` flag to true meaning that the `isFull` method will from
50+
* now on return `true` until at least one `MediaKeySession` has been removed
51+
* from this `ActiveSessionsStore` (through the `removeSession` method).
52+
*
53+
* This flag allows to store the information of whether too much
54+
* `MediaKeySession` seems to be created right now.
55+
*/
56+
public markAsFull(): void {
57+
this._isFull = true;
58+
}
59+
60+
/**
61+
* Add a new `MediaKeySession`, and its associated information, to the
62+
* `ActiveSessionsStore`.
63+
* @param {Object} sessionInfo
64+
*/
65+
public addSession(sessionInfo: IActiveSessionInfo) {
66+
this._sessions.push(sessionInfo);
67+
}
68+
69+
/**
70+
* Returns all information in the `ActiveSessionsStore` by order of insertion.
71+
* @returns {Array.<Object>}
72+
*/
73+
public getSessions(): IActiveSessionInfo[] {
74+
return this._sessions;
75+
}
76+
77+
/**
78+
* Remove element with the corresponding `MediaKeySession` information from
79+
* the `ActiveSessionsStore` if found.
80+
*
81+
* Returns `true` if the corresponding element has been found and removed, or
82+
* `false` if it wasn't found.
83+
*
84+
* @param {Object} sessionInfo
85+
* @returns {boolean}
86+
*/
87+
public removeSession(sessionInfo: IActiveSessionInfo): boolean {
88+
const indexOf = this._sessions.indexOf(sessionInfo);
89+
if (indexOf >= 0) {
90+
this._sessions.splice(indexOf, 1);
91+
this._isFull = false;
92+
return true;
93+
}
94+
return false;
95+
}
96+
97+
/**
98+
* If `true`, we know that there's too much `MediaKeySession` currently
99+
* created.
100+
*
101+
* @see `markAsFull` method.
102+
* @returns {boolean}
103+
*/
104+
public isFull(): boolean {
105+
return this._isFull;
106+
}
107+
}
108+
109+
/** Information linked to a session created by the `ContentDecryptor`. */
110+
export interface IActiveSessionInfo {
111+
/**
112+
* Record associated to the session.
113+
* Most notably, it allows both to identify the session as well as to
114+
* anounce and find out which key ids are already handled.
115+
*/
116+
record: KeySessionRecord;
117+
118+
/** Current keys' statuses linked that session. */
119+
keyStatuses: {
120+
/** Key ids linked to keys that are "usable". */
121+
whitelisted: Uint8Array[];
122+
/**
123+
* Key ids linked to keys that are not considered "usable".
124+
* Content linked to those keys are not decipherable and may thus be
125+
* fallbacked from.
126+
*/
127+
blacklisted: Uint8Array[];
128+
};
129+
130+
/** Source of the MediaKeySession linked to that record. */
131+
source: MediaKeySessionLoadingType;
132+
133+
/**
134+
* If different than `null`, all initialization data compatible with this
135+
* processed initialization data has been blacklisted with this corresponding
136+
* error.
137+
*/
138+
blacklistedSessionError: BlacklistedSessionError | null;
139+
}

src/main_thread/decrypt/utils/clean_old_loaded_sessions.ts

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
*/
1616

1717
import log from "../../../log";
18+
import arrayIncludes from "../../../utils/array_includes";
19+
import type KeySessionRecord from "./key_session_record";
1820
import type LoadedSessionsStore from "./loaded_sessions_store";
1921

2022
/**
@@ -28,18 +30,44 @@ import type LoadedSessionsStore from "./loaded_sessions_store";
2830
*/
2931
export default async function cleanOldLoadedSessions(
3032
loadedSessionsStore: LoadedSessionsStore,
33+
activeRecords: KeySessionRecord[],
3134
limit: number,
3235
): Promise<void> {
3336
if (limit < 0 || limit >= loadedSessionsStore.getLength()) {
3437
return;
3538
}
3639
log.info("DRM: LSS cache limit exceeded", limit, loadedSessionsStore.getLength());
3740
const proms: Array<Promise<unknown>> = [];
38-
const entries = loadedSessionsStore.getAll().slice(); // clone
39-
const toDelete = entries.length - limit;
40-
for (let i = 0; i < toDelete; i++) {
41-
const entry = entries[i];
42-
proms.push(loadedSessionsStore.closeSession(entry.mediaKeySession));
41+
const sessionsMetadata = loadedSessionsStore.getAll().slice(); // clone
42+
let toDelete = sessionsMetadata.length - limit;
43+
for (let i = 0; toDelete > 0 && i < sessionsMetadata.length; i++) {
44+
const metadata = sessionsMetadata[i];
45+
if (!arrayIncludes(activeRecords, metadata.keySessionRecord)) {
46+
proms.push(loadedSessionsStore.closeSession(metadata.mediaKeySession));
47+
toDelete--;
48+
}
49+
}
50+
if (toDelete > 0) {
51+
return Promise.all(proms).then(() => {
52+
return Promise.reject(
53+
new NoSessionSpaceError("Could not remove all sessions: some are still active"),
54+
);
55+
});
4356
}
4457
await Promise.all(proms);
4558
}
59+
60+
/**
61+
* Error thrown when the MediaKeySession is blacklisted.
62+
* Such MediaKeySession should not be re-used but other MediaKeySession for the
63+
* same content can still be used.
64+
* @class NoSessionSpaceError
65+
* @extends Error
66+
*/
67+
export class NoSessionSpaceError extends Error {
68+
constructor(message: string) {
69+
super(message);
70+
// @see https://stackoverflow.com/questions/41102060/typescript-extending-error-class
71+
Object.setPrototypeOf(this, NoSessionSpaceError.prototype);
72+
}
73+
}

src/main_thread/decrypt/utils/loaded_sessions_store.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,15 @@ export default class LoadedSessionsStore {
123123
return null;
124124
}
125125

126+
public hasEntryForRecord(keySessionRecord: KeySessionRecord): boolean {
127+
for (const stored of this._storage) {
128+
if (stored.keySessionRecord === keySessionRecord) {
129+
return true;
130+
}
131+
}
132+
return false;
133+
}
134+
126135
/**
127136
* Get `LoadedSessionsStore`'s entry for a given MediaKeySession.
128137
* Returns `null` if the given MediaKeySession is not stored in the

src/main_thread/init/directfile_content_initializer.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,9 @@ export default class DirectFileContentInitializer extends ContentInitializer {
101101
onWarning: (err: IPlayerError) => this.trigger("warning", err),
102102
onBlackListProtectionData: noop,
103103
onKeyIdsCompatibilityUpdate: noop,
104+
onTooMuchSessions: () => {
105+
log.error("Init: There's currently too much MediaKeySession created");
106+
},
104107
},
105108
cancelSignal,
106109
);

0 commit comments

Comments
 (0)