MediaSourceManager.cs 19 KB

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