jellyfin/MediaBrowser.Api/Playback/BaseStreamingService.cs

1229 lines
47 KiB
C#
Raw Normal View History

2015-03-07 22:43:53 +00:00
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
2015-03-07 22:43:53 +00:00
using MediaBrowser.Controller.Devices;
2014-03-25 05:25:03 +00:00
using MediaBrowser.Controller.Dlna;
2013-02-27 04:19:05 +00:00
using MediaBrowser.Controller.Library;
2014-02-20 16:37:41 +00:00
using MediaBrowser.Controller.MediaEncoding;
2014-04-01 22:23:07 +00:00
using MediaBrowser.Model.Dlna;
2014-06-02 19:32:41 +00:00
using MediaBrowser.Model.Dto;
2013-02-27 04:19:05 +00:00
using MediaBrowser.Model.Entities;
2015-03-07 22:43:53 +00:00
using MediaBrowser.Model.Extensions;
using MediaBrowser.Model.IO;
using MediaBrowser.Model.MediaInfo;
2015-06-08 21:32:20 +00:00
using MediaBrowser.Model.Serialization;
2013-02-27 04:19:05 +00:00
using System;
using System.Collections.Generic;
using System.Globalization;
2013-02-27 04:19:05 +00:00
using System.IO;
using System.Linq;
2014-04-06 17:53:23 +00:00
using System.Text;
2013-02-27 04:19:05 +00:00
using System.Threading;
using System.Threading.Tasks;
2016-08-19 00:10:10 +00:00
using MediaBrowser.Common.Net;
using MediaBrowser.Controller;
2016-11-10 14:41:24 +00:00
using MediaBrowser.Controller.Net;
2017-02-02 16:07:52 +00:00
using MediaBrowser.MediaEncoding.Encoder;
2016-11-01 03:07:45 +00:00
using MediaBrowser.Model.Diagnostics;
2013-02-27 04:19:05 +00:00
namespace MediaBrowser.Api.Playback
{
/// <summary>
/// Class BaseStreamingService
/// </summary>
2013-03-16 05:52:33 +00:00
public abstract class BaseStreamingService : BaseApiService
2013-02-27 04:19:05 +00:00
{
/// <summary>
/// Gets or sets the application paths.
/// </summary>
/// <value>The application paths.</value>
protected IServerConfigurationManager ServerConfigurationManager { get; private set; }
2013-02-27 04:19:05 +00:00
/// <summary>
/// Gets or sets the user manager.
/// </summary>
/// <value>The user manager.</value>
2013-09-04 17:02:19 +00:00
protected IUserManager UserManager { get; private set; }
/// <summary>
/// Gets or sets the library manager.
/// </summary>
/// <value>The library manager.</value>
2013-09-04 17:02:19 +00:00
protected ILibraryManager LibraryManager { get; private set; }
2013-03-04 05:43:06 +00:00
2013-02-27 04:19:05 +00:00
/// <summary>
2013-03-04 05:43:06 +00:00
/// Gets or sets the iso manager.
2013-02-27 04:19:05 +00:00
/// </summary>
2013-03-04 05:43:06 +00:00
/// <value>The iso manager.</value>
2013-09-04 17:02:19 +00:00
protected IIsoManager IsoManager { get; private set; }
2013-02-27 04:19:05 +00:00
/// <summary>
/// Gets or sets the media encoder.
/// </summary>
/// <value>The media encoder.</value>
2013-09-04 17:02:19 +00:00
protected IMediaEncoder MediaEncoder { get; private set; }
protected IFileSystem FileSystem { get; private set; }
2013-12-06 03:39:44 +00:00
2014-03-25 05:25:03 +00:00
protected IDlnaManager DlnaManager { get; private set; }
2015-01-20 05:19:13 +00:00
protected IDeviceManager DeviceManager { get; private set; }
2014-06-11 19:31:33 +00:00
protected ISubtitleEncoder SubtitleEncoder { get; private set; }
2015-03-07 22:43:53 +00:00
protected IMediaSourceManager MediaSourceManager { get; private set; }
2015-03-17 03:48:05 +00:00
protected IZipClient ZipClient { get; private set; }
2015-05-04 17:44:25 +00:00
protected IJsonSerializer JsonSerializer { get; private set; }
2013-12-06 03:39:44 +00:00
2016-08-19 00:10:10 +00:00
public static IServerApplicationHost AppHost;
public static IHttpClient HttpClient;
2016-11-10 14:41:24 +00:00
protected IAuthorizationContext AuthorizationContext { get; private set; }
2016-08-19 00:10:10 +00:00
2017-02-02 16:07:52 +00:00
protected EncodingHelper EncodingHelper { get; set; }
2013-02-27 04:19:05 +00:00
/// <summary>
2017-02-02 16:07:52 +00:00
/// Initializes a new instance of the <see cref="BaseStreamingService" /> class.
2013-02-27 04:19:05 +00:00
/// </summary>
2017-02-02 16:07:52 +00:00
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-27 04:19:05 +00:00
{
2017-02-02 16:07:52 +00: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-27 04:19:05 +00:00
}
/// <summary>
2017-02-02 16:07:52 +00:00
/// Gets the command line arguments.
/// </summary>
2017-02-02 16:07:52 +00:00
/// <param name="outputPath">The output path.</param>
/// <param name="state">The state.</param>
2017-02-02 16:07:52 +00:00
/// <param name="isEncoding">if set to <c>true</c> [is encoding].</param>
/// <returns>System.String.</returns>
2017-02-02 16:07:52 +00:00
protected abstract string GetCommandLineArguments(string outputPath, StreamState state, bool isEncoding);
2013-02-27 04:19:05 +00:00
/// <summary>
2017-02-02 16:07:52 +00:00
/// Gets the type of the transcoding job.
2013-02-27 04:19:05 +00:00
/// </summary>
2017-02-02 16:07:52 +00:00
/// <value>The type of the transcoding job.</value>
protected abstract TranscodingJobType TranscodingJobType { get; }
2013-02-27 04:19:05 +00:00
/// <summary>
2017-02-02 16:07:52 +00:00
/// Gets the output file extension.
2013-02-27 04:19:05 +00:00
/// </summary>
2015-07-25 17:21:10 +00:00
/// <param name="state">The state.</param>
2013-02-27 04:19:05 +00:00
/// <returns>System.String.</returns>
2017-02-02 16:07:52 +00:00
protected virtual string GetOutputFileExtension(StreamState state)
2013-02-27 04:19:05 +00:00
{
2017-02-02 16:07:52 +00:00
return Path.GetExtension(state.RequestedUrl);
2013-02-27 04:19:05 +00:00
}
/// <summary>
2017-02-02 16:07:52 +00:00
/// Gets the output file path.
2013-02-27 04:19:05 +00:00
/// </summary>
2015-07-25 17:21:10 +00:00
/// <param name="state">The state.</param>
2013-02-27 04:19:05 +00:00
/// <returns>System.String.</returns>
2017-02-02 16:07:52 +00:00
private string GetOutputFilePath(StreamState state)
2013-02-27 04:19:05 +00:00
{
2017-02-02 16:07:52 +00:00
var folder = ServerConfigurationManager.ApplicationPaths.TranscodingTempPath;
2017-02-02 16:07:52 +00:00
var outputFileExtension = GetOutputFileExtension(state);
2013-02-27 04:19:05 +00:00
2017-02-02 16:07:52 +00:00
var data = GetCommandLineArguments("dummy\\dummy", state, false);
2013-02-27 04:19:05 +00:00
2017-02-02 16:07:52 +00:00
data += "-" + (state.Request.DeviceId ?? string.Empty);
data += "-" + (state.Request.PlaySessionId ?? string.Empty);
2017-02-02 16:07:52 +00:00
var dataHash = data.GetMD5().ToString("N");
2016-04-30 04:00:45 +00:00
2017-02-02 16:07:52 +00:00
if (EnableOutputInSubFolder)
{
2017-02-02 16:07:52 +00:00
return Path.Combine(folder, dataHash, dataHash + (outputFileExtension ?? string.Empty).ToLower());
}
2017-02-02 16:07:52 +00:00
return Path.Combine(folder, dataHash + (outputFileExtension ?? string.Empty).ToLower());
}
2017-02-02 16:07:52 +00:00
protected virtual bool EnableOutputInSubFolder
2014-12-20 06:06:27 +00:00
{
2017-02-02 16:07:52 +00:00
get { return false; }
2014-12-20 06:06:27 +00:00
}
2017-02-02 16:07:52 +00:00
protected readonly CultureInfo UsCulture = new CultureInfo("en-US");
2017-02-02 16:07:52 +00:00
protected virtual string GetDefaultH264Preset()
{
return "superfast";
2013-02-27 04:19:05 +00:00
}
2014-06-28 19:35:30 +00: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 12:54:10 +00:00
if (state.MediaSource.RequiresOpening && string.IsNullOrWhiteSpace(state.Request.LiveStreamId))
2014-06-28 19:35:30 +00:00
{
2015-03-29 16:45:16 +00:00
var liveStreamResponse = await MediaSourceManager.OpenLiveStream(new LiveStreamRequest
{
OpenToken = state.MediaSource.OpenToken
}, false, cancellationTokenSource.Token).ConfigureAwait(false);
2014-06-28 19:35:30 +00:00
2017-02-02 16:07:52 +00:00
EncodingHelper.AttachMediaSourceInfo(state, liveStreamResponse.MediaSource, state.RequestedUrl);
2014-06-28 19:35:30 +00:00
2015-03-28 20:22:27 +00:00
if (state.VideoRequest != null)
2014-06-28 19:35:30 +00:00
{
2017-02-02 16:07:52 +00:00
EncodingHelper.TryStreamCopy(state);
2014-08-15 16:35:41 +00:00
}
2015-03-29 04:56:39 +00:00
}
2014-08-15 16:35:41 +00:00
2015-03-29 04:56:39 +00:00
if (state.MediaSource.BufferMs.HasValue)
{
await Task.Delay(state.MediaSource.BufferMs.Value, cancellationTokenSource.Token).ConfigureAwait(false);
2014-06-28 19:35:30 +00:00
}
}
2013-02-27 04:19:05 +00:00
/// <summary>
/// Starts the FFMPEG.
/// </summary>
/// <param name="state">The state.</param>
/// <param name="outputPath">The output path.</param>
2014-06-02 19:32:41 +00:00
/// <param name="cancellationTokenSource">The cancellation token source.</param>
2014-10-16 03:26:39 +00:00
/// <param name="workingDirectory">The working directory.</param>
2013-02-27 04:19:05 +00:00
/// <returns>Task.</returns>
2014-12-20 06:06:27 +00:00
protected async Task<TranscodingJob> StartFfMpeg(StreamState state,
string outputPath,
2014-10-16 03:26:39 +00:00
CancellationTokenSource cancellationTokenSource,
string workingDirectory = null)
2013-02-27 04:19:05 +00:00
{
2015-09-13 21:32:02 +00:00
FileSystem.CreateDirectory(Path.GetDirectoryName(outputPath));
2013-06-04 16:48:23 +00:00
2014-06-28 19:35:30 +00:00
await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);
2013-02-27 04:19:05 +00: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-03 02:30:24 +00:00
var transcodingId = Guid.NewGuid().ToString("N");
2015-03-28 20:22:27 +00:00
var commandLineArgs = GetCommandLineArguments(outputPath, state, true);
2016-11-01 03:07:45 +00:00
var process = ApiEntryPoint.Instance.ProcessFactory.Create(new ProcessOptions
2013-02-27 04:19:05 +00:00
{
2016-11-01 03:07:45 +00:00
CreateNoWindow = true,
UseShellExecute = false,
2013-02-27 04:19:05 +00:00
2016-11-01 03:07:45 +00:00
// Must consume both stdout and stderr or deadlocks may occur
//RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
2013-02-27 04:19:05 +00:00
2016-11-01 03:07:45 +00:00
FileName = MediaEncoder.EncoderPath,
Arguments = commandLineArgs,
2013-02-27 04:19:05 +00:00
2016-11-01 03:07:45 +00:00
IsHidden = true,
ErrorDialog = false,
EnableRaisingEvents = true,
WorkingDirectory = !string.IsNullOrWhiteSpace(workingDirectory) ? workingDirectory : null
});
2014-10-16 03:26:39 +00:00
2014-09-03 02:30:24 +00:00
var transcodingJob = ApiEntryPoint.Instance.OnTranscodeBeginning(outputPath,
2015-03-29 18:31:28 +00:00
state.Request.PlaySessionId,
2015-04-20 18:04:02 +00:00
state.MediaSource.LiveStreamId,
2014-09-03 02:30:24 +00:00
transcodingId,
TranscodingJobType,
process,
state.Request.DeviceId,
state,
cancellationTokenSource);
2013-02-27 04:19:05 +00:00
2014-04-03 22:50:04 +00:00
var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments;
Logger.Info(commandLineLogMessage);
2013-02-27 04:19:05 +00:00
var logFilePrefix = "ffmpeg-transcode";
2016-04-12 18:01:23 +00: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 18:01:23 +00:00
}
else if (state.VideoRequest != null && string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
{
logFilePrefix = "ffmpeg-remux";
2016-04-12 18:01:23 +00:00
}
var logFilePath = Path.Combine(ServerConfigurationManager.ApplicationPaths.LogDirectoryPath, logFilePrefix + "-" + Guid.NewGuid() + ".txt");
2015-09-13 21:32:02 +00:00
FileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath));
2013-02-27 04:19:05 +00: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 19:02:04 +00:00
state.LogFileStream = FileSystem.GetFileStream(logFilePath, FileOpenMode.Create, FileAccessMode.Write, FileShareMode.Read, true);
2013-02-27 04:19:05 +00:00
2015-05-04 17:44:25 +00: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 19:32:41 +00:00
await state.LogFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationTokenSource.Token).ConfigureAwait(false);
2014-04-03 22:50:04 +00:00
2014-09-03 02:30:24 +00:00
process.Exited += (sender, args) => OnFfMpegProcessExited(process, transcodingJob, state);
2013-02-27 04:19:05 +00:00
try
{
process.Start();
}
catch (Exception ex)
2013-02-27 04:19:05 +00:00
{
Logger.ErrorException("Error starting ffmpeg", ex);
ApiEntryPoint.Instance.OnTranscodeFailedToStart(outputPath, TranscodingJobType, state);
2013-02-27 04:19:05 +00:00
throw;
}
// MUST read both stdout and stderr asynchronously or a deadlock may occurr
2016-07-02 02:16:05 +00:00
//process.BeginOutputReadLine();
2013-02-27 04:19:05 +00:00
// Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback
var task = Task.Run(() => StartStreamingLog(transcodingJob, state, process.StandardError.BaseStream, state.LogFileStream));
2013-02-27 04:19:05 +00:00
// Wait for the file to exist before proceeeding
2016-04-04 05:07:10 +00:00
while (!FileSystem.FileExists(state.WaitForPath ?? outputPath) && !transcodingJob.HasExited)
2013-02-27 04:19:05 +00:00
{
2014-06-02 19:32:41 +00:00
await Task.Delay(100, cancellationTokenSource.Token).ConfigureAwait(false);
2013-02-27 04:19:05 +00:00
}
2014-09-03 02:30:24 +00:00
2016-09-07 17:17:26 +00:00
if (state.IsInputVideo && transcodingJob.Type == TranscodingJobType.Progressive && !transcodingJob.HasExited)
2014-10-15 00:04:44 +00:00
{
await Task.Delay(1000, cancellationTokenSource.Token).ConfigureAwait(false);
2016-09-07 17:17:26 +00:00
if (state.ReadInputAtNativeFramerate && !transcodingJob.HasExited)
2014-10-15 00:04:44 +00:00
{
2014-11-11 03:41:55 +00:00
await Task.Delay(1500, cancellationTokenSource.Token).ConfigureAwait(false);
2014-10-15 00:04:44 +00:00
}
}
2016-09-07 17:17:26 +00:00
if (!transcodingJob.HasExited)
{
StartThrottler(state, transcodingJob);
}
2016-08-19 00:10:10 +00:00
ReportUsage(state);
2015-02-28 18:47:05 +00:00
2014-09-03 02:30:24 +00:00
return transcodingJob;
2013-02-27 04:19:05 +00:00
}
2015-02-28 18:47:05 +00:00
private void StartThrottler(StreamState state, TranscodingJob transcodingJob)
{
2016-09-21 17:07:18 +00:00
if (EnableThrottling(state))
2015-02-28 18:47:05 +00:00
{
2016-11-01 03:07:45 +00:00
transcodingJob.TranscodingThrottler = state.TranscodingThrottler = new TranscodingThrottler(transcodingJob, Logger, ServerConfigurationManager, ApiEntryPoint.Instance.TimerFactory, FileSystem);
state.TranscodingThrottler.Start();
2015-02-28 18:47:05 +00:00
}
}
2016-09-23 05:45:14 +00:00
private bool EnableThrottling(StreamState state)
2015-05-19 19:15:40 +00:00
{
2016-11-08 18:44:23 +00:00
return false;
2017-02-02 16:07:52 +00:00
//// 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 19:15:40 +00:00
}
2016-04-29 16:54:51 +00:00
private async Task StartStreamingLog(TranscodingJob transcodingJob, StreamState state, Stream source, Stream target)
{
try
{
using (var reader = new StreamReader(source))
{
while (!reader.EndOfStream)
{
var line = await reader.ReadLineAsync().ConfigureAwait(false);
2014-09-03 02:30:24 +00:00
ParseLogLine(line, transcodingJob, state);
var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line);
await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false);
2015-09-20 02:06:56 +00:00
await target.FlushAsync().ConfigureAwait(false);
}
}
}
2015-05-07 22:27:01 +00:00
catch (ObjectDisposedException)
{
// Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux
}
catch (Exception ex)
{
Logger.ErrorException("Error reading ffmpeg log", ex);
}
}
2014-09-03 02:30:24 +00:00
private void ParseLogLine(string line, TranscodingJob transcodingJob, StreamState state)
{
float? framerate = null;
double? percent = null;
2014-09-03 02:30:24 +00:00
TimeSpan? transcodingPosition = null;
long? bytesTranscoded = null;
int? bitRate = null;
var parts = line.Split(' ');
var totalMs = state.RunTimeTicks.HasValue
? TimeSpan.FromTicks(state.RunTimeTicks.Value).TotalMilliseconds
: 0;
var startMs = state.Request.StartTimeTicks.HasValue
? TimeSpan.FromTicks(state.Request.StartTimeTicks.Value).TotalMilliseconds
: 0;
for (var i = 0; i < parts.Length; i++)
{
var part = parts[i];
if (string.Equals(part, "fps=", StringComparison.OrdinalIgnoreCase) &&
(i + 1 < parts.Length))
{
var rate = parts[i + 1];
float val;
if (float.TryParse(rate, NumberStyles.Any, UsCulture, out val))
{
framerate = val;
}
}
else if (state.RunTimeTicks.HasValue &&
part.StartsWith("time=", StringComparison.OrdinalIgnoreCase))
{
var time = part.Split(new[] { '=' }, 2).Last();
TimeSpan val;
if (TimeSpan.TryParse(time, UsCulture, out val))
{
var currentMs = startMs + val.TotalMilliseconds;
var percentVal = currentMs / totalMs;
percent = 100 * percentVal;
2014-09-03 02:30:24 +00:00
transcodingPosition = val;
}
}
else if (part.StartsWith("size=", StringComparison.OrdinalIgnoreCase))
{
var size = part.Split(new[] { '=' }, 2).Last();
int? scale = null;
if (size.IndexOf("kb", StringComparison.OrdinalIgnoreCase) != -1)
{
scale = 1024;
size = size.Replace("kb", string.Empty, StringComparison.OrdinalIgnoreCase);
}
if (scale.HasValue)
{
long val;
2014-12-20 06:06:27 +00:00
2014-09-03 02:30:24 +00:00
if (long.TryParse(size, NumberStyles.Any, UsCulture, out val))
{
bytesTranscoded = val * scale.Value;
}
}
}
else if (part.StartsWith("bitrate=", StringComparison.OrdinalIgnoreCase))
{
var rate = part.Split(new[] { '=' }, 2).Last();
2017-02-02 16:07:52 +00:00
int? scale = null;
if (rate.IndexOf("kbits/s", StringComparison.OrdinalIgnoreCase) != -1)
{
scale = 1024;
rate = rate.Replace("kbits/s", string.Empty, StringComparison.OrdinalIgnoreCase);
}
2014-02-02 14:47:00 +00:00
2017-02-02 16:07:52 +00:00
if (scale.HasValue)
{
float val;
2013-08-30 02:13:58 +00:00
2017-02-02 16:07:52 +00:00
if (float.TryParse(rate, NumberStyles.Any, UsCulture, out val))
{
bitRate = (int)Math.Ceiling(val * scale.Value);
}
}
}
2013-08-30 02:13:58 +00:00
}
2017-02-02 16:07:52 +00:00
if (framerate.HasValue || percent.HasValue)
2013-05-17 18:05:49 +00:00
{
2017-02-02 16:07:52 +00:00
ApiEntryPoint.Instance.ReportTranscodingProgress(transcodingJob, state, transcodingPosition, framerate, percent, bytesTranscoded, bitRate);
2013-05-17 18:05:49 +00:00
}
}
2013-02-27 04:19:05 +00:00
/// <summary>
/// Processes the exited.
/// </summary>
/// <param name="process">The process.</param>
2014-09-03 02:30:24 +00:00
/// <param name="job">The job.</param>
2013-02-27 04:19:05 +00:00
/// <param name="state">The state.</param>
2016-11-01 03:07:45 +00:00
private void OnFfMpegProcessExited(IProcess process, TranscodingJob job, StreamState state)
2013-02-27 04:19:05 +00:00
{
2014-06-26 17:04:11 +00:00
if (job != null)
{
job.HasExited = true;
}
2014-06-20 04:50:30 +00:00
Logger.Debug("Disposing stream resources");
2014-04-05 15:02:50 +00:00
state.Dispose();
2014-01-03 04:58:22 +00:00
2013-02-27 04:19:05 +00:00
try
{
Logger.Info("FFMpeg exited with code {0}", process.ExitCode);
2013-02-27 04:19:05 +00:00
}
catch
{
2014-06-20 04:50:30 +00:00
Logger.Error("FFMpeg exited with an error.");
2013-02-27 04:19:05 +00:00
}
2014-06-20 04:50:30 +00: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-27 04:19:05 +00:00
}
2014-02-13 05:11:54 +00: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 15:06:48 +00:00
request.DeviceProfileId = val;
}
2014-03-25 05:25:03 +00:00
else if (i == 1)
2014-03-23 05:10:33 +00:00
{
2014-03-26 15:06:48 +00:00
request.DeviceId = val;
2014-03-23 05:10:33 +00:00
}
2014-03-25 05:25:03 +00:00
else if (i == 2)
2014-03-23 17:18:24 +00:00
{
2014-03-26 15:06:48 +00:00
request.MediaSourceId = val;
2014-03-23 17:18:24 +00:00
}
2014-03-25 05:25:03 +00:00
else if (i == 3)
2014-03-26 15:06:48 +00:00
{
request.Static = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
else if (i == 4)
2014-02-13 05:11:54 +00:00
{
if (videoRequest != null)
{
2014-03-23 20:07:02 +00:00
videoRequest.VideoCodec = val;
2014-02-13 05:11:54 +00:00
}
}
2014-03-26 15:06:48 +00:00
else if (i == 5)
2014-02-13 05:11:54 +00:00
{
2014-03-23 20:07:02 +00:00
request.AudioCodec = val;
2014-02-13 05:11:54 +00:00
}
2014-03-26 15:06:48 +00:00
else if (i == 6)
2014-02-13 05:11:54 +00:00
{
if (videoRequest != null)
{
videoRequest.AudioStreamIndex = int.Parse(val, UsCulture);
}
}
2014-03-26 15:06:48 +00:00
else if (i == 7)
2014-02-13 05:11:54 +00:00
{
if (videoRequest != null)
{
videoRequest.SubtitleStreamIndex = int.Parse(val, UsCulture);
}
}
2014-03-26 15:06:48 +00:00
else if (i == 8)
2014-02-13 05:11:54 +00:00
{
if (videoRequest != null)
{
videoRequest.VideoBitRate = int.Parse(val, UsCulture);
}
}
2014-03-26 15:06:48 +00:00
else if (i == 9)
2014-02-13 05:11:54 +00:00
{
request.AudioBitRate = int.Parse(val, UsCulture);
}
2014-03-26 15:06:48 +00:00
else if (i == 10)
2014-02-13 05:11:54 +00:00
{
2014-03-23 05:10:33 +00:00
request.MaxAudioChannels = int.Parse(val, UsCulture);
2014-02-13 05:11:54 +00:00
}
2014-03-26 15:06:48 +00:00
else if (i == 11)
{
if (videoRequest != null)
{
2014-06-23 16:05:19 +00:00
videoRequest.MaxFramerate = float.Parse(val, UsCulture);
}
}
2014-03-26 15:06:48 +00:00
else if (i == 12)
{
if (videoRequest != null)
{
2014-03-28 04:24:11 +00:00
videoRequest.MaxWidth = int.Parse(val, UsCulture);
}
}
2014-03-26 15:06:48 +00:00
else if (i == 13)
2014-03-24 17:54:45 +00:00
{
if (videoRequest != null)
{
2014-03-28 04:24:11 +00:00
videoRequest.MaxHeight = int.Parse(val, UsCulture);
2014-03-24 17:54:45 +00:00
}
}
2014-03-26 15:06:48 +00:00
else if (i == 14)
2014-03-24 17:54:45 +00:00
{
2014-03-30 19:05:10 +00:00
request.StartTimeTicks = long.Parse(val, UsCulture);
2014-03-24 17:54:45 +00:00
}
2014-03-26 15:06:48 +00:00
else if (i == 15)
2014-03-28 04:24:11 +00:00
{
if (videoRequest != null)
{
videoRequest.Level = val;
}
}
2014-09-18 04:50:21 +00:00
else if (i == 16)
2014-09-23 04:05:29 +00:00
{
if (videoRequest != null)
{
videoRequest.MaxRefFrames = int.Parse(val, UsCulture);
}
}
2015-11-27 04:33:20 +00:00
else if (i == 17)
2014-09-23 04:05:29 +00:00
{
if (videoRequest != null)
{
videoRequest.MaxVideoBitDepth = int.Parse(val, UsCulture);
}
}
2015-11-27 04:33:20 +00:00
else if (i == 18)
2014-10-09 22:22:04 +00:00
{
if (videoRequest != null)
{
videoRequest.Profile = val;
}
}
2015-11-27 04:33:20 +00:00
else if (i == 19)
2014-11-12 04:51:40 +00:00
{
2016-04-04 00:01:03 +00:00
// cabac no longer used
2014-11-12 04:51:40 +00:00
}
2015-11-27 04:33:20 +00:00
else if (i == 20)
2015-03-23 17:19:21 +00:00
{
2015-03-29 18:31:28 +00:00
request.PlaySessionId = val;
2015-03-23 17:19:21 +00:00
}
2015-11-27 04:33:20 +00:00
else if (i == 21)
2015-04-12 16:46:29 +00:00
{
// api_key
}
2015-11-27 04:33:20 +00:00
else if (i == 22)
2015-03-29 18:16:40 +00:00
{
request.LiveStreamId = val;
}
2015-11-27 04:33:20 +00:00
else if (i == 23)
2015-04-24 20:06:37 +00:00
{
// Duplicating ItemId because of MediaMonkey
}
else if (i == 24)
{
if (videoRequest != null)
{
videoRequest.CopyTimestamps = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
}
2016-03-07 04:56:45 +00:00
else if (i == 25)
{
if (!string.IsNullOrWhiteSpace(val) && videoRequest != null)
{
SubtitleDeliveryMethod method;
if (Enum.TryParse(val, out method))
{
videoRequest.SubtitleMethod = method;
}
}
}
2016-08-23 05:08:07 +00:00
else if (i == 26)
2016-05-14 05:40:01 +00:00
{
request.TranscodingMaxAudioChannels = int.Parse(val, UsCulture);
}
2016-08-23 05:08:07 +00:00
else if (i == 27)
2016-07-13 19:16:51 +00:00
{
if (videoRequest != null)
{
videoRequest.EnableSubtitlesInManifest = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
}
2016-08-23 05:08:07 +00:00
else if (i == 28)
{
request.Tag = val;
}
2016-10-16 17:11:32 +00:00
else if (i == 29)
2016-11-14 07:28:20 +00:00
{
if (videoRequest != null)
{
videoRequest.RequireAvc = string.Equals("true", val, StringComparison.OrdinalIgnoreCase);
}
}
2017-01-29 20:00:29 +00:00
else if (i == 30)
{
request.SubtitleCodec = val;
}
2014-02-13 05:11:54 +00:00
}
}
2014-04-01 22:23:07 +00: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 21:11:27 +00:00
secondsSum += digit * timeFactor;
2014-04-01 22:23:07 +00:00
}
else
{
throw new ArgumentException("Invalid timeseek header");
}
2017-02-02 16:07:52 +00:00
timeFactor /= 60;
2014-06-01 19:41:35 +00:00
}
2017-02-02 16:07:52 +00:00
return TimeSpan.FromSeconds(secondsSum).Ticks;
2014-06-01 19:41:35 +00:00
}
2017-02-02 16:07:52 +00: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-02 04:10:46 +00:00
{
2017-02-02 16:07:52 +00:00
ParseDlnaHeaders(request);
2016-04-04 04:18:36 +00:00
2017-02-02 16:07:52 +00:00
if (!string.IsNullOrWhiteSpace(request.Params))
2014-04-02 04:10:46 +00:00
{
2017-02-02 16:07:52 +00:00
ParseParams(request);
2014-04-02 04:10:46 +00:00
}
2017-02-02 16:07:52 +00:00
var url = Request.PathInfo;
2016-04-04 05:07:10 +00:00
2017-02-02 16:07:52 +00:00
if (string.IsNullOrEmpty(request.AudioCodec))
2014-06-20 05:31:32 +00:00
{
2017-02-02 16:07:52 +00:00
request.AudioCodec = EncodingHelper.InferAudioCodec(url);
2014-06-20 05:31:32 +00:00
}
2017-02-02 16:07:52 +00:00
var state = new StreamState(MediaSourceManager, Logger, TranscodingJobType)
2016-04-27 19:23:05 +00:00
{
2017-02-02 16:07:52 +00:00
Request = request,
RequestedUrl = url,
UserAgent = Request.UserAgent
};
2016-04-27 19:23:05 +00:00
2017-02-02 16:07:52 +00:00
var auth = AuthorizationContext.GetAuthorizationInfo(Request);
if (!string.IsNullOrWhiteSpace(auth.UserId))
2014-04-02 04:10:46 +00:00
{
2017-02-02 16:07:52 +00:00
state.User = UserManager.GetUserById(auth.UserId);
2014-04-02 04:10:46 +00:00
}
2017-02-02 16:07:52 +00: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-02 04:10:46 +00:00
2017-02-02 16:07:52 +00:00
if (state.VideoRequest != null)
2014-04-02 04:10:46 +00:00
{
2017-02-02 16:07:52 +00:00
if (!string.IsNullOrWhiteSpace(state.VideoRequest.VideoCodec))
2014-10-20 03:04:45 +00:00
{
2017-02-02 16:07:52 +00:00
state.SupportedVideoCodecs = state.VideoRequest.VideoCodec.Split(',').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
state.VideoRequest.VideoCodec = state.SupportedVideoCodecs.FirstOrDefault();
2014-10-20 03:04:45 +00:00
}
2014-04-02 04:10:46 +00:00
}
2017-02-02 16:07:52 +00:00
if (!string.IsNullOrWhiteSpace(request.AudioCodec))
2014-04-02 04:10:46 +00:00
{
2017-02-02 16:07:52 +00: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-02 04:10:46 +00:00
}
2017-02-02 16:07:52 +00:00
if (!string.IsNullOrWhiteSpace(request.SubtitleCodec))
2014-04-02 04:10:46 +00:00
{
2017-02-02 16:07:52 +00: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-02 04:10:46 +00:00
}
2017-02-02 16:07:52 +00:00
var item = LibraryManager.GetItemById(request.Id);
2014-04-02 04:10:46 +00:00
2017-02-02 16:07:52 +00:00
state.IsInputVideo = string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase);
2014-04-02 04:10:46 +00:00
2017-02-02 16:07:52 +00:00
MediaSourceInfo mediaSource = null;
if (string.IsNullOrWhiteSpace(request.LiveStreamId))
2014-04-02 04:10:46 +00:00
{
2017-02-02 16:07:52 +00:00
TranscodingJob currentJob = !string.IsNullOrWhiteSpace(request.PlaySessionId) ?
ApiEntryPoint.Instance.GetTranscodingJob(request.PlaySessionId)
: null;
2014-04-02 04:10:46 +00:00
2017-02-02 16:07:52 +00:00
if (currentJob != null)
2014-09-23 04:05:29 +00:00
{
2017-02-02 16:07:52 +00:00
mediaSource = currentJob.MediaSource;
2014-09-23 04:05:29 +00:00
}
2017-02-02 16:07:52 +00:00
if (mediaSource == null)
2014-09-23 04:05:29 +00:00
{
2017-02-02 16:07:52 +00:00
var mediaSources = (await MediaSourceManager.GetPlayackMediaSources(request.Id, null, false, new[] { MediaType.Audio, MediaType.Video }, cancellationToken).ConfigureAwait(false)).ToList();
2014-04-02 04:10:46 +00:00
2017-02-02 16:07:52 +00:00
mediaSource = string.IsNullOrEmpty(request.MediaSourceId)
? mediaSources.First()
: mediaSources.FirstOrDefault(i => string.Equals(i.Id, request.MediaSourceId));
2014-04-02 04:10:46 +00:00
2017-02-02 16:07:52 +00:00
if (mediaSource == null && string.Equals(request.Id, request.MediaSourceId, StringComparison.OrdinalIgnoreCase))
2014-04-02 04:10:46 +00:00
{
2017-02-02 16:07:52 +00:00
mediaSource = mediaSources.First();
2014-04-02 04:10:46 +00:00
}
}
}
2017-02-02 16:07:52 +00:00
else
2014-10-20 03:04:45 +00:00
{
2017-02-02 16:07:52 +00:00
var liveStreamInfo = await MediaSourceManager.GetLiveStreamWithDirectStreamProvider(request.LiveStreamId, cancellationToken).ConfigureAwait(false);
mediaSource = liveStreamInfo.Item1;
state.DirectStreamProvider = liveStreamInfo.Item2;
}
2014-10-20 03:04:45 +00:00
2017-02-02 16:07:52 +00:00
var videoRequest = request as VideoStreamRequest;
2014-10-20 03:04:45 +00:00
2017-02-02 16:07:52 +00:00
EncodingHelper.AttachMediaSourceInfo(state, mediaSource, url);
2016-04-04 05:07:10 +00:00
2017-02-02 16:07:52 +00:00
var container = Path.GetExtension(state.RequestedUrl);
2014-04-06 17:53:23 +00:00
2017-02-02 16:07:52 +00:00
if (string.IsNullOrEmpty(container))
2014-04-06 17:53:23 +00:00
{
2017-02-02 16:07:52 +00:00
container = request.Static ?
state.InputContainer :
(Path.GetExtension(GetOutputFilePath(state)) ?? string.Empty).TrimStart('.');
2014-04-06 17:53:23 +00:00
}
2017-02-02 16:07:52 +00: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 17:53:23 +00:00
{
2017-02-02 16:07:52 +00:00
state.OutputVideoCodec = state.VideoRequest.VideoCodec;
state.OutputVideoBitrate = EncodingHelper.GetVideoBitrateParamValue(state.VideoRequest, state.VideoStream, state.OutputVideoCodec);
if (videoRequest != null)
2014-05-30 21:06:57 +00:00
{
2017-02-02 16:07:52 +00:00
EncodingHelper.TryStreamCopy(state);
2014-05-30 21:06:57 +00:00
}
2017-02-02 16:07:52 +00:00
if (state.OutputVideoBitrate.HasValue && !string.Equals(state.OutputVideoCodec, "copy", StringComparison.OrdinalIgnoreCase))
2014-04-06 17:53:23 +00:00
{
2017-02-02 16:07:52 +00: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 17:53:23 +00:00
}
2017-02-02 16:07:52 +00:00
ApplyDeviceProfileSettings(state);
}
else
2014-04-06 17:53:23 +00:00
{
2017-02-02 16:07:52 +00:00
ApplyDeviceProfileSettings(state);
2014-04-06 17:53:23 +00:00
}
2017-02-02 16:07:52 +00:00
state.OutputFilePath = GetOutputFilePath(state);
return state;
2014-04-06 17:53:23 +00:00
}
2014-04-08 04:17:18 +00:00
2014-03-25 05:25:03 +00:00
private void ApplyDeviceProfileSettings(StreamState state)
{
2016-10-25 19:02:04 +00:00
var headers = Request.Headers.ToDictionary();
2014-05-18 21:23:03 +00:00
2015-01-20 05:19:13 +00: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 21:23:03 +00:00
2014-04-23 02:47:46 +00:00
var profile = state.DeviceProfile;
2014-03-26 15:17:36 +00:00
if (profile == null)
{
// Don't use settings from the default profile.
// Only use a specific profile if it was requested.
return;
}
2014-03-25 05:25:03 +00:00
2014-10-20 03:04:45 +00:00
var audioCodec = state.ActualOutputAudioCodec;
var videoCodec = state.ActualOutputVideoCodec;
2014-03-25 05:25:03 +00:00
var mediaProfile = state.VideoRequest == null ?
2014-04-24 05:08:10 +00:00
profile.GetAudioMediaProfile(state.OutputContainer, audioCodec, state.OutputAudioChannels, state.OutputAudioBitrate) :
profile.GetVideoMediaProfile(state.OutputContainer,
audioCodec,
2014-04-24 05:08:10 +00:00
videoCodec,
state.OutputWidth,
state.OutputHeight,
state.TargetVideoBitDepth,
state.OutputVideoBitrate,
state.TargetVideoProfile,
state.TargetVideoLevel,
state.TargetFramerate,
state.TargetPacketLength,
2014-06-22 16:25:47 +00:00
state.TargetTimestamp,
2014-09-09 01:15:31 +00:00
state.IsTargetAnamorphic,
state.TargetRefFrames,
state.TargetVideoStreamCount,
2015-10-19 16:05:03 +00:00
state.TargetAudioStreamCount,
2016-10-03 06:28:45 +00:00
state.TargetVideoCodecTag,
2016-12-14 20:58:55 +00:00
state.IsTargetAVC);
2014-03-25 05:25:03 +00:00
if (mediaProfile != null)
{
state.MimeType = mediaProfile.MimeType;
}
2015-06-03 03:15:46 +00:00
if (!state.Request.Static)
2014-03-25 05:25:03 +00:00
{
2015-06-03 03:15:46 +00: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 19:16:51 +00:00
state.VideoRequest.EnableSubtitlesInManifest = transcodingProfile.EnableSubtitlesInManifest;
}
2015-06-03 03:15:46 +00:00
}
2014-03-25 05:25:03 +00:00
}
}
2016-08-19 00:10:10 +00: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-24 06:13:15 +00:00
if (!MediaEncoder.IsDefaultEncoderPath)
2016-08-19 00:10:10 +00:00
{
return Task.FromResult(true);
}
2016-11-01 03:07:45 +00:00
return Task.FromResult(true);
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00:00
//var dict = new Dictionary<string, string>();
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00:00
//var outputAudio = GetAudioEncoder(state);
//if (!string.IsNullOrWhiteSpace(outputAudio))
//{
// dict["outputAudio"] = outputAudio;
//}
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00:00
//var outputVideo = GetVideoEncoder(state);
//if (!string.IsNullOrWhiteSpace(outputVideo))
//{
// dict["outputVideo"] = outputVideo;
//}
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00: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-19 00:10:10 +00:00
2016-11-01 03:07:45 +00:00
//dict["id"] = AppHost.SystemId;
//dict["type"] = state.VideoRequest == null ? "Audio" : "Video";
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00:00
//var audioStream = state.AudioStream;
//if (audioStream != null && !string.IsNullOrWhiteSpace(audioStream.Codec))
//{
// dict["inputAudio"] = audioStream.Codec;
//}
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00:00
//var videoStream = state.VideoStream;
//if (videoStream != null && !string.IsNullOrWhiteSpace(videoStream.Codec))
//{
// dict["inputVideo"] = videoStream.Codec;
//}
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00: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-19 00:10:10 +00:00
2016-11-01 03:07:45 +00:00
//if (state.SupportedAudioCodecs.Count > 0)
//{
// dict["supportedAudioCodecs"] = string.Join(",", state.SupportedAudioCodecs.ToArray());
//}
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00:00
//var auth = AuthorizationContext.GetAuthorizationInfo(Request);
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00: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-19 00:10:10 +00:00
2016-11-01 03:07:45 +00: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-19 00:10:10 +00:00
2016-11-01 03:07:45 +00: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-19 00:10:10 +00:00
2016-11-01 03:07:45 +00:00
//ServerConfigurationManager.SaveConfiguration();
2016-08-19 00:10:10 +00:00
2016-11-01 03:07:45 +00: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-19 00:10:10 +00:00
}
2014-03-25 05:25:03 +00: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-23 02:47:46 +00:00
var profile = state.DeviceProfile;
2014-03-25 05:25:03 +00: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-02 01:26:51 +00: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 20:43:22 +00:00
if (state.RunTimeTicks.HasValue && !isStaticallyStreamed && profile != null)
2014-04-01 22:23:07 +00:00
{
2014-04-18 05:03:01 +00:00
AddTimeSeekResponseHeaders(state, responseHeaders);
2014-04-01 22:23:07 +00:00
}
2014-03-25 05:25:03 +00:00
2014-05-03 20:50:28 +00:00
if (profile == null)
{
profile = DlnaManager.GetDefaultProfile();
}
2014-10-20 03:04:45 +00:00
var audioCodec = state.ActualOutputAudioCodec;
if (state.VideoRequest == null)
2014-03-25 05:25:03 +00:00
{
2014-04-23 02:47:46 +00:00
responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
.BuildAudioHeader(
state.OutputContainer,
audioCodec,
state.OutputAudioBitrate,
state.OutputAudioSampleRate,
2014-04-23 02:47:46 +00:00
state.OutputAudioChannels,
isStaticallyStreamed,
state.RunTimeTicks,
state.TranscodeSeekInfo
);
2014-03-25 05:25:03 +00:00
}
2014-04-23 02:47:46 +00:00
else
2014-03-25 05:25:03 +00:00
{
2014-10-20 03:04:45 +00:00
var videoCodec = state.ActualOutputVideoCodec;
2014-04-23 02:47:46 +00:00
responseHeaders["contentFeatures.dlna.org"] = new ContentFeatureBuilder(profile)
.BuildVideoHeader(
state.OutputContainer,
videoCodec,
audioCodec,
state.OutputWidth,
state.OutputHeight,
2014-04-24 05:08:10 +00:00
state.TargetVideoBitDepth,
state.OutputVideoBitrate,
state.TargetTimestamp,
2014-04-23 02:47:46 +00:00
isStaticallyStreamed,
state.RunTimeTicks,
2014-04-24 05:08:10 +00:00
state.TargetVideoProfile,
state.TargetVideoLevel,
state.TargetFramerate,
state.TargetPacketLength,
2014-06-22 16:25:47 +00:00
state.TranscodeSeekInfo,
2014-09-09 01:15:31 +00:00
state.IsTargetAnamorphic,
state.TargetRefFrames,
state.TargetVideoStreamCount,
2015-10-19 16:05:03 +00:00
state.TargetAudioStreamCount,
2016-10-03 06:28:45 +00:00
state.TargetVideoCodecTag,
2016-12-14 20:58:55 +00:00
state.IsTargetAVC
2014-07-31 02:09:23 +00:00
).FirstOrDefault() ?? string.Empty;
2014-04-23 02:47:46 +00:00
}
2014-04-23 02:47:46 +00:00
foreach (var item in responseHeaders)
{
Request.Response.AddHeader(item.Key, item.Value);
}
2014-03-25 05:25:03 +00:00
}
2014-04-01 22:23:07 +00: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-27 04:19:05 +00:00
}
}