jellyfin/MediaBrowser.Api/Playback/BaseStreamingService.cs

1127 lines
44 KiB
C#
Raw Normal View History

2015-03-07 15:43:53 -07:00
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
2015-03-07 15:43:53 -07:00
using MediaBrowser.Controller.Devices;
2014-03-24 22:25:03 -07:00
using MediaBrowser.Controller.Dlna;
2013-02-26 21:19:05 -07:00
using MediaBrowser.Controller.Library;
2014-02-20 09:37:41 -07:00
using MediaBrowser.Controller.MediaEncoding;
2014-04-01 15:23:07 -07:00
using MediaBrowser.Model.Dlna;
2014-06-02 12:32:41 -07:00
using MediaBrowser.Model.Dto;
2013-02-26 21:19:05 -07:00
using MediaBrowser.Model.Entities;
2015-03-07 15:43:53 -07:00
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
2015-06-08 14:32:20 -07:00
using MediaBrowser.Model.Serialization;
2013-02-26 21:19:05 -07:00
using System;
using System.Collections.Generic;
using System.Globalization;
2013-02-26 21:19:05 -07:00
using System.IO;
using System.Linq;
2014-04-06 10:53:23 -07:00
using System.Text;
2013-02-26 21:19:05 -07:00
using System.Threading;
using System.Threading.Tasks;
2016-08-18 17:10:10 -07:00
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
2016-11-10 07:41:24 -07:00
using MediaBrowser.Controller.Net;
2016-10-31 20:07:45 -07:00
using MediaBrowser.Model.Diagnostics;
2013-02-26 21:19:05 -07:00
namespace MediaBrowser.Api.Playback
{
/// <summary>
/// Class BaseStreamingService
/// </summary>
2013-03-15 22:52:33 -07:00
public abstract class BaseStreamingService : BaseApiService
2013-02-26 21:19:05 -07:00
{
/// <summary>
/// Gets or sets the application paths.
/// </summary>
/// <value>The application paths.</value>
protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
2013-02-26 21:19:05 -07:00
/// <summary>
/// Gets or sets the user manager.
/// </summary>
/// <value>The user manager.</value>
2013-09-04 10:02:19 -07:00
protected IUserManager UserManager { get; private set; }
/// <summary>
/// Gets or sets the library manager.
/// </summary>
/// <value>The library manager.</value>
2013-09-04 10:02:19 -07:00
protected ILibraryManager LibraryManager { get; private set; }
2013-03-03 22:43:06 -07:00
2013-02-26 21:19:05 -07:00
/// <summary>
2013-03-03 22:43:06 -07:00
/// Gets or sets the iso manager.
2013-02-26 21:19:05 -07:00
/// </summary>
2013-03-03 22:43:06 -07:00
/// <value>The iso manager.</value>
2013-09-04 10:02:19 -07:00
protected IIsoManager IsoManager { get; private set; }
2013-02-26 21:19:05 -07:00
/// <summary>
/// Gets or sets the media encoder.
/// </summary>
/// <value>The media encoder.</value>
2013-09-04 10:02:19 -07:00
protected IMediaEncoder MediaEncoder { get; private set; }
protected IFileSystem FileSystem { get; private set; }
2013-12-05 20:39:44 -07:00
2014-03-24 22:25:03 -07:00
protected IDlnaManager DlnaManager { get; private set; }
2015-01-19 22:19:13 -07:00
protected IDeviceManager DeviceManager { get; private set; }
2014-06-11 12:31:33 -07:00
protected ISubtitleEncoder SubtitleEncoder { get; private set; }
2015-03-07 15:43:53 -07:00
protected IMediaSourceManager MediaSourceManager { get; private set; }
2015-03-16 20:48:05 -07:00
protected IZipClient ZipClient { get; private set; }
2015-05-04 10:44:25 -07:00
protected IJsonSerializer JsonSerializer { get; private set; }
2013-12-05 20:39:44 -07:00
2016-08-18 17:10:10 -07:00
public static IServerApplicationHost AppHost;
public static IHttpClient HttpClient;
2016-11-10 07:41:24 -07:00
protected IAuthorizationContext AuthorizationContext { get; private set; }
2016-08-18 17:10:10 -07:00
protected EncodingHelper EncodingHelper { get; set; }
2013-02-26 21:19:05 -07:00
/// <summary>
/// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
2013-02-26 21:19:05 -07:00
/// </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)
2013-02-26 21:19:05 -07:00
{
JsonSerializer = jsonSerializer;
AuthorizationContext = authorizationContext;
ZipClient = zipClient;
MediaSourceManager = mediaSourceManager;
DeviceManager = deviceManager;
SubtitleEncoder = subtitleEncoder;
DlnaManager = dlnaManager;
FileSystem = fileSystem;
ServerConfigurationManager = serverConfig;
UserManager = userManager;
LibraryManager = libraryManager;
IsoManager = isoManager;
MediaEncoder = mediaEncoder;
EncodingHelper = new EncodingHelper(MediaEncoder, serverConfig, FileSystem, SubtitleEncoder);
2013-02-26 21:19:05 -07:00
}
/// <summary>
/// Gets the command line arguments.
/// </summary>
/// <param name="outputPath">The output path.</param>
/// <param name="state">The state.</param>
/// <param name="isEncoding">if set to <c>true</c> [is encoding].</param>
/// <returns>System.String.</returns>
protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding);
2013-02-26 21:19:05 -07:00
/// <summary>
/// Gets the type of the transcoding job.
2013-02-26 21:19:05 -07:00
/// </summary>
/// <value>The type of the transcoding job.</value>
protected abstract TranscodingJobType TranscodingJobType { get; }
2013-02-26 21:19:05 -07:00
/// <summary>
/// Gets the output file extension.
2013-02-26 21:19:05 -07:00
/// </summary>
2015-07-25 10:21:10 -07:00
/// <param name="state">The state.</param>
2013-02-26 21:19:05 -07:00
/// <returns>System.String.</returns>
protected virtual string GetOutputFileExtension(StreamState state)
2013-02-26 21:19:05 -07:00
{
return Path.GetExtension(state.RequestedUrl);
2013-02-26 21:19:05 -07:00
}
/// <summary>
/// Gets the output file path.
2013-02-26 21:19:05 -07:00
/// </summary>
2017-02-17 14:11:13 -07:00
private string GetOutputFilePath(StreamState state, string outputFileExtension)
2013-02-26 21:19:05 -07:00
{
var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
var data = GetCommandLineArguments("dummy\\dummy", state, false);
2013-02-26 21:19:05 -07:00
data += "-" + (state.Request.DeviceId ?? string.Empty);
data += "-" + (state.Request.PlaySessionId ?? string.Empty);
var dataHash = data.GetMD5().ToString("N");
2016-04-29 21:00:45 -07:00
if (EnableOutputInSubFolder)
{
return Path.Combine(folder, dataHash, dataHash + (outputFileExtension ?? string.Empty).ToLower());
}
return Path.Combine(folder, dataHash + (outputFileExtension ?? string.Empty).ToLower());
}
protected virtual bool EnableOutputInSubFolder
2014-12-19 23:06:27 -07:00
{
get { return false; }
2014-12-19 23:06:27 -07:00
}
protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
protected virtual string GetDefaultH264Preset()
{
return "superfast";
2013-02-26 21:19:05 -07:00
}
2014-06-28 12:35:30 -07:00
private async Task AcquireResources(StreamState state, CancellationTokenSource cancellationTokenSource)
{
if (state.VideoType == VideoType.Iso && state.IsoType.HasValue && IsoManager.CanMount(state.MediaPath))
{
state.IsoMount = await IsoManager.Mount(state.MediaPath, cancellationTokenSource.Token).ConfigureAwait(false);
}
2015-08-24 05:54:10 -07:00
if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Request.LiveStreamId))
2014-06-28 12:35:30 -07:00
{
2015-03-29 09:45:16 -07:00
var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
{
OpenToken = state.MediaSource.OpenToken
2017-04-17 12:01:16 -07:00
}, cancellationTokenSource.Token).ConfigureAwait(false);
2014-06-28 12:35:30 -07:00
EncodingHelper.AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, state.RequestedUrl);
2014-06-28 12:35:30 -07:00
2015-03-28 13:22:27 -07:00
if (state.VideoRequest != null)
2014-06-28 12:35:30 -07:00
{
EncodingHelper.TryStreamCopy(state);
2014-08-15 09:35:41 -07:00
}
2015-03-28 21:56:39 -07:00
}
2014-08-15 09:35:41 -07:00
2015-03-28 21:56:39 -07:00
if (state.MediaSource.BufferMs.HasValue)
{
await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
2014-06-28 12:35:30 -07:00
}
}
2013-02-26 21:19:05 -07:00
/// <summary>
/// Starts the FFMPEG.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="outputPath">The output path.</param>
2014-06-02 12:32:41 -07:00
/// <param name="cancellationTokenSource">The cancellation token source.</param>
2014-10-15 20:26:39 -07:00
/// <param name="workingDirectory">The working directory.</param>
2013-02-26 21:19:05 -07:00
/// <returns>Task.</returns>
2014-12-19 23:06:27 -07:00
protected async Task<TranscodingJob> StartFfMpeg(StreamState state,
string outputPath,
2014-10-15 20:26:39 -07:00
CancellationTokenSource cancellationTokenSource,
string workingDirectory = null)
2013-02-26 21:19:05 -07:00
{
2015-09-13 14:32:02 -07:00
FileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));
2013-06-04 09:48:23 -07:00
2014-06-28 12:35:30 -07:00
await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
2013-02-26 21:19:05 -07:00
if (state.VideoRequest != null && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
{
var auth = AuthorizationContext.GetAuthorizationInfo(Request);
if (!string.IsNullOrWhiteSpace(auth.UserId))
{
var user = UserManager.GetUserById(auth.UserId);
if (!user.Policy.EnableVideoPlaybackTranscoding)
{
ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
throw new ArgumentException("User does not have access to video transcoding");
}
}
}
2014-09-02 19:30:24 -07:00
var transcodingId = Guid.NewGuid().ToString("N");
2015-03-28 13:22:27 -07:00
var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
2016-10-31 20:07:45 -07:00
var process = ApiEntryPoint.Instance.ProcessFactory.Create(new ProcessOptions
2013-02-26 21:19:05 -07:00
{
2016-10-31 20:07:45 -07:00
CreateNoWindow = true,
UseShellExecute = false,
2013-02-26 21:19:05 -07:00
2016-10-31 20:07:45 -07:00
// Must consume both stdout and stderr or deadlocks may occur
//RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
2013-02-26 21:19:05 -07:00
2016-10-31 20:07:45 -07:00
FileName = MediaEncoder.EncoderPath,
Arguments = commandLineArgs,
2013-02-26 21:19:05 -07:00
2016-10-31 20:07:45 -07:00
IsHidden = true,
ErrorDialog = false,
EnableRaisingEvents = true,
WorkingDirectory = !string.IsNullOrWhiteSpace(workingDirectory) ? workingDirectory : null
});
2014-10-15 20:26:39 -07:00
2014-09-02 19:30:24 -07:00
var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath,
2015-03-29 11:31:28 -07:00
state.Request.PlaySessionId,
2015-04-20 11:04:02 -07:00
state.MediaSource.LiveStreamId,
2014-09-02 19:30:24 -07:00
transcodingId,
TranscodingJobType,
process,
state.Request.DeviceId,
state,
cancellationTokenSource);
2013-02-26 21:19:05 -07:00
2014-04-03 15:50:04 -07:00
var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
Logger.Info(commandLineLogMessage);
2013-02-26 21:19:05 -07:00
var logFilePrefix = "ffmpeg-transcode";
2016-04-12 11:01:23 -07:00
if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) && string.Equals(state.OutputAudioCodec, "copy", StringComparison.OrdinalIgnoreCase))
{
logFilePrefix = "ffmpeg-directstream";
2016-04-12 11:01:23 -07:00
}
else if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
{
logFilePrefix = "ffmpeg-remux";
2016-04-12 11:01:23 -07:00
}
var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt");
2015-09-13 14:32:02 -07:00
FileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
2013-02-26 21:19:05 -07:00
// FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory.
2016-10-25 12:02:04 -07:00
state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
2013-02-26 21:19:05 -07:00
2015-05-04 10:44:25 -07:00
var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(Request.AbsoluteUri + Environment.NewLine + Environment.NewLine + JsonSerializer.SerializeToString(state.MediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine);
2014-06-02 12:32:41 -07:00
await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false);
2014-04-03 15:50:04 -07:00
2014-09-02 19:30:24 -07:00
process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);
2013-02-26 21:19:05 -07:00
try
{
process.Start();
}
catch (Exception ex)
2013-02-26 21:19:05 -07:00
{
Logger.ErrorException("Error starting ffmpeg", ex);
ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
2013-02-26 21:19:05 -07:00
throw;
}
// MUST read both stdout and stderr asynchronously or a deadlock may occurr
2016-07-01 19:16:05 -07:00
//process.BeginOutputReadLine();
2013-02-26 21:19:05 -07:00
2017-03-24 08:03:49 -07:00
state.TranscodingJob = transcodingJob;
2013-02-26 21:19:05 -07:00
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
2017-03-24 08:03:49 -07:00
new JobLogger(Logger).StartStreamingLog(state, process.StandardError.BaseStream, state.LogFileStream);
2013-02-26 21:19:05 -07:00
// Wait for the file to exist before proceeeding
2016-04-03 22:07:10 -07:00
while (!FileSystem.FileExists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited)
2013-02-26 21:19:05 -07:00
{
2014-06-02 12:32:41 -07:00
await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
2013-02-26 21:19:05 -07:00
}
2014-09-02 19:30:24 -07:00
2016-09-07 10:17:26 -07:00
if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
2014-10-14 17:04:44 -07:00
{
await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
2016-09-07 10:17:26 -07:00
if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
2014-10-14 17:04:44 -07:00
{
2014-11-10 20:41:55 -07:00
await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
2014-10-14 17:04:44 -07:00
}
}
2016-09-07 10:17:26 -07:00
if (!transcodingJob.HasExited)
{
StartThrottler(state, transcodingJob);
}
2016-08-18 17:10:10 -07:00
ReportUsage(state);
2015-02-28 11:47:05 -07:00
2014-09-02 19:30:24 -07:00
return transcodingJob;
2013-02-26 21:19:05 -07:00
}
2015-02-28 11:47:05 -07:00
private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
{
2016-09-21 10:07:18 -07:00
if (EnableThrottling(state))
2015-02-28 11:47:05 -07:00
{
2016-10-31 20:07:45 -07:00
transcodingJob.TranscodingThrottler = state.TranscodingThrottler = new TranscodingThrottler(transcodingJob, Logger, ServerConfigurationManager, ApiEntryPoint.Instance.TimerFactory, FileSystem);
state.TranscodingThrottler.Start();
2015-02-28 11:47:05 -07:00
}
}
2016-09-22 22:45:14 -07:00
private bool EnableThrottling(StreamState state)
2015-05-19 12:15:40 -07:00
{
2016-11-08 11:44:23 -07:00
return false;
//// do not use throttling with hardware encoders
//return state.InputProtocol == MediaProtocol.File &&
// state.RunTimeTicks.HasValue &&
// state.RunTimeTicks.Value >= TimeSpan.FromMinutes(5).Ticks &&
// state.IsInputVideo &&
// state.VideoType == VideoType.VideoFile &&
// !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase) &&
// string.Equals(GetVideoEncoder(state), "libx264", StringComparison.OrdinalIgnoreCase);
2015-05-19 12:15:40 -07:00
}
2013-02-26 21:19:05 -07:00
/// <summary>
/// Processes the exited.
/// </summary>
/// <param name="process">The process.</param>
2014-09-02 19:30:24 -07:00
/// <param name="job">The job.</param>
2013-02-26 21:19:05 -07:00
/// <param name="state">The state.</param>
2016-10-31 20:07:45 -07:00
private void OnFfMpegProcessExited(IProcess process, TranscodingJob job, StreamState state)
2013-02-26 21:19:05 -07:00
{
2014-06-26 10:04:11 -07:00
if (job != null)
{
job.HasExited = true;
}
2014-06-19 21:50:30 -07:00
Logger.Debug("Disposing stream resources");
2014-04-05 08:02:50 -07:00
state.Dispose();
2014-01-02 21:58:22 -07:00
2013-02-26 21:19:05 -07:00
try
{
Logger.Info("FFMpeg exited with code {0}", process.ExitCode);
2013-02-26 21:19:05 -07:00
}
catch
{
2014-06-19 21:50:30 -07:00
Logger.Error("FFMpeg exited with an error.");
2013-02-26 21:19:05 -07:00
}
2014-06-19 21:50:30 -07:00
// This causes on exited to be called twice:
//try
//{
// // Dispose the process
// process.Dispose();
//}
//catch (Exception ex)
//{
// Logger.ErrorException("Error disposing ffmpeg.", ex);
//}
2013-02-26 21:19:05 -07:00
}
2014-02-12 22:11:54 -07:00
/// <summary>
/// Parses the parameters.
/// </summary>
/// <param name="request">The request.</param>
private void ParseParams(StreamRequest request)
{
var vals = request.Params.Split(';');
var videoRequest = request as VideoStreamRequest;
for (var i = 0; i < vals.Length; i++)
{
var val = vals[i];
if (string.IsNullOrWhiteSpace(val))
{
continue;
}
if (i == 0)
{
2014-03-26 08:06:48 -07:00
request.DeviceProfileId = val;
}
2014-03-24 22:25:03 -07:00
else if (i == 1)
2014-03-22 22:10:33 -07:00
{
2014-03-26 08:06:48 -07:00
request.DeviceId = val;
2014-03-22 22:10:33 -07:00
}
2014-03-24 22:25:03 -07:00
else if (i == 2)
2014-03-23 10:18:24 -07:00
{
2014-03-26 08:06:48 -07:00
request.MediaSourceId = val;
2014-03-23 10:18:24 -07:00
}
2014-03-24 22:25:03 -07:00
else if (i == 3)
2014-03-26 08:06:48 -07:00
{
request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
else if (i == 4)
2014-02-12 22:11:54 -07:00
{
if (videoRequest != null)
{
2014-03-23 13:07:02 -07:00
videoRequest.VideoCodec = val;
2014-02-12 22:11:54 -07:00
}
}
2014-03-26 08:06:48 -07:00
else if (i == 5)
2014-02-12 22:11:54 -07:00
{
2014-03-23 13:07:02 -07:00
request.AudioCodec = val;
2014-02-12 22:11:54 -07:00
}
2014-03-26 08:06:48 -07:00
else if (i == 6)
2014-02-12 22:11:54 -07:00
{
if (videoRequest != null)
{
videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
}
}
2014-03-26 08:06:48 -07:00
else if (i == 7)
2014-02-12 22:11:54 -07:00
{
if (videoRequest != null)
{
videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
}
}
2014-03-26 08:06:48 -07:00
else if (i == 8)
2014-02-12 22:11:54 -07:00
{
if (videoRequest != null)
{
videoRequest.VideoBitRate = int.Parse(val, UsCulture);
}
}
2014-03-26 08:06:48 -07:00
else if (i == 9)
2014-02-12 22:11:54 -07:00
{
request.AudioBitRate = int.Parse(val, UsCulture);
}
2014-03-26 08:06:48 -07:00
else if (i == 10)
2014-02-12 22:11:54 -07:00
{
2014-03-22 22:10:33 -07:00
request.MaxAudioChannels = int.Parse(val, UsCulture);
2014-02-12 22:11:54 -07:00
}
2014-03-26 08:06:48 -07:00
else if (i == 11)
{
if (videoRequest != null)
{
2014-06-23 09:05:19 -07:00
videoRequest.MaxFramerate = float.Parse(val, UsCulture);
}
}
2014-03-26 08:06:48 -07:00
else if (i == 12)
{
if (videoRequest != null)
{
2014-03-27 21:24:11 -07:00
videoRequest.MaxWidth = int.Parse(val, UsCulture);
}
}
2014-03-26 08:06:48 -07:00
else if (i == 13)
2014-03-24 10:54:45 -07:00
{
if (videoRequest != null)
{
2014-03-27 21:24:11 -07:00
videoRequest.MaxHeight = int.Parse(val, UsCulture);
2014-03-24 10:54:45 -07:00
}
}
2014-03-26 08:06:48 -07:00
else if (i == 14)
2014-03-24 10:54:45 -07:00
{
2014-03-30 12:05:10 -07:00
request.StartTimeTicks = long.Parse(val, UsCulture);
2014-03-24 10:54:45 -07:00
}
2014-03-26 08:06:48 -07:00
else if (i == 15)
2014-03-27 21:24:11 -07:00
{
if (videoRequest != null)
{
videoRequest.Level = val;
}
}
2014-09-17 21:50:21 -07:00
else if (i == 16)
2014-09-22 21:05:29 -07:00
{
if (videoRequest != null)
{
videoRequest.MaxRefFrames = int.Parse(val, UsCulture);
}
}
2015-11-26 21:33:20 -07:00
else if (i == 17)
2014-09-22 21:05:29 -07:00
{
if (videoRequest != null)
{
videoRequest.MaxVideoBitDepth = int.Parse(val, UsCulture);
}
}
2015-11-26 21:33:20 -07:00
else if (i == 18)
2014-10-09 15:22:04 -07:00
{
if (videoRequest != null)
{
videoRequest.Profile = val;
}
}
2015-11-26 21:33:20 -07:00
else if (i == 19)
2014-11-11 21:51:40 -07:00
{
2016-04-03 17:01:03 -07:00
// cabac no longer used
2014-11-11 21:51:40 -07:00
}
2015-11-26 21:33:20 -07:00
else if (i == 20)
2015-03-23 10:19:21 -07:00
{
2015-03-29 11:31:28 -07:00
request.PlaySessionId = val;
2015-03-23 10:19:21 -07:00
}
2015-11-26 21:33:20 -07:00
else if (i == 21)
2015-04-12 09:46:29 -07:00
{
// api_key
}
2015-11-26 21:33:20 -07:00
else if (i == 22)
2015-03-29 11:16:40 -07:00
{
request.LiveStreamId = val;
}
2015-11-26 21:33:20 -07:00
else if (i == 23)
2015-04-24 13:06:37 -07:00
{
// Duplicating ItemId because of MediaMonkey
}
else if (i == 24)
{
if (videoRequest != null)
{
videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
}
2016-03-06 21:56:45 -07:00
else if (i == 25)
{
if (!string.IsNullOrWhiteSpace(val) && videoRequest != null)
{
SubtitleDeliveryMethod method;
if (Enum.TryParse(val, out method))
{
videoRequest.SubtitleMethod = method;
}
}
}
2016-08-22 22:08:07 -07:00
else if (i == 26)
2016-05-13 22:40:01 -07:00
{
request.TranscodingMaxAudioChannels = int.Parse(val, UsCulture);
}
2016-08-22 22:08:07 -07:00
else if (i == 27)
2016-07-13 12:16:51 -07:00
{
if (videoRequest != null)
{
videoRequest.EnableSubtitlesInManifest = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
}
2016-08-22 22:08:07 -07:00
else if (i == 28)
{
request.Tag = val;
}
2016-10-16 10:11:32 -07:00
else if (i == 29)
2016-11-14 00:28:20 -07:00
{
if (videoRequest != null)
{
videoRequest.RequireAvc = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
}
2017-01-29 13:00:29 -07:00
else if (i == 30)
{
request.SubtitleCodec = val;
}
2017-03-15 12:57:18 -07:00
else if (i == 31)
{
if (videoRequest != null)
{
videoRequest.RequireNonAnamorphic = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
}
else if (i == 32)
{
if (videoRequest != null)
{
videoRequest.DeInterlace = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
}
2014-02-12 22:11:54 -07:00
}
}
2014-04-01 15:23:07 -07:00
/// <summary>
/// Parses the dlna headers.
/// </summary>
/// <param name="request">The request.</param>
private void ParseDlnaHeaders(StreamRequest request)
{
if (!request.StartTimeTicks.HasValue)
{
var timeSeek = GetHeader("TimeSeekRange.dlna.org");
request.StartTimeTicks = ParseTimeSeekHeader(timeSeek);
}
}
/// <summary>
/// Parses the time seek header.
/// </summary>
private long? ParseTimeSeekHeader(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
if (value.IndexOf("npt=", StringComparison.OrdinalIgnoreCase) != 0)
{
throw new ArgumentException("Invalid timeseek header");
}
value = value.Substring(4).Split(new[] { '-' }, 2)[0];
if (value.IndexOf(':') == -1)
{
// Parses npt times in the format of '417.33'
double seconds;
if (double.TryParse(value, NumberStyles.Any, UsCulture, out seconds))
{
return TimeSpan.FromSeconds(seconds).Ticks;
}
throw new ArgumentException("Invalid timeseek header");
}
// Parses npt times in the format of '10:19:25.7'
var tokens = value.Split(new[] { ':' }, 3);
double secondsSum = 0;
var timeFactor = 3600;
foreach (var time in tokens)
{
double digit;
if (double.TryParse(time, NumberStyles.Any, UsCulture, out digit))
{
2016-03-27 14:11:27 -07:00
secondsSum += digit * timeFactor;
2014-04-01 15:23:07 -07:00
}
else
{
throw new ArgumentException("Invalid timeseek header");
}
timeFactor /= 60;
2014-06-01 12:41:35 -07:00
}
return TimeSpan.FromSeconds(secondsSum).Ticks;
2014-06-01 12:41:35 -07:00
}
/// <summary>
/// Gets the state.
/// </summary>
/// <param name="request">The request.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>StreamState.</returns>
protected async Task<StreamState> GetState(StreamRequest request, CancellationToken cancellationToken)
2014-04-01 21:10:46 -07:00
{
ParseDlnaHeaders(request);
2016-04-03 21:18:36 -07:00
if (!string.IsNullOrWhiteSpace(request.Params))
2014-04-01 21:10:46 -07:00
{
ParseParams(request);
2014-04-01 21:10:46 -07:00
}
var url = Request.PathInfo;
2016-04-03 22:07:10 -07:00
if (string.IsNullOrEmpty(request.AudioCodec))
2014-06-19 22:31:32 -07:00
{
request.AudioCodec = EncodingHelper.InferAudioCodec(url);
2014-06-19 22:31:32 -07:00
}
var state = new StreamState(MediaSourceManager, Logger, TranscodingJobType)
2016-04-27 12:23:05 -07:00
{
Request = request,
RequestedUrl = url,
UserAgent = Request.UserAgent
};
2016-04-27 12:23:05 -07:00
var auth = AuthorizationContext.GetAuthorizationInfo(Request);
if (!string.IsNullOrWhiteSpace(auth.UserId))
2014-04-01 21:10:46 -07:00
{
state.User = UserManager.GetUserById(auth.UserId);
2014-04-01 21:10:46 -07:00
}
2017-02-17 14:11:13 -07:00
//if ((Request.UserAgent ?? string.Empty).IndexOf("iphone", StringComparison.OrdinalIgnoreCase) != -1 ||
// (Request.UserAgent ?? string.Empty).IndexOf("ipad", StringComparison.OrdinalIgnoreCase) != -1 ||
// (Request.UserAgent ?? string.Empty).IndexOf("ipod", StringComparison.OrdinalIgnoreCase) != -1)
//{
// state.SegmentLength = 6;
//}
2014-04-01 21:10:46 -07:00
if (state.VideoRequest != null)
2014-04-01 21:10:46 -07:00
{
if (!string.IsNullOrWhiteSpace(state.VideoRequest.VideoCodec))
2014-10-19 20:04:45 -07:00
{
state.SupportedVideoCodecs = state.VideoRequest.VideoCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
state.VideoRequest.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
2014-10-19 20:04:45 -07:00
}
2014-04-01 21:10:46 -07:00
}
if (!string.IsNullOrWhiteSpace(request.AudioCodec))
2014-04-01 21:10:46 -07:00
{
state.SupportedAudioCodecs = request.AudioCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
state.Request.AudioCodec = state.SupportedAudioCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToAudioCodec(i))
?? state.SupportedAudioCodecs.FirstOrDefault();
2014-04-01 21:10:46 -07:00
}
if (!string.IsNullOrWhiteSpace(request.SubtitleCodec))
2014-04-01 21:10:46 -07:00
{
state.SupportedSubtitleCodecs = request.SubtitleCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
state.Request.SubtitleCodec = state.SupportedSubtitleCodecs.FirstOrDefault(i => MediaEncoder.CanEncodeToSubtitleCodec(i))
?? state.SupportedSubtitleCodecs.FirstOrDefault();
2014-04-01 21:10:46 -07:00
}
var item = LibraryManager.GetItemById(request.Id);
2014-04-01 21:10:46 -07:00
state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
2014-04-01 21:10:46 -07:00
2017-04-28 12:17:26 -07:00
//var primaryImage = item.GetImageInfo(ImageType.Primary, 0) ??
// item.Parents.Select(i => i.GetImageInfo(ImageType.Primary, 0)).FirstOrDefault(i => i != null);
//if (primaryImage != null)
//{
// state.AlbumCoverPath = primaryImage.Path;
//}
2017-04-27 11:13:16 -07:00
MediaSourceInfo mediaSource = null;
if (string.IsNullOrWhiteSpace(request.LiveStreamId))
2014-04-01 21:10:46 -07:00
{
TranscodingJob currentJob = !string.IsNullOrWhiteSpace(request.PlaySessionId) ?
ApiEntryPoint.Instance.GetTranscodingJob(request.PlaySessionId)
: null;
2014-04-01 21:10:46 -07:00
if (currentJob != null)
2014-09-22 21:05:29 -07:00
{
mediaSource = currentJob.MediaSource;
2014-09-22 21:05:29 -07:00
}
if (mediaSource == null)
2014-09-22 21:05:29 -07:00
{
var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(request.Id, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false)).ToList();
2014-04-01 21:10:46 -07:00
mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
? mediaSources.First()
: mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId));
2014-04-01 21:10:46 -07:00
if (mediaSource == null && string.Equals(request.Id, request.MediaSourceId, StringComparison.OrdinalIgnoreCase))
2014-04-01 21:10:46 -07:00
{
mediaSource = mediaSources.First();
2014-04-01 21:10:46 -07:00
}
}
}
else
2014-10-19 20:04:45 -07:00
{
var liveStreamInfo = await MediaSourceManager.GetLiveStreamWithDirectStreamProvider(request.LiveStreamId, cancellationToken).ConfigureAwait(false);
mediaSource = liveStreamInfo.Item1;
state.DirectStreamProvider = liveStreamInfo.Item2;
}
2014-10-19 20:04:45 -07:00
var videoRequest = request as VideoStreamRequest;
2014-10-19 20:04:45 -07:00
EncodingHelper.AttachMediaSourceInfo(state, mediaSource, url);
2016-04-03 22:07:10 -07:00
var container = Path.GetExtension(state.RequestedUrl);
2014-04-06 10:53:23 -07:00
2017-02-17 14:11:13 -07:00
if (string.IsNullOrEmpty(container))
{
container = request.Container;
}
if (string.IsNullOrEmpty(container))
2014-04-06 10:53:23 -07:00
{
container = request.Static ?
state.InputContainer :
2017-02-17 14:11:13 -07:00
GetOutputFileExtension(state);
2014-04-06 10:53:23 -07:00
}
state.OutputContainer = (container ?? string.Empty).TrimStart('.');
state.OutputAudioBitrate = EncodingHelper.GetAudioBitrateParam(state.Request, state.AudioStream);
state.OutputAudioSampleRate = request.AudioSampleRate;
state.OutputAudioCodec = state.Request.AudioCodec;
state.OutputAudioChannels = EncodingHelper.GetNumAudioChannelsParam(state.Request, state.AudioStream, state.OutputAudioCodec);
if (videoRequest != null)
2014-04-06 10:53:23 -07:00
{
state.OutputVideoCodec = state.VideoRequest.VideoCodec;
state.OutputVideoBitrate = EncodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);
if (videoRequest != null)
2014-05-30 14:06:57 -07:00
{
EncodingHelper.TryStreamCopy(state);
2014-05-30 14:06:57 -07:00
}
if (state.OutputVideoBitrate.HasValue && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
2014-04-06 10:53:23 -07:00
{
var resolution = ResolutionNormalizer.Normalize(
state.VideoStream == null ? (int?)null : state.VideoStream.BitRate,
state.OutputVideoBitrate.Value,
state.VideoStream == null ? null : state.VideoStream.Codec,
state.OutputVideoCodec,
videoRequest.MaxWidth,
videoRequest.MaxHeight);
videoRequest.MaxWidth = resolution.MaxWidth;
videoRequest.MaxHeight = resolution.MaxHeight;
2014-04-06 10:53:23 -07:00
}
ApplyDeviceProfileSettings(state);
}
else
2014-04-06 10:53:23 -07:00
{
ApplyDeviceProfileSettings(state);
2014-04-06 10:53:23 -07:00
}
2017-02-17 14:11:13 -07:00
var ext = string.IsNullOrWhiteSpace(state.OutputContainer)
? GetOutputFileExtension(state)
: ("." + state.OutputContainer);
state.OutputFilePath = GetOutputFilePath(state, ext);
return state;
2014-04-06 10:53:23 -07:00
}
2014-04-07 21:17:18 -07:00
2014-03-24 22:25:03 -07:00
private void ApplyDeviceProfileSettings(StreamState state)
{
2016-10-25 12:02:04 -07:00
var headers = Request.Headers.ToDictionary();
2014-05-18 14:23:03 -07:00
2015-01-19 22:19:13 -07:00
if (!string.IsNullOrWhiteSpace(state.Request.DeviceProfileId))
{
state.DeviceProfile = DlnaManager.GetProfile(state.Request.DeviceProfileId);
}
else
{
if (!string.IsNullOrWhiteSpace(state.Request.DeviceId))
{
var caps = DeviceManager.GetCapabilities(state.Request.DeviceId);
if (caps != null)
{
state.DeviceProfile = caps.DeviceProfile;
}
else
{
state.DeviceProfile = DlnaManager.GetProfile(headers);
}
}
}
2014-05-18 14:23:03 -07:00
2014-04-22 19:47:46 -07:00
var profile = state.DeviceProfile;
2014-03-26 08:17:36 -07:00
if (profile == null)
{
// Don't use settings from the default profile.
// Only use a specific profile if it was requested.
return;
}
2014-03-24 22:25:03 -07:00
2014-10-19 20:04:45 -07:00
var audioCodec = state.ActualOutputAudioCodec;
var videoCodec = state.ActualOutputVideoCodec;
2014-03-24 22:25:03 -07:00
var mediaProfile = state.VideoRequest == null ?
2014-04-23 22:08:10 -07:00
profile.GetAudioMediaProfile(state.OutputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate) :
profile.GetVideoMediaProfile(state.OutputContainer,
audioCodec,
2014-04-23 22:08:10 -07:00
videoCodec,
state.OutputWidth,
state.OutputHeight,
state.TargetVideoBitDepth,
state.OutputVideoBitrate,
state.TargetVideoProfile,
state.TargetVideoLevel,
state.TargetFramerate,
state.TargetPacketLength,
2014-06-22 09:25:47 -07:00
state.TargetTimestamp,
2014-09-08 18:15:31 -07:00
state.IsTargetAnamorphic,
state.TargetRefFrames,
state.TargetVideoStreamCount,
2015-10-19 09:05:03 -07:00
state.TargetAudioStreamCount,
2016-10-02 23:28:45 -07:00
state.TargetVideoCodecTag,
2016-12-14 13:58:55 -07:00
state.IsTargetAVC);
2014-03-24 22:25:03 -07:00
if (mediaProfile != null)
{
state.MimeType = mediaProfile.MimeType;
}
2015-06-02 20:15:46 -07:00
if (!state.Request.Static)
2014-03-24 22:25:03 -07:00
{
2015-06-02 20:15:46 -07:00
var transcodingProfile = state.VideoRequest == null ?
profile.GetAudioTranscodingProfile(state.OutputContainer, audioCodec) :
profile.GetVideoTranscodingProfile(state.OutputContainer, audioCodec, videoCodec);
if (transcodingProfile != null)
{
state.EstimateContentLength = transcodingProfile.EstimateContentLength;
state.EnableMpegtsM2TsMode = transcodingProfile.EnableMpegtsM2TsMode;
state.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo;
if (state.VideoRequest != null)
{
state.VideoRequest.CopyTimestamps = transcodingProfile.CopyTimestamps;
2016-07-13 12:16:51 -07:00
state.VideoRequest.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
}
2015-06-02 20:15:46 -07:00
}
2014-03-24 22:25:03 -07:00
}
}
2016-08-18 17:10:10 -07:00
private async void ReportUsage(StreamState state)
{
try
{
await ReportUsageInternal(state).ConfigureAwait(false);
}
catch
{
}
}
private Task ReportUsageInternal(StreamState state)
{
if (!ServerConfigurationManager.Configuration.EnableAnonymousUsageReporting)
{
return Task.FromResult(true);
}
2016-08-23 23:13:15 -07:00
if (!MediaEncoder.IsDefaultEncoderPath)
2016-08-18 17:10:10 -07:00
{
return Task.FromResult(true);
}
2016-10-31 20:07:45 -07:00
return Task.FromResult(true);
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//var dict = new Dictionary<string, string>();
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//var outputAudio = GetAudioEncoder(state);
//if (!string.IsNullOrWhiteSpace(outputAudio))
//{
// dict["outputAudio"] = outputAudio;
//}
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//var outputVideo = GetVideoEncoder(state);
//if (!string.IsNullOrWhiteSpace(outputVideo))
//{
// dict["outputVideo"] = outputVideo;
//}
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//if (ServerConfigurationManager.Configuration.CodecsUsed.Contains(outputAudio ?? string.Empty, StringComparer.OrdinalIgnoreCase) &&
// ServerConfigurationManager.Configuration.CodecsUsed.Contains(outputVideo ?? string.Empty, StringComparer.OrdinalIgnoreCase))
//{
// return Task.FromResult(true);
//}
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//dict["id"] = AppHost.SystemId;
//dict["type"] = state.VideoRequest == null ? "Audio" : "Video";
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//var audioStream = state.AudioStream;
//if (audioStream != null && !string.IsNullOrWhiteSpace(audioStream.Codec))
//{
// dict["inputAudio"] = audioStream.Codec;
//}
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//var videoStream = state.VideoStream;
//if (videoStream != null && !string.IsNullOrWhiteSpace(videoStream.Codec))
//{
// dict["inputVideo"] = videoStream.Codec;
//}
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//var cert = GetType().Assembly.GetModules().First().GetSignerCertificate();
//if (cert != null)
//{
// dict["assemblySig"] = cert.GetCertHashString();
// dict["certSubject"] = cert.Subject ?? string.Empty;
// dict["certIssuer"] = cert.Issuer ?? string.Empty;
//}
//else
//{
// return Task.FromResult(true);
//}
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//if (state.SupportedAudioCodecs.Count > 0)
//{
// dict["supportedAudioCodecs"] = string.Join(",", state.SupportedAudioCodecs.ToArray());
//}
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//var auth = AuthorizationContext.GetAuthorizationInfo(Request);
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//dict["appName"] = auth.Client ?? string.Empty;
//dict["appVersion"] = auth.Version ?? string.Empty;
//dict["device"] = auth.Device ?? string.Empty;
//dict["deviceId"] = auth.DeviceId ?? string.Empty;
//dict["context"] = "streaming";
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
////Logger.Info(JsonSerializer.SerializeToString(dict));
//if (!ServerConfigurationManager.Configuration.CodecsUsed.Contains(outputAudio ?? string.Empty, StringComparer.OrdinalIgnoreCase))
//{
// var list = ServerConfigurationManager.Configuration.CodecsUsed.ToList();
// list.Add(outputAudio);
// ServerConfigurationManager.Configuration.CodecsUsed = list.ToArray();
//}
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//if (!ServerConfigurationManager.Configuration.CodecsUsed.Contains(outputVideo ?? string.Empty, StringComparer.OrdinalIgnoreCase))
//{
// var list = ServerConfigurationManager.Configuration.CodecsUsed.ToList();
// list.Add(outputVideo);
// ServerConfigurationManager.Configuration.CodecsUsed = list.ToArray();
//}
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
//ServerConfigurationManager.SaveConfiguration();
2016-08-18 17:10:10 -07:00
2016-10-31 20:07:45 -07:00
////Logger.Info(JsonSerializer.SerializeToString(dict));
//var options = new HttpRequestOptions()
//{
// Url = "https://mb3admin.com/admin/service/transcoding/report",
// CancellationToken = CancellationToken.None,
// LogRequest = false,
// LogErrors = false,
// BufferContent = false
//};
//options.RequestContent = JsonSerializer.SerializeToString(dict);
//options.RequestContentType = "application/json";
//return HttpClient.Post(options);
2016-08-18 17:10:10 -07:00
}
2014-03-24 22:25:03 -07:00
/// <summary>
/// Adds the dlna headers.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="responseHeaders">The response headers.</param>
/// <param name="isStaticallyStreamed">if set to <c>true</c> [is statically streamed].</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns>
protected void AddDlnaHeaders(StreamState state, IDictionary<string, string> responseHeaders, bool isStaticallyStreamed)
{
2014-04-22 19:47:46 -07:00
var profile = state.DeviceProfile;
2014-03-24 22:25:03 -07:00
var transferMode = GetHeader("transferMode.dlna.org");
responseHeaders["transferMode.dlna.org"] = string.IsNullOrEmpty(transferMode) ? "Streaming" : transferMode;
responseHeaders["realTimeInfo.dlna.org"] = "DLNA.ORG_TLAG=*";
2015-06-01 18:26:51 -07:00
if (string.Equals(GetHeader("getMediaInfo.sec"), "1", StringComparison.OrdinalIgnoreCase))
{
if (state.RunTimeTicks.HasValue)
{
var ms = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds;
responseHeaders["MediaInfo.sec"] = string.Format("SEC_Duration={0};", Convert.ToInt32(ms).ToString(CultureInfo.InvariantCulture));
}
}
2014-05-03 13:43:22 -07:00
if (state.RunTimeTicks.HasValue && !isStaticallyStreamed && profile != null)
2014-04-01 15:23:07 -07:00
{
2014-04-17 22:03:01 -07:00
AddTimeSeekResponseHeaders(state, responseHeaders);
2014-04-01 15:23:07 -07:00
}
2014-03-24 22:25:03 -07:00
2014-05-03 13:50:28 -07:00
if (profile == null)
{
profile = DlnaManager.GetDefaultProfile();
}
2014-10-19 20:04:45 -07:00
var audioCodec = state.ActualOutputAudioCodec;
if (state.VideoRequest == null)
2014-03-24 22:25:03 -07:00
{
2014-04-22 19:47:46 -07:00
responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
.BuildAudioHeader(
state.OutputContainer,
audioCodec,
state.OutputAudioBitrate,
state.OutputAudioSampleRate,
2014-04-22 19:47:46 -07:00
state.OutputAudioChannels,
isStaticallyStreamed,
state.RunTimeTicks,
state.TranscodeSeekInfo
);
2014-03-24 22:25:03 -07:00
}
2014-04-22 19:47:46 -07:00
else
2014-03-24 22:25:03 -07:00
{
2014-10-19 20:04:45 -07:00
var videoCodec = state.ActualOutputVideoCodec;
2014-04-22 19:47:46 -07:00
responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
.BuildVideoHeader(
state.OutputContainer,
videoCodec,
audioCodec,
state.OutputWidth,
state.OutputHeight,
2014-04-23 22:08:10 -07:00
state.TargetVideoBitDepth,
state.OutputVideoBitrate,
state.TargetTimestamp,
2014-04-22 19:47:46 -07:00
isStaticallyStreamed,
state.RunTimeTicks,
2014-04-23 22:08:10 -07:00
state.TargetVideoProfile,
state.TargetVideoLevel,
state.TargetFramerate,
state.TargetPacketLength,
2014-06-22 09:25:47 -07:00
state.TranscodeSeekInfo,
2014-09-08 18:15:31 -07:00
state.IsTargetAnamorphic,
state.TargetRefFrames,
state.TargetVideoStreamCount,
2015-10-19 09:05:03 -07:00
state.TargetAudioStreamCount,
2016-10-02 23:28:45 -07:00
state.TargetVideoCodecTag,
2016-12-14 13:58:55 -07:00
state.IsTargetAVC
2014-07-30 19:09:23 -07:00
).FirstOrDefault() ?? string.Empty;
2014-04-22 19:47:46 -07:00
}
2014-04-22 19:47:46 -07:00
foreach (var item in responseHeaders)
{
Request.Response.AddHeader(item.Key, item.Value);
}
2014-03-24 22:25:03 -07:00
}
2014-04-01 15:23:07 -07:00
private void AddTimeSeekResponseHeaders(StreamState state, IDictionary<string, string> responseHeaders)
{
var runtimeSeconds = TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalSeconds.ToString(UsCulture);
var startSeconds = TimeSpan.FromTicks(state.Request.StartTimeTicks ?? 0).TotalSeconds.ToString(UsCulture);
responseHeaders["TimeSeekRange.dlna.org"] = string.Format("npt={0}-{1}/{1}", startSeconds, runtimeSeconds);
responseHeaders["X-AvailableSeekRange"] = string.Format("1 npt={0}-{1}", startSeconds, runtimeSeconds);
}
2013-02-26 21:19:05 -07:00
}
}