forked from muxinc/media-elements
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcastable-utils.js
More file actions
178 lines (146 loc) · 5.3 KB
/
castable-utils.js
File metadata and controls
178 lines (146 loc) · 5.3 KB
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
/* global WeakRef */
export const privateProps = new WeakMap();
export class InvalidStateError extends Error {}
export class NotSupportedError extends Error {}
export class NotFoundError extends Error {}
const HLS_RESPONSE_HEADERS = ['application/x-mpegURL','application/vnd.apple.mpegurl','audio/mpegurl']
// Fallback to a plain Set if WeakRef is not available.
export const IterableWeakSet = globalThis.WeakRef ?
class extends Set {
add(el) {
super.add(new WeakRef(el));
}
forEach(fn) {
super.forEach((ref) => {
const value = ref.deref();
if (value) fn(value);
});
}
} : Set;
export function onCastApiAvailable(callback) {
if (!globalThis.chrome?.cast?.isAvailable) {
globalThis.__onGCastApiAvailable = () => {
// The globalThis.__onGCastApiAvailable callback alone is not reliable for
// the added cast.framework. It's loaded in a separate JS file.
// https://www.gstatic.com/eureka/clank/101/cast_sender.js
// https://www.gstatic.com/cast/sdk/libs/sender/1.0/cast_framework.js
customElements
.whenDefined('google-cast-button')
.then(callback);
};
} else if (!globalThis.cast?.framework) {
customElements
.whenDefined('google-cast-button')
.then(callback);
} else {
callback();
}
}
export function requiresCastFramework() {
// todo: exclude for Android>=56 which supports the Remote Playback API natively.
return globalThis.chrome;
}
export function loadCastFramework() {
const sdkUrl = 'https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1';
if (globalThis.chrome?.cast || document.querySelector(`script[src="${sdkUrl}"]`)) return;
const script = document.createElement('script');
script.src = sdkUrl;
document.head.append(script);
}
export function castContext() {
return globalThis.cast?.framework?.CastContext.getInstance();
}
export function currentSession() {
return castContext()?.getCurrentSession();
}
export function currentMedia() {
return currentSession()?.getSessionObj().media[0];
}
export function editTracksInfo(request) {
return new Promise((resolve, reject) => {
currentMedia().editTracksInfo(request, resolve, reject);
});
}
export function getMediaStatus(request) {
return new Promise((resolve, reject) => {
currentMedia().getStatus(request, resolve, reject);
});
}
export function setCastOptions(options) {
return castContext().setOptions({
...getDefaultCastOptions(),
...options,
});
}
export function getDefaultCastOptions() {
return {
// Set the receiver application ID to your own (created in the
// Google Cast Developer Console), or optionally
// use the chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID
receiverApplicationId: 'CC1AD845',
// Auto join policy can be one of the following three:
// ORIGIN_SCOPED - Auto connect from same appId and page origin
// TAB_AND_ORIGIN_SCOPED - Auto connect from same appId, page origin, and tab
// PAGE_SCOPED - No auto connect
autoJoinPolicy: 'origin_scoped',
// The following flag enables Cast Connect(requires Chrome 87 or higher)
// https://developers.googleblog.com/2020/08/introducing-cast-connect-android-tv.html
androidReceiverCompatible: false,
language: 'en-US',
resumeSavedSession: true,
};
}
//Get the segment format given the end of the URL (.m4s, .ts, etc)
function getFormat(segment) {
if (!segment) return undefined;
const regex = /\.([a-zA-Z0-9]+)(?:\?.*)?$/;
const match = segment.match(regex);
return match ? match[1] : null;
}
function parsePlaylistUrls(playlistContent) {
const lines = playlistContent.split('\n');
const urls = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Locate available video playlists and get the next line which is the URI (https://datatracker.ietf.org/doc/html/draft-pantos-hls-rfc8216bis-17#section-4.4.6.2)
if (line.startsWith('#EXT-X-STREAM-INF')) {
const nextLine = lines[i + 1] ? lines[i + 1].trim() : '';
if (nextLine && !nextLine.startsWith('#')) {
urls.push(nextLine);
}
}
}
return urls;
}
function parseSegment(playlistContent){
const lines = playlistContent.split('\n');
const url = lines.find(line => !line.trim().startsWith('#') && line.trim() !== '');
return url;
}
export async function isHls(url) {
try {
const response = await fetch(url, {method: 'HEAD'});
const contentType = response.headers.get('Content-Type');
return HLS_RESPONSE_HEADERS.some((header) => contentType === header);
} catch (err) {
console.error('Error while trying to get the Content-Type of the manifest', err);
return false;
}
}
export async function getPlaylistSegmentFormat(url) {
try {
const mainManifestContent = await (await fetch(url)).text();
let availableChunksContent = mainManifestContent;
const playlists = parsePlaylistUrls(mainManifestContent);
if (playlists.length > 0) {
const chosenPlaylistUrl = new URL(playlists[0], url).toString();
availableChunksContent = await (await fetch(chosenPlaylistUrl)).text();
}
const segment = parseSegment(availableChunksContent);
const format = getFormat(segment);
return format
} catch (err) {
console.error('Error while trying to parse the manifest playlist', err);
return undefined;
}
}