HlsSegmentController.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. file = Path.Combine(_serverConfigurationManager.GetTranscodePath(), file);
  62. return FileStreamResponseHelpers.GetStaticFileResult(file, MimeTypes.GetMimeType(file)!, false, HttpContext);
  63. }
  64. /// <summary>
  65. /// Gets a hls video playlist.
  66. /// </summary>
  67. /// <param name="itemId">The video id.</param>
  68. /// <param name="playlistId">The playlist id.</param>
  69. /// <response code="200">Hls video playlist returned.</response>
  70. /// <returns>A <see cref="FileStreamResult"/> containing the playlist.</returns>
  71. [HttpGet("Videos/{itemId}/hls/{playlistId}/stream.m3u8")]
  72. [Authorize(Policy = Policies.DefaultAuthorization)]
  73. [ProducesResponseType(StatusCodes.Status200OK)]
  74. [ProducesPlaylistFile]
  75. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
  76. public ActionResult GetHlsPlaylistLegacy([FromRoute, Required] string itemId, [FromRoute, Required] string playlistId)
  77. {
  78. var file = playlistId + Path.GetExtension(Request.Path);
  79. file = Path.Combine(_serverConfigurationManager.GetTranscodePath(), file);
  80. return GetFileResult(file, file);
  81. }
  82. /// <summary>
  83. /// Stops an active encoding.
  84. /// </summary>
  85. /// <param name="deviceId">The device id of the client requesting. Used to stop encoding processes when needed.</param>
  86. /// <param name="playSessionId">The play session id.</param>
  87. /// <response code="204">Encoding stopped successfully.</response>
  88. /// <returns>A <see cref="NoContentResult"/> indicating success.</returns>
  89. [HttpDelete("Videos/ActiveEncodings")]
  90. [Authorize(Policy = Policies.DefaultAuthorization)]
  91. [ProducesResponseType(StatusCodes.Status204NoContent)]
  92. public ActionResult StopEncodingProcess([FromQuery] string deviceId, [FromQuery] string playSessionId)
  93. {
  94. _transcodingJobHelper.KillTranscodingJobs(deviceId, playSessionId, path => true);
  95. return NoContent();
  96. }
  97. /// <summary>
  98. /// Gets a hls video segment.
  99. /// </summary>
  100. /// <param name="itemId">The item id.</param>
  101. /// <param name="playlistId">The playlist id.</param>
  102. /// <param name="segmentId">The segment id.</param>
  103. /// <param name="segmentContainer">The segment container.</param>
  104. /// <response code="200">Hls video segment returned.</response>
  105. /// <response code="404">Hls segment not found.</response>
  106. /// <returns>A <see cref="FileStreamResult"/> containing the video segment.</returns>
  107. // Can't require authentication just yet due to seeing some requests come from Chrome without full query string
  108. // [Authenticated]
  109. [HttpGet("Videos/{itemId}/hls/{playlistId}/{segmentId}.{segmentContainer}")]
  110. [ProducesResponseType(StatusCodes.Status200OK)]
  111. [ProducesResponseType(StatusCodes.Status404NotFound)]
  112. [ProducesVideoFile]
  113. [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "itemId", Justification = "Required for ServiceStack")]
  114. public ActionResult GetHlsVideoSegmentLegacy(
  115. [FromRoute, Required] string itemId,
  116. [FromRoute, Required] string playlistId,
  117. [FromRoute, Required] string segmentId,
  118. [FromRoute, Required] string segmentContainer)
  119. {
  120. var file = segmentId + Path.GetExtension(Request.Path);
  121. var transcodeFolderPath = _serverConfigurationManager.GetTranscodePath();
  122. file = Path.Combine(transcodeFolderPath, file);
  123. var normalizedPlaylistId = playlistId;
  124. var filePaths = _fileSystem.GetFilePaths(transcodeFolderPath);
  125. // Add . to start of segment container for future use.
  126. segmentContainer = segmentContainer.Insert(0, ".");
  127. string? playlistPath = null;
  128. foreach (var path in filePaths)
  129. {
  130. var pathExtension = Path.GetExtension(path);
  131. if ((string.Equals(pathExtension, segmentContainer, StringComparison.OrdinalIgnoreCase)
  132. || string.Equals(pathExtension, ".m3u8", StringComparison.OrdinalIgnoreCase))
  133. && path.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1)
  134. {
  135. playlistPath = path;
  136. break;
  137. }
  138. }
  139. return playlistPath == null
  140. ? NotFound("Hls segment not found.")
  141. : GetFileResult(file, playlistPath);
  142. }
  143. private ActionResult GetFileResult(string path, string playlistPath)
  144. {
  145. var transcodingJob = _transcodingJobHelper.OnTranscodeBeginRequest(playlistPath, TranscodingJobType.Hls);
  146. Response.OnCompleted(() =>
  147. {
  148. if (transcodingJob != null)
  149. {
  150. _transcodingJobHelper.OnTranscodeEndRequest(transcodingJob);
  151. }
  152. return Task.CompletedTask;
  153. });
  154. return FileStreamResponseHelpers.GetStaticFileResult(path, MimeTypes.GetMimeType(path)!, false, HttpContext);
  155. }
  156. }
  157. }