HlsSegmentController.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. using System;
  2. using System.ComponentModel.DataAnnotations;
  3. using System.Diagnostics.CodeAnalysis;
  4. using System.IO;
  5. using System.Threading.Tasks;
  6. using Jellyfin.Api.Attributes;
  7. using Jellyfin.Api.Helpers;
  8. using MediaBrowser.Common.Configuration;
  9. using MediaBrowser.Controller.Configuration;
  10. using MediaBrowser.Controller.MediaEncoding;
  11. using MediaBrowser.Model.IO;
  12. using MediaBrowser.Model.Net;
  13. using Microsoft.AspNetCore.Authorization;
  14. using Microsoft.AspNetCore.Http;
  15. using Microsoft.AspNetCore.Mvc;
  16. namespace Jellyfin.Api.Controllers;
  17. /// <summary>
  18. /// The hls segment controller.
  19. /// </summary>
  20. [Route("")]
  21. public class HlsSegmentController : BaseJellyfinApiController
  22. {
  23. private readonly IFileSystem _fileSystem;
  24. private readonly IServerConfigurationManager _serverConfigurationManager;
  25. private readonly TranscodingJobHelper _transcodingJobHelper;
  26. /// <summary>
  27. /// Initializes a new instance of the <see cref="HlsSegmentController"/> class.
  28. /// </summary>
  29. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  30. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  31. /// <param name="transcodingJobHelper">Initialized instance of the <see cref="TranscodingJobHelper"/>.</param>
  32. public HlsSegmentController(
  33. IFileSystem fileSystem,
  34. IServerConfigurationManager serverConfigurationManager,
  35. TranscodingJobHelper transcodingJobHelper)
  36. {
  37. _fileSystem = fileSystem;
  38. _serverConfigurationManager = serverConfigurationManager;
  39. _transcodingJobHelper = transcodingJobHelper;
  40. }
  41. /// <summary>
  42. /// Gets the specified audio segment for an audio item.
  43. /// </summary>
  44. /// <param name="itemId">The item id.</param>
  45. /// <param name="segmentId">The segment id.</param>
  46. /// <response code="200">Hls audio segment returned.</response>
  47. /// <returns>A <see cref="FileStreamResult"/> containing the audio stream.</returns>
  48. // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
  49. // [Authenticated]
  50. [HttpGet("Audio/{itemId}/hls/{segmentId}/stream.mp3", Name = "GetHlsAudioSegmentLegacyMp3")]
  51. [HttpGet("Audio/{itemId}/hls/{segmentId}/stream.aac", Name = "GetHlsAudioSegmentLegacyAac")]
  52. [ProducesResponseType(StatusCodes.Status200OK)]
  53. [ProducesAudioFile]
  54. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
  55. public ActionResult GetHlsAudioSegmentLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string segmentId)
  56. {
  57. // TODO: Deprecate with new iOS app
  58. var file = string.Concat(segmentId, Path.GetExtension(Request.Path.Value.AsSpan()));
  59. var transcodePath = _serverConfigurationManager.GetTranscodePath();
  60. file = Path.GetFullPath(Path.Combine(transcodePath, file));
  61. var fileDir = Path.GetDirectoryName(file);
  62. if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath, StringComparison.InvariantCulture))
  63. {
  64. return BadRequest("Invalid segment.");
  65. }
  66. return FileStreamResponseHelpers.GetStaticFileResult(file, MimeTypes.GetMimeType(file));
  67. }
  68. /// <summary>
  69. /// Gets a hls video playlist.
  70. /// </summary>
  71. /// <param name="itemId">The video id.</param>
  72. /// <param name="playlistId">The playlist id.</param>
  73. /// <response code="200">Hls video playlist returned.</response>
  74. /// <returns>A <see cref="FileStreamResult"/> containing the playlist.</returns>
  75. [HttpGet("Videos/{itemId}/hls/{playlistId}/stream.m3u8")]
  76. [Authorize]
  77. [ProducesResponseType(StatusCodes.Status200OK)]
  78. [ProducesPlaylistFile]
  79. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
  80. public ActionResult GetHlsPlaylistLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string playlistId)
  81. {
  82. var file = string.Concat(playlistId, Path.GetExtension(Request.Path.Value.AsSpan()));
  83. var transcodePath = _serverConfigurationManager.GetTranscodePath();
  84. file = Path.GetFullPath(Path.Combine(transcodePath, file));
  85. var fileDir = Path.GetDirectoryName(file);
  86. if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath, StringComparison.InvariantCulture)
  87. || Path.GetExtension(file.AsSpan()).Equals(".m3u8", StringComparison.OrdinalIgnoreCase))
  88. {
  89. return BadRequest("Invalid segment.");
  90. }
  91. return GetFileResult(file, file);
  92. }
  93. /// <summary>
  94. /// Stops an active encoding.
  95. /// </summary>
  96. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  97. /// <param name="playSessionId">The play session id.</param>
  98. /// <response code="204">Encoding stopped successfully.</response>
  99. /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
  100. [HttpDelete("Videos/ActiveEncodings")]
  101. [Authorize]
  102. [ProducesResponseType(StatusCodes.Status204NoContent)]
  103. public ActionResult StopEncodingProcess(
  104. [FromQuery, Required] string deviceId,
  105. [FromQuery, Required] string playSessionId)
  106. {
  107. _transcodingJobHelper.KillTranscodingJobs(deviceId, playSessionId, path => true);
  108. return NoContent();
  109. }
  110. /// <summary>
  111. /// Gets a hls video segment.
  112. /// </summary>
  113. /// <param name="itemId">The item id.</param>
  114. /// <param name="playlistId">The playlist id.</param>
  115. /// <param name="segmentId">The segment id.</param>
  116. /// <param name="segmentContainer">The segment container.</param>
  117. /// <response code="200">Hls video segment returned.</response>
  118. /// <response code="404">Hls segment not found.</response>
  119. /// <returns>A <see cref="FileStreamResult"/> containing the video segment.</returns>
  120. // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
  121. // [Authenticated]
  122. [HttpGet("Videos/{itemId}/hls/{playlistId}/{segmentId}.{segmentContainer}")]
  123. [ProducesResponseType(StatusCodes.Status200OK)]
  124. [ProducesResponseType(StatusCodes.Status404NotFound)]
  125. [ProducesVideoFile]
  126. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
  127. public ActionResult GetHlsVideoSegmentLegacy(
  128. [FromRoute, Required] string itemId,
  129. [FromRoute, Required] string playlistId,
  130. [FromRoute, Required] string segmentId,
  131. [FromRoute, Required] string segmentContainer)
  132. {
  133. var file = string.Concat(segmentId, Path.GetExtension(Request.Path.Value.AsSpan()));
  134. var transcodeFolderPath = _serverConfigurationManager.GetTranscodePath();
  135. file = Path.GetFullPath(Path.Combine(transcodeFolderPath, file));
  136. var fileDir = Path.GetDirectoryName(file);
  137. if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodeFolderPath, StringComparison.InvariantCulture))
  138. {
  139. return BadRequest("Invalid segment.");
  140. }
  141. var normalizedPlaylistId = playlistId;
  142. var filePaths = _fileSystem.GetFilePaths(transcodeFolderPath);
  143. // Add . to start of segment container for future use.
  144. segmentContainer = segmentContainer.Insert(0, ".");
  145. string? playlistPath = null;
  146. foreach (var path in filePaths)
  147. {
  148. var pathExtension = Path.GetExtension(path);
  149. if ((string.Equals(pathExtension, segmentContainer, StringComparison.OrdinalIgnoreCase)
  150. || string.Equals(pathExtension, ".m3u8", StringComparison.OrdinalIgnoreCase))
  151. && path.Contains(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase))
  152. {
  153. playlistPath = path;
  154. break;
  155. }
  156. }
  157. return playlistPath is null
  158. ? NotFound("Hls segment not found.")
  159. : GetFileResult(file, playlistPath);
  160. }
  161. private ActionResult GetFileResult(string path, string playlistPath)
  162. {
  163. var transcodingJob = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
  164. Response.OnCompleted(() =>
  165. {
  166. if (transcodingJob is not null)
  167. {
  168. _transcodingJobHelper.OnTranscodeEndRequest(transcodingJob);
  169. }
  170. return Task.CompletedTask;
  171. });
  172. return FileStreamResponseHelpers.GetStaticFileResult(path, MimeTypes.GetMimeType(path));
  173. }
  174. }