jellyfin/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs

375 lines
14 KiB
C#
Raw Normal View History

2016-03-27 21:11:27 +00:00
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
2015-01-20 05:19:13 +00:00
using MediaBrowser.Controller.Devices;
2014-03-25 05:25:03 +00:00
using MediaBrowser.Controller.Dlna;
2013-09-18 18:49:06 +00:00
using MediaBrowser.Controller.Drawing;
using MediaBrowser.Controller.Library;
2014-02-20 16:37:41 +00:00
using MediaBrowser.Controller.MediaEncoding;
2014-08-30 14:26:29 +00:00
using MediaBrowser.Controller.Net;
2013-09-01 13:13:11 +00:00
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
2015-05-04 17:44:25 +00:00
using MediaBrowser.Model.Serialization;
2014-02-20 16:37:41 +00:00
using ServiceStack.Web;
using System;
using System.Collections.Generic;
2015-06-02 01:26:51 +00:00
using System.Globalization;
2013-12-21 18:37:34 +00:00
using System.Threading;
2013-02-27 04:19:05 +00:00
using System.Threading.Tasks;
2015-10-04 04:23:11 +00:00
using CommonIO;
2013-02-27 04:19:05 +00:00
namespace MediaBrowser.Api.Playback.Progressive
{
/// <summary>
/// Class BaseProgressiveStreamingService
/// </summary>
public abstract class BaseProgressiveStreamingService : BaseStreamingService
{
2013-09-18 18:49:06 +00:00
protected readonly IImageProcessor ImageProcessor;
2014-06-11 19:31:33 +00:00
protected readonly IHttpClient HttpClient;
2013-09-04 17:02:19 +00:00
2015-05-04 17:44:25 +00:00
protected 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, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, dlnaManager, subtitleEncoder, deviceManager, mediaSourceManager, zipClient, jsonSerializer)
2013-02-27 04:19:05 +00:00
{
2014-02-20 16:37:41 +00:00
ImageProcessor = imageProcessor;
2014-06-11 19:31:33 +00:00
HttpClient = httpClient;
2013-02-27 04:19:05 +00:00
}
/// <summary>
/// Gets the output file extension.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.String.</returns>
protected override string GetOutputFileExtension(StreamState state)
{
var ext = base.GetOutputFileExtension(state);
if (!string.IsNullOrEmpty(ext))
{
return ext;
}
var isVideoRequest = state.VideoRequest != null;
2013-03-09 02:34:54 +00:00
2013-02-27 04:19:05 +00:00
// Try to infer based on the desired video codec
if (isVideoRequest)
2013-02-27 04:19:05 +00:00
{
var videoCodec = state.VideoRequest.VideoCodec;
2014-08-30 14:26:29 +00:00
if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
{
return ".ts";
}
if (string.Equals(videoCodec, "theora", StringComparison.OrdinalIgnoreCase))
{
return ".ogv";
}
if (string.Equals(videoCodec, "vpx", StringComparison.OrdinalIgnoreCase))
{
return ".webm";
}
if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase))
{
return ".asf";
}
2013-02-27 04:19:05 +00:00
}
// Try to infer based on the desired audio codec
if (!isVideoRequest)
2013-02-27 04:19:05 +00:00
{
var audioCodec = state.Request.AudioCodec;
if (string.Equals("aac", audioCodec, StringComparison.OrdinalIgnoreCase))
2013-02-27 04:19:05 +00:00
{
return ".aac";
}
if (string.Equals("mp3", audioCodec, StringComparison.OrdinalIgnoreCase))
{
return ".mp3";
}
if (string.Equals("vorbis", audioCodec, StringComparison.OrdinalIgnoreCase))
{
return ".ogg";
}
if (string.Equals("wma", audioCodec, StringComparison.OrdinalIgnoreCase))
{
return ".wma";
2013-02-27 04:19:05 +00:00
}
}
return null;
}
/// <summary>
/// Gets the type of the transcoding job.
/// </summary>
/// <value>The type of the transcoding job.</value>
protected override TranscodingJobType TranscodingJobType
{
get { return TranscodingJobType.Progressive; }
}
/// <summary>
/// Processes the request.
/// </summary>
/// <param name="request">The request.</param>
2013-03-13 03:57:54 +00:00
/// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
2013-02-27 04:19:05 +00:00
/// <returns>Task.</returns>
2016-06-19 06:18:29 +00:00
protected async Task<object> ProcessRequest(StreamRequest request, bool isHeadRequest)
2013-02-27 04:19:05 +00:00
{
2014-08-17 05:38:13 +00:00
var cancellationTokenSource = new CancellationTokenSource();
2016-06-19 06:18:29 +00:00
var state = await GetState(request, cancellationTokenSource.Token).ConfigureAwait(false);
2013-02-27 04:19:05 +00:00
var responseHeaders = new Dictionary<string, string>();
2014-04-05 15:02:50 +00:00
// Static remote stream
if (request.Static && state.InputProtocol == MediaProtocol.Http)
2013-05-17 18:05:49 +00:00
{
2014-02-03 17:44:13 +00:00
AddDlnaHeaders(state, responseHeaders, true);
using (state)
2014-04-05 15:02:50 +00:00
{
2016-06-19 06:18:29 +00:00
return await GetStaticRemoteStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource)
.ConfigureAwait(false);
2014-04-05 15:02:50 +00:00
}
2013-05-17 18:05:49 +00:00
}
if (request.Static && state.InputProtocol != MediaProtocol.File)
{
throw new ArgumentException(string.Format("Input protocol {0} cannot be streamed statically.", state.InputProtocol));
}
var outputPath = state.OutputFilePath;
2016-06-19 06:18:29 +00:00
var outputPathExists = FileSystem.FileExists(outputPath);
2013-04-03 12:03:37 +00:00
2014-09-03 02:30:24 +00:00
var isTranscodeCached = outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive);
2013-04-03 12:03:37 +00:00
2014-09-03 02:30:24 +00:00
AddDlnaHeaders(state, responseHeaders, request.Static || isTranscodeCached);
2014-04-05 15:02:50 +00:00
// Static stream
2013-02-27 04:19:05 +00:00
if (request.Static)
{
var contentType = state.GetMimeType(state.MediaPath);
using (state)
2014-04-05 15:02:50 +00:00
{
2016-06-19 06:18:29 +00:00
return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
2014-08-30 14:26:29 +00:00
{
ResponseHeaders = responseHeaders,
ContentType = contentType,
IsHeadRequest = isHeadRequest,
2015-02-26 18:24:38 +00:00
Path = state.MediaPath
2016-06-19 06:18:29 +00:00
}).ConfigureAwait(false);
2014-04-05 15:02:50 +00:00
}
2013-02-27 04:19:05 +00:00
}
2014-04-05 15:02:50 +00:00
// Not static but transcode cache file exists
2014-09-03 02:30:24 +00:00
if (isTranscodeCached)
2013-02-27 04:19:05 +00:00
{
var contentType = state.GetMimeType(outputPath);
2014-04-05 15:02:50 +00:00
try
{
2016-06-19 06:18:29 +00:00
return await ResultFactory.GetStaticFileResult(Request, new StaticFileResultOptions
2014-08-30 14:26:29 +00:00
{
ResponseHeaders = responseHeaders,
ContentType = contentType,
IsHeadRequest = isHeadRequest,
Path = outputPath
2016-06-19 06:18:29 +00:00
}).ConfigureAwait(false);
2014-04-05 15:02:50 +00:00
}
finally
{
state.Dispose();
}
}
// Need to start ffmpeg
try
{
2016-06-19 06:18:29 +00:00
return await GetStreamResult(state, responseHeaders, isHeadRequest, cancellationTokenSource)
.ConfigureAwait(false);
2013-02-27 04:19:05 +00:00
}
2014-04-05 15:02:50 +00:00
catch
{
state.Dispose();
2013-02-27 04:19:05 +00:00
2014-04-05 15:02:50 +00:00
throw;
}
2013-02-27 04:19:05 +00:00
}
2013-05-17 18:05:49 +00:00
/// <summary>
/// Gets the static remote stream result.
/// </summary>
/// <param name="state">The state.</param>
2013-05-17 18:05:49 +00:00
/// <param name="responseHeaders">The response headers.</param>
/// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
2014-08-17 05:38:13 +00:00
/// <param name="cancellationTokenSource">The cancellation token source.</param>
2013-05-17 18:05:49 +00:00
/// <returns>Task{System.Object}.</returns>
2014-08-17 05:38:13 +00:00
private async Task<object> GetStaticRemoteStreamResult(StreamState state, Dictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
2013-05-17 18:05:49 +00:00
{
string useragent = null;
state.RemoteHttpHeaders.TryGetValue("User-Agent", out useragent);
2014-10-12 01:46:02 +00:00
var trySupportSeek = false;
2014-02-14 04:00:13 +00:00
var options = new HttpRequestOptions
2013-05-17 18:05:49 +00:00
{
Url = state.MediaPath,
UserAgent = useragent,
2014-08-17 05:38:13 +00:00
BufferContent = false,
CancellationToken = cancellationTokenSource.Token
2014-02-14 04:00:13 +00:00
};
2013-05-17 18:05:49 +00:00
2014-10-12 01:46:02 +00:00
if (trySupportSeek)
2014-10-11 20:38:13 +00:00
{
2014-10-12 01:46:02 +00:00
if (!string.IsNullOrWhiteSpace(Request.QueryString["Range"]))
{
options.RequestHeaders["Range"] = Request.QueryString["Range"];
}
2014-10-11 20:38:13 +00:00
}
var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
2014-02-19 05:21:03 +00:00
2014-10-12 01:46:02 +00:00
if (trySupportSeek)
2014-02-19 05:21:03 +00:00
{
2016-06-19 06:18:29 +00:00
foreach (var name in new[] { "Content-Range", "Accept-Ranges" })
2014-10-11 20:38:13 +00:00
{
2014-10-12 01:46:02 +00:00
var val = response.Headers[name];
if (!string.IsNullOrWhiteSpace(val))
{
responseHeaders[name] = val;
}
2014-10-11 20:38:13 +00:00
}
2014-02-19 05:21:03 +00:00
}
2014-10-12 01:46:02 +00:00
else
{
responseHeaders["Accept-Ranges"] = "none";
}
2016-06-19 06:18:29 +00:00
2014-10-12 01:46:02 +00:00
if (response.ContentLength.HasValue)
{
responseHeaders["Content-Length"] = response.ContentLength.Value.ToString(UsCulture);
}
2016-06-19 06:18:29 +00:00
if (isHeadRequest)
{
2014-10-12 01:46:02 +00:00
using (response)
2013-05-17 18:05:49 +00:00
{
2014-02-14 04:00:13 +00:00
return ResultFactory.GetResult(new byte[] { }, response.ContentType, responseHeaders);
2013-05-17 18:05:49 +00:00
}
}
2013-05-17 18:05:49 +00:00
var result = new StaticRemoteStreamWriter(response);
2013-05-17 18:05:49 +00:00
result.Options["Content-Type"] = response.ContentType;
2013-05-17 18:05:49 +00:00
// Add the response headers to the result object
foreach (var header in responseHeaders)
{
result.Options[header.Key] = header.Value;
2013-05-17 18:05:49 +00:00
}
return result;
2013-05-17 18:05:49 +00:00
}
2013-02-27 04:19:05 +00:00
/// <summary>
/// Gets the stream result.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="responseHeaders">The response headers.</param>
2013-03-13 03:57:54 +00:00
/// <param name="isHeadRequest">if set to <c>true</c> [is head request].</param>
2014-08-17 05:38:13 +00:00
/// <param name="cancellationTokenSource">The cancellation token source.</param>
2013-02-27 04:19:05 +00:00
/// <returns>Task{System.Object}.</returns>
2014-08-17 05:38:13 +00:00
private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest, CancellationTokenSource cancellationTokenSource)
2013-02-27 04:19:05 +00:00
{
// Use the command line args with a dummy playlist path
var outputPath = state.OutputFilePath;
2013-02-27 04:19:05 +00:00
2014-02-19 05:21:03 +00:00
responseHeaders["Accept-Ranges"] = "none";
var contentType = state.GetMimeType(outputPath);
2013-02-27 04:44:41 +00:00
2015-05-09 03:48:43 +00:00
// TODO: The isHeadRequest is only here because ServiceStack will add Content-Length=0 to the response
// What we really want to do is hunt that down and remove that
var contentLength = state.EstimateContentLength || isHeadRequest ? GetEstimatedContentLength(state) : null;
2014-03-27 04:02:45 +00:00
if (contentLength.HasValue)
{
responseHeaders["Content-Length"] = contentLength.Value.ToString(UsCulture);
}
2013-03-13 03:57:54 +00:00
// Headers only
if (isHeadRequest)
{
2014-02-19 05:25:00 +00:00
var streamResult = ResultFactory.GetResult(new byte[] { }, contentType, responseHeaders);
2014-03-27 04:02:45 +00:00
2015-05-09 03:48:43 +00:00
var hasOptions = streamResult as IHasOptions;
if (hasOptions != null)
2014-02-19 05:25:00 +00:00
{
2015-05-09 03:48:43 +00:00
if (contentLength.HasValue)
{
hasOptions.Options["Content-Length"] = contentLength.Value.ToString(CultureInfo.InvariantCulture);
}
else
2014-02-19 05:25:00 +00:00
{
2014-03-27 04:02:45 +00:00
if (hasOptions.Options.ContainsKey("Content-Length"))
{
hasOptions.Options.Remove("Content-Length");
}
2014-02-19 05:25:00 +00:00
}
}
2014-03-27 04:02:45 +00:00
2014-02-19 05:25:00 +00:00
return streamResult;
2013-03-13 03:57:54 +00:00
}
2014-08-17 05:38:13 +00:00
await ApiEntryPoint.Instance.TranscodingStartLock.WaitAsync(cancellationTokenSource.Token).ConfigureAwait(false);
try
2013-02-27 04:19:05 +00:00
{
2014-09-03 02:30:24 +00:00
TranscodingJob job;
2016-06-19 06:18:29 +00:00
if (!FileSystem.FileExists(outputPath))
2014-08-17 05:38:13 +00:00
{
2014-09-03 02:30:24 +00:00
job = await StartFfMpeg(state, outputPath, cancellationTokenSource).ConfigureAwait(false);
2014-08-17 05:38:13 +00:00
}
else
{
2014-09-03 02:30:24 +00:00
job = ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
2014-08-17 05:38:13 +00:00
state.Dispose();
}
2013-02-27 04:19:05 +00:00
2014-08-17 05:38:13 +00:00
var result = new ProgressiveStreamWriter(outputPath, Logger, FileSystem, job);
2014-08-17 05:38:13 +00:00
result.Options["Content-Type"] = contentType;
2014-08-17 05:38:13 +00:00
// Add the response headers to the result object
foreach (var item in responseHeaders)
{
result.Options[item.Key] = item.Value;
}
return result;
}
finally
{
2014-08-17 05:38:13 +00:00
ApiEntryPoint.Instance.TranscodingStartLock.Release();
}
2013-02-27 04:19:05 +00:00
}
2014-03-27 04:02:45 +00:00
2014-03-27 19:30:21 +00:00
/// <summary>
/// Gets the length of the estimated content.
/// </summary>
/// <param name="state">The state.</param>
/// <returns>System.Nullable{System.Int64}.</returns>
2014-03-27 04:02:45 +00:00
private long? GetEstimatedContentLength(StreamState state)
{
var totalBitrate = state.TotalOutputBitrate ?? 0;
2014-03-27 04:02:45 +00:00
if (totalBitrate > 0 && state.RunTimeTicks.HasValue)
{
return Convert.ToInt64(totalBitrate * TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds);
}
return null;
}
2013-02-27 04:19:05 +00:00
}
}