MediaSourceManager.cs 20 KB

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