@microsoft/live-share-media 1.0.0-preview.9 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +64 -61
  2. package/README.md +7 -13
  3. package/bin/IMediaPlayer.d.ts +20 -20
  4. package/bin/IMediaPlayer.js +6 -6
  5. package/bin/LiveMediaSession.d.ts +90 -94
  6. package/bin/LiveMediaSession.d.ts.map +1 -1
  7. package/bin/LiveMediaSession.js +228 -231
  8. package/bin/LiveMediaSession.js.map +1 -1
  9. package/bin/LiveMediaSessionCoordinator.d.ts +238 -227
  10. package/bin/LiveMediaSessionCoordinator.d.ts.map +1 -1
  11. package/bin/LiveMediaSessionCoordinator.js +476 -407
  12. package/bin/LiveMediaSessionCoordinator.js.map +1 -1
  13. package/bin/LiveMediaSessionCoordinatorSuspension.d.ts +19 -19
  14. package/bin/LiveMediaSessionCoordinatorSuspension.js +27 -27
  15. package/bin/MediaPlayerSynchronizer.d.ts +174 -163
  16. package/bin/MediaPlayerSynchronizer.d.ts.map +1 -1
  17. package/bin/MediaPlayerSynchronizer.js +503 -468
  18. package/bin/MediaPlayerSynchronizer.js.map +1 -1
  19. package/bin/MediaSessionActionThrottler.d.ts +11 -11
  20. package/bin/MediaSessionActionThrottler.js +13 -13
  21. package/bin/MediaSessionExtensions.d.ts +34 -34
  22. package/bin/MediaSessionExtensions.d.ts.map +1 -1
  23. package/bin/MediaSessionExtensions.js +12 -12
  24. package/bin/RepeatedActionThrottler.d.ts +19 -19
  25. package/bin/RepeatedActionThrottler.js +62 -62
  26. package/bin/RepeatedActionThrottler.js.map +1 -1
  27. package/bin/VolumeManager.d.ts +83 -83
  28. package/bin/VolumeManager.d.ts.map +1 -1
  29. package/bin/VolumeManager.js +174 -174
  30. package/bin/VolumeManager.js.map +1 -1
  31. package/bin/index.d.ts +13 -13
  32. package/bin/index.js +29 -29
  33. package/bin/internals/GroupCoordinatorState.d.ts +93 -92
  34. package/bin/internals/GroupCoordinatorState.d.ts.map +1 -1
  35. package/bin/internals/GroupCoordinatorState.js +407 -404
  36. package/bin/internals/GroupCoordinatorState.js.map +1 -1
  37. package/bin/internals/GroupPlaybackPosition.d.ts +67 -66
  38. package/bin/internals/GroupPlaybackPosition.d.ts.map +1 -1
  39. package/bin/internals/GroupPlaybackPosition.js +165 -166
  40. package/bin/internals/GroupPlaybackPosition.js.map +1 -1
  41. package/bin/internals/GroupPlaybackTrack.d.ts +45 -45
  42. package/bin/internals/GroupPlaybackTrack.d.ts.map +1 -1
  43. package/bin/internals/GroupPlaybackTrack.js +121 -121
  44. package/bin/internals/GroupPlaybackTrackData.d.ts +39 -39
  45. package/bin/internals/GroupPlaybackTrackData.d.ts.map +1 -1
  46. package/bin/internals/GroupPlaybackTrackData.js +69 -69
  47. package/bin/internals/GroupTransportState.d.ts +49 -48
  48. package/bin/internals/GroupTransportState.d.ts.map +1 -1
  49. package/bin/internals/GroupTransportState.js +111 -111
  50. package/bin/internals/GroupTransportState.js.map +1 -1
  51. package/bin/internals/consts.d.ts +75 -72
  52. package/bin/internals/consts.d.ts.map +1 -1
  53. package/bin/internals/consts.js +84 -81
  54. package/bin/internals/consts.js.map +1 -1
  55. package/bin/internals/index.d.ts +10 -10
  56. package/bin/internals/index.js +26 -26
  57. package/package.json +16 -9
  58. package/src/LiveMediaSession.ts +24 -20
  59. package/src/LiveMediaSessionCoordinator.ts +101 -29
  60. package/src/MediaPlayerSynchronizer.ts +47 -15
  61. package/src/VolumeManager.ts +4 -1
  62. package/src/internals/GroupCoordinatorState.ts +50 -35
  63. package/src/internals/GroupPlaybackPosition.ts +8 -7
  64. package/src/internals/GroupPlaybackTrack.ts +2 -2
  65. package/src/internals/GroupPlaybackTrackData.ts +2 -2
  66. package/src/internals/GroupTransportState.ts +11 -4
  67. package/src/internals/consts.ts +4 -0
  68. package/typedoc.json +10 -0
  69. package/bin/EphemeralMediaSession.d.ts +0 -102
  70. package/bin/EphemeralMediaSession.d.ts.map +0 -1
  71. package/bin/EphemeralMediaSession.js +0 -226
  72. package/bin/EphemeralMediaSession.js.map +0 -1
  73. package/bin/EphemeralMediaSessionCoordinator.d.ts +0 -228
  74. package/bin/EphemeralMediaSessionCoordinator.d.ts.map +0 -1
  75. package/bin/EphemeralMediaSessionCoordinator.js +0 -396
  76. package/bin/EphemeralMediaSessionCoordinator.js.map +0 -1
  77. package/bin/EphemeralMediaSessionCoordinatorSuspension.d.ts +0 -20
  78. package/bin/EphemeralMediaSessionCoordinatorSuspension.d.ts.map +0 -1
  79. package/bin/EphemeralMediaSessionCoordinatorSuspension.js +0 -28
  80. package/bin/EphemeralMediaSessionCoordinatorSuspension.js.map +0 -1
  81. package/bin/VolumeLimiter.d.ts +0 -70
  82. package/bin/VolumeLimiter.d.ts.map +0 -1
  83. package/bin/VolumeLimiter.js +0 -170
  84. package/bin/VolumeLimiter.js.map +0 -1
  85. package/src/test/GroupPlaybackPosition.spec.ts +0 -600
  86. package/src/test/GroupPlaybackTrack.spec.ts +0 -122
  87. package/src/test/SharedMediaSession.spec.ts +0 -149
  88. package/src/test/SharedMediaSessionCoordinator.spec.ts +0 -271
  89. package/src/test/VolumeManager.spec.ts +0 -219
