FileStreamResponseHelpers.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. using System;
  2. using System.IO;
  3. using System.Net.Http;
  4. using System.Net.Mime;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Jellyfin.Api.Models.PlaybackDtos;
  8. using Jellyfin.Api.Models.StreamingDtos;
  9. using MediaBrowser.Controller.MediaEncoding;
  10. using Microsoft.AspNetCore.Http;
  11. using Microsoft.AspNetCore.Mvc;
  12. using Microsoft.Net.Http.Headers;
  13. namespace Jellyfin.Api.Helpers
  14. {
  15. /// <summary>
  16. /// The stream response helpers.
  17. /// </summary>
  18. public static class FileStreamResponseHelpers
  19. {
  20. /// <summary>
  21. /// Returns a static file from a remote source.
  22. /// </summary>
  23. /// <param name="state">The current <see cref="StreamState"/>.</param>
  24. /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param>
  25. /// <param name="httpClient">The <see cref="HttpClient"/> making the remote request.</param>
  26. /// <param name="httpContext">The current http context.</param>
  27. /// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
  28. /// <returns>A <see cref="Task{ActionResult}"/> containing the API response.</returns>
  29. public static async Task<ActionResult> GetStaticRemoteStreamResult(
  30. StreamState state,
  31. bool isHeadRequest,
  32. HttpClient httpClient,
  33. HttpContext httpContext,
  34. CancellationToken cancellationToken = default)
  35. {
  36. if (state.RemoteHttpHeaders.TryGetValue(HeaderNames.UserAgent, out var useragent))
  37. {
  38. httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, useragent);
  39. }
  40. // Can't dispose the response as it's required up the call chain.
  41. var response = await httpClient.GetAsync(new Uri(state.MediaPath), cancellationToken).ConfigureAwait(false);
  42. var contentType = response.Content.Headers.ContentType?.ToString() ?? MediaTypeNames.Text.Plain;
  43. httpContext.Response.Headers[HeaderNames.AcceptRanges] = "none";
  44. if (isHeadRequest)
  45. {
  46. httpContext.Response.Headers[HeaderNames.ContentType] = contentType;
  47. return new OkResult();
  48. }
  49. return new FileStreamResult(await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false), contentType);
  50. }
  51. /// <summary>
  52. /// Returns a static file from the server.
  53. /// </summary>
  54. /// <param name="path">The path to the file.</param>
  55. /// <param name="contentType">The content type of the file.</param>
  56. /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param>
  57. /// <param name="httpContext">The current http context.</param>
  58. /// <returns>An <see cref="ActionResult"/> the file.</returns>
  59. public static ActionResult GetStaticFileResult(
  60. string path,
  61. string contentType,
  62. bool isHeadRequest,
  63. HttpContext httpContext)
  64. {
  65. httpContext.Response.ContentType = contentType;
  66. // if the request is a head request, return an OkResult (200) with the same headers as it would with a GET request
  67. if (isHeadRequest)
  68. {
  69. return new OkResult();
  70. }
  71. return new PhysicalFileResult(path, contentType) { EnableRangeProcessing = true };
  72. }
  73. /// <summary>
  74. /// Returns a transcoded file from the server.
  75. /// </summary>
  76. /// <param name="state">The current <see cref="StreamState"/>.</param>
  77. /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param>
  78. /// <param name="httpContext">The current http context.</param>
  79. /// <param name="transcodingJobHelper">The <see cref="TranscodingJobHelper"/> singleton.</param>
  80. /// <param name="ffmpegCommandLineArguments">The command line arguments to start ffmpeg.</param>
  81. /// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param>
  82. /// <param name="cancellationTokenSource">The <see cref="CancellationTokenSource"/>.</param>
  83. /// <returns>A <see cref="Task{ActionResult}"/> containing the transcoded file.</returns>
  84. public static async Task<ActionResult> GetTranscodedFile(
  85. StreamState state,
  86. bool isHeadRequest,
  87. HttpContext httpContext,
  88. TranscodingJobHelper transcodingJobHelper,
  89. string ffmpegCommandLineArguments,
  90. TranscodingJobType transcodingJobType,
  91. CancellationTokenSource cancellationTokenSource)
  92. {
  93. // Use the command line args with a dummy playlist path
  94. var outputPath = state.OutputFilePath;
  95. httpContext.Response.Headers[HeaderNames.AcceptRanges] = "none";
  96. var contentType = state.GetMimeType(outputPath);
  97. // Headers only
  98. if (isHeadRequest)
  99. {
  100. httpContext.Response.Headers[HeaderNames.ContentType] = contentType;
  101. return new OkResult();
  102. }
  103. var transcodingLock = transcodingJobHelper.GetTranscodingLock(outputPath);
  104. await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  105. try
  106. {
  107. TranscodingJobDto? job;
  108. if (!File.Exists(outputPath))
  109. {
  110. job = await transcodingJobHelper.StartFfMpeg(state, outputPath, ffmpegCommandLineArguments, httpContext.Request, transcodingJobType, cancellationTokenSource).ConfigureAwait(false);
  111. }
  112. else
  113. {
  114. job = transcodingJobHelper.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  115. state.Dispose();
  116. }
  117. var stream = new ProgressiveFileStream(outputPath, job, transcodingJobHelper);
  118. return new FileStreamResult(stream, contentType);
  119. }
  120. finally
  121. {
  122. transcodingLock.Release();
  123. }
  124. }
  125. }
  126. }