HlsHelpers.cs 5.8 KB

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