FileStreamResponseHelpers.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. /// <returns>A <see cref="Task{ActionResult}"/> containing the API response.</returns>
  27. public static async Task<ActionResult> GetStaticRemoteStreamResult(
  28. StreamState state,
  29. bool isHeadRequest,
  30. HttpClient httpClient,
  31. HttpContext httpContext)
  32. {
  33. if (state.RemoteHttpHeaders.TryGetValue(HeaderNames.UserAgent, out var useragent))
  34. {
  35. httpClient.DefaultRequestHeaders.Add(HeaderNames.UserAgent, useragent);
  36. }
  37. using var response = await httpClient.GetAsync(state.MediaPath).ConfigureAwait(false);
  38. var contentType = response.Content.Headers.ContentType.ToString();
  39. httpContext.Response.Headers[HeaderNames.AcceptRanges] = "none";
  40. if (isHeadRequest)
  41. {
  42. return new FileContentResult(Array.Empty<byte>(), contentType);
  43. }
  44. return new FileStreamResult(await response.Content.ReadAsStreamAsync().ConfigureAwait(false), contentType);
  45. }
  46. /// <summary>
  47. /// Returns a static file from the server.
  48. /// </summary>
  49. /// <param name="path">The path to the file.</param>
  50. /// <param name="contentType">The content type of the file.</param>
  51. /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param>
  52. /// <param name="httpContext">The current http context.</param>
  53. /// <returns>An <see cref="ActionResult"/> the file.</returns>
  54. public static ActionResult GetStaticFileResult(
  55. string path,
  56. string contentType,
  57. bool isHeadRequest,
  58. HttpContext httpContext)
  59. {
  60. httpContext.Response.ContentType = contentType;
  61. // if the request is a head request, return a NoContent result with the same headers as it would with a GET request
  62. if (isHeadRequest)
  63. {
  64. return new NoContentResult();
  65. }
  66. return new PhysicalFileResult(path, contentType);
  67. }
  68. /// <summary>
  69. /// Returns a transcoded file from the server.
  70. /// </summary>
  71. /// <param name="state">The current <see cref="StreamState"/>.</param>
  72. /// <param name="isHeadRequest">Whether the current request is a HTTP HEAD request so only the headers get returned.</param>
  73. /// <param name="httpContext">The current http context.</param>
  74. /// <param name="transcodingJobHelper">The <see cref="TranscodingJobHelper"/> singleton.</param>
  75. /// <param name="ffmpegCommandLineArguments">The command line arguments to start ffmpeg.</param>
  76. /// <param name="transcodingJobType">The <see cref="TranscodingJobType"/>.</param>
  77. /// <param name="cancellationTokenSource">The <see cref="CancellationTokenSource"/>.</param>
  78. /// <returns>A <see cref="Task{ActionResult}"/> containing the transcoded file.</returns>
  79. public static async Task<ActionResult> GetTranscodedFile(
  80. StreamState state,
  81. bool isHeadRequest,
  82. HttpContext httpContext,
  83. TranscodingJobHelper transcodingJobHelper,
  84. string ffmpegCommandLineArguments,
  85. TranscodingJobType transcodingJobType,
  86. CancellationTokenSource cancellationTokenSource)
  87. {
  88. // Use the command line args with a dummy playlist path
  89. var outputPath = state.OutputFilePath;
  90. httpContext.Response.Headers[HeaderNames.AcceptRanges] = "none";
  91. var contentType = state.GetMimeType(outputPath);
  92. // Headers only
  93. if (isHeadRequest)
  94. {
  95. return new FileContentResult(Array.Empty<byte>(), contentType);
  96. }
  97. var transcodingLock = transcodingJobHelper.GetTranscodingLock(outputPath);
  98. await transcodingLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
  99. try
  100. {
  101. TranscodingJobDto? job;
  102. if (!File.Exists(outputPath))
  103. {
  104. job = await transcodingJobHelper.StartFfMpeg(state, outputPath, ffmpegCommandLineArguments, httpContext.Request, transcodingJobType, cancellationTokenSource).ConfigureAwait(false);
  105. }
  106. else
  107. {
  108. job = transcodingJobHelper.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
  109. state.Dispose();
  110. }
  111. var memoryStream = new MemoryStream();
  112. await new ProgressiveFileCopier(outputPath, job, transcodingJobHelper, CancellationToken.None).WriteToAsync(memoryStream, CancellationToken.None).ConfigureAwait(false);
  113. memoryStream.Position = 0;
  114. return new FileStreamResult(memoryStream, contentType);
  115. }
  116. finally
  117. {
  118. transcodingLock.Release();
  119. }
  120. }
  121. }
  122. }