HlsSegmentController.cs 8.5 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.Constants;
  8. using Jellyfin.Api.Helpers;
  9. using MediaBrowser.Common.Configuration;
  10. using MediaBrowser.Controller.Configuration;
  11. using MediaBrowser.Controller.MediaEncoding;
  12. using MediaBrowser.Model.IO;
  13. using MediaBrowser.Model.Net;
  14. using Microsoft.AspNetCore.Authorization;
  15. using Microsoft.AspNetCore.Http;
  16. using Microsoft.AspNetCore.Mvc;
  17. namespace Jellyfin.Api.Controllers;
  18. /// <summary>
  19. /// The hls segment controller.
  20. /// </summary>
  21. [Route("")]
  22. public class HlsSegmentController : BaseJellyfinApiController
  23. {
  24. private readonly IFileSystem _fileSystem;
  25. private readonly IServerConfigurationManager _serverConfigurationManager;
  26. private readonly TranscodingJobHelper _transcodingJobHelper;
  27. /// <summary>
  28. /// Initializes a new instance of the <see cref="HlsSegmentController"/> class.
  29. /// </summary>
  30. /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param>
  31. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  32. /// <param name="transcodingJobHelper">Initialized instance of the <see cref="TranscodingJobHelper"/>.</param>
  33. public HlsSegmentController(
  34. IFileSystem fileSystem,
  35. IServerConfigurationManager serverConfigurationManager,
  36. TranscodingJobHelper transcodingJobHelper)
  37. {
  38. _fileSystem = fileSystem;
  39. _serverConfigurationManager = serverConfigurationManager;
  40. _transcodingJobHelper = transcodingJobHelper;
  41. }
  42. /// <summary>
  43. /// Gets the specified audio segment for an audio item.
  44. /// </summary>
  45. /// <param name="itemId">The item id.</param>
  46. /// <param name="segmentId">The segment id.</param>
  47. /// <response code="200">Hls audio segment returned.</response>
  48. /// <returns>A <see cref="FileStreamResult"/> containing the audio stream.</returns>
  49. // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
  50. // [Authenticated]
  51. [HttpGet("Audio/{itemId}/hls/{segmentId}/stream.mp3", Name = "GetHlsAudioSegmentLegacyMp3")]
  52. [HttpGet("Audio/{itemId}/hls/{segmentId}/stream.aac", Name = "GetHlsAudioSegmentLegacyAac")]
  53. [ProducesResponseType(StatusCodes.Status200OK)]
  54. [ProducesAudioFile]
  55. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
  56. public ActionResult GetHlsAudioSegmentLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string segmentId)
  57. {
  58. // TODO: Deprecate with new iOS app
  59. var file = segmentId + Path.GetExtension(Request.Path);
  60. var transcodePath = _serverConfigurationManager.GetTranscodePath();
  61. file = Path.GetFullPath(Path.Combine(transcodePath, file));
  62. var fileDir = Path.GetDirectoryName(file);
  63. if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath, StringComparison.InvariantCulture))
  64. {
  65. return BadRequest("Invalid segment.");
  66. }
  67. return FileStreamResponseHelpers.GetStaticFileResult(file, MimeTypes.GetMimeType(file));
  68. }
  69. /// <summary>
  70. /// Gets a hls video playlist.
  71. /// </summary>
  72. /// <param name="itemId">The video id.</param>
  73. /// <param name="playlistId">The playlist id.</param>
  74. /// <response code="200">Hls video playlist returned.</response>
  75. /// <returns>A <see cref="FileStreamResult"/> containing the playlist.</returns>
  76. [HttpGet("Videos/{itemId}/hls/{playlistId}/stream.m3u8")]
  77. [Authorize(Policy = Policies.DefaultAuthorization)]
  78. [ProducesResponseType(StatusCodes.Status200OK)]
  79. [ProducesPlaylistFile]
  80. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
  81. public ActionResult GetHlsPlaylistLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string playlistId)
  82. {
  83. var file = playlistId + Path.GetExtension(Request.Path);
  84. var transcodePath = _serverConfigurationManager.GetTranscodePath();
  85. file = Path.GetFullPath(Path.Combine(transcodePath, file));
  86. var fileDir = Path.GetDirectoryName(file);
  87. if (string.IsNullOrEmpty(fileDir) || !fileDir.StartsWith(transcodePath, StringComparison.InvariantCulture) || Path.GetExtension(file) != ".m3u8")
  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(Policy = Policies.DefaultAuthorization)]
  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 = segmentId + Path.GetExtension(Request.Path);
  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.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1)
  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. }