MediaSourceManager.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using Jellyfin.Data.Entities;
  10. using Jellyfin.Data.Enums;
  11. using MediaBrowser.Common.Configuration;
  12. using MediaBrowser.Common.Extensions;
  13. using MediaBrowser.Controller.Entities;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.MediaEncoding;
  16. using MediaBrowser.Controller.Persistence;
  17. using MediaBrowser.Controller.Providers;
  18. using MediaBrowser.Model.Dlna;
  19. using MediaBrowser.Model.Dto;
  20. using MediaBrowser.Model.Entities;
  21. using MediaBrowser.Model.Globalization;
  22. using MediaBrowser.Model.IO;
  23. using MediaBrowser.Model.MediaInfo;
  24. using MediaBrowser.Model.Serialization;
  25. using Microsoft.Extensions.Logging;
  26. namespace Emby.Server.Implementations.Library
  27. {
  28. public class MediaSourceManager : IMediaSourceManager, IDisposable
  29. {
  30. // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message.
  31. private const char LiveStreamIdDelimeter = '_';
  32. private readonly IItemRepository _itemRepo;
  33. private readonly IUserManager _userManager;
  34. private readonly ILibraryManager _libraryManager;
  35. private readonly IJsonSerializer _jsonSerializer;
  36. private readonly IFileSystem _fileSystem;
  37. private readonly ILogger<MediaSourceManager> _logger;
  38. private readonly IUserDataManager _userDataManager;
  39. private readonly IMediaEncoder _mediaEncoder;
  40. private readonly ILocalizationManager _localizationManager;
  41. private readonly IApplicationPaths _appPaths;
  42. private readonly Dictionary<string, ILiveStream> _openStreams = new Dictionary<string, ILiveStream>(StringComparer.OrdinalIgnoreCase);
  43. private readonly SemaphoreSlim _liveStreamSemaphore = new SemaphoreSlim(1, 1);
  44. private readonly object _disposeLock = new object();
  45. private IMediaSourceProvider[] _providers;
  46. public MediaSourceManager(
  47. IItemRepository itemRepo,
  48. IApplicationPaths applicationPaths,
  49. ILocalizationManager localizationManager,
  50. IUserManager userManager,
  51. ILibraryManager libraryManager,
  52. ILogger<MediaSourceManager> logger,
  53. IJsonSerializer jsonSerializer,
  54. IFileSystem fileSystem,
  55. IUserDataManager userDataManager,
  56. IMediaEncoder mediaEncoder)
  57. {
  58. _itemRepo = itemRepo;
  59. _userManager = userManager;
  60. _libraryManager = libraryManager;
  61. _logger = logger;
  62. _jsonSerializer = jsonSerializer;
  63. _fileSystem = fileSystem;
  64. _userDataManager = userDataManager;
  65. _mediaEncoder = mediaEncoder;
  66. _localizationManager = localizationManager;
  67. _appPaths = applicationPaths;
  68. }
  69. public void AddParts(IEnumerable<IMediaSourceProvider> providers)
  70. {
  71. _providers = providers.ToArray();
  72. }
  73. public List<MediaStream> GetMediaStreams(MediaStreamQuery query)
  74. {
  75. var list = _itemRepo.GetMediaStreams(query);
  76. foreach (var stream in list)
  77. {
  78. stream.SupportsExternalStream = StreamSupportsExternalStream(stream);
  79. }
  80. return list;
  81. }
  82. private static bool StreamSupportsExternalStream(MediaStream stream)
  83. {
  84. if (stream.IsExternal)
  85. {
  86. return true;
  87. }
  88. if (stream.IsTextSubtitleStream)
  89. {
  90. return true;
  91. }
  92. return false;
  93. }
  94. public List<MediaStream> GetMediaStreams(string mediaSourceId)
  95. {
  96. var list = GetMediaStreams(new MediaStreamQuery
  97. {
  98. ItemId = new Guid(mediaSourceId)
  99. });
  100. return GetMediaStreamsForItem(list);
  101. }
  102. public List<MediaStream> GetMediaStreams(Guid itemId)
  103. {
  104. var list = GetMediaStreams(new MediaStreamQuery
  105. {
  106. ItemId = itemId
  107. });
  108. return GetMediaStreamsForItem(list);
  109. }
  110. private List<MediaStream> GetMediaStreamsForItem(List<MediaStream> streams)
  111. {
  112. foreach (var stream in streams)
  113. {
  114. if (stream.Type == MediaStreamType.Subtitle)
  115. {
  116. stream.SupportsExternalStream = StreamSupportsExternalStream(stream);
  117. }
  118. }
  119. return streams;
  120. }
  121. /// <inheritdoc />
  122. public List<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query)
  123. {
  124. return _itemRepo.GetMediaAttachments(query);
  125. }
  126. /// <inheritdoc />
  127. public List<MediaAttachment> GetMediaAttachments(Guid itemId)
  128. {
  129. return GetMediaAttachments(new MediaAttachmentQuery
  130. {
  131. ItemId = itemId
  132. });
  133. }
  134. public async Task<List<MediaSourceInfo>> GetPlaybackMediaSources(BaseItem item, User user, bool allowMediaProbe, bool enablePathSubstitution, CancellationToken cancellationToken)
  135. {
  136. var mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user);
  137. if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder && !mediaSources[0].MediaStreams.Any(i => i.Type == MediaStreamType.Audio || i.Type == MediaStreamType.Video))
  138. {
  139. await item.RefreshMetadata(
  140. new MetadataRefreshOptions(new DirectoryService(_fileSystem))
  141. {
  142. EnableRemoteContentProbe = true,
  143. MetadataRefreshMode = MetadataRefreshMode.FullRefresh
  144. },
  145. cancellationToken).ConfigureAwait(false);
  146. mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user);
  147. }
  148. var dynamicMediaSources = await GetDynamicMediaSources(item, cancellationToken).ConfigureAwait(false);
  149. var list = new List<MediaSourceInfo>();
  150. list.AddRange(mediaSources);
  151. foreach (var source in dynamicMediaSources)
  152. {
  153. if (user != null)
  154. {
  155. SetDefaultAudioAndSubtitleStreamIndexes(item, source, user);
  156. }
  157. // Validate that this is actually possible
  158. if (source.SupportsDirectStream)
  159. {
  160. source.SupportsDirectStream = SupportsDirectStream(source.Path, source.Protocol);
  161. }
  162. list.Add(source);
  163. }
  164. if (user != null)
  165. {
  166. foreach (var source in list)
  167. {
  168. if (string.Equals(item.MediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  169. {
  170. source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding);
  171. }
  172. }
  173. }
  174. return SortMediaSources(list).Where(i => i.Type != MediaSourceType.Placeholder).ToList();
  175. }
  176. public MediaProtocol GetPathProtocol(string path)
  177. {
  178. if (path.StartsWith("Rtsp", StringComparison.OrdinalIgnoreCase))
  179. {
  180. return MediaProtocol.Rtsp;
  181. }
  182. if (path.StartsWith("Rtmp", StringComparison.OrdinalIgnoreCase))
  183. {
  184. return MediaProtocol.Rtmp;
  185. }
  186. if (path.StartsWith("Http", StringComparison.OrdinalIgnoreCase))
  187. {
  188. return MediaProtocol.Http;
  189. }
  190. if (path.StartsWith("rtp", StringComparison.OrdinalIgnoreCase))
  191. {
  192. return MediaProtocol.Rtp;
  193. }
  194. if (path.StartsWith("ftp", StringComparison.OrdinalIgnoreCase))
  195. {
  196. return MediaProtocol.Ftp;
  197. }
  198. if (path.StartsWith("udp", StringComparison.OrdinalIgnoreCase))
  199. {
  200. return MediaProtocol.Udp;
  201. }
  202. return _fileSystem.IsPathFile(path) ? MediaProtocol.File : MediaProtocol.Http;
  203. }
  204. public bool SupportsDirectStream(string path, MediaProtocol protocol)
  205. {
  206. if (protocol == MediaProtocol.File)
  207. {
  208. return true;
  209. }
  210. if (protocol == MediaProtocol.Http)
  211. {
  212. if (path != null)
  213. {
  214. if (path.IndexOf(".m3u", StringComparison.OrdinalIgnoreCase) != -1)
  215. {
  216. return false;
  217. }
  218. return true;
  219. }
  220. }
  221. return false;
  222. }
  223. private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(BaseItem item, CancellationToken cancellationToken)
  224. {
  225. var tasks = _providers.Select(i => GetDynamicMediaSources(item, i, cancellationToken));
  226. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  227. return results.SelectMany(i => i.ToList());
  228. }
  229. private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(BaseItem item, IMediaSourceProvider provider, CancellationToken cancellationToken)
  230. {
  231. try
  232. {
  233. var sources = await provider.GetMediaSources(item, cancellationToken).ConfigureAwait(false);
  234. var list = sources.ToList();
  235. foreach (var mediaSource in list)
  236. {
  237. mediaSource.InferTotalBitrate();
  238. SetKeyProperties(provider, mediaSource);
  239. }
  240. return list;
  241. }
  242. catch (Exception ex)
  243. {
  244. _logger.LogError(ex, "Error getting media sources");
  245. return new List<MediaSourceInfo>();
  246. }
  247. }
  248. private static void SetKeyProperties(IMediaSourceProvider provider, MediaSourceInfo mediaSource)
  249. {
  250. var prefix = provider.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture) + LiveStreamIdDelimeter;
  251. if (!string.IsNullOrEmpty(mediaSource.OpenToken) && !mediaSource.OpenToken.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
  252. {
  253. mediaSource.OpenToken = prefix + mediaSource.OpenToken;
  254. }
  255. if (!string.IsNullOrEmpty(mediaSource.LiveStreamId) && !mediaSource.LiveStreamId.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
  256. {
  257. mediaSource.LiveStreamId = prefix + mediaSource.LiveStreamId;
  258. }
  259. }
  260. public async Task<MediaSourceInfo> GetMediaSource(BaseItem item, string mediaSourceId, string liveStreamId, bool enablePathSubstitution, CancellationToken cancellationToken)
  261. {
  262. if (!string.IsNullOrEmpty(liveStreamId))
  263. {
  264. return await GetLiveStream(liveStreamId, cancellationToken).ConfigureAwait(false);
  265. }
  266. var sources = await GetPlaybackMediaSources(item, null, false, enablePathSubstitution, cancellationToken).ConfigureAwait(false);
  267. return sources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
  268. }
  269. public List<MediaSourceInfo> GetStaticMediaSources(BaseItem item, bool enablePathSubstitution, User user = null)
  270. {
  271. if (item == null)
  272. {
  273. throw new ArgumentNullException(nameof(item));
  274. }
  275. var hasMediaSources = (IHasMediaSources)item;
  276. var sources = hasMediaSources.GetMediaSources(enablePathSubstitution);
  277. if (user != null)
  278. {
  279. foreach (var source in sources)
  280. {
  281. SetDefaultAudioAndSubtitleStreamIndexes(item, source, user);
  282. }
  283. }
  284. return sources;
  285. }
  286. private string[] NormalizeLanguage(string language)
  287. {
  288. if (language == null)
  289. {
  290. return Array.Empty<string>();
  291. }
  292. var culture = _localizationManager.FindLanguageInfo(language);
  293. if (culture != null)
  294. {
  295. return culture.ThreeLetterISOLanguageNames;
  296. }
  297. return new string[] { language };
  298. }
  299. private void SetDefaultSubtitleStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowRememberingSelection)
  300. {
  301. if (userData.SubtitleStreamIndex.HasValue
  302. && user.RememberSubtitleSelections
  303. && user.SubtitleMode != SubtitlePlaybackMode.None && allowRememberingSelection)
  304. {
  305. var index = userData.SubtitleStreamIndex.Value;
  306. // Make sure the saved index is still valid
  307. if (index == -1 || source.MediaStreams.Any(i => i.Type == MediaStreamType.Subtitle && i.Index == index))
  308. {
  309. source.DefaultSubtitleStreamIndex = index;
  310. return;
  311. }
  312. }
  313. var preferredSubs = string.IsNullOrEmpty(user.SubtitleLanguagePreference)
  314. ? Array.Empty<string>() : NormalizeLanguage(user.SubtitleLanguagePreference);
  315. var defaultAudioIndex = source.DefaultAudioStreamIndex;
  316. var audioLangage = defaultAudioIndex == null
  317. ? null
  318. : source.MediaStreams.Where(i => i.Type == MediaStreamType.Audio && i.Index == defaultAudioIndex).Select(i => i.Language).FirstOrDefault();
  319. source.DefaultSubtitleStreamIndex = MediaStreamSelector.GetDefaultSubtitleStreamIndex(
  320. source.MediaStreams,
  321. preferredSubs,
  322. user.SubtitleMode,
  323. audioLangage);
  324. MediaStreamSelector.SetSubtitleStreamScores(source.MediaStreams, preferredSubs, user.SubtitleMode, audioLangage);
  325. }
  326. private void SetDefaultAudioStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowRememberingSelection)
  327. {
  328. if (userData.AudioStreamIndex.HasValue && user.RememberAudioSelections && allowRememberingSelection)
  329. {
  330. var index = userData.AudioStreamIndex.Value;
  331. // Make sure the saved index is still valid
  332. if (source.MediaStreams.Any(i => i.Type == MediaStreamType.Audio && i.Index == index))
  333. {
  334. source.DefaultAudioStreamIndex = index;
  335. return;
  336. }
  337. }
  338. var preferredAudio = string.IsNullOrEmpty(user.AudioLanguagePreference)
  339. ? Array.Empty<string>()
  340. : NormalizeLanguage(user.AudioLanguagePreference);
  341. source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferredAudio, user.PlayDefaultAudioTrack);
  342. }
  343. public void SetDefaultAudioAndSubtitleStreamIndexes(BaseItem item, MediaSourceInfo source, User user)
  344. {
  345. // Item would only be null if the app didn't supply ItemId as part of the live stream open request
  346. var mediaType = item == null ? MediaType.Video : item.MediaType;
  347. if (string.Equals(mediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase))
  348. {
  349. var userData = item == null ? new UserItemData() : _userDataManager.GetUserData(user, item);
  350. var allowRememberingSelection = item == null || item.EnableRememberingTrackSelections;
  351. SetDefaultAudioStreamIndex(source, userData, user, allowRememberingSelection);
  352. SetDefaultSubtitleStreamIndex(source, userData, user, allowRememberingSelection);
  353. }
  354. else if (string.Equals(mediaType, MediaType.Audio, StringComparison.OrdinalIgnoreCase))
  355. {
  356. var audio = source.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  357. if (audio != null)
  358. {
  359. source.DefaultAudioStreamIndex = audio.Index;
  360. }
  361. }
  362. }
  363. private static IEnumerable<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources)
  364. {
  365. return sources.OrderBy(i =>
  366. {
  367. if (i.VideoType.HasValue && i.VideoType.Value == VideoType.VideoFile)
  368. {
  369. return 0;
  370. }
  371. return 1;
  372. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  373. .ThenByDescending(i =>
  374. {
  375. var stream = i.VideoStream;
  376. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  377. })
  378. .ToList();
  379. }
  380. public async Task<Tuple<LiveStreamResponse, IDirectStreamProvider>> OpenLiveStreamInternal(LiveStreamRequest request, CancellationToken cancellationToken)
  381. {
  382. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  383. MediaSourceInfo mediaSource;
  384. ILiveStream liveStream;
  385. try
  386. {
  387. var tuple = GetProvider(request.OpenToken);
  388. var provider = tuple.Item1;
  389. var currentLiveStreams = _openStreams.Values.ToList();
  390. liveStream = await provider.OpenMediaSource(tuple.Item2, currentLiveStreams, cancellationToken).ConfigureAwait(false);
  391. mediaSource = liveStream.MediaSource;
  392. // Validate that this is actually possible
  393. if (mediaSource.SupportsDirectStream)
  394. {
  395. mediaSource.SupportsDirectStream = SupportsDirectStream(mediaSource.Path, mediaSource.Protocol);
  396. }
  397. SetKeyProperties(provider, mediaSource);
  398. _openStreams[mediaSource.LiveStreamId] = liveStream;
  399. }
  400. finally
  401. {
  402. _liveStreamSemaphore.Release();
  403. }
  404. // TODO: Don't hardcode this
  405. const bool isAudio = false;
  406. try
  407. {
  408. if (mediaSource.MediaStreams.Any(i => i.Index != -1) || !mediaSource.SupportsProbing)
  409. {
  410. AddMediaInfo(mediaSource, isAudio);
  411. }
  412. else
  413. {
  414. // hack - these two values were taken from LiveTVMediaSourceProvider
  415. string cacheKey = request.OpenToken;
  416. await new LiveStreamHelper(_mediaEncoder, _logger, _jsonSerializer, _appPaths)
  417. .AddMediaInfoWithProbe(mediaSource, isAudio, cacheKey, true, cancellationToken)
  418. .ConfigureAwait(false);
  419. }
  420. }
  421. catch (Exception ex)
  422. {
  423. _logger.LogError(ex, "Error probing live tv stream");
  424. AddMediaInfo(mediaSource, isAudio);
  425. }
  426. // TODO: @bond Fix
  427. var json = _jsonSerializer.SerializeToString(mediaSource);
  428. _logger.LogInformation("Live stream opened: " + json);
  429. var clone = _jsonSerializer.DeserializeFromString<MediaSourceInfo>(json);
  430. if (!request.UserId.Equals(Guid.Empty))
  431. {
  432. var user = _userManager.GetUserById(request.UserId);
  433. var item = request.ItemId.Equals(Guid.Empty)
  434. ? null
  435. : _libraryManager.GetItemById(request.ItemId);
  436. SetDefaultAudioAndSubtitleStreamIndexes(item, clone, user);
  437. }
  438. return new Tuple<LiveStreamResponse, IDirectStreamProvider>(new LiveStreamResponse(clone), liveStream as IDirectStreamProvider);
  439. }
  440. private static void AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio)
  441. {
  442. mediaSource.DefaultSubtitleStreamIndex = null;
  443. // Null this out so that it will be treated like a live stream
  444. if (mediaSource.IsInfiniteStream)
  445. {
  446. mediaSource.RunTimeTicks = null;
  447. }
  448. var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  449. if (audioStream == null || audioStream.Index == -1)
  450. {
  451. mediaSource.DefaultAudioStreamIndex = null;
  452. }
  453. else
  454. {
  455. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  456. }
  457. var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  458. if (videoStream != null)
  459. {
  460. if (!videoStream.BitRate.HasValue)
  461. {
  462. var width = videoStream.Width ?? 1920;
  463. if (width >= 3000)
  464. {
  465. videoStream.BitRate = 30000000;
  466. }
  467. else if (width >= 1900)
  468. {
  469. videoStream.BitRate = 20000000;
  470. }
  471. else if (width >= 1200)
  472. {
  473. videoStream.BitRate = 8000000;
  474. }
  475. else if (width >= 700)
  476. {
  477. videoStream.BitRate = 2000000;
  478. }
  479. }
  480. }
  481. // Try to estimate this
  482. mediaSource.InferTotalBitrate();
  483. }
  484. public async Task<IDirectStreamProvider> GetDirectStreamProviderByUniqueId(string uniqueId, CancellationToken cancellationToken)
  485. {
  486. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  487. try
  488. {
  489. var info = _openStreams.Values.FirstOrDefault(i =>
  490. {
  491. var liveStream = i as ILiveStream;
  492. if (liveStream != null)
  493. {
  494. return string.Equals(liveStream.UniqueId, uniqueId, StringComparison.OrdinalIgnoreCase);
  495. }
  496. return false;
  497. });
  498. return info as IDirectStreamProvider;
  499. }
  500. finally
  501. {
  502. _liveStreamSemaphore.Release();
  503. }
  504. }
  505. public async Task<LiveStreamResponse> OpenLiveStream(LiveStreamRequest request, CancellationToken cancellationToken)
  506. {
  507. var result = await OpenLiveStreamInternal(request, cancellationToken).ConfigureAwait(false);
  508. return result.Item1;
  509. }
  510. public async Task<MediaSourceInfo> GetLiveStreamMediaInfo(string id, CancellationToken cancellationToken)
  511. {
  512. var liveStreamInfo = await GetLiveStreamInfo(id, cancellationToken).ConfigureAwait(false);
  513. var mediaSource = liveStreamInfo.MediaSource;
  514. if (liveStreamInfo is IDirectStreamProvider)
  515. {
  516. var info = await _mediaEncoder.GetMediaInfo(new MediaInfoRequest
  517. {
  518. MediaSource = mediaSource,
  519. ExtractChapters = false,
  520. MediaType = DlnaProfileType.Video
  521. }, cancellationToken).ConfigureAwait(false);
  522. mediaSource.MediaStreams = info.MediaStreams;
  523. mediaSource.Container = info.Container;
  524. mediaSource.Bitrate = info.Bitrate;
  525. }
  526. return mediaSource;
  527. }
  528. public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string cacheKey, bool addProbeDelay, bool isLiveStream, CancellationToken cancellationToken)
  529. {
  530. var originalRuntime = mediaSource.RunTimeTicks;
  531. var now = DateTime.UtcNow;
  532. MediaInfo mediaInfo = null;
  533. var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N", CultureInfo.InvariantCulture) + ".json");
  534. if (!string.IsNullOrEmpty(cacheKey))
  535. {
  536. try
  537. {
  538. mediaInfo = _jsonSerializer.DeserializeFromFile<MediaInfo>(cacheFilePath);
  539. // _logger.LogDebug("Found cached media info");
  540. }
  541. catch (Exception ex)
  542. {
  543. _logger.LogDebug(ex, "_jsonSerializer.DeserializeFromFile threw an exception.");
  544. }
  545. }
  546. if (mediaInfo == null)
  547. {
  548. if (addProbeDelay)
  549. {
  550. var delayMs = mediaSource.AnalyzeDurationMs ?? 0;
  551. delayMs = Math.Max(3000, delayMs);
  552. await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);
  553. }
  554. if (isLiveStream)
  555. {
  556. mediaSource.AnalyzeDurationMs = 3000;
  557. }
  558. mediaInfo = await _mediaEncoder.GetMediaInfo(
  559. new MediaInfoRequest
  560. {
  561. MediaSource = mediaSource,
  562. MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
  563. ExtractChapters = false
  564. },
  565. cancellationToken).ConfigureAwait(false);
  566. if (cacheFilePath != null)
  567. {
  568. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  569. _jsonSerializer.SerializeToFile(mediaInfo, cacheFilePath);
  570. // _logger.LogDebug("Saved media info to {0}", cacheFilePath);
  571. }
  572. }
  573. var mediaStreams = mediaInfo.MediaStreams;
  574. if (isLiveStream && !string.IsNullOrEmpty(cacheKey))
  575. {
  576. var newList = new List<MediaStream>();
  577. newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Video).Take(1));
  578. newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Take(1));
  579. foreach (var stream in newList)
  580. {
  581. stream.Index = -1;
  582. stream.Language = null;
  583. }
  584. mediaStreams = newList;
  585. }
  586. _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));
  587. mediaSource.Bitrate = mediaInfo.Bitrate;
  588. mediaSource.Container = mediaInfo.Container;
  589. mediaSource.Formats = mediaInfo.Formats;
  590. mediaSource.MediaStreams = mediaStreams;
  591. mediaSource.RunTimeTicks = mediaInfo.RunTimeTicks;
  592. mediaSource.Size = mediaInfo.Size;
  593. mediaSource.Timestamp = mediaInfo.Timestamp;
  594. mediaSource.Video3DFormat = mediaInfo.Video3DFormat;
  595. mediaSource.VideoType = mediaInfo.VideoType;
  596. mediaSource.DefaultSubtitleStreamIndex = null;
  597. if (isLiveStream)
  598. {
  599. // Null this out so that it will be treated like a live stream
  600. if (!originalRuntime.HasValue)
  601. {
  602. mediaSource.RunTimeTicks = null;
  603. }
  604. }
  605. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  606. if (audioStream == null || audioStream.Index == -1)
  607. {
  608. mediaSource.DefaultAudioStreamIndex = null;
  609. }
  610. else
  611. {
  612. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  613. }
  614. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  615. if (videoStream != null)
  616. {
  617. if (!videoStream.BitRate.HasValue)
  618. {
  619. var width = videoStream.Width ?? 1920;
  620. if (width >= 3000)
  621. {
  622. videoStream.BitRate = 30000000;
  623. }
  624. else if (width >= 1900)
  625. {
  626. videoStream.BitRate = 20000000;
  627. }
  628. else if (width >= 1200)
  629. {
  630. videoStream.BitRate = 8000000;
  631. }
  632. else if (width >= 700)
  633. {
  634. videoStream.BitRate = 2000000;
  635. }
  636. }
  637. // This is coming up false and preventing stream copy
  638. videoStream.IsAVC = null;
  639. }
  640. if (isLiveStream)
  641. {
  642. mediaSource.AnalyzeDurationMs = 3000;
  643. }
  644. // Try to estimate this
  645. mediaSource.InferTotalBitrate(true);
  646. }
  647. public async Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetLiveStreamWithDirectStreamProvider(string id, CancellationToken cancellationToken)
  648. {
  649. if (string.IsNullOrEmpty(id))
  650. {
  651. throw new ArgumentNullException(nameof(id));
  652. }
  653. var info = await GetLiveStreamInfo(id, cancellationToken).ConfigureAwait(false);
  654. return new Tuple<MediaSourceInfo, IDirectStreamProvider>(info.MediaSource, info as IDirectStreamProvider);
  655. }
  656. private async Task<ILiveStream> GetLiveStreamInfo(string id, CancellationToken cancellationToken)
  657. {
  658. if (string.IsNullOrEmpty(id))
  659. {
  660. throw new ArgumentNullException(nameof(id));
  661. }
  662. await _liveStreamSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
  663. try
  664. {
  665. if (_openStreams.TryGetValue(id, out ILiveStream info))
  666. {
  667. return info;
  668. }
  669. else
  670. {
  671. throw new ResourceNotFoundException();
  672. }
  673. }
  674. finally
  675. {
  676. _liveStreamSemaphore.Release();
  677. }
  678. }
  679. public async Task<MediaSourceInfo> GetLiveStream(string id, CancellationToken cancellationToken)
  680. {
  681. var result = await GetLiveStreamWithDirectStreamProvider(id, cancellationToken).ConfigureAwait(false);
  682. return result.Item1;
  683. }
  684. public async Task CloseLiveStream(string id)
  685. {
  686. if (string.IsNullOrEmpty(id))
  687. {
  688. throw new ArgumentNullException(nameof(id));
  689. }
  690. await _liveStreamSemaphore.WaitAsync().ConfigureAwait(false);
  691. try
  692. {
  693. if (_openStreams.TryGetValue(id, out ILiveStream liveStream))
  694. {
  695. liveStream.ConsumerCount--;
  696. _logger.LogInformation("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liveStream.ConsumerCount);
  697. if (liveStream.ConsumerCount <= 0)
  698. {
  699. _openStreams.Remove(id);
  700. _logger.LogInformation("Closing live stream {0}", id);
  701. await liveStream.Close().ConfigureAwait(false);
  702. _logger.LogInformation("Live stream {0} closed successfully", id);
  703. }
  704. }
  705. }
  706. finally
  707. {
  708. _liveStreamSemaphore.Release();
  709. }
  710. }
  711. private Tuple<IMediaSourceProvider, string> GetProvider(string key)
  712. {
  713. if (string.IsNullOrEmpty(key))
  714. {
  715. throw new ArgumentException("key");
  716. }
  717. var keys = key.Split(new[] { LiveStreamIdDelimeter }, 2);
  718. var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture), keys[0], StringComparison.OrdinalIgnoreCase));
  719. var splitIndex = key.IndexOf(LiveStreamIdDelimeter, StringComparison.Ordinal);
  720. var keyId = key.Substring(splitIndex + 1);
  721. return new Tuple<IMediaSourceProvider, string>(provider, keyId);
  722. }
  723. /// <summary>
  724. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  725. /// </summary>
  726. public void Dispose()
  727. {
  728. Dispose(true);
  729. GC.SuppressFinalize(this);
  730. }
  731. /// <summary>
  732. /// Releases unmanaged and - optionally - managed resources.
  733. /// </summary>
  734. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  735. protected virtual void Dispose(bool dispose)
  736. {
  737. if (dispose)
  738. {
  739. lock (_disposeLock)
  740. {
  741. foreach (var key in _openStreams.Keys.ToList())
  742. {
  743. var task = CloseLiveStream(key);
  744. Task.WaitAll(task);
  745. }
  746. }
  747. }
  748. }
  749. }
  750. }