Merge pull request #798 from Bond-009/apientrypoint

Cleanup around the api endpoints
pull/810/head
Vasily 6 years ago committed by GitHub
commit 83af2db679
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Threading; using System.Threading;
@ -58,6 +59,8 @@ namespace MediaBrowser.Api
private readonly Dictionary<string, SemaphoreSlim> _transcodingLocks = private readonly Dictionary<string, SemaphoreSlim> _transcodingLocks =
new Dictionary<string, SemaphoreSlim>(); new Dictionary<string, SemaphoreSlim>();
private bool _disposed = false;
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="ApiEntryPoint" /> class. /// Initializes a new instance of the <see cref="ApiEntryPoint" /> class.
/// </summary> /// </summary>
@ -66,7 +69,15 @@ namespace MediaBrowser.Api
/// <param name="config">The configuration.</param> /// <param name="config">The configuration.</param>
/// <param name="fileSystem">The file system.</param> /// <param name="fileSystem">The file system.</param>
/// <param name="mediaSourceManager">The media source manager.</param> /// <param name="mediaSourceManager">The media source manager.</param>
public ApiEntryPoint(ILogger logger, ISessionManager sessionManager, IServerConfigurationManager config, IFileSystem fileSystem, IMediaSourceManager mediaSourceManager, ITimerFactory timerFactory, IProcessFactory processFactory, IHttpResultFactory resultFactory) public ApiEntryPoint(
ILogger logger,
ISessionManager sessionManager,
IServerConfigurationManager config,
IFileSystem fileSystem,
IMediaSourceManager mediaSourceManager,
ITimerFactory timerFactory,
IProcessFactory processFactory,
IHttpResultFactory resultFactory)
{ {
Logger = logger; Logger = logger;
_sessionManager = sessionManager; _sessionManager = sessionManager;
@ -77,9 +88,10 @@ namespace MediaBrowser.Api
ProcessFactory = processFactory; ProcessFactory = processFactory;
ResultFactory = resultFactory; ResultFactory = resultFactory;
Instance = this;
_sessionManager.PlaybackProgress += _sessionManager_PlaybackProgress; _sessionManager.PlaybackProgress += _sessionManager_PlaybackProgress;
_sessionManager.PlaybackStart += _sessionManager_PlaybackStart; _sessionManager.PlaybackStart += _sessionManager_PlaybackStart;
Instance = this;
} }
public static string[] Split(string value, char separator, bool removeEmpty) public static string[] Split(string value, char separator, bool removeEmpty)
@ -185,17 +197,40 @@ namespace MediaBrowser.Api
/// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> /// <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) protected virtual void Dispose(bool dispose)
{ {
var list = _activeTranscodingJobs.ToList(); if (_disposed)
var jobCount = list.Count; {
return;
}
if (dispose)
{
// TODO: dispose
}
Parallel.ForEach(list, j => KillTranscodingJob(j, false, path => true)); var jobs = _activeTranscodingJobs.ToList();
var jobCount = jobs.Count;
// Try to allow for some time to kill the ffmpeg processes and delete the partial stream files IEnumerable<Task> GetKillJobs()
{
foreach (var job in jobs)
{
yield return KillTranscodingJob(job, false, path => true);
}
}
// Wait for all processes to be killed
if (jobCount > 0) if (jobCount > 0)
{ {
var task = Task.Delay(1000); Task.WaitAll(GetKillJobs().ToArray());
Task.WaitAll(task);
} }
_activeTranscodingJobs.Clear();
_transcodingLocks.Clear();
_sessionManager.PlaybackProgress -= _sessionManager_PlaybackProgress;
_sessionManager.PlaybackStart -= _sessionManager_PlaybackStart;
_disposed = true;
} }
@ -212,12 +247,13 @@ namespace MediaBrowser.Api
/// <param name="state">The state.</param> /// <param name="state">The state.</param>
/// <param name="cancellationTokenSource">The cancellation token source.</param> /// <param name="cancellationTokenSource">The cancellation token source.</param>
/// <returns>TranscodingJob.</returns> /// <returns>TranscodingJob.</returns>
public TranscodingJob OnTranscodeBeginning(string path, public TranscodingJob OnTranscodeBeginning(
string path,
string playSessionId, string playSessionId,
string liveStreamId, string liveStreamId,
string transcodingJobId, string transcodingJobId,
TranscodingJobType type, TranscodingJobType type,
IProcess process, Process process,
string deviceId, string deviceId,
StreamState state, StreamState state,
CancellationTokenSource cancellationTokenSource) CancellationTokenSource cancellationTokenSource)
@ -446,7 +482,7 @@ namespace MediaBrowser.Api
/// Called when [transcode kill timer stopped]. /// Called when [transcode kill timer stopped].
/// </summary> /// </summary>
/// <param name="state">The state.</param> /// <param name="state">The state.</param>
private void OnTranscodeKillTimerStopped(object state) private async void OnTranscodeKillTimerStopped(object state)
{ {
var job = (TranscodingJob)state; var job = (TranscodingJob)state;
@ -463,7 +499,7 @@ namespace MediaBrowser.Api
Logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId); Logger.LogInformation("Transcoding kill timer stopped for JobId {0} PlaySessionId {1}. Killing transcoding", job.Id, job.PlaySessionId);
KillTranscodingJob(job, true, path => true).GetAwaiter().GetResult(); await KillTranscodingJob(job, true, path => true);
} }
/// <summary> /// <summary>
@ -551,7 +587,7 @@ namespace MediaBrowser.Api
{ {
if (job.TranscodingThrottler != null) if (job.TranscodingThrottler != null)
{ {
job.TranscodingThrottler.Stop(); job.TranscodingThrottler.Stop().GetAwaiter().GetResult();
} }
var process = job.Process; var process = job.Process;
@ -562,7 +598,7 @@ namespace MediaBrowser.Api
{ {
try try
{ {
Logger.LogInformation("Stopping ffmpeg process with q command for {path}", job.Path); Logger.LogInformation("Stopping ffmpeg process with q command for {Path}", job.Path);
//process.Kill(); //process.Kill();
process.StandardInput.WriteLine("q"); process.StandardInput.WriteLine("q");
@ -570,13 +606,13 @@ namespace MediaBrowser.Api
// Need to wait because killing is asynchronous // Need to wait because killing is asynchronous
if (!process.WaitForExit(5000)) if (!process.WaitForExit(5000))
{ {
Logger.LogInformation("Killing ffmpeg process for {path}", job.Path); Logger.LogInformation("Killing ffmpeg process for {Path}", job.Path);
process.Kill(); process.Kill();
} }
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, "Error killing transcoding job for {path}", job.Path); Logger.LogError(ex, "Error killing transcoding job for {Path}", job.Path);
} }
} }
} }
@ -606,7 +642,7 @@ namespace MediaBrowser.Api
return; return;
} }
Logger.LogInformation("Deleting partial stream file(s) {0}", path); Logger.LogInformation("Deleting partial stream file(s) {Path}", path);
await Task.Delay(delayMs).ConfigureAwait(false); await Task.Delay(delayMs).ConfigureAwait(false);
@ -627,13 +663,13 @@ namespace MediaBrowser.Api
} }
catch (IOException ex) catch (IOException ex)
{ {
Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); Logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false); await DeletePartialStreamFiles(path, jobType, retryCount + 1, 500).ConfigureAwait(false);
} }
catch (Exception ex) catch (Exception ex)
{ {
Logger.LogError(ex, "Error deleting partial stream file(s) {path}", path); Logger.LogError(ex, "Error deleting partial stream file(s) {Path}", path);
} }
} }
@ -674,7 +710,7 @@ namespace MediaBrowser.Api
catch (IOException ex) catch (IOException ex)
{ {
e = ex; e = ex;
Logger.LogError(ex, "Error deleting HLS file {path}", file); Logger.LogError(ex, "Error deleting HLS file {Path}", file);
} }
} }
@ -718,7 +754,7 @@ namespace MediaBrowser.Api
/// Gets or sets the process. /// Gets or sets the process.
/// </summary> /// </summary>
/// <value>The process.</value> /// <value>The process.</value>
public IProcess Process { get; set; } public Process Process { get; set; }
public ILogger Logger { get; private set; } public ILogger Logger { get; private set; }
/// <summary> /// <summary>
/// Gets or sets the active request count. /// Gets or sets the active request count.

