aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Api/Controllers/DynamicHlsController.cs
diff options
context:
space:
mode:
Diffstat (limited to 'Jellyfin.Api/Controllers/DynamicHlsController.cs')
-rw-r--r--Jellyfin.Api/Controllers/DynamicHlsController.cs193
1 files changed, 119 insertions, 74 deletions
diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs
index 6df76de0b4..a57cd568ce 100644
--- a/Jellyfin.Api/Controllers/DynamicHlsController.cs
+++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs
@@ -1431,9 +1431,7 @@ public class DynamicHlsController : BaseJellyfinApiController
throw new ArgumentException("StartTimeTicks is not allowed.");
}
- // CTS lifecycle is managed internally.
- var cancellationTokenSource = new CancellationTokenSource();
- var cancellationToken = cancellationTokenSource.Token;
+ var cancellationToken = HttpContext.RequestAborted;
var state = await StreamingHelpers.GetStreamingState(
streamingRequest,
@@ -1455,91 +1453,136 @@ public class DynamicHlsController : BaseJellyfinApiController
var segmentExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer);
- // Keep segment selection and transcoding replacement under the same playlist lock.
- // An out-of-order request must not replace a job while another request is using its output.
- using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
+ TranscodingJob? job = null;
+ TranscodingJob? jobToWaitFor = null;
+ CancellationTokenSource? cancellationTokenSource = null;
+ try
{
- TranscodingJob? job;
- var startTranscoding = false;
- if (System.IO.File.Exists(segmentPath))
+ while (true)
{
- job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- _logger.LogDebug("returning {0} [it exists]", segmentPath);
- return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
- }
+ // Readers must be able to acquire the lock while a replacement waits for them to finish.
+ await WaitForActiveTranscodingRequests(jobToWaitFor, cancellationToken).ConfigureAwait(false);
- var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
- var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
-
- if (segmentId == -1)
- {
- _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
- startTranscoding = true;
- segmentId = 0;
- }
- else if (currentTranscodingIndex is null)
- {
- _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
- startTranscoding = true;
- }
- else if (segmentId < currentTranscodingIndex.Value)
- {
- _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segmentId, currentTranscodingIndex);
- startTranscoding = true;
- }
- else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
- {
- _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", segmentId - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, segmentId);
- startTranscoding = true;
- }
-
- if (startTranscoding)
- {
- // If the playlist doesn't already exist, startup ffmpeg
- try
+ // Selection, reader registration and replacement remain atomic per playlist.
+ using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false))
{
- var currentJob = _transcodeManager.GetTranscodingJob(playlistPath, TranscodingJobType);
- await WaitForActiveTranscodingRequests(currentJob, cancellationToken).ConfigureAwait(false);
+ var startTranscoding = false;
+ if (System.IO.File.Exists(segmentPath))
+ {
+ job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
+ _logger.LogDebug("returning {0} [it exists]", segmentPath);
+ break;
+ }
- await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionId, p => false)
- .ConfigureAwait(false);
+ var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension);
+ var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength;
- if (currentTranscodingIndex.HasValue)
+ if (segmentId == -1)
+ {
+ _logger.LogDebug("Starting transcoding because fmp4 init file is being requested");
+ startTranscoding = true;
+ }
+ else if (currentTranscodingIndex is null)
{
- await DeleteLastFile(playlistPath, segmentExtension, 0).ConfigureAwait(false);
+ _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null");
+ startTranscoding = true;
+ }
+ else if (segmentId < currentTranscodingIndex.Value)
+ {
+ _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segmentId, currentTranscodingIndex);
+ startTranscoding = true;
+ }
+ else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange)
+ {
+ _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", segmentId - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, segmentId);
+ startTranscoding = true;
}
- streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks;
+ if (startTranscoding)
+ {
+ jobToWaitFor = _transcodeManager.GetTranscodingJob(playlistPath, TranscodingJobType);
+ if (jobToWaitFor?.ActiveRequestCount > 0)
+ {
+ continue;
+ }
+
+ try
+ {
+ await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionId, p => false)
+ .ConfigureAwait(false);
+
+ if (currentTranscodingIndex.HasValue)
+ {
+ await DeleteLastFile(playlistPath, segmentExtension, 0).ConfigureAwait(false);
+ }
+
+ // Preserve the init request's identity until replacement is actually selected.
+ if (segmentId == -1)
+ {
+ segmentId = 0;
+ }
+
+ streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks;
+ state.WaitForPath = segmentPath;
+
+ // The shared FFmpeg job must outlive cancellation of any one HTTP request.
+ cancellationTokenSource = new CancellationTokenSource();
+ job = await _transcodeManager.StartFfMpeg(
+ state,
+ playlistPath,
+ GetCommandLineArguments(playlistPath, state, false, segmentId),
+ Request.HttpContext.User.GetUserId(),
+ TranscodingJobType,
+ cancellationTokenSource).ConfigureAwait(false);
+ }
+ catch
+ {
+ if (cancellationTokenSource is not null)
+ {
+ var startedJob = state.TranscodingJob ?? _transcodeManager.GetTranscodingJob(playlistPath, TranscodingJobType);
+ if (startedJob?.CancellationTokenSource == cancellationTokenSource)
+ {
+ job = startedJob;
+ }
+ }
+
+ state.Dispose();
+ throw;
+ }
+ }
+ else
+ {
+ job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
+ if (job?.TranscodingThrottler is not null)
+ {
+ await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
+ }
+ }
- state.WaitForPath = segmentPath;
- job = await _transcodeManager.StartFfMpeg(
- state,
- playlistPath,
- GetCommandLineArguments(playlistPath, state, false, segmentId),
- Request.HttpContext.User.GetUserId(),
- TranscodingJobType,
- cancellationTokenSource).ConfigureAwait(false);
+ _logger.LogDebug("returning {0} [general case]", segmentPath);
+ job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
+ break;
}
- catch
- {
- state.Dispose();
- throw;
- }
-
- // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false);
}
- else
+
+ return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
+ }
+ catch
+ {
+ // OnCompleted is only registered once a response is ready.
+ if (job is not null)
{
- job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- if (job?.TranscodingThrottler is not null)
- {
- await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false);
- }
+ _transcodeManager.OnTranscodeEndRequest(job);
}
- _logger.LogDebug("returning {0} [general case]", segmentPath);
- job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
- return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false);
+ throw;
+ }
+ finally
+ {
+ if (job is null)
+ {
+ cancellationTokenSource?.Dispose();
+ }
}
}
@@ -1930,6 +1973,7 @@ public class DynamicHlsController : BaseJellyfinApiController
TranscodingJob? transcodingJob,
CancellationToken cancellationToken)
{
+ cancellationToken.ThrowIfCancellationRequested();
var segmentExists = System.IO.File.Exists(segmentPath);
if (segmentExists)
{
@@ -1999,6 +2043,7 @@ public class DynamicHlsController : BaseJellyfinApiController
private ActionResult GetSegmentResult(StreamState state, string segmentPath, int segmentIndex, TranscodingJob? transcodingJob)
{
var segmentEndingPositionTicks = state.Request.CurrentRuntimeTicks + state.Request.ActualSegmentLengthTicks;
+ var result = FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath));
Response.OnCompleted(() =>
{
@@ -2013,7 +2058,7 @@ public class DynamicHlsController : BaseJellyfinApiController
return Task.CompletedTask;
});
- return FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath));
+ return result;
}
private int? GetCurrentTranscodingIndex(string playlist, string segmentExtension)