aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Syncplay/SyncplayController.cs
blob: 83b477944738efada6f1e7f94ac4c73e452f8324 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Controller.Session;
using MediaBrowser.Controller.Syncplay;
using MediaBrowser.Model.Session;
using MediaBrowser.Model.Syncplay;
using Microsoft.Extensions.Logging;

namespace Emby.Server.Implementations.Syncplay
{
    /// <summary>
    /// Class SyncplayController.
    /// </summary>
    public class SyncplayController : ISyncplayController, IDisposable
    {
        private enum BroadcastType
        {
            AllGroup = 0,
            SingleSession = 1,
            AllExceptSession = 2,
            AllReady = 3
        }

        /// <summary>
        /// The logger.
        /// </summary>
        private readonly ILogger _logger;

        /// <summary>
        /// The session manager.
        /// </summary>
        private readonly ISessionManager _sessionManager;

        /// <summary>
        /// The syncplay manager.
        /// </summary>
        private readonly ISyncplayManager _syncplayManager;

        /// <summary>
        /// The group to manage.
        /// </summary>
        private readonly GroupInfo _group = new GroupInfo();

        /// <inheritdoc />
        public Guid GetGroupId() => _group.GroupId;

        /// <inheritdoc />
        public Guid GetPlayingItemId() => _group.PlayingItem.Id;

        /// <inheritdoc />
        public bool IsGroupEmpty() => _group.IsEmpty();

        private bool _disposed = false;

        public SyncplayController(
            ILogger logger,
            ISessionManager sessionManager,
            ISyncplayManager syncplayManager)
        {
            _logger = logger;
            _sessionManager = sessionManager;
            _syncplayManager = syncplayManager;
        }

        /// <inheritdoc />
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Releases unmanaged and optionally managed resources.
        /// </summary>
        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
        protected virtual void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;
        }

        // TODO: use this somewhere
        private void CheckDisposed()
        {
            if (_disposed)
            {
                throw new ObjectDisposedException(GetType().Name);
            }
        }

        private SessionInfo[] FilterSessions(SessionInfo from, BroadcastType type)
        {
            if (type == BroadcastType.SingleSession)
            {
                return new SessionInfo[] { from };
            }
            else if (type == BroadcastType.AllGroup)
            {
                return _group.Partecipants.Values.Select(
                    session => session.Session
                ).ToArray();
            }
            else if (type == BroadcastType.AllExceptSession)
            {
                return _group.Partecipants.Values.Select(
                    session => session.Session
                ).Where(
                    session => !session.Id.Equals(from.Id)
                ).ToArray();
            }
            else if (type == BroadcastType.AllReady)
            {
                return _group.Partecipants.Values.Where(
                    session => !session.IsBuffering
                ).Select(
                    session => session.Session
                ).ToArray();
            }
            else
            {
                return new SessionInfo[] {};
            }
        }

        private Task SendGroupUpdate<T>(SessionInfo from, BroadcastType type, GroupUpdate<T> message)
        {
            IEnumerable<Task> GetTasks()
            {
                SessionInfo[] sessions = FilterSessions(from, type);
                foreach (var session in sessions)
                {
                    yield return _sessionManager.SendSyncplayGroupUpdate(session.Id.ToString(), message, CancellationToken.None);
                }
            }

            return Task.WhenAll(GetTasks());
        }

        private Task SendCommand(SessionInfo from, BroadcastType type, SendCommand message)
        {
            IEnumerable<Task> GetTasks()
            {
                SessionInfo[] sessions = FilterSessions(from, type);
                foreach (var session in sessions)
                {
                    yield return _sessionManager.SendSyncplayCommand(session.Id.ToString(), message, CancellationToken.None);
                }
            }

            return Task.WhenAll(GetTasks());
        }

        private SendCommand NewSyncplayCommand(SendCommandType type)
        {
            var command = new SendCommand();
            command.GroupId = _group.GroupId.ToString();
            command.Command = type;
            command.PositionTicks = _group.PositionTicks;
            command.When = _group.LastActivity.ToUniversalTime().ToString("o");
            command.EmittedAt = DateTime.UtcNow.ToUniversalTime().ToString("o");
            return command;
        }

        private GroupUpdate<T> NewSyncplayGroupUpdate<T>(GroupUpdateType type, T data)
        {
            var command = new GroupUpdate<T>();
            command.GroupId = _group.GroupId.ToString();
            command.Type = type;
            command.Data = data;
            return command;
        }

