MediaSourceManager.cs 18 KB

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