-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathServerAbrStream.ts
321 lines (270 loc) · 11.8 KB
/
ServerAbrStream.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import { UMP } from './UMP.js';
import { ChunkedDataBuffer } from './ChunkedDataBuffer.js';
import { EventEmitterLike, PART, QUALITY, base64ToU8, getFormatKey } from '../utils/index.js';
import { VideoPlaybackAbrRequest } from '../../protos/generated/video_streaming/video_playback_abr_request.js';
import { MediaHeader } from '../../protos/generated/video_streaming/media_header.js';
import { NextRequestPolicy } from '../../protos/generated/video_streaming/next_request_policy.js';
import { FormatInitializationMetadata } from '../../protos/generated/video_streaming/format_initialization_metadata.js';
import { SabrRedirect } from '../../protos/generated/video_streaming/sabr_redirect.js';
import { SabrError } from '../../protos/generated/video_streaming/sabr_error.js';
import { StreamProtectionStatus } from '../../protos/generated/video_streaming/stream_protection_status.js';
import { PlaybackCookie } from '../../protos/generated/video_streaming/playback_cookie.js';
import type { FormatId } from '../../protos/generated/misc/common.js';
import type { ClientAbrState } from '../../protos/generated/video_streaming/client_abr_state.js';
import type { FetchFunction, InitializedFormat, InitOptions, MediaArgs, ServerAbrResponse, ServerAbrStreamOptions } from '../utils/types.js';
const DEFAULT_QUALITY = QUALITY.HD720;
export class ServerAbrStream extends EventEmitterLike {
private fetchFunction: FetchFunction;
private serverAbrStreamingUrl: string;
private videoPlaybackUstreamerConfig: string;
private poToken?: string;
private playbackCookie?: PlaybackCookie;
private totalDurationMs: number;
private initializedFormats: InitializedFormat[] = [];
private formatsByKey: Map<string, InitializedFormat> = new Map();
private headerIdToFormatKeyMap: Map<number, string> = new Map();
private previousSequences: Map<string, number[]> = new Map();
constructor(args: ServerAbrStreamOptions) {
super();
this.fetchFunction = args.fetch || fetch;
this.serverAbrStreamingUrl = args.serverAbrStreamingUrl;
this.videoPlaybackUstreamerConfig = args.videoPlaybackUstreamerConfig;
this.poToken = args.poToken;
this.totalDurationMs = args.durationMs;
}
public on(event: 'end', listener: (streamData: ServerAbrResponse) => void): void;
public on(event: 'data', listener: (streamData: ServerAbrResponse) => void): void;
public on(event: 'error', listener: (error: Error) => void): void;
public on(event: string, listener: (...data: any[]) => void): void {
super.on(event, listener);
}
public once(event: 'end', listener: (streamData: ServerAbrResponse) => void): void;
public once(event: 'data', listener: (streamData: ServerAbrResponse) => void): void;
public once(event: 'error', listener: (error: Error) => void): void;
public once(event: string, listener: (...args: any[]) => void): void {
super.once(event, listener);
}
/**
* Initializes the server ABR stream with the provided options.
* @param args - The initialization options.
*/
public async init(args: InitOptions) {
const { audioFormats, videoFormats, clientAbrState: initialState } = args;
const firstVideoFormat = videoFormats ? videoFormats[0] : undefined;
const clientAbrState: ClientAbrState = {
lastManualDirection: 0,
timeSinceLastManualFormatSelectionMs: 0,
lastManualSelectedResolution: videoFormats.length === 1 ? firstVideoFormat?.height : DEFAULT_QUALITY,
stickyResolution: videoFormats.length === 1 ? firstVideoFormat?.height : DEFAULT_QUALITY,
playerTimeMs: 0,
visibility: 0,
enabledTrackTypesBitfield: 0,
...initialState
};
const audioFormatIds = audioFormats.map<FormatId>((fmt) => ({
itag: fmt.itag,
lastModified: parseInt(fmt.lastModified),
xtags: fmt.xtags
}));
const videoFormatIds = videoFormats.map<FormatId>((fmt) => ({
itag: fmt.itag,
lastModified: parseInt(fmt.lastModified),
xtags: fmt.xtags
}));
if (typeof clientAbrState.playerTimeMs !== 'number')
throw new Error('Invalid media start time');
try {
while (clientAbrState.playerTimeMs < this.totalDurationMs) {
const data = await this.fetchMedia({ clientAbrState, audioFormatIds, videoFormatIds });
this.emit('data', data);
if (data.sabrError) break;
const mainFormat =
clientAbrState.enabledTrackTypesBitfield === 0
? data.initializedFormats.find((fmt) => fmt.mimeType?.includes('video'))
: data.initializedFormats[0];
for (const fmt of data.initializedFormats) {
this.previousSequences.set(fmt.formatKey, fmt.sequenceList.map((seq) => seq.sequenceNumber || 0));
}
if (
!mainFormat ||
mainFormat.sequenceCount ===
mainFormat.sequenceList[mainFormat.sequenceList.length - 1]?.sequenceNumber
) {
this.emit('end', data);
break;
}
clientAbrState.playerTimeMs += mainFormat.sequenceList.reduce((acc, seq) => acc + (seq.durationMs || 0), 0);
}
} catch (error) {
this.emit('error', error);
clientAbrState.playerTimeMs = Infinity;
}
}
private async fetchMedia(args: MediaArgs): Promise<ServerAbrResponse> {
const { clientAbrState, audioFormatIds, videoFormatIds } = args;
const body = VideoPlaybackAbrRequest.encode({
clientAbrState: clientAbrState,
selectedAudioFormatIds: audioFormatIds,
selectedVideoFormatIds: videoFormatIds,
selectedFormatIds: this.initializedFormats.map((fmt) => fmt.formatId),
videoPlaybackUstreamerConfig: base64ToU8(this.videoPlaybackUstreamerConfig),
streamerContext: {
field5: [],
field6: [],
poToken: this.poToken ? base64ToU8(this.poToken) : undefined,
playbackCookie: this.playbackCookie ? PlaybackCookie.encode(this.playbackCookie).finish() : undefined,
clientInfo: {
clientName: 1,
clientVersion: '2.2040620.05.00',
osName: 'Windows',
osVersion: '10.0'
}
},
bufferedRanges: this.initializedFormats.map((fmt) => fmt._state),
field1000: []
}).finish();
const response = await this.fetchFunction(this.serverAbrStreamingUrl, { method: 'POST', body });
const data = await response.arrayBuffer();
if (response.status !== 200 || !data.byteLength)
throw new Error(`Received an invalid response from the server: ${response.status}`);
return this.parseUMPResponse(new Uint8Array(data));
}
/**
* Parses the UMP response data and updates the initialized formats.
* @param response - The UMP response data as a byte array.
*/
public async parseUMPResponse(response: Uint8Array): Promise<ServerAbrResponse> {
this.headerIdToFormatKeyMap.clear();
this.initializedFormats.forEach((format) => {
format.sequenceList = [];
format.mediaChunks = [];
});
let sabrError: SabrError | undefined;
let sabrRedirect: SabrRedirect | undefined;
let streamProtectionStatus: StreamProtectionStatus | undefined;
const ump = new UMP(new ChunkedDataBuffer([ response ]));
ump.parse((part) => {
const data = part.data.chunks[0];
switch (part.type) {
case PART.MEDIA_HEADER:
this.processMediaHeader(data);
break;
case PART.MEDIA:
this.processMediaData(part.data);
break;
case PART.MEDIA_END:
this.processEndOfMedia(part.data);
break;
case PART.NEXT_REQUEST_POLICY:
this.processNextRequestPolicy(data);
break;
case PART.FORMAT_INITIALIZATION_METADATA:
this.processFormatInitialization(data);
break;
case PART.SABR_ERROR:
sabrError = SabrError.decode(data);
break;
case PART.SABR_REDIRECT:
sabrRedirect = this.processSabrRedirect(data);
break;
case PART.STREAM_PROTECTION_STATUS:
streamProtectionStatus = StreamProtectionStatus.decode(data);
break;
default:
break;
}
});
return {
initializedFormats: this.initializedFormats,
streamProtectionStatus,
sabrRedirect,
sabrError
};
}
private processMediaHeader(data: Uint8Array) {
const mediaHeader = MediaHeader.decode(data);
if (!mediaHeader.formatId) return;
const formatKey = getFormatKey(mediaHeader.formatId);
const currentFormat = this.formatsByKey.get(formatKey) || this.registerFormat(mediaHeader);
if (!currentFormat) return;
// FIXME: This is a hacky workaround to prevent duplicate sequences from being added. This should be fixed in the future (preferably by figuring out how to make the server not send duplicates).
if (mediaHeader.sequenceNumber !== undefined && this.previousSequences.get(formatKey)?.includes(mediaHeader.sequenceNumber))
return;
// Save the header's ID so we can identify its stream data later.
if (mediaHeader.headerId !== undefined) {
if (!this.headerIdToFormatKeyMap.has(mediaHeader.headerId)) {
this.headerIdToFormatKeyMap.set(mediaHeader.headerId, formatKey);
}
}
if (!currentFormat.sequenceList.some((seq) => seq.sequenceNumber === (mediaHeader.sequenceNumber || 0))) {
currentFormat.sequenceList.push({
itag: mediaHeader.itag,
formatId: mediaHeader.formatId,
isInitSegment: mediaHeader.isInitSeg,
durationMs: mediaHeader.durationMs,
startMs: mediaHeader.startMs,
startDataRange: mediaHeader.startDataRange,
sequenceNumber: mediaHeader.sequenceNumber,
contentLength: mediaHeader.contentLength,
timeRange: mediaHeader.timeRange
});
if (typeof mediaHeader.sequenceNumber === 'number') {
currentFormat._state.durationMs += mediaHeader.durationMs || 0;
currentFormat._state.endSegmentIndex += 1;
}
}
}
private processMediaData(data: ChunkedDataBuffer) {
const headerId = data.getUint8(0);
const streamData = data.split(1).remainingBuffer;
const formatKey = this.headerIdToFormatKeyMap.get(headerId);
if (!formatKey) return;
const currentFormat = this.formatsByKey.get(formatKey);
if (!currentFormat) return;
currentFormat.mediaChunks.push(streamData.chunks[0]);
}
private processEndOfMedia(data: ChunkedDataBuffer) {
const headerId = data.getUint8(0);
this.headerIdToFormatKeyMap.delete(headerId);
}
private processNextRequestPolicy(data: Uint8Array) {
const nextRequestPolicy = NextRequestPolicy.decode(data);
this.playbackCookie = nextRequestPolicy.playbackCookie;
}
private processFormatInitialization(data: Uint8Array) {
const formatInitializationMetadata = FormatInitializationMetadata.decode(data);
this.registerFormat(formatInitializationMetadata);
}
private processSabrRedirect(data: Uint8Array): SabrRedirect {
const sabrRedirect = SabrRedirect.decode(data);
if (!sabrRedirect.url) throw new Error('Invalid SABR redirect');
this.serverAbrStreamingUrl = sabrRedirect.url;
return sabrRedirect;
}
private registerFormat(data: MediaHeader | FormatInitializationMetadata): InitializedFormat | undefined {
if (!data.formatId)
return;
const formatKey = getFormatKey(data.formatId);
if (!this.formatsByKey.has(formatKey)) {
const format: InitializedFormat = {
formatId: data.formatId,
formatKey: formatKey,
durationMs: data.durationMs,
mimeType: 'mimeType' in data ? data.mimeType : undefined,
sequenceCount: 'field4' in data ? data.field4 : undefined,
sequenceList: [],
mediaChunks: [],
_state: {
formatId: data.formatId,
startTimeMs: 0,
durationMs: 0,
startSegmentIndex: 1,
endSegmentIndex: 0
}
};
this.initializedFormats.push(format);
this.formatsByKey.set(formatKey, this.initializedFormats[this.initializedFormats.length - 1]);
return format;
}
}
}