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

318 lines
11 KiB
C#
Raw Normal View History

using MediaBrowser.Common.IO;
2013-03-04 05:43:06 +00:00
using MediaBrowser.Common.Net;
2014-05-18 19:58:42 +00:00
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
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;
2013-12-21 18:37:34 +00:00
using MediaBrowser.Controller.LiveTv;
2014-02-20 16:37:41 +00:00
using MediaBrowser.Controller.MediaEncoding;
2013-09-01 13:13:11 +00:00
using MediaBrowser.Model.IO;
2014-02-20 16:37:41 +00:00
using ServiceStack.Web;
using System;
using System.Collections.Generic;
2013-02-27 04:19:05 +00:00
using System.IO;
2013-12-21 18:37:34 +00:00
using System.Threading;
2013-02-27 04:19:05 +00:00
using System.Threading.Tasks;
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
2014-06-11 19:31:33 +00:00
protected BaseProgressiveStreamingService(IServerConfigurationManager serverConfig, IUserManager userManager, ILibraryManager libraryManager, IIsoManager isoManager, IMediaEncoder mediaEncoder, IFileSystem fileSystem, ILiveTvManager liveTvManager, IDlnaManager dlnaManager, IChannelManager channelManager, ISubtitleEncoder subtitleEncoder, IImageProcessor imageProcessor, IHttpClient httpClient) : base(serverConfig, userManager, libraryManager, isoManager, mediaEncoder, fileSystem, liveTvManager, dlnaManager, channelManager, subtitleEncoder)
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;
if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase))
2013-02-27 04:19:05 +00:00
{
2014-03-23 20:07:02 +00:00
return ".ts";
}
if (string.Equals(videoCodec, "theora", StringComparison.OrdinalIgnoreCase))
2014-03-23 20:07:02 +00:00
{
return ".ogv";
}
if (string.Equals(videoCodec, "vpx", StringComparison.OrdinalIgnoreCase))
2014-03-23 20:07:02 +00:00
{
return ".webm";
}
if (string.Equals(videoCodec, "wmv", StringComparison.OrdinalIgnoreCase))
2014-03-23 20:07:02 +00:00
{
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>
2013-03-13 03:57:54 +00:00
protected object ProcessRequest(StreamRequest request, bool isHeadRequest)
2013-02-27 04:19:05 +00:00
{
2013-12-21 18:37:34 +00:00
var state = GetState(request, CancellationToken.None).Result;
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
2013-12-19 21:51:32 +00:00
if (request.Static && state.IsRemote)
2013-05-17 18:05:49 +00:00
{
2014-02-03 17:44:13 +00:00
AddDlnaHeaders(state, responseHeaders, true);
2014-04-05 15:02:50 +00:00
try
{
return GetStaticRemoteStreamResult(state.MediaPath, responseHeaders, isHeadRequest).Result;
}
finally
{
state.Dispose();
}
2013-05-17 18:05:49 +00:00
}
var outputPath = state.OutputFilePath;
2013-04-03 12:03:37 +00:00
var outputPathExists = File.Exists(outputPath);
2013-11-28 18:27:29 +00:00
var isStatic = request.Static ||
(outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive));
2013-04-03 12:03:37 +00:00
2013-11-28 18:27:29 +00:00
AddDlnaHeaders(state, responseHeaders, isStatic);
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);
2014-04-05 15:02:50 +00:00
try
{
return ResultFactory.GetStaticFileResult(Request, state.MediaPath, contentType, FileShare.Read, responseHeaders, isHeadRequest);
}
finally
{
state.Dispose();
}
2013-02-27 04:19:05 +00:00
}
2014-04-05 15:02:50 +00:00
// Not static but transcode cache file exists
2013-04-03 12:03:37 +00:00
if (outputPathExists && !ApiEntryPoint.Instance.HasActiveTranscodingJob(outputPath, TranscodingJobType.Progressive))
2013-02-27 04:19:05 +00:00
{
var contentType = state.GetMimeType(outputPath);
2014-04-05 15:02:50 +00:00
try
{
return ResultFactory.GetStaticFileResult(Request, outputPath, contentType, FileShare.Read, responseHeaders, isHeadRequest);
}
finally
{
state.Dispose();
}
}
// Need to start ffmpeg
try
{
return GetStreamResult(state, responseHeaders, isHeadRequest).Result;
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>
2013-12-19 21:51:32 +00:00
/// <param name="mediaPath">The media path.</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>
/// <returns>Task{System.Object}.</returns>
2013-12-19 21:51:32 +00:00
private async Task<object> GetStaticRemoteStreamResult(string mediaPath, Dictionary<string, string> responseHeaders, bool isHeadRequest)
2013-05-17 18:05:49 +00:00
{
2014-02-14 04:00:13 +00:00
var options = new HttpRequestOptions
2013-05-17 18:05:49 +00:00
{
Url = mediaPath,
UserAgent = GetUserAgent(mediaPath),
BufferContent = false
2014-02-14 04:00:13 +00:00
};
2013-05-17 18:05:49 +00:00
2014-02-14 04:00:13 +00:00
var response = await HttpClient.GetResponse(options).ConfigureAwait(false);
2013-05-17 18:05:49 +00:00
2014-02-14 04:00:13 +00:00
responseHeaders["Accept-Ranges"] = "none";
2013-05-17 18:05:49 +00:00
2014-02-19 05:21:03 +00:00
var length = response.Headers["Content-Length"];
if (!string.IsNullOrEmpty(length))
{
responseHeaders["Content-Length"] = length;
}
if (isHeadRequest)
{
using (response.Content)
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>
2013-02-27 04:19:05 +00:00
/// <returns>Task{System.Object}.</returns>
2013-03-27 03:27:03 +00:00
private async Task<object> GetStreamResult(StreamState state, IDictionary<string, string> responseHeaders, bool isHeadRequest)
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
2014-03-27 04:02:45 +00:00
var contentLength = state.EstimateContentLength ? GetEstimatedContentLength(state) : null;
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
if (!contentLength.HasValue)
2014-02-19 05:25:00 +00:00
{
2014-03-27 04:02:45 +00:00
var hasOptions = streamResult as IHasOptions;
if (hasOptions != null)
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
}
2013-02-27 04:19:05 +00:00
if (!File.Exists(outputPath))
{
2014-06-02 19:32:41 +00:00
await StartFfMpeg(state, outputPath, new CancellationTokenSource()).ConfigureAwait(false);
2013-02-27 04:19:05 +00:00
}
else
{
2013-03-08 19:14:09 +00:00
ApiEntryPoint.Instance.OnTranscodeBeginRequest(outputPath, TranscodingJobType.Progressive);
2014-04-05 15:02:50 +00:00
state.Dispose();
2013-02-27 04:19:05 +00:00
}
var result = new ProgressiveStreamWriter(outputPath, Logger, FileSystem);
result.Options["Content-Type"] = contentType;
// Add the response headers to the result object
foreach (var item in responseHeaders)
{
result.Options[item.Key] = item.Value;
}
return result;
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
}
}