< Summary - Jellyfin

Information
Class: Emby.Server.Implementations.Library.MediaSourceManager
Assembly: Emby.Server.Implementations
File(s): /srv/git/jellyfin/Emby.Server.Implementations/Library/MediaSourceManager.cs
Line coverage
18%
Covered lines: 35
Uncovered lines: 155
Coverable lines: 190
Total lines: 909
Line coverage: 18.4%
Branch coverage
10%
Covered branches: 12
Total branches: 114
Branch coverage: 10.5%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Coverage history

Coverage history 0 25 50 75 100

Metrics

File(s)

/srv/git/jellyfin/Emby.Server.Implementations/Library/MediaSourceManager.cs

#LineLine coverage
 1#nullable disable
 2
 3#pragma warning disable CS1591
 4
 5using System;
 6using System.Collections.Concurrent;
 7using System.Collections.Generic;
 8using System.Collections.Immutable;
 9using System.Globalization;
 10using System.IO;
 11using System.Linq;
 12using System.Text.Json;
 13using System.Threading;
 14using System.Threading.Tasks;
 15using AsyncKeyedLock;
 16using Jellyfin.Data;
 17using Jellyfin.Data.Enums;
 18using Jellyfin.Database.Implementations.Entities;
 19using Jellyfin.Database.Implementations.Enums;
 20using Jellyfin.Extensions;
 21using Jellyfin.Extensions.Json;
 22using MediaBrowser.Common.Configuration;
 23using MediaBrowser.Common.Extensions;
 24using MediaBrowser.Controller;
 25using MediaBrowser.Controller.Entities;
 26using MediaBrowser.Controller.Library;
 27using MediaBrowser.Controller.LiveTv;
 28using MediaBrowser.Controller.MediaEncoding;
 29using MediaBrowser.Controller.Persistence;
 30using MediaBrowser.Controller.Providers;
 31using MediaBrowser.Model.Dlna;
 32using MediaBrowser.Model.Dto;
 33using MediaBrowser.Model.Entities;
 34using MediaBrowser.Model.Globalization;
 35using MediaBrowser.Model.IO;
 36using MediaBrowser.Model.MediaInfo;
 37using Microsoft.Extensions.Logging;
 38
 39namespace Emby.Server.Implementations.Library
 40{
 41    public class MediaSourceManager : IMediaSourceManager, IDisposable
 42    {
 43        // Do not use a pipe here because Roku http requests to the server will fail, without any explicit error message
 44        private const char LiveStreamIdDelimiter = '_';
 45
 46        private readonly IServerApplicationHost _appHost;
 47        private readonly IItemRepository _itemRepo;
 48        private readonly IUserManager _userManager;
 49        private readonly ILibraryManager _libraryManager;
 50        private readonly IFileSystem _fileSystem;
 51        private readonly ILogger<MediaSourceManager> _logger;
 52        private readonly IUserDataManager _userDataManager;
 53        private readonly IMediaEncoder _mediaEncoder;
 54        private readonly ILocalizationManager _localizationManager;
 55        private readonly IApplicationPaths _appPaths;
 56        private readonly IDirectoryService _directoryService;
 57        private readonly IMediaStreamRepository _mediaStreamRepository;
 58        private readonly IMediaAttachmentRepository _mediaAttachmentRepository;
 2759        private readonly ConcurrentDictionary<string, ILiveStream> _openStreams = new ConcurrentDictionary<string, ILive
 2760        private readonly AsyncNonKeyedLocker _liveStreamLocker = new(1);
 2761        private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
 62
 63        private IMediaSourceProvider[] _providers;
 64
 65        public MediaSourceManager(
 66            IServerApplicationHost appHost,
 67            IItemRepository itemRepo,
 68            IApplicationPaths applicationPaths,
 69            ILocalizationManager localizationManager,
 70            IUserManager userManager,
 71            ILibraryManager libraryManager,
 72            ILogger<MediaSourceManager> logger,
 73            IFileSystem fileSystem,
 74            IUserDataManager userDataManager,
 75            IMediaEncoder mediaEncoder,
 76            IDirectoryService directoryService,
 77            IMediaStreamRepository mediaStreamRepository,
 78            IMediaAttachmentRepository mediaAttachmentRepository)
 79        {
 2780            _appHost = appHost;
 2781            _itemRepo = itemRepo;
 2782            _userManager = userManager;
 2783            _libraryManager = libraryManager;
 2784            _logger = logger;
 2785            _fileSystem = fileSystem;
 2786            _userDataManager = userDataManager;
 2787            _mediaEncoder = mediaEncoder;
 2788            _localizationManager = localizationManager;
 2789            _appPaths = applicationPaths;
 2790            _directoryService = directoryService;
 2791            _mediaStreamRepository = mediaStreamRepository;
 2792            _mediaAttachmentRepository = mediaAttachmentRepository;
 2793        }
 94
 95        public void AddParts(IEnumerable<IMediaSourceProvider> providers)
 96        {
 2197            _providers = providers.ToArray();
 2198        }
 99
 100        public IReadOnlyList<MediaStream> GetMediaStreams(MediaStreamQuery query)
 101        {
 0102            var list = _mediaStreamRepository.GetMediaStreams(query);
 103
 0104            foreach (var stream in list)
 105            {
 0106                stream.SupportsExternalStream = StreamSupportsExternalStream(stream);
 107            }
 108
 0109            return list;
 110        }
 111
 112        private static bool StreamSupportsExternalStream(MediaStream stream)
 113        {
 0114            if (stream.IsExternal)
 115            {
 0116                return true;
 117            }
 118
 0119            if (stream.IsTextSubtitleStream)
 120            {
 0121                return true;
 122            }
 123
 0124            if (stream.IsPgsSubtitleStream)
 125            {
 0126                return true;
 127            }
 128
 0129            return false;
 130        }
 131
 132        public IReadOnlyList<MediaStream> GetMediaStreams(Guid itemId)
 133        {
 0134            var list = GetMediaStreams(new MediaStreamQuery
 0135            {
 0136                ItemId = itemId
 0137            });
 138
 0139            return GetMediaStreamsForItem(list);
 140        }
 141
 142        private IReadOnlyList<MediaStream> GetMediaStreamsForItem(IReadOnlyList<MediaStream> streams)
 143        {
 0144            foreach (var stream in streams)
 145            {
 0146                if (stream.Type == MediaStreamType.Subtitle)
 147                {
 0148                    stream.SupportsExternalStream = StreamSupportsExternalStream(stream);
 149                }
 150            }
 151
 0152            return streams;
 153        }
 154
 155        /// <inheritdoc />
 156        public IReadOnlyList<MediaAttachment> GetMediaAttachments(MediaAttachmentQuery query)
 157        {
 0158            return _mediaAttachmentRepository.GetMediaAttachments(query);
 159        }
 160
 161        /// <inheritdoc />
 162        public IReadOnlyList<MediaAttachment> GetMediaAttachments(Guid itemId)
 163        {
 0164            return GetMediaAttachments(new MediaAttachmentQuery
 0165            {
 0166                ItemId = itemId
 0167            });
 168        }
 169
 170        public async Task<IReadOnlyList<MediaSourceInfo>> GetPlaybackMediaSources(BaseItem item, User user, bool allowMe
 171        {
 172            var mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user);
 173
 174            // If file is strm or main media stream is missing, force a metadata refresh with remote probing
 175            if (allowMediaProbe && mediaSources[0].Type != MediaSourceType.Placeholder
 176                && (item.Path.EndsWith(".strm", StringComparison.OrdinalIgnoreCase)
 177                    || (item.MediaType == MediaType.Video && mediaSources[0].MediaStreams.All(i => i.Type != MediaStream
 178                    || (item.MediaType == MediaType.Audio && mediaSources[0].MediaStreams.All(i => i.Type != MediaStream
 179            {
 180                await item.RefreshMetadata(
 181                    new MetadataRefreshOptions(_directoryService)
 182                    {
 183                        EnableRemoteContentProbe = true,
 184                        MetadataRefreshMode = MetadataRefreshMode.FullRefresh
 185                    },
 186                    cancellationToken).ConfigureAwait(false);
 187
 188                mediaSources = GetStaticMediaSources(item, enablePathSubstitution, user);
 189            }
 190
 191            var dynamicMediaSources = await GetDynamicMediaSources(item, cancellationToken).ConfigureAwait(false);
 192
 193            var list = new List<MediaSourceInfo>();
 194
 195            list.AddRange(mediaSources);
 196
 197            foreach (var source in dynamicMediaSources)
 198            {
 199                // Validate that this is actually possible
 200                if (source.SupportsDirectStream)
 201                {
 202                    source.SupportsDirectStream = SupportsDirectStream(source.Path, source.Protocol);
 203                }
 204
 205                if (user is not null)
 206                {
 207                    SetDefaultAudioAndSubtitleStreamIndices(item, source, user);
 208
 209                    if (item.MediaType == MediaType.Audio)
 210                    {
 211                        source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding);
 212                    }
 213                    else if (item.MediaType == MediaType.Video)
 214                    {
 215                        source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding);
 216                        source.SupportsDirectStream = user.HasPermission(PermissionKind.EnablePlaybackRemuxing);
 217                    }
 218                }
 219
 220                list.Add(source);
 221            }
 222
 223            return SortMediaSources(list).ToArray();
 224        }
 225
 226        /// <inheritdoc />>
 227        public MediaProtocol GetPathProtocol(string path)
 228        {
 2049229            if (path.StartsWith("Rtsp", StringComparison.OrdinalIgnoreCase))
 230            {
 1231                return MediaProtocol.Rtsp;
 232            }
 233
 2048234            if (path.StartsWith("Rtmp", StringComparison.OrdinalIgnoreCase))
 235            {
 0236                return MediaProtocol.Rtmp;
 237            }
 238
 2048239            if (path.StartsWith("Http", StringComparison.OrdinalIgnoreCase))
 240            {
 2241                return MediaProtocol.Http;
 242            }
 243
 2046244            if (path.StartsWith("rtp", StringComparison.OrdinalIgnoreCase))
 245            {
 0246                return MediaProtocol.Rtp;
 247            }
 248
 2046249            if (path.StartsWith("ftp", StringComparison.OrdinalIgnoreCase))
 250            {
 0251                return MediaProtocol.Ftp;
 252            }
 253
 2046254            if (path.StartsWith("udp", StringComparison.OrdinalIgnoreCase))
 255            {
 0256                return MediaProtocol.Udp;
 257            }
 258
 2046259            return _fileSystem.IsPathFile(path) ? MediaProtocol.File : MediaProtocol.Http;
 260        }
 261
 262        public bool SupportsDirectStream(string path, MediaProtocol protocol)
 263        {
 0264            if (protocol == MediaProtocol.File)
 265            {
 0266                return true;
 267            }
 268
 0269            if (protocol == MediaProtocol.Http)
 270            {
 0271                if (path is not null)
 272                {
 0273                    if (path.Contains(".m3u", StringComparison.OrdinalIgnoreCase))
 274                    {
 0275                        return false;
 276                    }
 277
 0278                    return true;
 279                }
 280            }
 281
 0282            return false;
 283        }
 284
 285        private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(BaseItem item, CancellationToken cancell
 286        {
 287            var tasks = _providers.Select(i => GetDynamicMediaSources(item, i, cancellationToken));
 288            var results = await Task.WhenAll(tasks).ConfigureAwait(false);
 289
 290            return results.SelectMany(i => i);
 291        }
 292
 293        private async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(BaseItem item, IMediaSourceProvider prov
 294        {
 295            try
 296            {
 297                var sources = await provider.GetMediaSources(item, cancellationToken).ConfigureAwait(false);
 298                var list = sources.ToList();
 299
 300                foreach (var mediaSource in list)
 301                {
 302                    mediaSource.InferTotalBitrate();
 303
 304                    SetKeyProperties(provider, mediaSource);
 305                }
 306
 307                return list;
 308            }
 309            catch (Exception ex)
 310            {
 311                _logger.LogError(ex, "Error getting media sources");
 312                return [];
 313            }
 314        }
 315
 316        private static void SetKeyProperties(IMediaSourceProvider provider, MediaSourceInfo mediaSource)
 317        {
 0318            var prefix = provider.GetType().FullName.GetMD5().ToString("N", CultureInfo.InvariantCulture) + LiveStreamId
 319
 0320            if (!string.IsNullOrEmpty(mediaSource.OpenToken) && !mediaSource.OpenToken.StartsWith(prefix, StringComparis
 321            {
 0322                mediaSource.OpenToken = prefix + mediaSource.OpenToken;
 323            }
 324
 0325            if (!string.IsNullOrEmpty(mediaSource.LiveStreamId) && !mediaSource.LiveStreamId.StartsWith(prefix, StringCo
 326            {
 0327                mediaSource.LiveStreamId = prefix + mediaSource.LiveStreamId;
 328            }
 0329        }
 330
 331        public async Task<MediaSourceInfo> GetMediaSource(BaseItem item, string mediaSourceId, string liveStreamId, bool
 332        {
 333            if (!string.IsNullOrEmpty(liveStreamId))
 334            {
 335                return await GetLiveStream(liveStreamId, cancellationToken).ConfigureAwait(false);
 336            }
 337
 338            var sources = await GetPlaybackMediaSources(item, null, false, enablePathSubstitution, cancellationToken).Co
 339
 340            return sources.FirstOrDefault(i => string.Equals(i.Id, mediaSourceId, StringComparison.OrdinalIgnoreCase));
 341        }
 342
 343        public IReadOnlyList<MediaSourceInfo> GetStaticMediaSources(BaseItem item, bool enablePathSubstitution, User use
 344        {
 0345            ArgumentNullException.ThrowIfNull(item);
 346
 0347            var hasMediaSources = (IHasMediaSources)item;
 348
 0349            var sources = hasMediaSources.GetMediaSources(enablePathSubstitution);
 350
 0351            if (user is not null)
 352            {
 0353                foreach (var source in sources)
 354                {
 0355                    SetDefaultAudioAndSubtitleStreamIndices(item, source, user);
 356
 0357                    if (item.MediaType == MediaType.Audio)
 358                    {
 0359                        source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableAudioPlaybackTranscoding);
 360                    }
 0361                    else if (item.MediaType == MediaType.Video)
 362                    {
 0363                        source.SupportsTranscoding = user.HasPermission(PermissionKind.EnableVideoPlaybackTranscoding);
 0364                        source.SupportsDirectStream = user.HasPermission(PermissionKind.EnablePlaybackRemuxing);
 365                    }
 366                }
 367            }
 368
 0369            return sources;
 370        }
 371
 372        private IReadOnlyList<string> NormalizeLanguage(string language)
 373        {
 0374            if (string.IsNullOrEmpty(language))
 375            {
 0376                return [];
 377            }
 378
 0379            var culture = _localizationManager.FindLanguageInfo(language);
 0380            if (culture is not null)
 381            {
 0382                return culture.ThreeLetterISOLanguageNames;
 383            }
 384
 0385            return [language];
 386        }
 387
 388        private void SetDefaultSubtitleStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowR
 389        {
 0390            if (userData is not null
 0391                && userData.SubtitleStreamIndex.HasValue
 0392                && user.RememberSubtitleSelections
 0393                && user.SubtitleMode != SubtitlePlaybackMode.None
 0394                && allowRememberingSelection)
 395            {
 0396                var index = userData.SubtitleStreamIndex.Value;
 397                // Make sure the saved index is still valid
 0398                if (index == -1 || source.MediaStreams.Any(i => i.Type == MediaStreamType.Subtitle && i.Index == index))
 399                {
 0400                    source.DefaultSubtitleStreamIndex = index;
 0401                    return;
 402                }
 403            }
 404
 0405            var preferredSubs = NormalizeLanguage(user.SubtitleLanguagePreference);
 406
 0407            var defaultAudioIndex = source.DefaultAudioStreamIndex;
 0408            var audioLanguage = defaultAudioIndex is null
 0409                ? null
 0410                : source.MediaStreams.Where(i => i.Type == MediaStreamType.Audio && i.Index == defaultAudioIndex).Select
 411
 0412            source.DefaultSubtitleStreamIndex = MediaStreamSelector.GetDefaultSubtitleStreamIndex(
 0413                source.MediaStreams,
 0414                preferredSubs,
 0415                user.SubtitleMode,
 0416                audioLanguage);
 417
 0418            MediaStreamSelector.SetSubtitleStreamScores(source.MediaStreams, preferredSubs, user.SubtitleMode, audioLang
 0419        }
 420
 421        private void SetDefaultAudioStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowReme
 422        {
 0423            if (userData is not null && userData.AudioStreamIndex.HasValue && user.RememberAudioSelections && allowRemem
 424            {
 0425                var index = userData.AudioStreamIndex.Value;
 426                // Make sure the saved index is still valid
 0427                if (source.MediaStreams.Any(i => i.Type == MediaStreamType.Audio && i.Index == index))
 428                {
 0429                    source.DefaultAudioStreamIndex = index;
 0430                    return;
 431                }
 432            }
 433
 0434            var preferredAudio = NormalizeLanguage(user.AudioLanguagePreference);
 435
 0436            source.DefaultAudioStreamIndex = MediaStreamSelector.GetDefaultAudioStreamIndex(source.MediaStreams, preferr
 0437        }
 438
 439        public void SetDefaultAudioAndSubtitleStreamIndices(BaseItem item, MediaSourceInfo source, User user)
 440        {
 441            // Item would only be null if the app didn't supply ItemId as part of the live stream open request
 0442            var mediaType = item?.MediaType ?? MediaType.Video;
 443
 0444            if (mediaType == MediaType.Video)
 445            {
 0446                var userData = item is null ? null : _userDataManager.GetUserData(user, item);
 447
 0448                var allowRememberingSelection = item is null || item.EnableRememberingTrackSelections;
 449
 0450                SetDefaultAudioStreamIndex(source, userData, user, allowRememberingSelection);
 0451                SetDefaultSubtitleStreamIndex(source, userData, user, allowRememberingSelection);
 452            }
 0453            else if (mediaType == MediaType.Audio)
 454            {
 0455                var audio = source.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
 456
 0457                if (audio is not null)
 458                {
 0459                    source.DefaultAudioStreamIndex = audio.Index;
 460                }
 461            }
 0462        }
 463
 464        private static IEnumerable<MediaSourceInfo> SortMediaSources(IEnumerable<MediaSourceInfo> sources)
 465        {
 0466            return sources.OrderBy(i =>
 0467            {
 0468                if (i.VideoType.HasValue && i.VideoType.Value == VideoType.VideoFile)
 0469                {
 0470                    return 0;
 0471                }
 0472
 0473                return 1;
 0474            }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
 0475            .ThenByDescending(i =>
 0476            {
 0477                var stream = i.VideoStream;
 0478
 0479                return stream?.Width ?? 0;
 0480            })
 0481            .Where(i => i.Type != MediaSourceType.Placeholder);
 482        }
 483
 484        public async Task<Tuple<LiveStreamResponse, IDirectStreamProvider>> OpenLiveStreamInternal(LiveStreamRequest req
 485        {
 486            MediaSourceInfo mediaSource;
 487            ILiveStream liveStream;
 488
 489            using (await _liveStreamLocker.LockAsync(cancellationToken).ConfigureAwait(false))
 490            {
 491                var (provider, keyId) = GetProvider(request.OpenToken);
 492
 493                var currentLiveStreams = _openStreams.Values.ToList();
 494
 495                liveStream = await provider.OpenMediaSource(keyId, currentLiveStreams, cancellationToken).ConfigureAwait
 496
 497                mediaSource = liveStream.MediaSource;
 498
 499                // Validate that this is actually possible
 500                if (mediaSource.SupportsDirectStream)
 501                {
 502                    mediaSource.SupportsDirectStream = SupportsDirectStream(mediaSource.Path, mediaSource.Protocol);
 503                }
 504
 505                SetKeyProperties(provider, mediaSource);
 506
 507                _openStreams[mediaSource.LiveStreamId] = liveStream;
 508            }
 509
 510            try
 511            {
 512                if (mediaSource.MediaStreams.Any(i => i.Index != -1) || !mediaSource.SupportsProbing)
 513                {
 514                    AddMediaInfo(mediaSource);
 515                }
 516                else
 517                {
 518                    // hack - these two values were taken from LiveTVMediaSourceProvider
 519                    string cacheKey = request.OpenToken;
 520
 521                    await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths)
 522                        .AddMediaInfoWithProbe(mediaSource, false, cacheKey, true, cancellationToken)
 523                        .ConfigureAwait(false);
 524                }
 525            }
 526            catch (Exception ex)
 527            {
 528                _logger.LogError(ex, "Error probing live tv stream");
 529                AddMediaInfo(mediaSource);
 530            }
 531
 532            // TODO: @bond Fix
 533            var json = JsonSerializer.SerializeToUtf8Bytes(mediaSource, _jsonOptions);
 534            _logger.LogInformation("Live stream opened: {@MediaSource}", mediaSource);
 535            var clone = JsonSerializer.Deserialize<MediaSourceInfo>(json, _jsonOptions);
 536
 537            if (!request.UserId.IsEmpty())
 538            {
 539                var user = _userManager.GetUserById(request.UserId);
 540                var item = request.ItemId.IsEmpty()
 541                    ? null
 542                    : _libraryManager.GetItemById(request.ItemId);
 543                SetDefaultAudioAndSubtitleStreamIndices(item, clone, user);
 544            }
 545
 546            return new Tuple<LiveStreamResponse, IDirectStreamProvider>(new LiveStreamResponse(clone), liveStream as IDi
 547        }
 548
 549        private static void AddMediaInfo(MediaSourceInfo mediaSource)
 550        {
 0551            mediaSource.DefaultSubtitleStreamIndex = null;
 552
 553            // Null this out so that it will be treated like a live stream
 0554            if (mediaSource.IsInfiniteStream)
 555            {
 0556                mediaSource.RunTimeTicks = null;
 557            }
 558
 0559            var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
 560
 0561            if (audioStream is null || audioStream.Index == -1)
 562            {
 0563                mediaSource.DefaultAudioStreamIndex = null;
 564            }
 565            else
 566            {
 0567                mediaSource.DefaultAudioStreamIndex = audioStream.Index;
 568            }
 569
 0570            var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
 0571            if (videoStream is not null)
 572            {
 0573                if (!videoStream.BitRate.HasValue)
 574                {
 0575                    var width = videoStream.Width ?? 1920;
 576
 0577                    if (width >= 3000)
 578                    {
 0579                        videoStream.BitRate = 30000000;
 580                    }
 0581                    else if (width >= 1900)
 582                    {
 0583                        videoStream.BitRate = 20000000;
 584                    }
 0585                    else if (width >= 1200)
 586                    {
 0587                        videoStream.BitRate = 8000000;
 588                    }
 0589                    else if (width >= 700)
 590                    {
 0591                        videoStream.BitRate = 2000000;
 592                    }
 593                }
 594            }
 595
 596            // Try to estimate this
 0597            mediaSource.InferTotalBitrate();
 0598        }
 599
 600        public async Task<LiveStreamResponse> OpenLiveStream(LiveStreamRequest request, CancellationToken cancellationTo
 601        {
 602            var result = await OpenLiveStreamInternal(request, cancellationToken).ConfigureAwait(false);
 603            return result.Item1;
 604        }
 605
 606        public async Task<MediaSourceInfo> GetLiveStreamMediaInfo(string id, CancellationToken cancellationToken)
 607        {
 608            // TODO probably shouldn't throw here but it is kept for "backwards compatibility"
 609            var liveStreamInfo = GetLiveStreamInfo(id) ?? throw new ResourceNotFoundException();
 610
 611            var mediaSource = liveStreamInfo.MediaSource;
 612
 613            if (liveStreamInfo is IDirectStreamProvider)
 614            {
 615                var info = await _mediaEncoder.GetMediaInfo(
 616                    new MediaInfoRequest
 617                    {
 618                        MediaSource = mediaSource,
 619                        ExtractChapters = false,
 620                        MediaType = DlnaProfileType.Video
 621                    },
 622                    cancellationToken).ConfigureAwait(false);
 623
 624                mediaSource.MediaStreams = info.MediaStreams;
 625                mediaSource.Container = info.Container;
 626                mediaSource.Bitrate = info.Bitrate;
 627            }
 628
 629            return mediaSource;
 630        }
 631
 632        public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string cacheKey, bool addProb
 633        {
 634            var originalRuntime = mediaSource.RunTimeTicks;
 635
 636            var now = DateTime.UtcNow;
 637
 638            MediaInfo mediaInfo = null;
 639            var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", c
 640
 641            if (!string.IsNullOrEmpty(cacheKey))
 642            {
 643                FileStream jsonStream = AsyncFile.OpenRead(cacheFilePath);
 644                try
 645                {
 646                    mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationT
 647                }
 648                catch (Exception ex)
 649                {
 650                    _logger.LogDebug(ex, "_jsonSerializer.DeserializeFromFile threw an exception.");
 651                }
 652                finally
 653                {
 654                    await jsonStream.DisposeAsync().ConfigureAwait(false);
 655                }
 656            }
 657
 658            if (mediaInfo is null)
 659            {
 660                if (addProbeDelay)
 661                {
 662                    var delayMs = mediaSource.AnalyzeDurationMs ?? 0;
 663                    delayMs = Math.Max(3000, delayMs);
 664                    await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);
 665                }
 666
 667                if (isLiveStream)
 668                {
 669                    mediaSource.AnalyzeDurationMs = 3000;
 670                }
 671
 672                mediaInfo = await _mediaEncoder.GetMediaInfo(
 673                    new MediaInfoRequest
 674                {
 675                    MediaSource = mediaSource,
 676                    MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
 677                    ExtractChapters = false
 678                },
 679                    cancellationToken).ConfigureAwait(false);
 680
 681                if (cacheFilePath is not null)
 682                {
 683                    Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
 684                    FileStream createStream = File.Create(cacheFilePath);
 685                    await using (createStream.ConfigureAwait(false))
 686                    {
 687                        await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).Co
 688                    }
 689
 690                    // _logger.LogDebug("Saved media info to {0}", cacheFilePath);
 691                }
 692            }
 693
 694            var mediaStreams = mediaInfo.MediaStreams;
 695
 696            if (isLiveStream && !string.IsNullOrEmpty(cacheKey))
 697            {
 698                var newList = new List<MediaStream>();
 699                newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Video).Take(1));
 700                newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Take(1));
 701
 702                foreach (var stream in newList)
 703                {
 704                    stream.Index = -1;
 705                    stream.Language = null;
 706                }
 707
 708                mediaStreams = newList;
 709            }
 710
 711            _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToS
 712
 713            mediaSource.Bitrate = mediaInfo.Bitrate;
 714            mediaSource.Container = mediaInfo.Container;
 715            mediaSource.Formats = mediaInfo.Formats;
 716            mediaSource.MediaStreams = mediaStreams;
 717            mediaSource.RunTimeTicks = mediaInfo.RunTimeTicks;
 718            mediaSource.Size = mediaInfo.Size;
 719            mediaSource.Timestamp = mediaInfo.Timestamp;
 720            mediaSource.Video3DFormat = mediaInfo.Video3DFormat;
 721            mediaSource.VideoType = mediaInfo.VideoType;
 722
 723            mediaSource.DefaultSubtitleStreamIndex = null;
 724
 725            if (isLiveStream)
 726            {
 727                // Null this out so that it will be treated like a live stream
 728                if (!originalRuntime.HasValue)
 729                {
 730                    mediaSource.RunTimeTicks = null;
 731                }
 732            }
 733
 734            var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
 735
 736            if (audioStream is null || audioStream.Index == -1)
 737            {
 738                mediaSource.DefaultAudioStreamIndex = null;
 739            }
 740            else
 741            {
 742                mediaSource.DefaultAudioStreamIndex = audioStream.Index;
 743            }
 744
 745            var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
 746            if (videoStream is not null)
 747            {
 748                if (!videoStream.BitRate.HasValue)
 749                {
 750                    var width = videoStream.Width ?? 1920;
 751
 752                    if (width >= 3000)
 753                    {
 754                        videoStream.BitRate = 30000000;
 755                    }
 756                    else if (width >= 1900)
 757                    {
 758                        videoStream.BitRate = 20000000;
 759                    }
 760                    else if (width >= 1200)
 761                    {
 762                        videoStream.BitRate = 8000000;
 763                    }
 764                    else if (width >= 700)
 765                    {
 766                        videoStream.BitRate = 2000000;
 767                    }
 768                }
 769
 770                // This is coming up false and preventing stream copy
 771                videoStream.IsAVC = null;
 772            }
 773
 774            if (isLiveStream)
 775            {
 776                mediaSource.AnalyzeDurationMs = 3000;
 777            }
 778
 779            // Try to estimate this
 780            mediaSource.InferTotalBitrate(true);
 781        }
 782
 783        public Task<Tuple<MediaSourceInfo, IDirectStreamProvider>> GetLiveStreamWithDirectStreamProvider(string id, Canc
 784        {
 0785            ArgumentException.ThrowIfNullOrEmpty(id);
 786
 0787            var info = GetLiveStreamInfo(id);
 0788            if (info is null)
 789            {
 0790                return Task.FromResult<Tuple<MediaSourceInfo, IDirectStreamProvider>>(new Tuple<MediaSourceInfo, IDirect
 791            }
 792
 0793            return Task.FromResult<Tuple<MediaSourceInfo, IDirectStreamProvider>>(new Tuple<MediaSourceInfo, IDirectStre
 794        }
 795
 796        public ILiveStream GetLiveStreamInfo(string id)
 797        {
 0798            ArgumentException.ThrowIfNullOrEmpty(id);
 799
 0800            if (_openStreams.TryGetValue(id, out ILiveStream info))
 801            {
 0802                return info;
 803            }
 804
 0805            return null;
 806        }
 807
 808        /// <inheritdoc />
 809        public ILiveStream GetLiveStreamInfoByUniqueId(string uniqueId)
 810        {
 0811            return _openStreams.Values.FirstOrDefault(stream => string.Equals(uniqueId, stream?.UniqueId, StringComparis
 812        }
 813
 814        public async Task<MediaSourceInfo> GetLiveStream(string id, CancellationToken cancellationToken)
 815        {
 816            var result = await GetLiveStreamWithDirectStreamProvider(id, cancellationToken).ConfigureAwait(false);
 817            return result.Item1;
 818        }
 819
 820        public async Task<IReadOnlyList<MediaSourceInfo>> GetRecordingStreamMediaSources(ActiveRecordingInfo info, Cance
 821        {
 822            var stream = new MediaSourceInfo
 823            {
 824                EncoderPath = _appHost.GetApiUrlForLocalAccess() + "/LiveTv/LiveRecordings/" + info.Id + "/stream",
 825                EncoderProtocol = MediaProtocol.Http,
 826                Path = info.Path,
 827                Protocol = MediaProtocol.File,
 828                Id = info.Id,
 829                SupportsDirectPlay = false,
 830                SupportsDirectStream = true,
 831                SupportsTranscoding = true,
 832                IsInfiniteStream = true,
 833                RequiresOpening = false,
 834                RequiresClosing = false,
 835                BufferMs = 0,
 836                IgnoreDts = true,
 837                IgnoreIndex = true
 838            };
 839
 840            await new LiveStreamHelper(_mediaEncoder, _logger, _appPaths)
 841                .AddMediaInfoWithProbe(stream, false, false, cancellationToken).ConfigureAwait(false);
 842
 843            return [stream];
 844        }
 845
 846        public async Task CloseLiveStream(string id)
 847        {
 848            ArgumentException.ThrowIfNullOrEmpty(id);
 849
 850            using (await _liveStreamLocker.LockAsync().ConfigureAwait(false))
 851            {
 852                if (_openStreams.TryGetValue(id, out ILiveStream liveStream))
 853                {
 854                    liveStream.ConsumerCount--;
 855
 856                    _logger.LogInformation("Live stream {0} consumer count is now {1}", liveStream.OriginalStreamId, liv
 857
 858                    if (liveStream.ConsumerCount <= 0)
 859                    {
 860                        _openStreams.TryRemove(id, out _);
 861
 862                        _logger.LogInformation("Closing live stream {0}", id);
 863
 864                        await liveStream.Close().ConfigureAwait(false);
 865                        _logger.LogInformation("Live stream {0} closed successfully", id);
 866                    }
 867                }
 868            }
 869        }
 870
 871        private (IMediaSourceProvider MediaSourceProvider, string KeyId) GetProvider(string key)
 872        {
 0873            ArgumentException.ThrowIfNullOrEmpty(key);
 874
 0875            var keys = key.Split(LiveStreamIdDelimiter, 2);
 876
 0877            var provider = _providers.FirstOrDefault(i => string.Equals(i.GetType().FullName.GetMD5().ToString("N", Cult
 878
 0879            var splitIndex = key.IndexOf(LiveStreamIdDelimiter, StringComparison.Ordinal);
 0880            var keyId = key.Substring(splitIndex + 1);
 881
 0882            return (provider, keyId);
 883        }
 884
 885        /// <inheritdoc />
 886        public void Dispose()
 887        {
 21888            Dispose(true);
 21889            GC.SuppressFinalize(this);
 21890        }
 891
 892        /// <summary>
 893        /// Releases unmanaged and - optionally - managed resources.
 894        /// </summary>
 895        /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release o
 896        protected virtual void Dispose(bool dispose)
 897        {
 21898            if (dispose)
 899            {
 42900                foreach (var key in _openStreams.Keys.ToList())
 901                {
 0902                    CloseLiveStream(key).GetAwaiter().GetResult();
 903                }
 904
 21905                _liveStreamLocker.Dispose();
 906            }
 21907        }
 908    }
 909}

Methods/Properties

.ctor(MediaBrowser.Controller.IServerApplicationHost,MediaBrowser.Controller.Persistence.IItemRepository,MediaBrowser.Common.Configuration.IApplicationPaths,MediaBrowser.Model.Globalization.ILocalizationManager,MediaBrowser.Controller.Library.IUserManager,MediaBrowser.Controller.Library.ILibraryManager,Microsoft.Extensions.Logging.ILogger`1<Emby.Server.Implementations.Library.MediaSourceManager>,MediaBrowser.Model.IO.IFileSystem,MediaBrowser.Controller.Library.IUserDataManager,MediaBrowser.Controller.MediaEncoding.IMediaEncoder,MediaBrowser.Controller.Providers.IDirectoryService,MediaBrowser.Controller.Persistence.IMediaStreamRepository,MediaBrowser.Controller.Persistence.IMediaAttachmentRepository)
AddParts(System.Collections.Generic.IEnumerable`1<MediaBrowser.Controller.Library.IMediaSourceProvider>)
GetMediaStreams(MediaBrowser.Controller.Persistence.MediaStreamQuery)
StreamSupportsExternalStream(MediaBrowser.Model.Entities.MediaStream)
GetMediaStreams(System.Guid)
GetMediaStreamsForItem(System.Collections.Generic.IReadOnlyList`1<MediaBrowser.Model.Entities.MediaStream>)
GetMediaAttachments(MediaBrowser.Controller.Persistence.MediaAttachmentQuery)
GetMediaAttachments(System.Guid)
GetPathProtocol(System.String)
SupportsDirectStream(System.String,MediaBrowser.Model.MediaInfo.MediaProtocol)
SetKeyProperties(MediaBrowser.Controller.Library.IMediaSourceProvider,MediaBrowser.Model.Dto.MediaSourceInfo)
GetStaticMediaSources(MediaBrowser.Controller.Entities.BaseItem,System.Boolean,Jellyfin.Database.Implementations.Entities.User)
NormalizeLanguage(System.String)
SetDefaultSubtitleStreamIndex(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Controller.Entities.UserItemData,Jellyfin.Database.Implementations.Entities.User,System.Boolean)
SetDefaultAudioStreamIndex(MediaBrowser.Model.Dto.MediaSourceInfo,MediaBrowser.Controller.Entities.UserItemData,Jellyfin.Database.Implementations.Entities.User,System.Boolean)
SetDefaultAudioAndSubtitleStreamIndices(MediaBrowser.Controller.Entities.BaseItem,MediaBrowser.Model.Dto.MediaSourceInfo,Jellyfin.Database.Implementations.Entities.User)
SortMediaSources(System.Collections.Generic.IEnumerable`1<MediaBrowser.Model.Dto.MediaSourceInfo>)
AddMediaInfo(MediaBrowser.Model.Dto.MediaSourceInfo)
GetLiveStreamWithDirectStreamProvider(System.String,System.Threading.CancellationToken)
GetLiveStreamInfo(System.String)
GetLiveStreamInfoByUniqueId(System.String)
GetProvider(System.String)
Dispose()
Dispose(System.Boolean)