        /// <inheritdoc />
        public void InitGroup(SessionInfo session)
        {
            _group.AddSession(session);
            _syncplayManager.MapSessionToGroup(session, this);

            _group.PlayingItem = session.FullNowPlayingItem;
            _group.IsPaused = true;
            _group.PositionTicks = session.PlayState.PositionTicks ??= 0;
            _group.LastActivity = DateTime.UtcNow;

            var updateSession = NewSyncplayGroupUpdate(GroupUpdateType.GroupJoined, DateTime.UtcNow.ToUniversalTime().ToString("o"));
            SendGroupUpdate(session, BroadcastType.SingleSession, updateSession);
            var pauseCommand = NewSyncplayCommand(SendCommandType.Pause);
            SendCommand(session, BroadcastType.SingleSession, pauseCommand);
        }

        /// <inheritdoc />
        public void SessionJoin(SessionInfo session, JoinGroupRequest request)
        {
            if (session.NowPlayingItem != null &&
                session.NowPlayingItem.Id.Equals(_group.PlayingItem.Id) &&
                request.PlayingItemId.Equals(_group.PlayingItem.Id))
            {
                _group.AddSession(session);
                _syncplayManager.MapSessionToGroup(session, this);

                var updateSession = NewSyncplayGroupUpdate(GroupUpdateType.GroupJoined, DateTime.UtcNow.ToUniversalTime().ToString("o"));
                SendGroupUpdate(session, BroadcastType.SingleSession, updateSession);

                var updateOthers = NewSyncplayGroupUpdate(GroupUpdateType.UserJoined, session.UserName);
                SendGroupUpdate(session, BroadcastType.AllExceptSession, updateOthers);

                // Client join and play, syncing will happen client side
                if (!_group.IsPaused)
                {
                    var playCommand = NewSyncplayCommand(SendCommandType.Play);
                    SendCommand(session, BroadcastType.SingleSession, playCommand);
                }
                else
                {
                    var pauseCommand = NewSyncplayCommand(SendCommandType.Pause);
                    SendCommand(session, BroadcastType.SingleSession, pauseCommand);
                }
            }
            else
            {
                var playRequest = new PlayRequest();
                playRequest.ItemIds = new Guid[] { _group.PlayingItem.Id };
                playRequest.StartPositionTicks = _group.PositionTicks;
                var update = NewSyncplayGroupUpdate(GroupUpdateType.PrepareSession, playRequest);
                SendGroupUpdate(session, BroadcastType.SingleSession, update);
            }
        }

        /// <inheritdoc />
        public void SessionLeave(SessionInfo session)
        {
            _group.RemoveSession(session);
            _syncplayManager.UnmapSessionFromGroup(session, this);

            var updateSession = NewSyncplayGroupUpdate(GroupUpdateType.GroupLeft, _group.PositionTicks);
            SendGroupUpdate(session, BroadcastType.SingleSession, updateSession);

            var updateOthers = NewSyncplayGroupUpdate(GroupUpdateType.UserLeft, session.UserName);
            SendGroupUpdate(session, BroadcastType.AllExceptSession, updateOthers);
        }

