2
0

MediaSourceManager.cs 21 KB

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