| | | 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; |
| | 68 | 61 | | private readonly ConcurrentDictionary<string, ILiveStream> _openStreams = new ConcurrentDictionary<string, ILive |
| | 68 | 62 | | private readonly AsyncNonKeyedLocker _liveStreamLocker = new(1); |
| | 68 | 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 | | { |
| | 68 | 82 | | _appHost = appHost; |
| | 68 | 83 | | _itemRepo = itemRepo; |
| | 68 | 84 | | _userManager = userManager; |
| | 68 | 85 | | _libraryManager = libraryManager; |
| | 68 | 86 | | _logger = logger; |
| | 68 | 87 | | _fileSystem = fileSystem; |
| | 68 | 88 | | _userDataManager = userDataManager; |
| | 68 | 89 | | _mediaEncoder = mediaEncoder; |
| | 68 | 90 | | _localizationManager = localizationManager; |
| | 68 | 91 | | _appPaths = applicationPaths; |
| | 68 | 92 | | _directoryService = directoryService; |
| | 68 | 93 | | _mediaStreamRepository = mediaStreamRepository; |
| | 68 | 94 | | _mediaAttachmentRepository = mediaAttachmentRepository; |
| | 68 | 95 | | } |
| | | 96 | | |
| | | 97 | | public void AddParts(IEnumerable<IMediaSourceProvider> providers) |
| | | 98 | | { |
| | 27 | 99 | | _providers = providers.ToArray(); |
| | 27 | 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 | | { |
| | 3508 | 242 | | if (string.IsNullOrEmpty(path)) |
| | | 243 | | { |
| | 0 | 244 | | return MediaProtocol.File; |
| | | 245 | | } |
| | | 246 | | |
| | 3508 | 247 | | if (path.StartsWith("Rtsp", StringComparison.OrdinalIgnoreCase)) |
| | | 248 | | { |
| | 1 | 249 | | return MediaProtocol.Rtsp; |
| | | 250 | | } |
| | | 251 | | |
| | 3507 | 252 | | if (path.StartsWith("Rtmp", StringComparison.OrdinalIgnoreCase)) |
| | | 253 | | { |
| | 0 | 254 | | return MediaProtocol.Rtmp; |
| | | 255 | | } |
| | | 256 | | |
| | 3507 | 257 | | if (path.StartsWith("Http", StringComparison.OrdinalIgnoreCase)) |
| | | 258 | | { |
| | 2 | 259 | | return MediaProtocol.Http; |
| | | 260 | | } |
| | | 261 | | |
| | 3505 | 262 | | if (path.StartsWith("rtp", StringComparison.OrdinalIgnoreCase)) |
| | | 263 | | { |
| | 0 | 264 | | return MediaProtocol.Rtp; |
| | | 265 | | } |
| | | 266 | | |
| | 3505 | 267 | | if (path.StartsWith("ftp", StringComparison.OrdinalIgnoreCase)) |
| | | 268 | | { |
| | 0 | 269 | | return MediaProtocol.Ftp; |
| | | 270 | | } |
| | | 271 | | |
| | 3505 | 272 | | if (path.StartsWith("udp", StringComparison.OrdinalIgnoreCase)) |
| | | 273 | | { |
| | 0 | 274 | | return MediaProtocol.Udp; |
| | | 275 | | } |
| | | 276 | | |
| | 3505 | 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 | | { |
| | 5 | 385 | | ArgumentNullException.ThrowIfNull(item); |
| | | 386 | | |
| | | 387 | | // Clients can ask for the sources of an item that has none (a container queued by mistake). |
| | 5 | 388 | | if (item is not IHasMediaSources hasMediaSources) |
| | | 389 | | { |
| | 1 | 390 | | throw new ArgumentException( |
| | 1 | 391 | | string.Format(CultureInfo.InvariantCulture, "{0} {1} has no media sources and cannot be played.", it |
| | 1 | 392 | | nameof(item)); |
| | | 393 | | } |
| | | 394 | | |
| | 4 | 395 | | var sources = hasMediaSources.GetMediaSources(enablePathSubstitution); |
| | | 396 | | |
| | 4 | 397 | | if (user is not null) |
| | | 398 | | { |
| | 3 | 399 | | sources = sources |
| | 3 | 400 | | .Where(source => !Guid.TryParse(source.Id, out var sourceId) |
| | 3 | 401 | | || sourceId.Equals(item.Id) |
| | 3 | 402 | | || _libraryManager.GetItemById<BaseItem>(sourceId, user) is not null) |
| | 3 | 403 | | .ToArray(); |
| | | 404 | | |
| | 24 | 405 | | foreach (var source in sources) |
| | | 406 | | { |
| | 9 | 407 | | SetDefaultAudioAndSubtitleStreamIndices(item, source, user); |
| | | 408 | | |
| | 9 | 409 | | if (item.MediaType == MediaType.Audio) |
| | | 410 | | { |
| | 0 | 411 | | source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding); |
| | | 412 | | } |
| | 9 | 413 | | else if (item.MediaType == MediaType.Video) |
| | | 414 | | { |
| | 9 | 415 | | source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding); |
| | 9 | 416 | | source.SupportsDirectStream = user.HasPermission(PermissionKind.EnablePlaybackRemuxing); |
| | | 417 | | } |
| | | 418 | | } |
| | | 419 | | |
| | 3 | 420 | | sources = SetAlternateVersionResumeStates(item, sources, user); |
| | | 421 | | } |
| | | 422 | | |
| | 4 | 423 | | return sources; |
| | | 424 | | } |
| | | 425 | | |
| | | 426 | | /// <summary> |
| | | 427 | | /// When the queried item is a primary, moves the most recently played version to the front so |
| | | 428 | | /// that resuming without an explicit source selection plays the version that was last watched. |
| | | 429 | | /// A directly queried alternate version keeps its own source first. Per-user playback position |
| | | 430 | | /// is not surfaced on the source itself; it is carried by each version's own UserData. |
| | | 431 | | /// </summary> |
| | | 432 | | /// <param name="item">The queried item.</param> |
| | | 433 | | /// <param name="sources">The item's media sources.</param> |
| | | 434 | | /// <param name="user">The user.</param> |
| | | 435 | | /// <returns>The media sources, reordered when a version drives resume.</returns> |
| | | 436 | | private IReadOnlyList<MediaSourceInfo> SetAlternateVersionResumeStates(BaseItem item, IReadOnlyList<MediaSourceI |
| | | 437 | | { |
| | | 438 | | // For a video, multiple sources means alternate versions. |
| | 3 | 439 | | if (item is not Video video || sources.Count < 2) |
| | | 440 | | { |
| | 0 | 441 | | return sources; |
| | | 442 | | } |
| | | 443 | | |
| | 3 | 444 | | var versions = video.GetAllVersions(); |
| | 3 | 445 | | if (versions.Count < 2) |
| | | 446 | | { |
| | 0 | 447 | | return sources; |
| | | 448 | | } |
| | | 449 | | |
| | 3 | 450 | | var userDataByVersion = _userDataManager.GetUserDataBatch(versions, user); |
| | 3 | 451 | | var dataBySourceId = new Dictionary<string, UserItemData>(versions.Count, StringComparer.OrdinalIgnoreCase); |
| | 24 | 452 | | foreach (var version in versions) |
| | | 453 | | { |
| | 9 | 454 | | if (userDataByVersion.TryGetValue(version.Id, out var data)) |
| | | 455 | | { |
| | 3 | 456 | | dataBySourceId[version.Id.ToString("N", CultureInfo.InvariantCulture)] = data; |
| | | 457 | | } |
| | | 458 | | } |
| | | 459 | | |
| | | 460 | | // Reorder only for a resumable (in-progress) version; |
| | | 461 | | // a completed version has no position to resume, so it must not be pulled to the front here. |
| | 3 | 462 | | var resumeSource = VersionPlaybackSelector.SelectMostRecentlyPlayed( |
| | 3 | 463 | | sources, |
| | 3 | 464 | | source => source.Id is not null ? dataBySourceId.GetValueOrDefault(source.Id) : null, |
| | 3 | 465 | | data => data.PlaybackPositionTicks > 0); |
| | | 466 | | |
| | 3 | 467 | | if (resumeSource is not null && !video.PrimaryVersionId.HasValue && !ReferenceEquals(sources[0], resumeSourc |
| | | 468 | | { |
| | 1 | 469 | | var reordered = new List<MediaSourceInfo>(sources.Count) { resumeSource }; |
| | 1 | 470 | | reordered.AddRange(sources.Where(s => !ReferenceEquals(s, resumeSource))); |
| | 1 | 471 | | return reordered; |
| | | 472 | | } |
| | | 473 | | |
| | 2 | 474 | | return sources; |
| | | 475 | | } |
| | | 476 | | |
| | | 477 | | private IReadOnlyList<string> NormalizeLanguage(string language) |
| | | 478 | | { |
| | 78 | 479 | | if (string.IsNullOrEmpty(language)) |
| | | 480 | | { |
| | 12 | 481 | | return []; |
| | | 482 | | } |
| | | 483 | | |
| | 66 | 484 | | var culture = _localizationManager.FindLanguageInfo(language); |
| | 66 | 485 | | if (culture is not null) |
| | | 486 | | { |
| | 66 | 487 | | return culture.Name.Contains('-', StringComparison.OrdinalIgnoreCase) ? [culture.Name] : culture.ThreeLe |
| | | 488 | | } |
| | | 489 | | |
| | 0 | 490 | | return [language]; |
| | | 491 | | } |
| | | 492 | | |
| | | 493 | | private void SetDefaultSubtitleStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowR |
| | | 494 | | { |
| | 39 | 495 | | if (userData is not null |
| | 39 | 496 | | && userData.SubtitleStreamIndex.HasValue |
| | 39 | 497 | | && user.RememberSubtitleSelections |
| | 39 | 498 | | && user.SubtitleMode != SubtitlePlaybackMode.None |
| | 39 | 499 | | && allowRememberingSelection) |
| | | 500 | | { |
| | 7 | 501 | | var index = userData.SubtitleStreamIndex.Value; |
| | | 502 | | // Make sure the saved index is still valid |
| | 7 | 503 | | var savedStream = source.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Subtitle && i.Index |
| | | 504 | | // "Only forced" rules out full tracks entirely, so a remembered one must not resurrect them. |
| | | 505 | | // The client reports whatever is playing, so an index remembered under another mode sticks forever othe |
| | 7 | 506 | | if (index == -1 |
| | 7 | 507 | | || (savedStream is not null |
| | 7 | 508 | | && (user.SubtitleMode != SubtitlePlaybackMode.OnlyForced || savedStream.IsForced))) |
| | | 509 | | { |
| | 5 | 510 | | source.DefaultSubtitleStreamIndex = index; |
| | 5 | 511 | | return; |
| | | 512 | | } |
| | | 513 | | } |
| | | 514 | | |
| | 34 | 515 | | var preferredSubs = NormalizeLanguage(user.SubtitleLanguagePreference); |
| | | 516 | | |
| | 34 | 517 | | var defaultAudioIndex = source.DefaultAudioStreamIndex; |
| | 34 | 518 | | var audioLanguage = defaultAudioIndex is null |
| | 34 | 519 | | ? null |
| | 34 | 520 | | : source.MediaStreams.Where(i => i.Type == MediaStreamType.Audio && i.Index == defaultAudioIndex).Select |
| | | 521 | | |
| | 34 | 522 | | source.DefaultSubtitleStreamIndex = MediaStreamSelector.GetDefaultSubtitleStreamIndex( |
| | 34 | 523 | | source.MediaStreams, |
| | 34 | 524 | | preferredSubs, |
| | 34 | 525 | | user.SubtitleMode, |
| | 34 | 526 | | audioLanguage); |
| | | 527 | | |
| | 34 | 528 | | MediaStreamSelector.SetSubtitleStreamScores(source.MediaStreams, preferredSubs, user.SubtitleMode, audioLang |
| | 34 | 529 | | } |
| | | 530 | | |
| | | 531 | | private void SetDefaultAudioStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowReme |
| | | 532 | | { |
| | 39 | 533 | | if (userData is not null && userData.AudioStreamIndex.HasValue && user.RememberAudioSelections && allowRemem |
| | | 534 | | { |
| | 0 | 535 | | var index = userData.AudioStreamIndex.Value; |
| | | 536 | | // Make sure the saved index is still valid |
| | 0 | 537 | | if (source.MediaStreams.Any(i => i.Type == MediaStreamType.Audio && i.Index == index)) |
| | | 538 | | { |
| | 0 | 539 | | source.DefaultAudioStreamIndex = index; |
| | 0 | 540 | | source.DefaultAudioIndexSource = AudioIndexSource.User; |
| | 0 | 541 | | return; |
| | | 542 | | } |
| | | 543 | | } |
| | | 544 | | |
| | 39 | 545 | | if (string.Equals(user.AudioLanguagePreference, "OriginalLanguage", StringComparison.OrdinalIgnoreCase)) |
| | | 546 | | { |
| | 16 | 547 | | if (user.PlayDefaultAudioTrack) |
| | | 548 | | { |
| | 6 | 549 | | source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex( |
| | 6 | 550 | | source.MediaStreams, |
| | 6 | 551 | | NormalizeLanguage(originalLanguage), |
| | 6 | 552 | | user.PlayDefaultAudioTrack); |
| | 6 | 553 | | return; |
| | | 554 | | } |
| | | 555 | | |
| | 10 | 556 | | var originalIndex = source.MediaStreams.FindIndex(i => i.Type == MediaStreamType.Audio && i.IsOriginal); |
| | | 557 | | |
| | 10 | 558 | | if (!string.IsNullOrWhiteSpace(originalLanguage) && originalIndex != -1) |
| | | 559 | | { |
| | 4 | 560 | | var mediaLanguageOriginal = source.MediaStreams[originalIndex].Language; |
| | 4 | 561 | | if (NormalizeLanguage(mediaLanguageOriginal).Contains(NormalizeLanguage(originalLanguage).FirstOrDef |
| | | 562 | | { |
| | 1 | 563 | | source.DefaultAudioStreamIndex = originalIndex; |
| | 1 | 564 | | return; |
| | | 565 | | } |
| | | 566 | | } |
| | 6 | 567 | | else if (originalIndex != -1) |
| | | 568 | | { |
| | 2 | 569 | | source.DefaultAudioStreamIndex = originalIndex; |
| | 2 | 570 | | return; |
| | | 571 | | } |
| | | 572 | | } |
| | | 573 | | |
| | 30 | 574 | | var preferredAudio = string.Equals(user.AudioLanguagePreference, "OriginalLanguage", StringComparison.Ordina |
| | 30 | 575 | | ? NormalizeLanguage(originalLanguage) |
| | 30 | 576 | | : NormalizeLanguage(user.AudioLanguagePreference); |
| | | 577 | | |
| | 30 | 578 | | source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferr |
| | 30 | 579 | | if (user.PlayDefaultAudioTrack) |
| | | 580 | | { |
| | 20 | 581 | | source.DefaultAudioIndexSource |= AudioIndexSource.Default; |
| | | 582 | | } |
| | | 583 | | |
| | 30 | 584 | | if (preferredAudio.Count > 0) |
| | | 585 | | { |
| | 22 | 586 | | source.DefaultAudioIndexSource |= AudioIndexSource.Language; |
| | | 587 | | } |
| | 30 | 588 | | } |
| | | 589 | | |
| | | 590 | | public void SetDefaultAudioAndSubtitleStreamIndices(BaseItem item, MediaSourceInfo source, User user) |
| | | 591 | | { |
| | | 592 | | // Item would only be null if the app didn't supply ItemId as part of the live stream open request |
| | 39 | 593 | | var mediaType = item?.MediaType ?? MediaType.Video; |
| | | 594 | | |
| | 39 | 595 | | if (mediaType == MediaType.Video) |
| | | 596 | | { |
| | 39 | 597 | | var userData = item is null ? null : _userDataManager.GetUserData(user, item); |
| | | 598 | | |
| | 39 | 599 | | var allowRememberingSelection = item is null || item.EnableRememberingTrackSelections; |
| | | 600 | | |
| | 39 | 601 | | var originalLanguage = item?.GetInheritedOriginalLanguage(); |
| | | 602 | | |
| | 39 | 603 | | SetDefaultAudioStreamIndex(source, userData, user, allowRememberingSelection, originalLanguage); |
| | 39 | 604 | | SetDefaultSubtitleStreamIndex(source, userData, user, allowRememberingSelection); |
| | | 605 | | } |
| | 0 | 606 | | else if (mediaType == MediaType.Audio) |
| | | 607 | | { |
| | 0 | 608 | | var audio = source.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio); |
| | | 609 | | |
| | 0 | 610 | | if (audio is not null) |
| | | 611 | | { |
| | 0 | 612 | | source.DefaultAudioStreamIndex = audio.Index; |
| | | 613 | | } |
| | | 614 | | } |
| | 0 | 615 | | } |
| | | 616 | | |
| | | 617 | | private static IEnumerable<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources, Guid preferre |
| | | 618 | | { |
| | | 619 | | // The source belonging to the queried item sorts first so it stays the default that gets played. |
| | 0 | 620 | | var preferredId = preferredItemId.IsEmpty() |
| | 0 | 621 | | ? null |
| | 0 | 622 | | : preferredItemId.ToString("N", CultureInfo.InvariantCulture); |
| | | 623 | | |
| | 0 | 624 | | return sources |
| | 0 | 625 | | .OrderByDescending(i => preferredId is not null && string.Equals(i.Id, preferredId, StringComparison.Ord |
| | 0 | 626 | | .ThenBy(i => |
| | 0 | 627 | | { |
| | 0 | 628 | | if (i.VideoType.HasValue && i.VideoType.Value == VideoType.VideoFile) |
| | 0 | 629 | | { |
| | 0 | 630 | | return 0; |
| | 0 | 631 | | } |
| | 0 | 632 | | |
| | 0 | 633 | | return 1; |
| | 0 | 634 | | }) |
| | 0 | 635 | | .ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0) |
| | 0 | 636 | | .ThenByDescending(i => |
| | 0 | 637 | | { |
| | 0 | 638 | | var stream = i.VideoStream; |
| | 0 | 639 | | |
| | 0 | 640 | | return stream?.Width ?? 0; |
| | 0 | 641 | | }) |
| | 0 | 642 | | .Where(i => i.Type != MediaSourceType.Placeholder); |
| | | 643 | | } |
| | | 644 | | |
| | | 645 | | public async Task<Tuple<LiveStreamResponse, IDirectStreamProvider>> OpenLiveStreamInternal(LiveStreamRequest req |
| | | 646 | | { |
| | | 647 | | MediaSourceInfo mediaSource; |
| | | 648 | | ILiveStream liveStream; |
| | | 649 | | |
| | 0 | 650 | | using (await _liveStreamLocker.LockAsync(cancellationToken).ConfigureAwait(false)) |
| | | 651 | | { |
| | 0 | 652 | | var (provider, keyId) = GetProvider(request.OpenToken); |
| | | 653 | | |
| | 0 | 654 | | var currentLiveStreams = _openStreams.Values.ToList(); |
| | | 655 | | |
| | 0 | 656 | | liveStream = await provider.OpenMediaSource(keyId, currentLiveStreams, cancellationToken).ConfigureAwait |
| | | 657 | | |
| | 0 | 658 | | mediaSource = liveStream.MediaSource; |
| | | 659 | | |
| | | 660 | | // Validate that this is actually possible |
| | 0 | 661 | | if (mediaSource.SupportsDirectStream) |
| | | 662 | | { |
| | 0 | 663 | | mediaSource.SupportsDirectStream = SupportsDirectStream(mediaSource.Path, mediaSource.Protocol); |
| | | 664 | | } |
| | | 665 | | |
| | 0 | 666 | | SetKeyProperties(provider, mediaSource); |
| | | 667 | | |
| | 0 | 668 | | _openStreams[mediaSource.LiveStreamId] = liveStream; |
| | 0 | 669 | | } |
| | | 670 | | |
| | | 671 | | try |
| | | 672 | | { |
| | 0 | 673 | | if (mediaSource.MediaStreams.Any(i => i.Index != -1) || !mediaSource.SupportsProbing) |
| | | 674 | | { |
| | 0 | 675 | | AddMediaInfo(mediaSource); |
| | | 676 | | } |
| | | 677 | | else |
| | | 678 | | { |
| | | 679 | | // hack - these two values were taken from LiveTVMediaSourceProvider |
| | 0 | 680 | | string cacheKey = request.OpenToken; |
| | | 681 | | |
| | 0 | 682 | | await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths) |
| | 0 | 683 | | .AddMediaInfoWithProbe(mediaSource, false, cacheKey, true, cancellationToken) |
| | 0 | 684 | | .ConfigureAwait(false); |
| | | 685 | | } |
| | 0 | 686 | | } |
| | 0 | 687 | | catch (Exception ex) |
| | | 688 | | { |
| | 0 | 689 | | _logger.LogError(ex, "Error probing live tv stream"); |
| | 0 | 690 | | AddMediaInfo(mediaSource); |
| | 0 | 691 | | } |
| | | 692 | | |
| | | 693 | | // TODO: @bond Fix |
| | 0 | 694 | | var json = JsonSerializer.SerializeToUtf8Bytes(mediaSource, _jsonOptions); |
| | 0 | 695 | | _logger.LogInformation("Live stream opened: {@MediaSource}", mediaSource); |
| | 0 | 696 | | var clone = JsonSerializer.Deserialize<MediaSourceInfo>(json, _jsonOptions); |
| | | 697 | | |
| | 0 | 698 | | if (!request.UserId.IsEmpty()) |
| | | 699 | | { |
| | 0 | 700 | | var user = _userManager.GetUserById(request.UserId); |
| | 0 | 701 | | var item = request.ItemId.IsEmpty() |
| | 0 | 702 | | ? null |
| | 0 | 703 | | : _libraryManager.GetItemById(request.ItemId); |
| | 0 | 704 | | SetDefaultAudioAndSubtitleStreamIndices(item, clone, user); |
| | | 705 | | } |
| | | 706 | | |
| | 0 | 707 | | return new Tuple<LiveStreamResponse, IDirectStreamProvider>(new LiveStreamResponse(clone), liveStream as IDi |
| | 0 | 708 | | } |
| | | 709 | | |
| | | 710 | | private static void AddMediaInfo(MediaSourceInfo mediaSource) |
| | | 711 | | { |
| | 0 | 712 | | mediaSource.DefaultSubtitleStreamIndex = null; |
| | | 713 | | |
| | | 714 | | // Null this out so that it will be treated like a live stream |
| | 0 | 715 | | if (mediaSource.IsInfiniteStream) |
| | | 716 | | { |
| | 0 | 717 | | mediaSource.RunTimeTicks = null; |
| | | 718 | | } |
| | | 719 | | |
| | 0 | 720 | | var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio); |
| | | 721 | | |
| | 0 | 722 | | if (audioStream is null || audioStream.Index == -1) |
| | | 723 | | { |
| | 0 | 724 | | mediaSource.DefaultAudioStreamIndex = null; |
| | | 725 | | } |
| | | 726 | | else |
| | | 727 | | { |
| | 0 | 728 | | mediaSource.DefaultAudioStreamIndex = audioStream.Index; |
| | | 729 | | } |
| | | 730 | | |
| | 0 | 731 | | var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video); |
| | 0 | 732 | | if (videoStream is not null) |
| | | 733 | | { |
| | 0 | 734 | | if (!videoStream.BitRate.HasValue) |
| | | 735 | | { |
| | 0 | 736 | | var width = videoStream.Width ?? 1920; |
| | | 737 | | |
| | 0 | 738 | | if (width >= 3000) |
| | | 739 | | { |
| | 0 | 740 | | videoStream.BitRate = 30000000; |
| | | 741 | | } |
| | 0 | 742 | | else if (width >= 1900) |
| | | 743 | | { |
| | 0 | 744 | | videoStream.BitRate = 20000000; |
| | | 745 | | } |
| | 0 | 746 | | else if (width >= 1200) |
| | | 747 | | { |
| | 0 | 748 | | videoStream.BitRate = 8000000; |
| | | 749 | | } |
| | 0 | 750 | | else if (width >= 700) |
| | | 751 | | { |
| | 0 | 752 | | videoStream.BitRate = 2000000; |
| | | 753 | | } |
| | | 754 | | } |
| | | 755 | | } |
| | | 756 | | |
| | | 757 | | // Try to estimate this |
| | 0 | 758 | | mediaSource.InferTotalBitrate(); |
| | 0 | 759 | | } |
| | | 760 | | |
| | | 761 | | public async Task<LiveStreamResponse> OpenLiveStream(LiveStreamRequest request, CancellationToken cancellationTo |
| | | 762 | | { |
| | 0 | 763 | | var result = await OpenLiveStreamInternal(request, cancellationToken).ConfigureAwait(false); |
| | 0 | 764 | | return result.Item1; |
| | 0 | 765 | | } |
| | | 766 | | |
| | | 767 | | public async Task<MediaSourceInfo> GetLiveStreamMediaInfo(string id, CancellationToken cancellationToken) |
| | | 768 | | { |
| | | 769 | | // TODO probably shouldn't throw here but it is kept for "backwards compatibility" |
| | 0 | 770 | | var liveStreamInfo = GetLiveStreamInfo(id) ?? throw new ResourceNotFoundException(); |
| | | 771 | | |
| | 0 | 772 | | var mediaSource = liveStreamInfo.MediaSource; |
| | | 773 | | |
| | 0 | 774 | | if (liveStreamInfo is IDirectStreamProvider) |
| | | 775 | | { |
| | 0 | 776 | | var info = await _mediaEncoder.GetMediaInfo( |
| | 0 | 777 | | new MediaInfoRequest |
| | 0 | 778 | | { |
| | 0 | 779 | | MediaSource = mediaSource, |
| | 0 | 780 | | ExtractChapters = false, |
| | 0 | 781 | | MediaType = DlnaProfileType.Video |
| | 0 | 782 | | }, |
| | 0 | 783 | | cancellationToken).ConfigureAwait(false); |
| | | 784 | | |
| | 0 | 785 | | mediaSource.MediaStreams = info.MediaStreams; |
| | 0 | 786 | | mediaSource.Container = info.Container; |
| | 0 | 787 | | mediaSource.Bitrate = info.Bitrate; |
| | | 788 | | } |
| | | 789 | | |
| | 0 | 790 | | return mediaSource; |
| | 0 | 791 | | } |
| | | 792 | | |
| | | 793 | | public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string cacheKey, bool addProb |
| | | 794 | | { |
| | 0 | 795 | | var originalRuntime = mediaSource.RunTimeTicks; |
| | | 796 | | |
| | 0 | 797 | | var now = DateTime.UtcNow; |
| | | 798 | | |
| | 0 | 799 | | MediaInfo mediaInfo = null; |
| | 0 | 800 | | var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", c |
| | | 801 | | |
| | 0 | 802 | | if (!string.IsNullOrEmpty(cacheKey)) |
| | | 803 | | { |
| | 0 | 804 | | FileStream jsonStream = AsyncFile.OpenRead(cacheFilePath); |
| | | 805 | | try |
| | | 806 | | { |
| | 0 | 807 | | mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationT |
| | 0 | 808 | | } |
| | 0 | 809 | | catch (Exception ex) |
| | | 810 | | { |
| | 0 | 811 | | _logger.LogDebug(ex, "Error parsing cached media info."); |
| | 0 | 812 | | } |
| | | 813 | | finally |
| | | 814 | | { |
| | 0 | 815 | | await jsonStream.DisposeAsync().ConfigureAwait(false); |
| | | 816 | | } |
| | 0 | 817 | | } |
| | | 818 | | |
| | 0 | 819 | | if (mediaInfo is null) |
| | | 820 | | { |
| | 0 | 821 | | if (addProbeDelay) |
| | | 822 | | { |
| | 0 | 823 | | var delayMs = mediaSource.AnalyzeDurationMs ?? 0; |
| | 0 | 824 | | delayMs = Math.Max(3000, delayMs); |
| | 0 | 825 | | await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); |
| | | 826 | | } |
| | | 827 | | |
| | 0 | 828 | | if (isLiveStream) |
| | | 829 | | { |
| | 0 | 830 | | mediaSource.AnalyzeDurationMs = 3000; |
| | | 831 | | } |
| | | 832 | | |
| | 0 | 833 | | mediaInfo = await _mediaEncoder.GetMediaInfo( |
| | 0 | 834 | | new MediaInfoRequest |
| | 0 | 835 | | { |
| | 0 | 836 | | MediaSource = mediaSource, |
| | 0 | 837 | | MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video, |
| | 0 | 838 | | ExtractChapters = false |
| | 0 | 839 | | }, |
| | 0 | 840 | | cancellationToken).ConfigureAwait(false); |
| | | 841 | | |
| | 0 | 842 | | if (cacheFilePath is not null) |
| | | 843 | | { |
| | 0 | 844 | | Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath)); |
| | 0 | 845 | | FileStream createStream = AsyncFile.Create(cacheFilePath); |
| | 0 | 846 | | await using (createStream.ConfigureAwait(false)) |
| | | 847 | | { |
| | 0 | 848 | | await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).Co |
| | | 849 | | } |
| | | 850 | | |
| | | 851 | | // _logger.LogDebug("Saved media info to {0}", cacheFilePath); |
| | | 852 | | } |
| | | 853 | | } |
| | | 854 | | |
| | 0 | 855 | | var mediaStreams = mediaInfo.MediaStreams; |
| | | 856 | | |
| | 0 | 857 | | if (isLiveStream && !string.IsNullOrEmpty(cacheKey)) |
| | | 858 | | { |
| | 0 | 859 | | var newList = new List<MediaStream>(); |
| | 0 | 860 | | newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Video).Take(1)); |
| | 0 | 861 | | newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Take(1)); |
| | | 862 | | |
| | 0 | 863 | | foreach (var stream in newList) |
| | | 864 | | { |
| | 0 | 865 | | stream.Index = -1; |
| | 0 | 866 | | stream.Language = null; |
| | | 867 | | } |
| | | 868 | | |
| | 0 | 869 | | mediaStreams = newList; |
| | | 870 | | } |
| | | 871 | | |
| | 0 | 872 | | _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToS |
| | | 873 | | |
| | 0 | 874 | | mediaSource.Bitrate = mediaInfo.Bitrate; |
| | 0 | 875 | | mediaSource.Container = mediaInfo.Container; |
| | 0 | 876 | | mediaSource.Formats = mediaInfo.Formats; |
| | 0 | 877 | | mediaSource.MediaStreams = mediaStreams; |
| | 0 | 878 | | mediaSource.RunTimeTicks = mediaInfo.RunTimeTicks; |
| | 0 | 879 | | mediaSource.Size = mediaInfo.Size; |
| | 0 | 880 | | mediaSource.Timestamp = mediaInfo.Timestamp; |
| | 0 | 881 | | mediaSource.Video3DFormat = mediaInfo.Video3DFormat; |
| | 0 | 882 | | mediaSource.VideoType = mediaInfo.VideoType; |
| | | 883 | | |
| | 0 | 884 | | mediaSource.DefaultSubtitleStreamIndex = null; |
| | | 885 | | |
| | 0 | 886 | | if (isLiveStream) |
| | | 887 | | { |
| | | 888 | | // Null this out so that it will be treated like a live stream |
| | 0 | 889 | | if (!originalRuntime.HasValue) |
| | | 890 | | { |
| | 0 | 891 | | mediaSource.RunTimeTicks = null; |
| | | 892 | | } |
| | | 893 | | } |
| | | 894 | | |
| | 0 | 895 | | var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio); |
| | | 896 | | |
| | 0 | 897 | | if (audioStream is null || audioStream.Index == -1) |
| | | 898 | | { |
| | 0 | 899 | | mediaSource.DefaultAudioStreamIndex = null; |
| | | 900 | | } |
| | | 901 | | else |
| | | 902 | | { |
| | 0 | 903 | | mediaSource.DefaultAudioStreamIndex = audioStream.Index; |
| | | 904 | | } |
| | | 905 | | |
| | 0 | 906 | | var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video); |
| | 0 | 907 | | if (videoStream is not null) |
| | | 908 | | { |
| | 0 | 909 | | if (!videoStream.BitRate.HasValue) |
| | | 910 | | { |
| | 0 | 911 | | var width = videoStream.Width ?? 1920; |
| | | 912 | | |
| | 0 | 913 | | if (width >= 3000) |
| | | 914 | | { |
| | 0 | 915 | | videoStream.BitRate = 30000000; |
| | | 916 | | } |
| | 0 | 917 | | else if (width >= 1900) |
| | | 918 | | { |
| | 0 | 919 | | videoStream.BitRate = 20000000; |
| | | 920 | | } |
| | 0 | 921 | | else if (width >= 1200) |
| | | 922 | | { |
| | 0 | 923 | | videoStream.BitRate = 8000000; |
| | | 924 | | } |
| | 0 | 925 | | else if (width >= 700) |
| | | 926 | | { |
| | 0 | 927 | | videoStream.BitRate = 2000000; |
| | | 928 | | } |
| | | 929 | | } |
| | | 930 | | |
| | | 931 | | // This is coming up false and preventing stream copy |
| | 0 | 932 | | videoStream.IsAVC = null; |
| | | 933 | | } |
| | | 934 | | |
| | 0 | 935 | | if (isLiveStream) |
| | | 936 | | { |
| | 0 | 937 | | mediaSource.AnalyzeDurationMs = 3000; |
| | | 938 | | } |
| | | 939 | | |
| | | 940 | | // Try to estimate this |
| | 0 | 941 | | mediaSource.InferTotalBitrate(true); |
| | 0 | 942 | | } |
| | | 943 | | |
| | | 944 | | public Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetLiveStreamWithDirectStreamProvider(string id, Canc |
| | | 945 | | { |
| | 0 | 946 | | ArgumentException.ThrowIfNullOrEmpty(id); |
| | | 947 | | |
| | 0 | 948 | | var info = GetLiveStreamInfo(id); |
| | 0 | 949 | | if (info is null) |
| | | 950 | | { |
| | 0 | 951 | | return Task.FromResult<Tuple<MediaSourceInfo, IDirectStreamProvider>>(new Tuple<MediaSourceInfo, IDirect |
| | | 952 | | } |
| | | 953 | | |
| | 0 | 954 | | return Task.FromResult<Tuple<MediaSourceInfo, IDirectStreamProvider>>(new Tuple<MediaSourceInfo, IDirectStre |
| | | 955 | | } |
| | | 956 | | |
| | | 957 | | public ILiveStream GetLiveStreamInfo(string id) |
| | | 958 | | { |
| | 0 | 959 | | ArgumentException.ThrowIfNullOrEmpty(id); |
| | | 960 | | |
| | 0 | 961 | | if (_openStreams.TryGetValue(id, out ILiveStream info)) |
| | | 962 | | { |
| | 0 | 963 | | return info; |
| | | 964 | | } |
| | | 965 | | |
| | 0 | 966 | | return null; |
| | | 967 | | } |
| | | 968 | | |
| | | 969 | | /// <inheritdoc /> |
| | | 970 | | public ILiveStream GetLiveStreamInfoByUniqueId(string uniqueId) |
| | | 971 | | { |
| | 0 | 972 | | return _openStreams.Values.FirstOrDefault(stream => string.Equals(uniqueId, stream?.UniqueId, StringComparis |
| | | 973 | | } |
| | | 974 | | |
| | | 975 | | public async Task<MediaSourceInfo> GetLiveStream(string id, CancellationToken cancellationToken) |
| | | 976 | | { |
| | 0 | 977 | | var result = await GetLiveStreamWithDirectStreamProvider(id, cancellationToken).ConfigureAwait(false); |
| | 0 | 978 | | return result.Item1; |
| | 0 | 979 | | } |
| | | 980 | | |
| | | 981 | | public async Task<IReadOnlyList<MediaSourceInfo>> GetRecordingStreamMediaSources(ActiveRecordingInfo info, Cance |
| | | 982 | | { |
| | 0 | 983 | | var stream = new MediaSourceInfo |
| | 0 | 984 | | { |
| | 0 | 985 | | EncoderPath = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveRecordings/" + info.Id + "/stream", |
| | 0 | 986 | | EncoderProtocol = MediaProtocol.Http, |
| | 0 | 987 | | Path = info.Path, |
| | 0 | 988 | | Protocol = MediaProtocol.File, |
| | 0 | 989 | | Id = info.Id, |
| | 0 | 990 | | SupportsDirectPlay = false, |
| | 0 | 991 | | SupportsDirectStream = true, |
| | 0 | 992 | | SupportsTranscoding = true, |
| | 0 | 993 | | IsInfiniteStream = true, |
| | 0 | 994 | | RequiresOpening = false, |
| | 0 | 995 | | RequiresClosing = false, |
| | 0 | 996 | | BufferMs = 0, |
| | 0 | 997 | | IgnoreDts = true, |
| | 0 | 998 | | IgnoreIndex = true |
| | 0 | 999 | | }; |
| | | 1000 | | |
| | 0 | 1001 | | await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths) |
| | 0 | 1002 | | .AddMediaInfoWithProbe(stream, false, false, cancellationToken).ConfigureAwait(false); |
| | | 1003 | | |
| | 0 | 1004 | | return [stream]; |
| | 0 | 1005 | | } |
| | | 1006 | | |
| | | 1007 | | public async Task CloseLiveStream(string id) |
| | | 1008 | | { |
| | 0 | 1009 | | ArgumentException.ThrowIfNullOrEmpty(id); |
| | | 1010 | | |
| | 0 | 1011 | | using (await _liveStreamLocker.LockAsync().ConfigureAwait(false)) |
| | | 1012 | | { |
| | 0 | 1013 | | if (_openStreams.TryGetValue(id, out ILiveStream liveStream)) |
| | | 1014 | | { |
| | 0 | 1015 | | liveStream.ConsumerCount--; |
| | | 1016 | | |
| | 0 | 1017 | | _logger.LogInformation("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liv |
| | | 1018 | | |
| | 0 | 1019 | | if (liveStream.ConsumerCount <= 0) |
| | | 1020 | | { |
| | 0 | 1021 | | _openStreams.TryRemove(id, out _); |
| | | 1022 | | |
| | 0 | 1023 | | _logger.LogInformation("Closing live stream {0}", id); |
| | | 1024 | | |
| | 0 | 1025 | | await liveStream.Close().ConfigureAwait(false); |
| | 0 | 1026 | | _logger.LogInformation("Live stream {0} closed successfully", id); |
| | | 1027 | | } |
| | | 1028 | | } |
| | 0 | 1029 | | } |
| | 0 | 1030 | | } |
| | | 1031 | | |
| | | 1032 | | private (IMediaSourceProvider MediaSourceProvider, string KeyId) GetProvider(string key) |
| | | 1033 | | { |
| | 0 | 1034 | | ArgumentException.ThrowIfNullOrEmpty(key); |
| | | 1035 | | |
| | 0 | 1036 | | var keys = key.Split(LiveStreamIdDelimiter, 2); |
| | | 1037 | | |
| | 0 | 1038 | | var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", Cult |
| | | 1039 | | |
| | 0 | 1040 | | var splitIndex = key.IndexOf(LiveStreamIdDelimiter, StringComparison.Ordinal); |
| | 0 | 1041 | | var keyId = key.Substring(splitIndex + 1); |
| | | 1042 | | |
| | 0 | 1043 | | return (provider, keyId); |
| | | 1044 | | } |
| | | 1045 | | |
| | | 1046 | | /// <inheritdoc /> |
| | | 1047 | | public void Dispose() |
| | | 1048 | | { |
| | 27 | 1049 | | Dispose(true); |
| | 27 | 1050 | | GC.SuppressFinalize(this); |
| | 27 | 1051 | | } |
| | | 1052 | | |
| | | 1053 | | /// <summary> |
| | | 1054 | | /// Releases unmanaged and - optionally - managed resources. |
| | | 1055 | | /// </summary> |
| | | 1056 | | /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o |
| | | 1057 | | protected virtual void Dispose(bool dispose) |
| | | 1058 | | { |
| | 27 | 1059 | | if (dispose) |
| | | 1060 | | { |
| | 54 | 1061 | | foreach (var key in _openStreams.Keys.ToList()) |
| | | 1062 | | { |
| | 0 | 1063 | | CloseLiveStream(key).GetAwaiter().GetResult(); |
| | | 1064 | | } |
| | | 1065 | | |
| | 27 | 1066 | | _liveStreamLocker.Dispose(); |
| | | 1067 | | } |
| | 27 | 1068 | | } |
| | | 1069 | | } |
| | | 1070 | | } |