        /// <inheritdoc />
        public void HandleRequest(SessionInfo session, PlaybackRequest request)
        {
            if (request.Type.Equals(PlaybackRequestType.Play))
            {
                if (_group.IsPaused)
                {
                    var delay = _group.GetHighestPing() * 2;
                    delay = delay < _group.DefaulPing ? _group.DefaulPing : delay;

                    _group.IsPaused = false;
                    _group.LastActivity = DateTime.UtcNow.AddMilliseconds(
                        delay
                    );

                    var command = NewSyncplayCommand(SendCommandType.Play);
                    SendCommand(session, BroadcastType.AllGroup, command);
                }
                else
                {
                    // Client got lost
                    var command = NewSyncplayCommand(SendCommandType.Play);
                    SendCommand(session, BroadcastType.SingleSession, command);
                }
            }
            else if (request.Type.Equals(PlaybackRequestType.Pause))
            {
                if (!_group.IsPaused)
                {
                    _group.IsPaused = true;
                    var currentTime = DateTime.UtcNow;
                    var elapsedTime = currentTime - _group.LastActivity;
                    _group.LastActivity = currentTime;
                    _group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0;

                    var command = NewSyncplayCommand(SendCommandType.Pause);
                    SendCommand(session, BroadcastType.AllGroup, command);
                }
                else
                {
                    var command = NewSyncplayCommand(SendCommandType.Pause);
                    SendCommand(session, BroadcastType.SingleSession, command);
                }
            }
            else if (request.Type.Equals(PlaybackRequestType.Seek))
            {
                // Sanitize PositionTicks
                var ticks = request.PositionTicks ??= 0;
                ticks = ticks >= 0 ? ticks : 0;
                if (_group.PlayingItem.RunTimeTicks != null)
                {
                    var runTimeTicks = _group.PlayingItem.RunTimeTicks ??= 0;
                    ticks = ticks > runTimeTicks ? runTimeTicks : ticks;
                }

                _group.IsPaused = true;
                _group.PositionTicks = ticks;
                _group.LastActivity = DateTime.UtcNow;

                var command = NewSyncplayCommand(SendCommandType.Seek);
                SendCommand(session, BroadcastType.AllGroup, command);
            }
            // TODO: client does not implement this yet
            else if (request.Type.Equals(PlaybackRequestType.Buffering))
            {
                if (!_group.IsPaused)
                {
                    _group.IsPaused = true;
                    var currentTime = DateTime.UtcNow;
                    var elapsedTime = currentTime - _group.LastActivity;
                    _group.LastActivity = currentTime;
                    _group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0;

                    _group.SetBuffering(session, true);

                    // Send pause command to all non-buffering sessions
                    var command = NewSyncplayCommand(SendCommandType.Pause);
                    SendCommand(session, BroadcastType.AllReady, command);

                    var updateOthers = NewSyncplayGroupUpdate(GroupUpdateType.GroupWait, session.UserName);
                    SendGroupUpdate(session, BroadcastType.AllExceptSession, updateOthers);
                }
                else
                {
                    var command = NewSyncplayCommand(SendCommandType.Pause);
                    SendCommand(session, BroadcastType.SingleSession, command);
                }
            }
            // TODO: client does not implement this yet
            else if (request.Type.Equals(PlaybackRequestType.BufferingComplete))
            {
                if (_group.IsPaused)
                {
                    _group.SetBuffering(session, false);

                    if (_group.IsBuffering()) {
                        // Others are buffering, tell this client to pause when ready
                        var when = request.When ??= DateTime.UtcNow;
                        var currentTime = DateTime.UtcNow;
                        var elapsedTime = currentTime - when;
                        var clientPosition = TimeSpan.FromTicks(request.PositionTicks ??= 0) + elapsedTime;
                        var delay = _group.PositionTicks - clientPosition.Ticks;

                        var command = NewSyncplayCommand(SendCommandType.Pause);
                        command.When = currentTime.AddMilliseconds(
                            delay
                        ).ToUniversalTime().ToString("o");
                        SendCommand(session, BroadcastType.SingleSession, command);
                    }
                    else
                    {
                        // Let other clients resume as soon as the buffering client catches up
                        var when = request.When ??= DateTime.UtcNow;
                        var currentTime = DateTime.UtcNow;
                        var elapsedTime = currentTime - when;
                        var clientPosition = TimeSpan.FromTicks(request.PositionTicks ??= 0) + elapsedTime;
                        var delay = _group.PositionTicks - clientPosition.Ticks;

                        _group.IsPaused = false;

                        if (delay > _group.GetHighestPing() * 2)
                        {
                            // Client that was buffering is recovering, notifying others to resume
                            _group.LastActivity = currentTime.AddMilliseconds(
                                delay
                            );
                            var command = NewSyncplayCommand(SendCommandType.Play);
                            SendCommand(session, BroadcastType.AllExceptSession, command);
                        }
                        else
                        {
                            // Client, that was buffering, resumed playback but did not update others in time
                            delay = _group.GetHighestPing() * 2;
                            delay = delay < _group.DefaulPing ? _group.DefaulPing : delay;

                            _group.LastActivity = currentTime.AddMilliseconds(
                                delay
                            );

                            var command = NewSyncplayCommand(SendCommandType.Play);
                            SendCommand(session, BroadcastType.AllGroup, command);
                        }
                    }                    
                }
                else
                {
                    // Make sure client has latest group state
                    var command = NewSyncplayCommand(SendCommandType.Play);
                    SendCommand(session, BroadcastType.SingleSession, command);
                }
            }
            else if (request.Type.Equals(PlaybackRequestType.UpdatePing))
            {
                _group.UpdatePing(session, request.Ping ??= _group.DefaulPing);
            }
        }

        /// <inheritdoc />
        public GroupInfoView GetInfo()
        {
            var info = new GroupInfoView();
            info.GroupId = GetGroupId().ToString();
            info.PlayingItemName = _group.PlayingItem.Name;
            info.PlayingItemId = _group.PlayingItem.Id.ToString();
            info.PositionTicks = _group.PositionTicks;
            info.Partecipants = _group.Partecipants.Values.Select(session => session.Session.UserName).ToArray();
            return info;
        }
    }
}