FileStreamResponseHelpers.cs 6.2 KB

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