| | | 1 | | #nullable disable |
| | | 2 | | |
| | | 3 | | #pragma warning disable CS1591 |
| | | 4 | | |
| | | 5 | | using System; |
| | | 6 | | using System.Collections.Concurrent; |
| | | 7 | | using System.Collections.Generic; |
| | | 8 | | using System.Collections.Immutable; |
| | | 9 | | using System.Globalization; |
| | | 10 | | using System.IO; |
| | | 11 | | using System.Linq; |
| | | 12 | | using System.Text.Json; |
| | | 13 | | using System.Threading; |
| | | 14 | | using System.Threading.Tasks; |
| | | 15 | | using AsyncKeyedLock; |
| | | 16 | | using Jellyfin.Data; |
| | | 17 | | using Jellyfin.Data.Enums; |
| | | 18 | | using Jellyfin.Database.Implementations.Entities; |
| | | 19 | | using Jellyfin.Database.Implementations.Enums; |
| | | 20 | | using Jellyfin.Extensions; |
| | | 21 | | using Jellyfin.Extensions.Json; |
| | | 22 | | using MediaBrowser.Common.Configuration; |
| | | 23 | | using MediaBrowser.Common.Extensions; |
| | | 24 | | using MediaBrowser.Controller; |
| | | 25 | | using MediaBrowser.Controller.Entities; |
| | | 26 | | using MediaBrowser.Controller.Entities.TV; |
| | | 27 | | using MediaBrowser.Controller.IO; |
| | | 28 | | using MediaBrowser.Controller.Library; |
| | | 29 | | using MediaBrowser.Controller.LiveTv; |
| | | 30 | | using MediaBrowser.Controller.MediaEncoding; |
| | | 31 | | using MediaBrowser.Controller.Persistence; |
| | | 32 | | using MediaBrowser.Controller.Providers; |
| | | 33 | | using MediaBrowser.Model.Dlna; |
| | | 34 | | using MediaBrowser.Model.Dto; |
| | | 35 | | using MediaBrowser.Model.Entities; |
| | | 36 | | using MediaBrowser.Model.Globalization; |
| | | 37 | | using MediaBrowser.Model.IO; |
| | | 38 | | using MediaBrowser.Model.MediaInfo; |
| | | 39 | | using Microsoft.Extensions.Logging; |
| | | 40 | | |
| | | 41 | | namespace Emby.Server.Implementations.Library |
| | | 42 | | { |
| | | 43 | | public class MediaSourceManager : IMediaSourceManager, IDisposable |
| | | 44 | | { |
| | | 45 | | // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message |
| | | 46 | | private const char LiveStreamIdDelimiter = '_'; |
| | | 47 | | |
| | | 48 | | private readonly IServerApplicationHost _appHost; |
| | | 49 | | private readonly IItemRepository _itemRepo; |
| | | 50 | | private readonly IUserManager _userManager; |
| | | 51 | | private readonly ILibraryManager _libraryManager; |
| | | 52 | | private readonly IFileSystem _fileSystem; |
| | | 53 | | private readonly ILogger<MediaSourceManager> _logger; |
| | | 54 | | private readonly IUserDataManager _userDataManager; |
| | | 55 | | private readonly IMediaEncoder _mediaEncoder; |
| | | 56 | | private readonly ILocalizationManager _localizationManager; |
| | | 57 | | private readonly IApplicationPaths _appPaths; |
| | | 58 | | private readonly IDirectoryService _directoryService; |
| | | 59 | | private readonly IMediaStreamRepository _mediaStreamRepository; |
| | | 60 | | private readonly IMediaAttachmentRepository _mediaAttachmentRepository; |
| | 54 | 61 | | private readonly ConcurrentDictionary<string, ILiveStream> _openStreams = new ConcurrentDictionary<string, ILive |
| | 54 | 62 | | private readonly AsyncNonKeyedLocker _liveStreamLocker = new(1); |
| | 54 | 63 | | private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; |
| | | 64 | | |
| | | 65 | | private IMediaSourceProvider[] _providers; |
| | | 66 | | |
| | | 67 | | public MediaSourceManager( |
| | | 68 | | IServerApplicationHost appHost, |
| | | 69 | | IItemRepository itemRepo, |
| | | 70 | | IApplicationPaths applicationPaths, |
| | | 71 | | ILocalizationManager localizationManager, |
| | | 72 | | IUserManager userManager, |
| | | 73 | | ILibraryManager libraryManager, |
| | | 74 | | ILogger<MediaSourceManager> logger, |
| | | 75 | | IFileSystem fileSystem, |
| | | 76 | | IUserDataManager userDataManager, |
| | | 77 | | IMediaEncoder mediaEncoder, |
| | | 78 | | IDirectoryService directoryService, |
| | | 79 | | IMediaStreamRepository mediaStreamRepository, |
| | | 80 | | IMediaAttachmentRepository mediaAttachmentRepository) |
| | | 81 | | { |
| | 54 | 82 | | _appHost = appHost; |
| | 54 | 83 | | _itemRepo = itemRepo; |
| | 54 | 84 | | _userManager = userManager; |
| | 54 | 85 | | _libraryManager = libraryManager; |
| | 54 | 86 | | _logger = logger; |
| | 54 | 87 | | _fileSystem = fileSystem; |
| | 54 | 88 | | _userDataManager = userDataManager; |
| | 54 | 89 | | _mediaEncoder = mediaEncoder; |
| | 54 | 90 | | _localizationManager = localizationManager; |
| | 54 | 91 | | _appPaths = applicationPaths; |
| | 54 | 92 | | _directoryService = directoryService; |
| | 54 | 93 | | _mediaStreamRepository = mediaStreamRepository; |
| | 54 | 94 | | _mediaAttachmentRepository = mediaAttachmentRepository; |
| | 54 | 95 | | } |
| | | 96 | | |
| | | 97 | | public void AddParts(IEnumerable<IMediaSourceProvider> providers) |
| | | 98 | | { |
| | 22 | 99 | | _providers = providers.ToArray(); |
| | 22 | 100 | | } |
| | | 101 | | |
| | | 102 | | public IReadOnlyList<MediaStream> GetMediaStreams(MediaStreamQuery query) |
| | | 103 | | { |
| | 0 | 104 | | var list = _mediaStreamRepository.GetMediaStreams(query); |
| | | 105 | | |
| | 0 | 106 | | foreach (var stream in list) |
| | | 107 | | { |
| | 0 | 108 | | stream.SupportsExternalStream = StreamSupportsExternalStream(stream); |
| | | 109 | | } |
| | | 110 | | |
| | 0 | 111 | | return list; |
| | | 112 | | } |
| | | 113 | | |
| | | 114 | | private static bool StreamSupportsExternalStream(MediaStream stream) |
| | | 115 | | { |
| | 0 | 116 | | if (stream.IsExternal) |
| | | 117 | | { |
| | 0 | 118 | | return true; |
| | | 119 | | } |
| | | 120 | | |
| | 0 | 121 | | if (stream.IsTextSubtitleStream) |
| | | 122 | | { |
| | 0 | 123 | | return true; |
| | | 124 | | } |
| | | 125 | | |
| | 0 | 126 | | if (stream.IsPgsSubtitleStream) |
| | | 127 | | { |
| | 0 | 128 | | return true; |
| | | 129 | | } |
| | | 130 | | |
| | 0 | 131 | | if (stream.IsVobSubSubtitleStream) |
| | | 132 | | { |
| | 0 | 133 | | return true; |
| | | 134 | | } |
| | | 135 | | |
| | 0 | 136 | | return false; |
| | | 137 | | } |
| | | 138 | | |
| | | 139 | | public IReadOnlyList<MediaStream> GetMediaStreams(Guid itemId) |
| | | 140 | | { |
| | 0 | 141 | | var list = GetMediaStreams(new MediaStreamQuery |
| | 0 | 142 | | { |
| | 0 | 143 | | ItemId = itemId |
| | 0 | 144 | | }); |
| | | 145 | | |
| | 0 | 146 | | return GetMediaStreamsForItem(list); |
| | | 147 | | } |
| | | 148 | | |
| | | 149 | | private IReadOnlyList<MediaStream> GetMediaStreamsForItem(IReadOnlyList<MediaStream> streams) |
| | | 150 | | { |
| | 0 | 151 | | foreach (var stream in streams) |
| | | 152 | | { |
| | 0 | 153 | | if (stream.Type == MediaStreamType.Subtitle) |
| | | 154 | | { |
| | 0 | 155 | | stream.SupportsExternalStream = StreamSupportsExternalStream(stream); |
| | | 156 | | } |
| | | 157 | | } |
| | | 158 | | |
| | 0 | 159 | | return streams; |
| | | 160 | | } |
| | | 161 | | |
| | | 162 | | /// <inheritdoc /> |
| | | 163 | | public IReadOnlyList<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query) |
| | | 164 | | { |
| | 0 | 165 | | return _mediaAttachmentRepository.GetMediaAttachments(query); |
| | | 166 | | } |
| | | 167 | | |
| | | 168 | | /// <inheritdoc /> |
| | | 169 | | public IReadOnlyList<MediaAttachment> GetMediaAttachments(Guid itemId) |
| | | 170 | | { |
| | 0 | 171 | | return GetMediaAttachments(new MediaAttachmentQuery |
| | 0 | 172 | | { |
| | 0 | 173 | | ItemId = itemId |
| | 0 | 174 | | }); |
| | | 175 | | } |
| | | 176 | | |
| | | 177 | | public async Task<IReadOnlyList<MediaSourceInfo>> GetPlaybackMediaSources(BaseItem item, User user, bool allowMe |
| | | 178 | | { |
| | 0 | 179 | | var mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user); |
| | 0 | 180 | | ResolveSymlinkPaths(mediaSources, enablePathSubstitution); |
| | | 181 | | |
| | | 182 | | // If file is strm or main media stream is missing, force a metadata refresh with remote probing |
| | 0 | 183 | | if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder |
| | 0 | 184 | | && (item.Path.EndsWith(".strm", StringComparison.OrdinalIgnoreCase) |
| | 0 | 185 | | || (item.MediaType == MediaType.Video && mediaSources[0].MediaStreams.All(i => i.Type != MediaStream |
| | 0 | 186 | | || (item.MediaType == MediaType.Audio && mediaSources[0].MediaStreams.All(i => i.Type != MediaStream |
| | | 187 | | { |
| | 0 | 188 | | await item.RefreshMetadata( |
| | 0 | 189 | | new MetadataRefreshOptions(_directoryService) |
| | 0 | 190 | | { |
| | 0 | 191 | | EnableRemoteContentProbe = true, |
| | 0 | 192 | | MetadataRefreshMode = MetadataRefreshMode.FullRefresh |
| | 0 | 193 | | }, |
| | 0 | 194 | | cancellationToken).ConfigureAwait(false); |
| | | 195 | | |
| | 0 | 196 | | mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user); |
| | 0 | 197 | | ResolveSymlinkPaths(mediaSources, enablePathSubstitution); |
| | | 198 | | } |
| | | 199 | | |
| | 0 | 200 | | var dynamicMediaSources = await GetDynamicMediaSources(item, cancellationToken).ConfigureAwait(false); |
| | | 201 | | |
| | 0 | 202 | | var list = new List<MediaSourceInfo>(); |
| | | 203 | | |
| | 0 | 204 | | list.AddRange(mediaSources); |
| | | 205 | | |
| | 0 | 206 | | foreach (var source in dynamicMediaSources) |
| | | 207 | | { |
| | | 208 | | // Validate that this is actually possible |
| | 0 | 209 | | if (source.SupportsDirectStream) |
| | | 210 | | { |
| | 0 | 211 | | source.SupportsDirectStream = SupportsDirectStream(source.Path, source.Protocol); |
| | | 212 | | } |
| | | 213 | | |
| | 0 | 214 | | if (user is not null) |
| | | 215 | | { |
| | 0 | 216 | | SetDefaultAudioAndSubtitleStreamIndices(item, source, user); |
| | | 217 | | |
| | 0 | 218 | | if (item.MediaType == MediaType.Audio) |
| | | 219 | | { |
| | 0 | 220 | | source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding); |
| | | 221 | | } |
| | 0 | 222 | | else if (item.MediaType == MediaType.Video) |
| | | 223 | | { |
| | 0 | 224 | | source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding); |
| | 0 | 225 | | source.SupportsDirectStream = user.HasPermission(PermissionKind.EnablePlaybackRemuxing); |
| | | 226 | | } |
| | | 227 | | } |
| | | 228 | | |
| | 0 | 229 | | list.Add(source); |
| | | 230 | | } |
| | | 231 | | |
| | 0 | 232 | | var preferredId = mediaSources.Count > 0 && Guid.TryParse(mediaSources[0].Id, out var topSourceId) |
| | 0 | 233 | | ? topSourceId |
| | 0 | 234 | | : item.Id; |
| | | 235 | | |
| | 0 | 236 | | return SortMediaSources(list, preferredId).ToArray(); |
| | 0 | 237 | | } |
| | | 238 | | |
| | | 239 | | /// <inheritdoc />> |
| | | 240 | | public MediaProtocol GetPathProtocol(string path) |
| | | 241 | | { |
| | 2298 | 242 | | if (string.IsNullOrEmpty(path)) |
| | | 243 | | { |
| | 0 | 244 | | return MediaProtocol.File; |
| | | 245 | | } |
| | | 246 | | |
| | 2298 | 247 | | if (path.StartsWith("Rtsp", StringComparison.OrdinalIgnoreCase)) |
| | | 248 | | { |
| | 1 | 249 | | return MediaProtocol.Rtsp; |
| | | 250 | | } |
| | | 251 | | |
| | 2297 | 252 | | if (path.StartsWith("Rtmp", StringComparison.OrdinalIgnoreCase)) |
| | | 253 | | { |
| | 0 | 254 | | return MediaProtocol.Rtmp; |
| | | 255 | | } |
| | | 256 | | |
| | 2297 | 257 | | if (path.StartsWith("Http", StringComparison.OrdinalIgnoreCase)) |
| | | 258 | | { |
| | 2 | 259 | | return MediaProtocol.Http; |
| | | 260 | | } |
| | | 261 | | |
| | 2295 | 262 | | if (path.StartsWith("rtp", StringComparison.OrdinalIgnoreCase)) |
| | | 263 | | { |
| | 0 | 264 | | return MediaProtocol.Rtp; |
| | | 265 | | } |
| | | 266 | | |
| | 2295 | 267 | | if (path.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) |
| | | 268 | | { |
| | 0 | 269 | | return MediaProtocol.Ftp; |
| | | 270 | | } |
| | | 271 | | |
| | 2295 | 272 | | if (path.StartsWith("udp", StringComparison.OrdinalIgnoreCase)) |
| | | 273 | | { |
| | 0 | 274 | | return MediaProtocol.Udp; |
| | | 275 | | } |
| | | 276 | | |
| | 2295 | 277 | | return _fileSystem.IsPathFile(path) ? MediaProtocol.File : MediaProtocol.Http; |
| | | 278 | | } |
| | | 279 | | |
| | | 280 | | public bool SupportsDirectStream(string path, MediaProtocol protocol) |
| | | 281 | | { |
| | 0 | 282 | | if (protocol == MediaProtocol.File) |
| | | 283 | | { |
| | 0 | 284 | | return true; |
| | | 285 | | } |
| | | 286 | | |
| | 0 | 287 | | if (protocol == MediaProtocol.Http) |
| | | 288 | | { |
| | 0 | 289 | | if (path is not null) |
| | | 290 | | { |
| | 0 | 291 | | if (path.Contains(".m3u", StringComparison.OrdinalIgnoreCase)) |
| | | 292 | | { |
| | 0 | 293 | | return false; |
| | | 294 | | } |
| | | 295 | | |
| | 0 | 296 | | return true; |
| | | 297 | | } |
| | | 298 | | } |
| | | 299 | | |
| | 0 | 300 | | return false; |
| | | 301 | | } |
| | | 302 | | |
| | | 303 | | private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(BaseItem item, CancellationToken cancell |
| | | 304 | | { |
| | 0 | 305 | | var tasks = _providers.Select(i => GetDynamicMediaSources(item, i, cancellationToken)); |
| | 0 | 306 | | var results = await Task.WhenAll(tasks).ConfigureAwait(false); |
| | | 307 | | |
| | 0 | 308 | | return results.SelectMany(i => i); |
| | 0 | 309 | | } |
| | | 310 | | |
| | | 311 | | private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(BaseItem item, IMediaSourceProvider prov |
| | | 312 | | { |
| | | 313 | | try |
| | | 314 | | { |
| | 0 | 315 | | var sources = await provider.GetMediaSources(item, cancellationToken).ConfigureAwait(false); |
| | 0 | 316 | | var list = sources.ToList(); |
| | | 317 | | |
| | 0 | 318 | | foreach (var mediaSource in list) |
| | | 319 | | { |
| | 0 | 320 | | mediaSource.InferTotalBitrate(); |
| | | 321 | | |
| | 0 | 322 | | SetKeyProperties(provider, mediaSource); |
| | | 323 | | } |
| | | 324 | | |
| | 0 | 325 | | return list; |
| | | 326 | | } |
| | 0 | 327 | | catch (Exception ex) |
| | | 328 | | { |
| | 0 | 329 | | _logger.LogError(ex, "Error getting media sources"); |
| | 0 | 330 | | return []; |
| | | 331 | | } |
| | 0 | 332 | | } |
| | | 333 | | |
| | | 334 | | /// <summary> |
| | | 335 | | /// Resolves symlinked file paths on the supplied sources to the real on-disk target. |
| | | 336 | | /// Skipped when <paramref name="enablePathSubstitution"/> is set because the path may |
| | | 337 | | /// already have been rewritten to a UNC/URL meant for the client to consume directly. |
| | | 338 | | /// </summary> |
| | | 339 | | private static void ResolveSymlinkPaths(IReadOnlyList<MediaSourceInfo> sources, bool enablePathSubstitution) |
| | | 340 | | { |
| | 0 | 341 | | if (enablePathSubstitution) |
| | | 342 | | { |
| | 0 | 343 | | return; |
| | | 344 | | } |
| | | 345 | | |
| | 0 | 346 | | foreach (var source in sources) |
| | | 347 | | { |
| | 0 | 348 | | if (source.Protocol == MediaProtocol.File |
| | 0 | 349 | | && FileSystemHelper.ResolveLinkTarget(source.Path, returnFinalTarget: true) is { Exists: true } targ |
| | | 350 | | { |
| | 0 | 351 | | source.Path = target.FullName; |
| | | 352 | | } |
| | | 353 | | } |
| | 0 | 354 | | } |
| | | 355 | | |
| | | 356 | | private static void SetKeyProperties(IMediaSourceProvider provider, MediaSourceInfo mediaSource) |
| | | 357 | | { |
| | 0 | 358 | | var prefix = provider.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture) + LiveStreamId |
| | | 359 | | |
| | 0 | 360 | | if (!string.IsNullOrEmpty(mediaSource.OpenToken) && !mediaSource.OpenToken.StartsWith(prefix, StringComparis |
| | | 361 | | { |
| | 0 | 362 | | mediaSource.OpenToken = prefix + mediaSource.OpenToken; |
| | | 363 | | } |
| | | 364 | | |
| | 0 | 365 | | if (!string.IsNullOrEmpty(mediaSource.LiveStreamId) && !mediaSource.LiveStreamId.StartsWith(prefix, StringCo |
| | | 366 | | { |
| | 0 | 367 | | mediaSource.LiveStreamId = prefix + mediaSource.LiveStreamId; |
| | | 368 | | } |
| | 0 | 369 | | } |
| | | 370 | | |
| | | 371 | | public async Task<MediaSourceInfo> GetMediaSource(BaseItem item, string mediaSourceId, string liveStreamId, bool |
| | | 372 | | { |
| | 0 | 373 | | if (!string.IsNullOrEmpty(liveStreamId)) |
| | | 374 | | { |
| | 0 | 375 | | return await GetLiveStream(liveStreamId, cancellationToken).ConfigureAwait(false); |
| | | 376 | | } |
| | | 377 | | |
| | 0 | 378 | | var sources = await GetPlaybackMediaSources(item, null, false, enablePathSubstitution, cancellationToken).Co |
| | | 379 | | |
| | 0 | 380 | | return sources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase)); |
| | 0 | 381 | | } |
| | | 382 | | |
| | | 383 | | public IReadOnlyList<MediaSourceInfo> GetStaticMediaSources(BaseItem item, bool enablePathSubstitution, User use |
| | | 384 | | { |
| | 4 | 385 | | ArgumentNullException.ThrowIfNull(item); |
| | | 386 | | |
| | 4 | 387 | | var hasMediaSources = (IHasMediaSources)item; |
| | | 388 | | |
| | 4 | 389 | | var sources = hasMediaSources.GetMediaSources(enablePathSubstitution); |
| | | 390 | | |
| | 4 | 391 | | if (user is not null) |
| | | 392 | | { |
| | 3 | 393 | | sources = sources |
| | 3 | 394 | | .Where(source => !Guid.TryParse(source.Id, out var sourceId) |
| | 3 | 395 | | || sourceId.Equals(item.Id) |
| | 3 | 396 | | || _libraryManager.GetItemById<BaseItem>(sourceId, user) is not null) |
| | 3 | 397 | | .ToArray(); |
| | | 398 | | |
| | 24 | 399 | | foreach (var source in sources) |
| | | 400 | | { |
| | 9 | 401 | | SetDefaultAudioAndSubtitleStreamIndices(item, source, user); |
| | | 402 | | |
| | 9 | 403 | | if (item.MediaType == MediaType.Audio) |
| | | 404 | | { |
| | 0 | 405 | | source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding); |
| | | 406 | | } |
| | 9 | 407 | | else if (item.MediaType == MediaType.Video) |
| | | 408 | | { |
| | 9 | 409 | | source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding); |
| | 9 | 410 | | source.SupportsDirectStream = user.HasPermission(PermissionKind.EnablePlaybackRemuxing); |
| | | 411 | | } |
| | | 412 | | } |
| | | 413 | | |
| | 3 | 414 | | sources = SetAlternateVersionResumeStates(item, sources, user); |
| | | 415 | | } |
| | | 416 | | |
| | 4 | 417 | | return sources; |
| | | 418 | | } |
| | | 419 | | |
| | | 420 | | /// <summary> |
| | | 421 | | /// When the queried item is a primary, moves the most recently played version to the front so |
| | | 422 | | /// that resuming without an explicit source selection plays the version that was last watched. |
| | | 423 | | /// A directly queried alternate version keeps its own source first. Per-user playback position |
| | | 424 | | /// is not surfaced on the source itself; it is carried by each version's own UserData. |
| | | 425 | | /// </summary> |
| | | 426 | | /// <param name="item">The queried item.</param> |
| | | 427 | | /// <param name="sources">The item's media sources.</param> |
| | | 428 | | /// <param name="user">The user.</param> |
| | | 429 | | /// <returns>The media sources, reordered when a version drives resume.</returns> |
| | | 430 | | private IReadOnlyList<MediaSourceInfo> SetAlternateVersionResumeStates(BaseItem item, IReadOnlyList<MediaSourceI |
| | | 431 | | { |
| | | 432 | | // For a video, multiple sources means alternate versions. |
| | 3 | 433 | | if (item is not Video video || sources.Count < 2) |
| | | 434 | | { |
| | 0 | 435 | | return sources; |
| | | 436 | | } |
| | | 437 | | |
| | 3 | 438 | | var versions = video.GetAllVersions(); |
| | 3 | 439 | | if (versions.Count < 2) |
| | | 440 | | { |
| | 0 | 441 | | return sources; |
| | | 442 | | } |
| | | 443 | | |
| | 3 | 444 | | var userDataByVersion = _userDataManager.GetUserDataBatch(versions, user); |
| | 3 | 445 | | var dataBySourceId = new Dictionary<string, UserItemData>(versions.Count, StringComparer.OrdinalIgnoreCase); |
| | 24 | 446 | | foreach (var version in versions) |
| | | 447 | | { |
| | 9 | 448 | | if (userDataByVersion.TryGetValue(version.Id, out var data)) |
| | | 449 | | { |
| | 3 | 450 | | dataBySourceId[version.Id.ToString("N", CultureInfo.InvariantCulture)] = data; |
| | | 451 | | } |
| | | 452 | | } |
| | | 453 | | |
| | | 454 | | // Reorder only for a resumable (in-progress) version; |
| | | 455 | | // a completed version has no position to resume, so it must not be pulled to the front here. |
| | 3 | 456 | | var resumeSource = VersionPlaybackSelector.SelectMostRecentlyPlayed( |
| | 3 | 457 | | sources, |
| | 3 | 458 | | source => source.Id is not null ? dataBySourceId.GetValueOrDefault(source.Id) : null, |
| | 3 | 459 | | data => data.PlaybackPositionTicks > 0); |
| | | 460 | | |
| | 3 | 461 | | if (resumeSource is not null && !video.PrimaryVersionId.HasValue && !ReferenceEquals(sources[0], resumeSourc |
| | | 462 | | { |
| | 1 | 463 | | var reordered = new List<MediaSourceInfo>(sources.Count) { resumeSource }; |
| | 1 | 464 | | reordered.AddRange(sources.Where(s => !ReferenceEquals(s, resumeSource))); |
| | 1 | 465 | | return reordered; |
| | | 466 | | } |
| | | 467 | | |
| | 2 | 468 | | return sources; |
| | | 469 | | } |
| | | 470 | | |
| | | 471 | | private IReadOnlyList<string> NormalizeLanguage(string language) |
| | | 472 | | { |
| | 67 | 473 | | if (string.IsNullOrEmpty(language)) |
| | | 474 | | { |
| | 1 | 475 | | return []; |
| | | 476 | | } |
| | | 477 | | |
| | 66 | 478 | | var culture = _localizationManager.FindLanguageInfo(language); |
| | 66 | 479 | | if (culture is not null) |
| | | 480 | | { |
| | 66 | 481 | | return culture.Name.Contains('-', StringComparison.OrdinalIgnoreCase) ? [culture.Name] : culture.ThreeLe |
| | | 482 | | } |
| | | 483 | | |
| | 0 | 484 | | return [language]; |
| | | 485 | | } |
| | | 486 | | |
| | | 487 | | private void SetDefaultSubtitleStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowR |
| | | 488 | | { |
| | 31 | 489 | | if (userData is not null |
| | 31 | 490 | | && userData.SubtitleStreamIndex.HasValue |
| | 31 | 491 | | && user.RememberSubtitleSelections |
| | 31 | 492 | | && user.SubtitleMode != SubtitlePlaybackMode.None |
| | 31 | 493 | | && allowRememberingSelection) |
| | | 494 | | { |
| | 0 | 495 | | var index = userData.SubtitleStreamIndex.Value; |
| | | 496 | | // Make sure the saved index is still valid |
| | 0 | 497 | | if (index == -1 || source.MediaStreams.Any(i => i.Type == MediaStreamType.Subtitle && i.Index == index)) |
| | | 498 | | { |
| | 0 | 499 | | source.DefaultSubtitleStreamIndex = index; |
| | 0 | 500 | | return; |
| | | 501 | | } |
| | | 502 | | } |
| | | 503 | | |
| | 31 | 504 | | var preferredSubs = NormalizeLanguage(user.SubtitleLanguagePreference); |
| | | 505 | | |
| | 31 | 506 | | var defaultAudioIndex = source.DefaultAudioStreamIndex; |
| | 31 | 507 | | var audioLanguage = defaultAudioIndex is null |
| | 31 | 508 | | ? null |
| | 31 | 509 | | : source.MediaStreams.Where(i => i.Type == MediaStreamType.Audio && i.Index == defaultAudioIndex).Select |
| | | 510 | | |
| | 31 | 511 | | source.DefaultSubtitleStreamIndex = MediaStreamSelector.GetDefaultSubtitleStreamIndex( |
| | 31 | 512 | | source.MediaStreams, |
| | 31 | 513 | | preferredSubs, |
| | 31 | 514 | | user.SubtitleMode, |
| | 31 | 515 | | audioLanguage); |
| | | 516 | | |
| | 31 | 517 | | MediaStreamSelector.SetSubtitleStreamScores(source.MediaStreams, preferredSubs, user.SubtitleMode, audioLang |
| | 31 | 518 | | } |
| | | 519 | | |
| | | 520 | | private void SetDefaultAudioStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowReme |
| | | 521 | | { |
| | 31 | 522 | | if (userData is not null && userData.AudioStreamIndex.HasValue && user.RememberAudioSelections && allowRemem |
| | | 523 | | { |
| | 0 | 524 | | var index = userData.AudioStreamIndex.Value; |
| | | 525 | | // Make sure the saved index is still valid |
| | 0 | 526 | | if (source.MediaStreams.Any(i => i.Type == MediaStreamType.Audio && i.Index == index)) |
| | | 527 | | { |
| | 0 | 528 | | source.DefaultAudioStreamIndex = index; |
| | 0 | 529 | | source.DefaultAudioIndexSource = AudioIndexSource.User; |
| | 0 | 530 | | return; |
| | | 531 | | } |
| | | 532 | | } |
| | | 533 | | |
| | 31 | 534 | | if (string.Equals(user.AudioLanguagePreference, "OriginalLanguage", StringComparison.OrdinalIgnoreCase)) |
| | | 535 | | { |
| | 16 | 536 | | if (user.PlayDefaultAudioTrack) |
| | | 537 | | { |
| | 6 | 538 | | source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex( |
| | 6 | 539 | | source.MediaStreams, |
| | 6 | 540 | | NormalizeLanguage(originalLanguage), |
| | 6 | 541 | | user.PlayDefaultAudioTrack); |
| | 6 | 542 | | return; |
| | | 543 | | } |
| | | 544 | | |
| | 10 | 545 | | var originalIndex = source.MediaStreams.FindIndex(i => i.Type == MediaStreamType.Audio && i.IsOriginal); |
| | | 546 | | |
| | 10 | 547 | | if (!string.IsNullOrWhiteSpace(originalLanguage) && originalIndex != -1) |
| | | 548 | | { |
| | 4 | 549 | | var mediaLanguageOriginal = source.MediaStreams[originalIndex].Language; |
| | 4 | 550 | | if (NormalizeLanguage(mediaLanguageOriginal).Contains(NormalizeLanguage(originalLanguage).FirstOrDef |
| | | 551 | | { |
| | 1 | 552 | | source.DefaultAudioStreamIndex = originalIndex; |
| | 1 | 553 | | return; |
| | | 554 | | } |
| | | 555 | | } |
| | 6 | 556 | | else if (originalIndex != -1) |
| | | 557 | | { |
| | 2 | 558 | | source.DefaultAudioStreamIndex = originalIndex; |
| | 2 | 559 | | return; |
| | | 560 | | } |
| | | 561 | | } |
| | | 562 | | |
| | 22 | 563 | | var preferredAudio = string.Equals(user.AudioLanguagePreference, "OriginalLanguage", StringComparison.Ordina |
| | 22 | 564 | | ? NormalizeLanguage(originalLanguage) |
| | 22 | 565 | | : NormalizeLanguage(user.AudioLanguagePreference); |
| | | 566 | | |
| | 22 | 567 | | source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferr |
| | 22 | 568 | | if (user.PlayDefaultAudioTrack) |
| | | 569 | | { |
| | 12 | 570 | | source.DefaultAudioIndexSource |= AudioIndexSource.Default; |
| | | 571 | | } |
| | | 572 | | |
| | 22 | 573 | | if (preferredAudio.Count > 0) |
| | | 574 | | { |
| | 22 | 575 | | source.DefaultAudioIndexSource |= AudioIndexSource.Language; |
| | | 576 | | } |
| | 22 | 577 | | } |
| | | 578 | | |
| | | 579 | | public void SetDefaultAudioAndSubtitleStreamIndices(BaseItem item, MediaSourceInfo source, User user) |
| | | 580 | | { |
| | | 581 | | // Item would only be null if the app didn't supply ItemId as part of the live stream open request |
| | 31 | 582 | | var mediaType = item?.MediaType ?? MediaType.Video; |
| | | 583 | | |
| | 31 | 584 | | if (mediaType == MediaType.Video) |
| | | 585 | | { |
| | 31 | 586 | | var userData = item is null ? null : _userDataManager.GetUserData(user, item); |
| | | 587 | | |
| | 31 | 588 | | var allowRememberingSelection = item is null || item.EnableRememberingTrackSelections; |
| | | 589 | | |
| | 31 | 590 | | var originalLanguage = item?.GetInheritedOriginalLanguage(); |
| | | 591 | | |
| | 31 | 592 | | SetDefaultAudioStreamIndex(source, userData, user, allowRememberingSelection, originalLanguage); |
| | 31 | 593 | | SetDefaultSubtitleStreamIndex(source, userData, user, allowRememberingSelection); |
| | | 594 | | } |
| | 0 | 595 | | else if (mediaType == MediaType.Audio) |
| | | 596 | | { |
| | 0 | 597 | | var audio = source.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio); |
| | | 598 | | |
| | 0 | 599 | | if (audio is not null) |
| | | 600 | | { |
| | 0 | 601 | | source.DefaultAudioStreamIndex = audio.Index; |
| | | 602 | | } |
| | | 603 | | } |
| | 0 | 604 | | } |
| | | 605 | | |
| | | 606 | | private static IEnumerable<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources, Guid preferre |
| | | 607 | | { |
| | | 608 | | // The source belonging to the queried item sorts first so it stays the default that gets played. |
| | 0 | 609 | | var preferredId = preferredItemId.IsEmpty() |
| | 0 | 610 | | ? null |
| | 0 | 611 | | : preferredItemId.ToString("N", CultureInfo.InvariantCulture); |
| | | 612 | | |
| | 0 | 613 | | return sources |
| | 0 | 614 | | .OrderByDescending(i => preferredId is not null && string.Equals(i.Id, preferredId, StringComparison.Ord |
| | 0 | 615 | | .ThenBy(i => |
| | 0 | 616 | | { |
| | 0 | 617 | | if (i.VideoType.HasValue && i.VideoType.Value == VideoType.VideoFile) |
| | 0 | 618 | | { |
| | 0 | 619 | | return 0; |
| | 0 | 620 | | } |
| | 0 | 621 | | |
| | 0 | 622 | | return 1; |
| | 0 | 623 | | }) |
| | 0 | 624 | | .ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0) |
| | 0 | 625 | | .ThenByDescending(i => |
| | 0 | 626 | | { |
| | 0 | 627 | | var stream = i.VideoStream; |
| | 0 | 628 | | |
| | 0 | 629 | | return stream?.Width ?? 0; |
| | 0 | 630 | | }) |
| | 0 | 631 | | .Where(i => i.Type != MediaSourceType.Placeholder); |
| | | 632 | | } |
| | | 633 | | |
| | | 634 | | public async Task<Tuple<LiveStreamResponse, IDirectStreamProvider>> OpenLiveStreamInternal(LiveStreamRequest req |
| | | 635 | | { |
| | | 636 | | MediaSourceInfo mediaSource; |
| | | 637 | | ILiveStream liveStream; |
| | | 638 | | |
| | 0 | 639 | | using (await _liveStreamLocker.LockAsync(cancellationToken).ConfigureAwait(false)) |
| | | 640 | | { |
| | 0 | 641 | | var (provider, keyId) = GetProvider(request.OpenToken); |
| | | 642 | | |
| | 0 | 643 | | var currentLiveStreams = _openStreams.Values.ToList(); |
| | | 644 | | |
| | 0 | 645 | | liveStream = await provider.OpenMediaSource(keyId, currentLiveStreams, cancellationToken).ConfigureAwait |
| | | 646 | | |
| | 0 | 647 | | mediaSource = liveStream.MediaSource; |
| | | 648 | | |
| | | 649 | | // Validate that this is actually possible |
| | 0 | 650 | | if (mediaSource.SupportsDirectStream) |
| | | 651 | | { |
| | 0 | 652 | | mediaSource.SupportsDirectStream = SupportsDirectStream(mediaSource.Path, mediaSource.Protocol); |
| | | 653 | | } |
| | | 654 | | |
| | 0 | 655 | | SetKeyProperties(provider, mediaSource); |
| | | 656 | | |
| | 0 | 657 | | _openStreams[mediaSource.LiveStreamId] = liveStream; |
| | 0 | 658 | | } |
| | | 659 | | |
| | | 660 | | try |
| | | 661 | | { |
| | 0 | 662 | | if (mediaSource.MediaStreams.Any(i => i.Index != -1) || !mediaSource.SupportsProbing) |
| | | 663 | | { |
| | 0 | 664 | | AddMediaInfo(mediaSource); |
| | | 665 | | } |
| | | 666 | | else |
| | | 667 | | { |
| | | 668 | | // hack - these two values were taken from LiveTVMediaSourceProvider |
| | 0 | 669 | | string cacheKey = request.OpenToken; |
| | | 670 | | |
| | 0 | 671 | | await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths) |
| | 0 | 672 | | .AddMediaInfoWithProbe(mediaSource, false, cacheKey, true, cancellationToken) |
| | 0 | 673 | | .ConfigureAwait(false); |
| | | 674 | | } |
| | 0 | 675 | | } |
| | 0 | 676 | | catch (Exception ex) |
| | | 677 | | { |
| | 0 | 678 | | _logger.LogError(ex, "Error probing live tv stream"); |
| | 0 | 679 | | AddMediaInfo(mediaSource); |
| | 0 | 680 | | } |
| | | 681 | | |
| | | 682 | | // TODO: @bond Fix |
| | 0 | 683 | | var json = JsonSerializer.SerializeToUtf8Bytes(mediaSource, _jsonOptions); |
| | 0 | 684 | | _logger.LogInformation("Live stream opened: {@MediaSource}", mediaSource); |
| | 0 | 685 | | var clone = JsonSerializer.Deserialize<MediaSourceInfo>(json, _jsonOptions); |
| | | 686 | | |
| | 0 | 687 | | if (!request.UserId.IsEmpty()) |
| | | 688 | | { |
| | 0 | 689 | | var user = _userManager.GetUserById(request.UserId); |
| | 0 | 690 | | var item = request.ItemId.IsEmpty() |
| | 0 | 691 | | ? null |
| | 0 | 692 | | : _libraryManager.GetItemById(request.ItemId); |
| | 0 | 693 | | SetDefaultAudioAndSubtitleStreamIndices(item, clone, user); |
| | | 694 | | } |
| | | 695 | | |
| | 0 | 696 | | return new Tuple<LiveStreamResponse, IDirectStreamProvider>(new LiveStreamResponse(clone), liveStream as IDi |
| | 0 | 697 | | } |
| | | 698 | | |
| | | 699 | | private static void AddMediaInfo(MediaSourceInfo mediaSource) |
| | | 700 | | { |
| | 0 | 701 | | mediaSource.DefaultSubtitleStreamIndex = null; |
| | | 702 | | |
| | | 703 | | // Null this out so that it will be treated like a live stream |
| | 0 | 704 | | if (mediaSource.IsInfiniteStream) |
| | | 705 | | { |
| | 0 | 706 | | mediaSource.RunTimeTicks = null; |
| | | 707 | | } |
| | | 708 | | |
| | 0 | 709 | | var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio); |
| | | 710 | | |
| | 0 | 711 | | if (audioStream is null || audioStream.Index == -1) |
| | | 712 | | { |
| | 0 | 713 | | mediaSource.DefaultAudioStreamIndex = null; |
| | | 714 | | } |
| | | 715 | | else |
| | | 716 | | { |
| | 0 | 717 | | mediaSource.DefaultAudioStreamIndex = audioStream.Index; |
| | | 718 | | } |
| | | 719 | | |
| | 0 | 720 | | var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video); |
| | 0 | 721 | | if (videoStream is not null) |
| | | 722 | | { |
| | 0 | 723 | | if (!videoStream.BitRate.HasValue) |
| | | 724 | | { |
| | 0 | 725 | | var width = videoStream.Width ?? 1920; |
| | | 726 | | |
| | 0 | 727 | | if (width >= 3000) |
| | | 728 | | { |
| | 0 | 729 | | videoStream.BitRate = 30000000; |
| | | 730 | | } |
| | 0 | 731 | | else if (width >= 1900) |
| | | 732 | | { |
| | 0 | 733 | | videoStream.BitRate = 20000000; |
| | | 734 | | } |
| | 0 | 735 | | else if (width >= 1200) |
| | | 736 | | { |
| | 0 | 737 | | videoStream.BitRate = 8000000; |
| | | 738 | | } |
| | 0 | 739 | | else if (width >= 700) |
| | | 740 | | { |
| | 0 | 741 | | videoStream.BitRate = 2000000; |
| | | 742 | | } |
| | | 743 | | } |
| | | 744 | | } |
| | | 745 | | |
| | | 746 | | // Try to estimate this |
| | 0 | 747 | | mediaSource.InferTotalBitrate(); |
| | 0 | 748 | | } |
| | | 749 | | |
| | | 750 | | public async Task<LiveStreamResponse> OpenLiveStream(LiveStreamRequest request, CancellationToken cancellationTo |
| | | 751 | | { |
| | 0 | 752 | | var result = await OpenLiveStreamInternal(request, cancellationToken).ConfigureAwait(false); |
| | 0 | 753 | | return result.Item1; |
| | 0 | 754 | | } |
| | | 755 | | |
| | | 756 | | public async Task<MediaSourceInfo> GetLiveStreamMediaInfo(string id, CancellationToken cancellationToken) |
| | | 757 | | { |
| | | 758 | | // TODO probably shouldn't throw here but it is kept for "backwards compatibility" |
| | 0 | 759 | | var liveStreamInfo = GetLiveStreamInfo(id) ?? throw new ResourceNotFoundException(); |
| | | 760 | | |
| | 0 | 761 | | var mediaSource = liveStreamInfo.MediaSource; |
| | | 762 | | |
| | 0 | 763 | | if (liveStreamInfo is IDirectStreamProvider) |
| | | 764 | | { |
| | 0 | 765 | | var info = await _mediaEncoder.GetMediaInfo( |
| | 0 | 766 | | new MediaInfoRequest |
| | 0 | 767 | | { |
| | 0 | 768 | | MediaSource = mediaSource, |
| | 0 | 769 | | ExtractChapters = false, |
| | 0 | 770 | | MediaType = DlnaProfileType.Video |
| | 0 | 771 | | }, |
| | 0 | 772 | | cancellationToken).ConfigureAwait(false); |
| | | 773 | | |
| | 0 | 774 | | mediaSource.MediaStreams = info.MediaStreams; |
| | 0 | 775 | | mediaSource.Container = info.Container; |
| | 0 | 776 | | mediaSource.Bitrate = info.Bitrate; |
| | | 777 | | } |
| | | 778 | | |
| | 0 | 779 | | return mediaSource; |
| | 0 | 780 | | } |
| | | 781 | | |
| | | 782 | | public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string cacheKey, bool addProb |
| | | 783 | | { |
| | 0 | 784 | | var originalRuntime = mediaSource.RunTimeTicks; |
| | | 785 | | |
| | 0 | 786 | | var now = DateTime.UtcNow; |
| | | 787 | | |
| | 0 | 788 | | MediaInfo mediaInfo = null; |
| | 0 | 789 | | var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", c |
| | | 790 | | |
| | 0 | 791 | | if (!string.IsNullOrEmpty(cacheKey)) |
| | | 792 | | { |
| | 0 | 793 | | FileStream jsonStream = AsyncFile.OpenRead(cacheFilePath); |
| | | 794 | | try |
| | | 795 | | { |
| | 0 | 796 | | mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationT |
| | 0 | 797 | | } |
| | 0 | 798 | | catch (Exception ex) |
| | | 799 | | { |
| | 0 | 800 | | _logger.LogDebug(ex, "Error parsing cached media info."); |
| | 0 | 801 | | } |
| | | 802 | | finally |
| | | 803 | | { |
| | 0 | 804 | | await jsonStream.DisposeAsync().ConfigureAwait(false); |
| | | 805 | | } |
| | 0 | 806 | | } |
| | | 807 | | |
| | 0 | 808 | | if (mediaInfo is null) |
| | | 809 | | { |
| | 0 | 810 | | if (addProbeDelay) |
| | | 811 | | { |
| | 0 | 812 | | var delayMs = mediaSource.AnalyzeDurationMs ?? 0; |
| | 0 | 813 | | delayMs = Math.Max(3000, delayMs); |
| | 0 | 814 | | await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); |
| | | 815 | | } |
| | | 816 | | |
| | 0 | 817 | | if (isLiveStream) |
| | | 818 | | { |
| | 0 | 819 | | mediaSource.AnalyzeDurationMs = 3000; |
| | | 820 | | } |
| | | 821 | | |
| | 0 | 822 | | mediaInfo = await _mediaEncoder.GetMediaInfo( |
| | 0 | 823 | | new MediaInfoRequest |
| | 0 | 824 | | { |
| | 0 | 825 | | MediaSource = mediaSource, |
| | 0 | 826 | | MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video, |
| | 0 | 827 | | ExtractChapters = false |
| | 0 | 828 | | }, |
| | 0 | 829 | | cancellationToken).ConfigureAwait(false); |
| | | 830 | | |
| | 0 | 831 | | if (cacheFilePath is not null) |
| | | 832 | | { |
| | 0 | 833 | | Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); |
| | 0 | 834 | | FileStream createStream = AsyncFile.Create(cacheFilePath); |
| | 0 | 835 | | await using (createStream.ConfigureAwait(false)) |
| | | 836 | | { |
| | 0 | 837 | | await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).Co |
| | | 838 | | } |
| | | 839 | | |
| | | 840 | | // _logger.LogDebug("Saved media info to {0}", cacheFilePath); |
| | | 841 | | } |
| | | 842 | | } |
| | | 843 | | |
| | 0 | 844 | | var mediaStreams = mediaInfo.MediaStreams; |
| | | 845 | | |
| | 0 | 846 | | if (isLiveStream && !string.IsNullOrEmpty(cacheKey)) |
| | | 847 | | { |
| | 0 | 848 | | var newList = new List<MediaStream>(); |
| | 0 | 849 | | newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Video).Take(1)); |
| | 0 | 850 | | newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Take(1)); |
| | | 851 | | |
| | 0 | 852 | | foreach (var stream in newList) |
| | | 853 | | { |
| | 0 | 854 | | stream.Index = -1; |
| | 0 | 855 | | stream.Language = null; |
| | | 856 | | } |
| | | 857 | | |
| | 0 | 858 | | mediaStreams = newList; |
| | | 859 | | } |
| | | 860 | | |
| | 0 | 861 | | _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToS |
| | | 862 | | |
| | 0 | 863 | | mediaSource.Bitrate = mediaInfo.Bitrate; |
| | 0 | 864 | | mediaSource.Container = mediaInfo.Container; |
| | 0 | 865 | | mediaSource.Formats = mediaInfo.Formats; |
| | 0 | 866 | | mediaSource.MediaStreams = mediaStreams; |
| | 0 | 867 | | mediaSource.RunTimeTicks = mediaInfo.RunTimeTicks; |
| | 0 | 868 | | mediaSource.Size = mediaInfo.Size; |
| | 0 | 869 | | mediaSource.Timestamp = mediaInfo.Timestamp; |
| | 0 | 870 | | mediaSource.Video3DFormat = mediaInfo.Video3DFormat; |
| | 0 | 871 | | mediaSource.VideoType = mediaInfo.VideoType; |
| | | 872 | | |
| | 0 | 873 | | mediaSource.DefaultSubtitleStreamIndex = null; |
| | | 874 | | |
| | 0 | 875 | | if (isLiveStream) |
| | | 876 | | { |
| | | 877 | | // Null this out so that it will be treated like a live stream |
| | 0 | 878 | | if (!originalRuntime.HasValue) |
| | | 879 | | { |
| | 0 | 880 | | mediaSource.RunTimeTicks = null; |
| | | 881 | | } |
| | | 882 | | } |
| | | 883 | | |
| | 0 | 884 | | var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio); |
| | | 885 | | |
| | 0 | 886 | | if (audioStream is null || audioStream.Index == -1) |
| | | 887 | | { |
| | 0 | 888 | | mediaSource.DefaultAudioStreamIndex = null; |
| | | 889 | | } |
| | | 890 | | else |
| | | 891 | | { |
| | 0 | 892 | | mediaSource.DefaultAudioStreamIndex = audioStream.Index; |
| | | 893 | | } |
| | | 894 | | |
| | 0 | 895 | | var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video); |
| | 0 | 896 | | if (videoStream is not null) |
| | | 897 | | { |
| | 0 | 898 | | if (!videoStream.BitRate.HasValue) |
| | | 899 | | { |
| | 0 | 900 | | var width = videoStream.Width ?? 1920; |
| | | 901 | | |
| | 0 | 902 | | if (width >= 3000) |
| | | 903 | | { |
| | 0 | 904 | | videoStream.BitRate = 30000000; |
| | | 905 | | } |
| | 0 | 906 | | else if (width >= 1900) |
| | | 907 | | { |
| | 0 | 908 | | videoStream.BitRate = 20000000; |
| | | 909 | | } |
| | 0 | 910 | | else if (width >= 1200) |
| | | 911 | | { |
| | 0 | 912 | | videoStream.BitRate = 8000000; |
| | | 913 | | } |
| | 0 | 914 | | else if (width >= 700) |
| | | 915 | | { |
| | 0 | 916 | | videoStream.BitRate = 2000000; |
| | | 917 | | } |
| | | 918 | | } |
| | | 919 | | |
| | | 920 | | // This is coming up false and preventing stream copy |
| | 0 | 921 | | videoStream.IsAVC = null; |
| | | 922 | | } |
| | | 923 | | |
| | 0 | 924 | | if (isLiveStream) |
| | | 925 | | { |
| | 0 | 926 | | mediaSource.AnalyzeDurationMs = 3000; |
| | | 927 | | } |
| | | 928 | | |
| | | 929 | | // Try to estimate this |
| | 0 | 930 | | mediaSource.InferTotalBitrate(true); |
| | 0 | 931 | | } |
| | | 932 | | |
| | | 933 | | public Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetLiveStreamWithDirectStreamProvider(string id, Canc |
| | | 934 | | { |
| | 0 | 935 | | ArgumentException.ThrowIfNullOrEmpty(id); |
| | | 936 | | |
| | 0 | 937 | | var info = GetLiveStreamInfo(id); |
| | 0 | 938 | | if (info is null) |
| | | 939 | | { |
| | 0 | 940 | | return Task.FromResult<Tuple<MediaSourceInfo, IDirectStreamProvider>>(new Tuple<MediaSourceInfo, IDirect |
| | | 941 | | } |
| | | 942 | | |
| | 0 | 943 | | return Task.FromResult<Tuple<MediaSourceInfo, IDirectStreamProvider>>(new Tuple<MediaSourceInfo, IDirectStre |
| | | 944 | | } |
| | | 945 | | |
| | | 946 | | public ILiveStream GetLiveStreamInfo(string id) |
| | | 947 | | { |
| | 0 | 948 | | ArgumentException.ThrowIfNullOrEmpty(id); |
| | | 949 | | |
| | 0 | 950 | | if (_openStreams.TryGetValue(id, out ILiveStream info)) |
| | | 951 | | { |
| | 0 | 952 | | return info; |
| | | 953 | | } |
| | | 954 | | |
| | 0 | 955 | | return null; |
| | | 956 | | } |
| | | 957 | | |
| | | 958 | | /// <inheritdoc /> |
| | | 959 | | public ILiveStream GetLiveStreamInfoByUniqueId(string uniqueId) |
| | | 960 | | { |
| | 0 | 961 | | return _openStreams.Values.FirstOrDefault(stream => string.Equals(uniqueId, stream?.UniqueId, StringComparis |
| | | 962 | | } |
| | | 963 | | |
| | | 964 | | public async Task<MediaSourceInfo> GetLiveStream(string id, CancellationToken cancellationToken) |
| | | 965 | | { |
| | 0 | 966 | | var result = await GetLiveStreamWithDirectStreamProvider(id, cancellationToken).ConfigureAwait(false); |
| | 0 | 967 | | return result.Item1; |
| | 0 | 968 | | } |
| | | 969 | | |
| | | 970 | | public async Task<IReadOnlyList<MediaSourceInfo>> GetRecordingStreamMediaSources(ActiveRecordingInfo info, Cance |
| | | 971 | | { |
| | 0 | 972 | | var stream = new MediaSourceInfo |
| | 0 | 973 | | { |
| | 0 | 974 | | EncoderPath = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveRecordings/" + info.Id + "/stream", |
| | 0 | 975 | | EncoderProtocol = MediaProtocol.Http, |
| | 0 | 976 | | Path = info.Path, |
| | 0 | 977 | | Protocol = MediaProtocol.File, |
| | 0 | 978 | | Id = info.Id, |
| | 0 | 979 | | SupportsDirectPlay = false, |
| | 0 | 980 | | SupportsDirectStream = true, |
| | 0 | 981 | | SupportsTranscoding = true, |
| | 0 | 982 | | IsInfiniteStream = true, |
| | 0 | 983 | | RequiresOpening = false, |
| | 0 | 984 | | RequiresClosing = false, |
| | 0 | 985 | | BufferMs = 0, |
| | 0 | 986 | | IgnoreDts = true, |
| | 0 | 987 | | IgnoreIndex = true |
| | 0 | 988 | | }; |
| | | 989 | | |
| | 0 | 990 | | await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths) |
| | 0 | 991 | | .AddMediaInfoWithProbe(stream, false, false, cancellationToken).ConfigureAwait(false); |
| | | 992 | | |
| | 0 | 993 | | return [stream]; |
| | 0 | 994 | | } |
| | | 995 | | |
| | | 996 | | public async Task CloseLiveStream(string id) |
| | | 997 | | { |
| | 0 | 998 | | ArgumentException.ThrowIfNullOrEmpty(id); |
| | | 999 | | |
| | 0 | 1000 | | using (await _liveStreamLocker.LockAsync().ConfigureAwait(false)) |
| | | 1001 | | { |
| | 0 | 1002 | | if (_openStreams.TryGetValue(id, out ILiveStream liveStream)) |
| | | 1003 | | { |
| | 0 | 1004 | | liveStream.ConsumerCount--; |
| | | 1005 | | |
| | 0 | 1006 | | _logger.LogInformation("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liv |
| | | 1007 | | |
| | 0 | 1008 | | if (liveStream.ConsumerCount <= 0) |
| | | 1009 | | { |
| | 0 | 1010 | | _openStreams.TryRemove(id, out _); |
| | | 1011 | | |
| | 0 | 1012 | | _logger.LogInformation("Closing live stream {0}", id); |
| | | 1013 | | |
| | 0 | 1014 | | await liveStream.Close().ConfigureAwait(false); |
| | 0 | 1015 | | _logger.LogInformation("Live stream {0} closed successfully", id); |
| | | 1016 | | } |
| | | 1017 | | } |
| | 0 | 1018 | | } |
| | 0 | 1019 | | } |
| | | 1020 | | |
| | | 1021 | | private (IMediaSourceProvider MediaSourceProvider, string KeyId) GetProvider(string key) |
| | | 1022 | | { |
| | 0 | 1023 | | ArgumentException.ThrowIfNullOrEmpty(key); |
| | | 1024 | | |
| | 0 | 1025 | | var keys = key.Split(LiveStreamIdDelimiter, 2); |
| | | 1026 | | |
| | 0 | 1027 | | var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", Cult |
| | | 1028 | | |
| | 0 | 1029 | | var splitIndex = key.IndexOf(LiveStreamIdDelimiter, StringComparison.Ordinal); |
| | 0 | 1030 | | var keyId = key.Substring(splitIndex + 1); |
| | | 1031 | | |
| | 0 | 1032 | | return (provider, keyId); |
| | | 1033 | | } |
| | | 1034 | | |
| | | 1035 | | /// <inheritdoc /> |
| | | 1036 | | public void Dispose() |
| | | 1037 | | { |
| | 22 | 1038 | | Dispose(true); |
| | 22 | 1039 | | GC.SuppressFinalize(this); |
| | 22 | 1040 | | } |
| | | 1041 | | |
| | | 1042 | | /// <summary> |
| | | 1043 | | /// Releases unmanaged and - optionally - managed resources. |
| | | 1044 | | /// </summary> |
| | | 1045 | | /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o |
| | | 1046 | | protected virtual void Dispose(bool dispose) |
| | | 1047 | | { |
| | 22 | 1048 | | if (dispose) |
| | | 1049 | | { |
| | 44 | 1050 | | foreach (var key in _openStreams.Keys.ToList()) |
| | | 1051 | | { |
| | 0 | 1052 | | CloseLiveStream(key).GetAwaiter().GetResult(); |
| | | 1053 | | } |
| | | 1054 | | |
| | 22 | 1055 | | _liveStreamLocker.Dispose(); |
| | | 1056 | | } |
| | 22 | 1057 | | } |
| | | 1058 | | } |
| | | 1059 | | } |