@microsoft/live-share-media 0.5.0 → 0.5.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.
@@ -1,446 +1,446 @@
1
- /**
2
- * Copyright (c) Microsoft Corporation. All rights reserved.
3
- * Licensed under the Microsoft Live Share SDK License.
4
- */
5
-
6
- import { IEvent, IEphemeralEvent, EphemeralEvent, TimeInterval, IRuntimeSignaler, EphemeralTelemetryLogger } from '@microsoft/live-share';
7
- import EventEmitter from 'events';
8
- import { ExtendedMediaMetadata, CoordinationWaitPoint, ExtendedMediaSessionPlaybackState, ExtendedMediaSessionActionDetails } from '../MediaSessionExtensions';
9
- import { GroupPlaybackTrack, GroupPlaybackTrackEvents, IPlaybackTrack } from './GroupPlaybackTrack';
10
- import { GroupTransportState, ITransportState } from './GroupTransportState';
11
- import { GroupPlaybackPosition, ICurrentPlaybackPosition } from './GroupPlaybackPosition';
12
- import { IMediaPlayerState } from '../EphemeralMediaSessionCoordinator';
13
- import { GroupTransportStateEvents } from './GroupTransportState';
14
- import { GroupPlaybackTrackData, PlaybackTrackDataEvents, IPlaybackTrackData } from './GroupPlaybackTrackData';
15
- import { TelemetryEvents } from './consts';
16
-
17
- /**
18
- * @hidden
19
- */
20
- export interface IPositionUpdateEvent extends IEphemeralEvent {
21
- track: IPlaybackTrack;
22
- trackData: IPlaybackTrackData;
23
- transport: ITransportState;
24
- playbackState: ExtendedMediaSessionPlaybackState;
25
- position: number;
26
- waitPoint?: CoordinationWaitPoint;
27
- }
28
-
29
- /**
30
- * @hidden
31
- */
32
- export interface ITransportCommandEvent extends IEphemeralEvent {
33
- track: IPlaybackTrack;
34
- position: number;
35
- }
36
-
37
- /**
38
- * @hidden
39
- */
40
- export interface ISetTrackEvent extends IEphemeralEvent {
41
- metadata: ExtendedMediaMetadata|null;
42
- waitPoints: CoordinationWaitPoint[];
43
- }
44
-
45
- /**
46
- * @hidden
47
- */
48
- export interface ISetTrackDataEvent extends IEphemeralEvent {
49
- data: object|null;
50
- }
51
-
52
- /**
53
- * @hidden
54
- */
55
- export interface ITriggerActionEvent extends IEvent {
56
- details: ExtendedMediaSessionActionDetails;
57
- }
58
-
59
- /**
60
- * @hidden
61
- */
62
- export enum GroupCoordinatorStateEvents {
63
- newwaitpoint = 'newwaitpoint',
64
- triggeraction = 'triggeraction'
65
- }
66
-
67
- /**
68
- * @hidden
69
- */
70
- export class GroupCoordinatorState extends EventEmitter {
71
- private readonly _runtime: IRuntimeSignaler;
72
- private readonly _logger: EphemeralTelemetryLogger;
73
- private readonly _maxPlaybackDrift: TimeInterval;
74
- private _getMediaPlayerState: () => IMediaPlayerState;
75
-
76
- // Shared group state
77
- private _playbackTrack: GroupPlaybackTrack;
78
- private _playbackTrackData: GroupPlaybackTrackData;
79
- private _transportState: GroupTransportState;
80
- private _playbackPosition: GroupPlaybackPosition;
81
-
82
- // Suspension tracking
83
- private _suspensionCnt: number = 0;
84
- private _waitPoint?: CoordinationWaitPoint;
85
-
86
- // "Soft Suspension" tracking
87
- // - Soft suspensions temporarily disconnect the local media session when transitioning between
88
- // paused, playing, and none states. This is to give the local client time to finish any inprogress
89
- // operations like sending a transport command or ending a suspension.
90
- private _lastStateChange: ExtendedMediaSessionPlaybackState = 'none';
91
- private _lastStateChangeTime: number = 0;
92
-
93
- constructor (runtime: IRuntimeSignaler, maxPlaybackDrift: TimeInterval, positionUpdateInterval: TimeInterval, getMediaPlayerState: () => IMediaPlayerState) {
94
- super();
95
- this._runtime = runtime;
96
- this._logger = new EphemeralTelemetryLogger(runtime);
97
- this._maxPlaybackDrift = maxPlaybackDrift;
98
- this._playbackTrack = new GroupPlaybackTrack(getMediaPlayerState);
99
- this._playbackTrackData = new GroupPlaybackTrackData(this._playbackTrack);
100
- this._transportState = new GroupTransportState(this._playbackTrack, getMediaPlayerState);
101
- this._playbackPosition = new GroupPlaybackPosition(this._transportState, this._runtime, positionUpdateInterval);
102
- this._getMediaPlayerState = getMediaPlayerState;
103
-
104
- // Listen track related events
105
- this._playbackTrack.on(GroupPlaybackTrackEvents.trackChange, evt => {
106
- if (!this.isSuspended) {
107
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackChanged);
108
- this.emitSetTrack(evt.metadata!);
109
- } else {
110
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackChangeDelayed);
111
- }
112
- });
113
-
114
- // Listen for track data changes
115
- this._playbackTrackData.on(PlaybackTrackDataEvents.dataChange, evt => {
116
- if (!this.isSuspended && !this.isWaiting) {
117
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackDataChanged);
118
- this.emitTriggerAction({action: 'datachange', data: evt.data});
119
- } else {
120
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackDataChangeDelayed);
121
- }
122
- });
123
-
124
- // Listen to transport related events
125
- this._transportState.on(GroupTransportStateEvents.transportStateChange, evt => {
126
- if (!this.isSuspended && !this.isWaiting) {
127
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TransportStateChanged, null, {
128
- action: evt.action,
129
- seekTime: evt.seekTime
130
- });
131
-
132
- // Trigger action
133
- switch (evt.action) {
134
- case 'play':
135
- this.emitTriggerAction({action: 'play', seekTime: evt.seekTime});
136
- break;
137
-
138
- case 'pause':
139
- this.emitTriggerAction({action: 'pause', seekTime: evt.seekTime});
140
- break;
141
-
142
- case 'seekto':
143
- this.emitTriggerAction({action: 'seekto', seekTime: evt.seekTime});
144
- break;
145
- }
146
- } else {
147
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TransportStateChangeDelayed, null, {
148
- action: evt.action,
149
- seekTime: evt.seekTime
150
- });
151
- }
152
- });
153
- }
154
-
155
- public get playbackTrack(): GroupPlaybackTrack {
156
- return this._playbackTrack;
157
- }
158
-
159
- public get playbackTrackData(): GroupPlaybackTrackData {
160
- return this._playbackTrackData;
161
- }
162
-
163
- public get transportState(): GroupTransportState {
164
- return this._transportState;
165
- }
166
-
167
- public get playbackPosition(): GroupPlaybackPosition {
168
- return this._playbackPosition;
169
- }
170
-
171
- public get waitingAt(): CoordinationWaitPoint|undefined {
172
- return this._waitPoint;
173
- }
174
-
175
- public get isSuspended(): boolean {
176
- return this._suspensionCnt > 0;
177
- }
178
-
179
- public get isWaiting(): boolean {
180
- return !!this._waitPoint;
181
- }
182
-
183
- public beginSuspension(waitPoint?: CoordinationWaitPoint): void {
184
- this._suspensionCnt++;
185
-
186
- if (waitPoint) {
187
- // Save most recent wait point
188
- this._waitPoint = waitPoint;
189
-
190
- // Add to track state if dynamic wait point
191
- this.playbackTrack.addWaitPoint(waitPoint);
192
- }
193
- }
194
-
195
- public endSuspension(syncState: boolean): void {
196
- if (this._suspensionCnt == 0) {
197
- throw new Error(`Too many suspensions.`);
198
- }
199
-
200
- this._suspensionCnt--;
201
- if (this._suspensionCnt == 0 && syncState) {
202
- // Sync media session to group
203
- this.syncLocalMediaSession();
204
- }
205
- }
206
-
207
- public createPositionUpdateEvent(state: IMediaPlayerState): Partial<IPositionUpdateEvent> {
208
- const { positionState, playbackState } = state;
209
- if (this.isSuspended) {
210
- // Report suspension state
211
- return {
212
- track: this.playbackTrack.current,
213
- trackData: this.playbackTrackData.current,
214
- transport: this.transportState.current,
215
- playbackState: 'suspended',
216
- position: positionState?.position || 0.0,
217
- waitPoint: this._waitPoint
218
- };
219
- } else {
220
- // Report current position
221
- return {
222
- track: this.playbackTrack.current,
223
- trackData: this.playbackTrackData.current,
224
- transport: this.transportState.current,
225
- playbackState: this._waitPoint ? 'waiting' : playbackState,
226
- position: positionState?.position || 0.0,
227
- waitPoint: this._waitPoint
228
- };
229
- }
230
- }
231
-
232
- public handleSetTrack(event: ISetTrackEvent, local: boolean): void {
233
- // Update shared track
234
- // - Will trigger 'trackChange' event to update media session
235
- const updated = this.playbackTrack.updateTrack({
236
- metadata: event.metadata,
237
- waitPoints: event.waitPoints,
238
- timestamp: event.timestamp,
239
- clientId: event.clientId || ''
240
- });
241
-
242
- if (updated) {
243
- this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemoteSetTrackReceived, null, {correlationId: EphemeralTelemetryLogger.formatCorrelationId(event.clientId, event.timestamp)});
244
- }
245
- }
246
-
247
- public handleSetTrackData(event: ISetTrackDataEvent, local: boolean): void {
248
- // Update shared track data
249
- // - Will trigger 'dataChange' event to update media session
250
- const updated = this.playbackTrackData.updateData({
251
- data: event.data,
252
- timestamp: event.timestamp,
253
- clientId: event.clientId || ''
254
- });
255
-
256
- if (updated) {
257
- this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemoteSetTrackReceived, null, {correlationId: EphemeralTelemetryLogger.formatCorrelationId(event.clientId, event.timestamp)});
258
- }
259
- }
260
-
261
- public handleTransportCommand(event: ITransportCommandEvent, local: boolean): void {
262
- // Ensure change is for current track
263
- // - Will trigger a 'trackChange' event if newer track.
264
- this.playbackTrack.updateTrack(event.track);
265
- if (this.playbackTrack.compare(event.track.metadata)) {
266
- // Update playback state
267
- let playbackState = this.transportState.playbackState;
268
- switch (event.name) {
269
- case 'play':
270
- playbackState = 'playing';
271
- break;
272
- case 'pause':
273
- playbackState = 'paused';
274
- break;
275
- }
276
-
277
- // Try to update playback state
278
- const newState: ITransportState = {
279
- playbackState: playbackState,
280
- startPosition: event.position,
281
- timestamp: event.timestamp,
282
- clientId: event.clientId || ''
283
- };
284
- const updated = this.transportState.updateState(newState);
285
-
286
- if (updated) {
287
- const correlationId = EphemeralTelemetryLogger.formatCorrelationId(event.clientId, event.timestamp);
288
- switch (event.name) {
289
- case 'play':
290
- this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemotePlayReceived, null, {correlationId: correlationId});
291
- break;
292
- case 'pause':
293
- this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemotePauseReceived, null, {correlationId: correlationId});
294
- break;
295
- case 'seekTo':
296
- this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemoteSeekToReceived, null, {correlationId: correlationId});
297
- break;
298
- }
299
-
300
- }
301
- }
302
- }
303
-
304
- public handlePositionUpdate(event: IPositionUpdateEvent, local: boolean): void {
305
- // Ensure change is for current track
306
- // - Will trigger a 'trackChange' event if newer track.
307
- this.playbackTrack.updateTrack(event.track);
308
- if (this.playbackTrack.compare(event.track.metadata)) {
309
- // Ensure we have the latest track data
310
- this.playbackTrackData.updateData(event.trackData);
311
-
312
- // Update transport state if needed
313
- // - Ignore transport state changes if the client has ended as this will cause the local
314
- // player to start playback even though the video may have ended for everyone.
315
- if (event.playbackState != 'ended') {
316
- this.transportState.updateState(event.transport);
317
- }
318
-
319
- // Ensure change is for current transport state
320
- if (this.transportState.compare(event.transport)) {
321
- // Update playback position
322
- const position: ICurrentPlaybackPosition = {
323
- playbackState: event.playbackState,
324
- waitPoint: event.waitPoint,
325
- position: event.position,
326
- timestamp: event.timestamp,
327
- clientId: event.clientId || ''
328
- };
329
- this.playbackPosition.UpdatePlaybackPosition(position);
330
-
331
- // Ensure local media session is in sync with group
332
- if (local && !this.isSuspended) {
333
- // Begin a "soft suspension" on select state changes
334
- // - This is needed because the catchup logic can try to sink the client with
335
- // the rest of the group while the local player is trying to to seek to a
336
- // new position.
337
- switch (event.playbackState) {
338
- case 'none':
339
- case 'paused':
340
- case 'playing':
341
- if (event.playbackState != this._lastStateChange) {
342
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.BeginSoftSuspension, null, {playbackState: event.playbackState});
343
- this._lastStateChange = event.playbackState;
344
- this._lastStateChangeTime = EphemeralEvent.getTimestamp();
345
- }
346
- break;
347
- }
348
-
349
- // Are we waiting?
350
- if (this.isWaiting) {
351
- // Check for end of waiting
352
- if (this.playbackPosition.clientsWaiting == 0) {
353
- this._waitPoint = undefined;
354
-
355
- // Start syncing again
356
- this.syncLocalMediaSession();
357
- }
358
- } else {
359
- // Sync client with group
360
- this.syncLocalMediaSession();
361
- }
362
- }
363
- }
364
- }
365
- }
366
-
367
- public async syncLocalMediaSession(): Promise<void> {
368
- // Skip further syncs if we're waiting or in a "soft suspension".
369
- const softSuspensionDelta = EphemeralEvent.getTimestamp() - this._lastStateChangeTime;
370
- if (!this.isWaiting && softSuspensionDelta >= 1000) {
371
- let { metadata, trackData, positionState, playbackState } = this._getMediaPlayerState();
372
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.CheckingForSyncIssues);
373
-
374
- // Check for track change
375
- if (!this.playbackTrack.compare(metadata)) {
376
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackOutOfSync);
377
- this.emitSetTrack(this.playbackTrack.metadata!);
378
- return;
379
- }
380
-
381
- // Once local playback has ended there's no need to further sync the client. In fact
382
- // doing so could cause the player to loop.
383
- // - The playbackPosition.trackEnded check is to catch late joiners and prevents syncing if everyone
384
- // else has finished the video.
385
- // - Should another user seek or press play after the video has ended that will cause
386
- // a transport action to trigger which will take the player out of the ended state.
387
- if (playbackState != "ended" && !this._playbackPosition.trackEnded) {
388
- // Ensure we have a position
389
- let position = positionState?.position;
390
- if (position == undefined) {
391
- position = 0.0;
392
- }
393
-
394
- // Check for catchup
395
- // - Target can return -1 in cases where there is no position tracking data
396
- const target = this.playbackPosition.targetPosition;
397
- if (target >= 0.0 && Math.abs(target - position) >= this._maxPlaybackDrift.seconds) {
398
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.PositionOutOfSync, null, {
399
- current: position,
400
- target: target
401
- });
402
- await this.emitTriggerAction({action: 'catchup', seekTime: target});
403
- }
404
-
405
- // Sync transport state
406
- if (this.transportState.playbackState != playbackState) {
407
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TransportOutOfSync, null, {
408
- current: playbackState,
409
- target: this.transportState.playbackState
410
- });
411
- switch (this.transportState.playbackState) {
412
- case 'playing':
413
- await this.emitTriggerAction({action: 'play'});
414
- break;
415
- case 'paused':
416
- await this.emitTriggerAction({action: 'pause'});
417
- break;
418
- }
419
- }
420
-
421
- // Sync track data
422
- if (JSON.stringify(this.playbackTrackData.data) != JSON.stringify(trackData)) {
423
- this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackDataOutOfSync);
424
- await this.emitTriggerAction({action: 'datachange', data: this.playbackTrackData.data});
425
- }
426
- }
427
-
428
- }
429
- }
430
-
431
- private emitSetTrack(metadata: ExtendedMediaMetadata): void {
432
- // Reset tracking states
433
- this._waitPoint = undefined;
434
-
435
- // Trigger settrack action
436
- this.emitTriggerAction({action: 'settrack', metadata: metadata});
437
- }
438
-
439
- private emitTriggerAction(details: ExtendedMediaSessionActionDetails): void {
440
- const evt: ITriggerActionEvent = {
441
- name: GroupCoordinatorStateEvents.triggeraction,
442
- details: details
443
- };
444
- this.emit(GroupCoordinatorStateEvents.triggeraction, evt);
445
- }
1
+ /**
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the Microsoft Live Share SDK License.
4
+ */
5
+
6
+ import { IEvent, IEphemeralEvent, EphemeralEvent, TimeInterval, IRuntimeSignaler, EphemeralTelemetryLogger } from '@microsoft/live-share';
7
+ import EventEmitter from 'events';
8
+ import { ExtendedMediaMetadata, CoordinationWaitPoint, ExtendedMediaSessionPlaybackState, ExtendedMediaSessionActionDetails } from '../MediaSessionExtensions';
9
+ import { GroupPlaybackTrack, GroupPlaybackTrackEvents, IPlaybackTrack } from './GroupPlaybackTrack';
10
+ import { GroupTransportState, ITransportState } from './GroupTransportState';
11
+ import { GroupPlaybackPosition, ICurrentPlaybackPosition } from './GroupPlaybackPosition';
12
+ import { IMediaPlayerState } from '../EphemeralMediaSessionCoordinator';
13
+ import { GroupTransportStateEvents } from './GroupTransportState';
14
+ import { GroupPlaybackTrackData, PlaybackTrackDataEvents, IPlaybackTrackData } from './GroupPlaybackTrackData';
15
+ import { TelemetryEvents } from './consts';
16
+
17
+ /**
18
+ * @hidden
19
+ */
20
+ export interface IPositionUpdateEvent extends IEphemeralEvent {
21
+ track: IPlaybackTrack;
22
+ trackData: IPlaybackTrackData;
23
+ transport: ITransportState;
24
+ playbackState: ExtendedMediaSessionPlaybackState;
25
+ position: number;
26
+ waitPoint?: CoordinationWaitPoint;
27
+ }
28
+
29
+ /**
30
+ * @hidden
31
+ */
32
+ export interface ITransportCommandEvent extends IEphemeralEvent {
33
+ track: IPlaybackTrack;
34
+ position: number;
35
+ }
36
+
37
+ /**
38
+ * @hidden
39
+ */
40
+ export interface ISetTrackEvent extends IEphemeralEvent {
41
+ metadata: ExtendedMediaMetadata|null;
42
+ waitPoints: CoordinationWaitPoint[];
43
+ }
44
+
45
+ /**
46
+ * @hidden
47
+ */
48
+ export interface ISetTrackDataEvent extends IEphemeralEvent {
49
+ data: object|null;
50
+ }
51
+
52
+ /**
53
+ * @hidden
54
+ */
55
+ export interface ITriggerActionEvent extends IEvent {
56
+ details: ExtendedMediaSessionActionDetails;
57
+ }
58
+
59
+ /**
60
+ * @hidden
61
+ */
62
+ export enum GroupCoordinatorStateEvents {
63
+ newwaitpoint = 'newwaitpoint',
64
+ triggeraction = 'triggeraction'
65
+ }
66
+
67
+ /**
68
+ * @hidden
69
+ */
70
+ export class GroupCoordinatorState extends EventEmitter {
71
+ private readonly _runtime: IRuntimeSignaler;
72
+ private readonly _logger: EphemeralTelemetryLogger;
73
+ private readonly _maxPlaybackDrift: TimeInterval;
74
+ private _getMediaPlayerState: () => IMediaPlayerState;
75
+
76
+ // Shared group state
77
+ private _playbackTrack: GroupPlaybackTrack;
78
+ private _playbackTrackData: GroupPlaybackTrackData;
79
+ private _transportState: GroupTransportState;
80
+ private _playbackPosition: GroupPlaybackPosition;
81
+
82
+ // Suspension tracking
83
+ private _suspensionCnt: number = 0;
84
+ private _waitPoint?: CoordinationWaitPoint;
85
+
86
+ // "Soft Suspension" tracking
87
+ // - Soft suspensions temporarily disconnect the local media session when transitioning between
88
+ // paused, playing, and none states. This is to give the local client time to finish any inprogress
89
+ // operations like sending a transport command or ending a suspension.
90
+ private _lastStateChange: ExtendedMediaSessionPlaybackState = 'none';
91
+ private _lastStateChangeTime: number = 0;
92
+
93
+ constructor (runtime: IRuntimeSignaler, maxPlaybackDrift: TimeInterval, positionUpdateInterval: TimeInterval, getMediaPlayerState: () => IMediaPlayerState) {
94
+ super();
95
+ this._runtime = runtime;
96
+ this._logger = new EphemeralTelemetryLogger(runtime);
97
+ this._maxPlaybackDrift = maxPlaybackDrift;
98
+ this._playbackTrack = new GroupPlaybackTrack(getMediaPlayerState);
99
+ this._playbackTrackData = new GroupPlaybackTrackData(this._playbackTrack);
100
+ this._transportState = new GroupTransportState(this._playbackTrack, getMediaPlayerState);
101
+ this._playbackPosition = new GroupPlaybackPosition(this._transportState, this._runtime, positionUpdateInterval);
102
+ this._getMediaPlayerState = getMediaPlayerState;
103
+
104
+ // Listen track related events
105
+ this._playbackTrack.on(GroupPlaybackTrackEvents.trackChange, evt => {
106
+ if (!this.isSuspended) {
107
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackChanged);
108
+ this.emitSetTrack(evt.metadata!);
109
+ } else {
110
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackChangeDelayed);
111
+ }
112
+ });
113
+
114
+ // Listen for track data changes
115
+ this._playbackTrackData.on(PlaybackTrackDataEvents.dataChange, evt => {
116
+ if (!this.isSuspended && !this.isWaiting) {
117
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackDataChanged);
118
+ this.emitTriggerAction({action: 'datachange', data: evt.data});
119
+ } else {
120
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackDataChangeDelayed);
121
+ }
122
+ });
123
+
124
+ // Listen to transport related events
125
+ this._transportState.on(GroupTransportStateEvents.transportStateChange, evt => {
126
+ if (!this.isSuspended && !this.isWaiting) {
127
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TransportStateChanged, null, {
128
+ action: evt.action,
129
+ seekTime: evt.seekTime
130
+ });
131
+
132
+ // Trigger action
133
+ switch (evt.action) {
134
+ case 'play':
135
+ this.emitTriggerAction({action: 'play', seekTime: evt.seekTime});
136
+ break;
137
+
138
+ case 'pause':
139
+ this.emitTriggerAction({action: 'pause', seekTime: evt.seekTime});
140
+ break;
141
+
142
+ case 'seekto':
143
+ this.emitTriggerAction({action: 'seekto', seekTime: evt.seekTime});
144
+ break;
145
+ }
146
+ } else {
147
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TransportStateChangeDelayed, null, {
148
+ action: evt.action,
149
+ seekTime: evt.seekTime
150
+ });
151
+ }
152
+ });
153
+ }
154
+
155
+ public get playbackTrack(): GroupPlaybackTrack {
156
+ return this._playbackTrack;
157
+ }
158
+
159
+ public get playbackTrackData(): GroupPlaybackTrackData {
160
+ return this._playbackTrackData;
161
+ }
162
+
163
+ public get transportState(): GroupTransportState {
164
+ return this._transportState;
165
+ }
166
+
167
+ public get playbackPosition(): GroupPlaybackPosition {
168
+ return this._playbackPosition;
169
+ }
170
+
171
+ public get waitingAt(): CoordinationWaitPoint|undefined {
172
+ return this._waitPoint;
173
+ }
174
+
175
+ public get isSuspended(): boolean {
176
+ return this._suspensionCnt > 0;
177
+ }
178
+
179
+ public get isWaiting(): boolean {
180
+ return !!this._waitPoint;
181
+ }
182
+
183
+ public beginSuspension(waitPoint?: CoordinationWaitPoint): void {
184
+ this._suspensionCnt++;
185
+
186
+ if (waitPoint) {
187
+ // Save most recent wait point
188
+ this._waitPoint = waitPoint;
189
+
190
+ // Add to track state if dynamic wait point
191
+ this.playbackTrack.addWaitPoint(waitPoint);
192
+ }
193
+ }
194
+
195
+ public endSuspension(syncState: boolean): void {
196
+ if (this._suspensionCnt == 0) {
197
+ throw new Error(`Too many suspensions.`);
198
+ }
199
+
200
+ this._suspensionCnt--;
201
+ if (this._suspensionCnt == 0 && syncState) {
202
+ // Sync media session to group
203
+ this.syncLocalMediaSession();
204
+ }
205
+ }
206
+
207
+ public createPositionUpdateEvent(state: IMediaPlayerState): Partial<IPositionUpdateEvent> {
208
+ const { positionState, playbackState } = state;
209
+ if (this.isSuspended) {
210
+ // Report suspension state
211
+ return {
212
+ track: this.playbackTrack.current,
213
+ trackData: this.playbackTrackData.current,
214
+ transport: this.transportState.current,
215
+ playbackState: 'suspended',
216
+ position: positionState?.position || 0.0,
217
+ waitPoint: this._waitPoint
218
+ };
219
+ } else {
220
+ // Report current position
221
+ return {
222
+ track: this.playbackTrack.current,
223
+ trackData: this.playbackTrackData.current,
224
+ transport: this.transportState.current,
225
+ playbackState: this._waitPoint ? 'waiting' : playbackState,
226
+ position: positionState?.position || 0.0,
227
+ waitPoint: this._waitPoint
228
+ };
229
+ }
230
+ }
231
+
232
+ public handleSetTrack(event: ISetTrackEvent, local: boolean): void {
233
+ // Update shared track
234
+ // - Will trigger 'trackChange' event to update media session
235
+ const updated = this.playbackTrack.updateTrack({
236
+ metadata: event.metadata,
237
+ waitPoints: event.waitPoints,
238
+ timestamp: event.timestamp,
239
+ clientId: event.clientId || ''
240
+ });
241
+
242
+ if (updated) {
243
+ this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemoteSetTrackReceived, null, {correlationId: EphemeralTelemetryLogger.formatCorrelationId(event.clientId, event.timestamp)});
244
+ }
245
+ }
246
+
247
+ public handleSetTrackData(event: ISetTrackDataEvent, local: boolean): void {
248
+ // Update shared track data
249
+ // - Will trigger 'dataChange' event to update media session
250
+ const updated = this.playbackTrackData.updateData({
251
+ data: event.data,
252
+ timestamp: event.timestamp,
253
+ clientId: event.clientId || ''
254
+ });
255
+
256
+ if (updated) {
257
+ this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemoteSetTrackReceived, null, {correlationId: EphemeralTelemetryLogger.formatCorrelationId(event.clientId, event.timestamp)});
258
+ }
259
+ }
260
+
261
+ public handleTransportCommand(event: ITransportCommandEvent, local: boolean): void {
262
+ // Ensure change is for current track
263
+ // - Will trigger a 'trackChange' event if newer track.
264
+ this.playbackTrack.updateTrack(event.track);
265
+ if (this.playbackTrack.compare(event.track.metadata)) {
266
+ // Update playback state
267
+ let playbackState = this.transportState.playbackState;
268
+ switch (event.name) {
269
+ case 'play':
270
+ playbackState = 'playing';
271
+ break;
272
+ case 'pause':
273
+ playbackState = 'paused';
274
+ break;
275
+ }
276
+
277
+ // Try to update playback state
278
+ const newState: ITransportState = {
279
+ playbackState: playbackState,
280
+ startPosition: event.position,
281
+ timestamp: event.timestamp,
282
+ clientId: event.clientId || ''
283
+ };
284
+ const updated = this.transportState.updateState(newState);
285
+
286
+ if (updated) {
287
+ const correlationId = EphemeralTelemetryLogger.formatCorrelationId(event.clientId, event.timestamp);
288
+ switch (event.name) {
289
+ case 'play':
290
+ this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemotePlayReceived, null, {correlationId: correlationId});
291
+ break;
292
+ case 'pause':
293
+ this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemotePauseReceived, null, {correlationId: correlationId});
294
+ break;
295
+ case 'seekTo':
296
+ this._logger.sendTelemetryEvent(TelemetryEvents.SessionCoordinator.RemoteSeekToReceived, null, {correlationId: correlationId});
297
+ break;
298
+ }
299
+
300
+ }
301
+ }
302
+ }
303
+
304
+ public handlePositionUpdate(event: IPositionUpdateEvent, local: boolean): void {
305
+ // Ensure change is for current track
306
+ // - Will trigger a 'trackChange' event if newer track.
307
+ this.playbackTrack.updateTrack(event.track);
308
+ if (this.playbackTrack.compare(event.track.metadata)) {
309
+ // Ensure we have the latest track data
310
+ this.playbackTrackData.updateData(event.trackData);
311
+
312
+ // Update transport state if needed
313
+ // - Ignore transport state changes if the client has ended as this will cause the local
314
+ // player to start playback even though the video may have ended for everyone.
315
+ if (event.playbackState != 'ended') {
316
+ this.transportState.updateState(event.transport);
317
+ }
318
+
319
+ // Ensure change is for current transport state
320
+ if (this.transportState.compare(event.transport)) {
321
+ // Update playback position
322
+ const position: ICurrentPlaybackPosition = {
323
+ playbackState: event.playbackState,
324
+ waitPoint: event.waitPoint,
325
+ position: event.position,
326
+ timestamp: event.timestamp,
327
+ clientId: event.clientId || ''
328
+ };
329
+ this.playbackPosition.UpdatePlaybackPosition(position);
330
+
331
+ // Ensure local media session is in sync with group
332
+ if (local && !this.isSuspended) {
333
+ // Begin a "soft suspension" on select state changes
334
+ // - This is needed because the catchup logic can try to sink the client with
335
+ // the rest of the group while the local player is trying to to seek to a
336
+ // new position.
337
+ switch (event.playbackState) {
338
+ case 'none':
339
+ case 'paused':
340
+ case 'playing':
341
+ if (event.playbackState != this._lastStateChange) {
342
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.BeginSoftSuspension, null, {playbackState: event.playbackState});
343
+ this._lastStateChange = event.playbackState;
344
+ this._lastStateChangeTime = EphemeralEvent.getTimestamp();
345
+ }
346
+ break;
347
+ }
348
+
349
+ // Are we waiting?
350
+ if (this.isWaiting) {
351
+ // Check for end of waiting
352
+ if (this.playbackPosition.clientsWaiting == 0) {
353
+ this._waitPoint = undefined;
354
+
355
+ // Start syncing again
356
+ this.syncLocalMediaSession();
357
+ }
358
+ } else {
359
+ // Sync client with group
360
+ this.syncLocalMediaSession();
361
+ }
362
+ }
363
+ }
364
+ }
365
+ }
366
+
367
+ public async syncLocalMediaSession(): Promise<void> {
368
+ // Skip further syncs if we're waiting or in a "soft suspension".
369
+ const softSuspensionDelta = EphemeralEvent.getTimestamp() - this._lastStateChangeTime;
370
+ if (!this.isWaiting && softSuspensionDelta >= 1000) {
371
+ let { metadata, trackData, positionState, playbackState } = this._getMediaPlayerState();
372
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.CheckingForSyncIssues);
373
+
374
+ // Check for track change
375
+ if (!this.playbackTrack.compare(metadata)) {
376
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackOutOfSync);
377
+ this.emitSetTrack(this.playbackTrack.metadata!);
378
+ return;
379
+ }
380
+
381
+ // Once local playback has ended there's no need to further sync the client. In fact
382
+ // doing so could cause the player to loop.
383
+ // - The playbackPosition.trackEnded check is to catch late joiners and prevents syncing if everyone
384
+ // else has finished the video.
385
+ // - Should another user seek or press play after the video has ended that will cause
386
+ // a transport action to trigger which will take the player out of the ended state.
387
+ if (playbackState != "ended" && !this._playbackPosition.trackEnded) {
388
+ // Ensure we have a position
389
+ let position = positionState?.position;
390
+ if (position == undefined) {
391
+ position = 0.0;
392
+ }
393
+
394
+ // Check for catchup
395
+ // - Target can return -1 in cases where there is no position tracking data
396
+ const target = this.playbackPosition.targetPosition;
397
+ if (target >= 0.0 && Math.abs(target - position) >= this._maxPlaybackDrift.seconds) {
398
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.PositionOutOfSync, null, {
399
+ current: position,
400
+ target: target
401
+ });
402
+ await this.emitTriggerAction({action: 'catchup', seekTime: target});
403
+ }
404
+
405
+ // Sync transport state
406
+ if (this.transportState.playbackState != playbackState) {
407
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TransportOutOfSync, null, {
408
+ current: playbackState,
409
+ target: this.transportState.playbackState
410
+ });
411
+ switch (this.transportState.playbackState) {
412
+ case 'playing':
413
+ await this.emitTriggerAction({action: 'play'});
414
+ break;
415
+ case 'paused':
416
+ await this.emitTriggerAction({action: 'pause'});
417
+ break;
418
+ }
419
+ }
420
+
421
+ // Sync track data
422
+ if (JSON.stringify(this.playbackTrackData.data) != JSON.stringify(trackData)) {
423
+ this._logger.sendTelemetryEvent(TelemetryEvents.GroupCoordinator.TrackDataOutOfSync);
424
+ await this.emitTriggerAction({action: 'datachange', data: this.playbackTrackData.data});
425
+ }
426
+ }
427
+
428
+ }
429
+ }
430
+
431
+ private emitSetTrack(metadata: ExtendedMediaMetadata): void {
432
+ // Reset tracking states
433
+ this._waitPoint = undefined;
434
+
435
+ // Trigger settrack action
436
+ this.emitTriggerAction({action: 'settrack', metadata: metadata});
437
+ }
438
+
439
+ private emitTriggerAction(details: ExtendedMediaSessionActionDetails): void {
440
+ const evt: ITriggerActionEvent = {
441
+ name: GroupCoordinatorStateEvents.triggeraction,
442
+ details: details
443
+ };
444
+ this.emit(GroupCoordinatorStateEvents.triggeraction, evt);
445
+ }
446
446
  }