SyncPlayController.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using MediaBrowser.Controller.Session;
  7. using MediaBrowser.Controller.SyncPlay;
  8. using MediaBrowser.Model.Session;
  9. using MediaBrowser.Model.SyncPlay;
  10. namespace Emby.Server.Implementations.SyncPlay
  11. {
  12. /// <summary>
  13. /// Class SyncPlayController.
  14. /// </summary>
  15. /// <remarks>
  16. /// Class is not thread-safe, external locking is required when accessing methods.
  17. /// </remarks>
  18. public class SyncPlayController : ISyncPlayController
  19. {
  20. /// <summary>
  21. /// Used to filter the sessions of a group.
  22. /// </summary>
  23. private enum BroadcastType
  24. {
  25. /// <summary>
  26. /// All sessions will receive the message.
  27. /// </summary>
  28. AllGroup = 0,
  29. /// <summary>
  30. /// Only the specified session will receive the message.
  31. /// </summary>
  32. CurrentSession = 1,
  33. /// <summary>
  34. /// All sessions, except the current one, will receive the message.
  35. /// </summary>
  36. AllExceptCurrentSession = 2,
  37. /// <summary>
  38. /// Only sessions that are not buffering will receive the message.
  39. /// </summary>
  40. AllReady = 3
  41. }
  42. /// <summary>
  43. /// The session manager.
  44. /// </summary>
  45. private readonly ISessionManager _sessionManager;
  46. /// <summary>
  47. /// The SyncPlay manager.
  48. /// </summary>
  49. private readonly ISyncPlayManager _syncPlayManager;
  50. /// <summary>
  51. /// The group to manage.
  52. /// </summary>
  53. private readonly GroupInfo _group = new GroupInfo();
  54. /// <inheritdoc />
  55. public Guid GetGroupId() => _group.GroupId;
  56. /// <inheritdoc />
  57. public Guid GetPlayingItemId() => _group.PlayingItem.Id;
  58. /// <inheritdoc />
  59. public bool IsGroupEmpty() => _group.IsEmpty();
  60. /// <summary>
  61. /// Initializes a new instance of the <see cref="SyncPlayController" /> class.
  62. /// </summary>
  63. /// <param name="sessionManager">The session manager.</param>
  64. /// <param name="syncPlayManager">The SyncPlay manager.</param>
  65. public SyncPlayController(
  66. ISessionManager sessionManager,
  67. ISyncPlayManager syncPlayManager)
  68. {
  69. _sessionManager = sessionManager;
  70. _syncPlayManager = syncPlayManager;
  71. }
  72. /// <summary>
  73. /// Converts DateTime to UTC string.
  74. /// </summary>
  75. /// <param name="date">The date to convert.</param>
  76. /// <value>The UTC string.</value>
  77. private string DateToUTCString(DateTime date)
  78. {
  79. return date.ToUniversalTime().ToString("o");
  80. }
  81. /// <summary>
  82. /// Filters sessions of this group.
  83. /// </summary>
  84. /// <param name="from">The current session.</param>
  85. /// <param name="type">The filtering type.</param>
  86. /// <value>The array of sessions matching the filter.</value>
  87. private SessionInfo[] FilterSessions(SessionInfo from, BroadcastType type)
  88. {
  89. switch (type)
  90. {
  91. case BroadcastType.CurrentSession:
  92. return new SessionInfo[] { from };
  93. case BroadcastType.AllGroup:
  94. return _group.Participants.Values.Select(
  95. session => session.Session).ToArray();
  96. case BroadcastType.AllExceptCurrentSession:
  97. return _group.Participants.Values.Select(
  98. session => session.Session).Where(
  99. session => !session.Id.Equals(from.Id)).ToArray();
  100. case BroadcastType.AllReady:
  101. return _group.Participants.Values.Where(
  102. session => !session.IsBuffering).Select(
  103. session => session.Session).ToArray();
  104. default:
  105. return Array.Empty<SessionInfo>();
  106. }
  107. }
  108. /// <summary>
  109. /// Sends a GroupUpdate message to the interested sessions.
  110. /// </summary>
  111. /// <param name="from">The current session.</param>
  112. /// <param name="type">The filtering type.</param>
  113. /// <param name="message">The message to send.</param>
  114. /// <param name="cancellationToken">The cancellation token.</param>
  115. /// <value>The task.</value>
  116. private Task SendGroupUpdate<T>(SessionInfo from, BroadcastType type, GroupUpdate<T> message, CancellationToken cancellationToken)
  117. {
  118. IEnumerable<Task> GetTasks()
  119. {
  120. SessionInfo[] sessions = FilterSessions(from, type);
  121. foreach (var session in sessions)
  122. {
  123. yield return _sessionManager.SendSyncPlayGroupUpdate(session.Id.ToString(), message, cancellationToken);
  124. }
  125. }
  126. return Task.WhenAll(GetTasks());
  127. }
  128. /// <summary>
  129. /// Sends a playback command to the interested sessions.
  130. /// </summary>
  131. /// <param name="from">The current session.</param>
  132. /// <param name="type">The filtering type.</param>
  133. /// <param name="message">The message to send.</param>
  134. /// <param name="cancellationToken">The cancellation token.</param>
  135. /// <value>The task.</value>
  136. private Task SendCommand(SessionInfo from, BroadcastType type, SendCommand message, CancellationToken cancellationToken)
  137. {
  138. IEnumerable<Task> GetTasks()
  139. {
  140. SessionInfo[] sessions = FilterSessions(from, type);
  141. foreach (var session in sessions)
  142. {
  143. yield return _sessionManager.SendSyncPlayCommand(session.Id.ToString(), message, cancellationToken);
  144. }
  145. }
  146. return Task.WhenAll(GetTasks());
  147. }
  148. /// <summary>
  149. /// Builds a new playback command with some default values.
  150. /// </summary>
  151. /// <param name="type">The command type.</param>
  152. /// <value>The SendCommand.</value>
  153. private SendCommand NewSyncPlayCommand(SendCommandType type)
  154. {
  155. return new SendCommand()
  156. {
  157. GroupId = _group.GroupId.ToString(),
  158. Command = type,
  159. PositionTicks = _group.PositionTicks,
  160. When = DateToUTCString(_group.LastActivity),
  161. EmittedAt = DateToUTCString(DateTime.UtcNow)
  162. };
  163. }
  164. /// <summary>
  165. /// Builds a new group update message.
  166. /// </summary>
  167. /// <param name="type">The update type.</param>
  168. /// <param name="data">The data to send.</param>
  169. /// <value>The GroupUpdate.</value>
  170. private GroupUpdate<T> NewSyncPlayGroupUpdate<T>(GroupUpdateType type, T data)
  171. {
  172. return new GroupUpdate<T>()
  173. {
  174. GroupId = _group.GroupId.ToString(),
  175. Type = type,
  176. Data = data
  177. };
  178. }
  179. /// <inheritdoc />
  180. public void CreateGroup(SessionInfo session, CancellationToken cancellationToken)
  181. {
  182. _group.AddSession(session);
  183. _syncPlayManager.AddSessionToGroup(session, this);
  184. _group.PlayingItem = session.FullNowPlayingItem;
  185. _group.IsPaused = session.PlayState.IsPaused;
  186. _group.PositionTicks = session.PlayState.PositionTicks ?? 0;
  187. _group.LastActivity = DateTime.UtcNow;
  188. var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow));
  189. SendGroupUpdate(session, BroadcastType.CurrentSession, updateSession, cancellationToken);
  190. }
  191. /// <inheritdoc />
  192. public void SessionJoin(SessionInfo session, JoinGroupRequest request, CancellationToken cancellationToken)
  193. {
  194. if (session.NowPlayingItem?.Id == _group.PlayingItem.Id)
  195. {
  196. _group.AddSession(session);
  197. _syncPlayManager.AddSessionToGroup(session, this);
  198. var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupJoined, DateToUTCString(DateTime.UtcNow));
  199. SendGroupUpdate(session, BroadcastType.CurrentSession, updateSession, cancellationToken);
  200. var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserJoined, session.UserName);
  201. SendGroupUpdate(session, BroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
  202. // Syncing will happen client-side
  203. if (!_group.IsPaused)
  204. {
  205. var playCommand = NewSyncPlayCommand(SendCommandType.Play);
  206. SendCommand(session, BroadcastType.CurrentSession, playCommand, cancellationToken);
  207. }
  208. else
  209. {
  210. var pauseCommand = NewSyncPlayCommand(SendCommandType.Pause);
  211. SendCommand(session, BroadcastType.CurrentSession, pauseCommand, cancellationToken);
  212. }
  213. }
  214. else
  215. {
  216. var playRequest = new PlayRequest();
  217. playRequest.ItemIds = new Guid[] { _group.PlayingItem.Id };
  218. playRequest.StartPositionTicks = _group.PositionTicks;
  219. var update = NewSyncPlayGroupUpdate(GroupUpdateType.PrepareSession, playRequest);
  220. SendGroupUpdate(session, BroadcastType.CurrentSession, update, cancellationToken);
  221. }
  222. }
  223. /// <inheritdoc />
  224. public void SessionLeave(SessionInfo session, CancellationToken cancellationToken)
  225. {
  226. _group.RemoveSession(session);
  227. _syncPlayManager.RemoveSessionFromGroup(session, this);
  228. var updateSession = NewSyncPlayGroupUpdate(GroupUpdateType.GroupLeft, _group.PositionTicks);
  229. SendGroupUpdate(session, BroadcastType.CurrentSession, updateSession, cancellationToken);
  230. var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.UserLeft, session.UserName);
  231. SendGroupUpdate(session, BroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
  232. }
  233. /// <inheritdoc />
  234. public void HandleRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
  235. {
  236. // The server's job is to maintain a consistent state for clients to reference
  237. // and notify clients of state changes. The actual syncing of media playback
  238. // happens client side. Clients are aware of the server's time and use it to sync.
  239. switch (request.Type)
  240. {
  241. case PlaybackRequestType.Play:
  242. HandlePlayRequest(session, request, cancellationToken);
  243. break;
  244. case PlaybackRequestType.Pause:
  245. HandlePauseRequest(session, request, cancellationToken);
  246. break;
  247. case PlaybackRequestType.Seek:
  248. HandleSeekRequest(session, request, cancellationToken);
  249. break;
  250. case PlaybackRequestType.Buffer:
  251. HandleBufferingRequest(session, request, cancellationToken);
  252. break;
  253. case PlaybackRequestType.Ready:
  254. HandleBufferingDoneRequest(session, request, cancellationToken);
  255. break;
  256. case PlaybackRequestType.Ping:
  257. HandlePingUpdateRequest(session, request);
  258. break;
  259. }
  260. }
  261. /// <summary>
  262. /// Handles a play action requested by a session.
  263. /// </summary>
  264. /// <param name="session">The session.</param>
  265. /// <param name="request">The play action.</param>
  266. /// <param name="cancellationToken">The cancellation token.</param>
  267. private void HandlePlayRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
  268. {
  269. if (_group.IsPaused)
  270. {
  271. // Pick a suitable time that accounts for latency
  272. var delay = _group.GetHighestPing() * 2;
  273. delay = delay < _group.DefaultPing ? _group.DefaultPing : delay;
  274. // Unpause group and set starting point in future
  275. // Clients will start playback at LastActivity (datetime) from PositionTicks (playback position)
  276. // The added delay does not guarantee, of course, that the command will be received in time
  277. // Playback synchronization will mainly happen client side
  278. _group.IsPaused = false;
  279. _group.LastActivity = DateTime.UtcNow.AddMilliseconds(
  280. delay);
  281. var command = NewSyncPlayCommand(SendCommandType.Play);
  282. SendCommand(session, BroadcastType.AllGroup, command, cancellationToken);
  283. }
  284. else
  285. {
  286. // Client got lost, sending current state
  287. var command = NewSyncPlayCommand(SendCommandType.Play);
  288. SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
  289. }
  290. }
  291. /// <summary>
  292. /// Handles a pause action requested by a session.
  293. /// </summary>
  294. /// <param name="session">The session.</param>
  295. /// <param name="request">The pause action.</param>
  296. /// <param name="cancellationToken">The cancellation token.</param>
  297. private void HandlePauseRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
  298. {
  299. if (!_group.IsPaused)
  300. {
  301. // Pause group and compute the media playback position
  302. _group.IsPaused = true;
  303. var currentTime = DateTime.UtcNow;
  304. var elapsedTime = currentTime - _group.LastActivity;
  305. _group.LastActivity = currentTime;
  306. // Seek only if playback actually started
  307. // Pause request may be issued during the delay added to account for latency
  308. _group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0;
  309. var command = NewSyncPlayCommand(SendCommandType.Pause);
  310. SendCommand(session, BroadcastType.AllGroup, command, cancellationToken);
  311. }
  312. else
  313. {
  314. // Client got lost, sending current state
  315. var command = NewSyncPlayCommand(SendCommandType.Pause);
  316. SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
  317. }
  318. }
  319. /// <summary>
  320. /// Handles a seek action requested by a session.
  321. /// </summary>
  322. /// <param name="session">The session.</param>
  323. /// <param name="request">The seek action.</param>
  324. /// <param name="cancellationToken">The cancellation token.</param>
  325. private void HandleSeekRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
  326. {
  327. // Sanitize PositionTicks
  328. var ticks = SanitizePositionTicks(request.PositionTicks);
  329. // Pause and seek
  330. _group.IsPaused = true;
  331. _group.PositionTicks = ticks;
  332. _group.LastActivity = DateTime.UtcNow;
  333. var command = NewSyncPlayCommand(SendCommandType.Seek);
  334. SendCommand(session, BroadcastType.AllGroup, command, cancellationToken);
  335. }
  336. /// <summary>
  337. /// Handles a buffering action requested by a session.
  338. /// </summary>
  339. /// <param name="session">The session.</param>
  340. /// <param name="request">The buffering action.</param>
  341. /// <param name="cancellationToken">The cancellation token.</param>
  342. private void HandleBufferingRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
  343. {
  344. if (!_group.IsPaused)
  345. {
  346. // Pause group and compute the media playback position
  347. _group.IsPaused = true;
  348. var currentTime = DateTime.UtcNow;
  349. var elapsedTime = currentTime - _group.LastActivity;
  350. _group.LastActivity = currentTime;
  351. _group.PositionTicks += elapsedTime.Ticks > 0 ? elapsedTime.Ticks : 0;
  352. _group.SetBuffering(session, true);
  353. // Send pause command to all non-buffering sessions
  354. var command = NewSyncPlayCommand(SendCommandType.Pause);
  355. SendCommand(session, BroadcastType.AllReady, command, cancellationToken);
  356. var updateOthers = NewSyncPlayGroupUpdate(GroupUpdateType.GroupWait, session.UserName);
  357. SendGroupUpdate(session, BroadcastType.AllExceptCurrentSession, updateOthers, cancellationToken);
  358. }
  359. else
  360. {
  361. // Client got lost, sending current state
  362. var command = NewSyncPlayCommand(SendCommandType.Pause);
  363. SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
  364. }
  365. }
  366. /// <summary>
  367. /// Handles a buffering-done action requested by a session.
  368. /// </summary>
  369. /// <param name="session">The session.</param>
  370. /// <param name="request">The buffering-done action.</param>
  371. /// <param name="cancellationToken">The cancellation token.</param>
  372. private void HandleBufferingDoneRequest(SessionInfo session, PlaybackRequest request, CancellationToken cancellationToken)
  373. {
  374. if (_group.IsPaused)
  375. {
  376. _group.SetBuffering(session, false);
  377. var requestTicks = SanitizePositionTicks(request.PositionTicks);
  378. var when = request.When ?? DateTime.UtcNow;
  379. var currentTime = DateTime.UtcNow;
  380. var elapsedTime = currentTime - when;
  381. var clientPosition = TimeSpan.FromTicks(requestTicks) + elapsedTime;
  382. var delay = _group.PositionTicks - clientPosition.Ticks;
  383. if (_group.IsBuffering())
  384. {
  385. // Others are still buffering, tell this client to pause when ready
  386. var command = NewSyncPlayCommand(SendCommandType.Pause);
  387. var pauseAtTime = currentTime.AddMilliseconds(delay);
  388. command.When = DateToUTCString(pauseAtTime);
  389. SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
  390. }
  391. else
  392. {
  393. // Let other clients resume as soon as the buffering client catches up
  394. _group.IsPaused = false;
  395. if (delay > _group.GetHighestPing() * 2)
  396. {
  397. // Client that was buffering is recovering, notifying others to resume
  398. _group.LastActivity = currentTime.AddMilliseconds(
  399. delay);
  400. var command = NewSyncPlayCommand(SendCommandType.Play);
  401. SendCommand(session, BroadcastType.AllExceptCurrentSession, command, cancellationToken);
  402. }
  403. else
  404. {
  405. // Client, that was buffering, resumed playback but did not update others in time
  406. delay = _group.GetHighestPing() * 2;
  407. delay = delay < _group.DefaultPing ? _group.DefaultPing : delay;
  408. _group.LastActivity = currentTime.AddMilliseconds(
  409. delay);
  410. var command = NewSyncPlayCommand(SendCommandType.Play);
  411. SendCommand(session, BroadcastType.AllGroup, command, cancellationToken);
  412. }
  413. }
  414. }
  415. else
  416. {
  417. // Group was not waiting, make sure client has latest state
  418. var command = NewSyncPlayCommand(SendCommandType.Play);
  419. SendCommand(session, BroadcastType.CurrentSession, command, cancellationToken);
  420. }
  421. }
  422. /// <summary>
  423. /// Sanitizes the PositionTicks, considers the current playing item when available.
  424. /// </summary>
  425. /// <param name="positionTicks">The PositionTicks.</param>
  426. /// <value>The sanitized PositionTicks.</value>
  427. private long SanitizePositionTicks(long? positionTicks)
  428. {
  429. var ticks = positionTicks ?? 0;
  430. ticks = ticks >= 0 ? ticks : 0;
  431. if (_group.PlayingItem != null)
  432. {
  433. var runTimeTicks = _group.PlayingItem.RunTimeTicks ?? 0;
  434. ticks = ticks > runTimeTicks ? runTimeTicks : ticks;
  435. }
  436. return ticks;
  437. }
  438. /// <summary>
  439. /// Updates ping of a session.
  440. /// </summary>
  441. /// <param name="session">The session.</param>
  442. /// <param name="request">The update.</param>
  443. private void HandlePingUpdateRequest(SessionInfo session, PlaybackRequest request)
  444. {
  445. // Collected pings are used to account for network latency when unpausing playback
  446. _group.UpdatePing(session, request.Ping ?? _group.DefaultPing);
  447. }
  448. /// <inheritdoc />
  449. public GroupInfoView GetInfo()
  450. {
  451. return new GroupInfoView()
  452. {
  453. GroupId = GetGroupId().ToString(),
  454. PlayingItemName = _group.PlayingItem.Name,
  455. PlayingItemId = _group.PlayingItem.Id.ToString(),
  456. PositionTicks = _group.PositionTicks,
  457. Participants = _group.Participants.Values.Select(session => session.Session.UserName).Distinct().ToList()
  458. };
  459. }
  460. }
  461. }