2
0

HlsSegmentController.cs 7.7 KB

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