-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlatencymanager.js
453 lines (381 loc) · 15.9 KB
/
latencymanager.js
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
452
453
(function() {
// body of the function
const HAVE_NOTHING = 0;
const HAVE_METADATA = 1;
const HAVE_CURRENT_DATA = 2;
const HAVE_FUTURE_DATA = 3;
const HAVE_ENOUGH_DATA = 4;
THEOplayer.TimeServer = function(timeserverUri, syncinterval) {
this.latency = 0;
this.rtt = 0;
this.syncedTimestamp;
this.interval = 0;
if (syncinterval != undefined)
this.interval = syncinterval * 1000;
this.synctimeout = undefined;
this.listeners = {};
this.timeserver = "https://time.theoplayer.com";
if (timeserverUri !== undefined && timeserverUri !== "")
this.timeserver = timeserverUri;
this.listeners = [];
this.addEventListener = function(type, callback) {
if (!(type in this.listeners)) {
this.listeners[type] = [];
}
this.listeners[type].push(callback);
};
this.removeEventListener = function(type, callback) {
if (!(type in this.listeners)) {
return;
}
var stack = this.listeners[type];
for (var i = 0, l = stack.length; i < l; i++) {
if (stack[i] === callback) {
stack.splice(i, 1);
return;
}
}
};
this.dispatchEvent = function(event) {
if (!(event.type in this.listeners)) {
return true;
}
var stack = this.listeners[event.type].slice();
for (var i = 0, l = stack.length; i < l; i++) {
stack[i].call(this, event);
}
return !event.defaultPrevented;
};
this.sync = function() {
var beforeRequest = Date.now();
var xhr = new XMLHttpRequest();
xhr.open('GET', this.timeserver);
xhr.onload = (function() {
if (xhr.status === 200) {
console.log("Timeserver sync" + xhr.responseText);
var now = Date.now();
this.rtt = now - beforeRequest;
this.syncedTimestamp = new Date(xhr.responseText);
this.latency = this.syncedTimestamp.getTime() + (this.rtt / 2.0) - now;
var syncEventData = {
latency: this.latency,
servertime: this.syncedTimestamp,
localtime: now,
rtt: this.rtt
};
this.dispatchEvent(new Event("sync", syncEventData));
} else {
console.log("Timeserver sync error " + xhr.status)
this.dispatchEvent(new Event("error", {
errorMessage: "Timeserver " + this.timeserver + ' has responded with status code ' + xhr.status
}));
}
if (this.interval > 0) {
if (this.synctimeout != undefined) {
clearTimeout(this.synctimeout);
}
this.synctimeout = setTimeout(function() {
this.sync();
}.bind(this), this.interval);
}
}.bind(this));
xhr.send();
}
this.getLatency = function() {
return this.latency;
}
this.getServerTime = function() {
return new Date(Date.now() + this.latency);
}
}
THEOplayer.LatencyManager = function(playerInstance, timeserver, configuration) {
this.version = "1.0.3"
//Event Listeners
this.listeners = {};
//THEOplayer instance
this.player = playerInstance;
//frequency of the update
this.interval = 100;
//instance of TimeServer must support timeserver.getServerTime() : Date()
this.timeserver = timeserver;
//target latency value the player must
this.targetlatency = 5000;
//window around targetlatency the manager will consider in sync
this.latencywindow = 250;
//window around targetlatency the manager considers to fire seek command rather than change playbackrate
this.seekwindow = 2500;
//the current latency of the player
//== this.timeServer.getServerTime() - this.player.currentProgramDateTime
this.currentlatency = 0;
//If buffer is below this value, latencymanager will not act
this.safebuffervalue = HAVE_ENOUGH_DATA;
//maximum increase/decrease in speed
this.ratechange = 0.08;
//Allow the player to be early (currentatency < targetLatency is ok)
this.allowearly = false;
//when in this mode the manager will chase targetLatency +/- (latencyWindow / 2)
this.catchingup = true;
//manager is paused
this.paused = false;
//manager has started
this._started = false;
this._timeout = null;
this.fireupdate = true;
this.now = Date();
this.servernow = Date();
this.programDateTime = Date();
this.enableoverlay = false;
//lastseek is used to avoid firing multiple seek commands
this._lastSeek = new Date();
//seektimeout is used in combination with _lastseek
//manager will not issue more than 1 seek command per _seekTimeout (in ms)
this._seekTimeOut = 1000;
this.currenthigh = 0;
this.currentlow = 0;
this.seekhigh = 0;
this.seeklow = 0;
this.pgdtrequest = 0;
this.disableOnPause = false;
this.sync = true;
//additional fix to compensate for encoder/packager latency
this.encoderlatency = 0;
this.currentpackagerlatency = 0;
this.currentpackagerDateTime = 0;
this.currentencoderlatency = 0;
this.encodertime = 0;
this.useencodertime = false;
this.SEEKTIMEOUT = 2000;
this.isSynced = function() {
return this.currentLow <= this.currentlatency &&
this.currentlatency < this.currentHigh;
}
this.update = function() {
if (!this.player.paused) {
this.now = Date.now();
this.programDateTime = this.player.currentProgramDateTime;
this.pgdtrequest = Date.now() - this.now;
this.servernow = this.timeserver.getServerTime();
this.currentlatency = this.servernow - this.programDateTime;
this.currentpackagerlatency = this.currentlatency;
this.currentencoderlatency = this.currentlatency - this.encoderlatency;
this.encodertime = this.programDateTime - this.encoderlatency;
this.packagertime = this.programDateTime;
if (!this.paused) {
this.currenthigh = this.targetlatency + this.latencywindow;
this.currentlow = this.targetlatency - this.latencywindow;
this.seekhigh = this.targetlatency + this.seekwindow;
this.seeklow = this.targetlatency - this.seekwindow;
if (this.catchingup) {
this.currenthigh = this.targetlatency + (this.latencywindow / 2);
this.currentlow = this.targetlatency - (this.latencywindow / 2);
}
if (this.currentlatency < this.seeklow) {
this._setpbr(1 - this.ratechange);
this._seekToSync();
} else if (this.currentlatency > this.seekhigh) {
this._setpbr(1 + this.ratechange);
this._seekToSync();
} else if (this.currentlatency > this.currenthigh) {
this.catchingup = true;
this._setpbr(1 + this.ratechange);
} else if (!this.allowearly && (this.currentlatency < this.currentlow)) {
this.catchingup = true;
this._setpbr(1 - this.ratechange);
} else {
this.catchingup = false;
this._setpbr(1);
}
} else {
this._setpbr(1);
}
this.sendupdate();
}
if (this._started)
this._timeout = setTimeout(this.update, this.interval);
}.bind(this);
this.sendupdate = function() {
if (this.fireupdate) {
var l = this.getLatency();
theoplayerAndroid.sendMessage('THEOplayer.latencyManager.update', JSON.stringify(l));
}
}.bind(this);
this.lastSeek = 0;
//seek to the synchronisation point
this._seekToSync = function() {
var diff = ((this.timeserver.getServerTime() - this.player.currentProgramDateTime) - this.targetlatency) / 1000.0;
this._seekTo(this.player.currentTime + diff);
}.bind(this);
this._lastSeek = 0;
//seek to a specific time
this._seekTo = function(time) {
var currentSeek = new Date().getTime();
if (!this.player.seeking && (currentSeek - this._lastSeek) > this.SEEKTIMEOUT) {
this._lastSeek = new Date().getTime();
this.player.currentTime = time;
this.dispatchEvent(new CustomEvent("seek", {
detail: {
to: time
}
}));
}
}.bind(this);
//Evaluates whether the player has a buffer state that allows the manager to actively manage the player
//to avoid buffer underruns
this.hasSafeBuffer = function() {
return this.player.readyState >= this.safebuffervalue
}.bind(this)
//set the players playbackrate if it is in a safe state
this._setpbr = function(pbr) {
if (this.player.playbackRate !== pbr) {
if (pbr > 1) {
if (this.hasSafeBuffer()) {
var oldpbr = this.player.playbackRate;
this.player.playbackRate = pbr;
this.dispatchEvent(new CustomEvent("ratechange", {
detail: {
old: oldpbr,
new: pbr
}
}));
}
} else {
var oldpbr = this.player.playbackRate;
this.player.playbackRate = pbr;
this.dispatchEvent(new CustomEvent("ratechange", {
detail: {
old: oldpbr,
new: pbr
}
}));
}
}
}.bind(this);
//start the manager
this.start = function() {
if (!this._started) {
this._started = true;
this._timeout = setTimeout(this.update, this.interval);
this.dispatchEvent(new CustomEvent("started"));
}
}.bind(this);
//stop the manager
this.stop = function() {
if (this._started) {
clearTimeout(this._timeout)
this._timeout = null;
this._started = false;
this.dispatchEvent(new CustomEvent("stopped"));
}
}.bind(this);
this.configure = function(config) {
if (typeof config === "string")
config = JSON.parse(config);
this.targetlatency = config.targetlatency || 5000;
this.latencywindow = config.latencywindow || 250;
this.seekwindow = config.seekwindow || 5000;
this.interval = config.interval || 200;
this.ratechange = config.ratechange || 0.08;
this.fireupdate = config.fireupdate || true;
this.disableOnPause = config.disableonpause || false;
this.sync = config.sync || true;
this.encoderlatency = config.encoderlatency || 0;
this.useencodertime = config.useencodertime || false;
if (THEOplayer.timeServer && (THEOplayer.timeServer.timeserver !== config.timeserver)) {
THEOplayer.timeServer.timeserver = config.timeserver;
THEOplayer.timeServer.sync();
}
this.pause(false);
}.bind(this);
this.getConfiguration = function() {
return {
targetlatency: this.targetlatency,
latencywindow: this.latencywindow,
seekwindow: this.seekwindow,
interval: this.interval,
ratechange: this.ratechange,
fireupdate: this.fireupdate,
sync: this.sync
}
}.bind(this);
this.getLatency = function() {
return {
currentlatency: this.currentlatency,
localtime: this.now,
programdatetime: this.programDateTime.getTime(),
servertime: this.servernow.getTime()
}
}.bind(this);
this.getLatencyString = function() {
return JSON.stringify(this.getLatency())
}.bind(this);
//listen for an event of type 'type'
this.addEventListener = function(type, callback) {
if (!(type in this.listeners)) {
this.listeners[type] = [];
}
this.listeners[type].push(callback);
};
//remove eventlistener
this.removeEventListener = function(type, callback) {
if (!(type in this.listeners)) {
return;
}
var stack = this.listeners[type];
for (var i = 0, l = stack.length; i < l; i++) {
if (stack[i] === callback) {
stack.splice(i, 1);
return;
}
}
};
//fire event
this.dispatchEvent = function(event) {
if (!(event.type in this.listeners)) {
return true;
}
var stack = this.listeners[event.type].slice();
for (var i = 0, l = stack.length; i < l; i++) {
stack[i].call(this, event);
}
return !event.defaultPrevented;
};
this.pause = function(isPaused) {
this.paused = isPaused;
if (this._started) {
if (!isPaused)
this._seekToSync();
}
};
this.configure(configuration);
}
THEOplayer.initializeLatencyManager = function(playerInstance, configuration) {
if (typeof configuration === "string")
configuration = JSON.parse(configuration);
var player = playerInstance;
if (!player)
player = THEOplayer.players[0];
var ts = "https://time.akamai.com/?iso&ms";
if (configuration.timeserver)
ts = configuration.timeserver;
var timeinterval = 300;
if (configuration.timeinterval)
timeinterval = configuration.timeinterval;
THEOplayer.timeServer = new THEOplayer.TimeServer(ts, timeinterval);
if (configuration.sync === undefined || configuration.sync === true)
THEOplayer.timeServer.sync();
THEOplayer.playingcount = 0;
THEOplayer.latencyManager = new THEOplayer.LatencyManager(player, THEOplayer.timeServer, configuration);
player.addEventListener("playing", function() {
if (THEOplayer.playingcount === 0) {
THEOplayer.timeServer.sync();
THEOplayer.latencyManager.start();
THEOplayer.latencyManager.pause(false);
}
THEOplayer.playingcount++;
});
player.addEventListener("sourcechange", function() {
THEOplayer.latencyManager.stop();
THEOplayer.playingcount = 0;
});
}
}());