PlayToController.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. using MediaBrowser.Controller.Dlna;
  2. using MediaBrowser.Controller.Drawing;
  3. using MediaBrowser.Controller.Entities;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Localization;
  6. using MediaBrowser.Controller.Session;
  7. using MediaBrowser.Dlna.Didl;
  8. using MediaBrowser.Dlna.Ssdp;
  9. using MediaBrowser.Model.Dlna;
  10. using MediaBrowser.Model.Dto;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.Logging;
  13. using MediaBrowser.Model.Session;
  14. using MediaBrowser.Model.System;
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Globalization;
  18. using System.Linq;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. namespace MediaBrowser.Dlna.PlayTo
  22. {
  23. public class PlayToController : ISessionController, IDisposable
  24. {
  25. private Device _device;
  26. private readonly SessionInfo _session;
  27. private readonly ISessionManager _sessionManager;
  28. private readonly ILibraryManager _libraryManager;
  29. private readonly ILogger _logger;
  30. private readonly IDlnaManager _dlnaManager;
  31. private readonly IUserManager _userManager;
  32. private readonly IImageProcessor _imageProcessor;
  33. private readonly IUserDataManager _userDataManager;
  34. private readonly ILocalizationManager _localization;
  35. private readonly IMediaSourceManager _mediaSourceManager;
  36. private readonly DeviceDiscovery _deviceDiscovery;
  37. private readonly string _serverAddress;
  38. private readonly string _accessToken;
  39. public bool IsSessionActive
  40. {
  41. get
  42. {
  43. return _device != null;
  44. }
  45. }
  46. public void OnActivity()
  47. {
  48. }
  49. public bool SupportsMediaControl
  50. {
  51. get { return IsSessionActive; }
  52. }
  53. private Timer _updateTimer;
  54. public PlayToController(SessionInfo session, ISessionManager sessionManager, ILibraryManager libraryManager, ILogger logger, IDlnaManager dlnaManager, IUserManager userManager, IImageProcessor imageProcessor, string serverAddress, string accessToken, DeviceDiscovery deviceDiscovery, IUserDataManager userDataManager, ILocalizationManager localization, IMediaSourceManager mediaSourceManager)
  55. {
  56. _session = session;
  57. _sessionManager = sessionManager;
  58. _libraryManager = libraryManager;
  59. _dlnaManager = dlnaManager;
  60. _userManager = userManager;
  61. _imageProcessor = imageProcessor;
  62. _serverAddress = serverAddress;
  63. _deviceDiscovery = deviceDiscovery;
  64. _userDataManager = userDataManager;
  65. _localization = localization;
  66. _mediaSourceManager = mediaSourceManager;
  67. _accessToken = accessToken;
  68. _logger = logger;
  69. }
  70. public void Init(Device device)
  71. {
  72. _device = device;
  73. _device.PlaybackStart += _device_PlaybackStart;
  74. _device.PlaybackProgress += _device_PlaybackProgress;
  75. _device.PlaybackStopped += _device_PlaybackStopped;
  76. _device.MediaChanged += _device_MediaChanged;
  77. _device.Start();
  78. _deviceDiscovery.DeviceLeft += _deviceDiscovery_DeviceLeft;
  79. _updateTimer = new Timer(updateTimer_Elapsed, null, 60000, 60000);
  80. }
  81. void _deviceDiscovery_DeviceLeft(object sender, SsdpMessageEventArgs e)
  82. {
  83. string nts;
  84. e.Headers.TryGetValue("NTS", out nts);
  85. string usn;
  86. if (!e.Headers.TryGetValue("USN", out usn)) usn = String.Empty;
  87. string nt;
  88. if (!e.Headers.TryGetValue("NT", out nt)) nt = String.Empty;
  89. if ( usn.IndexOf(_device.Properties.UUID, StringComparison.OrdinalIgnoreCase) != -1 &&
  90. !_disposed)
  91. {
  92. if (usn.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) != -1 ||
  93. nt.IndexOf("MediaRenderer:", StringComparison.OrdinalIgnoreCase) != -1)
  94. {
  95. try
  96. {
  97. _sessionManager.ReportSessionEnded(_session.Id);
  98. }
  99. catch
  100. {
  101. // Could throw if the session is already gone
  102. }
  103. }
  104. }
  105. }
  106. private void updateTimer_Elapsed(object state)
  107. {
  108. if (DateTime.UtcNow >= _device.DateLastActivity.AddSeconds(120))
  109. {
  110. try
  111. {
  112. // Session is inactive, mark it for Disposal and don't start the elapsed timer.
  113. _sessionManager.ReportSessionEnded(_session.Id);
  114. }
  115. catch (Exception ex)
  116. {
  117. _logger.ErrorException("Error in ReportSessionEnded", ex);
  118. }
  119. }
  120. }
  121. async void _device_MediaChanged(object sender, MediaChangedEventArgs e)
  122. {
  123. try
  124. {
  125. var streamInfo = StreamParams.ParseFromUrl(e.OldMediaInfo.Url, _libraryManager, _mediaSourceManager);
  126. if (streamInfo.Item != null)
  127. {
  128. var progress = GetProgressInfo(e.OldMediaInfo, streamInfo);
  129. var positionTicks = progress.PositionTicks;
  130. ReportPlaybackStopped(e.OldMediaInfo, streamInfo, positionTicks);
  131. }
  132. streamInfo = StreamParams.ParseFromUrl(e.NewMediaInfo.Url, _libraryManager, _mediaSourceManager);
  133. if (streamInfo.Item == null) return;
  134. var newItemProgress = GetProgressInfo(e.NewMediaInfo, streamInfo);
  135. await _sessionManager.OnPlaybackStart(newItemProgress).ConfigureAwait(false);
  136. }
  137. catch (Exception ex)
  138. {
  139. _logger.ErrorException("Error reporting progress", ex);
  140. }
  141. }
  142. async void _device_PlaybackStopped(object sender, PlaybackStoppedEventArgs e)
  143. {
  144. try
  145. {
  146. var streamInfo = StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager);
  147. if (streamInfo.Item == null) return;
  148. var progress = GetProgressInfo(e.MediaInfo, streamInfo);
  149. var positionTicks = progress.PositionTicks;
  150. ReportPlaybackStopped(e.MediaInfo, streamInfo, positionTicks);
  151. var duration = streamInfo.MediaSource == null ?
  152. (_device.Duration == null ? (long?)null : _device.Duration.Value.Ticks) :
  153. streamInfo.MediaSource.RunTimeTicks;
  154. var playedToCompletion = (positionTicks.HasValue && positionTicks.Value == 0);
  155. if (!playedToCompletion && duration.HasValue && positionTicks.HasValue)
  156. {
  157. double percent = positionTicks.Value;
  158. percent /= duration.Value;
  159. playedToCompletion = Math.Abs(1 - percent) <= .1;
  160. }
  161. if (playedToCompletion)
  162. {
  163. await SetPlaylistIndex(_currentPlaylistIndex + 1).ConfigureAwait(false);
  164. }
  165. else
  166. {
  167. Playlist.Clear();
  168. }
  169. }
  170. catch (Exception ex)
  171. {
  172. _logger.ErrorException("Error reporting playback stopped", ex);
  173. }
  174. }
  175. private async void ReportPlaybackStopped(uBaseObject mediaInfo, StreamParams streamInfo, long? positionTicks)
  176. {
  177. try
  178. {
  179. await _sessionManager.OnPlaybackStopped(new PlaybackStopInfo
  180. {
  181. ItemId = mediaInfo.Id,
  182. SessionId = _session.Id,
  183. PositionTicks = positionTicks,
  184. MediaSourceId = streamInfo.MediaSourceId
  185. }).ConfigureAwait(false);
  186. }
  187. catch (Exception ex)
  188. {
  189. _logger.ErrorException("Error reporting progress", ex);
  190. }
  191. }
  192. async void _device_PlaybackStart(object sender, PlaybackStartEventArgs e)
  193. {
  194. try
  195. {
  196. var info = StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager);
  197. if (info.Item != null)
  198. {
  199. var progress = GetProgressInfo(e.MediaInfo, info);
  200. await _sessionManager.OnPlaybackStart(progress).ConfigureAwait(false);
  201. }
  202. }
  203. catch (Exception ex)
  204. {
  205. _logger.ErrorException("Error reporting progress", ex);
  206. }
  207. }
  208. async void _device_PlaybackProgress(object sender, PlaybackProgressEventArgs e)
  209. {
  210. try
  211. {
  212. var info = StreamParams.ParseFromUrl(e.MediaInfo.Url, _libraryManager, _mediaSourceManager);
  213. if (info.Item != null)
  214. {
  215. var progress = GetProgressInfo(e.MediaInfo, info);
  216. await _sessionManager.OnPlaybackProgress(progress).ConfigureAwait(false);
  217. }
  218. }
  219. catch (Exception ex)
  220. {
  221. _logger.ErrorException("Error reporting progress", ex);
  222. }
  223. }
  224. private PlaybackStartInfo GetProgressInfo(uBaseObject mediaInfo, StreamParams info)
  225. {
  226. var ticks = _device.Position.Ticks;
  227. if (!info.IsDirectStream)
  228. {
  229. ticks += info.StartPositionTicks;
  230. }
  231. return new PlaybackStartInfo
  232. {
  233. ItemId = info.ItemId,
  234. SessionId = _session.Id,
  235. PositionTicks = ticks,
  236. IsMuted = _device.IsMuted,
  237. IsPaused = _device.IsPaused,
  238. MediaSourceId = info.MediaSourceId,
  239. AudioStreamIndex = info.AudioStreamIndex,
  240. SubtitleStreamIndex = info.SubtitleStreamIndex,
  241. VolumeLevel = _device.Volume,
  242. CanSeek = info.MediaSource == null ? _device.Duration.HasValue : info.MediaSource.RunTimeTicks.HasValue,
  243. PlayMethod = info.IsDirectStream ? PlayMethod.DirectStream : PlayMethod.Transcode,
  244. QueueableMediaTypes = new List<string> { mediaInfo.MediaType }
  245. };
  246. }
  247. #region SendCommands
  248. public async Task SendPlayCommand(PlayRequest command, CancellationToken cancellationToken)
  249. {
  250. _logger.Debug("{0} - Received PlayRequest: {1}", this._session.DeviceName, command.PlayCommand);
  251. var user = String.IsNullOrEmpty(command.ControllingUserId) ? null : _userManager.GetUserById(command.ControllingUserId);
  252. var items = new List<BaseItem>();
  253. foreach (string id in command.ItemIds)
  254. {
  255. AddItemFromId(Guid.Parse(id), items);
  256. }
  257. var playlist = new List<PlaylistItem>();
  258. var isFirst = true;
  259. foreach (var item in items)
  260. {
  261. if (isFirst && command.StartPositionTicks.HasValue)
  262. {
  263. playlist.Add(CreatePlaylistItem(item, user, command.StartPositionTicks.Value, null, null, null));
  264. isFirst = false;
  265. }
  266. else
  267. {
  268. playlist.Add(CreatePlaylistItem(item, user, 0, null, null, null));
  269. }
  270. }
  271. _logger.Debug("{0} - Playlist created", _session.DeviceName);
  272. if (command.PlayCommand == PlayCommand.PlayLast)
  273. {
  274. Playlist.AddRange(playlist);
  275. }
  276. if (command.PlayCommand == PlayCommand.PlayNext)
  277. {
  278. Playlist.AddRange(playlist);
  279. }
  280. if (!String.IsNullOrWhiteSpace(command.ControllingUserId))
  281. {
  282. await _sessionManager.LogSessionActivity(_session.Client, _session.ApplicationVersion, _session.DeviceId,
  283. _session.DeviceName, _session.RemoteEndPoint, user).ConfigureAwait(false);
  284. }
  285. await PlayItems(playlist).ConfigureAwait(false);
  286. }
  287. public Task SendPlaystateCommand(PlaystateRequest command, CancellationToken cancellationToken)
  288. {
  289. switch (command.Command)
  290. {
  291. case PlaystateCommand.Stop:
  292. Playlist.Clear();
  293. return _device.SetStop();
  294. case PlaystateCommand.Pause:
  295. return _device.SetPause();
  296. case PlaystateCommand.Unpause:
  297. return _device.SetPlay();
  298. case PlaystateCommand.Seek:
  299. {
  300. return Seek(command.SeekPositionTicks ?? 0);
  301. }
  302. case PlaystateCommand.NextTrack:
  303. return SetPlaylistIndex(_currentPlaylistIndex + 1);
  304. case PlaystateCommand.PreviousTrack:
  305. return SetPlaylistIndex(_currentPlaylistIndex - 1);
  306. }
  307. return Task.FromResult(true);
  308. }
  309. private async Task Seek(long newPosition)
  310. {
  311. var media = _device.CurrentMediaInfo;
  312. if (media != null)
  313. {
  314. var info = StreamParams.ParseFromUrl(media.Url, _libraryManager, _mediaSourceManager);
  315. if (info.Item != null && !info.IsDirectStream)
  316. {
  317. var user = _session.UserId.HasValue ? _userManager.GetUserById(_session.UserId.Value) : null;
  318. var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, info.AudioStreamIndex, info.SubtitleStreamIndex);
  319. await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl).ConfigureAwait(false);
  320. if (newItem.StreamInfo.IsDirectStream)
  321. {
  322. await _device.Seek(TimeSpan.FromTicks(newPosition)).ConfigureAwait(false);
  323. }
  324. return;
  325. }
  326. await _device.Seek(TimeSpan.FromTicks(newPosition)).ConfigureAwait(false);
  327. }
  328. }
  329. public Task SendUserDataChangeInfo(UserDataChangeInfo info, CancellationToken cancellationToken)
  330. {
  331. return Task.FromResult(true);
  332. }
  333. public Task SendRestartRequiredNotification(SystemInfo info, CancellationToken cancellationToken)
  334. {
  335. return Task.FromResult(true);
  336. }
  337. public Task SendServerRestartNotification(CancellationToken cancellationToken)
  338. {
  339. return Task.FromResult(true);
  340. }
  341. public Task SendSessionEndedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
  342. {
  343. return Task.FromResult(true);
  344. }
  345. public Task SendPlaybackStartNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
  346. {
  347. return Task.FromResult(true);
  348. }
  349. public Task SendPlaybackStoppedNotification(SessionInfoDto sessionInfo, CancellationToken cancellationToken)
  350. {
  351. return Task.FromResult(true);
  352. }
  353. public Task SendServerShutdownNotification(CancellationToken cancellationToken)
  354. {
  355. return Task.FromResult(true);
  356. }
  357. public Task SendLibraryUpdateInfo(LibraryUpdateInfo info, CancellationToken cancellationToken)
  358. {
  359. return Task.FromResult(true);
  360. }
  361. #endregion
  362. #region Playlist
  363. private int _currentPlaylistIndex;
  364. private readonly List<PlaylistItem> _playlist = new List<PlaylistItem>();
  365. private List<PlaylistItem> Playlist
  366. {
  367. get
  368. {
  369. return _playlist;
  370. }
  371. }
  372. private void AddItemFromId(Guid id, List<BaseItem> list)
  373. {
  374. var item = _libraryManager.GetItemById(id);
  375. if (item.MediaType == MediaType.Audio || item.MediaType == MediaType.Video)
  376. {
  377. list.Add(item);
  378. }
  379. }
  380. private PlaylistItem CreatePlaylistItem(BaseItem item, User user, long startPostionTicks, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex)
  381. {
  382. var deviceInfo = _device.Properties;
  383. var profile = _dlnaManager.GetProfile(deviceInfo.ToDeviceIdentification()) ??
  384. _dlnaManager.GetDefaultProfile();
  385. var hasMediaSources = item as IHasMediaSources;
  386. var mediaSources = hasMediaSources != null
  387. ? (_mediaSourceManager.GetStaticMediaSources(hasMediaSources, true, user)).ToList()
  388. : new List<MediaSourceInfo>();
  389. var playlistItem = GetPlaylistItem(item, mediaSources, profile, _session.DeviceId, mediaSourceId, audioStreamIndex, subtitleStreamIndex);
  390. playlistItem.StreamInfo.StartPositionTicks = startPostionTicks;
  391. playlistItem.StreamUrl = playlistItem.StreamInfo.ToDlnaUrl(_serverAddress, _accessToken);
  392. var itemXml = new DidlBuilder(profile, user, _imageProcessor, _serverAddress, _accessToken, _userDataManager, _localization, _mediaSourceManager, _logger)
  393. .GetItemDidl(item, null, _session.DeviceId, new Filter(), playlistItem.StreamInfo);
  394. playlistItem.Didl = itemXml;
  395. return playlistItem;
  396. }
  397. private string GetDlnaHeaders(PlaylistItem item)
  398. {
  399. var profile = item.Profile;
  400. var streamInfo = item.StreamInfo;
  401. if (streamInfo.MediaType == DlnaProfileType.Audio)
  402. {
  403. return new ContentFeatureBuilder(profile)
  404. .BuildAudioHeader(streamInfo.Container,
  405. streamInfo.AudioCodec,
  406. streamInfo.TargetAudioBitrate,
  407. streamInfo.TargetAudioSampleRate,
  408. streamInfo.TargetAudioChannels,
  409. streamInfo.IsDirectStream,
  410. streamInfo.RunTimeTicks,
  411. streamInfo.TranscodeSeekInfo);
  412. }
  413. if (streamInfo.MediaType == DlnaProfileType.Video)
  414. {
  415. var list = new ContentFeatureBuilder(profile)
  416. .BuildVideoHeader(streamInfo.Container,
  417. streamInfo.VideoCodec,
  418. streamInfo.AudioCodec,
  419. streamInfo.TargetWidth,
  420. streamInfo.TargetHeight,
  421. streamInfo.TargetVideoBitDepth,
  422. streamInfo.TargetVideoBitrate,
  423. streamInfo.TargetTimestamp,
  424. streamInfo.IsDirectStream,
  425. streamInfo.RunTimeTicks,
  426. streamInfo.TargetVideoProfile,
  427. streamInfo.TargetVideoLevel,
  428. streamInfo.TargetFramerate,
  429. streamInfo.TargetPacketLength,
  430. streamInfo.TranscodeSeekInfo,
  431. streamInfo.IsTargetAnamorphic,
  432. streamInfo.IsTargetCabac,
  433. streamInfo.TargetRefFrames,
  434. streamInfo.TargetVideoStreamCount,
  435. streamInfo.TargetAudioStreamCount);
  436. return list.FirstOrDefault();
  437. }
  438. return null;
  439. }
  440. private PlaylistItem GetPlaylistItem(BaseItem item, List<MediaSourceInfo> mediaSources, DeviceProfile profile, string deviceId, string mediaSourceId, int? audioStreamIndex, int? subtitleStreamIndex)
  441. {
  442. if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  443. {
  444. return new PlaylistItem
  445. {
  446. StreamInfo = new StreamBuilder(_logger).BuildVideoItem(new VideoOptions
  447. {
  448. ItemId = item.Id.ToString("N"),
  449. MediaSources = mediaSources,
  450. Profile = profile,
  451. DeviceId = deviceId,
  452. MaxBitrate = profile.MaxStreamingBitrate,
  453. MediaSourceId = mediaSourceId,
  454. AudioStreamIndex = audioStreamIndex,
  455. SubtitleStreamIndex = subtitleStreamIndex
  456. }),
  457. Profile = profile
  458. };
  459. }
  460. if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  461. {
  462. return new PlaylistItem
  463. {
  464. StreamInfo = new StreamBuilder(_logger).BuildAudioItem(new AudioOptions
  465. {
  466. ItemId = item.Id.ToString("N"),
  467. MediaSources = mediaSources,
  468. Profile = profile,
  469. DeviceId = deviceId,
  470. MaxBitrate = profile.MaxStreamingBitrate,
  471. MediaSourceId = mediaSourceId
  472. }),
  473. Profile = profile
  474. };
  475. }
  476. if (string.Equals(item.MediaType, MediaType.Photo, StringComparison.OrdinalIgnoreCase))
  477. {
  478. return new PlaylistItemFactory().Create((Photo)item, profile);
  479. }
  480. throw new ArgumentException("Unrecognized item type.");
  481. }
  482. /// <summary>
  483. /// Plays the items.
  484. /// </summary>
  485. /// <param name="items">The items.</param>
  486. /// <returns></returns>
  487. private async Task<bool> PlayItems(IEnumerable<PlaylistItem> items)
  488. {
  489. Playlist.Clear();
  490. Playlist.AddRange(items);
  491. _logger.Debug("{0} - Playing {1} items", _session.DeviceName, Playlist.Count);
  492. await SetPlaylistIndex(0).ConfigureAwait(false);
  493. return true;
  494. }
  495. private async Task SetPlaylistIndex(int index)
  496. {
  497. if (index < 0 || index >= Playlist.Count)
  498. {
  499. Playlist.Clear();
  500. await _device.SetStop();
  501. return;
  502. }
  503. _currentPlaylistIndex = index;
  504. var currentitem = Playlist[index];
  505. await _device.SetAvTransport(currentitem.StreamUrl, GetDlnaHeaders(currentitem), currentitem.Didl);
  506. var streamInfo = currentitem.StreamInfo;
  507. if (streamInfo.StartPositionTicks > 0 && streamInfo.IsDirectStream)
  508. await _device.Seek(TimeSpan.FromTicks(streamInfo.StartPositionTicks));
  509. }
  510. #endregion
  511. private bool _disposed;
  512. public void Dispose()
  513. {
  514. if (!_disposed)
  515. {
  516. _disposed = true;
  517. _device.PlaybackStart -= _device_PlaybackStart;
  518. _device.PlaybackProgress -= _device_PlaybackProgress;
  519. _device.PlaybackStopped -= _device_PlaybackStopped;
  520. _device.MediaChanged -= _device_MediaChanged;
  521. _deviceDiscovery.DeviceLeft -= _deviceDiscovery_DeviceLeft;
  522. DisposeUpdateTimer();
  523. _device.Dispose();
  524. }
  525. }
  526. private void DisposeUpdateTimer()
  527. {
  528. if (_updateTimer != null)
  529. {
  530. _updateTimer.Dispose();
  531. _updateTimer = null;
  532. }
  533. }
  534. private readonly CultureInfo _usCulture = new CultureInfo("en-US");
  535. public Task SendGeneralCommand(GeneralCommand command, CancellationToken cancellationToken)
  536. {
  537. GeneralCommandType commandType;
  538. if (Enum.TryParse(command.Name, true, out commandType))
  539. {
  540. switch (commandType)
  541. {
  542. case GeneralCommandType.VolumeDown:
  543. return _device.VolumeDown();
  544. case GeneralCommandType.VolumeUp:
  545. return _device.VolumeUp();
  546. case GeneralCommandType.Mute:
  547. return _device.Mute();
  548. case GeneralCommandType.Unmute:
  549. return _device.Unmute();
  550. case GeneralCommandType.ToggleMute:
  551. return _device.ToggleMute();
  552. case GeneralCommandType.SetAudioStreamIndex:
  553. {
  554. string arg;
  555. if (command.Arguments.TryGetValue("Index", out arg))
  556. {
  557. int val;
  558. if (Int32.TryParse(arg, NumberStyles.Any, _usCulture, out val))
  559. {
  560. return SetAudioStreamIndex(val);
  561. }
  562. throw new ArgumentException("Unsupported SetAudioStreamIndex value supplied.");
  563. }
  564. throw new ArgumentException("SetAudioStreamIndex argument cannot be null");
  565. }
  566. case GeneralCommandType.SetSubtitleStreamIndex:
  567. {
  568. string arg;
  569. if (command.Arguments.TryGetValue("Index", out arg))
  570. {
  571. int val;
  572. if (Int32.TryParse(arg, NumberStyles.Any, _usCulture, out val))
  573. {
  574. return SetSubtitleStreamIndex(val);
  575. }
  576. throw new ArgumentException("Unsupported SetSubtitleStreamIndex value supplied.");
  577. }
  578. throw new ArgumentException("SetSubtitleStreamIndex argument cannot be null");
  579. }
  580. case GeneralCommandType.SetVolume:
  581. {
  582. string arg;
  583. if (command.Arguments.TryGetValue("Volume", out arg))
  584. {
  585. int volume;
  586. if (Int32.TryParse(arg, NumberStyles.Any, _usCulture, out volume))
  587. {
  588. return _device.SetVolume(volume);
  589. }
  590. throw new ArgumentException("Unsupported volume value supplied.");
  591. }
  592. throw new ArgumentException("Volume argument cannot be null");
  593. }
  594. default:
  595. return Task.FromResult(true);
  596. }
  597. }
  598. return Task.FromResult(true);
  599. }
  600. private async Task SetAudioStreamIndex(int? newIndex)
  601. {
  602. var media = _device.CurrentMediaInfo;
  603. if (media != null)
  604. {
  605. var info = StreamParams.ParseFromUrl(media.Url, _libraryManager, _mediaSourceManager);
  606. if (info.Item != null)
  607. {
  608. var progress = GetProgressInfo(media, info);
  609. var newPosition = progress.PositionTicks ?? 0;
  610. var user = _session.UserId.HasValue ? _userManager.GetUserById(_session.UserId.Value) : null;
  611. var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, newIndex, info.SubtitleStreamIndex);
  612. await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl).ConfigureAwait(false);
  613. if (newItem.StreamInfo.IsDirectStream)
  614. {
  615. await _device.Seek(TimeSpan.FromTicks(newPosition)).ConfigureAwait(false);
  616. }
  617. }
  618. }
  619. }
  620. private async Task SetSubtitleStreamIndex(int? newIndex)
  621. {
  622. var media = _device.CurrentMediaInfo;
  623. if (media != null)
  624. {
  625. var info = StreamParams.ParseFromUrl(media.Url, _libraryManager, _mediaSourceManager);
  626. if (info.Item != null)
  627. {
  628. var progress = GetProgressInfo(media, info);
  629. var newPosition = progress.PositionTicks ?? 0;
  630. var user = _session.UserId.HasValue ? _userManager.GetUserById(_session.UserId.Value) : null;
  631. var newItem = CreatePlaylistItem(info.Item, user, newPosition, info.MediaSourceId, info.AudioStreamIndex, newIndex);
  632. await _device.SetAvTransport(newItem.StreamUrl, GetDlnaHeaders(newItem), newItem.Didl).ConfigureAwait(false);
  633. if (newItem.StreamInfo.IsDirectStream && newPosition > 0)
  634. {
  635. // This is rather arbitrary, but give the player time to start playing
  636. await Task.Delay(2000).ConfigureAwait(false);
  637. await _device.Seek(TimeSpan.FromTicks(newPosition)).ConfigureAwait(false);
  638. }
  639. }
  640. }
  641. }
  642. private class StreamParams
  643. {
  644. public string ItemId { get; set; }
  645. public bool IsDirectStream { get; set; }
  646. public long StartPositionTicks { get; set; }
  647. public int? AudioStreamIndex { get; set; }
  648. public int? SubtitleStreamIndex { get; set; }
  649. public string DeviceProfileId { get; set; }
  650. public string DeviceId { get; set; }
  651. public string MediaSourceId { get; set; }
  652. public BaseItem Item { get; set; }
  653. public MediaSourceInfo MediaSource { get; set; }
  654. private static string GetItemId(string url)
  655. {
  656. var parts = url.Split('/');
  657. for (var i = 0; i < parts.Length; i++)
  658. {
  659. var part = parts[i];
  660. if (string.Equals(part, "audio", StringComparison.OrdinalIgnoreCase) ||
  661. string.Equals(part, "videos", StringComparison.OrdinalIgnoreCase))
  662. {
  663. if (parts.Length > i + 1)
  664. {
  665. return parts[i + 1];
  666. }
  667. }
  668. }
  669. return null;
  670. }
  671. public static StreamParams ParseFromUrl(string url, ILibraryManager libraryManager, IMediaSourceManager mediaSourceManager)
  672. {
  673. var request = new StreamParams
  674. {
  675. ItemId = GetItemId(url)
  676. };
  677. Guid parsedId;
  678. if (string.IsNullOrWhiteSpace(request.ItemId) || !Guid.TryParse(request.ItemId, out parsedId))
  679. {
  680. return request;
  681. }
  682. const string srch = "params=";
  683. var index = url.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
  684. if (index == -1) return request;
  685. var vals = url.Substring(index + srch.Length).Split(';');
  686. for (var i = 0; i < vals.Length; i++)
  687. {
  688. var val = vals[i];
  689. if (string.IsNullOrWhiteSpace(val))
  690. {
  691. continue;
  692. }
  693. if (i == 0)
  694. {
  695. request.DeviceProfileId = val;
  696. }
  697. else if (i == 1)
  698. {
  699. request.DeviceId = val;
  700. }
  701. else if (i == 2)
  702. {
  703. request.MediaSourceId = val;
  704. }
  705. else if (i == 3)
  706. {
  707. request.IsDirectStream = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
  708. }
  709. else if (i == 6)
  710. {
  711. request.AudioStreamIndex = int.Parse(val, CultureInfo.InvariantCulture);
  712. }
  713. else if (i == 7)
  714. {
  715. request.SubtitleStreamIndex = int.Parse(val, CultureInfo.InvariantCulture);
  716. }
  717. else if (i == 14)
  718. {
  719. request.StartPositionTicks = long.Parse(val, CultureInfo.InvariantCulture);
  720. }
  721. }
  722. request.Item = string.IsNullOrWhiteSpace(request.ItemId)
  723. ? null
  724. : libraryManager.GetItemById(parsedId);
  725. var hasMediaSources = request.Item as IHasMediaSources;
  726. request.MediaSource = hasMediaSources == null ?
  727. null :
  728. mediaSourceManager.GetMediaSource(hasMediaSources, request.MediaSourceId, false).Result;
  729. return request;
  730. }
  731. }
  732. public Task SendMessage<T>(string name, T data, CancellationToken cancellationToken)
  733. {
  734. // Not supported or needed right now
  735. return Task.FromResult(true);
  736. }
  737. }
  738. }