@microsoft/live-share-media 0.5.0-beta → 0.5.0-beta.2

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,248 +1,248 @@
1
- /**
2
- * Copyright (c) Microsoft Corporation. All rights reserved.
3
- * Licensed under the Microsoft Live Share SDK License.
4
- */
5
-
6
- import { DataObject, DataObjectFactory } from '@fluidframework/aqueduct';
7
- import { EphemeralTelemetryLogger, UserMeetingRole } from '@microsoft/live-share';
8
- import { MediaPlayerSynchronizer } from './MediaPlayerSynchronizer';
9
- import { ITriggerActionEvent, TelemetryEvents } from './internals';
10
- import { MediaSessionCoordinatorEvents, ExtendedMediaSessionAction, ExtendedMediaSessionActionDetails } from './MediaSessionExtensions';
11
- import { EphemeralMediaSessionCoordinator, IMediaPlayerState } from './EphemeralMediaSessionCoordinator';
12
- import { MediaSessionActionThrottler } from './MediaSessionActionThrottler';
13
- import { RepeatedActionThrottler } from './RepeatedActionThrottler';
14
- import { IMediaPlayer } from './IMediaPlayer';
15
-
16
- /**
17
- * Ephemeral fluid object that synchronizes media playback across multiple clients.
18
- */
19
- export class EphemeralMediaSession extends DataObject {
20
- private _actionThrottler: MediaSessionActionThrottler = new RepeatedActionThrottler();
21
- private _logger?: EphemeralTelemetryLogger;
22
- private _requestPlayerStateHandler?: () => IMediaPlayerState;
23
- private _coordinator?: EphemeralMediaSessionCoordinator;
24
- private readonly _actionHandlers: Map<string, MediaSessionActionHandler> = new Map();
25
- private _synchronizing?: MediaPlayerSynchronizer;
26
-
27
- // Position update timer
28
- private _updateTimer: any;
29
- private _lastUpdateTime: number = 0;
30
-
31
- /**
32
- * The objects fluid type name.
33
- */
34
- public static readonly TypeName = `@microsoft/fluid-media:SharedMediaSession`;
35
-
36
- /**
37
- * The objects fluid type factory.
38
- */
39
- public static readonly factory = new DataObjectFactory(
40
- EphemeralMediaSession.TypeName,
41
- EphemeralMediaSession,
42
- [],
43
- {}
44
- );
45
-
46
- /**
47
- * Extension point that lets applications replace the default logic for throttling the sessions
48
- * local sync behavior.
49
- *
50
- * @remarks
51
- * The `EphemeralMediaCoordinator` is fairly aggressive at wanting to keep the local media player
52
- * in sync with the rest of the group. This aggressiveness can result in the coordinator sending
53
- * new sync actions before the local player has finished responding to the previous sync action.
54
- * The `ActionThrottler` gives apps fine grain control over how aggressive they want sync to be.
55
- *
56
- * By default, a `RepeatedAction` throttler is used which prevents the same sync action from
57
- * being sent within an adjustable time period.
58
- */
59
- public get actionThrottler(): MediaSessionActionThrottler {
60
- return this._actionThrottler;
61
- }
62
-
63
- public set actionThrottler(value: MediaSessionActionThrottler) {
64
- this._actionThrottler = value;
65
- }
66
-
67
- /**
68
- * Returns true if the object has been initialized.
69
- */
70
- public get isInitialized(): boolean {
71
- return this.coordinator.isInitialized;
72
- }
73
-
74
- /**
75
- * @deprecated isInitialized should be used instead
76
- * Returns true if the object has been initialized.
77
- */
78
- public get isStarted(): boolean {
79
- return this.isInitialized
80
- }
81
-
82
- /**
83
- * The group coordinator for the session.
84
- */
85
- public get coordinator(): EphemeralMediaSessionCoordinator {
86
- return this._coordinator!;
87
- }
88
-
89
- /**
90
- * Returns the logger used by the session and coordinator.
91
- *
92
- * @remarks
93
- * This is used by the `MediaPlayerSynchronizer` to log events.
94
- */
95
- public get logger(): EphemeralTelemetryLogger {
96
- return this._logger!;
97
- }
98
-
99
- /**
100
- * initialize the object.
101
- * @param acceptTransportChangesFrom Optional. List of roles allowed to group transport
102
- * operations like play/pause/seek/setTrack.
103
- */
104
- public initialize(acceptTransportChangesFrom?: UserMeetingRole[]): Promise<void> {
105
- return this.coordinator.initialize(acceptTransportChangesFrom);
106
- }
107
-
108
- /**
109
- * @deprecated initialize should be used instead
110
- * initialize the object.
111
- * @param acceptTransportChangesFrom Optional. List of roles allowed to group transport
112
- * operations like play/pause/seek/setTrack.
113
- */
114
- public start(acceptTransportChangesFrom?: UserMeetingRole[]): Promise<void> {
115
- return this.initialize(acceptTransportChangesFrom)
116
- }
117
-
118
- /**
119
- * Registers an action handler with the session.
120
- * @param action Name of the action to register a handler for.
121
- * @param handler Function called when the action is triggered.
122
- */
123
- public setActionHandler(action: ExtendedMediaSessionAction, handler: MediaSessionActionHandler | null): void {
124
- if (handler) {
125
- // add handler
126
- this._actionHandlers.set(action, handler);
127
-
128
- } else if (this._actionHandlers.has(action)) {
129
- // remove handler
130
- this._actionHandlers.delete(action);
131
- }
132
- }
133
-
134
- /**
135
- * Registers a handler that will be queried anytime the group coordinate needs to know the
136
- * local players transport state and position.
137
- */
138
- public setRequestPlayerStateHandler(handler: () => IMediaPlayerState) {
139
- this._requestPlayerStateHandler = handler;
140
- }
141
-
142
- /**
143
- * Begins synchronizing the playback of a media element.
144
- * @param player Something that "looks like" and HTML Media Element.
145
- * @returns A new synchronizer instance. Call `synchronizer.end()` to stop synchronizing the elements playback.
146
- */
147
- public synchronize(player: IMediaPlayer): MediaPlayerSynchronizer {
148
- // A session can only synchronize one player at a time
149
- if (this._synchronizing) {
150
- this._synchronizing.end();
151
- }
152
-
153
- // Start position update timer
154
- if (!this._updateTimer) {
155
- this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.BeginPositionUpdateTimer);
156
- this._updateTimer = setInterval(() => {
157
- // Get current state
158
- const state = this.getCurrentPlayerState();
159
-
160
- // Check for hit wait point
161
- this.checkWaitPointHit(state);
162
-
163
- // Send position update if interval hit
164
- const now = new Date().getTime();
165
- const delta = (now - this._lastUpdateTime) / 1000;
166
- if (this.coordinator.isInitialized && delta >= this.coordinator.positionUpdateInterval) {
167
- this._lastUpdateTime = now;
168
- this.coordinator.sendPositionUpdate(state);
169
- }
170
- }, 500);
171
- }
172
-
173
- return new MediaPlayerSynchronizer(player, this, () => {
174
- this._synchronizing = undefined;
175
- });
176
- }
177
-
178
- protected async hasInitialized(): Promise<void> {
179
- this. _logger = new EphemeralTelemetryLogger(this.runtime);
180
-
181
- // Create coordinator and listen for triggered actions
182
- this._coordinator = new EphemeralMediaSessionCoordinator(this.runtime, () => this.getCurrentPlayerState());
183
- this._coordinator.on(MediaSessionCoordinatorEvents.triggeraction, (event: ITriggerActionEvent) => {
184
- // Pre-process actions
185
- const details = event.details;
186
- const seekTime = typeof details.seekTime == 'number' ? details.seekTime : -1;
187
- switch (details.action) {
188
- case 'play':
189
- this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.PlayAction, null, {position: seekTime});
190
- break;
191
- case 'pause':
192
- this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.PauseAction, null, {position: seekTime});
193
- break;
194
- case 'seekto':
195
- this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.SeekToAction, null, {position: seekTime});
196
- break;
197
- case 'settrack':
198
- this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.SetTrackAction);
199
- break;
200
- case 'datachange':
201
- this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.DataChangeAction);
202
- break;
203
- case 'catchup':
204
- // Default to seekto if catchup not implemented
205
- this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.CatchUpAction, null, {position: seekTime});
206
- if (!this._actionHandlers.has('catchup')) {
207
- details.action = 'seekto';
208
- }
209
- break;
210
- }
211
-
212
- // Dispatch action
213
- this.dispatchAction(details);
214
- });
215
- }
216
-
217
- private checkWaitPointHit(state: IMediaPlayerState): void {
218
- // Was a wait point hit?
219
- if (state.positionState && this.coordinator.isInitialized) {
220
- const waitPoint = this.coordinator.findNextWaitPoint();
221
- if (waitPoint && state.positionState.position != undefined && state.positionState.position >= waitPoint.position) {
222
- // Ensure handler registered
223
- if (!this._actionHandlers.has('wait')) {
224
- throw new Error(`SharedMediaSession: wait point hit but no 'wait' action registered.`);
225
- }
226
-
227
- // Begin suspension for wait point
228
- const suspension = this.coordinator.beginSuspension(waitPoint);
229
- this.dispatchAction({action: 'wait', suspension: suspension});
230
- }
231
- }
232
- }
233
-
234
- private getCurrentPlayerState(): IMediaPlayerState {
235
- if (!this._requestPlayerStateHandler) {
236
- throw new Error(`SharedMediaSession: no getPlayerState callback configured.`);
237
- }
238
-
239
- return this._requestPlayerStateHandler();
240
- }
241
-
242
- private dispatchAction(details: MediaSessionActionDetails|ExtendedMediaSessionActionDetails): void {
243
- if (this._actionHandlers.has(details.action)) {
244
- const handler = this._actionHandlers.get(details.action);
245
- this._actionThrottler.throttled(details, handler);
246
- }
247
- }
248
- }
1
+ /**
2
+ * Copyright (c) Microsoft Corporation. All rights reserved.
3
+ * Licensed under the Microsoft Live Share SDK License.
4
+ */
5
+
6
+ import { DataObject, DataObjectFactory } from '@fluidframework/aqueduct';
7
+ import { EphemeralTelemetryLogger, UserMeetingRole } from '@microsoft/live-share';
8
+ import { MediaPlayerSynchronizer } from './MediaPlayerSynchronizer';
9
+ import { ITriggerActionEvent, TelemetryEvents } from './internals';
10
+ import { MediaSessionCoordinatorEvents, ExtendedMediaSessionAction, ExtendedMediaSessionActionDetails } from './MediaSessionExtensions';
11
+ import { EphemeralMediaSessionCoordinator, IMediaPlayerState } from './EphemeralMediaSessionCoordinator';
12
+ import { MediaSessionActionThrottler } from './MediaSessionActionThrottler';
13
+ import { RepeatedActionThrottler } from './RepeatedActionThrottler';
14
+ import { IMediaPlayer } from './IMediaPlayer';
15
+
16
+ /**
17
+ * Ephemeral fluid object that synchronizes media playback across multiple clients.
18
+ */
19
+ export class EphemeralMediaSession extends DataObject {
20
+ private _actionThrottler: MediaSessionActionThrottler = new RepeatedActionThrottler();
21
+ private _logger?: EphemeralTelemetryLogger;
22
+ private _requestPlayerStateHandler?: () => IMediaPlayerState;
23
+ private _coordinator?: EphemeralMediaSessionCoordinator;
24
+ private readonly _actionHandlers: Map<string, MediaSessionActionHandler> = new Map();
25
+ private _synchronizing?: MediaPlayerSynchronizer;
26
+
27
+ // Position update timer
28
+ private _updateTimer: any;
29
+ private _lastUpdateTime: number = 0;
30
+
31
+ /**
32
+ * The objects fluid type name.
33
+ */
34
+ public static readonly TypeName = `@microsoft/fluid-media:SharedMediaSession`;
35
+
36
+ /**
37
+ * The objects fluid type factory.
38
+ */
39
+ public static readonly factory = new DataObjectFactory(
40
+ EphemeralMediaSession.TypeName,
41
+ EphemeralMediaSession,
42
+ [],
43
+ {}
44
+ );
45
+
46
+ /**
47
+ * Extension point that lets applications replace the default logic for throttling the sessions
48
+ * local sync behavior.
49
+ *
50
+ * @remarks
51
+ * The `EphemeralMediaCoordinator` is fairly aggressive at wanting to keep the local media player
52
+ * in sync with the rest of the group. This aggressiveness can result in the coordinator sending
53
+ * new sync actions before the local player has finished responding to the previous sync action.
54
+ * The `ActionThrottler` gives apps fine grain control over how aggressive they want sync to be.
55
+ *
56
+ * By default, a `RepeatedAction` throttler is used which prevents the same sync action from
57
+ * being sent within an adjustable time period.
58
+ */
59
+ public get actionThrottler(): MediaSessionActionThrottler {
60
+ return this._actionThrottler;
61
+ }
62
+
63
+ public set actionThrottler(value: MediaSessionActionThrottler) {
64
+ this._actionThrottler = value;
65
+ }
66
+
67
+ /**
68
+ * Returns true if the object has been initialized.
69
+ */
70
+ public get isInitialized(): boolean {
71
+ return this.coordinator.isInitialized;
72
+ }
73
+
74
+ /**
75
+ * @deprecated isInitialized should be used instead
76
+ * Returns true if the object has been initialized.
77
+ */
78
+ public get isStarted(): boolean {
79
+ return this.isInitialized
80
+ }
81
+
82
+ /**
83
+ * The group coordinator for the session.
84
+ */
85
+ public get coordinator(): EphemeralMediaSessionCoordinator {
86
+ return this._coordinator!;
87
+ }
88
+
89
+ /**
90
+ * Returns the logger used by the session and coordinator.
91
+ *
92
+ * @remarks
93
+ * This is used by the `MediaPlayerSynchronizer` to log events.
94
+ */
95
+ public get logger(): EphemeralTelemetryLogger {
96
+ return this._logger!;
97
+ }
98
+
99
+ /**
100
+ * initialize the object.
101
+ * @param acceptTransportChangesFrom Optional. List of roles allowed to group transport
102
+ * operations like play/pause/seek/setTrack.
103
+ */
104
+ public initialize(acceptTransportChangesFrom?: UserMeetingRole[]): Promise<void> {
105
+ return this.coordinator.initialize(acceptTransportChangesFrom);
106
+ }
107
+
108
+ /**
109
+ * @deprecated initialize should be used instead
110
+ * initialize the object.
111
+ * @param acceptTransportChangesFrom Optional. List of roles allowed to group transport
112
+ * operations like play/pause/seek/setTrack.
113
+ */
114
+ public start(acceptTransportChangesFrom?: UserMeetingRole[]): Promise<void> {
115
+ return this.initialize(acceptTransportChangesFrom)
116
+ }
117
+
118
+ /**
119
+ * Registers an action handler with the session.
120
+ * @param action Name of the action to register a handler for.
121
+ * @param handler Function called when the action is triggered.
122
+ */
123
+ public setActionHandler(action: ExtendedMediaSessionAction, handler: MediaSessionActionHandler | null): void {
124
+ if (handler) {
125
+ // add handler
126
+ this._actionHandlers.set(action, handler);
127
+
128
+ } else if (this._actionHandlers.has(action)) {
129
+ // remove handler
130
+ this._actionHandlers.delete(action);
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Registers a handler that will be queried anytime the group coordinate needs to know the
136
+ * local players transport state and position.
137
+ */
138
+ public setRequestPlayerStateHandler(handler: () => IMediaPlayerState) {
139
+ this._requestPlayerStateHandler = handler;
140
+ }
141
+
142
+ /**
143
+ * Begins synchronizing the playback of a media element.
144
+ * @param player Something that "looks like" and HTML Media Element.
145
+ * @returns A new synchronizer instance. Call `synchronizer.end()` to stop synchronizing the elements playback.
146
+ */
147
+ public synchronize(player: IMediaPlayer): MediaPlayerSynchronizer {
148
+ // A session can only synchronize one player at a time
149
+ if (this._synchronizing) {
150
+ this._synchronizing.end();
151
+ }
152
+
153
+ // Start position update timer
154
+ if (!this._updateTimer) {
155
+ this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.BeginPositionUpdateTimer);
156
+ this._updateTimer = setInterval(() => {
157
+ // Get current state
158
+ const state = this.getCurrentPlayerState();
159
+
160
+ // Check for hit wait point
161
+ this.checkWaitPointHit(state);
162
+
163
+ // Send position update if interval hit
164
+ const now = new Date().getTime();
165
+ const delta = (now - this._lastUpdateTime) / 1000;
166
+ if (this.coordinator.isInitialized && delta >= this.coordinator.positionUpdateInterval) {
167
+ this._lastUpdateTime = now;
168
+ this.coordinator.sendPositionUpdate(state);
169
+ }
170
+ }, 500);
171
+ }
172
+
173
+ return new MediaPlayerSynchronizer(player, this, () => {
174
+ this._synchronizing = undefined;
175
+ });
176
+ }
177
+
178
+ protected async hasInitialized(): Promise<void> {
179
+ this. _logger = new EphemeralTelemetryLogger(this.runtime);
180
+
181
+ // Create coordinator and listen for triggered actions
182
+ this._coordinator = new EphemeralMediaSessionCoordinator(this.runtime, () => this.getCurrentPlayerState());
183
+ this._coordinator.on(MediaSessionCoordinatorEvents.triggeraction, (event: ITriggerActionEvent) => {
184
+ // Pre-process actions
185
+ const details = event.details;
186
+ const seekTime = typeof details.seekTime == 'number' ? details.seekTime : -1;
187
+ switch (details.action) {
188
+ case 'play':
189
+ this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.PlayAction, null, {position: seekTime});
190
+ break;
191
+ case 'pause':
192
+ this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.PauseAction, null, {position: seekTime});
193
+ break;
194
+ case 'seekto':
195
+ this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.SeekToAction, null, {position: seekTime});
196
+ break;
197
+ case 'settrack':
198
+ this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.SetTrackAction);
199
+ break;
200
+ case 'datachange':
201
+ this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.DataChangeAction);
202
+ break;
203
+ case 'catchup':
204
+ // Default to seekto if catchup not implemented
205
+ this.logger.sendTelemetryEvent(TelemetryEvents.MediaSession.CatchUpAction, null, {position: seekTime});
206
+ if (!this._actionHandlers.has('catchup')) {
207
+ details.action = 'seekto';
208
+ }
209
+ break;
210
+ }
211
+
212
+ // Dispatch action
213
+ this.dispatchAction(details);
214
+ });
215
+ }
216
+
217
+ private checkWaitPointHit(state: IMediaPlayerState): void {
218
+ // Was a wait point hit?
219
+ if (state.positionState && this.coordinator.isInitialized) {
220
+ const waitPoint = this.coordinator.findNextWaitPoint();
221
+ if (waitPoint && state.positionState.position != undefined && state.positionState.position >= waitPoint.position) {
222
+ // Ensure handler registered
223
+ if (!this._actionHandlers.has('wait')) {
224
+ throw new Error(`SharedMediaSession: wait point hit but no 'wait' action registered.`);
225
+ }
226
+
227
+ // Begin suspension for wait point
228
+ const suspension = this.coordinator.beginSuspension(waitPoint);
229
+ this.dispatchAction({action: 'wait', suspension: suspension});
230
+ }
231
+ }
232
+ }
233
+
234
+ private getCurrentPlayerState(): IMediaPlayerState {
235
+ if (!this._requestPlayerStateHandler) {
236
+ throw new Error(`SharedMediaSession: no getPlayerState callback configured.`);
237
+ }
238
+
239
+ return this._requestPlayerStateHandler();
240
+ }
241
+
242
+ private dispatchAction(details: MediaSessionActionDetails|ExtendedMediaSessionActionDetails): void {
243
+ if (this._actionHandlers.has(details.action)) {
244
+ const handler = this._actionHandlers.get(details.action);
245
+ this._actionThrottler.throttled(details, handler);
246
+ }
247
+ }
248
+ }