MediaSourceManager.cs 19 KB

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