@@ -1,408 +1,477 @@
1
- "use strict";
2
- /**
3
- * Copyright (c) Microsoft Corporation. All rights reserved.
4
- * Licensed under the Microsoft Live Share SDK License.
5
- */
6
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
- return new (P || (P = Promise))(function (resolve, reject) {
9
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
- step((generator = generator.apply(thisArg, _arguments || [])).next());
13
- });
14
- };
15
- var __importDefault = (this && this.__importDefault) || function (mod) {
16
- return (mod && mod.__esModule) ? mod : { "default": mod };
17
- };
18
- Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.LiveMediaSessionCoordinator = void 0;
20
- const live_share_1 = require("@microsoft/live-share");
21
- const internals_1 = require("./internals");
22
- const LiveMediaSessionCoordinatorSuspension_1 = require("./LiveMediaSessionCoordinatorSuspension");
23
- const events_1 = __importDefault(require("events"));
24
- /**
25
- * The `LiveMediaSessionCoordinator` tracks the playback & position state of all other
26
- * clients being synchronized with. It is responsible for keeping the local media player
27
- * in sync with the group.
28
- */
29
- class LiveMediaSessionCoordinator extends events_1.default {
30
- /**
31
- * @hidden
32
- * Applications shouldn't directly create new coordinator instances.
33
- */
34
- constructor(runtime, getPlayerState) {
35
- super();
36
- this._positionUpdateInterval = new live_share_1.TimeInterval(2000);
37
- this._maxPlaybackDrift = new live_share_1.TimeInterval(1000);
38
- this._hasInitialized = false;
39
- /**
40
- * Controls whether or not the local client is allowed to instruct the group to play or pause.
41
- *
42
- * @remarks
43
- * This flag largely meant to influence decisions made by the coordinator and can be used by
44
- * the UI to determine what controls should be shown to the user. It does not provide any
45
- * security in itself.
46
- *
47
- * If your app is running in a semi-trusted environment where only some clients are allowed
48
- * to play/pause media, you should use "role based verification" to enforce those policies.
49
- */
50
- this.canPlayPause = true;
51
- /**
52
- * Controls whether or not the local client is allowed to seek the group to a new playback
53
- * position.
54
- *
55
- * @remarks
56
- * This flag largely meant to influence decisions made by the coordinator and can be used by
57
- * the UI to determine what controls should be shown to the user. It does not provide any
58
- * security in itself.
59
- *
60
- * If your app is running in a semi-trusted environment where only some clients are allowed
61
- * to change the playback position, you should use "role based verification" to enforce those policies.
62
- */
63
- this.canSeek = true;
64
- /**
65
- * Controls whether or not the local client is allowed to change tracks.
66
- *
67
- * @remarks
68
- * This flag largely meant to influence decisions made by the coordinator and can be used by
69
- * the UI to determine what controls should be shown to the user. It does not provide any
70
- * security in itself.
71
- *
72
- * If your app is running in a semi-trusted environment where only some clients are allowed
73
- * to change tracks, you should use "role based verification" to enforce those policies.
74
- */
75
- this.canSetTrack = true;
76
- /**
77
- * Controls whether or not the local client is allowed to change the tracks custom data object.
78
- *
79
- * @remarks
80
- * This flag largely meant to influence decisions made by the coordinator and can be used by
81
- * the UI to determine what controls should be shown to the user. It does not provide any
82
- * security in itself.
83
- *
84
- * If your app is running in a semi-trusted environment where only some clients are allowed
85
- * to change the tracks data object, you should use "role based verification" to enforce those
86
- * policies.
87
- */
88
- this.canSetTrackData = true;
89
- this._runtime = runtime;
90
- this._logger = new live_share_1.LiveTelemetryLogger(runtime);
91
- this._getPlayerState = getPlayerState;
92
- }
93
- /**
94
- * Returns true if the local client is in a suspended state.
95
- */
96
- get isSuspended() {
97
- return this._groupState ? this._groupState.isSuspended : false;
98
- }
99
- /**
100
- * Max amount of playback drift allowed in seconds.
101
- *
102
- * @remarks
103
- * Should the local clients playback position lag by more than the specified value, the
104
- * coordinator will trigger a `catchup` action.
105
- *
106
- * Defaults to a value of `1` second.
107
- */
108
- get maxPlaybackDrift() {
109
- return this._maxPlaybackDrift.seconds;
110
- }
111
- set maxPlaybackDrift(value) {
112
- this._maxPlaybackDrift.seconds = value;
113
- }
114
- /**
115
- * Frequency with which position updates are broadcast to the rest of the group in
116
- * seconds.
117
- *
118
- * @remarks
119
- * Defaults to a value of `2` seconds.
120
- */
121
- get positionUpdateInterval() {
122
- return this._positionUpdateInterval.seconds;
123
- }
124
- set positionUpdateInterval(value) {
125
- this._positionUpdateInterval.seconds = value;
126
- }
127
- /**
128
- * Instructs the group to play the current track.
129
- *
130
- * @remarks
131
- * Throws an exception if the session/coordinator hasn't been initialized, no track has been
132
- * loaded, or `canPlayPause` is false.
133
- */
134
- play() {
135
- var _a;
136
- if (!this._hasInitialized) {
137
- throw new Error(`LiveMediaSessionCoordinator.play() called before initialize() called.`);
138
- }
139
- if (!((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.current.metadata)) {
140
- throw new Error(`LiveMediaSessionCoordinator.play() called before MediaSession.metadata assigned.`);
141
- }
142
- if (!this.canPlayPause) {
143
- throw new Error(`LiveMediaSessionCoordinator.play() operation blocked.`);
144
- }
145
- // Get projected position
146
- const position = this.getPlayerPosition();
147
- // Send transport command
148
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.PlayCalled, null, { position: position });
149
- this._playEvent.sendEvent({
150
- track: this._groupState.playbackTrack.current,
151
- position: position,
152
- });
153
- }
154
- /**
155
- * Instructs the group to pause the current track.
156
- *
157
- * @remarks
158
- * Throws an exception if the session/coordinator hasn't been initialized, no track has been
159
- * loaded, or `canPlayPause` is false.
160
- */
161
- pause() {
162
- var _a;
163
- if (!this._hasInitialized) {
164
- throw new Error(`LiveMediaSessionCoordinator.pause() called before initialize() called.`);
165
- }
166
- if (!((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.current.metadata)) {
167
- throw new Error(`LiveMediaSessionCoordinator.pause() called before MediaSession.metadata assigned.`);
168
- }
169
- if (!this.canPlayPause) {
170
- throw new Error(`LiveMediaSessionCoordinator.pause() operation blocked.`);
171
- }
172
- // Get projected position
173
- const position = this.getPlayerPosition();
174
- // Send transport command
175
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.PauseCalled, null, { position: position });
176
- this._pauseEvent.sendEvent({
177
- track: this._groupState.playbackTrack.current,
178
- position: position,
179
- });
180
- }
181
- /**
182
- * Instructs the group to seek to a new position within the current track.
183
- *
184
- * @remarks
185
- * Throws an exception if the session/coordinator hasn't been initialized, no track has been
186
- * loaded, or `canSeek` is false.
187
- * @param time Playback position in seconds to seek to.
188
- */
189
- seekTo(time) {
190
- var _a;
191
- if (!this._hasInitialized) {
192
- throw new Error(`LiveMediaSessionCoordinator.seekTo() called before initialize() called.`);
193
- }
194
- if (!((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.current.metadata)) {
195
- throw new Error(`LiveMediaSessionCoordinator.seekTo() called before MediaSession.metadata assigned.`);
196
- }
197
- if (!this.canSeek) {
198
- throw new Error(`LiveMediaSessionCoordinator.seekTo() operation blocked.`);
199
- }
200
- // Send transport command
201
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.SeekToCalled, null, { position: time });
202
- this._seekToEvent.sendEvent({
203
- track: this._groupState.playbackTrack.current,
204
- position: time,
205
- });
206
- }
207
- /**
208
- * Instructs the group to load a new track.
209
- *
210
- * @remarks
211
- * Throws an exception if the session/coordinator hasn't been initialized or `canSetTrack` is
212
- * false.
213
- * @param metadata The track to load or `null` to indicate that the end of the track is reached.
214
- * @param waitPoints Optional. List of static wait points to configure for the track. Dynamic wait points can be added via the `beginSuspension()` call.
215
- */
216
- setTrack(metadata, waitPoints) {
217
- if (!this._hasInitialized) {
218
- throw new Error(`LiveMediaSessionCoordinator.setTrack() called before initialize() called.`);
219
- }
220
- if (!this.canSetTrack) {
221
- throw new Error(`LiveMediaSessionCoordinator.setTrack() operation blocked.`);
222
- }
223
- // Send transport command
224
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.SetTrackCalled);
225
- this._setTrackEvent.sendEvent({
226
- metadata: metadata,
227
- waitPoints: waitPoints || [],
228
- });
229
- }
230
- /**
231
- * Updates the track data object for the current track.
232
- *
233
- * @remarks
234
- * The track data object can be used by applications to synchronize things like pitch, roll,
235
- * and yaw of a 360 video. This data object will be reset to null anytime the track changes.
236
- *
237
- * Throws an exception if the session/coordinator hasn't been initialized or `canSetTrackData` is
238
- * false.
239
- * @param data New data object to sync with the group. This value will be synchronized using a last writer wins strategy.
240
- */
241
- setTrackData(data) {
242
- if (!this._hasInitialized) {
243
- throw new Error(`LiveMediaSessionCoordinator.setTrackData() called before initialize() called.`);
244
- }
245
- if (!this.canSetTrackData) {
246
- throw new Error(`LiveMediaSessionCoordinator.setTrackData() operation blocked.`);
247
- }
248
- // Send transport command
249
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.SetTrackDataCalled);
250
- this._setTrackDataEvent.sendEvent({
251
- data: data,
252
- });
253
- }
254
- /**
255
- * Begins a new local suspension.
256
- *
257
- * @remarks
258
- * Suspension temporarily suspend the clients local synchronization with the group. This can
259
- * be useful for displaying ads to users or temporarily disconnecting from the session while
260
- * the user seeks the video using a timeline scrubber.
261
- *
262
- * Multiple simultaneous suspensions are allowed and when the last suspension ends the local
263
- * client will be immediately re-synchronized with the group.
264
- *
265
- * A "Dynamic Wait Point" can be specified when `beginSuspension()` is called and the wait
266
- * point will be broadcast to all other clients in the group. Those clients will then
267
- * automatically enter a suspension state once they reach the positions specified by the
268
- * wait point. Clients that are passed the wait point will immediately suspend.
269
- *
270
- * Any wait point based suspension (dynamic or static) will result in all clients remaining
271
- * in a suspension state until the list client ends their suspension. This behavior can be
272
- * conditionally bypassed by settings the wait points `maxClients` value.
273
- *
274
- * Throws an exception if the session/coordinator hasn't been initialized.
275
- * @param waitPoint Optional. Dynamic wait point to broadcast to all of the clients.
276
- * @returns The suspension object. Call `end()` on the returned suspension to end the suspension.
277
- */
278
- beginSuspension(waitPoint) {
279
- var _a;
280
- if (!this._hasInitialized) {
281
- throw new Error(`LiveMediaSessionCoordinator.beginSuspension() called before initialize() called.`);
282
- }
283
- if (!((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.current.metadata)) {
284
- throw new Error(`LiveMediaSessionCoordinator.beginSuspension() called before MediaSession.metadata assigned.`);
285
- }
286
- // Tell group state that suspension is started
287
- if (waitPoint) {
288
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.BeginSuspensionAndWait, null, {
289
- position: waitPoint.position,
290
- maxClients: waitPoint.maxClients,
291
- });
292
- this._lastWaitPoint = waitPoint;
293
- this._groupState.beginSuspension(waitPoint);
294
- }
295
- else {
296
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.BeginSuspension);
297
- this._groupState.beginSuspension();
298
- }
299
- // Return new suspension object
300
- return new LiveMediaSessionCoordinatorSuspension_1.LiveMediaSessionCoordinatorSuspension(waitPoint, (time) => {
301
- var _a, _b;
302
- if (waitPoint) {
303
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.EndSuspensionAndWait, null, {
304
- position: waitPoint.position,
305
- maxClients: waitPoint.maxClients,
306
- });
307
- }
308
- else {
309
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.EndSuspension);
310
- }
311
- this._groupState.endSuspension(time == undefined);
312
- if (time != undefined &&
313
- !((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.isSuspended) &&
314
- !((_b = this._groupState) === null || _b === void 0 ? void 0 : _b.isWaiting)) {
315
- // Seek to new position
316
- this.seekTo(Math.max(time, 0.0));
317
- }
318
- });
319
- }
320
- /**
321
- * @hidden
322
- * Called by MediaSession to verify the coordinator has been initialized.
323
- */
324
- get isInitialized() {
325
- return this._hasInitialized;
326
- }
327
- /**
328
- * @hidden
329
- * Called by MediaSession to start coordinator.
330
- */
331
- initialize(acceptTransportChangesFrom) {
332
- return __awaiter(this, void 0, void 0, function* () {
333
- if (this._hasInitialized) {
334
- throw new Error(`LiveMediaSessionCoordinator.initialize() already initialized.`);
335
- }
336
- // Create children
337
- yield this.createChildren(acceptTransportChangesFrom);
338
- this._hasInitialized = true;
339
- });
340
- }
341
- /**
342
- * @hidden
343
- * Called by the MediaSession to detect if a wait point has been hit.
344
- */
345
- findNextWaitPoint() {
346
- var _a;
347
- return (((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.findNextWaitPoint(this._lastWaitPoint)) || null);
348
- }
349
- /**
350
- * @hidden
351
- * Called by MediaSession to trigger the sending of a position update.
352
- */
353
- sendPositionUpdate(state) {
354
- var _a;
355
- if (!this._hasInitialized) {
356
- throw new Error(`LiveMediaSessionCoordinator.sendPositionUpdate() called before initialize() called.`);
357
- }
358
- // Send position update event
359
- const evt = this._groupState.createPositionUpdateEvent(state);
360
- (_a = this._positionUpdateEvent) === null || _a === void 0 ? void 0 : _a.sendEvent(evt);
361
- }
362
- createChildren(acceptTransportChangesFrom) {
363
- return __awaiter(this, void 0, void 0, function* () {
364
- // Create event scopes
365
- const scope = new live_share_1.LiveEventScope(this._runtime, acceptTransportChangesFrom);
366
- const unrestrictedScope = new live_share_1.LiveEventScope(this._runtime);
367
- // Initialize internal coordinator state
368
- this._groupState = new internals_1.GroupCoordinatorState(this._runtime, this._maxPlaybackDrift, this._positionUpdateInterval, this._getPlayerState);
369
- this._groupState.on(internals_1.GroupCoordinatorStateEvents.triggeraction, (evt) => this.emit(evt.name, evt));
370
- // Listen for track changes
371
- this._setTrackEvent = new live_share_1.LiveEventTarget(scope, "setTrack", (event, local) => this._groupState.handleSetTrack(event, local));
372
- this._setTrackDataEvent = new live_share_1.LiveEventTarget(scope, "setTrackData", (event, local) => this._groupState.handleSetTrackData(event, local));
373
- // Listen for transport commands
374
- this._playEvent = new live_share_1.LiveEventTarget(scope, "play", (event, local) => this._groupState.handleTransportCommand(event, local));
375
- this._pauseEvent = new live_share_1.LiveEventTarget(scope, "pause", (event, local) => this._groupState.handleTransportCommand(event, local));
376
- this._seekToEvent = new live_share_1.LiveEventTarget(scope, "seekTo", (event, local) => this._groupState.handleTransportCommand(event, local));
377
- // Listen for position updates
378
- this._positionUpdateEvent = new live_share_1.LiveEventTarget(unrestrictedScope, "positionUpdate", (event, local) => this._groupState.handlePositionUpdate(event, local));
379
- // Listen for joined event
380
- this._joinedEvent = new live_share_1.LiveEventTarget(unrestrictedScope, "joined", (evt, local) => {
381
- var _a;
382
- // Immediately send a position update
383
- this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.RemoteJoinReceived, null, {
384
- correlationId: live_share_1.LiveTelemetryLogger.formatCorrelationId(evt.clientId, evt.timestamp),
385
- });
386
- const state = this._getPlayerState();
387
- const update = this._groupState.createPositionUpdateEvent(state);
388
- (_a = this._positionUpdateEvent) === null || _a === void 0 ? void 0 : _a.sendEvent(update);
389
- });
390
- // Send initial joined event
391
- this._joinedEvent.sendEvent({});
392
- });
393
- }
394
- getPlayerPosition() {
395
- const { positionState, playbackState } = this._getPlayerState();
396
- switch (playbackState) {
397
- case "none":
398
- case "ended":
399
- return 0.0;
400
- default:
401
- return positionState && positionState.position != undefined
402
- ? positionState.position
403
- : 0.0;
404
- }
405
- }
406
- }
407
- exports.LiveMediaSessionCoordinator = LiveMediaSessionCoordinator;
1
+ "use strict";
2
+ /**
3
+ * Copyright (c) Microsoft Corporation. All rights reserved.
4
+ * Licensed under the Microsoft Live Share SDK License.
5
+ */
6
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
7
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
8
+ return new (P || (P = Promise))(function (resolve, reject) {
9
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
10
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
11
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
12
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
13
+ });
14
+ };
15
+ var __importDefault = (this && this.__importDefault) || function (mod) {
16
+ return (mod && mod.__esModule) ? mod : { "default": mod };
17
+ };
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.LiveMediaSessionCoordinator = void 0;
20
+ const live_share_1 = require("@microsoft/live-share");
21
+ const internals_1 = require("./internals");
22
+ const LiveMediaSessionCoordinatorSuspension_1 = require("./LiveMediaSessionCoordinatorSuspension");
23
+ const events_1 = __importDefault(require("events"));
24
+ /**
25
+ * The `LiveMediaSessionCoordinator` tracks the playback & position state of all other
26
+ * clients being synchronized with. It is responsible for keeping the local media player
27
+ * in sync with the group.
28
+ */
29
+ class LiveMediaSessionCoordinator extends events_1.default {
30
+ /**
31
+ * @hidden
32
+ * Applications shouldn't directly create new coordinator instances.
33
+ */
34
+ constructor(runtime, liveRuntime, getPlayerState) {
35
+ super();
36
+ this._positionUpdateInterval = new live_share_1.TimeInterval(2000);
37
+ this._maxPlaybackDrift = new live_share_1.TimeInterval(1000);
38
+ this._hasInitialized = false;
39
+ /**
40
+ * Controls whether or not the local client is allowed to instruct the group to play or pause.
41
+ *
42
+ * @remarks
43
+ * This flag largely meant to influence decisions made by the coordinator and can be used by
44
+ * the UI to determine what controls should be shown to the user. It does not provide any
45
+ * security in itself.
46
+ *
47
+ * If your app is running in a semi-trusted environment where only some clients are allowed
48
+ * to play/pause media, you should use "role based verification" to enforce those policies.
49
+ */
50
+ this.canPlayPause = true;
51
+ /**
52
+ * Controls whether or not the local client is allowed to seek the group to a new playback
53
+ * position.
54
+ *
55
+ * @remarks
56
+ * This flag largely meant to influence decisions made by the coordinator and can be used by
57
+ * the UI to determine what controls should be shown to the user. It does not provide any
58
+ * security in itself.
59
+ *
60
+ * If your app is running in a semi-trusted environment where only some clients are allowed
61
+ * to change the playback position, you should use "role based verification" to enforce those policies.
62
+ */
63
+ this.canSeek = true;
64
+ /**
65
+ * Controls whether or not the local client is allowed to change tracks.
66
+ *
67
+ * @remarks
68
+ * This flag largely meant to influence decisions made by the coordinator and can be used by
69
+ * the UI to determine what controls should be shown to the user. It does not provide any
70
+ * security in itself.
71
+ *
72
+ * If your app is running in a semi-trusted environment where only some clients are allowed
73
+ * to change tracks, you should use "role based verification" to enforce those policies.
74
+ */
75
+ this.canSetTrack = true;
76
+ /**
77
+ * Controls whether or not the local client is allowed to change the tracks custom data object.
78
+ *
79
+ * @remarks
80
+ * This flag largely meant to influence decisions made by the coordinator and can be used by
81
+ * the UI to determine what controls should be shown to the user. It does not provide any
82
+ * security in itself.
83
+ *
84
+ * If your app is running in a semi-trusted environment where only some clients are allowed
85
+ * to change the tracks data object, you should use "role based verification" to enforce those
86
+ * policies.
87
+ */
88
+ this.canSetTrackData = true;
89
+ this._runtime = runtime;
90
+ this._liveRuntime = liveRuntime;
91
+ this._logger = new live_share_1.LiveTelemetryLogger(runtime, liveRuntime);
92
+ this._getPlayerState = getPlayerState;
93
+ }
94
+ /**
95
+ * Returns true if the local client is in a suspended state.
96
+ */
97
+ get isSuspended() {
98
+ return this._groupState ? this._groupState.isSuspended : false;
99
+ }
100
+ /**
101
+ * Max amount of playback drift allowed in seconds.
102
+ *
103
+ * @remarks
104
+ * Should the local clients playback position lag by more than the specified value, the
105
+ * coordinator will trigger a `catchup` action.
106
+ *
107
+ * Defaults to a value of `1` second.
108
+ */
109
+ get maxPlaybackDrift() {
110
+ return this._maxPlaybackDrift.seconds;
111
+ }
112
+ set maxPlaybackDrift(value) {
113
+ this._maxPlaybackDrift.seconds = value;
114
+ }
115
+ /**
116
+ * Frequency with which position updates are broadcast to the rest of the group in
117
+ * seconds.
118
+ *
119
+ * @remarks
120
+ * Defaults to a value of `2` seconds.
121
+ */
122
+ get positionUpdateInterval() {
123
+ return this._positionUpdateInterval.seconds;
124
+ }
125
+ set positionUpdateInterval(value) {
126
+ this._positionUpdateInterval.seconds = value;
127
+ }
128
+ /**
129
+ * Instructs the group to play the current track.
130
+ *
131
+ * @remarks
132
+ * Throws an exception if the session/coordinator hasn't been initialized, no track has been
133
+ * loaded, or `canPlayPause` is false.
134
+ *
135
+ * @returns a void promise that resolves once complete, throws if user does not have proper roles
136
+ */
137
+ play() {
138
+ var _a;
139
+ return __awaiter(this, void 0, void 0, function* () {
140
+ if (!this._hasInitialized) {
141
+ throw new Error(`LiveMediaSessionCoordinator.play() called before initialize() called.`);
142
+ }
143
+ if (!((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.current.metadata)) {
144
+ throw new Error(`LiveMediaSessionCoordinator.play() called before MediaSession.metadata assigned.`);
145
+ }
146
+ if (!this.canPlayPause) {
147
+ throw new Error(`LiveMediaSessionCoordinator.play() operation blocked.`);
148
+ }
149
+ // Get projected position
150
+ const position = this.getPlayerPosition();
151
+ // Send transport command
152
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.PlayCalled, null, { position: position });
153
+ yield this._playEvent.sendEvent({
154
+ track: this._groupState.playbackTrack.current,
155
+ position: position,
156
+ });
157
+ });
158
+ }
159
+ /**
160
+ * Instructs the group to pause the current track.
161
+ *
162
+ * @remarks
163
+ * Throws an exception if the session/coordinator hasn't been initialized, no track has been
164
+ * loaded, or `canPlayPause` is false.
165
+ *
166
+ * @returns a void promise that resolves once complete, throws if user does not have proper roles
167
+ */
168
+ pause() {
169
+ var _a;
170
+ return __awaiter(this, void 0, void 0, function* () {
171
+ if (!this._hasInitialized) {
172
+ throw new Error(`LiveMediaSessionCoordinator.pause() called before initialize() called.`);
173
+ }
174
+ if (!((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.current.metadata)) {
175
+ throw new Error(`LiveMediaSessionCoordinator.pause() called before MediaSession.metadata assigned.`);
176
+ }
177
+ if (!this.canPlayPause) {
178
+ throw new Error(`LiveMediaSessionCoordinator.pause() operation blocked.`);
179
+ }
180
+ // Get projected position
181
+ const position = this.getPlayerPosition();
182
+ // Send transport command
183
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.PauseCalled, null, { position: position });
184
+ yield this._pauseEvent.sendEvent({
185
+ track: this._groupState.playbackTrack.current,
186
+ position: position,
187
+ });
188
+ });
189
+ }
190
+ /**
191
+ * Instructs the group to seek to a new position within the current track.
192
+ *
193
+ * @remarks
194
+ * Throws an exception if the session/coordinator hasn't been initialized, no track has been
195
+ * loaded, or `canSeek` is false.
196
+ * @param time Playback position in seconds to seek to.
197
+ * @returns a void promise that resolves once complete, throws if user does not have proper roles
198
+ */
199
+ seekTo(time) {
200
+ var _a;
201
+ return __awaiter(this, void 0, void 0, function* () {
202
+ if (!this._hasInitialized) {
203
+ throw new Error(`LiveMediaSessionCoordinator.seekTo() called before initialize() called.`);
204
+ }
205
+ if (!((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.current.metadata)) {
206
+ throw new Error(`LiveMediaSessionCoordinator.seekTo() called before MediaSession.metadata assigned.`);
207
+ }
208
+ if (!this.canSeek) {
209
+ throw new Error(`LiveMediaSessionCoordinator.seekTo() operation blocked.`);
210
+ }
211
+ // Send transport command
212
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.SeekToCalled, null, { position: time });
213
+ try {
214
+ yield this._seekToEvent.sendEvent({
215
+ track: this._groupState.playbackTrack.current,
216
+ position: time,
217
+ });
218
+ }
219
+ catch (err) {
220
+ yield this._groupState.syncLocalMediaSession();
221
+ throw err;
222
+ }
223
+ });
224
+ }
225
+ /**
226
+ * Instructs the group to load a new track.
227
+ *
228
+ * @remarks
229
+ * Throws an exception if the session/coordinator hasn't been initialized or `canSetTrack` is
230
+ * false.
231
+ * @param metadata The track to load or `null` to indicate that the end of the track is reached.
232
+ * @param waitPoints Optional. List of static wait points to configure for the track. Dynamic wait points can be added via the `beginSuspension()` call.
233
+ * @returns a void promise that resolves once complete, throws if user does not have proper roles
234
+ */
235
+ setTrack(metadata, waitPoints) {
236
+ return __awaiter(this, void 0, void 0, function* () {
237
+ if (!this._hasInitialized) {
238
+ throw new Error(`LiveMediaSessionCoordinator.setTrack() called before initialize() called.`);
239
+ }
240
+ if (!this.canSetTrack) {
241
+ throw new Error(`LiveMediaSessionCoordinator.setTrack() operation blocked.`);
242
+ }
243
+ // Send transport command
244
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.SetTrackCalled);
245
+ yield this._setTrackEvent.sendEvent({
246
+ metadata: metadata,
247
+ waitPoints: waitPoints || [],
248
+ });
249
+ });
250
+ }
251
+ /**
252
+ * Updates the track data object for the current track.
253
+ *
254
+ * @remarks
255
+ * The track data object can be used by applications to synchronize things like pitch, roll,
256
+ * and yaw of a 360 video. This data object will be reset to null anytime the track changes.
257
+ *
258
+ * Throws an exception if the session/coordinator hasn't been initialized or `canSetTrackData` is
259
+ * false.
260
+ * @param data New data object to sync with the group. This value will be synchronized using a last writer wins strategy.
261
+ * @returns a void promise that resolves once complete, throws if user does not have proper roles
262
+ */
263
+ setTrackData(data) {
264
+ return __awaiter(this, void 0, void 0, function* () {
265
+ if (!this._hasInitialized) {
266
+ throw new Error(`LiveMediaSessionCoordinator.setTrackData() called before initialize() called.`);
267
+ }
268
+ if (!this.canSetTrackData) {
269
+ throw new Error(`LiveMediaSessionCoordinator.setTrackData() operation blocked.`);
270
+ }
271
+ // Send transport command
272
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.SetTrackDataCalled);
273
+ yield this._setTrackDataEvent.sendEvent({
274
+ data: data,
275
+ });
276
+ });
277
+ }
278
+ /**
279
+ * Begins a new local suspension.
280
+ *
281
+ * @remarks
282
+ * Suspension temporarily suspend the clients local synchronization with the group. This can
283
+ * be useful for displaying ads to users or temporarily disconnecting from the session while
284
+ * the user seeks the video using a timeline scrubber.
285
+ *
286
+ * Multiple simultaneous suspensions are allowed and when the last suspension ends the local
287
+ * client will be immediately re-synchronized with the group.
288
+ *
289
+ * A "Dynamic Wait Point" can be specified when `beginSuspension()` is called and the wait
290
+ * point will be broadcast to all other clients in the group. Those clients will then
291
+ * automatically enter a suspension state once they reach the positions specified by the
292
+ * wait point. Clients that are passed the wait point will immediately suspend.
293
+ *
294
+ * Any wait point based suspension (dynamic or static) will result in all clients remaining
295
+ * in a suspension state until the list client ends their suspension. This behavior can be
296
+ * conditionally bypassed by settings the wait points `maxClients` value.
297
+ *
298
+ * Throws an exception if the session/coordinator hasn't been initialized.
299
+ * @param waitPoint Optional. Dynamic wait point to broadcast to all of the clients.
300
+ * @returns The suspension object. Call `end()` on the returned suspension to end the suspension.
301
+ */
302
+ beginSuspension(waitPoint) {
303
+ var _a;
304
+ if (!this._hasInitialized) {
305
+ throw new Error(`LiveMediaSessionCoordinator.beginSuspension() called before initialize() called.`);
306
+ }
307
+ if (!((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.current.metadata)) {
308
+ throw new Error(`LiveMediaSessionCoordinator.beginSuspension() called before MediaSession.metadata assigned.`);
309
+ }
310
+ // Tell group state that suspension is started
311
+ if (waitPoint) {
312
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.BeginSuspensionAndWait, null, {
313
+ position: waitPoint.position,
314
+ maxClients: waitPoint.maxClients,
315
+ });
316
+ this._lastWaitPoint = waitPoint;
317
+ this._groupState.beginSuspension(waitPoint);
318
+ }
319
+ else {
320
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.BeginSuspension);
321
+ this._groupState.beginSuspension();
322
+ }
323
+ // Return new suspension object
324
+ return new LiveMediaSessionCoordinatorSuspension_1.LiveMediaSessionCoordinatorSuspension(waitPoint, (time) => {
325
+ var _a, _b;
326
+ if (waitPoint) {
327
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.EndSuspensionAndWait, null, {
328
+ position: waitPoint.position,
329
+ maxClients: waitPoint.maxClients,
330
+ });
331
+ }
332
+ else {
333
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.EndSuspension);
334
+ }
335
+ this._groupState.endSuspension(time == undefined);
336
+ if (time != undefined &&
337
+ !((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.isSuspended) &&
338
+ !((_b = this._groupState) === null || _b === void 0 ? void 0 : _b.isWaiting)) {
339
+ // Seek to new position
340
+ this.seekTo(Math.max(time, 0.0));
341
+ }
342
+ });
343
+ }
344
+ /**
345
+ * @hidden
346
+ * Called by MediaSession to verify the coordinator has been initialized.
347
+ */
348
+ get isInitialized() {
349
+ return this._hasInitialized;
350
+ }
351
+ /**
352
+ * @hidden
353
+ * Called by MediaSession to start coordinator.
354
+ */
355
+ initialize(acceptTransportChangesFrom) {
356
+ return __awaiter(this, void 0, void 0, function* () {
357
+ if (this._hasInitialized) {
358
+ throw new Error(`LiveMediaSessionCoordinator.initialize() already initialized.`);
359
+ }
360
+ // Create children
361
+ yield this.createChildren(acceptTransportChangesFrom);
362
+ this._hasInitialized = true;
363
+ });
364
+ }
365
+ /**
366
+ * @hidden
367
+ * Called by the MediaSession to detect if a wait point has been hit.
368
+ */
369
+ findNextWaitPoint() {
370
+ var _a;
371
+ return (((_a = this._groupState) === null || _a === void 0 ? void 0 : _a.playbackTrack.findNextWaitPoint(this._lastWaitPoint)) || null);
372
+ }
373
+ /**
374
+ * @hidden
375
+ * Called by MediaSession to trigger the sending of a position update.
376
+ */
377
+ sendPositionUpdate(state) {
378
+ if (!this._hasInitialized) {
379
+ throw new Error(`LiveMediaSessionCoordinator.sendPositionUpdate() called before initialize() called.`);
380
+ }
381
+ // Send position update event
382
+ this.verifyLocalUserRoles()
383
+ .then((valid) => {
384
+ var _a, _b;
385
+ const evt = this._groupState.createPositionUpdateEvent(state);
386
+ if (!valid) {
387
+ // We still need to update _groupState with the local user's position.
388
+ // So we do this here rather than on the receiving end.
389
+ this._groupState.handlePositionUpdate({
390
+ clientId: (_a = this._runtime.clientId) !== null && _a !== void 0 ? _a : "",
391
+ timestamp: this._liveRuntime.getTimestamp(),
392
+ data: evt,
393
+ }, true);
394
+ return;
395
+ }
396
+ return (_b = this._positionUpdateEvent) === null || _b === void 0 ? void 0 : _b.sendEvent(evt);
397
+ })
398
+ .catch((err) => {
399
+ this._logger.sendErrorEvent(internals_1.TelemetryEvents.SessionCoordinator.PositionUpdateEventError, err);
400
+ });
401
+ }
402
+ createChildren(acceptTransportChangesFrom) {
403
+ return __awaiter(this, void 0, void 0, function* () {
404
+ this._allowedRoles = acceptTransportChangesFrom;
405
+ // Create event scopes
406
+ const scope = new live_share_1.LiveEventScope(this._runtime, this._liveRuntime, acceptTransportChangesFrom);
407
+ const unrestrictedScope = new live_share_1.LiveEventScope(this._runtime, this._liveRuntime);
408
+ // Initialize internal coordinator state
409
+ this._groupState = new internals_1.GroupCoordinatorState(this._runtime, this._liveRuntime, this._maxPlaybackDrift, this._positionUpdateInterval, this._getPlayerState);
410
+ this._groupState.on(internals_1.GroupCoordinatorStateEvents.triggeraction, (evt) => this.emit(evt.name, evt));
411
+ // Listen for track changes
412
+ this._setTrackEvent = new live_share_1.LiveEventTarget(scope, "setTrack", (event, local) => this._groupState.handleSetTrack(event, local));
413
+ this._setTrackDataEvent = new live_share_1.LiveEventTarget(scope, "setTrackData", (event, local) => this._groupState.handleSetTrackData(event, local));
414
+ // Listen for transport commands
415
+ this._playEvent = new live_share_1.LiveEventTarget(scope, "play", (event, local) => this._groupState.handleTransportCommand(event, local));
416
+ this._pauseEvent = new live_share_1.LiveEventTarget(scope, "pause", (event, local) => this._groupState.handleTransportCommand(event, local));
417
+ this._seekToEvent = new live_share_1.LiveEventTarget(scope, "seekTo", (event, local) => this._groupState.handleTransportCommand(event, local));
418
+ // Listen for position updates
419
+ this._positionUpdateEvent = new live_share_1.LiveEventTarget(unrestrictedScope, "positionUpdate", (event, local) => this._groupState.handlePositionUpdate(event, local));
420
+ // Listen for joined event
421
+ this._joinedEvent = new live_share_1.LiveEventTarget(unrestrictedScope, "joined", (evt, local) => {
422
+ // Immediately send a position update
423
+ this._logger.sendTelemetryEvent(internals_1.TelemetryEvents.SessionCoordinator.RemoteJoinReceived, null, {
424
+ correlationId: live_share_1.LiveTelemetryLogger.formatCorrelationId(evt.clientId, evt.timestamp),
425
+ });
426
+ const state = this._getPlayerState();
427
+ this.sendPositionUpdate(state);
428
+ });
429
+ this.verifyLocalUserRoles()
430
+ .then((verified) => {
431
+ var _a;
432
+ if (!verified)
433
+ return;
434
+ // Send initial joined event
435
+ return (_a = this._joinedEvent) === null || _a === void 0 ? void 0 : _a.sendEvent(undefined);
436
+ })
437
+ .catch((err) => {
438
+ this._logger.sendErrorEvent(internals_1.TelemetryEvents.SessionCoordinator.SendJoinedEventError, err);
439
+ });
440
+ });
441
+ }
442
+ getPlayerPosition() {
443
+ const { positionState, playbackState } = this._getPlayerState();
444
+ switch (playbackState) {
445
+ case "none":
446
+ case "ended":
447
+ return 0.0;
448
+ default:
449
+ return positionState && positionState.position != undefined
450
+ ? positionState.position
451
+ : 0.0;
452
+ }
453
+ }
454
+ verifyLocalUserRoles() {
455
+ var _a;
456
+ return __awaiter(this, void 0, void 0, function* () {
457
+ const clientId = yield this.waitUntilConnected();
458
+ return this._liveRuntime.verifyRolesAllowed(clientId, (_a = this._allowedRoles) !== null && _a !== void 0 ? _a : []);
459
+ });
460
+ }
461
+ waitUntilConnected() {
462
+ return new Promise((resolve) => {
463
+ const onConnected = (clientId) => {
464
+ this._runtime.off("connected", onConnected);
465
+ resolve(clientId);
466
+ };
467
+ if (this._runtime.clientId && this._runtime.connected) {
468
+ resolve(this._runtime.clientId);
469
+ }
470
+ else {
471
+ this._runtime.on("connected", onConnected);
472
+ }
473
+ });
474
+ }
475
+ }
476
+ exports.LiveMediaSessionCoordinator = LiveMediaSessionCoordinator;
408
477
  //# sourceMappingURL=LiveMediaSessionCoordinator.js.map