LiveStreamHelper.cs 6.7 KB

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