MediaSourceManager.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Library;
  4. using MediaBrowser.Controller.MediaEncoding;
  5. using MediaBrowser.Controller.Persistence;
  6. using MediaBrowser.Model.Dto;
  7. using MediaBrowser.Model.Entities;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.MediaInfo;
  10. using MediaBrowser.Model.Serialization;
  11. using System;
  12. using System.Collections.Concurrent;
  13. using System.Collections.Generic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Threading;
  17. using System.Threading.Tasks;
  18. using CommonIO;
  19. using MediaBrowser.Common.IO;
  20. namespace MediaBrowser.Server.Implementations.Library
  21. {
  22. public class MediaSourceManager : IMediaSourceManager, IDisposable
  23. {
  24. private readonly IItemRepository _itemRepo;
  25. private readonly IUserManager _userManager;
  26. private readonly ILibraryManager _libraryManager;
  27. private readonly IJsonSerializer _jsonSerializer;
  28. private readonly IFileSystem _fileSystem;
  29. private IMediaSourceProvider[] _providers;
  30. private readonly ILogger _logger;
  31. private readonly IUserDataManager _userDataManager;
  32. public MediaSourceManager(IItemRepository itemRepo, IUserManager userManager, ILibraryManager libraryManager, ILogger logger, IJsonSerializer jsonSerializer, IFileSystem fileSystem, IUserDataManager userDataManager)
  33. {
  34. _itemRepo = itemRepo;
  35. _userManager = userManager;
  36. _libraryManager = libraryManager;
  37. _logger = logger;
  38. _jsonSerializer = jsonSerializer;
  39. _fileSystem = fileSystem;
  40. _userDataManager = userDataManager;
  41. }
  42. public void AddParts(IEnumerable<IMediaSourceProvider> providers)
  43. {
  44. _providers = providers.ToArray();
  45. }
  46. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  47. {
  48. var list = _itemRepo.GetMediaStreams(query)
  49. .ToList();
  50. foreach (var stream in list)
  51. {
  52. stream.SupportsExternalStream = StreamSupportsExternalStream(stream);
  53. }
  54. return list;
  55. }
  56. private bool StreamSupportsExternalStream(MediaStream stream)
  57. {
  58. if (stream.IsExternal)
  59. {
  60. return true;
  61. }
  62. if (stream.IsTextSubtitleStream)
  63. {
  64. if (string.Equals(stream.Codec, "ass", StringComparison.OrdinalIgnoreCase))
  65. {
  66. return false;
  67. }
  68. return true;
  69. }
  70. return false;
  71. }
  72. public IEnumerable<MediaStream> GetMediaStreams(string mediaSourceId)
  73. {
  74. var list = GetMediaStreams(new MediaStreamQuery
  75. {
  76. ItemId = new Guid(mediaSourceId)
  77. });
  78. return GetMediaStreamsForItem(list);
  79. }
  80. public IEnumerable<MediaStream> GetMediaStreams(Guid itemId)
  81. {
  82. var list = GetMediaStreams(new MediaStreamQuery
  83. {
  84. ItemId = itemId
  85. });
  86. return GetMediaStreamsForItem(list);
  87. }
  88. private IEnumerable<MediaStream> GetMediaStreamsForItem(IEnumerable<MediaStream> streams)
  89. {
  90. var list = streams.ToList();
  91. var subtitleStreams = list
  92. .Where(i => i.Type == MediaStreamType.Subtitle)
  93. .ToList();
  94. if (subtitleStreams.Count > 0)
  95. {
  96. foreach (var subStream in subtitleStreams)
  97. {
  98. subStream.SupportsExternalStream = StreamSupportsExternalStream(subStream);
  99. }
  100. }
  101. return list;
  102. }
  103. public async Task<IEnumerable<MediaSourceInfo>> GetPlayackMediaSources(string id, string userId, bool enablePathSubstitution, string[] supportedLiveMediaTypes, CancellationToken cancellationToken)
  104. {
  105. var item = _libraryManager.GetItemById(id);
  106. var hasMediaSources = (IHasMediaSources)item;
  107. User user = null;
  108. if (!string.IsNullOrWhiteSpace(userId))
  109. {
  110. user = _userManager.GetUserById(userId);
  111. }
  112. var mediaSources = GetStaticMediaSources(hasMediaSources, enablePathSubstitution, user);
  113. var dynamicMediaSources = await GetDynamicMediaSources(hasMediaSources, cancellationToken).ConfigureAwait(false);
  114. var list = new List<MediaSourceInfo>();
  115. list.AddRange(mediaSources);
  116. foreach (var source in dynamicMediaSources)
  117. {
  118. if (user != null)
  119. {
  120. SetUserProperties(hasMediaSources, source, user);
  121. }
  122. if (source.Protocol == MediaProtocol.File)
  123. {
  124. // TODO: Path substitution
  125. if (!_fileSystem.FileExists(source.Path))
  126. {
  127. source.SupportsDirectStream = false;
  128. }
  129. }
  130. else if (source.Protocol == MediaProtocol.Http)
  131. {
  132. // TODO: Allow this when the source is plain http, e.g. not HLS or Mpeg Dash
  133. source.SupportsDirectStream = false;
  134. }
  135. else
  136. {
  137. source.SupportsDirectStream = false;
  138. }
  139. list.Add(source);
  140. }
  141. foreach (var source in list)
  142. {
  143. if (user != null)
  144. {
  145. if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  146. {
  147. if (!user.Policy.EnableAudioPlaybackTranscoding)
  148. {
  149. source.SupportsTranscoding = false;
  150. }
  151. }
  152. else if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  153. {
  154. if (!user.Policy.EnableVideoPlaybackTranscoding)
  155. {
  156. source.SupportsTranscoding = false;
  157. }
  158. }
  159. }
  160. }
  161. return SortMediaSources(list).Where(i => i.Type != MediaSourceType.Placeholder);
  162. }
  163. private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(IHasMediaSources item, CancellationToken cancellationToken)
  164. {
  165. var tasks = _providers.Select(i => GetDynamicMediaSources(item, i, cancellationToken));
  166. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  167. return results.SelectMany(i => i.ToList());
  168. }
  169. private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(IHasMediaSources item, IMediaSourceProvider provider, CancellationToken cancellationToken)
  170. {
  171. try
  172. {
  173. var sources = await provider.GetMediaSources(item, cancellationToken).ConfigureAwait(false);
  174. var list = sources.ToList();
  175. foreach (var mediaSource in list)
  176. {
  177. SetKeyProperties(provider, mediaSource);
  178. }
  179. return list;
  180. }
  181. catch (Exception ex)
  182. {
  183. _logger.ErrorException("Error getting media sources", ex);
  184. return new List<MediaSourceInfo>();
  185. }
  186. }
  187. private void SetKeyProperties(IMediaSourceProvider provider, MediaSourceInfo mediaSource)
  188. {
  189. var prefix = provider.GetType().FullName.GetMD5().ToString("N") + LiveStreamIdDelimeter;
  190. if (!string.IsNullOrWhiteSpace(mediaSource.OpenToken) && !mediaSource.OpenToken.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
  191. {
  192. mediaSource.OpenToken = prefix + mediaSource.OpenToken;
  193. }
  194. if (!string.IsNullOrWhiteSpace(mediaSource.LiveStreamId) && !mediaSource.LiveStreamId.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
  195. {
  196. mediaSource.LiveStreamId = prefix + mediaSource.LiveStreamId;
  197. }
  198. }
  199. public async Task<MediaSourceInfo> GetMediaSource(IHasMediaSources item, string mediaSourceId, bool enablePathSubstitution)
  200. {
  201. var sources = await GetPlayackMediaSources(item.Id.ToString("N"), null, enablePathSubstitution, new[] { MediaType.Audio, MediaType.Video },
  202. CancellationToken.None).ConfigureAwait(false);
  203. return sources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  204. }
  205. public IEnumerable<MediaSourceInfo> GetStaticMediaSources(IHasMediaSources item, bool enablePathSubstitution, User user = null)
  206. {
  207. if (item == null)
  208. {
  209. throw new ArgumentNullException("item");
  210. }
  211. if (!(item is Video))
  212. {
  213. return item.GetMediaSources(enablePathSubstitution);
  214. }
  215. var sources = item.GetMediaSources(enablePathSubstitution).ToList();
  216. if (user != null)
  217. {
  218. foreach (var source in sources)
  219. {
  220. SetUserProperties(item, source, user);
  221. }
  222. }
  223. return sources;
  224. }
  225. private void SetUserProperties(IHasUserData item, MediaSourceInfo source, User user)
  226. {
  227. var userData = item == null ? new UserItemData() : _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
  228. SetDefaultAudioStreamIndex(source, userData, user);
  229. SetDefaultSubtitleStreamIndex(source, userData, user);
  230. }
  231. private void SetDefaultSubtitleStreamIndex(MediaSourceInfo source, UserItemData userData, User user)
  232. {
  233. if (userData.SubtitleStreamIndex.HasValue)
  234. {
  235. var index = userData.SubtitleStreamIndex.Value;
  236. // Make sure the saved index is still valid
  237. if (index == -1 || source.MediaStreams.Any(i => i.Type == MediaStreamType.Subtitle && i.Index == index))
  238. {
  239. source.DefaultSubtitleStreamIndex = index;
  240. return;
  241. }
  242. }
  243. var preferredSubs = string.IsNullOrEmpty(user.Configuration.SubtitleLanguagePreference)
  244. ? new List<string> { }
  245. : new List<string> { user.Configuration.SubtitleLanguagePreference };
  246. var defaultAudioIndex = source.DefaultAudioStreamIndex;
  247. var audioLangage = defaultAudioIndex == null
  248. ? null
  249. : source.MediaStreams.Where(i => i.Type == MediaStreamType.Audio && i.Index == defaultAudioIndex).Select(i => i.Language).FirstOrDefault();
  250. source.DefaultSubtitleStreamIndex = MediaStreamSelector.GetDefaultSubtitleStreamIndex(source.MediaStreams,
  251. preferredSubs,
  252. user.Configuration.SubtitleMode,
  253. audioLangage);
  254. MediaStreamSelector.SetSubtitleStreamScores(source.MediaStreams, preferredSubs,
  255. user.Configuration.SubtitleMode, audioLangage);
  256. }
  257. private void SetDefaultAudioStreamIndex(MediaSourceInfo source, UserItemData userData, User user)
  258. {
  259. if (userData.AudioStreamIndex.HasValue)
  260. {
  261. var index = userData.AudioStreamIndex.Value;
  262. // Make sure the saved index is still valid
  263. if (source.MediaStreams.Any(i => i.Type == MediaStreamType.Audio && i.Index == index))
  264. {
  265. source.DefaultAudioStreamIndex = index;
  266. return;
  267. }
  268. }
  269. var preferredAudio = string.IsNullOrEmpty(user.Configuration.AudioLanguagePreference)
  270. ? new string[] { }
  271. : new[] { user.Configuration.AudioLanguagePreference };
  272. source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferredAudio, user.Configuration.PlayDefaultAudioTrack);
  273. }
  274. private IEnumerable<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources)
  275. {
  276. return sources.OrderBy(i =>
  277. {
  278. if (i.VideoType.HasValue && i.VideoType.Value == VideoType.VideoFile)
  279. {
  280. return 0;
  281. }
  282. return 1;
  283. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  284. .ThenByDescending(i =>
  285. {
  286. var stream = i.VideoStream;
  287. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  288. })
  289. .ToList();
  290. }
  291. private readonly ConcurrentDictionary<string, LiveStreamInfo> _openStreams = new ConcurrentDictionary<string, LiveStreamInfo>(StringComparer.OrdinalIgnoreCase);
  292. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  293. public async Task<LiveStreamResponse> OpenLiveStream(LiveStreamRequest request, bool enableAutoClose, CancellationToken cancellationToken)
  294. {
  295. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  296. try
  297. {
  298. var tuple = GetProvider(request.OpenToken);
  299. var provider = tuple.Item1;
  300. var mediaSource = await provider.OpenMediaSource(tuple.Item2, cancellationToken).ConfigureAwait(false);
  301. if (string.IsNullOrWhiteSpace(mediaSource.LiveStreamId))
  302. {
  303. throw new InvalidOperationException(string.Format("{0} returned null LiveStreamId", provider.GetType().Name));
  304. }
  305. SetKeyProperties(provider, mediaSource);
  306. var info = new LiveStreamInfo
  307. {
  308. Date = DateTime.UtcNow,
  309. EnableCloseTimer = enableAutoClose,
  310. Id = mediaSource.LiveStreamId,
  311. MediaSource = mediaSource
  312. };
  313. _openStreams.AddOrUpdate(mediaSource.LiveStreamId, info, (key, i) => info);
  314. if (enableAutoClose)
  315. {
  316. StartCloseTimer();
  317. }
  318. var json = _jsonSerializer.SerializeToString(mediaSource);
  319. _logger.Debug("Live stream opened: " + json);
  320. var clone = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
  321. if (!string.IsNullOrWhiteSpace(request.UserId))
  322. {
  323. var user = _userManager.GetUserById(request.UserId);
  324. var item = string.IsNullOrWhiteSpace(request.ItemId)
  325. ? null
  326. : _libraryManager.GetItemById(request.ItemId);
  327. SetUserProperties(item, clone, user);
  328. }
  329. return new LiveStreamResponse
  330. {
  331. MediaSource = clone
  332. };
  333. }
  334. finally
  335. {
  336. _liveStreamSemaphore.Release();
  337. }
  338. }
  339. public async Task<MediaSourceInfo> GetLiveStream(string id, CancellationToken cancellationToken)
  340. {
  341. if (string.IsNullOrWhiteSpace(id))
  342. {
  343. throw new ArgumentNullException("id");
  344. }
  345. _logger.Debug("Getting live stream {0}", id);
  346. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  347. try
  348. {
  349. LiveStreamInfo info;
  350. if (_openStreams.TryGetValue(id, out info))
  351. {
  352. return info.MediaSource;
  353. }
  354. else
  355. {
  356. throw new ResourceNotFoundException();
  357. }
  358. }
  359. finally
  360. {
  361. _liveStreamSemaphore.Release();
  362. }
  363. }
  364. public async Task PingLiveStream(string id, CancellationToken cancellationToken)
  365. {
  366. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  367. try
  368. {
  369. LiveStreamInfo info;
  370. if (_openStreams.TryGetValue(id, out info))
  371. {
  372. info.Date = DateTime.UtcNow;
  373. }
  374. else
  375. {
  376. _logger.Error("Failed to update MediaSource timestamp for {0}", id);
  377. }
  378. }
  379. finally
  380. {
  381. _liveStreamSemaphore.Release();
  382. }
  383. }
  384. public async Task CloseLiveStream(string id, CancellationToken cancellationToken)
  385. {
  386. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  387. try
  388. {
  389. LiveStreamInfo current;
  390. if (_openStreams.TryGetValue(id, out current))
  391. {
  392. if (current.MediaSource.RequiresClosing)
  393. {
  394. var tuple = GetProvider(id);
  395. await tuple.Item1.CloseMediaSource(tuple.Item2, cancellationToken).ConfigureAwait(false);
  396. }
  397. }
  398. LiveStreamInfo removed;
  399. if (_openStreams.TryRemove(id, out removed))
  400. {
  401. removed.Closed = true;
  402. }
  403. if (_openStreams.Count == 0)
  404. {
  405. StopCloseTimer();
  406. }
  407. }
  408. finally
  409. {
  410. _liveStreamSemaphore.Release();
  411. }
  412. }
  413. // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message.
  414. private const char LiveStreamIdDelimeter = '_';
  415. private Tuple<IMediaSourceProvider, string> GetProvider(string key)
  416. {
  417. if (string.IsNullOrWhiteSpace(key))
  418. {
  419. throw new ArgumentException("key");
  420. }
  421. var keys = key.Split(new[] { LiveStreamIdDelimeter }, 2);
  422. var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N"), keys[0], StringComparison.OrdinalIgnoreCase));
  423. var splitIndex = key.IndexOf(LiveStreamIdDelimeter);
  424. var keyId = key.Substring(splitIndex + 1);
  425. return new Tuple<IMediaSourceProvider, string>(provider, keyId);
  426. }
  427. private Timer _closeTimer;
  428. private readonly TimeSpan _openStreamMaxAge = TimeSpan.FromSeconds(60);
  429. private void StartCloseTimer()
  430. {
  431. StopCloseTimer();
  432. _closeTimer = new Timer(CloseTimerCallback, null, _openStreamMaxAge, _openStreamMaxAge);
  433. }
  434. private void StopCloseTimer()
  435. {
  436. var timer = _closeTimer;
  437. if (timer != null)
  438. {
  439. _closeTimer = null;
  440. timer.Dispose();
  441. }
  442. }
  443. private async void CloseTimerCallback(object state)
  444. {
  445. var infos = _openStreams
  446. .Values
  447. .Where(i => i.EnableCloseTimer && (DateTime.UtcNow - i.Date) > _openStreamMaxAge)
  448. .ToList();
  449. foreach (var info in infos)
  450. {
  451. if (!info.Closed)
  452. {
  453. try
  454. {
  455. await CloseLiveStream(info.Id, CancellationToken.None).ConfigureAwait(false);
  456. }
  457. catch (Exception ex)
  458. {
  459. _logger.ErrorException("Error closing media source", ex);
  460. }
  461. }
  462. }
  463. }
  464. /// <summary>
  465. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  466. /// </summary>
  467. public void Dispose()
  468. {
  469. StopCloseTimer();
  470. Dispose(true);
  471. }
  472. private readonly object _disposeLock = new object();
  473. /// <summary>
  474. /// Releases unmanaged and - optionally - managed resources.
  475. /// </summary>
  476. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  477. protected virtual void Dispose(bool dispose)
  478. {
  479. if (dispose)
  480. {
  481. lock (_disposeLock)
  482. {
  483. foreach (var key in _openStreams.Keys.ToList())
  484. {
  485. var task = CloseLiveStream(key, CancellationToken.None);
  486. Task.WaitAll(task);
  487. }
  488. _openStreams.Clear();
  489. }
  490. }
  491. }
  492. private class LiveStreamInfo
  493. {
  494. public DateTime Date;
  495. public bool EnableCloseTimer;
  496. public string Id;
  497. public bool Closed;
  498. public MediaSourceInfo MediaSource;
  499. }
  500. }
  501. }