@ -43,7 +43,7 @@ namespace MediaBrowser.Api
public static string[] SplitValue(string value, char delim) public static string[] SplitValue(string value, char delim)
{ {
if (string.IsNullOrWhiteSpace(value)) if (value == null)
{ {
return Array.Empty<string>(); return Array.Empty<string>();
} }
@ -53,8 +53,14 @@ namespace MediaBrowser.Api
public static Guid[] GetGuids(string value) public static Guid[] GetGuids(string value)
{ {
// Unfortunately filtermenu.js was using |. This can be deprecated after a while. if (value == null)
return (value ?? string.Empty).Split(new[] { ',', '|' }, StringSplitOptions.RemoveEmptyEntries).Select(i => new Guid(i)).ToArray(); {
return Array.Empty<Guid>();
}
return value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
.Select(i => new Guid(i))
.ToArray();
} }
/// <summary> /// <summary>
@ -118,7 +124,8 @@ namespace MediaBrowser.Api
options.Fields = hasFields.GetItemFields(); options.Fields = hasFields.GetItemFields();
} }
if (!options.ContainsField(Model.Querying.ItemFields.RecursiveItemCount) || !options.ContainsField(Model.Querying.ItemFields.ChildCount)) if (!options.ContainsField(Model.Querying.ItemFields.RecursiveItemCount)
|| !options.ContainsField(Model.Querying.ItemFields.ChildCount))
{ {
var client = authContext.GetAuthorizationInfo(Request).Client ?? string.Empty; var client = authContext.GetAuthorizationInfo(Request).Client ?? string.Empty;
if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 || if (client.IndexOf("kodi", StringComparison.OrdinalIgnoreCase) != -1 ||
@ -145,8 +152,7 @@ namespace MediaBrowser.Api
} }
} }
var hasDtoOptions = request as IHasDtoOptions; if (request is IHasDtoOptions hasDtoOptions)
if (hasDtoOptions != null)
{ {
options.EnableImages = hasDtoOptions.EnableImages ?? true; options.EnableImages = hasDtoOptions.EnableImages ?? true;
@ -294,7 +300,7 @@ namespace MediaBrowser.Api
return pathInfo[index]; return pathInfo[index];
} }
private List<string> Parse(string pathUri) private string[] Parse(string pathUri)
{ {
var actionParts = pathUri.Split(new[] { "://" }, StringSplitOptions.None); var actionParts = pathUri.Split(new[] { "://" }, StringSplitOptions.None);
@ -308,7 +314,7 @@ namespace MediaBrowser.Api
var args = pathInfo.Split('/'); var args = pathInfo.Split('/');
return args.Skip(1).ToList(); return args.Skip(1).ToArray();
} }
/// <summary> /// <summary>

