LiveStreamHelper.cs 6.7 KB

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