jellyfin-server/MediaBrowser.Api/ApiEntryPoint.cs

579 lines
18 KiB
C#
Raw Normal View History

using MediaBrowser.Api.Playback;
using MediaBrowser.Controller;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Controller.Session;
using MediaBrowser.Model.Logging;
2014-06-20 04:50:30 +00:00
using MediaBrowser.Model.Session;
using System;
using System.Collections.Generic;
using System.Diagnostics;
2013-06-12 21:47:02 +00:00
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Api
{
/// <summary>
/// Class ServerEntryPoint
/// </summary>
2013-03-08 19:14:09 +00:00
public class ApiEntryPoint : IServerEntryPoint
{
/// <summary>
/// The instance
/// </summary>
2013-03-08 19:14:09 +00:00
public static ApiEntryPoint Instance;
/// <summary>
/// Gets or sets the logger.
/// </summary>
/// <value>The logger.</value>
private ILogger Logger { get; set; }
2013-12-22 18:58:51 +00:00
/// <summary>
/// The application paths
/// </summary>
2014-02-15 16:36:09 +00:00
private readonly IServerApplicationPaths _appPaths;
2013-12-22 18:58:51 +00:00
private readonly ISessionManager _sessionManager;
2014-07-08 01:41:03 +00:00
public readonly SemaphoreSlim TranscodingStartLock = new SemaphoreSlim(1, 1);
2014-07-02 18:34:08 +00:00
/// <summary>
2013-03-08 19:14:09 +00:00
/// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
/// </summary>
/// <param name="logger">The logger.</param>
2013-12-22 18:58:51 +00:00
/// <param name="appPaths">The application paths.</param>
2014-06-26 17:04:11 +00:00
/// <param name="sessionManager">The session manager.</param>
public ApiEntryPoint(ILogger logger, IServerApplicationPaths appPaths, ISessionManager sessionManager)
{
Logger = logger;
2014-02-15 16:36:09 +00:00
_appPaths = appPaths;
_sessionManager = sessionManager;
Instance = this;
}
/// <summary>
/// Runs this instance.
/// </summary>
public void Run()
{
try
{
DeleteEncodedMediaCache();
}
2013-12-22 18:58:51 +00:00
catch (DirectoryNotFoundException)
{
// Don't clutter the log
}
catch (IOException ex)
{
Logger.ErrorException("Error deleting encoded media cache", ex);
}
}
/// <summary>
/// Deletes the encoded media cache.
/// </summary>
private void DeleteEncodedMediaCache()
{
foreach (var file in Directory.EnumerateFiles(_appPaths.TranscodingTempPath, "*", SearchOption.AllDirectories)
.ToList())
{
File.Delete(file);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool dispose)
{
2013-04-10 15:32:09 +00:00
var jobCount = _activeTranscodingJobs.Count;
2014-07-08 01:41:03 +00:00
Parallel.ForEach(_activeTranscodingJobs.ToList(), j => KillTranscodingJob(j, path => true));
// Try to allow for some time to kill the ffmpeg processes and delete the partial stream files
if (jobCount > 0)
{
Thread.Sleep(1000);
}
}
/// <summary>
/// The active transcoding jobs
/// </summary>
2013-04-10 15:32:09 +00:00
private readonly List<TranscodingJob> _activeTranscodingJobs = new List<TranscodingJob>();
/// <summary>
/// Called when [transcode beginning].
/// </summary>
/// <param name="path">The path.</param>
2014-09-03 02:30:24 +00:00
/// <param name="transcodingJobId">The transcoding job identifier.</param>
/// <param name="type">The type.</param>
/// <param name="process">The process.</param>
2013-10-03 14:14:40 +00:00
/// <param name="deviceId">The device id.</param>
/// <param name="state">The state.</param>
2014-06-02 19:32:41 +00:00
/// <param name="cancellationTokenSource">The cancellation token source.</param>
2014-09-03 02:30:24 +00:00
/// <returns>TranscodingJob.</returns>
public TranscodingJob OnTranscodeBeginning(string path,
string transcodingJobId,
TranscodingJobType type,
Process process,
string deviceId,
StreamState state,
CancellationTokenSource cancellationTokenSource)
{
2013-04-10 15:32:09 +00:00
lock (_activeTranscodingJobs)
{
2014-09-03 02:30:24 +00:00
var job = new TranscodingJob
{
Type = type,
Path = path,
Process = process,
2013-06-12 02:59:38 +00:00
ActiveRequestCount = 1,
2014-06-02 19:32:41 +00:00
DeviceId = deviceId,
2014-09-03 02:30:24 +00:00
CancellationTokenSource = cancellationTokenSource,
Id = transcodingJobId
};
_activeTranscodingJobs.Add(job);
ReportTranscodingProgress(job, state, null, null, null, null);
2014-09-03 02:30:24 +00:00
return job;
}
}
2014-09-03 02:30:24 +00:00
public void ReportTranscodingProgress(TranscodingJob job, StreamState state, TimeSpan? transcodingPosition, float? framerate, double? percentComplete, long? bytesTranscoded)
{
2014-09-03 02:30:24 +00:00
var ticks = transcodingPosition.HasValue ? transcodingPosition.Value.Ticks : (long?)null;
if (job != null)
{
job.Framerate = framerate;
job.CompletionPercentage = percentComplete;
job.TranscodingPositionTicks = ticks;
job.BytesTranscoded = bytesTranscoded;
}
var deviceId = state.Request.DeviceId;
if (!string.IsNullOrWhiteSpace(deviceId))
{
2014-10-20 03:04:45 +00:00
var audioCodec = state.ActualOutputVideoCodec;
var videoCodec = state.ActualOutputVideoCodec;
_sessionManager.ReportTranscodingInfo(deviceId, new TranscodingInfo
{
Bitrate = state.TotalOutputBitrate,
AudioCodec = audioCodec,
VideoCodec = videoCodec,
Container = state.OutputContainer,
Framerate = framerate,
2014-06-06 04:56:47 +00:00
CompletionPercentage = percentComplete,
Width = state.OutputWidth,
Height = state.OutputHeight,
AudioChannels = state.OutputAudioChannels
});
}
}
/// <summary>
/// <summary>
/// The progressive
/// </summary>
/// Called when [transcode failed to start].
/// </summary>
/// <param name="path">The path.</param>
/// <param name="type">The type.</param>
/// <param name="state">The state.</param>
public void OnTranscodeFailedToStart(string path, TranscodingJobType type, StreamState state)
{
2013-04-10 15:32:09 +00:00
lock (_activeTranscodingJobs)
{
2013-04-10 15:32:09 +00:00
var job = _activeTranscodingJobs.First(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
2013-04-10 15:32:09 +00:00
_activeTranscodingJobs.Remove(job);
}
if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
{
_sessionManager.ClearTranscodingInfo(state.Request.DeviceId);
}
}
/// <summary>
/// Determines whether [has active transcoding job] [the specified path].
/// </summary>
/// <param name="path">The path.</param>
/// <param name="type">The type.</param>
/// <returns><c>true</c> if [has active transcoding job] [the specified path]; otherwise, <c>false</c>.</returns>
public bool HasActiveTranscodingJob(string path, TranscodingJobType type)
2014-06-26 17:04:11 +00:00
{
return GetTranscodingJob(path, type) != null;
}
public TranscodingJob GetTranscodingJob(string path, TranscodingJobType type)
{
2013-04-10 15:32:09 +00:00
lock (_activeTranscodingJobs)
{
2014-06-26 17:04:11 +00:00
return _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
}
}
2014-09-03 02:30:24 +00:00
public TranscodingJob GetTranscodingJob(string id)
{
lock (_activeTranscodingJobs)
{
return _activeTranscodingJobs.FirstOrDefault(j => j.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
}
}
/// <summary>
/// Called when [transcode begin request].
/// </summary>
/// <param name="path">The path.</param>
/// <param name="type">The type.</param>
2014-09-03 02:30:24 +00:00
public TranscodingJob OnTranscodeBeginRequest(string path, TranscodingJobType type)
{
2013-04-10 15:32:09 +00:00
lock (_activeTranscodingJobs)
{
2013-04-10 15:32:09 +00:00
var job = _activeTranscodingJobs.FirstOrDefault(j => j.Type == type && j.Path.Equals(path, StringComparison.OrdinalIgnoreCase));
if (job == null)
{
2014-09-03 02:30:24 +00:00
return null;
}
job.ActiveRequestCount++;
2014-09-18 04:50:21 +00:00
job.DisposeKillTimer();
2014-09-03 02:30:24 +00:00
return job;
}
}
2014-09-03 02:30:24 +00:00
public void OnTranscodeEndRequest(TranscodingJob job)
{
2014-09-03 02:30:24 +00:00
job.ActiveRequestCount--;
if (job.ActiveRequestCount == 0)
{
2014-09-18 04:50:21 +00:00
if (job.Type == TranscodingJobType.Progressive)
{
2014-09-18 04:50:21 +00:00
const int timerDuration = 1000;
if (job.KillTimer == null)
{
job.KillTimer = new Timer(OnTranscodeKillTimerStopped, job, timerDuration, Timeout.Infinite);
}
else
{
job.KillTimer.Change(timerDuration, Timeout.Infinite);
}
}
}
}
/// <summary>
/// Called when [transcode kill timer stopped].
/// </summary>
/// <param name="state">The state.</param>
private void OnTranscodeKillTimerStopped(object state)
{
var job = (TranscodingJob)state;
2014-07-08 01:41:03 +00:00
KillTranscodingJob(job, path => true);
}
/// <summary>
/// Kills the single transcoding job.
/// </summary>
2013-10-03 14:14:40 +00:00
/// <param name="deviceId">The device id.</param>
2014-07-22 01:29:06 +00:00
/// <param name="deleteFiles">The delete files.</param>
2014-07-08 01:41:03 +00:00
/// <returns>Task.</returns>
2014-07-22 01:29:06 +00:00
/// <exception cref="ArgumentNullException">deviceId</exception>
2014-10-06 23:58:46 +00:00
internal void KillTranscodingJobs(string deviceId, Func<string, bool> deleteFiles)
{
2013-10-03 14:14:40 +00:00
if (string.IsNullOrEmpty(deviceId))
{
2013-10-03 14:14:40 +00:00
throw new ArgumentNullException("deviceId");
}
2014-10-06 23:58:46 +00:00
KillTranscodingJobs(j => string.Equals(deviceId, j.DeviceId, StringComparison.OrdinalIgnoreCase), deleteFiles);
}
2014-06-28 19:35:30 +00:00
/// <summary>
/// Kills the transcoding jobs.
/// </summary>
2014-07-22 01:29:06 +00:00
/// <param name="killJob">The kill job.</param>
/// <param name="deleteFiles">The delete files.</param>
2014-07-08 01:41:03 +00:00
/// <returns>Task.</returns>
2014-10-06 23:58:46 +00:00
internal void KillTranscodingJobs(Func<TranscodingJob, bool> killJob, Func<string, bool> deleteFiles)
2014-06-28 19:35:30 +00:00
{
var jobs = new List<TranscodingJob>();
lock (_activeTranscodingJobs)
{
// This is really only needed for HLS.
// Progressive streams can stop on their own reliably
2014-07-22 01:29:06 +00:00
jobs.AddRange(_activeTranscodingJobs.Where(killJob));
2014-06-28 19:35:30 +00:00
}
2014-07-02 18:34:08 +00:00
if (jobs.Count == 0)
2014-06-28 19:35:30 +00:00
{
2014-07-02 18:34:08 +00:00
return;
}
2014-10-06 23:58:46 +00:00
foreach (var job in jobs)
2014-07-02 18:34:08 +00:00
{
2014-10-06 23:58:46 +00:00
KillTranscodingJob(job, deleteFiles);
2014-06-28 19:35:30 +00:00
}
}
/// <summary>
/// Kills the transcoding job.
/// </summary>
/// <param name="job">The job.</param>
2014-07-08 01:41:03 +00:00
/// <param name="delete">The delete.</param>
private void KillTranscodingJob(TranscodingJob job, Func<string, bool> delete)
{
2013-04-10 15:32:09 +00:00
lock (_activeTranscodingJobs)
{
2013-04-10 15:32:09 +00:00
_activeTranscodingJobs.Remove(job);
2014-06-02 19:32:41 +00:00
if (!job.CancellationTokenSource.IsCancellationRequested)
{
job.CancellationTokenSource.Cancel();
}
2014-09-18 04:50:21 +00:00
job.DisposeKillTimer();
}
2014-06-20 04:50:30 +00:00
lock (job.ProcessLock)
{
2014-06-20 04:50:30 +00:00
var process = job.Process;
2013-06-10 04:00:44 +00:00
2014-06-20 04:50:30 +00:00
var hasExited = true;
2013-06-10 04:00:44 +00:00
2014-06-20 04:50:30 +00:00
try
2013-06-10 04:00:44 +00:00
{
2014-06-20 04:50:30 +00:00
hasExited = process.HasExited;
2013-06-10 04:00:44 +00:00
}
2014-06-20 04:50:30 +00:00
catch (Exception ex)
2013-06-10 04:00:44 +00:00
{
2014-06-20 04:50:30 +00:00
Logger.ErrorException("Error determining if ffmpeg process has exited for {0}", ex, job.Path);
2013-06-10 04:00:44 +00:00
}
2014-06-20 04:50:30 +00:00
if (!hasExited)
2013-06-10 04:00:44 +00:00
{
2014-06-20 04:50:30 +00:00
try
{
Logger.Info("Killing ffmpeg process for {0}", job.Path);
//process.Kill();
process.StandardInput.WriteLine("q");
// Need to wait because killing is asynchronous
process.WaitForExit(5000);
}
catch (Exception ex)
{
Logger.ErrorException("Error killing transcoding job for {0}", ex, job.Path);
}
2013-06-10 04:00:44 +00:00
}
}
2014-07-08 01:41:03 +00:00
if (delete(job.Path))
2014-06-20 04:50:30 +00:00
{
DeletePartialStreamFiles(job.Path, job.Type, 0, 1500);
}
2014-01-03 04:58:22 +00:00
}
2013-06-10 04:00:44 +00:00
2014-01-03 04:58:22 +00:00
private async void DeletePartialStreamFiles(string path, TranscodingJobType jobType, int retryCount, int delayMs)
{
2014-06-29 02:30:20 +00:00
if (retryCount >= 10)
2014-01-03 04:58:22 +00:00
{
return;
}
2013-06-10 04:00:44 +00:00
2014-01-03 04:58:22 +00:00
Logger.Info("Deleting partial stream file(s) {0}", path);
await Task.Delay(delayMs).ConfigureAwait(false);
try
{
if (jobType == TranscodingJobType.Progressive)
2013-06-10 04:00:44 +00:00
{
2014-01-03 04:58:22 +00:00
DeleteProgressivePartialStreamFiles(path);
2013-06-10 04:00:44 +00:00
}
2014-01-03 04:58:22 +00:00
else
2013-06-10 04:00:44 +00:00
{
2014-01-03 04:58:22 +00:00
DeleteHlsPartialStreamFiles(path);
2013-06-10 04:00:44 +00:00
}
2014-09-09 01:15:31 +00:00
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
}
2014-01-03 04:58:22 +00:00
catch (IOException ex)
{
Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
DeletePartialStreamFiles(path, jobType, retryCount + 1, 500);
}
catch (Exception ex)
{
Logger.ErrorException("Error deleting partial stream file(s) {0}", ex, path);
}
}
2013-06-10 04:00:44 +00:00
/// <summary>
/// Deletes the progressive partial stream files.
/// </summary>
/// <param name="outputFilePath">The output file path.</param>
private void DeleteProgressivePartialStreamFiles(string outputFilePath)
{
File.Delete(outputFilePath);
}
/// <summary>
/// Deletes the HLS partial stream files.
/// </summary>
/// <param name="outputFilePath">The output file path.</param>
private void DeleteHlsPartialStreamFiles(string outputFilePath)
{
var directory = Path.GetDirectoryName(outputFilePath);
var name = Path.GetFileNameWithoutExtension(outputFilePath);
var filesToDelete = Directory.EnumerateFiles(directory)
.Where(f => f.IndexOf(name, StringComparison.OrdinalIgnoreCase) != -1)
.ToList();
2014-06-28 19:35:30 +00:00
Exception e = null;
2013-06-10 04:00:44 +00:00
foreach (var file in filesToDelete)
{
try
{
Logger.Info("Deleting HLS file {0}", file);
File.Delete(file);
2014-09-09 01:15:31 +00:00
}
catch (DirectoryNotFoundException)
{
}
catch (FileNotFoundException)
{
2014-10-06 23:58:46 +00:00
2013-06-10 04:00:44 +00:00
}
catch (IOException ex)
{
2014-06-28 19:35:30 +00:00
e = ex;
2013-06-10 04:00:44 +00:00
Logger.ErrorException("Error deleting HLS file {0}", ex, file);
}
}
2014-06-28 19:35:30 +00:00
if (e != null)
{
throw e;
}
2013-06-10 04:00:44 +00:00
}
}
/// <summary>
/// Class TranscodingJob
/// </summary>
public class TranscodingJob
{
/// <summary>
/// Gets or sets the path.
/// </summary>
/// <value>The path.</value>
public string Path { get; set; }
/// <summary>
/// Gets or sets the type.
/// </summary>
/// <value>The type.</value>
public TranscodingJobType Type { get; set; }
/// <summary>
/// Gets or sets the process.
/// </summary>
/// <value>The process.</value>
public Process Process { get; set; }
/// <summary>
/// Gets or sets the active request count.
/// </summary>
/// <value>The active request count.</value>
public int ActiveRequestCount { get; set; }
/// <summary>
/// Gets or sets the kill timer.
/// </summary>
/// <value>The kill timer.</value>
public Timer KillTimer { get; set; }
2013-06-12 02:59:38 +00:00
2013-10-03 14:14:40 +00:00
public string DeviceId { get; set; }
2014-06-02 19:32:41 +00:00
public CancellationTokenSource CancellationTokenSource { get; set; }
2014-06-20 04:50:30 +00:00
public object ProcessLock = new object();
2014-06-26 17:04:11 +00:00
public bool HasExited { get; set; }
2014-09-03 02:30:24 +00:00
public string Id { get; set; }
public float? Framerate { get; set; }
public double? CompletionPercentage { get; set; }
public long? BytesDownloaded { get; set; }
public long? BytesTranscoded { get; set; }
2014-10-06 23:58:46 +00:00
2014-09-03 02:30:24 +00:00
public long? TranscodingPositionTicks { get; set; }
public long? DownloadPositionTicks { get; set; }
2014-09-18 04:50:21 +00:00
public void DisposeKillTimer()
{
if (KillTimer != null)
{
KillTimer.Dispose();
KillTimer = null;
}
}
}
/// <summary>
/// Enum TranscodingJobType
/// </summary>
public enum TranscodingJobType
{
/// <summary>
/// The progressive
/// </summary>
Progressive,
/// <summary>
/// The HLS
/// </summary>
2014-10-12 17:31:41 +00:00
Hls,
/// <summary>
/// The dash
/// </summary>
Dash
}
}