@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
@ -68,10 +69,8 @@ namespace MediaBrowser.Api.Playback
protected IDeviceManager DeviceManager { get; private set; } protected IDeviceManager DeviceManager { get; private set; }
protected ISubtitleEncoder SubtitleEncoder { get; private set; } protected ISubtitleEncoder SubtitleEncoder { get; private set; }
protected IMediaSourceManager MediaSourceManager { get; private set; } protected IMediaSourceManager MediaSourceManager { get; private set; }
protected IZipClient ZipClient { get; private set; }
protected IJsonSerializer JsonSerializer { get; private set; } protected IJsonSerializer JsonSerializer { get; private set; }
public static IServerApplicationHost AppHost;
public static IHttpClient HttpClient; public static IHttpClient HttpClient;
protected IAuthorizationContext AuthorizationContext { get; private set; } protected IAuthorizationContext AuthorizationContext { get; private set; }
@ -80,21 +79,33 @@ namespace MediaBrowser.Api.Playback
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="BaseStreamingService" /> class. /// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
/// </summary> /// </summary>
protected BaseStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext) protected BaseStreamingService(
IServerConfigurationManager serverConfig,
IUserManager userManager,
ILibraryManager libraryManager,
IIsoManager isoManager,
IMediaEncoder mediaEncoder,
IFileSystem fileSystem,
IDlnaManager dlnaManager,
ISubtitleEncoder subtitleEncoder,
IDeviceManager deviceManager,
IMediaSourceManager mediaSourceManager,
IJsonSerializer jsonSerializer,
IAuthorizationContext authorizationContext)
{ {
JsonSerializer = jsonSerializer;
AuthorizationContext = authorizationContext;
ZipClient = zipClient;
MediaSourceManager = mediaSourceManager;
DeviceManager = deviceManager;
SubtitleEncoder = subtitleEncoder;
DlnaManager = dlnaManager;
FileSystem = fileSystem;
ServerConfigurationManager = serverConfig; ServerConfigurationManager = serverConfig;
UserManager = userManager; UserManager = userManager;
LibraryManager = libraryManager; LibraryManager = libraryManager;
IsoManager = isoManager; IsoManager = isoManager;
MediaEncoder = mediaEncoder; MediaEncoder = mediaEncoder;
FileSystem = fileSystem;
DlnaManager = dlnaManager;
SubtitleEncoder = subtitleEncoder;
DeviceManager = deviceManager;
MediaSourceManager = mediaSourceManager;
JsonSerializer = jsonSerializer;
AuthorizationContext = authorizationContext;
EncodingHelper = new EncodingHelper(MediaEncoder, FileSystem, SubtitleEncoder); EncodingHelper = new EncodingHelper(MediaEncoder, FileSystem, SubtitleEncoder);
} }
@ -187,7 +198,8 @@ namespace MediaBrowser.Api.Playback
/// <param name="cancellationTokenSource">The cancellation token source.</param> /// <param name="cancellationTokenSource">The cancellation token source.</param>
/// <param name="workingDirectory">The working directory.</param> /// <param name="workingDirectory">The working directory.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
protected async Task<TranscodingJob> StartFfMpeg(StreamState state, protected async Task<TranscodingJob> StartFfMpeg(
StreamState state,
string outputPath, string outputPath,
CancellationTokenSource cancellationTokenSource, CancellationTokenSource cancellationTokenSource,
string workingDirectory = null) string workingDirectory = null)
@ -215,24 +227,27 @@ namespace MediaBrowser.Api.Playback
var transcodingId = Guid.NewGuid().ToString("N"); var transcodingId = Guid.NewGuid().ToString("N");
var commandLineArgs = GetCommandLineArguments(outputPath, encodingOptions, state, true); var commandLineArgs = GetCommandLineArguments(outputPath, encodingOptions, state, true);
var process = ApiEntryPoint.Instance.ProcessFactory.Create(new ProcessOptions var process = new Process()
{ {
CreateNoWindow = true, StartInfo = new ProcessStartInfo()
UseShellExecute = false, {
WindowStyle = ProcessWindowStyle.Hidden,
// Must consume both stdout and stderr or deadlocks may occur CreateNoWindow = true,
//RedirectStandardOutput = true, UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true, // Must consume both stdout and stderr or deadlocks may occur
//RedirectStandardOutput = true,
FileName = MediaEncoder.EncoderPath, RedirectStandardError = true,
Arguments = commandLineArgs, RedirectStandardInput = true,
IsHidden = true, FileName = MediaEncoder.EncoderPath,
ErrorDialog = false, Arguments = commandLineArgs,
EnableRaisingEvents = true, WorkingDirectory = string.IsNullOrWhiteSpace(workingDirectory) ? null : workingDirectory,
WorkingDirectory = !string.IsNullOrWhiteSpace(workingDirectory) ? workingDirectory : null
}); ErrorDialog = false
},
EnableRaisingEvents = true
};
var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath, var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath,
state.Request.PlaySessionId, state.Request.PlaySessionId,
@ -248,13 +263,17 @@ namespace MediaBrowser.Api.Playback
Logger.LogInformation(commandLineLogMessage); Logger.LogInformation(commandLineLogMessage);
var logFilePrefix = "ffmpeg-transcode"; var logFilePrefix = "ffmpeg-transcode";
if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase)) if (state.VideoRequest != null)
{
logFilePrefix = "ffmpeg-directstream";
}
else if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
{ {
logFilePrefix = "ffmpeg-remux"; if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase)
&& string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
{
logFilePrefix = "ffmpeg-directstream";
}
else if (string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
{
logFilePrefix = "ffmpeg-remux";
}
} }
var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt"); var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt");
@ -341,7 +360,7 @@ namespace MediaBrowser.Api.Playback
/// <param name="process">The process.</param> /// <param name="process">The process.</param>
/// <param name="job">The job.</param> /// <param name="job">The job.</param>
/// <param name="state">The state.</param> /// <param name="state">The state.</param>
private void OnFfMpegProcessExited(IProcess process, TranscodingJob job, StreamState state) private void OnFfMpegProcessExited(Process process, TranscodingJob job, StreamState state)
{ {
if (job != null) if (job != null)
{ {

@ -54,17 +54,6 @@ namespace MediaBrowser.Api.Playback.Hls
/// <value>The type of the transcoding job.</value> /// <value>The type of the transcoding job.</value>
protected override TranscodingJobType TranscodingJobType => TranscodingJobType.Hls; protected override TranscodingJobType TranscodingJobType => TranscodingJobType.Hls;
/// <summary>
/// Processes the request.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="isLive">if set to <c>true</c> [is live].</param>
/// <returns>System.Object.</returns>
protected async Task<object> ProcessRequest(StreamRequest request, bool isLive)
{
return await ProcessRequestAsync(request, isLive).ConfigureAwait(false);
}
/// <summary> /// <summary>
/// Processes the request async. /// Processes the request async.
/// </summary> /// </summary>
@ -74,7 +63,7 @@ namespace MediaBrowser.Api.Playback.Hls
/// <exception cref="ArgumentException">A video bitrate is required /// <exception cref="ArgumentException">A video bitrate is required
/// or /// or
/// An audio bitrate is required</exception> /// An audio bitrate is required</exception>
private async Task<object> ProcessRequestAsync(StreamRequest request, bool isLive) protected async Task<object> ProcessRequestAsync(StreamRequest request, bool isLive)
{ {
var cancellationTokenSource = new CancellationTokenSource(); var cancellationTokenSource = new CancellationTokenSource();
@ -324,7 +313,31 @@ namespace MediaBrowser.Api.Playback.Hls
return 0; return 0;
} }
public BaseHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer, authorizationContext) public BaseHlsService(
IServerConfigurationManager serverConfig,
IUserManager userManager,
ILibraryManager libraryManager,
IIsoManager isoManager,
IMediaEncoder mediaEncoder,
IFileSystem fileSystem,
IDlnaManager dlnaManager,
ISubtitleEncoder subtitleEncoder,
IDeviceManager deviceManager,
IMediaSourceManager mediaSourceManager,
IJsonSerializer jsonSerializer,
IAuthorizationContext authorizationContext)
: base(serverConfig,
userManager,
libraryManager,
isoManager,
mediaEncoder,
fileSystem,
dlnaManager,
subtitleEncoder,
deviceManager,
mediaSourceManager,
jsonSerializer,
authorizationContext)
{ {
} }
} }

@ -95,7 +95,32 @@ namespace MediaBrowser.Api.Playback.Hls
public class DynamicHlsService : BaseHlsService public class DynamicHlsService : BaseHlsService
{ {
public DynamicHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext, INetworkManager networkManager) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer, authorizationContext) public DynamicHlsService(
IServerConfigurationManager serverConfig,
IUserManager userManager,
ILibraryManager libraryManager,
IIsoManager isoManager,
IMediaEncoder mediaEncoder,
IFileSystem fileSystem,
IDlnaManager dlnaManager,
ISubtitleEncoder subtitleEncoder,
IDeviceManager deviceManager,
IMediaSourceManager mediaSourceManager,
IJsonSerializer jsonSerializer,
IAuthorizationContext authorizationContext,
INetworkManager networkManager)
: base(serverConfig,
userManager,
libraryManager,
isoManager,
mediaEncoder,
fileSystem,
dlnaManager,
subtitleEncoder,
deviceManager,
mediaSourceManager,
jsonSerializer,
authorizationContext)
{ {
NetworkManager = networkManager; NetworkManager = networkManager;
} }
@ -209,7 +234,7 @@ namespace MediaBrowser.Api.Playback.Hls
// If the playlist doesn't already exist, startup ffmpeg // If the playlist doesn't already exist, startup ffmpeg
try try
{ {
ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.PlaySessionId, p => false); await ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.PlaySessionId, p => false);
if (currentTranscodingIndex.HasValue) if (currentTranscodingIndex.HasValue)
{ {
@ -233,7 +258,7 @@ namespace MediaBrowser.Api.Playback.Hls
job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(playlistPath, TranscodingJobType);
if (job.TranscodingThrottler != null) if (job.TranscodingThrottler != null)
{ {
job.TranscodingThrottler.UnpauseTranscoding(); await job.TranscodingThrottler.UnpauseTranscoding();
} }
} }
} }

