MediaSourceManager.cs 20 KB

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