LiveStreamHelper.cs 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. FileStream jsonStream = AsyncFile.OpenRead(cacheFilePath);
  44. try
  45. {
  46. mediaInfo = await JsonSerializer.DeserializeAsync<MediaInfo>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
  47. // _logger.LogDebug("Found cached media info");
  48. }
  49. catch (Exception ex)
  50. {
  51. _logger.LogError(ex, "Error deserializing mediainfo cache");
  52. }
  53. finally
  54. {
  55. await jsonStream.DisposeAsync().ConfigureAwait(false);
  56. }
  57. }
  58. if (mediaInfo is null)
  59. {
  60. if (addProbeDelay)
  61. {
  62. var delayMs = mediaSource.AnalyzeDurationMs ?? 0;
  63. delayMs = Math.Max(3000, delayMs);
  64. _logger.LogInformation("Waiting {0}ms before probing the live stream", delayMs);
  65. await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false);
  66. }
  67. mediaSource.AnalyzeDurationMs = 3000;
  68. mediaInfo = await _mediaEncoder.GetMediaInfo(
  69. new MediaInfoRequest
  70. {
  71. MediaSource = mediaSource,
  72. MediaType = isAudio ? DlnaProfileType.Audio : DlnaProfileType.Video,
  73. ExtractChapters = false
  74. },
  75. cancellationToken).ConfigureAwait(false);
  76. if (cacheFilePath is not null)
  77. {
  78. Directory.CreateDirectory(Path.GetDirectoryName(cacheFilePath));
  79. FileStream createStream = AsyncFile.OpenWrite(cacheFilePath);
  80. await using (createStream.ConfigureAwait(false))
  81. {
  82. await JsonSerializer.SerializeAsync(createStream, mediaInfo, _jsonOptions, cancellationToken).ConfigureAwait(false);
  83. }
  84. _logger.LogDebug("Saved media info to {0}", cacheFilePath);
  85. }
  86. }
  87. var mediaStreams = mediaInfo.MediaStreams;
  88. if (!string.IsNullOrEmpty(cacheKey))
  89. {
  90. var newList = new List<MediaStream>();
  91. newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Video).Take(1));
  92. newList.AddRange(mediaStreams.Where(i => i.Type == MediaStreamType.Audio).Take(1));
  93. foreach (var stream in newList)
  94. {
  95. stream.Index = -1;
  96. stream.Language = null;
  97. }
  98. mediaStreams = newList;
  99. }
  100. _logger.LogInformation("Live tv media info probe took {0} seconds", (DateTime.UtcNow - now).TotalSeconds.ToString(CultureInfo.InvariantCulture));
  101. mediaSource.Bitrate = mediaInfo.Bitrate;
  102. mediaSource.Container = mediaInfo.Container;
  103. mediaSource.Formats = mediaInfo.Formats;
  104. mediaSource.MediaStreams = mediaStreams;
  105. mediaSource.RunTimeTicks = mediaInfo.RunTimeTicks;
  106. mediaSource.Size = mediaInfo.Size;
  107. mediaSource.Timestamp = mediaInfo.Timestamp;
  108. mediaSource.Video3DFormat = mediaInfo.Video3DFormat;
  109. mediaSource.VideoType = mediaInfo.VideoType;
  110. mediaSource.DefaultSubtitleStreamIndex = null;
  111. // Null this out so that it will be treated like a live stream
  112. if (!originalRuntime.HasValue)
  113. {
  114. mediaSource.RunTimeTicks = null;
  115. }
  116. var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio);
  117. if (audioStream is null || audioStream.Index == -1)
  118. {
  119. mediaSource.DefaultAudioStreamIndex = null;
  120. }
  121. else
  122. {
  123. mediaSource.DefaultAudioStreamIndex = audioStream.Index;
  124. }
  125. var videoStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video);
  126. if (videoStream is not null)
  127. {
  128. if (!videoStream.BitRate.HasValue)
  129. {
  130. var width = videoStream.Width ?? 1920;
  131. if (width >= 3000)
  132. {
  133. videoStream.BitRate = 30000000;
  134. }
  135. else if (width >= 1900)
  136. {
  137. videoStream.BitRate = 20000000;
  138. }
  139. else if (width >= 1200)
  140. {
  141. videoStream.BitRate = 8000000;
  142. }
  143. else if (width >= 700)
  144. {
  145. videoStream.BitRate = 2000000;
  146. }
  147. }
  148. // This is coming up false and preventing stream copy
  149. videoStream.IsAVC = null;
  150. }
  151. mediaSource.AnalyzeDurationMs = 3000;
  152. // Try to estimate this
  153. mediaSource.InferTotalBitrate(true);
  154. }
  155. public Task AddMediaInfoWithProbe(MediaSourceInfo mediaSource, bool isAudio, bool addProbeDelay, CancellationToken cancellationToken)
  156. {
  157. return AddMediaInfoWithProbe(mediaSource, isAudio, null, addProbeDelay, cancellationToken);
  158. }
  159. }
  160. }