LiveStreamHelper.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #nullable disable
  2. #pragma warning disable CS1591
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text.Json;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Jellyfin.Extensions.Json;
  12. using MediaBrowser.Common.Configuration;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Controller.MediaEncoding;
  15. using MediaBrowser.Model.Dlna;
  16. using MediaBrowser.Model.Dto;
  17. using MediaBrowser.Model.Entities;
  18. using MediaBrowser.Model.IO;
  19. using MediaBrowser.Model.MediaInfo;
  20. using Microsoft.Extensions.Logging;
  21. namespace Emby.Server.Implementations.Library
  22. {
  23. public class LiveStreamHelper
  24. {
  25. private readonly IMediaEncoder _mediaEncoder;
  26. private readonly ILogger _logger;
  27. private readonly IApplicationPaths _appPaths;
  28. private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
  29. public LiveStreamHelper(IMediaEncoder mediaEncoder, ILogger logger, IApplicationPaths appPaths)
  30. {
  31. _mediaEncoder = mediaEncoder;
  32. _logger = logger;
  33. _appPaths = appPaths;
  34. }
  35. public async Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, string cacheKey, bool addProbeDelay, CancellationToken cancellationToken)
  36. {
  37. var originalRuntime = mediaSource.RunTimeTicks;
  38. var now = DateTime.UtcNow;
  39. MediaInfo mediaInfo = null;
  40. var cacheFilePath = string.IsNullOrEmpty(cacheKey) ? null : Path.Combine(_appPaths.CachePath, "mediainfo", cacheKey.GetMD5().ToString("N", CultureInfo.InvariantCulture) + ".json");
  41. if (!string.IsNullOrEmpty(cacheKey))
  42. {
  43. try
  44. {
  45. await using FileStream jsonStream = AsyncFile.OpenRead(cacheFilePath);
  46. mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  47. // _logger.LogDebug("Found cached media info");
  48. }
  49. catch
  50. {
  51. }
  52. }
  53. if (mediaInfo is null)
  54. {
  55. if (addProbeDelay)
  56. {
  57. var delayMs = mediaSource.AnalyzeDurationMs ?? 0;
  58. delayMs = Math.Max(3000, delayMs);
  59. _logger.LogInformation("Waiting {0}ms before probing the live stream", delayMs);
  60. await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);
  61. }
  62. mediaSource.AnalyzeDurationMs = 3000;
  63. mediaInfo = await _mediaEncoder.GetMediaInfo(
  64. new MediaInfoRequest
  65. {
  66. MediaSource = mediaSource,
  67. MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
  68. ExtractChapters = false
  69. },
  70. cancellationToken).ConfigureAwait(false);
  71. if (cacheFilePath is not null)
  72. {
  73. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  74. await using FileStream createStream = AsyncFile.OpenWrite(cacheFilePath);
  75. await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).ConfigureAwait(false);
  76. // _logger.LogDebug("Saved media info to {0}", cacheFilePath);
  77. }
  78. }
  79. var mediaStreams = mediaInfo.MediaStreams;
  80. if (!string.IsNullOrEmpty(cacheKey))
  81. {
  82. var newList = new List<MediaStream>();
  83. newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Video).Take(1));
  84. newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Take(1));
  85. foreach (var stream in newList)
  86. {
  87. stream.Index = -1;
  88. stream.Language = null;
  89. }
  90. mediaStreams = newList;
  91. }
  92. _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));
  93. mediaSource.Bitrate = mediaInfo.Bitrate;
  94. mediaSource.Container = mediaInfo.Container;
  95. mediaSource.Formats = mediaInfo.Formats;
  96. mediaSource.MediaStreams = mediaStreams;
  97. mediaSource.RunTimeTicks = mediaInfo.RunTimeTicks;
  98. mediaSource.Size = mediaInfo.Size;
  99. mediaSource.Timestamp = mediaInfo.Timestamp;
  100. mediaSource.Video3DFormat = mediaInfo.Video3DFormat;
  101. mediaSource.VideoType = mediaInfo.VideoType;
  102. mediaSource.DefaultSubtitleStreamIndex = null;
  103. // Null this out so that it will be treated like a live stream
  104. if (!originalRuntime.HasValue)
  105. {
  106. mediaSource.RunTimeTicks = null;
  107. }
  108. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  109. if (audioStream is null || audioStream.Index == -1)
  110. {
  111. mediaSource.DefaultAudioStreamIndex = null;
  112. }
  113. else
  114. {
  115. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  116. }
  117. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  118. if (videoStream is not null)
  119. {
  120. if (!videoStream.BitRate.HasValue)
  121. {
  122. var width = videoStream.Width ?? 1920;
  123. if (width >= 3000)
  124. {
  125. videoStream.BitRate = 30000000;
  126. }
  127. else if (width >= 1900)
  128. {
  129. videoStream.BitRate = 20000000;
  130. }
  131. else if (width >= 1200)
  132. {
  133. videoStream.BitRate = 8000000;
  134. }
  135. else if (width >= 700)
  136. {
  137. videoStream.BitRate = 2000000;
  138. }
  139. }
  140. // This is coming up false and preventing stream copy
  141. videoStream.IsAVC = null;
  142. }
  143. mediaSource.AnalyzeDurationMs = 3000;
  144. // Try to estimate this
  145. mediaSource.InferTotalBitrate(true);
  146. }
  147. public Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, bool addProbeDelay, CancellationToken cancellationToken)
  148. {
  149. return AddMediaInfoWithProbe(mediaSource, isAudio, null, addProbeDelay, cancellationToken);
  150. }
  151. }
  152. }