diff --git a/Jellyfin.Api/Controllers/PlaystateController.cs b/Jellyfin.Api/Controllers/PlaystateController.cs
new file mode 100644
index 0000000000..05a6edf4ed
--- /dev/null
+++ b/Jellyfin.Api/Controllers/PlaystateController.cs
@@ -0,0 +1,372 @@
+using System;
+using System.Diagnostics.CodeAnalysis;
+using System.Threading.Tasks;
+using Jellyfin.Api.Constants;
+using Jellyfin.Api.Helpers;
+using Jellyfin.Data.Entities;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.Net;
+using MediaBrowser.Controller.Session;
+using MediaBrowser.Model.Dto;
+using MediaBrowser.Model.IO;
+using MediaBrowser.Model.Session;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Controllers
+{
+ ///
+ /// Playstate controller.
+ ///
+ [Authorize(Policy = Policies.DefaultAuthorization)]
+ public class PlaystateController : BaseJellyfinApiController
+ {
+ private readonly IUserManager _userManager;
+ private readonly IUserDataManager _userDataRepository;
+ private readonly ILibraryManager _libraryManager;
+ private readonly ISessionManager _sessionManager;
+ private readonly IAuthorizationContext _authContext;
+ private readonly ILogger _logger;
+ private readonly TranscodingJobHelper _transcodingJobHelper;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Instance of the interface.
+ /// Instance of the interface.
+ /// Instance of the interface.
+ /// Instance of the interface.
+ /// Instance of the interface.
+ /// Instance of the interface.
+ /// Instance of the interface.
+ /// Instance of the interface.
+ public PlaystateController(
+ IUserManager userManager,
+ IUserDataManager userDataRepository,
+ ILibraryManager libraryManager,
+ ISessionManager sessionManager,
+ IAuthorizationContext authContext,
+ ILoggerFactory loggerFactory,
+ IMediaSourceManager mediaSourceManager,
+ IFileSystem fileSystem)
+ {
+ _userManager = userManager;
+ _userDataRepository = userDataRepository;
+ _libraryManager = libraryManager;
+ _sessionManager = sessionManager;
+ _authContext = authContext;
+ _logger = loggerFactory.CreateLogger();
+
+ _transcodingJobHelper = new TranscodingJobHelper(
+ loggerFactory.CreateLogger(),
+ mediaSourceManager,
+ fileSystem);
+ }
+
+ ///
+ /// Marks an item as played for user.
+ ///
+ /// User id.
+ /// Item id.
+ /// Optional. The date the item was played.
+ /// Item marked as played.
+ /// An containing the .
+ [HttpPost("/Users/{userId}/PlayedItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult MarkPlayedItem(
+ [FromRoute] Guid userId,
+ [FromRoute] Guid itemId,
+ [FromQuery] DateTime? datePlayed)
+ {
+ var user = _userManager.GetUserById(userId);
+ var session = RequestHelpers.GetSession(_sessionManager, _authContext, Request);
+ var dto = UpdatePlayedStatus(user, itemId, true, datePlayed);
+ foreach (var additionalUserInfo in session.AdditionalUsers)
+ {
+ var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
+ UpdatePlayedStatus(additionalUser, itemId, true, datePlayed);
+ }
+
+ return dto;
+ }
+
+ ///
+ /// Marks an item as unplayed for user.
+ ///
+ /// User id.
+ /// Item id.
+ /// Item marked as unplayed.
+ /// A containing the .
+ [HttpDelete("/Users/{userId}/PlayedItem/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status200OK)]
+ public ActionResult MarkUnplayedItem([FromRoute] Guid userId, [FromRoute] Guid itemId)
+ {
+ var user = _userManager.GetUserById(userId);
+ var session = RequestHelpers.GetSession(_sessionManager, _authContext, Request);
+ var dto = UpdatePlayedStatus(user, itemId, false, null);
+ foreach (var additionalUserInfo in session.AdditionalUsers)
+ {
+ var additionalUser = _userManager.GetUserById(additionalUserInfo.UserId);
+ UpdatePlayedStatus(additionalUser, itemId, false, null);
+ }
+
+ return dto;
+ }
+
+ ///
+ /// Reports playback has started within a session.
+ ///
+ /// The playback start info.
+ /// Playback start recorded.
+ /// A .
+ [HttpPost("/Sessions/Playing")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task ReportPlaybackStart([FromBody] PlaybackStartInfo playbackStartInfo)
+ {
+ playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId);
+ playbackStartInfo.SessionId = RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id;
+ await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ ///
+ /// Reports playback progress within a session.
+ ///
+ /// The playback progress info.
+ /// Playback progress recorded.
+ /// A .
+ [HttpPost("/Sessions/Playing/Progress")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task ReportPlaybackProgress([FromBody] PlaybackProgressInfo playbackProgressInfo)
+ {
+ playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId);
+ playbackProgressInfo.SessionId = RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id;
+ await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ ///
+ /// Pings a playback session.
+ ///
+ /// Playback session id.
+ /// Playback session pinged.
+ /// A .
+ [HttpPost("/Sessions/Playing/Ping")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public ActionResult PingPlaybackSession([FromQuery] string playSessionId)
+ {
+ _transcodingJobHelper.PingTranscodingJob(playSessionId, null);
+ return NoContent();
+ }
+
+ ///
+ /// Reports playback has stopped within a session.
+ ///
+ /// The playback stop info.
+ /// Playback stop recorded.
+ /// A .
+ [HttpPost("/Sessions/Playing/Stopped")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ public async Task ReportPlaybackStopped([FromBody] PlaybackStopInfo playbackStopInfo)
+ {
+ _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty);
+ if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId))
+ {
+ await _transcodingJobHelper.KillTranscodingJobs(_authContext.GetAuthorizationInfo(Request).DeviceId, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false);
+ }
+
+ playbackStopInfo.SessionId = RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id;
+ await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ ///
+ /// Reports that a user has begun playing an item.
+ ///
+ /// User id.
+ /// Item id.
+ /// The id of the MediaSource.
+ /// Indicates if the client can seek.
+ /// The audio stream index.
+ /// The subtitle stream index.
+ /// The play method.
+ /// The live stream id.
+ /// The play session id.
+ /// Play start recorded.
+ /// A .
+ [HttpPost("/Users/{userId}/PlayingItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
+ public async Task OnPlaybackStart(
+ [FromRoute] Guid userId,
+ [FromRoute] Guid itemId,
+ [FromQuery] string mediaSourceId,
+ [FromQuery] bool canSeek,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] PlayMethod playMethod,
+ [FromQuery] string liveStreamId,
+ [FromQuery] string playSessionId)
+ {
+ var playbackStartInfo = new PlaybackStartInfo
+ {
+ CanSeek = canSeek,
+ ItemId = itemId,
+ MediaSourceId = mediaSourceId,
+ AudioStreamIndex = audioStreamIndex,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ PlayMethod = playMethod,
+ PlaySessionId = playSessionId,
+ LiveStreamId = liveStreamId
+ };
+
+ playbackStartInfo.PlayMethod = ValidatePlayMethod(playbackStartInfo.PlayMethod, playbackStartInfo.PlaySessionId);
+ playbackStartInfo.SessionId = RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id;
+ await _sessionManager.OnPlaybackStart(playbackStartInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ ///
+ /// Reports a user's playback progress.
+ ///
+ /// User id.
+ /// Item id.
+ /// The id of the MediaSource.
+ /// Optional. The current position, in ticks. 1 tick = 10000 ms.
+ /// Indicates if the player is paused.
+ /// Indicates if the player is muted.
+ /// The audio stream index.
+ /// The subtitle stream index.
+ /// Scale of 0-100.
+ /// The play method.
+ /// The live stream id.
+ /// The play session id.
+ /// The repeat mode.
+ /// Play progress recorded.
+ /// A .
+ [HttpPost("/Users/{userId}/PlayingItems/{itemId}/Progress")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
+ public async Task OnPlaybackProgress(
+ [FromRoute] Guid userId,
+ [FromRoute] Guid itemId,
+ [FromQuery] string mediaSourceId,
+ [FromQuery] long? positionTicks,
+ [FromQuery] bool isPaused,
+ [FromQuery] bool isMuted,
+ [FromQuery] int? audioStreamIndex,
+ [FromQuery] int? subtitleStreamIndex,
+ [FromQuery] int? volumeLevel,
+ [FromQuery] PlayMethod playMethod,
+ [FromQuery] string liveStreamId,
+ [FromQuery] string playSessionId,
+ [FromQuery] RepeatMode repeatMode)
+ {
+ var playbackProgressInfo = new PlaybackProgressInfo
+ {
+ ItemId = itemId,
+ PositionTicks = positionTicks,
+ IsMuted = isMuted,
+ IsPaused = isPaused,
+ MediaSourceId = mediaSourceId,
+ AudioStreamIndex = audioStreamIndex,
+ SubtitleStreamIndex = subtitleStreamIndex,
+ VolumeLevel = volumeLevel,
+ PlayMethod = playMethod,
+ PlaySessionId = playSessionId,
+ LiveStreamId = liveStreamId,
+ RepeatMode = repeatMode
+ };
+
+ playbackProgressInfo.PlayMethod = ValidatePlayMethod(playbackProgressInfo.PlayMethod, playbackProgressInfo.PlaySessionId);
+ playbackProgressInfo.SessionId = RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id;
+ await _sessionManager.OnPlaybackProgress(playbackProgressInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ ///
+ /// Reports that a user has stopped playing an item.
+ ///
+ /// User id.
+ /// Item id.
+ /// The id of the MediaSource.
+ /// The next media type that will play.
+ /// Optional. The position, in ticks, where playback stopped. 1 tick = 10000 ms.
+ /// The live stream id.
+ /// The play session id.
+ /// Playback stop recorded.
+ /// A .
+ [HttpDelete("/Users/{userId}/PlayingItems/{itemId}")]
+ [ProducesResponseType(StatusCodes.Status204NoContent)]
+ [SuppressMessage("Microsoft.Performance", "CA1801:ReviewUnusedParameters", MessageId = "userId", Justification = "Required for ServiceStack")]
+ public async Task OnPlaybackStopped(
+ [FromRoute] Guid userId,
+ [FromRoute] Guid itemId,
+ [FromQuery] string mediaSourceId,
+ [FromQuery] string nextMediaType,
+ [FromQuery] long? positionTicks,
+ [FromQuery] string liveStreamId,
+ [FromQuery] string playSessionId)
+ {
+ var playbackStopInfo = new PlaybackStopInfo
+ {
+ ItemId = itemId,
+ PositionTicks = positionTicks,
+ MediaSourceId = mediaSourceId,
+ PlaySessionId = playSessionId,
+ LiveStreamId = liveStreamId,
+ NextMediaType = nextMediaType
+ };
+
+ _logger.LogDebug("ReportPlaybackStopped PlaySessionId: {0}", playbackStopInfo.PlaySessionId ?? string.Empty);
+ if (!string.IsNullOrWhiteSpace(playbackStopInfo.PlaySessionId))
+ {
+ await _transcodingJobHelper.KillTranscodingJobs(_authContext.GetAuthorizationInfo(Request).DeviceId, playbackStopInfo.PlaySessionId, s => true).ConfigureAwait(false);
+ }
+
+ playbackStopInfo.SessionId = RequestHelpers.GetSession(_sessionManager, _authContext, Request).Id;
+ await _sessionManager.OnPlaybackStopped(playbackStopInfo).ConfigureAwait(false);
+ return NoContent();
+ }
+
+ ///
+ /// Updates the played status.
+ ///
+ /// The user.
+ /// The item id.
+ /// if set to true [was played].
+ /// The date played.
+ /// Task.
+ private UserItemDataDto UpdatePlayedStatus(User user, Guid itemId, bool wasPlayed, DateTime? datePlayed)
+ {
+ var item = _libraryManager.GetItemById(itemId);
+
+ if (wasPlayed)
+ {
+ item.MarkPlayed(user, datePlayed, true);
+ }
+ else
+ {
+ item.MarkUnplayed(user);
+ }
+
+ return _userDataRepository.GetUserDataDto(item, user);
+ }
+
+ private PlayMethod ValidatePlayMethod(PlayMethod method, string playSessionId)
+ {
+ if (method == PlayMethod.Transcode)
+ {
+ var job = string.IsNullOrWhiteSpace(playSessionId) ? null : _transcodingJobHelper.GetTranscodingJob(playSessionId);
+ if (job == null)
+ {
+ return PlayMethod.DirectPlay;
+ }
+ }
+
+ return method;
+ }
+ }
+}
diff --git a/Jellyfin.Api/Helpers/TranscodingJobHelper.cs b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs
new file mode 100644
index 0000000000..44f662e6e0
--- /dev/null
+++ b/Jellyfin.Api/Helpers/TranscodingJobHelper.cs
@@ -0,0 +1,354 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using Jellyfin.Api.Models.PlaybackDtos;
+using MediaBrowser.Controller.Library;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.IO;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Helpers
+{
+ ///
+ /// Transcoding job helpers.
+ ///
+ public class TranscodingJobHelper
+ {
+ ///
+ /// The active transcoding jobs.
+ ///
+ private static readonly List _activeTranscodingJobs = new List();
+
+ ///
+ /// The transcoding locks.
+ ///
+ private static readonly Dictionary _transcodingLocks = new Dictionary();
+
+ private readonly ILogger _logger;
+ private readonly IMediaSourceManager _mediaSourceManager;
+ private readonly IFileSystem _fileSystem;
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Instance of the interface.
+ /// Instance of the interface.
+ /// Instance of the interface.
+ public TranscodingJobHelper(
+ ILogger logger,
+ IMediaSourceManager mediaSourceManager,
+ IFileSystem fileSystem)
+ {
+ _logger = logger;
+ _mediaSourceManager = mediaSourceManager;
+ _fileSystem = fileSystem;
+ }
+
+ ///
+ /// Get transcoding job.
+ ///
+ /// Playback session id.
+ /// The transcoding job.
+ public TranscodingJobDto GetTranscodingJob(string playSessionId)
+ {
+ lock (_activeTranscodingJobs)
+ {
+ return _activeTranscodingJobs.FirstOrDefault(j => string.Equals(j.PlaySessionId, playSessionId, StringComparison.OrdinalIgnoreCase));
+ }
+ }
+
+ ///
+ /// Ping transcoding job.
+ ///
+ /// Play session id.
+ /// Is user paused.
+ /// Play session id is null.
+ public void PingTranscodingJob(string playSessionId, bool? isUserPaused)
+ {
+ if (string.IsNullOrEmpty(playSessionId))
+ {
+ throw new ArgumentNullException(nameof(playSessionId));
+ }
+
+ _logger.LogDebug("PingTranscodingJob PlaySessionId={0} isUsedPaused: {1}", playSessionId, isUserPaused);
+
+ List jobs;
+
+ lock (_activeTranscodingJobs)
+ {
+ // This is really only needed for HLS.
+ // Progressive streams can stop on their own reliably
+ jobs = _activeTranscodingJobs.Where(j => string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase)).ToList();
+ }
+
+ foreach (var job in jobs)
+ {
+ if (isUserPaused.HasValue)
+ {
+ _logger.LogDebug("Setting job.IsUserPaused to {0}. jobId: {1}", isUserPaused, job.Id);
+ job.IsUserPaused = isUserPaused.Value;
+ }
+
+ PingTimer(job, true);
+ }
+ }
+
+ private void PingTimer(TranscodingJobDto job, bool isProgressCheckIn)
+ {
+ if (job.HasExited)
+ {
+ job.StopKillTimer();
+ return;
+ }
+
+ var timerDuration = 10000;
+
+ if (job.Type != TranscodingJobType.Progressive)
+ {
+ timerDuration = 60000;
+ }
+
+ job.PingTimeout = timerDuration;
+ job.LastPingDate = DateTime.UtcNow;
+
+ // Don't start the timer for playback checkins with progressive streaming
+ if (job.Type != TranscodingJobType.Progressive || !isProgressCheckIn)
+ {
+ job.StartKillTimer(OnTranscodeKillTimerStopped);
+ }
+ else
+ {
+ job.ChangeKillTimerIfStarted();
+ }
+ }
+
+ ///
+ /// Called when [transcode kill timer stopped].
+ ///
+ /// The state.
+ private async void OnTranscodeKillTimerStopped(object state)
+ {
+ var job = (TranscodingJobDto)state;
+
+ if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
+ {
+ var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
+
+ if (timeSinceLastPing < job.PingTimeout)
+ {
+ job.StartKillTimer(OnTranscodeKillTimerStopped, job.PingTimeout);
+ return;
+ }
+ }
+
+ _logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
+
+ await KillTranscodingJob(job, true, path => true).ConfigureAwait(false);
+ }
+
+ ///
+ /// Kills the single transcoding job.
+ ///
+ /// The device id.
+ /// The play session identifier.
+ /// The delete files.
+ /// Task.
+ public Task KillTranscodingJobs(string deviceId, string playSessionId, Func deleteFiles)
+ {
+ return KillTranscodingJobs(
+ j => string.IsNullOrWhiteSpace(playSessionId)
+ ? string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase)
+ : string.Equals(playSessionId, j.PlaySessionId, StringComparison.OrdinalIgnoreCase), deleteFiles);
+ }
+
+ ///
+ /// Kills the transcoding jobs.
+ ///
+ /// The kill job.
+ /// The delete files.
+ /// Task.
+ private Task KillTranscodingJobs(Func killJob, Func deleteFiles)
+ {
+ var jobs = new List();
+
+ lock (_activeTranscodingJobs)
+ {
+ // This is really only needed for HLS.
+ // Progressive streams can stop on their own reliably
+ jobs.AddRange(_activeTranscodingJobs.Where(killJob));
+ }
+
+ if (jobs.Count == 0)
+ {
+ return Task.CompletedTask;
+ }
+
+ IEnumerable GetKillJobs()
+ {
+ foreach (var job in jobs)
+ {
+ yield return KillTranscodingJob(job, false, deleteFiles);
+ }
+ }
+
+ return Task.WhenAll(GetKillJobs());
+ }
+
+ ///
+ /// Kills the transcoding job.
+ ///
+ /// The job.
+ /// if set to true [close live stream].
+ /// The delete.
+ private async Task KillTranscodingJob(TranscodingJobDto job, bool closeLiveStream, Func delete)
+ {
+ job.DisposeKillTimer();
+
+ _logger.LogDebug("KillTranscodingJob - JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
+
+ lock (_activeTranscodingJobs)
+ {
+ _activeTranscodingJobs.Remove(job);
+
+ if (!job.CancellationTokenSource!.IsCancellationRequested)
+ {
+ job.CancellationTokenSource.Cancel();
+ }
+ }
+
+ lock (_transcodingLocks)
+ {
+ _transcodingLocks.Remove(job.Path!);
+ }
+
+ lock (job.ProcessLock!)
+ {
+ job.TranscodingThrottler?.Stop().GetAwaiter().GetResult();
+
+ var process = job.Process;
+
+ var hasExited = job.HasExited;
+
+ if (!hasExited)
+ {
+ try
+ {
+ _logger.LogInformation("Stopping ffmpeg process with q command for {Path}", job.Path);
+
+ process!.StandardInput.WriteLine("q");
+
+ // Need to wait because killing is asynchronous
+ if (!process.WaitForExit(5000))
+ {
+ _logger.LogInformation("Killing ffmpeg process for {Path}", job.Path);
+ process.Kill();
+ }
+ }
+ catch (InvalidOperationException)
+ {
+ }
+ }
+ }
+
+ if (delete(job.Path!))
+ {
+ await DeletePartialStreamFiles(job.Path!, job.Type, 0, 1500).ConfigureAwait(false);
+ }
+
+ if (closeLiveStream && !string.IsNullOrWhiteSpace(job.LiveStreamId))
+ {
+ try
+ {
+ await _mediaSourceManager.CloseLiveStream(job.LiveStreamId).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error closing live stream for {Path}", job.Path);
+ }
+ }
+ }
+
+ private async Task DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
+ {
+ if (retryCount >= 10)
+ {
+ return;
+ }
+
+ _logger.LogInformation("Deleting partial stream file(s) {Path}", path);
+
+ await Task.Delay(delayMs).ConfigureAwait(false);
+
+ try
+ {
+ if (jobType == TranscodingJobType.Progressive)
+ {
+ DeleteProgressivePartialStreamFiles(path);
+ }
+ else
+ {
+ DeleteHlsPartialStreamFiles(path);
+ }
+ }
+ catch (IOException ex)
+ {
+ _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
+
+ await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
+ }
+ }
+
+ ///
+ /// Deletes the progressive partial stream files.
+ ///
+ /// The output file path.
+ private void DeleteProgressivePartialStreamFiles(string outputFilePath)
+ {
+ if (File.Exists(outputFilePath))
+ {
+ _fileSystem.DeleteFile(outputFilePath);
+ }
+ }
+
+ ///
+ /// Deletes the HLS partial stream files.
+ ///
+ /// The output file path.
+ private void DeleteHlsPartialStreamFiles(string outputFilePath)
+ {
+ var directory = Path.GetDirectoryName(outputFilePath);
+ var name = Path.GetFileNameWithoutExtension(outputFilePath);
+
+ var filesToDelete = _fileSystem.GetFilePaths(directory)
+ .Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1);
+
+ List? exs = null;
+ foreach (var file in filesToDelete)
+ {
+ try
+ {
+ _logger.LogDebug("Deleting HLS file {0}", file);
+ _fileSystem.DeleteFile(file);
+ }
+ catch (IOException ex)
+ {
+ (exs ??= new List(4)).Add(ex);
+ _logger.LogError(ex, "Error deleting HLS file {Path}", file);
+ }
+ }
+
+ if (exs != null)
+ {
+ throw new AggregateException("Error deleting HLS files", exs);
+ }
+ }
+ }
+}
diff --git a/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs
new file mode 100644
index 0000000000..dcc3224704
--- /dev/null
+++ b/Jellyfin.Api/Models/PlaybackDtos/TranscodingJobDto.cs
@@ -0,0 +1,256 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.Linq;
+using System.Threading;
+using System.Threading.Tasks;
+using MediaBrowser.Controller.MediaEncoding;
+using MediaBrowser.Model.Dto;
+using Microsoft.Extensions.Logging;
+
+namespace Jellyfin.Api.Models.PlaybackDtos
+{
+ ///
+ /// Class TranscodingJob.
+ ///
+ public class TranscodingJobDto
+ {
+ ///
+ /// The process lock.
+ ///
+ [SuppressMessage("Microsoft.Performance", "CA1051:NoVisibleInstanceFields", MessageId = "ProcessLock", Justification = "Imported from ServiceStack")]
+ [SuppressMessage("Microsoft.Performance", "SA1401:PrivateField", MessageId = "ProcessLock", Justification = "Imported from ServiceStack")]
+ public readonly object ProcessLock = new object();
+
+ ///
+ /// Timer lock.
+ ///
+ private readonly object _timerLock = new object();
+
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// Instance of the interface.
+ public TranscodingJobDto(ILogger logger)
+ {
+ Logger = logger;
+ }
+
+ ///
+ /// Gets or sets the play session identifier.
+ ///
+ /// The play session identifier.
+ public string? PlaySessionId { get; set; }
+
+ ///
+ /// Gets or sets the live stream identifier.
+ ///
+ /// The live stream identifier.
+ public string? LiveStreamId { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether is live output.
+ ///
+ public bool IsLiveOutput { get; set; }
+
+ ///
+ /// Gets or sets the path.
+ ///
+ /// The path.
+ public MediaSourceInfo? MediaSource { get; set; }
+
+ ///
+ /// Gets or sets path.
+ ///
+ public string? Path { get; set; }
+
+ ///
+ /// Gets or sets the type.
+ ///
+ /// The type.
+ public TranscodingJobType Type { get; set; }
+
+ ///
+ /// Gets or sets the process.
+ ///
+ /// The process.
+ public Process? Process { get; set; }
+
+ ///
+ /// Gets logger.
+ ///
+ public ILogger Logger { get; private set; }
+
+ ///
+ /// Gets or sets the active request count.
+ ///
+ /// The active request count.
+ public int ActiveRequestCount { get; set; }
+
+ ///
+ /// Gets or sets the kill timer.
+ ///
+ /// The kill timer.
+ private Timer? KillTimer { get; set; }
+
+ ///
+ /// Gets or sets device id.
+ ///
+ public string? DeviceId { get; set; }
+
+ ///
+ /// Gets or sets cancellation token source.
+ ///
+ public CancellationTokenSource? CancellationTokenSource { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether has exited.
+ ///
+ public bool HasExited { get; set; }
+
+ ///
+ /// Gets or sets a value indicating whether is user paused.
+ ///
+ public bool IsUserPaused { get; set; }
+
+ ///
+ /// Gets or sets id.
+ ///
+ public string? Id { get; set; }
+
+ ///
+ /// Gets or sets framerate.
+ ///
+ public float? Framerate { get; set; }
+
+ ///
+ /// Gets or sets completion percentage.
+ ///
+ public double? CompletionPercentage { get; set; }
+
+ ///
+ /// Gets or sets bytes downloaded.
+ ///
+ public long? BytesDownloaded { get; set; }
+
+ ///
+ /// Gets or sets bytes transcoded.
+ ///
+ public long? BytesTranscoded { get; set; }
+
+ ///
+ /// Gets or sets bit rate.
+ ///
+ public int? BitRate { get; set; }
+
+ ///
+ /// Gets or sets transcoding position ticks.
+ ///
+ public long? TranscodingPositionTicks { get; set; }
+
+ ///
+ /// Gets or sets download position ticks.
+ ///
+ public long? DownloadPositionTicks { get; set; }
+
+ ///
+ /// Gets or sets transcoding throttler.
+ ///
+ public TranscodingThrottler? TranscodingThrottler { get; set; }
+
+ ///
+ /// Gets or sets last ping date.
+ ///
+ public DateTime LastPingDate { get; set; }
+
+ ///
+ /// Gets or sets ping timeout.
+ ///
+ public int PingTimeout { get; set; }
+
+ ///
+ /// Stop kill timer.
+ ///
+ public void StopKillTimer()
+ {
+ lock (_timerLock)
+ {
+ KillTimer?.Change(Timeout.Infinite, Timeout.Infinite);
+ }
+ }
+
+ ///
+ /// Dispose kill timer.
+ ///
+ public void DisposeKillTimer()
+ {
+ lock (_timerLock)
+ {
+ if (KillTimer != null)
+ {
+ KillTimer.Dispose();
+ KillTimer = null;
+ }
+ }
+ }
+
+ ///
+ /// Start kill timer.
+ ///
+ /// Callback action.
+ public void StartKillTimer(Action