MediaSourceManager.cs 19 KB

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