-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
rendition-helper.ts
451 lines (436 loc) · 14.1 KB
/
rendition-helper.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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import { codecsSetSelectionPreferenceValue } from './codecs';
import { getVideoSelectionOptions } from './hdr';
import { logger } from './logger';
import type { Level, VideoRange } from '../types/level';
import type {
AudioSelectionOption,
MediaPlaylist,
SubtitleSelectionOption,
VideoSelectionOption,
} from '../types/media-playlist';
export type CodecSetTier = {
minBitrate: number;
minHeight: number;
minFramerate: number;
maxScore: number;
videoRanges: Record<string, number>;
channels: Record<string, number>;
hasDefaultAudio: boolean;
fragmentError: number;
};
type AudioTrackGroup = {
tracks: MediaPlaylist[];
channels: Record<string, number>;
hasDefault: boolean;
hasAutoSelect: boolean;
};
type StartParameters = {
codecSet: string | undefined;
videoRanges: Array<VideoRange>;
preferHDR: boolean;
minFramerate: number;
minBitrate: number;
};
export function getStartCodecTier(
codecTiers: Record<string, CodecSetTier>,
currentVideoRange: VideoRange | undefined,
currentBw: number,
audioPreference: AudioSelectionOption | undefined,
videoPreference: VideoSelectionOption | undefined,
): StartParameters {
const codecSets = Object.keys(codecTiers);
const channelsPreference = audioPreference?.channels;
const audioCodecPreference = audioPreference?.audioCodec;
const preferStereo = channelsPreference && parseInt(channelsPreference) === 2;
// Use first level set to determine stereo, and minimum resolution and framerate
let hasStereo = true;
let hasCurrentVideoRange = false;
let minHeight = Infinity;
let minFramerate = Infinity;
let minBitrate = Infinity;
let selectedScore = 0;
let videoRanges: Array<VideoRange> = [];
const { preferHDR, allowedVideoRanges } = getVideoSelectionOptions(
currentVideoRange,
videoPreference,
);
for (let i = codecSets.length; i--; ) {
const tier = codecTiers[codecSets[i]];
hasStereo = tier.channels[2] > 0;
minHeight = Math.min(minHeight, tier.minHeight);
minFramerate = Math.min(minFramerate, tier.minFramerate);
minBitrate = Math.min(minBitrate, tier.minBitrate);
const matchingVideoRanges = allowedVideoRanges.filter(
(range) => tier.videoRanges[range] > 0,
);
if (matchingVideoRanges.length > 0) {
hasCurrentVideoRange = true;
videoRanges = matchingVideoRanges;
}
}
minHeight = Number.isFinite(minHeight) ? minHeight : 0;
minFramerate = Number.isFinite(minFramerate) ? minFramerate : 0;
const maxHeight = Math.max(1080, minHeight);
const maxFramerate = Math.max(30, minFramerate);
minBitrate = Number.isFinite(minBitrate) ? minBitrate : currentBw;
currentBw = Math.max(minBitrate, currentBw);
// If there are no variants with matching preference, set currentVideoRange to undefined
if (!hasCurrentVideoRange) {
currentVideoRange = undefined;
videoRanges = [];
}
const codecSet = codecSets.reduce(
(selected: string | undefined, candidate: string) => {
// Remove candiates which do not meet bitrate, default audio, stereo or channels preference, 1080p or lower, 30fps or lower, or SDR/HDR selection if present
const candidateTier = codecTiers[candidate];
if (candidate === selected) {
return selected;
}
if (candidateTier.minBitrate > currentBw) {
logStartCodecCandidateIgnored(
candidate,
`min bitrate of ${candidateTier.minBitrate} > current estimate of ${currentBw}`,
);
return selected;
}
if (!candidateTier.hasDefaultAudio) {
logStartCodecCandidateIgnored(
candidate,
`no renditions with default or auto-select sound found`,
);
return selected;
}
if (
audioCodecPreference &&
candidate.indexOf(audioCodecPreference.substring(0, 4)) % 5 !== 0
) {
logStartCodecCandidateIgnored(
candidate,
`audio codec preference "${audioCodecPreference}" not found`,
);
return selected;
}
if (channelsPreference && !preferStereo) {
if (!candidateTier.channels[channelsPreference]) {
logStartCodecCandidateIgnored(
candidate,
`no renditions with ${channelsPreference} channel sound found (channels options: ${Object.keys(
candidateTier.channels,
)})`,
);
return selected;
}
} else if (
(!audioCodecPreference || preferStereo) &&
hasStereo &&
candidateTier.channels['2'] === 0
) {
logStartCodecCandidateIgnored(
candidate,
`no renditions with stereo sound found`,
);
return selected;
}
if (candidateTier.minHeight > maxHeight) {
logStartCodecCandidateIgnored(
candidate,
`min resolution of ${candidateTier.minHeight} > maximum of ${maxHeight}`,
);
return selected;
}
if (candidateTier.minFramerate > maxFramerate) {
logStartCodecCandidateIgnored(
candidate,
`min framerate of ${candidateTier.minFramerate} > maximum of ${maxFramerate}`,
);
return selected;
}
if (!videoRanges.some((range) => candidateTier.videoRanges[range] > 0)) {
logStartCodecCandidateIgnored(
candidate,
`no variants with VIDEO-RANGE of ${JSON.stringify(
videoRanges,
)} found`,
);
return selected;
}
if (candidateTier.maxScore < selectedScore) {
logStartCodecCandidateIgnored(
candidate,
`max score of ${candidateTier.maxScore} < selected max of ${selectedScore}`,
);
return selected;
}
// Remove candiates with less preferred codecs or more errors
if (
selected &&
(codecsSetSelectionPreferenceValue(candidate) >=
codecsSetSelectionPreferenceValue(selected) ||
candidateTier.fragmentError > codecTiers[selected].fragmentError)
) {
return selected;
}
selectedScore = candidateTier.maxScore;
return candidate;
},
undefined,
);
return {
codecSet,
videoRanges,
preferHDR,
minFramerate,
minBitrate,
};
}
function logStartCodecCandidateIgnored(codeSet: string, reason: string) {
logger.log(
`[abr] start candidates with "${codeSet}" ignored because ${reason}`,
);
}
export type AudioTracksByGroup = {
hasDefaultAudio: boolean;
hasAutoSelectAudio: boolean;
groups: Record<string, AudioTrackGroup>;
};
export function getAudioTracksByGroup(allAudioTracks: MediaPlaylist[]) {
return allAudioTracks.reduce(
(audioTracksByGroup: AudioTracksByGroup, track) => {
let trackGroup = audioTracksByGroup.groups[track.groupId];
if (!trackGroup) {
trackGroup = audioTracksByGroup.groups[track.groupId] = {
tracks: [],
channels: { 2: 0 },
hasDefault: false,
hasAutoSelect: false,
};
}
trackGroup.tracks.push(track);
const channelsKey = track.channels || '2';
trackGroup.channels[channelsKey] =
(trackGroup.channels[channelsKey] || 0) + 1;
trackGroup.hasDefault = trackGroup.hasDefault || track.default;
trackGroup.hasAutoSelect = trackGroup.hasAutoSelect || track.autoselect;
if (trackGroup.hasDefault) {
audioTracksByGroup.hasDefaultAudio = true;
}
if (trackGroup.hasAutoSelect) {
audioTracksByGroup.hasAutoSelectAudio = true;
}
return audioTracksByGroup;
},
{
hasDefaultAudio: false,
hasAutoSelectAudio: false,
groups: {},
},
);
}
export function getCodecTiers(
levels: Level[],
audioTracksByGroup: AudioTracksByGroup,
minAutoLevel: number,
maxAutoLevel: number,
): Record<string, CodecSetTier> {
return levels
.slice(minAutoLevel, maxAutoLevel + 1)
.reduce((tiers: Record<string, CodecSetTier>, level) => {
if (!level.codecSet) {
return tiers;
}
const audioGroups = level.audioGroups;
let tier = tiers[level.codecSet];
if (!tier) {
tiers[level.codecSet] = tier = {
minBitrate: Infinity,
minHeight: Infinity,
minFramerate: Infinity,
maxScore: 0,
videoRanges: { SDR: 0 },
channels: { '2': 0 },
hasDefaultAudio: !audioGroups,
fragmentError: 0,
};
}
tier.minBitrate = Math.min(tier.minBitrate, level.bitrate);
const lesserWidthOrHeight = Math.min(level.height, level.width);
tier.minHeight = Math.min(tier.minHeight, lesserWidthOrHeight);
tier.minFramerate = Math.min(tier.minFramerate, level.frameRate);
tier.maxScore = Math.max(tier.maxScore, level.score);
tier.fragmentError += level.fragmentError;
tier.videoRanges[level.videoRange] =
(tier.videoRanges[level.videoRange] || 0) + 1;
if (audioGroups) {
audioGroups.forEach((audioGroupId) => {
if (!audioGroupId) {
return;
}
const audioGroup = audioTracksByGroup.groups[audioGroupId];
// Default audio is any group with DEFAULT=YES, or if missing then any group with AUTOSELECT=YES, or all variants
tier.hasDefaultAudio =
tier.hasDefaultAudio || audioTracksByGroup.hasDefaultAudio
? audioGroup.hasDefault
: audioGroup.hasAutoSelect ||
(!audioTracksByGroup.hasDefaultAudio &&
!audioTracksByGroup.hasAutoSelectAudio);
Object.keys(audioGroup.channels).forEach((channels) => {
tier.channels[channels] =
(tier.channels[channels] || 0) + audioGroup.channels[channels];
});
});
}
return tiers;
}, {});
}
export function findMatchingOption(
option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,
tracks: MediaPlaylist[],
matchPredicate?: (
option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,
track: MediaPlaylist,
) => boolean,
): number {
if ('attrs' in option) {
const index = tracks.indexOf(option);
if (index !== -1) {
return index;
}
}
for (let i = 0; i < tracks.length; i++) {
const track = tracks[i];
if (matchesOption(option, track, matchPredicate)) {
return i;
}
}
return -1;
}
export function matchesOption(
option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,
track: MediaPlaylist,
matchPredicate?: (
option: MediaPlaylist | AudioSelectionOption | SubtitleSelectionOption,
track: MediaPlaylist,
) => boolean,
): boolean {
const {
groupId,
name,
lang,
assocLang,
characteristics,
default: isDefault,
} = option;
const forced = (option as SubtitleSelectionOption).forced;
return (
(groupId === undefined || track.groupId === groupId) &&
(name === undefined || track.name === name) &&
(lang === undefined || track.lang === lang) &&
(lang === undefined || track.assocLang === assocLang) &&
(isDefault === undefined || track.default === isDefault) &&
(forced === undefined || track.forced === forced) &&
(characteristics === undefined ||
characteristicsMatch(characteristics, track.characteristics)) &&
(matchPredicate === undefined || matchPredicate(option, track))
);
}
function characteristicsMatch(
characteristicsA: string,
characteristicsB: string = '',
): boolean {
const arrA = characteristicsA.split(',');
const arrB = characteristicsB.split(',');
// Expects each item to be unique:
return (
arrA.length === arrB.length && !arrA.some((el) => arrB.indexOf(el) === -1)
);
}
export function audioMatchPredicate(
option: MediaPlaylist | AudioSelectionOption,
track: MediaPlaylist,
) {
const { audioCodec, channels } = option;
return (
(audioCodec === undefined ||
(track.audioCodec || '').substring(0, 4) ===
audioCodec.substring(0, 4)) &&
(channels === undefined || channels === (track.channels || '2'))
);
}
export function findClosestLevelWithAudioGroup(
option: MediaPlaylist | AudioSelectionOption,
levels: Level[],
allAudioTracks: MediaPlaylist[],
searchIndex: number,
matchPredicate: (
option: MediaPlaylist | AudioSelectionOption,
track: MediaPlaylist,
) => boolean,
): number {
const currentLevel = levels[searchIndex];
// Are there variants with same URI as current level?
// If so, find a match that does not require any level URI change
const variants = levels.reduce(
(variantMap: { [uri: string]: number[] }, level, index) => {
const uri = level.uri;
const renditions = variantMap[uri] || (variantMap[uri] = []);
renditions.push(index);
return variantMap;
},
{},
);
const renditions = variants[currentLevel.uri];
if (renditions.length > 1) {
searchIndex = Math.max.apply(Math, renditions);
}
// Find best match
const currentVideoRange = currentLevel.videoRange;
const currentFrameRate = currentLevel.frameRate;
const currentVideoCodec = currentLevel.codecSet.substring(0, 4);
const matchingVideo = searchDownAndUpList(
levels,
searchIndex,
(level: Level) => {
if (
level.videoRange !== currentVideoRange ||
level.frameRate !== currentFrameRate ||
level.codecSet.substring(0, 4) !== currentVideoCodec
) {
return false;
}
const audioGroups = level.audioGroups;
const tracks = allAudioTracks.filter(
(track): boolean =>
!audioGroups || audioGroups.indexOf(track.groupId) !== -1,
);
return findMatchingOption(option, tracks, matchPredicate) > -1;
},
);
if (matchingVideo > -1) {
return matchingVideo;
}
return searchDownAndUpList(levels, searchIndex, (level: Level) => {
const audioGroups = level.audioGroups;
const tracks = allAudioTracks.filter(
(track): boolean =>
!audioGroups || audioGroups.indexOf(track.groupId) !== -1,
);
return findMatchingOption(option, tracks, matchPredicate) > -1;
});
}
function searchDownAndUpList(
arr: any[],
searchIndex: number,
predicate: (item: any) => boolean,
): number {
for (let i = searchIndex; i; i--) {
if (predicate(arr[i])) {
return i;
}
}
for (let i = searchIndex + 1; i < arr.length; i++) {
if (predicate(arr[i])) {
return i;
}
}
return -1;
}