@ -102,9 +102,9 @@ namespace MediaBrowser.Api.Playback.Hls
return GetFileResult(file, file); return GetFileResult(file, file);
} }
public void Delete(StopEncodingProcess request) public Task Delete(StopEncodingProcess request)
{ {
ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.PlaySessionId, path => true); return ApiEntryPoint.Instance.KillTranscodingJobs(request.DeviceId, request.PlaySessionId, path => true);
} }
/// <summary> /// <summary>

@ -1,4 +1,5 @@
using System; using System;
using System.Threading.Tasks;
using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Devices;
using MediaBrowser.Controller.Dlna; using MediaBrowser.Controller.Dlna;
@ -24,9 +25,9 @@ namespace MediaBrowser.Api.Playback.Hls
[Authenticated] [Authenticated]
public class VideoHlsService : BaseHlsService public class VideoHlsService : BaseHlsService
{ {
public object Get(GetLiveHlsStream request) public Task<object> Get(GetLiveHlsStream request)
{ {
return ProcessRequest(request, true); return ProcessRequestAsync(request, true);
} }
/// <summary> /// <summary>
@ -130,7 +131,31 @@ namespace MediaBrowser.Api.Playback.Hls
return args; return args;
} }
public VideoHlsService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer, authorizationContext) public VideoHlsService(
IServerConfigurationManager serverConfig,
IUserManager userManager,
ILibraryManager libraryManager,
IIsoManager isoManager,
IMediaEncoder mediaEncoder,
IFileSystem fileSystem,
IDlnaManager dlnaManager,
ISubtitleEncoder subtitleEncoder,
IDeviceManager deviceManager,
IMediaSourceManager mediaSourceManager,
IJsonSerializer jsonSerializer,
IAuthorizationContext authorizationContext)
: base(serverConfig,
userManager,
libraryManager,
isoManager,
mediaEncoder,
fileSystem,
dlnaManager,
subtitleEncoder,
deviceManager,
mediaSourceManager,
jsonSerializer,
authorizationContext)
{ {
} }
} }

