2
0

HlsSegmentController.cs 9.2 KB

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