2
0

FileStreamResponseHelpers.cs 6.0 KB

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