HlsHelpers.cs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. using System;
  2. using System.Globalization;
  3. using System.IO;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Api.Models.StreamingDtos;
  7. using MediaBrowser.Controller.MediaEncoding;
  8. using MediaBrowser.Controller.Streaming;
  9. using MediaBrowser.Model.IO;
  10. using Microsoft.Extensions.Logging;
  11. namespace Jellyfin.Api.Helpers;
  12. /// <summary>
  13. /// The hls helpers.
  14. /// </summary>
  15. public static class HlsHelpers
  16. {
  17. /// <summary>
  18. /// Waits for a minimum number of segments to be available.
  19. /// </summary>
  20. /// <param name="playlist">The playlist string.</param>
  21. /// <param name="segmentCount">The segment count.</param>
  22. /// <param name="logger">Instance of the <see cref="ILogger"/> interface.</param>
  23. /// <param name="cancellationToken">The <see cref="CancellationToken"/>.</param>
  24. /// <returns>A <see cref="Task"/> indicating the waiting process.</returns>
  25. public static async Task WaitForMinimumSegmentCount(string playlist, int? segmentCount, ILogger logger, CancellationToken cancellationToken)
  26. {
  27. logger.LogDebug("Waiting for {0} segments in {1}", segmentCount, playlist);
  28. while (!cancellationToken.IsCancellationRequested)
  29. {
  30. try
  31. {
  32. // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written
  33. var fileStream = new FileStream(
  34. playlist,
  35. FileMode.Open,
  36. FileAccess.Read,
  37. FileShare.ReadWrite,
  38. IODefaults.FileStreamBufferSize,
  39. FileOptions.Asynchronous | FileOptions.SequentialScan);
  40. await using (fileStream.ConfigureAwait(false))
  41. {
  42. using var reader = new StreamReader(fileStream);
  43. var count = 0;
  44. while (!reader.EndOfStream)
  45. {
  46. var line = await reader.ReadLineAsync(cancellationToken).ConfigureAwait(false);
  47. if (line is null)
  48. {
  49. // Nothing currently in buffer.
  50. break;
  51. }
  52. if (line.Contains("#EXTINF:", StringComparison.OrdinalIgnoreCase))
  53. {
  54. count++;
  55. if (count >= segmentCount)
  56. {
  57. logger.LogDebug("Finished waiting for {0} segments in {1}", segmentCount, playlist);
  58. return;
  59. }
  60. }
  61. }
  62. }
  63. await Task.Delay(100, cancellationToken).ConfigureAwait(false);
  64. }
  65. catch (IOException)
  66. {
  67. // May get an error if the file is locked
  68. }
  69. await Task.Delay(50, cancellationToken).ConfigureAwait(false);
  70. }
  71. }
  72. /// <summary>
  73. /// Gets the #EXT-X-MAP string.
  74. /// </summary>
  75. /// <param name="outputPath">The output path of the file.</param>
  76. /// <param name="state">The <see cref="StreamState"/>.</param>
  77. /// <param name="isOsDepends">Get a normal string or depends on OS.</param>
  78. /// <returns>The string text of #EXT-X-MAP.</returns>
  79. public static string GetFmp4InitFileName(string outputPath, StreamState state, bool isOsDepends)
  80. {
  81. var directory = Path.GetDirectoryName(outputPath) ?? throw new ArgumentException($"Provided path ({outputPath}) is not valid.", nameof(outputPath));
  82. var outputFileNameWithoutExtension = Path.GetFileNameWithoutExtension(outputPath);
  83. var outputPrefix = Path.Combine(directory, outputFileNameWithoutExtension);
  84. var outputExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
  85. // on Linux/Unix
  86. // #EXT-X-MAP:URI="prefix-1.mp4"
  87. var fmp4InitFileName = outputFileNameWithoutExtension + "-1" + outputExtension;
  88. if (!isOsDepends)
  89. {
  90. return fmp4InitFileName;
  91. }
  92. if (OperatingSystem.IsWindows())
  93. {
  94. // on Windows
  95. // #EXT-X-MAP:URI="X:\transcodes\prefix-1.mp4"
  96. fmp4InitFileName = outputPrefix + "-1" + outputExtension;
  97. }
  98. return fmp4InitFileName;
  99. }
  100. /// <summary>
  101. /// Gets the hls playlist text.
  102. /// </summary>
  103. /// <param name="path">The path to the playlist file.</param>
  104. /// <param name="state">The <see cref="StreamState"/>.</param>
  105. /// <returns>The playlist text as a string.</returns>
  106. public static string GetLivePlaylistText(string path, StreamState state)
  107. {
  108. var text = File.ReadAllText(path);
  109. var segmentFormat = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.');
  110. if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase))
  111. {
  112. var fmp4InitFileName = GetFmp4InitFileName(path, state, true);
  113. var baseUrlParam = string.Format(
  114. CultureInfo.InvariantCulture,
  115. "hls/{0}/",
  116. Path.GetFileNameWithoutExtension(path));
  117. var newFmp4InitFileName = baseUrlParam + GetFmp4InitFileName(path, state, false);
  118. // Replace fMP4 init file URI.
  119. text = text.Replace(fmp4InitFileName, newFmp4InitFileName, StringComparison.InvariantCulture);
  120. }
  121. return text;
  122. }
  123. }