HlsSegmentController.cs 9.1 KB

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