@ -32,7 +32,33 @@ namespace MediaBrowser.Api.Playback.Progressive
//[Authenticated] //[Authenticated]
public class AudioService : BaseProgressiveStreamingService public class AudioService : BaseProgressiveStreamingService
{ {
public AudioService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext, IImageProcessor imageProcessor, IEnvironmentInfo environmentInfo) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer, authorizationContext, imageProcessor, environmentInfo) public AudioService(
IServerConfigurationManager serverConfig,
IUserManager userManager,
ILibraryManager libraryManager,
IIsoManager isoManager,
IMediaEncoder mediaEncoder,
IFileSystem fileSystem,
IDlnaManager dlnaManager,
ISubtitleEncoder subtitleEncoder,
IDeviceManager deviceManager,
IMediaSourceManager mediaSourceManager,
IJsonSerializer jsonSerializer,
IAuthorizationContext authorizationContext,
IEnvironmentInfo environmentInfo)
: base(serverConfig,
userManager,
libraryManager,
isoManager,
mediaEncoder,
fileSystem,
dlnaManager,
subtitleEncoder,
deviceManager,
mediaSourceManager,
jsonSerializer,
authorizationContext,
environmentInfo)
{ {
} }

@ -25,12 +25,35 @@ namespace MediaBrowser.Api.Playback.Progressive
/// </summary> /// </summary>
public abstract class BaseProgressiveStreamingService : BaseStreamingService public abstract class BaseProgressiveStreamingService : BaseStreamingService
{ {
protected readonly IImageProcessor ImageProcessor;
protected readonly IEnvironmentInfo EnvironmentInfo; protected readonly IEnvironmentInfo EnvironmentInfo;
public BaseProgressiveStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext, IImageProcessor imageProcessor, IEnvironmentInfo environmentInfo) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer, authorizationContext) public BaseProgressiveStreamingService(
IServerConfigurationManager serverConfig,
IUserManager userManager,
ILibraryManager libraryManager,
IIsoManager isoManager,
IMediaEncoder mediaEncoder,
IFileSystem fileSystem,
IDlnaManager dlnaManager,
ISubtitleEncoder subtitleEncoder,
IDeviceManager deviceManager,
IMediaSourceManager mediaSourceManager,
IJsonSerializer jsonSerializer,
IAuthorizationContext authorizationContext,
IEnvironmentInfo environmentInfo)
: base(serverConfig,
userManager,
libraryManager,
isoManager,
mediaEncoder,
fileSystem,
dlnaManager,
subtitleEncoder,
deviceManager,
mediaSourceManager,
jsonSerializer,
authorizationContext)
{ {
ImageProcessor = imageProcessor;
EnvironmentInfo = environmentInfo; EnvironmentInfo = environmentInfo;
} }

