HlsHelpers.cs 5.4 KB

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