@ -68,7 +68,33 @@ namespace MediaBrowser.Api.Playback.Progressive
//[Authenticated] //[Authenticated]
public class VideoService : BaseProgressiveStreamingService public class VideoService : BaseProgressiveStreamingService
{ {
public VideoService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, IDlnaManager dlnaManager, ISubtitleEncoder subtitleEncoder, IDeviceManager deviceManager, IMediaSourceManager mediaSourceManager, IZipClient zipClient, IJsonSerializer jsonSerializer, IAuthorizationContext authorizationContext, IImageProcessor imageProcessor, IEnvironmentInfo environmentInfo) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer, authorizationContext, imageProcessor, environmentInfo) public VideoService(
IServerConfigurationManager serverConfig,
IUserManager userManager,
ILibraryManager libraryManager,
IIsoManager isoManager,
IMediaEncoder mediaEncoder,
IFileSystem fileSystem,
IDlnaManager dlnaManager,
ISubtitleEncoder subtitleEncoder,
IDeviceManager deviceManager,
IMediaSourceManager mediaSourceManager,
IJsonSerializer jsonSerializer,
IAuthorizationContext authorizationContext,
IEnvironmentInfo environmentInfo)
: base(serverConfig,
userManager,
libraryManager,
isoManager,
mediaEncoder,
fileSystem,
dlnaManager,
subtitleEncoder,
deviceManager,
mediaSourceManager,
jsonSerializer,
authorizationContext,
environmentInfo)
{ {
} }

@ -1,4 +1,5 @@
using System; using System;
using System.Threading.Tasks;
using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Configuration;
using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.IO; using MediaBrowser.Model.IO;
@ -36,7 +37,7 @@ namespace MediaBrowser.Api.Playback
_timer = _timerFactory.Create(TimerCallback, null, 5000, 5000); _timer = _timerFactory.Create(TimerCallback, null, 5000, 5000);
} }
private void TimerCallback(object state) private async void TimerCallback(object state)
{ {
if (_job.HasExited) if (_job.HasExited)
{ {
@ -48,15 +49,15 @@ namespace MediaBrowser.Api.Playback
if (options.EnableThrottling && IsThrottleAllowed(_job, options.ThrottleDelaySeconds)) if (options.EnableThrottling && IsThrottleAllowed(_job, options.ThrottleDelaySeconds))
{ {
PauseTranscoding(); await PauseTranscoding();
} }
else else
{ {
UnpauseTranscoding(); await UnpauseTranscoding();
} }
} }
private void PauseTranscoding() private async Task PauseTranscoding()
{ {
if (!_isPaused) if (!_isPaused)
{ {
@ -64,7 +65,7 @@ namespace MediaBrowser.Api.Playback
try try
{ {
_job.Process.StandardInput.Write("c"); await _job.Process.StandardInput.WriteAsync("c");
_isPaused = true; _isPaused = true;
} }
catch (Exception ex) catch (Exception ex)
@ -74,7 +75,7 @@ namespace MediaBrowser.Api.Playback
} }
} }
public void UnpauseTranscoding() public async Task UnpauseTranscoding()
{ {
if (_isPaused) if (_isPaused)
{ {
@ -82,7 +83,7 @@ namespace MediaBrowser.Api.Playback
try try
{ {
_job.Process.StandardInput.WriteLine(); await _job.Process.StandardInput.WriteLineAsync();
_isPaused = false; _isPaused = false;
} }
catch (Exception ex) catch (Exception ex)
@ -153,10 +154,10 @@ namespace MediaBrowser.Api.Playback
return false; return false;
} }
public void Stop() public async Task Stop()
{ {
DisposeTimer(); DisposeTimer();
UnpauseTranscoding(); await UnpauseTranscoding();
} }
public void Dispose() public void Dispose()

@ -287,7 +287,6 @@ namespace MediaBrowser.Api.Playback
SubtitleEncoder, SubtitleEncoder,
DeviceManager, DeviceManager,
MediaSourceManager, MediaSourceManager,
ZipClient,
JsonSerializer, JsonSerializer,
AuthorizationContext, AuthorizationContext,
NetworkManager) NetworkManager)
@ -334,10 +333,8 @@ namespace MediaBrowser.Api.Playback
SubtitleEncoder, SubtitleEncoder,
DeviceManager, DeviceManager,
MediaSourceManager, MediaSourceManager,
ZipClient,
JsonSerializer, JsonSerializer,
AuthorizationContext, AuthorizationContext,
ImageProcessor,
EnvironmentInfo) EnvironmentInfo)
{ {
Request = Request Request = Request

Loading…
Cancel
Save