From 12a1414d73c0671b0b502352b524aac66bf9c4c6 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 30 Mar 2016 15:43:37 -0400 Subject: remove unneeded wait for exit --- MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs | 3 --- 1 file changed, 3 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 69cc8ebf7e..442f151dd0 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -175,9 +175,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV //process.Kill(); _process.StandardInput.WriteLine("q"); - - // Need to wait because killing is asynchronous - _process.WaitForExit(5000); } catch (Exception ex) { -- cgit v1.2.3 From e13fcb3cd42b67374621d7e02961e4bd335a235f Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 31 Mar 2016 15:22:07 -0400 Subject: update sat/ip --- .../EntryPoints/ExternalPortForwarding.cs | 18 ++- .../LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs | 170 +++++++++------------ .../MediaBrowser.Server.Implementations.csproj | 1 + 3 files changed, 83 insertions(+), 106 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs b/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs index c0c6264387..a7e5396eb9 100644 --- a/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs +++ b/MediaBrowser.Server.Implementations/EntryPoints/ExternalPortForwarding.cs @@ -31,20 +31,26 @@ namespace MediaBrowser.Server.Implementations.EntryPoints _appHost = appHost; _config = config; _ssdp = ssdp; + + _config.ConfigurationUpdated += _config_ConfigurationUpdated; } - public void Run() + private void _config_ConfigurationUpdated(object sender, EventArgs e) { - //NatUtility.Logger = new LogWriter(_logger); + } - if (_config.Configuration.EnableUPnP) - { - Discover(); - } + public void Run() + { + Discover(); } private async void Discover() { + if (!_config.Configuration.EnableUPnP) + { + return; + } + var discoverer = new NatDiscoverer(); var cancellationTokenSource = new CancellationTokenSource(10000); diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs index da1894bb74..413ce45498 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs @@ -15,6 +15,7 @@ using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Serialization; using MediaBrowser.Model.Extensions; +using System.Xml.Linq; namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp { @@ -171,58 +172,87 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp public async Task GetInfo(string url, CancellationToken cancellationToken) { + Uri locationUri = new Uri(url); + string devicetype = ""; + string friendlyname = ""; + string uniquedevicename = ""; + string manufacturer = ""; + string manufacturerurl = ""; + string modelname = ""; + string modeldescription = ""; + string modelnumber = ""; + string modelurl = ""; + string serialnumber = ""; + string presentationurl = ""; + string capabilities = ""; + string m3u = ""; + var document = XDocument.Load(locationUri.AbsoluteUri); + var xnm = new XmlNamespaceManager(new NameTable()); + XNamespace n1 = "urn:ses-com:satip"; + XNamespace n0 = "urn:schemas-upnp-org:device-1-0"; + xnm.AddNamespace("root", n0.NamespaceName); + xnm.AddNamespace("satip:", n1.NamespaceName); + if (document.Root != null) + { + var deviceElement = document.Root.Element(n0 + "device"); + if (deviceElement != null) + { + var devicetypeElement = deviceElement.Element(n0 + "deviceType"); + if (devicetypeElement != null) + devicetype = devicetypeElement.Value; + var friendlynameElement = deviceElement.Element(n0 + "friendlyName"); + if (friendlynameElement != null) + friendlyname = friendlynameElement.Value; + var manufactureElement = deviceElement.Element(n0 + "manufacturer"); + if (manufactureElement != null) + manufacturer = manufactureElement.Value; + var manufactureurlElement = deviceElement.Element(n0 + "manufacturerURL"); + if (manufactureurlElement != null) + manufacturerurl = manufactureurlElement.Value; + var modeldescriptionElement = deviceElement.Element(n0 + "modelDescription"); + if (modeldescriptionElement != null) + modeldescription = modeldescriptionElement.Value; + var modelnameElement = deviceElement.Element(n0 + "modelName"); + if (modelnameElement != null) + modelname = modelnameElement.Value; + var modelnumberElement = deviceElement.Element(n0 + "modelNumber"); + if (modelnumberElement != null) + modelnumber = modelnumberElement.Value; + var modelurlElement = deviceElement.Element(n0 + "modelURL"); + if (modelurlElement != null) + modelurl = modelurlElement.Value; + var serialnumberElement = deviceElement.Element(n0 + "serialNumber"); + if (serialnumberElement != null) + serialnumber = serialnumberElement.Value; + var uniquedevicenameElement = deviceElement.Element(n0 + "UDN"); + if (uniquedevicenameElement != null) uniquedevicename = uniquedevicenameElement.Value; + var presentationUrlElement = deviceElement.Element(n0 + "presentationURL"); + if (presentationUrlElement != null) presentationurl = presentationUrlElement.Value; + var capabilitiesElement = deviceElement.Element(n1 + "X_SATIPCAP"); + if (capabilitiesElement != null) capabilities = capabilitiesElement.Value; + var m3uElement = deviceElement.Element(n1 + "X_SATIPM3U"); + if (m3uElement != null) m3u = m3uElement.Value; + } + } + + var result = new SatIpTunerHostInfo { Url = url, + Id = uniquedevicename, IsEnabled = true, Type = SatIpHost.DeviceType, Tuners = 1, - TunersAvailable = 1 + TunersAvailable = 1, + M3UUrl = m3u }; - using (var stream = await _httpClient.Get(url, cancellationToken).ConfigureAwait(false)) - { - using (var streamReader = new StreamReader(stream)) - { - // Use XmlReader for best performance - using (var reader = XmlReader.Create(streamReader)) - { - reader.MoveToContent(); - - // Loop through each element - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.Element) - { - switch (reader.Name) - { - case "device": - using (var subtree = reader.ReadSubtree()) - { - FillFromDeviceNode(result, subtree); - } - break; - default: - reader.Skip(); - break; - } - } - } - } - } - } - - if (string.IsNullOrWhiteSpace(result.DeviceId)) + result.FriendlyName = friendlyname; + if (string.IsNullOrWhiteSpace(result.Id)) { throw new NotImplementedException(); } - // Device hasn't implemented an m3u list - if (string.IsNullOrWhiteSpace(result.M3UUrl)) - { - result.IsEnabled = false; - } - else if (!result.M3UUrl.StartsWith("http", StringComparison.OrdinalIgnoreCase)) { var fullM3uUrl = url.Substring(0, url.LastIndexOf('/')); @@ -233,66 +263,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp return result; } - - private void FillFromDeviceNode(SatIpTunerHostInfo info, XmlReader reader) - { - reader.MoveToContent(); - - while (reader.Read()) - { - if (reader.NodeType == XmlNodeType.Element) - { - switch (reader.LocalName) - { - case "UDN": - { - info.DeviceId = reader.ReadElementContentAsString(); - break; - } - - case "friendlyName": - { - info.FriendlyName = reader.ReadElementContentAsString(); - break; - } - - case "satip:X_SATIPCAP": - case "X_SATIPCAP": - { - // DVBS2-2 - var value = reader.ReadElementContentAsString() ?? string.Empty; - var parts = value.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries); - if (parts.Length == 2) - { - int intValue; - if (int.TryParse(parts[1], NumberStyles.Any, CultureInfo.InvariantCulture, out intValue)) - { - info.TunersAvailable = intValue; - } - - if (int.TryParse(parts[0].Substring(parts[0].Length - 1), NumberStyles.Any, CultureInfo.InvariantCulture, out intValue)) - { - info.Tuners = intValue; - } - } - break; - } - - case "satip:X_SATIPM3U": - case "X_SATIPM3U": - { - // /channellist.lua?select=m3u - info.M3UUrl = reader.ReadElementContentAsString(); - break; - } - - default: - reader.Skip(); - break; - } - } - } - } } public class SatIpTunerHostInfo : TunerHostInfo diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index 84c1cae544..14d2755055 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -103,6 +103,7 @@ ..\ThirdParty\ServiceStack.Text\ServiceStack.Text.dll + ..\ThirdParty\UniversalDetector\UniversalDetector.dll -- cgit v1.2.3 From 54de1b744b996683fe9209c8ebbd2316290e9eb0 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 31 Mar 2016 15:32:26 -0400 Subject: stub out sat channel scan --- MediaBrowser.Api/LiveTv/LiveTvService.cs | 16 +++++++++++++++- MediaBrowser.Controller/LiveTv/ILiveTvManager.cs | 2 ++ .../LiveTv/LiveTvManager.cs | 7 +++++++ .../LiveTv/TunerHosts/SatIp/ChannelScan.cs | 20 ++++++++++++++++++++ .../MediaBrowser.Server.Implementations.csproj | 1 + 5 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs index 5b7bc78a8b..ebcf8fbeac 100644 --- a/MediaBrowser.Api/LiveTv/LiveTvService.cs +++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs @@ -482,7 +482,14 @@ namespace MediaBrowser.Api.LiveTv [Authenticated(AllowBeforeStartupWizard = true)] public class GetSatIniMappings : IReturn> { - + + } + + [Route("/LiveTv/TunerHosts/Satip/ChannelScan", "GET", Summary = "Scans for available channels")] + [Authenticated(AllowBeforeStartupWizard = true)] + public class GetSatChannnelScanResult : TunerHostInfo + { + } public class LiveTvService : BaseApiService @@ -504,6 +511,13 @@ namespace MediaBrowser.Api.LiveTv _dtoService = dtoService; } + public async Task Get(GetSatChannnelScanResult request) + { + var result = await _liveTvManager.GetSatChannelScanResult(request, CancellationToken.None).ConfigureAwait(false); + + return ToOptimizedResult(result); + } + public async Task Get(GetLiveTvRegistrationInfo request) { var result = await _liveTvManager.GetRegistrationInfo(request.ChannelId, request.ProgramId, request.Feature).ConfigureAwait(false); diff --git a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs index 56b7a307a1..a4bd32fffe 100644 --- a/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs +++ b/MediaBrowser.Controller/LiveTv/ILiveTvManager.cs @@ -383,5 +383,7 @@ namespace MediaBrowser.Controller.LiveTv /// /// List<NameValuePair>. List GetSatIniMappings(); + + Task> GetSatChannelScanResult(TunerHostInfo info, CancellationToken cancellationToken); } } diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index 3849f44ab7..87c2e8394b 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -2480,5 +2480,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv } } } + + public async Task> GetSatChannelScanResult(TunerHostInfo info, CancellationToken cancellationToken) + { + var result = await new TunerHosts.SatIp.ChannelScan().Scan(info, cancellationToken).ConfigureAwait(false); + + return result.Select(i => new ChannelInfo()).ToList(); + } } } \ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs new file mode 100644 index 0000000000..2277f8f630 --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs @@ -0,0 +1,20 @@ +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.LiveTv; + +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp +{ + public class ChannelScan + { + public async Task> Scan(TunerHostInfo info, CancellationToken cancellationToken) + { + return new List(); + } + } + + public class SatChannel + { + // TODO: Add properties + } +} diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index 14d2755055..b5ec4649e2 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -247,6 +247,7 @@ + -- cgit v1.2.3 From edd9ad6d63aaa320e97cd48b75ac544ed7c8b361 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 31 Mar 2016 16:01:27 -0400 Subject: add rtsp classes --- .../LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs | 88 ++++++++ .../LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs | 141 ++++++++++++ .../LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs | 150 ++++++++++++ .../LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs | 251 +++++++++++++++++++++ .../LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs | 1 - .../MediaBrowser.Server.Implementations.csproj | 4 + 6 files changed, 634 insertions(+), 1 deletion(-) create mode 100644 MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs create mode 100644 MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs create mode 100644 MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs create mode 100644 MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs new file mode 100644 index 0000000000..fae7c4bfc7 --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs @@ -0,0 +1,88 @@ +/* + Copyright (C) <2007-2016> + + SatIp.RtspSample is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + SatIp.RtspSample is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with SatIp.RtspSample. If not, see . +*/ + +using System.Collections.Generic; + +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +{ + /// + /// Standard RTSP request methods. + /// + public sealed class RtspMethod + { + public override int GetHashCode() + { + return (_name != null ? _name.GetHashCode() : 0); + } + + private readonly string _name; + private static readonly IDictionary _values = new Dictionary(); + + public static readonly RtspMethod Describe = new RtspMethod("DESCRIBE"); + public static readonly RtspMethod Announce = new RtspMethod("ANNOUNCE"); + public static readonly RtspMethod GetParameter = new RtspMethod("GET_PARAMETER"); + public static readonly RtspMethod Options = new RtspMethod("OPTIONS"); + public static readonly RtspMethod Pause = new RtspMethod("PAUSE"); + public static readonly RtspMethod Play = new RtspMethod("PLAY"); + public static readonly RtspMethod Record = new RtspMethod("RECORD"); + public static readonly RtspMethod Redirect = new RtspMethod("REDIRECT"); + public static readonly RtspMethod Setup = new RtspMethod("SETUP"); + public static readonly RtspMethod SetParameter = new RtspMethod("SET_PARAMETER"); + public static readonly RtspMethod Teardown = new RtspMethod("TEARDOWN"); + + private RtspMethod(string name) + { + _name = name; + _values.Add(name, this); + } + + public override string ToString() + { + return _name; + } + + public override bool Equals(object obj) + { + var method = obj as RtspMethod; + if (method != null && this == method) + { + return true; + } + return false; + } + + public static ICollection Values + { + get { return _values.Values; } + } + + public static explicit operator RtspMethod(string name) + { + RtspMethod value; + if (!_values.TryGetValue(name, out value)) + { + return null; + } + return value; + } + + public static implicit operator string(RtspMethod method) + { + return method._name; + } + } +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs new file mode 100644 index 0000000000..d8462b2238 --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs @@ -0,0 +1,141 @@ +/* + Copyright (C) <2007-2016> + + SatIp.RtspSample is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + SatIp.RtspSample is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with SatIp.RtspSample. If not, see . +*/ + +using System.Collections.Generic; +using System.Text; + + +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +{ + /// + /// A simple class that can be used to serialise RTSP requests. + /// + public class RtspRequest + { + private readonly RtspMethod _method; + private readonly string _uri; + private readonly int _majorVersion; + private readonly int _minorVersion; + private IDictionary _headers = new Dictionary(); + private string _body = string.Empty; + + /// + /// Initialise a new instance of the class. + /// + /// The request method. + /// The request URI + /// The major version number. + /// The minor version number. + public RtspRequest(RtspMethod method, string uri, int majorVersion, int minorVersion) + { + _method = method; + _uri = uri; + _majorVersion = majorVersion; + _minorVersion = minorVersion; + } + + /// + /// Get the request method. + /// + public RtspMethod Method + { + get + { + return _method; + } + } + + /// + /// Get the request URI. + /// + public string Uri + { + get + { + return _uri; + } + } + + /// + /// Get the request major version number. + /// + public int MajorVersion + { + get + { + return _majorVersion; + } + } + + /// + /// Get the request minor version number. + /// + public int MinorVersion + { + get + { + return _minorVersion; + } + } + + /// + /// Get or set the request headers. + /// + public IDictionary Headers + { + get + { + return _headers; + } + set + { + _headers = value; + } + } + + /// + /// Get or set the request body. + /// + public string Body + { + get + { + return _body; + } + set + { + _body = value; + } + } + + /// + /// Serialise this request. + /// + /// raw request bytes + public byte[] Serialise() + { + var request = new StringBuilder(); + request.AppendFormat("{0} {1} RTSP/{2}.{3}\r\n", _method, _uri, _majorVersion, _minorVersion); + foreach (var header in _headers) + { + request.AppendFormat("{0}: {1}\r\n", header.Key, header.Value); + } + request.AppendFormat("\r\n{0}", _body); + return Encoding.UTF8.GetBytes(request.ToString()); + } + } +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs new file mode 100644 index 0000000000..0bf80012d2 --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs @@ -0,0 +1,150 @@ +/* + Copyright (C) <2007-2016> + + SatIp.RtspSample is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + SatIp.RtspSample is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with SatIp.RtspSample. If not, see . +*/ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + + +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +{ + /// + /// A simple class that can be used to deserialise RTSP responses. + /// + public class RtspResponse + { + private static readonly Regex RegexStatusLine = new Regex(@"RTSP/(\d+)\.(\d+)\s+(\d+)\s+([^.]+?)\r\n(.*)", RegexOptions.Singleline); + + private int _majorVersion = 1; + private int _minorVersion; + private RtspStatusCode _statusCode; + private string _reasonPhrase; + private IDictionary _headers; + private string _body; + + /// + /// Initialise a new instance of the class. + /// + private RtspResponse() + { + } + + /// + /// Get the response major version number. + /// + public int MajorVersion + { + get + { + return _majorVersion; + } + } + + /// + /// Get the response minor version number. + /// + public int MinorVersion + { + get + { + return _minorVersion; + } + } + + /// + /// Get the response status code. + /// + public RtspStatusCode StatusCode + { + get + { + return _statusCode; + } + } + + /// + /// Get the response reason phrase. + /// + public string ReasonPhrase + { + get + { + return _reasonPhrase; + } + } + + /// + /// Get the response headers. + /// + public IDictionary Headers + { + get + { + return _headers; + } + } + + /// + /// Get the response body. + /// + public string Body + { + get + { + return _body; + } + set + { + _body = value; + } + } + + /// + /// Deserialise/parse an RTSP response. + /// + /// The raw response bytes. + /// The number of valid bytes in the response. + /// a response object + public static RtspResponse Deserialise(byte[] responseBytes, int responseByteCount) + { + var response = new RtspResponse(); + var responseString = Encoding.UTF8.GetString(responseBytes, 0, responseByteCount); + + var m = RegexStatusLine.Match(responseString); + if (m.Success) + { + response._majorVersion = int.Parse(m.Groups[1].Captures[0].Value); + response._minorVersion = int.Parse(m.Groups[2].Captures[0].Value); + response._statusCode = (RtspStatusCode)int.Parse(m.Groups[3].Captures[0].Value); + response._reasonPhrase = m.Groups[4].Captures[0].Value; + responseString = m.Groups[5].Captures[0].Value; + } + + var sections = responseString.Split(new[] { "\r\n\r\n" }, StringSplitOptions.None); + response._body = sections[1]; + var headers = sections[0].Split(new[] { "\r\n" }, StringSplitOptions.None); + response._headers = new Dictionary(); + foreach (var headerInfo in headers.Select(header => header.Split(':'))) + { + response._headers.Add(headerInfo[0], headerInfo[1].Trim()); + } + return response; + } + } +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs new file mode 100644 index 0000000000..8786314edb --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs @@ -0,0 +1,251 @@ +/* + Copyright (C) <2007-2016> + + SatIp.RtspSample is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + SatIp.RtspSample is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with SatIp.RtspSample. If not, see . +*/ + +using System.ComponentModel; + +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +{ + /// + /// Standard RTSP status codes. + /// + public enum RtspStatusCode + { + /// + /// 100 continue + /// + Continue = 100, + + /// + /// 200 OK + /// + [Description("Okay")] + Ok = 200, + /// + /// 201 created + /// + Created = 201, + + /// + /// 250 low on storage space + /// + [Description("Low On Storage Space")] + LowOnStorageSpace = 250, + + /// + /// 300 multiple choices + /// + [Description("Multiple Choices")] + MultipleChoices = 300, + /// + /// 301 moved permanently + /// + [Description("Moved Permanently")] + MovedPermanently = 301, + /// + /// 302 moved temporarily + /// + [Description("Moved Temporarily")] + MovedTemporarily = 302, + /// + /// 303 see other + /// + [Description("See Other")] + SeeOther = 303, + /// + /// 304 not modified + /// + [Description("Not Modified")] + NotModified = 304, + /// + /// 305 use proxy + /// + [Description("Use Proxy")] + UseProxy = 305, + + /// + /// 400 bad request + /// + [Description("Bad Request")] + BadRequest = 400, + /// + /// 401 unauthorised + /// + Unauthorised = 401, + /// + /// 402 payment required + /// + [Description("Payment Required")] + PaymentRequired = 402, + /// + /// 403 forbidden + /// + Forbidden = 403, + /// + /// 404 not found + /// + [Description("Not Found")] + NotFound = 404, + /// + /// 405 method not allowed + /// + [Description("Method Not Allowed")] + MethodNotAllowed = 405, + /// + /// 406 not acceptable + /// + [Description("Not Acceptable")] + NotAcceptable = 406, + /// + /// 407 proxy authentication required + /// + [Description("Proxy Authentication Required")] + ProxyAuthenticationRequred = 407, + /// + /// 408 request time-out + /// + [Description("Request Time-Out")] + RequestTimeOut = 408, + + /// + /// 410 gone + /// + Gone = 410, + /// + /// 411 length required + /// + [Description("Length Required")] + LengthRequired = 411, + /// + /// 412 precondition failed + /// + [Description("Precondition Failed")] + PreconditionFailed = 412, + /// + /// 413 request entity too large + /// + [Description("Request Entity Too Large")] + RequestEntityTooLarge = 413, + /// + /// 414 request URI too large + /// + [Description("Request URI Too Large")] + RequestUriTooLarge = 414, + /// + /// 415 unsupported media type + /// + [Description("Unsupported Media Type")] + UnsupportedMediaType = 415, + + /// + /// 451 parameter not understood + /// + [Description("Parameter Not Understood")] + ParameterNotUnderstood = 451, + /// + /// 452 conference not found + /// + [Description("Conference Not Found")] + ConferenceNotFound = 452, + /// + /// 453 not enough bandwidth + /// + [Description("Not Enough Bandwidth")] + NotEnoughBandwidth = 453, + /// + /// 454 session not found + /// + [Description("Session Not Found")] + SessionNotFound = 454, + /// + /// 455 method not valid in this state + /// + [Description("Method Not Valid In This State")] + MethodNotValidInThisState = 455, + /// + /// 456 header field not valid for this resource + /// + [Description("Header Field Not Valid For This Resource")] + HeaderFieldNotValidForThisResource = 456, + /// + /// 457 invalid range + /// + [Description("Invalid Range")] + InvalidRange = 457, + /// + /// 458 parameter is read-only + /// + [Description("Parameter Is Read-Only")] + ParameterIsReadOnly = 458, + /// + /// 459 aggregate operation not allowed + /// + [Description("Aggregate Operation Not Allowed")] + AggregateOperationNotAllowed = 459, + /// + /// 460 only aggregate operation allowed + /// + [Description("Only Aggregate Operation Allowed")] + OnlyAggregateOperationAllowed = 460, + /// + /// 461 unsupported transport + /// + [Description("Unsupported Transport")] + UnsupportedTransport = 461, + /// + /// 462 destination unreachable + /// + [Description("Destination Unreachable")] + DestinationUnreachable = 462, + + /// + /// 500 internal server error + /// + [Description("Internal Server Error")] + InternalServerError = 500, + /// + /// 501 not implemented + /// + [Description("Not Implemented")] + NotImplemented = 501, + /// + /// 502 bad gateway + /// + [Description("Bad Gateway")] + BadGateway = 502, + /// + /// 503 service unavailable + /// + [Description("Service Unavailable")] + ServiceUnavailable = 503, + /// + /// 504 gateway time-out + /// + [Description("Gateway Time-Out")] + GatewayTimeOut = 504, + /// + /// 505 RTSP version not supported + /// + [Description("RTSP Version Not Supported")] + RtspVersionNotSupported = 505, + + /// + /// 551 option not supported + /// + [Description("Option Not Supported")] + OptionNotSupported = 551 + } +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs index 413ce45498..d0a55966f3 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs @@ -235,7 +235,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp } } - var result = new SatIpTunerHostInfo { Url = url, diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index b5ec4649e2..02f7596e00 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -248,6 +248,10 @@ + + + + -- cgit v1.2.3 From fa841e86104cb05f59b4caec686b69dba9284084 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 31 Mar 2016 16:04:07 -0400 Subject: add RtspSession --- .../LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs | 681 +++++++++++++++++++++ .../MediaBrowser.Server.Implementations.csproj | 1 + 2 files changed, 682 insertions(+) create mode 100644 MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs new file mode 100644 index 0000000000..e76fb71757 --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs @@ -0,0 +1,681 @@ +/* + Copyright (C) <2007-2016> + + SatIp.RtspSample is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + SatIp.RtspSample is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with SatIp.RtspSample. If not, see . +*/ + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Linq; +using System.Net; +using System.Net.NetworkInformation; +using System.Net.Sockets; +using System.Text.RegularExpressions; +using MediaBrowser.Model.Logging; + +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +{ + public class RtspSession : IDisposable + { + #region Private Fields + private static readonly Regex RegexRtspSessionHeader = new Regex(@"\s*([^\s;]+)(;timeout=(\d+))?"); + private const int DefaultRtspSessionTimeout = 30; // unit = s + private static readonly Regex RegexDescribeResponseSignalInfo = new Regex(@";tuner=\d+,(\d+),(\d+),(\d+),", RegexOptions.Singleline | RegexOptions.IgnoreCase); + private string _address; + private string _rtspSessionId; + + public string RtspSessionId + { + get { return _rtspSessionId; } + set { _rtspSessionId = value; } + } + private int _rtspSessionTimeToLive = 0; + private string _rtspStreamId; + private int _clientRtpPort; + private int _clientRtcpPort; + private int _serverRtpPort; + private int _serverRtcpPort; + private int _rtpPort; + private int _rtcpPort; + private string _rtspStreamUrl; + private string _destination; + private string _source; + private string _transport; + private int _signalLevel; + private int _signalQuality; + private Socket _rtspSocket; + private int _rtspSequenceNum = 1; + private bool _disposed = false; + private ILogger _logger; + #endregion + + #region Constructor + + public RtspSession(string address, ILogger logger) + { + _address = address; + _logger = logger; + } + ~RtspSession() + { + Dispose(false); + } + #endregion + + #region Properties + + #region Rtsp + + public string RtspStreamId + { + get { return _rtspStreamId; } + set { if (_rtspStreamId != value) { _rtspStreamId = value; OnPropertyChanged("RtspStreamId"); } } + } + public string RtspStreamUrl + { + get { return _rtspStreamUrl; } + set { if (_rtspStreamUrl != value) { _rtspStreamUrl = value; OnPropertyChanged("RtspStreamUrl"); } } + } + + public int RtspSessionTimeToLive + { + get + { + if (_rtspSessionTimeToLive == 0) + _rtspSessionTimeToLive = DefaultRtspSessionTimeout; + return _rtspSessionTimeToLive * 1000 - 20; + } + set { if (_rtspSessionTimeToLive != value) { _rtspSessionTimeToLive = value; OnPropertyChanged("RtspSessionTimeToLive"); } } + } + + #endregion + + #region Rtp Rtcp + + /// + /// The LocalEndPoint Address + /// + public string Destination + { + get + { + if (string.IsNullOrEmpty(_destination)) + { + var result = ""; + var host = Dns.GetHostName(); + var hostentry = Dns.GetHostEntry(host); + foreach (var ip in hostentry.AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork)) + { + result = ip.ToString(); + } + + _destination = result; + } + return _destination; + } + set + { + if (_destination != value) + { + _destination = value; + OnPropertyChanged("Destination"); + } + } + } + + /// + /// The RemoteEndPoint Address + /// + public string Source + { + get { return _source; } + set + { + if (_source != value) + { + _source = value; + OnPropertyChanged("Source"); + } + } + } + + /// + /// The Media Data Delivery RemoteEndPoint Port if we use Unicast + /// + public int ServerRtpPort + { + get + { + return _serverRtpPort; + } + set { if (_serverRtpPort != value) { _serverRtpPort = value; OnPropertyChanged("ServerRtpPort"); } } + } + + /// + /// The Media Metadata Delivery RemoteEndPoint Port if we use Unicast + /// + public int ServerRtcpPort + { + get { return _serverRtcpPort; } + set { if (_serverRtcpPort != value) { _serverRtcpPort = value; OnPropertyChanged("ServerRtcpPort"); } } + } + + /// + /// The Media Data Delivery LocalEndPoint Port if we use Unicast + /// + public int ClientRtpPort + { + get { return _clientRtpPort; } + set { if (_clientRtpPort != value) { _clientRtpPort = value; OnPropertyChanged("ClientRtpPort"); } } + } + + /// + /// The Media Metadata Delivery LocalEndPoint Port if we use Unicast + /// + public int ClientRtcpPort + { + get { return _clientRtcpPort; } + set { if (_clientRtcpPort != value) { _clientRtcpPort = value; OnPropertyChanged("ClientRtcpPort"); } } + } + + /// + /// The Media Data Delivery RemoteEndPoint Port if we use Multicast + /// + public int RtpPort + { + get { return _rtpPort; } + set { if (_rtpPort != value) { _rtpPort = value; OnPropertyChanged("RtpPort"); } } + } + + /// + /// The Media Meta Delivery RemoteEndPoint Port if we use Multicast + /// + public int RtcpPort + { + get { return _rtcpPort; } + set { if (_rtcpPort != value) { _rtcpPort = value; OnPropertyChanged("RtcpPort"); } } + } + + #endregion + + public string Transport + { + get + { + if (string.IsNullOrEmpty(_transport)) + { + _transport = "unicast"; + } + return _transport; + } + set + { + if (_transport != value) + { + _transport = value; + OnPropertyChanged("Transport"); + } + } + } + public int SignalLevel + { + get { return _signalLevel; } + set { if (_signalLevel != value) { _signalLevel = value; OnPropertyChanged("SignalLevel"); } } + } + public int SignalQuality + { + get { return _signalQuality; } + set { if (_signalQuality != value) { _signalQuality = value; OnPropertyChanged("SignalQuality"); } } + } + + #endregion + + #region Private Methods + + private void ProcessSessionHeader(string sessionHeader, string response) + { + if (!string.IsNullOrEmpty(sessionHeader)) + { + var m = RegexRtspSessionHeader.Match(sessionHeader); + if (!m.Success) + { + _logger.Error("Failed to tune, RTSP {0} response session header {1} format not recognised", response, sessionHeader); + } + _rtspSessionId = m.Groups[1].Captures[0].Value; + _rtspSessionTimeToLive = m.Groups[3].Captures.Count == 1 ? int.Parse(m.Groups[3].Captures[0].Value) : DefaultRtspSessionTimeout; + } + } + private void ProcessTransportHeader(string transportHeader) + { + if (!string.IsNullOrEmpty(transportHeader)) + { + var transports = transportHeader.Split(','); + foreach (var transport in transports) + { + if (transport.Trim().StartsWith("RTP/AVP")) + { + var sections = transport.Split(';'); + foreach (var section in sections) + { + var parts = section.Split('='); + if (parts[0].Equals("server_port")) + { + var ports = parts[1].Split('-'); + _serverRtpPort = int.Parse(ports[0]); + _serverRtcpPort = int.Parse(ports[1]); + } + else if (parts[0].Equals("destination")) + { + _destination = parts[1]; + } + else if (parts[0].Equals("port")) + { + var ports = parts[1].Split('-'); + _rtpPort = int.Parse(ports[0]); + _rtcpPort = int.Parse(ports[1]); + } + else if (parts[0].Equals("ttl")) + { + _rtspSessionTimeToLive = int.Parse(parts[1]); + } + else if (parts[0].Equals("source")) + { + _source = parts[1]; + } + else if (parts[0].Equals("client_port")) + { + var ports = parts[1].Split('-'); + var rtp = int.Parse(ports[0]); + var rtcp = int.Parse(ports[1]); + //if (!rtp.Equals(_rtpPort)) + //{ + // Logger.Error("SAT>IP base: server specified RTP client port {0} instead of {1}", rtp, _rtpPort); + //} + //if (!rtcp.Equals(_rtcpPort)) + //{ + // Logger.Error("SAT>IP base: server specified RTCP client port {0} instead of {1}", rtcp, _rtcpPort); + //} + _rtpPort = rtp; + _rtcpPort = rtcp; + } + } + } + } + } + } + private void Connect() + { + _rtspSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + var ip = IPAddress.Parse(_address); + var rtspEndpoint = new IPEndPoint(ip, 554); + _rtspSocket.Connect(rtspEndpoint); + } + private void Disconnect() + { + if (_rtspSocket != null && _rtspSocket.Connected) + { + _rtspSocket.Shutdown(SocketShutdown.Both); + _rtspSocket.Close(); + } + } + private void SendRequest(RtspRequest request) + { + if (_rtspSocket == null) + { + Connect(); + } + try + { + request.Headers.Add("CSeq", _rtspSequenceNum.ToString()); + _rtspSequenceNum++; + byte[] requestBytes = request.Serialise(); + if (_rtspSocket != null) + { + var requestBytesCount = _rtspSocket.Send(requestBytes, requestBytes.Length, SocketFlags.None); + if (requestBytesCount < 1) + { + + } + } + } + catch (Exception e) + { + _logger.Error(e.Message); + } + } + private void ReceiveResponse(out RtspResponse response) + { + response = null; + var responseBytesCount = 0; + byte[] responseBytes = new byte[1024]; + try + { + responseBytesCount = _rtspSocket.Receive(responseBytes, responseBytes.Length, SocketFlags.None); + response = RtspResponse.Deserialise(responseBytes, responseBytesCount); + string contentLengthString; + int contentLength = 0; + if (response.Headers.TryGetValue("Content-Length", out contentLengthString)) + { + contentLength = int.Parse(contentLengthString); + if ((string.IsNullOrEmpty(response.Body) && contentLength > 0) || response.Body.Length < contentLength) + { + if (response.Body == null) + { + response.Body = string.Empty; + } + while (responseBytesCount > 0 && response.Body.Length < contentLength) + { + responseBytesCount = _rtspSocket.Receive(responseBytes, responseBytes.Length, SocketFlags.None); + response.Body += System.Text.Encoding.UTF8.GetString(responseBytes, 0, responseBytesCount); + } + } + } + } + catch (SocketException) + { + } + } + + #endregion + + #region Public Methods + + public RtspStatusCode Setup(string query, string transporttype) + { + + RtspRequest request; + RtspResponse response; + //_rtspClient = new RtspClient(_rtspDevice.ServerAddress); + if ((_rtspSocket == null)) + { + Connect(); + } + if (string.IsNullOrEmpty(_rtspSessionId)) + { + request = new RtspRequest(RtspMethod.Setup, string.Format("rtsp://{0}:{1}/?{2}", _address, 554, query), 1, 0); + switch (transporttype) + { + case "multicast": + request.Headers.Add("Transport", string.Format("RTP/AVP;multicast")); + break; + case "unicast": + var activeTcpConnections = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections(); + var usedPorts = new HashSet(); + foreach (var connection in activeTcpConnections) + { + usedPorts.Add(connection.LocalEndPoint.Port); + } + for (var port = 40000; port <= 65534; port += 2) + { + if (!usedPorts.Contains(port) && !usedPorts.Contains(port + 1)) + { + + _clientRtpPort = port; + _clientRtcpPort = port + 1; + break; + } + } + request.Headers.Add("Transport", string.Format("RTP/AVP;unicast;client_port={0}-{1}", _clientRtpPort, _clientRtcpPort)); + break; + } + } + else + { + request = new RtspRequest(RtspMethod.Setup, string.Format("rtsp://{0}:{1}/?{2}", _address, 554, query), 1, 0); + switch (transporttype) + { + case "multicast": + request.Headers.Add("Transport", string.Format("RTP/AVP;multicast")); + break; + case "unicast": + request.Headers.Add("Transport", string.Format("RTP/AVP;unicast;client_port={0}-{1}", _clientRtpPort, _clientRtcpPort)); + break; + } + + } + SendRequest(request); + ReceiveResponse(out response); + + //if (_rtspClient.SendRequest(request, out response) != RtspStatusCode.Ok) + //{ + // Logger.Error("Failed to tune, non-OK RTSP SETUP status code {0} {1}", response.StatusCode, response.ReasonPhrase); + //} + if (!response.Headers.TryGetValue("com.ses.streamID", out _rtspStreamId)) + { + _logger.Error(string.Format("Failed to tune, not able to locate Stream ID header in RTSP SETUP response")); + } + string sessionHeader; + if (!response.Headers.TryGetValue("Session", out sessionHeader)) + { + _logger.Error(string.Format("Failed to tune, not able to locate Session header in RTSP SETUP response")); + } + ProcessSessionHeader(sessionHeader, "Setup"); + string transportHeader; + if (!response.Headers.TryGetValue("Transport", out transportHeader)) + { + _logger.Error(string.Format("Failed to tune, not able to locate Transport header in RTSP SETUP response")); + } + ProcessTransportHeader(transportHeader); + return response.StatusCode; + } + + public RtspStatusCode Play(string query) + { + if ((_rtspSocket == null)) + { + Connect(); + } + //_rtspClient = new RtspClient(_rtspDevice.ServerAddress); + RtspResponse response; + string data; + if (string.IsNullOrEmpty(query)) + { + data = string.Format("rtsp://{0}:{1}/stream={2}", _address, + 554, _rtspStreamId); + } + else + { + data = string.Format("rtsp://{0}:{1}/stream={2}?{3}", _address, + 554, _rtspStreamId, query); + } + var request = new RtspRequest(RtspMethod.Play, data, 1, 0); + request.Headers.Add("Session", _rtspSessionId); + SendRequest(request); + ReceiveResponse(out response); + //if (_rtspClient.SendRequest(request, out response) != RtspStatusCode.Ok) + //{ + // Logger.Error("Failed to tune, non-OK RTSP SETUP status code {0} {1}", response.StatusCode, response.ReasonPhrase); + //} + //Logger.Info("RtspSession-Play : \r\n {0}", response); + string sessionHeader; + if (!response.Headers.TryGetValue("Session", out sessionHeader)) + { + _logger.Error(string.Format("Failed to tune, not able to locate Session header in RTSP Play response")); + } + ProcessSessionHeader(sessionHeader, "Play"); + string rtpinfoHeader; + if (!response.Headers.TryGetValue("RTP-Info", out rtpinfoHeader)) + { + _logger.Error(string.Format("Failed to tune, not able to locate Rtp-Info header in RTSP Play response")); + } + return response.StatusCode; + } + + public RtspStatusCode Options() + { + if ((_rtspSocket == null)) + { + Connect(); + } + //_rtspClient = new RtspClient(_rtspDevice.ServerAddress); + RtspRequest request; + RtspResponse response; + + + if (string.IsNullOrEmpty(_rtspSessionId)) + { + request = new RtspRequest(RtspMethod.Options, string.Format("rtsp://{0}:{1}/", _address, 554), 1, 0); + } + else + { + request = new RtspRequest(RtspMethod.Options, string.Format("rtsp://{0}:{1}/", _address, 554), 1, 0); + request.Headers.Add("Session", _rtspSessionId); + } + SendRequest(request); + ReceiveResponse(out response); + //if (_rtspClient.SendRequest(request, out response) != RtspStatusCode.Ok) + //{ + // Logger.Error("Failed to tune, non-OK RTSP SETUP status code {0} {1}", response.StatusCode, response.ReasonPhrase); + //} + //Logger.Info("RtspSession-Options : \r\n {0}", response); + string sessionHeader; + if (!response.Headers.TryGetValue("Session", out sessionHeader)) + { + _logger.Error(string.Format("Failed to tune, not able to locate session header in RTSP Options response")); + } + ProcessSessionHeader(sessionHeader, "Options"); + string optionsHeader; + if (!response.Headers.TryGetValue("Public", out optionsHeader)) + { + _logger.Error(string.Format("Failed to tune, not able to Options header in RTSP Options response")); + } + return response.StatusCode; + } + + public RtspStatusCode Describe(out int level, out int quality) + { + if ((_rtspSocket == null)) + { + Connect(); + } + //_rtspClient = new RtspClient(_rtspDevice.ServerAddress); + RtspRequest request; + RtspResponse response; + level = 0; + quality = 0; + + if (string.IsNullOrEmpty(_rtspSessionId)) + { + request = new RtspRequest(RtspMethod.Describe, string.Format("rtsp://{0}:{1}/", _address, 554), 1, 0); + request.Headers.Add("Accept", "application/sdp"); + + } + else + { + request = new RtspRequest(RtspMethod.Describe, string.Format("rtsp://{0}:{1}/stream={2}", _address, 554, _rtspStreamId), 1, 0); + request.Headers.Add("Accept", "application/sdp"); + request.Headers.Add("Session", _rtspSessionId); + } + SendRequest(request); + ReceiveResponse(out response); + //if (_rtspClient.SendRequest(request, out response) != RtspStatusCode.Ok) + //{ + // Logger.Error("Failed to tune, non-OK RTSP Describe status code {0} {1}", response.StatusCode, response.ReasonPhrase); + //} + //Logger.Info("RtspSession-Describe : \r\n {0}", response); + string sessionHeader; + if (!response.Headers.TryGetValue("Session", out sessionHeader)) + { + _logger.Error(string.Format("Failed to tune, not able to locate session header in RTSP Describe response")); + } + ProcessSessionHeader(sessionHeader, "Describe"); + var m = RegexDescribeResponseSignalInfo.Match(response.Body); + if (m.Success) + { + + //isSignalLocked = m.Groups[2].Captures[0].Value.Equals("1"); + level = int.Parse(m.Groups[1].Captures[0].Value) * 100 / 255; // level: 0..255 => 0..100 + quality = int.Parse(m.Groups[3].Captures[0].Value) * 100 / 15; // quality: 0..15 => 0..100 + + } + /* + v=0 + o=- 1378633020884883 1 IN IP4 192.168.2.108 + s=SatIPServer:1 4 + t=0 0 + a=tool:idl4k + m=video 52780 RTP/AVP 33 + c=IN IP4 0.0.0.0 + b=AS:5000 + a=control:stream=4 + a=fmtp:33 ver=1.0;tuner=1,0,0,0,12344,h,dvbs2,,off,,22000,34;pids=0,100,101,102,103,106 + =sendonly + */ + + + return response.StatusCode; + } + + public RtspStatusCode TearDown() + { + if ((_rtspSocket == null)) + { + Connect(); + } + //_rtspClient = new RtspClient(_rtspDevice.ServerAddress); + RtspResponse response; + + var request = new RtspRequest(RtspMethod.Teardown, string.Format("rtsp://{0}:{1}/stream={2}", _address, 554, _rtspStreamId), 1, 0); + request.Headers.Add("Session", _rtspSessionId); + SendRequest(request); + ReceiveResponse(out response); + //if (_rtspClient.SendRequest(request, out response) != RtspStatusCode.Ok) + //{ + // Logger.Error("Failed to tune, non-OK RTSP Teardown status code {0} {1}", response.StatusCode, response.ReasonPhrase); + //} + return response.StatusCode; + } + + #endregion + + #region Public Events + + public event PropertyChangedEventHandler PropertyChanged; + + #endregion + + #region Protected Methods + + protected void OnPropertyChanged(string name) + { + //var handler = PropertyChanged; + //if (handler != null) + //{ + // handler(this, new PropertyChangedEventArgs(name)); + //} + } + + #endregion + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this);//Disconnect(); + } + + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + TearDown(); + Disconnect(); + } + } + _disposed = true; + } + } +} diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index 02f7596e00..ae39d3eb99 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -251,6 +251,7 @@ + -- cgit v1.2.3 From 1381447bda7982aa0fd8aac30fa29fc42dc437e3 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 31 Mar 2016 19:26:13 -0400 Subject: update sat/ip --- .../LiveTv/LiveTvManager.cs | 13 +-- .../LiveTv/TunerHosts/SatIp/ChannelScan.cs | 95 +++++++++++++++++++++- .../LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs | 2 +- .../LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs | 3 +- .../LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs | 3 +- .../LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs | 11 ++- .../LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs | 2 +- .../LiveTv/TunerHosts/SatIp/SatIpHost.cs | 3 +- 8 files changed, 114 insertions(+), 18 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index 87c2e8394b..d40f2a141d 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -2450,7 +2450,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv public List GetSatIniMappings() { - var names = GetType().Assembly.GetManifestResourceNames().Where(i => i.IndexOf("SatIp.ini.satellite", StringComparison.OrdinalIgnoreCase) != -1).ToList(); + var names = GetType().Assembly.GetManifestResourceNames().Where(i => i.IndexOf("SatIp.ini", StringComparison.OrdinalIgnoreCase) != -1).ToList(); return names.Select(GetSatIniMappings).Where(i => i != null).DistinctBy(i => i.Value.Split('|')[0]).ToList(); } @@ -2472,20 +2472,21 @@ namespace MediaBrowser.Server.Implementations.LiveTv return null; } + var srch = "SatIp.ini."; + var filename = Path.GetFileName(resource); + return new NameValuePair { Name = satType1 + " " + satType2, - Value = satType2 + "|" + Path.GetFileName(resource) + Value = satType2 + "|" + filename.Substring(filename.IndexOf(srch) + srch.Length) }; } } } - public async Task> GetSatChannelScanResult(TunerHostInfo info, CancellationToken cancellationToken) + public Task> GetSatChannelScanResult(TunerHostInfo info, CancellationToken cancellationToken) { - var result = await new TunerHosts.SatIp.ChannelScan().Scan(info, cancellationToken).ConfigureAwait(false); - - return result.Select(i => new ChannelInfo()).ToList(); + return new TunerHosts.SatIp.ChannelScan(_logger).Scan(info, cancellationToken); } } } \ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs index 2277f8f630..20737df50d 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs @@ -1,15 +1,104 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; +using IniParser; +using IniParser.Model; +using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Logging; +using MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.Rtsp; namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp { public class ChannelScan { - public async Task> Scan(TunerHostInfo info, CancellationToken cancellationToken) + private readonly ILogger _logger; + + public ChannelScan(ILogger logger) + { + _logger = logger; + } + + public async Task> Scan(TunerHostInfo info, CancellationToken cancellationToken) + { + var timedToken = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(timedToken.Token, cancellationToken); + + using (var rtspSession = new RtspSession(info.Url, _logger)) + { + var ini = info.SourceA.Split('|')[1]; + var resource = GetType().Assembly.GetManifestResourceNames().FirstOrDefault(i => i.EndsWith(ini, StringComparison.OrdinalIgnoreCase)); + + _logger.Info("Opening ini file {0}", resource); + using (var stream = GetType().Assembly.GetManifestResourceStream(resource)) + { + using (var reader = new StreamReader(stream)) + { + var parser = new StreamIniDataParser(); + var data = parser.ReadData(reader); + + var count = GetInt(data, "DVB", "0", 0); + + var index = 1; + var source = "1"; + + while (!linkedToken.IsCancellationRequested) + { + float percent = count == 0 ? 0 : (float)(index) / count; + percent = Math.Max(percent * 100, 100); + + //SetControlPropertyThreadSafe(pgbSearchResult, "Value", (int)percent); + var strArray = data["DVB"][index.ToString(CultureInfo.InvariantCulture)].Split(','); + + string tuning; + if (strArray[4] == "S2") + { + tuning = string.Format("src={0}&freq={1}&pol={2}&sr={3}&fec={4}&msys=dvbs2&mtype={5}&plts=on&ro=0.35&pids=0,16,17,18,20", source, strArray[0], strArray[1].ToLower(), strArray[2].ToLower(), strArray[3], strArray[5].ToLower()); + } + else + { + tuning = string.Format("src={0}&freq={1}&pol={2}&sr={3}&fec={4}&msys=dvbs&mtype={5}&pids=0,16,17,18,20", source, strArray[0], strArray[1].ToLower(), strArray[2], strArray[3], strArray[5].ToLower()); + } + + if (string.IsNullOrEmpty(rtspSession.RtspSessionId)) + { + rtspSession.Setup(tuning, "unicast"); + + rtspSession.Play(string.Empty); + } + else + { + rtspSession.Play(tuning); + } + + int signallevel; + int signalQuality; + rtspSession.Describe(out signallevel, out signalQuality); + + await Task.Delay(500).ConfigureAwait(false); + index++; + } + } + } + } + + return new List(); + } + + private int GetInt(IniData data, string s1, string s2, int defaultValue) { - return new List(); + var value = data[s1][s2]; + int numericValue; + if (int.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out numericValue)) + { + return numericValue; + } + + return defaultValue; } } diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs index fae7c4bfc7..5f286f1db5 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspMethod.cs @@ -17,7 +17,7 @@ using System.Collections.Generic; -namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.Rtsp { /// /// Standard RTSP request methods. diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs index d8462b2238..600eda02da 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspRequest.cs @@ -18,8 +18,7 @@ using System.Collections.Generic; using System.Text; - -namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.Rtsp { /// /// A simple class that can be used to serialise RTSP requests. diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs index 0bf80012d2..97290623b9 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspResponse.cs @@ -21,8 +21,7 @@ using System.Linq; using System.Text; using System.Text.RegularExpressions; - -namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.Rtsp { /// /// A simple class that can be used to deserialise RTSP responses. diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs index e76fb71757..71b3f8a184 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspSession.cs @@ -25,7 +25,7 @@ using System.Net.Sockets; using System.Text.RegularExpressions; using MediaBrowser.Model.Logging; -namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.Rtsp { public class RtspSession : IDisposable { @@ -58,15 +58,22 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp private Socket _rtspSocket; private int _rtspSequenceNum = 1; private bool _disposed = false; - private ILogger _logger; + private readonly ILogger _logger; #endregion #region Constructor public RtspSession(string address, ILogger logger) { + if (string.IsNullOrWhiteSpace(address)) + { + throw new ArgumentNullException("address"); + } + _address = address; _logger = logger; + + _logger.Info("Creating RtspSession with url {0}", address); } ~RtspSession() { diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs index 8786314edb..6d6d50623b 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/Rtsp/RtspStatusCode.cs @@ -17,7 +17,7 @@ using System.ComponentModel; -namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.SatIp +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp.Rtsp { /// /// Standard RTSP status codes. diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs index 46a2a8524b..ffd85fd18a 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs @@ -40,7 +40,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp return await new M3uParser(Logger, _fileSystem, _httpClient).Parse(tuner.M3UUrl, ChannelIdPrefix, tuner.Id, cancellationToken).ConfigureAwait(false); } - return new List(); + var channels = await new ChannelScan(Logger).Scan(tuner, cancellationToken).ConfigureAwait(false); + return channels; } public static string DeviceType -- cgit v1.2.3 From 0694dba1e0ac86e9f8b6f6a135baddbe76b41033 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 31 Mar 2016 20:31:55 -0400 Subject: update channel scan --- .../LiveTv/TunerHosts/SatIp/ChannelScan.cs | 48 ++++++++++------------ 1 file changed, 22 insertions(+), 26 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs index 20737df50d..fdeae25b0e 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/ChannelScan.cs @@ -25,28 +25,31 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp public async Task> Scan(TunerHostInfo info, CancellationToken cancellationToken) { - var timedToken = new CancellationTokenSource(TimeSpan.FromSeconds(30)); - var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(timedToken.Token, cancellationToken); + var ini = info.SourceA.Split('|')[1]; + var resource = GetType().Assembly.GetManifestResourceNames().FirstOrDefault(i => i.EndsWith(ini, StringComparison.OrdinalIgnoreCase)); - using (var rtspSession = new RtspSession(info.Url, _logger)) - { - var ini = info.SourceA.Split('|')[1]; - var resource = GetType().Assembly.GetManifestResourceNames().FirstOrDefault(i => i.EndsWith(ini, StringComparison.OrdinalIgnoreCase)); + _logger.Info("Opening ini file {0}", resource); + var list = new List(); - _logger.Info("Opening ini file {0}", resource); - using (var stream = GetType().Assembly.GetManifestResourceStream(resource)) + using (var stream = GetType().Assembly.GetManifestResourceStream(resource)) + { + using (var reader = new StreamReader(stream)) { - using (var reader = new StreamReader(stream)) - { - var parser = new StreamIniDataParser(); - var data = parser.ReadData(reader); + var parser = new StreamIniDataParser(); + var data = parser.ReadData(reader); - var count = GetInt(data, "DVB", "0", 0); + var count = GetInt(data, "DVB", "0", 0); - var index = 1; - var source = "1"; + _logger.Info("DVB Count: {0}", count); + + var index = 1; + var source = "1"; + + while (index <= count) + { + cancellationToken.ThrowIfCancellationRequested(); - while (!linkedToken.IsCancellationRequested) + using (var rtspSession = new RtspSession(info.Url, _logger)) { float percent = count == 0 ? 0 : (float)(index) / count; percent = Math.Max(percent * 100, 100); @@ -64,16 +67,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp tuning = string.Format("src={0}&freq={1}&pol={2}&sr={3}&fec={4}&msys=dvbs&mtype={5}&pids=0,16,17,18,20", source, strArray[0], strArray[1].ToLower(), strArray[2], strArray[3], strArray[5].ToLower()); } - if (string.IsNullOrEmpty(rtspSession.RtspSessionId)) - { - rtspSession.Setup(tuning, "unicast"); + rtspSession.Setup(tuning, "unicast"); - rtspSession.Play(string.Empty); - } - else - { - rtspSession.Play(tuning); - } + rtspSession.Play(string.Empty); int signallevel; int signalQuality; @@ -86,7 +82,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp } } - return new List(); + return list; } private int GetInt(IniData data, string s1, string s2, int defaultValue) -- cgit v1.2.3 From 04c8cb5aec70b2ec04fd65c662af7a46cb760b1a Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 3 Apr 2016 19:20:43 -0400 Subject: get dynamic info from hdhr --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 81 ++++++++++++++-------- 1 file changed, 52 insertions(+), 29 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index db7f6f86c3..9629f608cc 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -59,7 +59,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun return id; } - protected override async Task> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken) + private async Task> GetLineup(TunerHostInfo info, CancellationToken cancellationToken) { var options = new HttpRequestOptions { @@ -68,29 +68,29 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun }; using (var stream = await _httpClient.Get(options)) { - var root = JsonSerializer.DeserializeFromStream>(stream); + var lineup = JsonSerializer.DeserializeFromStream>(stream) ?? new List(); - if (root != null) + if (info.ImportFavoritesOnly) { - var result = root.Select(i => new ChannelInfo - { - Name = i.GuideName, - Number = i.GuideNumber.ToString(CultureInfo.InvariantCulture), - Id = GetChannelId(info, i), - IsFavorite = i.Favorite, - TunerHostId = info.Id + lineup = lineup.Where(i => i.Favorite).ToList(); + } - }); + return lineup; + } + } - if (info.ImportFavoritesOnly) - { - result = result.Where(i => i.IsFavorite ?? true).ToList(); - } + protected override async Task> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken) + { + var lineup = await GetLineup(info, cancellationToken).ConfigureAwait(false); - return result; - } - return new List(); - } + return lineup.Select(i => new ChannelInfo + { + Name = i.GuideName, + Number = i.GuideNumber.ToString(CultureInfo.InvariantCulture), + Id = GetChannelId(info, i), + IsFavorite = i.Favorite, + TunerHostId = info.Id + }); } private async Task GetModelInfo(TunerHostInfo info, CancellationToken cancellationToken) @@ -226,17 +226,21 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun { public string GuideNumber { get; set; } public string GuideName { get; set; } + public string VideoCodec { get; set; } + public string AudioCodec { get; set; } public string URL { get; set; } public bool Favorite { get; set; } public bool DRM { get; set; } + public int HD { get; set; } } - private MediaSourceInfo GetMediaSource(TunerHostInfo info, string channelId, string profile) + private async Task GetMediaSource(TunerHostInfo info, string channelId, string profile) { int? width = null; int? height = null; bool isInterlaced = true; - var videoCodec = !string.IsNullOrWhiteSpace(GetEncodingOptions().HardwareAccelerationType) ? null : "mpeg2video"; + string videoCodec = null; + string audioCodec = "ac3"; int? videoBitrate = null; @@ -297,6 +301,25 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun videoBitrate = 1000000; } + if (string.IsNullOrWhiteSpace(videoCodec)) + { + var lineup = await GetLineup(info, CancellationToken.None).ConfigureAwait(false); + var channel = lineup.FirstOrDefault(i => string.Equals(i.GuideNumber, channelId, StringComparison.OrdinalIgnoreCase)); + if (channel != null) + { + videoCodec = channel.VideoCodec; + audioCodec = channel.AudioCodec; + + videoBitrate = channel.HD == 1 ? 15000000 : 2000000; + } + } + + // normalize + if (string.Equals(videoCodec, "mpeg2", StringComparison.OrdinalIgnoreCase)) + { + videoCodec = "mpeg2video"; + } + var url = GetApiUrl(info, true) + "/auto/v" + channelId; if (!string.IsNullOrWhiteSpace(profile) && !string.Equals(profile, "native", StringComparison.OrdinalIgnoreCase)) @@ -327,7 +350,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun Type = MediaStreamType.Audio, // Set the index to -1 because we don't know the exact index of the audio stream within the container Index = -1, - Codec = "ac3", + Codec = audioCodec, BitRate = 192000 } }, @@ -364,7 +387,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun } var hdhrId = GetHdHrIdFromChannelId(channelId); - list.Add(GetMediaSource(info, hdhrId, "native")); + list.Add(await GetMediaSource(info, hdhrId, "native").ConfigureAwait(false)); try { @@ -373,12 +396,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun if (model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1) { - list.Insert(0, GetMediaSource(info, hdhrId, "heavy")); + list.Add(await GetMediaSource(info, hdhrId, "heavy").ConfigureAwait(false)); - list.Add(GetMediaSource(info, hdhrId, "internet480")); - list.Add(GetMediaSource(info, hdhrId, "internet360")); - list.Add(GetMediaSource(info, hdhrId, "internet240")); - list.Add(GetMediaSource(info, hdhrId, "mobile")); + list.Add(await GetMediaSource(info, hdhrId, "internet480").ConfigureAwait(false)); + list.Add(await GetMediaSource(info, hdhrId, "internet360").ConfigureAwait(false)); + list.Add(await GetMediaSource(info, hdhrId, "internet240").ConfigureAwait(false)); + list.Add(await GetMediaSource(info, hdhrId, "mobile").ConfigureAwait(false)); } } catch (Exception ex) @@ -409,7 +432,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun } var hdhrId = GetHdHrIdFromChannelId(channelId); - return GetMediaSource(info, hdhrId, streamId); + return await GetMediaSource(info, hdhrId, streamId).ConfigureAwait(false); } public async Task Validate(TunerHostInfo info) -- cgit v1.2.3 From d9dcd21c47b95919745ec7b5058383357fd73d65 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 3 Apr 2016 20:01:03 -0400 Subject: update hdhr streaming --- MediaBrowser.Api/Playback/BaseStreamingService.cs | 23 +++++----------------- .../Playback/Progressive/VideoService.cs | 4 +--- MediaBrowser.Api/Playback/StreamRequest.cs | 3 --- MediaBrowser.Api/Playback/StreamState.cs | 13 ------------ MediaBrowser.Controller/LiveTv/ChannelInfo.cs | 4 ++++ .../MediaEncoding/EncodingJobOptions.cs | 3 --- MediaBrowser.Dlna/Didl/DidlBuilder.cs | 2 -- MediaBrowser.Dlna/PlayTo/PlayToController.cs | 1 - MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs | 13 ------------ .../Encoder/EncodingJobFactory.cs | 9 --------- MediaBrowser.Model/Dlna/ConditionProcessor.cs | 3 --- MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs | 2 -- MediaBrowser.Model/Dlna/DeviceProfile.cs | 3 +-- MediaBrowser.Model/Dlna/ProfileConditionValue.cs | 1 - MediaBrowser.Model/Dlna/StreamBuilder.cs | 21 ++------------------ MediaBrowser.Model/Dlna/StreamInfo.cs | 18 +++-------------- MediaBrowser.Model/Entities/MediaStream.cs | 6 ------ .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 13 +++++++----- .../Persistence/SqliteItemRepository.cs | 7 ++----- 19 files changed, 26 insertions(+), 123 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 00ac7be879..108b594942 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -1452,10 +1452,7 @@ namespace MediaBrowser.Api.Playback } else if (i == 19) { - if (videoRequest != null) - { - videoRequest.Cabac = string.Equals("true", val, StringComparison.OrdinalIgnoreCase); - } + // cabac no longer used } else if (i == 20) { @@ -1805,10 +1802,10 @@ namespace MediaBrowser.Api.Playback { if (string.IsNullOrEmpty(videoStream.Profile)) { - return false; + //return false; } - if (!string.Equals(request.Profile, videoStream.Profile, StringComparison.OrdinalIgnoreCase)) + if (!string.IsNullOrEmpty(videoStream.Profile) && !string.Equals(request.Profile, videoStream.Profile, StringComparison.OrdinalIgnoreCase)) { var currentScore = GetVideoProfileScore(videoStream.Profile); var requestedScore = GetVideoProfileScore(request.Profile); @@ -1884,24 +1881,16 @@ namespace MediaBrowser.Api.Playback { if (!videoStream.Level.HasValue) { - return false; + //return false; } - if (videoStream.Level.Value > requestLevel) + if (videoStream.Level.HasValue && videoStream.Level.Value > requestLevel) { return false; } } } - if (request.Cabac.HasValue && request.Cabac.Value) - { - if (videoStream.IsCabac.HasValue && !videoStream.IsCabac.Value) - { - return false; - } - } - return request.EnableAutoStreamCopy; } @@ -2028,7 +2017,6 @@ namespace MediaBrowser.Api.Playback state.TargetPacketLength, state.TargetTimestamp, state.IsTargetAnamorphic, - state.IsTargetCabac, state.TargetRefFrames, state.TargetVideoStreamCount, state.TargetAudioStreamCount, @@ -2131,7 +2119,6 @@ namespace MediaBrowser.Api.Playback state.TargetPacketLength, state.TranscodeSeekInfo, state.IsTargetAnamorphic, - state.IsTargetCabac, state.TargetRefFrames, state.TargetVideoStreamCount, state.TargetAudioStreamCount, diff --git a/MediaBrowser.Api/Playback/Progressive/VideoService.cs b/MediaBrowser.Api/Playback/Progressive/VideoService.cs index 7c68b17312..b0d87c975b 100644 --- a/MediaBrowser.Api/Playback/Progressive/VideoService.cs +++ b/MediaBrowser.Api/Playback/Progressive/VideoService.cs @@ -137,12 +137,10 @@ namespace MediaBrowser.Api.Playback.Progressive args += " -mpegts_m2ts_mode 1"; } - var isOutputMkv = string.Equals(state.OutputContainer, "mkv", StringComparison.OrdinalIgnoreCase); - if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase)) { if (state.VideoStream != null && IsH264(state.VideoStream) && - (string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase) || isOutputMkv)) + (string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase))) { args += " -bsf:v h264_mp4toannexb"; } diff --git a/MediaBrowser.Api/Playback/StreamRequest.cs b/MediaBrowser.Api/Playback/StreamRequest.cs index 1135a3a54d..5167af98a2 100644 --- a/MediaBrowser.Api/Playback/StreamRequest.cs +++ b/MediaBrowser.Api/Playback/StreamRequest.cs @@ -190,9 +190,6 @@ namespace MediaBrowser.Api.Playback [ApiMember(Name = "CopyTimestamps", Description = "Whether or not to copy timestamps when transcoding with an offset. Defaults to false.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] public bool CopyTimestamps { get; set; } - [ApiMember(Name = "Cabac", Description = "Enable if cabac encoding is required", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] - public bool? Cabac { get; set; } - public VideoStreamRequest() { EnableAutoStreamCopy = true; diff --git a/MediaBrowser.Api/Playback/StreamState.cs b/MediaBrowser.Api/Playback/StreamState.cs index f1f6bb71f3..ed8a27fafe 100644 --- a/MediaBrowser.Api/Playback/StreamState.cs +++ b/MediaBrowser.Api/Playback/StreamState.cs @@ -480,18 +480,5 @@ namespace MediaBrowser.Api.Playback return false; } } - - public bool? IsTargetCabac - { - get - { - if (Request.Static) - { - return VideoStream == null ? null : VideoStream.IsCabac; - } - - return true; - } - } } } diff --git a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs index 7d8df96ede..372b095fd1 100644 --- a/MediaBrowser.Controller/LiveTv/ChannelInfo.cs +++ b/MediaBrowser.Controller/LiveTv/ChannelInfo.cs @@ -59,5 +59,9 @@ namespace MediaBrowser.Controller.LiveTv /// /// null if [is favorite] contains no value, true if [is favorite]; otherwise, false. public bool? IsFavorite { get; set; } + + public bool? IsHD { get; set; } + public string AudioCodec { get; set; } + public string VideoCodec { get; set; } } } diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs index ddaf7ff6d2..c87ac4e734 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingJobOptions.cs @@ -58,8 +58,6 @@ namespace MediaBrowser.Controller.MediaEncoding } } - public bool? Cabac { get; set; } - public EncodingJobOptions() { @@ -87,7 +85,6 @@ namespace MediaBrowser.Controller.MediaEncoding MaxRefFrames = info.MaxRefFrames; MaxVideoBitDepth = info.MaxVideoBitDepth; SubtitleMethod = info.SubtitleDeliveryMethod; - Cabac = info.Cabac; Context = info.Context; if (info.SubtitleDeliveryMethod != SubtitleDeliveryMethod.External) diff --git a/MediaBrowser.Dlna/Didl/DidlBuilder.cs b/MediaBrowser.Dlna/Didl/DidlBuilder.cs index e8e969a5f1..728b397dee 100644 --- a/MediaBrowser.Dlna/Didl/DidlBuilder.cs +++ b/MediaBrowser.Dlna/Didl/DidlBuilder.cs @@ -171,7 +171,6 @@ namespace MediaBrowser.Dlna.Didl streamInfo.TargetPacketLength, streamInfo.TranscodeSeekInfo, streamInfo.IsTargetAnamorphic, - streamInfo.IsTargetCabac, streamInfo.TargetRefFrames, streamInfo.TargetVideoStreamCount, streamInfo.TargetAudioStreamCount, @@ -317,7 +316,6 @@ namespace MediaBrowser.Dlna.Didl streamInfo.TargetPacketLength, streamInfo.TargetTimestamp, streamInfo.IsTargetAnamorphic, - streamInfo.IsTargetCabac, streamInfo.TargetRefFrames, streamInfo.TargetVideoStreamCount, streamInfo.TargetAudioStreamCount, diff --git a/MediaBrowser.Dlna/PlayTo/PlayToController.cs b/MediaBrowser.Dlna/PlayTo/PlayToController.cs index 314756cdf2..db5e0ee293 100644 --- a/MediaBrowser.Dlna/PlayTo/PlayToController.cs +++ b/MediaBrowser.Dlna/PlayTo/PlayToController.cs @@ -523,7 +523,6 @@ namespace MediaBrowser.Dlna.PlayTo streamInfo.TargetPacketLength, streamInfo.TranscodeSeekInfo, streamInfo.IsTargetAnamorphic, - streamInfo.IsTargetCabac, streamInfo.TargetRefFrames, streamInfo.TargetVideoStreamCount, streamInfo.TargetAudioStreamCount, diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs index ae676dbc5a..b23bd16f35 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJob.cs @@ -391,19 +391,6 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - public bool? IsTargetCabac - { - get - { - if (Options.Static) - { - return VideoStream == null ? null : VideoStream.IsCabac; - } - - return true; - } - } - public int? TargetVideoStreamCount { get diff --git a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs index f782fd05f4..070aae3a70 100644 --- a/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs +++ b/MediaBrowser.MediaEncoding/Encoder/EncodingJobFactory.cs @@ -664,14 +664,6 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - if (request.Cabac.HasValue && request.Cabac.Value) - { - if (videoStream.IsCabac.HasValue && !videoStream.IsCabac.Value) - { - return false; - } - } - return request.EnableAutoStreamCopy; } @@ -773,7 +765,6 @@ namespace MediaBrowser.MediaEncoding.Encoder state.TargetPacketLength, state.TargetTimestamp, state.IsTargetAnamorphic, - state.IsTargetCabac, state.TargetRefFrames, state.TargetVideoStreamCount, state.TargetAudioStreamCount, diff --git a/MediaBrowser.Model/Dlna/ConditionProcessor.cs b/MediaBrowser.Model/Dlna/ConditionProcessor.cs index fef04647a4..69f1369dc0 100644 --- a/MediaBrowser.Model/Dlna/ConditionProcessor.cs +++ b/MediaBrowser.Model/Dlna/ConditionProcessor.cs @@ -17,7 +17,6 @@ namespace MediaBrowser.Model.Dlna int? packetLength, TransportStreamTimestamp? timestamp, bool? isAnamorphic, - bool? isCabac, int? refFrames, int? numVideoStreams, int? numAudioStreams, @@ -27,8 +26,6 @@ namespace MediaBrowser.Model.Dlna { case ProfileConditionValue.IsAnamorphic: return IsConditionSatisfied(condition, isAnamorphic); - case ProfileConditionValue.IsCabac: - return IsConditionSatisfied(condition, isCabac); case ProfileConditionValue.VideoFramerate: return IsConditionSatisfied(condition, videoFramerate); case ProfileConditionValue.VideoLevel: diff --git a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs index 58d669c220..c4b3383a2b 100644 --- a/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs +++ b/MediaBrowser.Model/Dlna/ContentFeatureBuilder.cs @@ -115,7 +115,6 @@ namespace MediaBrowser.Model.Dlna int? packetLength, TranscodeSeekInfo transcodeSeekInfo, bool? isAnamorphic, - bool? isCabac, int? refFrames, int? numVideoStreams, int? numAudioStreams, @@ -157,7 +156,6 @@ namespace MediaBrowser.Model.Dlna packetLength, timestamp, isAnamorphic, - isCabac, refFrames, numVideoStreams, numAudioStreams, diff --git a/MediaBrowser.Model/Dlna/DeviceProfile.cs b/MediaBrowser.Model/Dlna/DeviceProfile.cs index 80c060c499..423928f620 100644 --- a/MediaBrowser.Model/Dlna/DeviceProfile.cs +++ b/MediaBrowser.Model/Dlna/DeviceProfile.cs @@ -283,7 +283,6 @@ namespace MediaBrowser.Model.Dlna int? packetLength, TransportStreamTimestamp timestamp, bool? isAnamorphic, - bool? isCabac, int? refFrames, int? numVideoStreams, int? numAudioStreams, @@ -321,7 +320,7 @@ namespace MediaBrowser.Model.Dlna var anyOff = false; foreach (ProfileCondition c in i.Conditions) { - if (!conditionProcessor.IsVideoConditionSatisfied(c, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames, numVideoStreams, numAudioStreams, videoCodecTag)) + if (!conditionProcessor.IsVideoConditionSatisfied(c, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, refFrames, numVideoStreams, numAudioStreams, videoCodecTag)) { anyOff = true; break; diff --git a/MediaBrowser.Model/Dlna/ProfileConditionValue.cs b/MediaBrowser.Model/Dlna/ProfileConditionValue.cs index 4ad326e519..c17a09c3fb 100644 --- a/MediaBrowser.Model/Dlna/ProfileConditionValue.cs +++ b/MediaBrowser.Model/Dlna/ProfileConditionValue.cs @@ -17,7 +17,6 @@ VideoTimestamp = 12, IsAnamorphic = 13, RefFrames = 14, - IsCabac = 15, NumAudioStreams = 16, NumVideoStreams = 17, IsSecondaryAudio = 18, diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index e5477cfd03..f80c52e384 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -597,7 +597,6 @@ namespace MediaBrowser.Model.Dlna string videoProfile = videoStream == null ? null : videoStream.Profile; float? videoFramerate = videoStream == null ? null : videoStream.AverageFrameRate ?? videoStream.AverageFrameRate; bool? isAnamorphic = videoStream == null ? null : videoStream.IsAnamorphic; - bool? isCabac = videoStream == null ? null : videoStream.IsCabac; string videoCodecTag = videoStream == null ? null : videoStream.CodecTag; int? audioBitrate = audioStream == null ? null : audioStream.BitRate; @@ -614,7 +613,7 @@ namespace MediaBrowser.Model.Dlna // Check container conditions foreach (ProfileCondition i in conditions) { - if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames, numVideoStreams, numAudioStreams, videoCodecTag)) + if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, refFrames, numVideoStreams, numAudioStreams, videoCodecTag)) { LogConditionFailure(profile, "VideoContainerProfile", i, mediaSource); @@ -647,7 +646,7 @@ namespace MediaBrowser.Model.Dlna foreach (ProfileCondition i in conditions) { - if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, isCabac, refFrames, numVideoStreams, numAudioStreams, videoCodecTag)) + if (!conditionProcessor.IsVideoConditionSatisfied(i, width, height, bitDepth, videoBitrate, videoProfile, videoLevel, videoFramerate, packetLength, timestamp, isAnamorphic, refFrames, numVideoStreams, numAudioStreams, videoCodecTag)) { LogConditionFailure(profile, "VideoCodecProfile", i, mediaSource); @@ -910,22 +909,6 @@ namespace MediaBrowser.Model.Dlna } break; } - case ProfileConditionValue.IsCabac: - { - bool val; - if (BoolHelper.TryParseCultureInvariant(value, out val)) - { - if (condition.Condition == ProfileConditionType.Equals) - { - item.Cabac = val; - } - else if (condition.Condition == ProfileConditionType.NotEquals) - { - item.Cabac = !val; - } - } - break; - } case ProfileConditionValue.IsAnamorphic: case ProfileConditionValue.AudioProfile: case ProfileConditionValue.Has64BitOffsets: diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index 436ed20712..a2867dcc9f 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -30,7 +30,6 @@ namespace MediaBrowser.Model.Dlna public string VideoCodec { get; set; } public string VideoProfile { get; set; } - public bool? Cabac { get; set; } public bool CopyTimestamps { get; set; } public string AudioCodec { get; set; } @@ -219,7 +218,9 @@ namespace MediaBrowser.Model.Dlna list.Add(new NameValuePair("MaxRefFrames", item.MaxRefFrames.HasValue ? StringHelper.ToStringCultureInvariant(item.MaxRefFrames.Value) : string.Empty)); list.Add(new NameValuePair("MaxVideoBitDepth", item.MaxVideoBitDepth.HasValue ? StringHelper.ToStringCultureInvariant(item.MaxVideoBitDepth.Value) : string.Empty)); list.Add(new NameValuePair("Profile", item.VideoProfile ?? string.Empty)); - list.Add(new NameValuePair("Cabac", item.Cabac.HasValue ? item.Cabac.Value.ToString() : string.Empty)); + + // no longer used + list.Add(new NameValuePair("Cabac", string.Empty)); list.Add(new NameValuePair("PlaySessionId", item.PlaySessionId ?? string.Empty)); list.Add(new NameValuePair("api_key", accessToken ?? string.Empty)); @@ -632,19 +633,6 @@ namespace MediaBrowser.Model.Dlna } } - public bool? IsTargetCabac - { - get - { - if (IsDirectStream) - { - return TargetVideoStream == null ? null : TargetVideoStream.IsCabac; - } - - return true; - } - } - public int? TargetWidth { get diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs index 79fa46baf4..bdc043e9a7 100644 --- a/MediaBrowser.Model/Entities/MediaStream.cs +++ b/MediaBrowser.Model/Entities/MediaStream.cs @@ -232,11 +232,5 @@ namespace MediaBrowser.Model.Entities /// /// true if this instance is anamorphic; otherwise, false. public bool? IsAnamorphic { get; set; } - - /// - /// Gets or sets a value indicating whether this instance is cabac. - /// - /// null if [is cabac] contains no value, true if [is cabac]; otherwise, false. - public bool? IsCabac { get; set; } } } diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 9629f608cc..ef8efbe987 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -89,7 +89,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun Number = i.GuideNumber.ToString(CultureInfo.InvariantCulture), Id = GetChannelId(info, i), IsFavorite = i.Favorite, - TunerHostId = info.Id + TunerHostId = info.Id, + IsHD = i.HD == 1, + AudioCodec = i.AudioCodec, + VideoCodec = i.VideoCodec }); } @@ -303,14 +306,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun if (string.IsNullOrWhiteSpace(videoCodec)) { - var lineup = await GetLineup(info, CancellationToken.None).ConfigureAwait(false); - var channel = lineup.FirstOrDefault(i => string.Equals(i.GuideNumber, channelId, StringComparison.OrdinalIgnoreCase)); + var channels = await GetChannels(info, true, CancellationToken.None).ConfigureAwait(false); + var channel = channels.FirstOrDefault(i => string.Equals(i.Number, channelId, StringComparison.OrdinalIgnoreCase)); if (channel != null) { videoCodec = channel.VideoCodec; audioCodec = channel.AudioCodec; - videoBitrate = channel.HD == 1 ? 15000000 : 2000000; + videoBitrate = (channel.IsHD ?? true) ? 15000000 : 2000000; } } @@ -343,7 +346,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun Width = width, Height = height, BitRate = videoBitrate - + }, new MediaStream { diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index eda0a263ac..71c338fdb3 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -2755,7 +2755,7 @@ namespace MediaBrowser.Server.Implementations.Persistence _saveStreamCommand.GetParameter(index++).Value = stream.BitDepth; _saveStreamCommand.GetParameter(index++).Value = stream.IsAnamorphic; _saveStreamCommand.GetParameter(index++).Value = stream.RefFrames; - _saveStreamCommand.GetParameter(index++).Value = stream.IsCabac; + _saveStreamCommand.GetParameter(index++).Value = null; _saveStreamCommand.GetParameter(index++).Value = stream.CodecTag; _saveStreamCommand.GetParameter(index++).Value = stream.Comment; @@ -2907,10 +2907,7 @@ namespace MediaBrowser.Server.Implementations.Persistence item.RefFrames = reader.GetInt32(24); } - if (!reader.IsDBNull(25)) - { - item.IsCabac = reader.GetBoolean(25); - } + // cabac no longer used if (!reader.IsDBNull(26)) { -- cgit v1.2.3 From b844471860e468bc1641e2d854fd8a5ab8ce7f3f Mon Sep 17 00:00:00 2001 From: Daniel Becker Date: Sun, 3 Apr 2016 23:39:40 -0700 Subject: fix resolution for internet540 profile; remove obsolete internet720 profile --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index ef8efbe987..2503412d52 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -263,18 +263,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun videoCodec = "h264"; videoBitrate = 15000000; } - else if (string.Equals(profile, "internet720", StringComparison.OrdinalIgnoreCase)) - { - width = 1280; - height = 720; - isInterlaced = false; - videoCodec = "h264"; - videoBitrate = 8000000; - } else if (string.Equals(profile, "internet540", StringComparison.OrdinalIgnoreCase)) { - width = 1280; - height = 720; + width = 960; + height = 546; isInterlaced = false; videoCodec = "h264"; videoBitrate = 2500000; -- cgit v1.2.3 From aa817508e25ce164184c44d2c16fd5091961dc6d Mon Sep 17 00:00:00 2001 From: Daniel Becker Date: Sun, 3 Apr 2016 23:42:07 -0700 Subject: actually add internet540 profile --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 2503412d52..1012385676 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -393,6 +393,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun { list.Add(await GetMediaSource(info, hdhrId, "heavy").ConfigureAwait(false)); + list.Add(await GetMediaSource(info, hdhrId, "internet540").ConfigureAwait(false)); list.Add(await GetMediaSource(info, hdhrId, "internet480").ConfigureAwait(false)); list.Add(await GetMediaSource(info, hdhrId, "internet360").ConfigureAwait(false)); list.Add(await GetMediaSource(info, hdhrId, "internet240").ConfigureAwait(false)); -- cgit v1.2.3 From c9092de032b4166f5907283f35d361ee7c49a3ee Mon Sep 17 00:00:00 2001 From: Daniel Becker Date: Sun, 3 Apr 2016 23:46:45 -0700 Subject: allow disabling of hardware transcoding on HDTC-2US --- MediaBrowser.Model/LiveTv/LiveTvOptions.cs | 4 +++- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs index 660f30cc9c..46f630fe04 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs @@ -31,6 +31,7 @@ namespace MediaBrowser.Model.LiveTv public string Type { get; set; } public string DeviceId { get; set; } public bool ImportFavoritesOnly { get; set; } + public bool AllowHWTranscoding { get; set; } public bool IsEnabled { get; set; } public string M3UUrl { get; set; } public string InfoUrl { get; set; } @@ -47,6 +48,7 @@ namespace MediaBrowser.Model.LiveTv public TunerHostInfo() { IsEnabled = true; + AllowHWTranscoding = true; } } @@ -70,4 +72,4 @@ namespace MediaBrowser.Model.LiveTv EnableAllTuners = true; } } -} \ No newline at end of file +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index ef8efbe987..64780a8e31 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -397,7 +397,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun string model = await GetModelInfo(info, cancellationToken).ConfigureAwait(false); model = model ?? string.Empty; - if (model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1) + if (info.AllowHWTranscoding && (model.IndexOf("hdtc", StringComparison.OrdinalIgnoreCase) != -1)) { list.Add(await GetMediaSource(info, hdhrId, "heavy").ConfigureAwait(false)); -- cgit v1.2.3 From 1cea5bcbd8360fa7c5c9bfd273f27f472809a178 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 5 Apr 2016 22:18:56 -0400 Subject: improve identify feature --- MediaBrowser.Api/ItemLookupService.cs | 15 +++++++++----- .../Providers/MetadataRefreshOptions.cs | 3 +++ MediaBrowser.Providers/Manager/MetadataService.cs | 13 ++++++++++++ MediaBrowser.Providers/Omdb/OmdbItemProvider.cs | 6 ++---- .../HttpServer/HttpListenerHost.cs | 23 ++++++++++++---------- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 2 +- 6 files changed, 42 insertions(+), 20 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Api/ItemLookupService.cs b/MediaBrowser.Api/ItemLookupService.cs index 8be37e2100..41bfd9da28 100644 --- a/MediaBrowser.Api/ItemLookupService.cs +++ b/MediaBrowser.Api/ItemLookupService.cs @@ -202,14 +202,19 @@ namespace MediaBrowser.Api // } //} Logger.Info("Setting provider id's to item {0}-{1}: {2}", item.Id, item.Name, _json.SerializeToString(request.ProviderIds)); + + // Since the refresh process won't erase provider Ids, we need to set this explicitly now. item.ProviderIds = request.ProviderIds; + //item.ProductionYear = request.ProductionYear; + //item.Name = request.Name; - var task = _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(_fileSystem) + var task = _providerManager.RefreshFullItem(item, new MetadataRefreshOptions(_fileSystem) { MetadataRefreshMode = MetadataRefreshMode.FullRefresh, ImageRefreshMode = ImageRefreshMode.FullRefresh, ReplaceAllMetadata = true, - ReplaceAllImages = request.ReplaceAllImages + ReplaceAllImages = request.ReplaceAllImages, + SearchResult = request }, CancellationToken.None); Task.WaitAll(task); @@ -234,7 +239,7 @@ namespace MediaBrowser.Api contentPath = await reader.ReadToEndAsync().ConfigureAwait(false); } - if (_fileSystem.FileExists(contentPath)) + if (_fileSystem.FileExists(contentPath)) { return ToStaticFileResult(contentPath); } @@ -275,7 +280,7 @@ namespace MediaBrowser.Api var fullCachePath = GetFullCachePath(urlHash + "." + ext); - _fileSystem.CreateDirectory(Path.GetDirectoryName(fullCachePath)); + _fileSystem.CreateDirectory(Path.GetDirectoryName(fullCachePath)); using (var stream = result.Content) { using (var filestream = _fileSystem.GetFileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, true)) @@ -284,7 +289,7 @@ namespace MediaBrowser.Api } } - _fileSystem.CreateDirectory(Path.GetDirectoryName(pointerCachePath)); + _fileSystem.CreateDirectory(Path.GetDirectoryName(pointerCachePath)); using (var writer = new StreamWriter(pointerCachePath)) { await writer.WriteAsync(fullCachePath).ConfigureAwait(false); diff --git a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs index 29f4feb3d7..9427b2afd7 100644 --- a/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs +++ b/MediaBrowser.Controller/Providers/MetadataRefreshOptions.cs @@ -1,5 +1,6 @@ using System.Linq; using CommonIO; +using MediaBrowser.Model.Providers; namespace MediaBrowser.Controller.Providers { @@ -13,6 +14,7 @@ namespace MediaBrowser.Controller.Providers public bool IsPostRecursiveRefresh { get; set; } public MetadataRefreshMode MetadataRefreshMode { get; set; } + public RemoteSearchResult SearchResult { get; set; } public bool ForceSave { get; set; } @@ -37,6 +39,7 @@ namespace MediaBrowser.Controller.Providers ImageRefreshMode = copy.ImageRefreshMode; ReplaceAllImages = copy.ReplaceAllImages; ReplaceImages = copy.ReplaceImages.ToList(); + SearchResult = copy.SearchResult; } } } diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index c1ae43124d..8f7c93f32a 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -13,6 +13,7 @@ using System.Threading.Tasks; using CommonIO; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Model.Providers; namespace MediaBrowser.Providers.Manager { @@ -136,6 +137,11 @@ namespace MediaBrowser.Providers.Manager { var id = itemOfType.GetLookupInfo(); + if (refreshOptions.SearchResult != null) + { + ApplySearchResult(id, refreshOptions.SearchResult); + } + //await FindIdentities(id, cancellationToken).ConfigureAwait(false); id.IsAutomated = refreshOptions.IsAutomated; @@ -207,6 +213,13 @@ namespace MediaBrowser.Providers.Manager return updateType; } + private void ApplySearchResult(ItemLookupInfo lookupInfo, RemoteSearchResult result) + { + lookupInfo.ProviderIds = result.ProviderIds; + lookupInfo.Name = result.Name; + lookupInfo.Year = result.ProductionYear; + } + private async Task FindIdentities(TIdType id, CancellationToken cancellationToken) { try diff --git a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs index 75bec7b65d..894750c812 100644 --- a/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs +++ b/MediaBrowser.Providers/Omdb/OmdbItemProvider.cs @@ -60,9 +60,8 @@ namespace MediaBrowser.Providers.Omdb return GetSearchResultsInternal(searchInfo, type, true, cancellationToken); } - private async Task> GetSearchResultsInternal(ItemLookupInfo searchInfo, string type, bool enableMultipleResults, CancellationToken cancellationToken) + private async Task> GetSearchResultsInternal(ItemLookupInfo searchInfo, string type, bool isSearch, CancellationToken cancellationToken) { - bool isSearch = false; var episodeSearchInfo = searchInfo as EpisodeInfo; var list = new List(); @@ -95,10 +94,9 @@ namespace MediaBrowser.Providers.Omdb } // &s means search and returns a list of results as opposed to t - if (enableMultipleResults) + if (isSearch) { url += "&s=" + WebUtility.UrlEncode(name); - isSearch = true; } else { diff --git a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs index 3e4f4a70c6..25463b660e 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -344,6 +344,19 @@ namespace MediaBrowser.Server.Implementations.HttpServer LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent); } + if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) || + string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase)) + { + httpRes.RedirectToUrl(DefaultRedirectPath); + return Task.FromResult(true); + } + if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) || + string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase)) + { + httpRes.RedirectToUrl("emby/" + DefaultRedirectPath); + return Task.FromResult(true); + } + if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) || localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1 || @@ -363,16 +376,6 @@ namespace MediaBrowser.Server.Implementations.HttpServer } } - if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase)) - { - httpRes.RedirectToUrl(DefaultRedirectPath); - return Task.FromResult(true); - } - if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase)) - { - httpRes.RedirectToUrl("emby/" + DefaultRedirectPath); - return Task.FromResult(true); - } if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl(DefaultRedirectPath); diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index ef8efbe987..7fc54819dd 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -75,7 +75,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun lineup = lineup.Where(i => i.Favorite).ToList(); } - return lineup; + return lineup.Where(i => !i.DRM).ToList(); } } -- cgit v1.2.3 From e31aec4bc5bdda2731fcef9d1d85ccd0f41847f3 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 8 Apr 2016 14:32:38 -0400 Subject: update metadata refresh --- MediaBrowser.Controller/Channels/IChannelItem.cs | 11 ---- .../Channels/IChannelMediaItem.cs | 18 ----- MediaBrowser.Controller/Entities/BaseItem.cs | 3 + MediaBrowser.Controller/Entities/IHasImages.cs | 5 +- MediaBrowser.Controller/Entities/IHasMetadata.cs | 2 + .../MediaBrowser.Controller.csproj | 2 - .../Providers/IHasItemChangeMonitor.cs | 3 +- .../Folders/DefaultImageProvider.cs | 2 +- MediaBrowser.Providers/Manager/MetadataService.cs | 76 ++++++++++++++++++---- .../MediaInfo/AudioImageProvider.cs | 9 +-- .../MediaInfo/FFProbeProvider.cs | 6 +- .../MediaInfo/VideoImageProvider.cs | 6 +- MediaBrowser.Providers/Photos/PhotoProvider.cs | 6 +- .../TV/TheTVDB/TvdbSeriesImageProvider.cs | 4 +- .../Channels/ChannelImageProvider.cs | 2 +- .../Channels/ChannelManager.cs | 3 +- .../LiveTv/ChannelImageProvider.cs | 2 +- .../LiveTv/ProgramImageProvider.cs | 2 +- .../LiveTv/RecordingImageProvider.cs | 2 +- .../Persistence/SqliteItemRepository.cs | 23 ++++++- 20 files changed, 115 insertions(+), 72 deletions(-) delete mode 100644 MediaBrowser.Controller/Channels/IChannelItem.cs delete mode 100644 MediaBrowser.Controller/Channels/IChannelMediaItem.cs (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Controller/Channels/IChannelItem.cs b/MediaBrowser.Controller/Channels/IChannelItem.cs deleted file mode 100644 index 9b5f0359bd..0000000000 --- a/MediaBrowser.Controller/Channels/IChannelItem.cs +++ /dev/null @@ -1,11 +0,0 @@ -using MediaBrowser.Controller.Entities; - -namespace MediaBrowser.Controller.Channels -{ - public interface IChannelItem : IHasImages, IHasTags - { - string ChannelId { get; set; } - - string ExternalId { get; set; } - } -} diff --git a/MediaBrowser.Controller/Channels/IChannelMediaItem.cs b/MediaBrowser.Controller/Channels/IChannelMediaItem.cs deleted file mode 100644 index 60a29da90b..0000000000 --- a/MediaBrowser.Controller/Channels/IChannelMediaItem.cs +++ /dev/null @@ -1,18 +0,0 @@ -using MediaBrowser.Model.Channels; -using MediaBrowser.Model.Entities; -using System.Collections.Generic; - -namespace MediaBrowser.Controller.Channels -{ - public interface IChannelMediaItem : IChannelItem - { - long? RunTimeTicks { get; set; } - string MediaType { get; } - - ChannelMediaContentType ContentType { get; set; } - - ExtraType? ExtraType { get; set; } - - List ChannelMediaSources { get; set; } - } -} \ No newline at end of file diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index ba5da03d10..29f416b8c6 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -412,6 +412,9 @@ namespace MediaBrowser.Controller.Entities [IgnoreDataMember] public DateTime DateLastRefreshed { get; set; } + [IgnoreDataMember] + public DateTime? DateModifiedDuringLastRefresh { get; set; } + /// /// The logger /// diff --git a/MediaBrowser.Controller/Entities/IHasImages.cs b/MediaBrowser.Controller/Entities/IHasImages.cs index a38b7394dd..897250caa1 100644 --- a/MediaBrowser.Controller/Entities/IHasImages.cs +++ b/MediaBrowser.Controller/Entities/IHasImages.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Controller.Providers; +using System; +using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Entities; using System.Collections.Generic; using System.Threading; @@ -206,6 +207,8 @@ namespace MediaBrowser.Controller.Entities /// The image. /// The index. void SetImage(ItemImageInfo image, int index); + + DateTime? DateModifiedDuringLastRefresh { get; set; } } public static class HasImagesExtensions diff --git a/MediaBrowser.Controller/Entities/IHasMetadata.cs b/MediaBrowser.Controller/Entities/IHasMetadata.cs index 0e4ae04ff0..1f680b35f3 100644 --- a/MediaBrowser.Controller/Entities/IHasMetadata.cs +++ b/MediaBrowser.Controller/Entities/IHasMetadata.cs @@ -25,6 +25,8 @@ namespace MediaBrowser.Controller.Entities /// The date last saved. DateTime DateLastSaved { get; set; } + SourceType SourceType { get; set; } + /// /// Gets or sets the date last refreshed. /// diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 6f429ed2fc..235638b5f1 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -85,10 +85,8 @@ - - diff --git a/MediaBrowser.Controller/Providers/IHasItemChangeMonitor.cs b/MediaBrowser.Controller/Providers/IHasItemChangeMonitor.cs index 4c7069dd6d..9441c3ecde 100644 --- a/MediaBrowser.Controller/Providers/IHasItemChangeMonitor.cs +++ b/MediaBrowser.Controller/Providers/IHasItemChangeMonitor.cs @@ -8,9 +8,8 @@ namespace MediaBrowser.Controller.Providers /// Determines whether the specified item has changed. /// /// The item. - /// The status. /// The directory service. /// true if the specified item has changed; otherwise, false. - bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService); + bool HasChanged(IHasMetadata item, IDirectoryService directoryService); } } \ No newline at end of file diff --git a/MediaBrowser.Providers/Folders/DefaultImageProvider.cs b/MediaBrowser.Providers/Folders/DefaultImageProvider.cs index ee83efd26d..afd8c583d8 100644 --- a/MediaBrowser.Providers/Folders/DefaultImageProvider.cs +++ b/MediaBrowser.Providers/Folders/DefaultImageProvider.cs @@ -157,7 +157,7 @@ namespace MediaBrowser.Providers.Folders }); } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { return GetSupportedImages(item).Any(i => !item.HasImage(i)); } diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index 8f7c93f32a..47783ebc69 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -1,4 +1,5 @@ using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.IO; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -11,8 +12,11 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using CommonIO; +using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Controller.Playlists; using MediaBrowser.Model.Providers; namespace MediaBrowser.Providers.Manager @@ -68,6 +72,11 @@ namespace MediaBrowser.Providers.Manager result.ItemDateModified = item.DateModified; + if (EnableDateLastRefreshed(item)) + { + return Task.FromResult(true); + } + return ProviderRepo.SaveMetadataStatus(result, CancellationToken.None); } @@ -83,7 +92,22 @@ namespace MediaBrowser.Providers.Manager return new MetadataStatus { ItemId = item.Id }; } - return ProviderRepo.GetMetadataStatus(item.Id) ?? new MetadataStatus { ItemId = item.Id }; + if (EnableDateLastRefreshed(item) && item.DateModifiedDuringLastRefresh.HasValue) + { + return new MetadataStatus + { + ItemId = item.Id, + DateLastImagesRefresh = item.DateLastRefreshed, + DateLastMetadataRefresh = item.DateLastRefreshed, + ItemDateModified = item.DateModifiedDuringLastRefresh.Value + }; + } + + var result = ProviderRepo.GetMetadataStatus(item.Id) ?? new MetadataStatus { ItemId = item.Id }; + + item.DateModifiedDuringLastRefresh = result.ItemDateModified; + + return result; } public async Task RefreshMetadata(IHasMetadata item, MetadataRefreshOptions refreshOptions, CancellationToken cancellationToken) @@ -119,13 +143,20 @@ namespace MediaBrowser.Providers.Manager Item = itemOfType }; + bool hasRefreshedMetadata = false; + bool hasRefreshedImages = false; + // Next run metadata providers if (refreshOptions.MetadataRefreshMode != MetadataRefreshMode.None) { var providers = GetProviders(item, refreshResult, refreshOptions) .ToList(); - if (providers.Count > 0 || !refreshResult.DateLastMetadataRefresh.HasValue) + var dateLastRefresh = EnableDateLastRefreshed(item) + ? item.DateLastRefreshed + : refreshResult.DateLastMetadataRefresh ?? default(DateTime); + + if (providers.Count > 0 || dateLastRefresh == default(DateTime)) { if (item.BeforeMetadataRefresh()) { @@ -151,6 +182,7 @@ namespace MediaBrowser.Providers.Manager if (result.Failures == 0) { refreshResult.SetDateLastMetadataRefresh(DateTime.UtcNow); + hasRefreshedMetadata = true; } else { @@ -172,6 +204,7 @@ namespace MediaBrowser.Providers.Manager if (result.Failures == 0) { refreshResult.SetDateLastImagesRefresh(DateTime.UtcNow); + hasRefreshedImages = true; } else { @@ -194,9 +227,15 @@ namespace MediaBrowser.Providers.Manager updateType = updateType | ItemUpdateType.MetadataDownload; } - if (refreshOptions.MetadataRefreshMode >= MetadataRefreshMode.Default && refreshOptions.ImageRefreshMode >= ImageRefreshMode.Default) + if (hasRefreshedMetadata && hasRefreshedImages) { item.DateLastRefreshed = DateTime.UtcNow; + item.DateModifiedDuringLastRefresh = item.DateModified; + } + else + { + item.DateLastRefreshed = default(DateTime); + item.DateModifiedDuringLastRefresh = null; } // Save to database @@ -254,7 +293,12 @@ namespace MediaBrowser.Providers.Manager return true; } - if (item is BoxSet || (item is IItemByName && !(item is MusicArtist))) + if (item is BoxSet || item is IItemByName || item is Playlist) + { + return true; + } + + if (item.SourceType != SourceType.Library) { return true; } @@ -364,8 +408,12 @@ namespace MediaBrowser.Providers.Manager // Get providers to refresh var providers = ((ProviderManager)ProviderManager).GetMetadataProviders(item).ToList(); + var dateLastRefresh = EnableDateLastRefreshed(item) + ? item.DateLastRefreshed + : status.DateLastMetadataRefresh ?? default(DateTime); + // Run all if either of these flags are true - var runAllProviders = options.ReplaceAllMetadata || options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || !status.DateLastMetadataRefresh.HasValue; + var runAllProviders = options.ReplaceAllMetadata || options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || dateLastRefresh == default(DateTime); if (!runAllProviders) { @@ -384,7 +432,7 @@ namespace MediaBrowser.Providers.Manager var hasFileChangeMonitor = i as IHasItemChangeMonitor; if (hasFileChangeMonitor != null) { - return HasChanged(item, hasFileChangeMonitor, status, options.DirectoryService); + return HasChanged(item, hasFileChangeMonitor, options.DirectoryService); } return false; @@ -429,8 +477,12 @@ namespace MediaBrowser.Providers.Manager // Get providers to refresh var providers = allImageProviders.Where(i => !(i is ILocalImageProvider)).ToList(); + var dateLastImageRefresh = EnableDateLastRefreshed(item) + ? item.DateLastRefreshed + : status.DateLastImagesRefresh ?? default(DateTime); + // Run all if either of these flags are true - var runAllProviders = options.ImageRefreshMode == ImageRefreshMode.FullRefresh || !status.DateLastImagesRefresh.HasValue; + var runAllProviders = options.ImageRefreshMode == ImageRefreshMode.FullRefresh || dateLastImageRefresh == default(DateTime); if (!runAllProviders) { @@ -440,13 +492,13 @@ namespace MediaBrowser.Providers.Manager var hasChangeMonitor = i as IHasChangeMonitor; if (hasChangeMonitor != null) { - return HasChanged(item, hasChangeMonitor, status.DateLastImagesRefresh.Value, options.DirectoryService); + return HasChanged(item, hasChangeMonitor, dateLastImageRefresh, options.DirectoryService); } var hasFileChangeMonitor = i as IHasItemChangeMonitor; if (hasFileChangeMonitor != null) { - return HasChanged(item, hasFileChangeMonitor, status, options.DirectoryService); + return HasChanged(item, hasFileChangeMonitor, options.DirectoryService); } return false; @@ -558,7 +610,7 @@ namespace MediaBrowser.Providers.Manager if (options.MetadataRefreshMode != MetadataRefreshMode.FullRefresh) { // If the local provider fails don't continue with remote providers because the user's saved metadata could be lost - return refreshResult; + //return refreshResult; } } } @@ -738,11 +790,11 @@ namespace MediaBrowser.Providers.Manager } } - private bool HasChanged(IHasMetadata item, IHasItemChangeMonitor changeMonitor, MetadataStatus status, IDirectoryService directoryService) + private bool HasChanged(IHasMetadata item, IHasItemChangeMonitor changeMonitor, IDirectoryService directoryService) { try { - var hasChanged = changeMonitor.HasChanged(item, status, directoryService); + var hasChanged = changeMonitor.HasChanged(item, directoryService); //if (hasChanged) //{ diff --git a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs index af610520fd..aa495afbcf 100644 --- a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs @@ -159,14 +159,11 @@ namespace MediaBrowser.Providers.MediaInfo return item.LocationType == LocationType.FileSystem && audio != null && !audio.IsArchive; } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { - if (status.ItemDateModified.HasValue) + if (item.DateModifiedDuringLastRefresh.HasValue) { - if (status.ItemDateModified.Value != item.DateModified) - { - return true; - } + return item.DateModifiedDuringLastRefresh.Value != item.DateModified; } return false; diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs index a2d15d8634..9db4ab96e9 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeProvider.cs @@ -163,11 +163,11 @@ namespace MediaBrowser.Providers.MediaInfo return prober.Probe(item, cancellationToken); } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { - if (status.ItemDateModified.HasValue) + if (item.DateModifiedDuringLastRefresh.HasValue) { - if (status.ItemDateModified.Value != item.DateModified) + if (item.DateModifiedDuringLastRefresh.Value != item.DateModified) { return true; } diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs index f3235a1021..a5751da0aa 100644 --- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs @@ -151,11 +151,11 @@ namespace MediaBrowser.Providers.MediaInfo } } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { - if (status.ItemDateModified.HasValue) + if (item.DateModifiedDuringLastRefresh.HasValue) { - if (status.ItemDateModified.Value != item.DateModified) + if (item.DateModifiedDuringLastRefresh.Value != item.DateModified) { return true; } diff --git a/MediaBrowser.Providers/Photos/PhotoProvider.cs b/MediaBrowser.Providers/Photos/PhotoProvider.cs index ef31449589..882363b2f8 100644 --- a/MediaBrowser.Providers/Photos/PhotoProvider.cs +++ b/MediaBrowser.Providers/Photos/PhotoProvider.cs @@ -152,11 +152,11 @@ namespace MediaBrowser.Providers.Photos get { return "Embedded Information"; } } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { - if (status.ItemDateModified.HasValue) + if (item.DateModifiedDuringLastRefresh.HasValue) { - return status.ItemDateModified.Value != item.DateModified; + return item.DateModifiedDuringLastRefresh.Value != item.DateModified; } return false; diff --git a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesImageProvider.cs b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesImageProvider.cs index 011ed9ed01..d1cdc717e4 100644 --- a/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesImageProvider.cs +++ b/MediaBrowser.Providers/TV/TheTVDB/TvdbSeriesImageProvider.cs @@ -332,7 +332,7 @@ namespace MediaBrowser.Providers.TV }); } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { if (!TvdbSeriesProvider.Current.GetTvDbOptions().EnableAutomaticUpdates) { @@ -346,7 +346,7 @@ namespace MediaBrowser.Providers.TV var fileInfo = _fileSystem.GetFileInfo(imagesXmlPath); - return fileInfo.Exists && _fileSystem.GetLastWriteTimeUtc(fileInfo) > (status.DateLastMetadataRefresh ?? DateTime.MinValue); + return fileInfo.Exists && _fileSystem.GetLastWriteTimeUtc(fileInfo) > item.DateLastRefreshed; } return false; diff --git a/MediaBrowser.Server.Implementations/Channels/ChannelImageProvider.cs b/MediaBrowser.Server.Implementations/Channels/ChannelImageProvider.cs index f13c71c6df..c98f71ce2a 100644 --- a/MediaBrowser.Server.Implementations/Channels/ChannelImageProvider.cs +++ b/MediaBrowser.Server.Implementations/Channels/ChannelImageProvider.cs @@ -47,7 +47,7 @@ namespace MediaBrowser.Server.Implementations.Channels return ((ChannelManager)_channelManager).GetChannelProvider(channel); } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { return GetSupportedImages(item).Any(i => !item.HasImage(i)); } diff --git a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs index a206c19256..c9956c68a5 100644 --- a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs +++ b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs @@ -1406,7 +1406,8 @@ namespace MediaBrowser.Server.Implementations.Channels throw new ArgumentNullException("channel"); } - var result = GetAllChannels().FirstOrDefault(i => string.Equals(GetInternalChannelId(i.Name).ToString("N"), channel.ChannelId, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Name, channel.Name, StringComparison.OrdinalIgnoreCase)); + var result = GetAllChannels() + .FirstOrDefault(i => string.Equals(GetInternalChannelId(i.Name).ToString("N"), channel.ChannelId, StringComparison.OrdinalIgnoreCase) || string.Equals(i.Name, channel.Name, StringComparison.OrdinalIgnoreCase)); if (result == null) { diff --git a/MediaBrowser.Server.Implementations/LiveTv/ChannelImageProvider.cs b/MediaBrowser.Server.Implementations/LiveTv/ChannelImageProvider.cs index 24d38a63e0..dccc7aa932 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/ChannelImageProvider.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/ChannelImageProvider.cs @@ -77,7 +77,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv get { return 0; } } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { return GetSupportedImages(item).Any(i => !item.HasImage(i)); } diff --git a/MediaBrowser.Server.Implementations/LiveTv/ProgramImageProvider.cs b/MediaBrowser.Server.Implementations/LiveTv/ProgramImageProvider.cs index ab8ec720b2..3f0538bd0b 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/ProgramImageProvider.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/ProgramImageProvider.cs @@ -74,7 +74,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv } } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { var liveTvItem = item as LiveTvProgram; diff --git a/MediaBrowser.Server.Implementations/LiveTv/RecordingImageProvider.cs b/MediaBrowser.Server.Implementations/LiveTv/RecordingImageProvider.cs index fce3223ea9..25678c29d3 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/RecordingImageProvider.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/RecordingImageProvider.cs @@ -68,7 +68,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv get { return 0; } } - public bool HasChanged(IHasMetadata item, MetadataStatus status, IDirectoryService directoryService) + public bool HasChanged(IHasMetadata item, IDirectoryService directoryService) { var liveTvItem = item as ILiveTvRecording; diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index b6699d1648..a30ff66df0 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -223,6 +223,7 @@ namespace MediaBrowser.Server.Implementations.Persistence _connection.AddColumn(Logger, "TypedBaseItems", "TrailerTypes", "Text"); _connection.AddColumn(Logger, "TypedBaseItems", "CriticRating", "Float"); _connection.AddColumn(Logger, "TypedBaseItems", "CriticRatingSummary", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "DateModifiedDuringLastRefresh", "DATETIME"); PrepareStatements(); @@ -355,7 +356,8 @@ namespace MediaBrowser.Server.Implementations.Persistence "Studios", "Tags", "SourceType", - "TrailerTypes" + "TrailerTypes", + "DateModifiedDuringLastRefresh" }; private readonly string[] _mediaStreamSaveColumns = @@ -459,7 +461,8 @@ namespace MediaBrowser.Server.Implementations.Persistence "SourceType", "TrailerTypes", "CriticRating", - "CriticRatingSummary" + "CriticRatingSummary", + "DateModifiedDuringLastRefresh" }; _saveItemCommand = _connection.CreateCommand(); _saveItemCommand.CommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns.ToArray()) + ") values ("; @@ -752,7 +755,16 @@ namespace MediaBrowser.Server.Implementations.Persistence _saveItemCommand.GetParameter(index++).Value = item.CriticRating; _saveItemCommand.GetParameter(index++).Value = item.CriticRatingSummary; - + + if (!item.DateModifiedDuringLastRefresh.HasValue || item.DateModifiedDuringLastRefresh.Value == default(DateTime)) + { + _saveItemCommand.GetParameter(index++).Value = null; + } + else + { + _saveItemCommand.GetParameter(index++).Value = item.DateModifiedDuringLastRefresh.Value; + } + _saveItemCommand.Transaction = transaction; _saveItemCommand.ExecuteNonQuery(); @@ -1125,6 +1137,11 @@ namespace MediaBrowser.Server.Implementations.Persistence } } + if (!reader.IsDBNull(51)) + { + item.DateModifiedDuringLastRefresh = reader.GetDateTime(51).ToUniversalTime(); + } + return item; } -- cgit v1.2.3 From 5bddb226f6ad3e42c3c32199684c4382d8e1661d Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 12 Apr 2016 13:37:58 -0400 Subject: update hdhr stream --- MediaBrowser.Model/Dlna/StreamBuilder.cs | 4 ++++ .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index d28e21bf25..6bb2a9f827 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -509,6 +509,10 @@ namespace MediaBrowser.Model.Dlna private int GetAudioBitrate(int? maxTotalBitrate, int? targetAudioChannels, string targetAudioCodec, MediaStream audioStream) { var defaultBitrate = 128000; + if (StringHelper.EqualsIgnoreCase(targetAudioCodec, "ac3")) + { + defaultBitrate = 192000; + } if (targetAudioChannels.HasValue) { diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 3c1e4af361..638b4b9afe 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -354,8 +354,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun BufferMs = 0, Container = "ts", Id = profile, - SupportsDirectPlay = true, - SupportsDirectStream = true, + SupportsDirectPlay = false, + SupportsDirectStream = false, SupportsTranscoding = true }; -- cgit v1.2.3 From 57e3bb72f93baca695ba2b6670faec8ee0e1796b Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 14 Apr 2016 15:12:00 -0400 Subject: update stream selection --- MediaBrowser.Api/Playback/Hls/VideoHlsService.cs | 7 +++---- MediaBrowser.Api/Playback/MediaInfoService.cs | 21 +++++++++++++++++++-- MediaBrowser.Model/Dlna/StreamBuilder.cs | 10 +++++----- MediaBrowser.Model/Dlna/StreamInfoSorter.cs | 19 ++++++++++++++++++- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 4 +++- 5 files changed, 48 insertions(+), 13 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs b/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs index 610628ced9..5f427146e3 100644 --- a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs @@ -86,11 +86,10 @@ namespace MediaBrowser.Api.Playback.Hls // See if we can save come cpu cycles by avoiding encoding if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase)) { - return state.VideoStream != null && IsH264(state.VideoStream) ? - args + " -bsf:v h264_mp4toannexb" : - args; + // if h264_mp4toannexb is ever added, do not use it for live tv + return args; } - + var keyFrameArg = string.Format(" -force_key_frames \"expr:gte(t,n_forced*{0})\"", state.SegmentLength.ToString(UsCulture)); diff --git a/MediaBrowser.Api/Playback/MediaInfoService.cs b/MediaBrowser.Api/Playback/MediaInfoService.cs index 2bf61f90bd..ffe7c50c8e 100644 --- a/MediaBrowser.Api/Playback/MediaInfoService.cs +++ b/MediaBrowser.Api/Playback/MediaInfoService.cs @@ -227,7 +227,7 @@ namespace MediaBrowser.Api.Playback SetDeviceSpecificData(item, mediaSource, profile, auth, maxBitrate, startTimeTicks, mediaSourceId, audioStreamIndex, subtitleStreamIndex, result.PlaySessionId); } - SortMediaSources(result); + SortMediaSources(result, maxBitrate); } private void SetDeviceSpecificData(BaseItem item, @@ -375,7 +375,7 @@ namespace MediaBrowser.Api.Playback } } - private void SortMediaSources(PlaybackInfoResponse result) + private void SortMediaSources(PlaybackInfoResponse result, int? maxBitrate) { var originalList = result.MediaSources.ToList(); @@ -409,6 +409,23 @@ namespace MediaBrowser.Api.Playback return 1; } + }).ThenBy(i => + { + if (maxBitrate.HasValue) + { + if (i.Bitrate.HasValue) + { + if (i.Bitrate.Value <= maxBitrate.Value) + { + return 0; + } + + return 2; + } + } + + return 1; + }).ThenBy(originalList.IndexOf) .ToList(); } diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 09d762aaef..1e6b7c729d 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -55,7 +55,7 @@ namespace MediaBrowser.Model.Dlna stream.DeviceProfileId = options.Profile.Id; } - return GetOptimalStream(streams); + return GetOptimalStream(streams, options.GetMaxBitrate()); } public StreamInfo BuildVideoItem(VideoOptions options) @@ -88,12 +88,12 @@ namespace MediaBrowser.Model.Dlna stream.DeviceProfileId = options.Profile.Id; } - return GetOptimalStream(streams); + return GetOptimalStream(streams, options.GetMaxBitrate()); } - private StreamInfo GetOptimalStream(List streams) + private StreamInfo GetOptimalStream(List streams, int? maxBitrate) { - streams = StreamInfoSorter.SortMediaSources(streams); + streams = StreamInfoSorter.SortMediaSources(streams, maxBitrate); foreach (StreamInfo stream in streams) { @@ -424,7 +424,7 @@ namespace MediaBrowser.Model.Dlna playlistItem.EstimateContentLength = transcodingProfile.EstimateContentLength; playlistItem.TranscodeSeekInfo = transcodingProfile.TranscodeSeekInfo; - // TODO: We should probably preserve the full list and sent it tp the server that way + // TODO: We should probably preserve the full list and sent it to the server that way string[] supportedAudioCodecs = transcodingProfile.AudioCodec.Split(','); string inputAudioCodec = audioStream == null ? null : audioStream.Codec; foreach (string supportedAudioCodec in supportedAudioCodecs) diff --git a/MediaBrowser.Model/Dlna/StreamInfoSorter.cs b/MediaBrowser.Model/Dlna/StreamInfoSorter.cs index 0cccd80804..293054e5b3 100644 --- a/MediaBrowser.Model/Dlna/StreamInfoSorter.cs +++ b/MediaBrowser.Model/Dlna/StreamInfoSorter.cs @@ -7,7 +7,7 @@ namespace MediaBrowser.Model.Dlna { public class StreamInfoSorter { - public static List SortMediaSources(List streams) + public static List SortMediaSources(List streams, int? maxBitrate) { return streams.OrderBy(i => { @@ -41,6 +41,23 @@ namespace MediaBrowser.Model.Dlna return 1; } + }).ThenBy(i => + { + if (maxBitrate.HasValue) + { + if (i.MediaSource.Bitrate.HasValue) + { + if (i.MediaSource.Bitrate.Value <= maxBitrate.Value) + { + return 0; + } + + return 2; + } + } + + return 1; + }).ToList(); } } diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 638b4b9afe..3499fad413 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -246,6 +246,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun string audioCodec = "ac3"; int? videoBitrate = null; + int? audioBitrate = null; if (string.Equals(profile, "mobile", StringComparison.OrdinalIgnoreCase)) { @@ -306,6 +307,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun audioCodec = channel.AudioCodec; videoBitrate = (channel.IsHD ?? true) ? 15000000 : 2000000; + audioBitrate = (channel.IsHD ?? true) ? 448000 : 192000; } } @@ -346,7 +348,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun // Set the index to -1 because we don't know the exact index of the audio stream within the container Index = -1, Codec = audioCodec, - BitRate = 192000 + BitRate = audioBitrate } }, RequiresOpening = false, -- cgit v1.2.3 From cf4a14357ef8c602dd6dbfc0d8e9737ae0badaaa Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 16 Apr 2016 13:19:20 -0400 Subject: restore hdhr direct play for now --- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 3499fad413..4c140602d2 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -356,7 +356,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun BufferMs = 0, Container = "ts", Id = profile, - SupportsDirectPlay = false, + SupportsDirectPlay = true, SupportsDirectStream = false, SupportsTranscoding = true }; -- cgit v1.2.3 From 565b3350a125cf49cd288542bf28188ef906dd10 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 17 Apr 2016 16:57:57 -0400 Subject: update version --- MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index d33b2c51df..3c7ee55b7d 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -40,7 +40,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { onStarted(); - _logger.Info("Copying recording stream to file stream"); + _logger.Info("Copying recording stream to file {0}", targetFile); var durationToken = new CancellationTokenSource(duration); var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; @@ -48,6 +48,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, linkedToken).ConfigureAwait(false); } } + + _logger.Info("Recording completed to file {0}", targetFile); } } } -- cgit v1.2.3 From 0ebb82dc57fefcdf765855e3fda0dd0f90c43f33 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 18 Apr 2016 13:43:00 -0400 Subject: update NAL usage --- MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs | 2 +- MediaBrowser.Api/Playback/Hls/VideoHlsService.cs | 2 +- MediaBrowser.Api/Playback/Progressive/VideoService.cs | 2 +- MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs | 2 +- MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs | 9 ++++++++- .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 9 ++++++++- 6 files changed, 20 insertions(+), 6 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs index fa8f0c009b..bc155ff458 100644 --- a/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/DynamicHlsService.cs @@ -828,7 +828,7 @@ namespace MediaBrowser.Api.Playback.Hls // See if we can save come cpu cycles by avoiding encoding if (string.Equals(codec, "copy", StringComparison.OrdinalIgnoreCase)) { - if (state.VideoStream != null && IsH264(state.VideoStream) && !string.IsNullOrWhiteSpace(state.VideoStream.NalLengthSize)) + if (state.VideoStream != null && IsH264(state.VideoStream) && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase)) { Logger.Debug("Enabling h264_mp4toannexb due to nal_length_size of {0}", state.VideoStream.NalLengthSize); args += " -bsf:v h264_mp4toannexb"; diff --git a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs b/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs index 5709ca15ae..87b1c4248c 100644 --- a/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/VideoHlsService.cs @@ -87,7 +87,7 @@ namespace MediaBrowser.Api.Playback.Hls if (codec.Equals("copy", StringComparison.OrdinalIgnoreCase)) { // if h264_mp4toannexb is ever added, do not use it for live tv - if (state.VideoStream != null && IsH264(state.VideoStream) && !string.IsNullOrWhiteSpace(state.VideoStream.NalLengthSize)) + if (state.VideoStream != null && IsH264(state.VideoStream) && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase)) { Logger.Debug("Enabling h264_mp4toannexb due to nal_length_size of {0}", state.VideoStream.NalLengthSize); args += " -bsf:v h264_mp4toannexb"; diff --git a/MediaBrowser.Api/Playback/Progressive/VideoService.cs b/MediaBrowser.Api/Playback/Progressive/VideoService.cs index 6054a245ba..3319fbaec7 100644 --- a/MediaBrowser.Api/Playback/Progressive/VideoService.cs +++ b/MediaBrowser.Api/Playback/Progressive/VideoService.cs @@ -139,7 +139,7 @@ namespace MediaBrowser.Api.Playback.Progressive if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase)) { - if (state.VideoStream != null && IsH264(state.VideoStream) && string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(state.VideoStream.NalLengthSize)) + if (state.VideoStream != null && IsH264(state.VideoStream) && string.Equals(state.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase) && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase)) { Logger.Debug("Enabling h264_mp4toannexb due to nal_length_size of {0}", state.VideoStream.NalLengthSize); args += " -bsf:v h264_mp4toannexb"; diff --git a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs index 3a0526f43b..b8efedf09d 100644 --- a/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/VideoEncoder.cs @@ -73,7 +73,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (string.Equals(videoCodec, "copy", StringComparison.OrdinalIgnoreCase)) { - if (state.VideoStream != null && IsH264(state.VideoStream) && string.Equals(state.Options.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(state.VideoStream.NalLengthSize)) + if (state.VideoStream != null && IsH264(state.VideoStream) && string.Equals(state.Options.OutputContainer, "ts", StringComparison.OrdinalIgnoreCase) && !string.Equals(state.VideoStream.NalLengthSize, "0", StringComparison.OrdinalIgnoreCase)) { Logger.Debug("Enabling h264_mp4toannexb due to nal_length_size of {0}", state.VideoStream.NalLengthSize); args += " -bsf:v h264_mp4toannexb"; diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index d40f2a141d..ab2b59d482 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -511,8 +511,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv if (!(service is EmbyTV.EmbyTV)) { // We can't trust that we'll be able to direct stream it through emby server, no matter what the provider says - mediaSource.SupportsDirectStream = true; + mediaSource.SupportsDirectStream = false; mediaSource.SupportsTranscoding = true; + foreach (var stream in mediaSource.MediaStreams) + { + if (stream.Type == MediaStreamType.Video && string.IsNullOrWhiteSpace(stream.NalLengthSize)) + { + stream.NalLengthSize = "0"; + } + } } } diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 4c140602d2..469767c658 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -317,6 +317,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun videoCodec = "mpeg2video"; } + string nal = null; + if (string.Equals(videoCodec, "h264", StringComparison.OrdinalIgnoreCase)) + { + nal = "0"; + } + var url = GetApiUrl(info, true) + "/auto/v" + channelId; if (!string.IsNullOrWhiteSpace(profile) && !string.Equals(profile, "native", StringComparison.OrdinalIgnoreCase)) @@ -339,7 +345,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun Codec = videoCodec, Width = width, Height = height, - BitRate = videoBitrate + BitRate = videoBitrate, + NalLengthSize = nal }, new MediaStream -- cgit v1.2.3 From f3c3c74d84d81ada293ff10c2eabcd1be418f54f Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 21 Apr 2016 14:00:46 -0400 Subject: add probe property --- .../LiveTv/TunerHosts/BaseTunerHost.cs | 30 +++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs index 02a8d69387..9bb5b4fd7d 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/BaseTunerHost.cs @@ -224,7 +224,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts var stream = await GetChannelStream(host, channelId, streamId, cancellationToken).ConfigureAwait(false); - //await AddMediaInfo(stream, false, resourcePool, cancellationToken).ConfigureAwait(false); + if (EnableMediaProbing) + { + await AddMediaInfo(stream, false, resourcePool, cancellationToken).ConfigureAwait(false); + } + return new Tuple(stream, resourcePool); } catch (Exception ex) @@ -239,6 +243,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts throw new LiveTvConflictException(); } + protected virtual bool EnableMediaProbing + { + get { return false; } + } + protected async Task IsAvailable(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken) { try @@ -268,6 +277,25 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts return _semaphoreLocks.GetOrAdd(url, key => new SemaphoreSlim(1, 1)); } + private async Task AddMediaInfo(MediaSourceInfo mediaSource, bool isAudio, SemaphoreSlim resourcePool, CancellationToken cancellationToken) + { + await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + await AddMediaInfoInternal(mediaSource, isAudio, cancellationToken).ConfigureAwait(false); + + // Leave the resource locked. it will be released upstream + } + catch (Exception) + { + // Release the resource if there's some kind of failure. + resourcePool.Release(); + + throw; + } + } + private async Task AddMediaInfoInternal(MediaSourceInfo mediaSource, bool isAudio, CancellationToken cancellationToken) { var originalRuntime = mediaSource.RunTimeTicks; -- cgit v1.2.3 From 54e04dd027f75066981524f7db02664b3afed2ab Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 25 Apr 2016 22:16:46 -0400 Subject: support duration on recording url --- MediaBrowser.Controller/LiveTv/ITunerHost.cs | 2 ++ .../LiveTv/EmbyTV/DirectRecorder.cs | 9 ++++++--- .../LiveTv/EmbyTV/EmbyTV.cs | 23 ++++++++++++++++------ .../LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs | 8 ++++++++ .../LiveTv/TunerHosts/M3UTunerHost.cs | 5 +++++ .../LiveTv/TunerHosts/SatIp/SatIpHost.cs | 5 +++++ 6 files changed, 43 insertions(+), 9 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Controller/LiveTv/ITunerHost.cs b/MediaBrowser.Controller/LiveTv/ITunerHost.cs index 498602ddf9..1e7aa3de5a 100644 --- a/MediaBrowser.Controller/LiveTv/ITunerHost.cs +++ b/MediaBrowser.Controller/LiveTv/ITunerHost.cs @@ -46,6 +46,8 @@ namespace MediaBrowser.Controller.LiveTv /// The cancellation token. /// Task<List<MediaSourceInfo>>. Task> GetChannelStreamMediaSources(string channelId, CancellationToken cancellationToken); + + string ApplyDuration(string streamPath, TimeSpan duration); } public interface IConfigurableTunerHost { diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 3c7ee55b7d..98249f5ac9 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -42,10 +42,13 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _logger.Info("Copying recording stream to file {0}", targetFile); - var durationToken = new CancellationTokenSource(duration); - var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; + if (!mediaSource.RunTimeTicks.HasValue) + { + var durationToken = new CancellationTokenSource(duration); + cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; + } - await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, linkedToken).ConfigureAwait(false); + await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false); } } diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 60ff23b04b..d85e8ba3f9 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -591,7 +591,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV throw new ApplicationException("Tuner not found."); } - private async Task> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken) + private async Task> GetChannelStreamInternal(string channelId, string streamId, CancellationToken cancellationToken) { _logger.Info("Streaming Channel " + channelId); @@ -599,7 +599,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { try { - return await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false); + var result = await hostInstance.GetChannelStream(channelId, streamId, cancellationToken).ConfigureAwait(false); + + return new Tuple(result.Item1, hostInstance, result.Item2); } catch (Exception e) { @@ -797,8 +799,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV // HDHR doesn't seem to release the tuner right away after first probing with ffmpeg //await Task.Delay(3000, cancellationToken).ConfigureAwait(false); - var duration = recordingEndDate - DateTime.UtcNow; - var recorder = await GetRecorder().ConfigureAwait(false); if (recorder is EncodedRecorder) @@ -816,6 +816,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV recording.DateLastUpdated = DateTime.UtcNow; _recordingProvider.AddOrUpdate(recording); + var duration = recordingEndDate - DateTime.UtcNow; + _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); _logger.Info("Writing file to path: " + recordPath); @@ -823,10 +825,19 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV Action onStarted = () => { - result.Item2.Release(); + result.Item3.Release(); isResourceOpen = false; }; + var pathWithDuration = result.Item2.ApplyDuration(mediaStreamInfo.Path, duration); + + // If it supports supplying duration via url + if (!string.Equals(pathWithDuration, mediaStreamInfo.Path, StringComparison.OrdinalIgnoreCase)) + { + mediaStreamInfo.Path = pathWithDuration; + mediaStreamInfo.RunTimeTicks = duration.Ticks; + } + await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken).ConfigureAwait(false); recording.Status = RecordingStatus.Completed; @@ -836,7 +847,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { if (isResourceOpen) { - result.Item2.Release(); + result.Item3.Release(); } _libraryMonitor.ReportFileSystemChangeComplete(recordPath, false); diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs index 469767c658..a3e5589e88 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/HdHomerun/HdHomerunHost.cs @@ -59,6 +59,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.HdHomerun return id; } + public string ApplyDuration(string streamPath, TimeSpan duration) + { + streamPath += streamPath.IndexOf('?') == -1 ? "?" : "&"; + streamPath += "duration=" + Convert.ToInt32(duration.TotalSeconds).ToString(CultureInfo.InvariantCulture); + + return streamPath; + } + private async Task> GetLineup(TunerHostInfo info, CancellationToken cancellationToken) { var options = new HttpRequestOptions diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index 523f14dfc8..c874e51b61 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -146,5 +146,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts { return Task.FromResult(true); } + + public string ApplyDuration(string streamPath, TimeSpan duration) + { + return streamPath; + } } } diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs index ffd85fd18a..1e571c84fb 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs @@ -164,5 +164,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp return list; } + + public string ApplyDuration(string streamPath, TimeSpan duration) + { + return streamPath; + } } } -- cgit v1.2.3 From 747518decc3e59a9c6b01f31e5360ce194919d8d Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 27 Apr 2016 17:26:28 -0400 Subject: added option to preserve original audio when recording --- MediaBrowser.Model/LiveTv/LiveTvOptions.cs | 1 + MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs | 6 ++++-- .../LiveTv/EmbyTV/EncodedRecorder.cs | 7 +++++-- 3 files changed, 10 insertions(+), 4 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs index 46f630fe04..fc2b155ecd 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs @@ -9,6 +9,7 @@ namespace MediaBrowser.Model.LiveTv public string RecordingPath { get; set; } public bool EnableAutoOrganize { get; set; } public bool EnableRecordingEncoding { get; set; } + public bool EnableOriginalAudioWithEncodedRecordings { get; set; } public List TunerHosts { get; set; } public List ListingProviders { get; set; } diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index d85e8ba3f9..351bc05af6 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -927,13 +927,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV private async Task GetRecorder() { - if (GetConfiguration().EnableRecordingEncoding) + var config = GetConfiguration(); + + if (config.EnableRecordingEncoding) { var regInfo = await _security.GetRegistrationStatus("embytvrecordingconversion").ConfigureAwait(false); if (regInfo.IsValid) { - return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer); + return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer, config); } } diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 442f151dd0..63d0846fc1 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -12,6 +12,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; +using MediaBrowser.Model.LiveTv; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Serialization; @@ -23,6 +24,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV private readonly IFileSystem _fileSystem; private readonly IMediaEncoder _mediaEncoder; private readonly IApplicationPaths _appPaths; + private readonly LiveTvOptions _liveTvOptions; private bool _hasExited; private Stream _logFileStream; private string _targetPath; @@ -30,13 +32,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV private readonly IJsonSerializer _json; private readonly TaskCompletionSource _taskCompletionSource = new TaskCompletionSource(); - public EncodedRecorder(ILogger logger, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IApplicationPaths appPaths, IJsonSerializer json) + public EncodedRecorder(ILogger logger, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IApplicationPaths appPaths, IJsonSerializer json, LiveTvOptions liveTvOptions) { _logger = logger; _fileSystem = fileSystem; _mediaEncoder = mediaEncoder; _appPaths = appPaths; _json = json; + _liveTvOptions = liveTvOptions; } public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) @@ -129,7 +132,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { var copyAudio = new[] { "aac", "mp3" }; var mediaStreams = mediaSource.MediaStreams ?? new List(); - if (mediaStreams.Any(i => i.Type == MediaStreamType.Audio && copyAudio.Contains(i.Codec, StringComparer.OrdinalIgnoreCase))) + if (_liveTvOptions.EnableOriginalAudioWithEncodedRecordings || mediaStreams.Any(i => i.Type == MediaStreamType.Audio && copyAudio.Contains(i.Codec, StringComparer.OrdinalIgnoreCase))) { return "-codec:a:0 copy"; } -- cgit v1.2.3 From 8537cbe6c2e1b6a5508d3f13bf0ec0224e88b452 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 29 Apr 2016 12:54:26 -0400 Subject: add audio sync to converted recordings --- MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 63d0846fc1..fa4f821364 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -143,7 +143,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { audioChannels = audioStream.Channels ?? audioChannels; } - return "-codec:a:0 aac -strict experimental -ab 320000"; + return "-codec:a:0 aac -strict experimental -ab 320000 -af \"async=1000\""; } private bool EncodeVideo(MediaSourceInfo mediaSource) -- cgit v1.2.3 From 5d28c65783f850db58ea990a04ec09da38c24442 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 30 Apr 2016 00:00:28 -0400 Subject: update recordings --- .../LiveTv/EmbyTV/DirectRecorder.cs | 10 +++++++++- .../LiveTv/EmbyTV/EncodedRecorder.cs | 14 ++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 98249f5ac9..54443d9ca3 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -42,8 +42,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _logger.Info("Copying recording stream to file {0}", targetFile); - if (!mediaSource.RunTimeTicks.HasValue) + if (mediaSource.RunTimeTicks.HasValue) { + // The media source already has a fixed duration + // But add another stop 1 minute later just in case the recording gets stuck for any reason + var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMinutes(1))); + cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; + } + else + { + // The media source if infinite so we need to handle stopping ourselves var durationToken = new CancellationTokenSource(duration); cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; } diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index fa4f821364..d589b2bc38 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -44,6 +44,20 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) { + if (mediaSource.RunTimeTicks.HasValue) + { + // The media source already has a fixed duration + // But add another stop 1 minute later just in case the recording gets stuck for any reason + var durationToken = new CancellationTokenSource(duration.Add(TimeSpan.FromMinutes(1))); + cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; + } + else + { + // The media source if infinite so we need to handle stopping ourselves + var durationToken = new CancellationTokenSource(duration); + cancellationToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; + } + _targetPath = targetFile; _fileSystem.CreateDirectory(Path.GetDirectoryName(targetFile)); -- cgit v1.2.3 From 1f9d32afc52e9bd133ddf22d12bdc468adaf9ebe Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 30 Apr 2016 18:05:13 -0400 Subject: limit use of GetUserDataKey --- MediaBrowser.Api/Movies/MoviesService.cs | 4 ++-- .../UserLibrary/BaseItemsByNameService.cs | 8 +++---- MediaBrowser.Api/UserLibrary/UserLibraryService.cs | 8 ++----- MediaBrowser.Controller/Entities/BaseItem.cs | 14 +++++------- MediaBrowser.Controller/Entities/Folder.cs | 2 +- .../Entities/UserViewBuilder.cs | 10 ++++----- .../Library/IUserDataManager.cs | 5 +++++ .../ContentDirectory/ControlHandler.cs | 2 +- .../Channels/ChannelManager.cs | 12 +++++------ .../Dto/DtoService.cs | 4 ++-- .../Library/MediaSourceManager.cs | 2 +- .../Library/UserDataManager.cs | 15 +++++++++++++ .../LiveTv/LiveTvManager.cs | 12 +++++------ .../Session/SessionManager.cs | 25 ++++++++-------------- .../Sorting/DatePlayedComparer.cs | 2 +- .../Sorting/PlayCountComparer.cs | 2 +- .../Sync/SyncManager.cs | 2 +- .../TV/TVSeriesManager.cs | 4 ++-- MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs | 2 +- 19 files changed, 70 insertions(+), 65 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Api/Movies/MoviesService.cs b/MediaBrowser.Api/Movies/MoviesService.cs index 065f882687..bfbb3a6d75 100644 --- a/MediaBrowser.Api/Movies/MoviesService.cs +++ b/MediaBrowser.Api/Movies/MoviesService.cs @@ -247,7 +247,7 @@ namespace MediaBrowser.Api.Movies var recentlyPlayedMovies = allMoviesForCategories .Select(i => { - var userdata = _userDataRepository.GetUserData(user.Id, i.GetUserDataKey()); + var userdata = _userDataRepository.GetUserData(user, i); return new Tuple(i, userdata.Played, userdata.LastPlayedDate ?? DateTime.MinValue); }) .Where(i => i.Item2) @@ -260,7 +260,7 @@ namespace MediaBrowser.Api.Movies .Select(i => { var score = 0; - var userData = _userDataRepository.GetUserData(user.Id, i.GetUserDataKey()); + var userData = _userDataRepository.GetUserData(user, i); if (userData.IsFavorite) { diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs index 6ae2b08322..b3164ce3f7 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs @@ -274,7 +274,7 @@ namespace MediaBrowser.Api.UserLibrary { items = items.Where(i => { - var userdata = UserDataRepository.GetUserData(user.Id, i.GetUserDataKey()); + var userdata = UserDataRepository.GetUserData(user, i); return userdata != null && userdata.Likes.HasValue && !userdata.Likes.Value; }); @@ -284,7 +284,7 @@ namespace MediaBrowser.Api.UserLibrary { items = items.Where(i => { - var userdata = UserDataRepository.GetUserData(user.Id, i.GetUserDataKey()); + var userdata = UserDataRepository.GetUserData(user, i); return userdata != null && userdata.Likes.HasValue && userdata.Likes.Value; }); @@ -294,7 +294,7 @@ namespace MediaBrowser.Api.UserLibrary { items = items.Where(i => { - var userdata = UserDataRepository.GetUserData(user.Id, i.GetUserDataKey()); + var userdata = UserDataRepository.GetUserData(user, i); var likes = userdata.Likes ?? false; var favorite = userdata.IsFavorite; @@ -307,7 +307,7 @@ namespace MediaBrowser.Api.UserLibrary { items = items.Where(i => { - var userdata = UserDataRepository.GetUserData(user.Id, i.GetUserDataKey()); + var userdata = UserDataRepository.GetUserData(user, i); return userdata != null && userdata.IsFavorite; }); diff --git a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs index c2c481cb6f..8cc5cab358 100644 --- a/MediaBrowser.Api/UserLibrary/UserLibraryService.cs +++ b/MediaBrowser.Api/UserLibrary/UserLibraryService.cs @@ -519,10 +519,8 @@ namespace MediaBrowser.Api.UserLibrary var item = string.IsNullOrEmpty(itemId) ? user.RootFolder : _libraryManager.GetItemById(itemId); - var key = item.GetUserDataKey(); - // Get the user data for this item - var data = _userDataRepository.GetUserData(user.Id, key); + var data = _userDataRepository.GetUserData(user, item); // Set favorite status data.IsFavorite = isFavorite; @@ -567,10 +565,8 @@ namespace MediaBrowser.Api.UserLibrary var item = string.IsNullOrEmpty(itemId) ? user.RootFolder : _libraryManager.GetItemById(itemId); - var key = item.GetUserDataKey(); - // Get the user data for this item - var data = _userDataRepository.GetUserData(user.Id, key); + var data = _userDataRepository.GetUserData(user, item); data.Likes = likes; diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 9171c2a716..4828426fdc 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1617,9 +1617,7 @@ namespace MediaBrowser.Controller.Entities throw new ArgumentNullException(); } - var key = GetUserDataKey(); - - var data = UserDataManager.GetUserData(user.Id, key); + var data = UserDataManager.GetUserData(user, this); if (datePlayed.HasValue) { @@ -1654,9 +1652,7 @@ namespace MediaBrowser.Controller.Entities throw new ArgumentNullException(); } - var key = GetUserDataKey(); - - var data = UserDataManager.GetUserData(user.Id, key); + var data = UserDataManager.GetUserData(user, this); //I think it is okay to do this here. // if this is only called when a user is manually forcing something to un-played @@ -1987,14 +1983,14 @@ namespace MediaBrowser.Controller.Entities public virtual bool IsPlayed(User user) { - var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey()); + var userdata = UserDataManager.GetUserData(user, this); return userdata != null && userdata.Played; } public bool IsFavoriteOrLiked(User user) { - var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey()); + var userdata = UserDataManager.GetUserData(user, this); return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false)); } @@ -2006,7 +2002,7 @@ namespace MediaBrowser.Controller.Entities throw new ArgumentNullException("user"); } - var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey()); + var userdata = UserDataManager.GetUserData(user, this); return userdata == null || !userdata.Played; } diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index f4cdc8fa1b..41f0c02bdc 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -1635,7 +1635,7 @@ namespace MediaBrowser.Controller.Entities var isUnplayed = true; - var itemUserData = UserDataManager.GetUserData(user.Id, child.GetUserDataKey()); + var itemUserData = UserDataManager.GetUserData(user, child); // Incrememt totalPercentPlayed if (itemUserData != null) diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index db669ca37d..5a0e0b614b 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -348,7 +348,7 @@ namespace MediaBrowser.Controller.Entities .Where(i => !i.IsFolder) .OfType(); - var artists = _libraryManager.GetAlbumArtists(items).Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite); + var artists = _libraryManager.GetAlbumArtists(items).Where(i => _userDataManager.GetUserData(user, i).IsFavorite); return GetResult(artists, parent, query); } @@ -1218,7 +1218,7 @@ namespace MediaBrowser.Controller.Entities if (query.IsLiked.HasValue) { - userData = userData ?? userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + userData = userData ?? userDataManager.GetUserData(user, item); if (!userData.Likes.HasValue || userData.Likes != query.IsLiked.Value) { @@ -1228,7 +1228,7 @@ namespace MediaBrowser.Controller.Entities if (query.IsFavoriteOrLiked.HasValue) { - userData = userData ?? userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + userData = userData ?? userDataManager.GetUserData(user, item); var isFavoriteOrLiked = userData.IsFavorite || (userData.Likes ?? false); if (isFavoriteOrLiked != query.IsFavoriteOrLiked.Value) @@ -1239,7 +1239,7 @@ namespace MediaBrowser.Controller.Entities if (query.IsFavorite.HasValue) { - userData = userData ?? userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + userData = userData ?? userDataManager.GetUserData(user, item); if (userData.IsFavorite != query.IsFavorite.Value) { @@ -1249,7 +1249,7 @@ namespace MediaBrowser.Controller.Entities if (query.IsResumable.HasValue) { - userData = userData ?? userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + userData = userData ?? userDataManager.GetUserData(user, item); var isResumable = userData.PlaybackPositionTicks > 0; if (isResumable != query.IsResumable.Value) diff --git a/MediaBrowser.Controller/Library/IUserDataManager.cs b/MediaBrowser.Controller/Library/IUserDataManager.cs index 56ac14e9df..4ff0f6439f 100644 --- a/MediaBrowser.Controller/Library/IUserDataManager.cs +++ b/MediaBrowser.Controller/Library/IUserDataManager.cs @@ -45,6 +45,11 @@ namespace MediaBrowser.Controller.Library /// Task{UserItemData}. UserItemData GetUserData(Guid userId, string key); + UserItemData GetUserData(IHasUserData user, IHasUserData item); + + UserItemData GetUserData(string userId, IHasUserData item); + UserItemData GetUserData(Guid userId, IHasUserData item); + /// /// Gets the user data dto. /// diff --git a/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs b/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs index 34fb2a6df7..bc9fa1d7e7 100644 --- a/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs +++ b/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs @@ -111,7 +111,7 @@ namespace MediaBrowser.Dlna.ContentDirectory var newbookmark = int.Parse(sparams["PosSecond"], _usCulture); - var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + var userdata = _userDataManager.GetUserData(user, item); userdata.PlaybackPositionTicks = TimeSpan.FromSeconds(newbookmark).Ticks; diff --git a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs index c9956c68a5..6a9842cb2e 100644 --- a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs +++ b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs @@ -133,7 +133,7 @@ namespace MediaBrowser.Server.Implementations.Channels if (query.IsFavorite.HasValue) { var val = query.IsFavorite.Value; - channels = channels.Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val) + channels = channels.Where(i => _userDataManager.GetUserData(user, i).IsFavorite == val) .ToList(); } @@ -1437,7 +1437,7 @@ namespace MediaBrowser.Server.Implementations.Channels case ItemFilter.IsFavoriteOrLikes: return items.Where(item => { - var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + var userdata = _userDataManager.GetUserData(user, item); if (userdata == null) { @@ -1453,7 +1453,7 @@ namespace MediaBrowser.Server.Implementations.Channels case ItemFilter.Likes: return items.Where(item => { - var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + var userdata = _userDataManager.GetUserData(user, item); return userdata != null && userdata.Likes.HasValue && userdata.Likes.Value; }); @@ -1461,7 +1461,7 @@ namespace MediaBrowser.Server.Implementations.Channels case ItemFilter.Dislikes: return items.Where(item => { - var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + var userdata = _userDataManager.GetUserData(user, item); return userdata != null && userdata.Likes.HasValue && !userdata.Likes.Value; }); @@ -1469,7 +1469,7 @@ namespace MediaBrowser.Server.Implementations.Channels case ItemFilter.IsFavorite: return items.Where(item => { - var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + var userdata = _userDataManager.GetUserData(user, item); return userdata != null && userdata.IsFavorite; }); @@ -1477,7 +1477,7 @@ namespace MediaBrowser.Server.Implementations.Channels case ItemFilter.IsResumable: return items.Where(item => { - var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + var userdata = _userDataManager.GetUserData(user, item); return userdata != null && userdata.PlaybackPositionTicks > 0; }); diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index 7adde5c273..b19f5727c8 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -487,7 +487,7 @@ namespace MediaBrowser.Server.Implementations.Dto { if (item.IsFolder) { - var userData = _userDataRepository.GetUserData(user.Id, item.GetUserDataKey()); + var userData = _userDataRepository.GetUserData(user, item); // Skip the user data manager because we've already looped through the recursive tree and don't want to do it twice // TODO: Improve in future @@ -1686,7 +1686,7 @@ namespace MediaBrowser.Server.Implementations.Dto dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max(); } - var userdata = _userDataRepository.GetUserData(user.Id, child.GetUserDataKey()); + var userdata = _userDataRepository.GetUserData(user, child); recursiveItemCount++; diff --git a/MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs b/MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs index 092b797ce7..a47fcdf4f8 100644 --- a/MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs +++ b/MediaBrowser.Server.Implementations/Library/MediaSourceManager.cs @@ -267,7 +267,7 @@ namespace MediaBrowser.Server.Implementations.Library private void SetUserProperties(IHasUserData item, MediaSourceInfo source, User user) { - var userData = item == null ? new UserItemData() : _userDataManager.GetUserData(user.Id, item.GetUserDataKey()); + var userData = item == null ? new UserItemData() : _userDataManager.GetUserData(user, item); var allowRememberingSelection = item == null || item.EnableRememberingTrackSelections; diff --git a/MediaBrowser.Server.Implementations/Library/UserDataManager.cs b/MediaBrowser.Server.Implementations/Library/UserDataManager.cs index ae737d2446..c16beed8cc 100644 --- a/MediaBrowser.Server.Implementations/Library/UserDataManager.cs +++ b/MediaBrowser.Server.Implementations/Library/UserDataManager.cs @@ -172,6 +172,21 @@ namespace MediaBrowser.Server.Implementations.Library return userId + key; } + public UserItemData GetUserData(IHasUserData user, IHasUserData item) + { + return GetUserData(user.Id, item.GetUserDataKey()); + } + + public UserItemData GetUserData(string userId, IHasUserData item) + { + return GetUserData(userId, item.GetUserDataKey()); + } + + public UserItemData GetUserData(Guid userId, IHasUserData item) + { + return GetUserData(userId, item.GetUserDataKey()); + } + public UserItemDataDto GetUserDataDto(IHasUserData item, User user) { var userData = GetUserData(user.Id, item.GetUserDataKey()); diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index ab2b59d482..eec8328f89 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -164,7 +164,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv var val = query.IsFavorite.Value; channels = channels - .Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val); + .Where(i => _userDataManager.GetUserData(user, i).IsFavorite == val); } if (query.IsLiked.HasValue) @@ -174,7 +174,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv channels = channels .Where(i => { - var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes; + var likes = _userDataManager.GetUserData(user, i).Likes; return likes.HasValue && likes.Value == val; }); @@ -187,7 +187,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv channels = channels .Where(i => { - var likes = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).Likes; + var likes = _userDataManager.GetUserData(user, i).Likes; return likes.HasValue && likes.Value != val; }); @@ -200,7 +200,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv { if (enableFavoriteSorting) { - var userData = _userDataManager.GetUserData(user.Id, i.GetUserDataKey()); + var userData = _userDataManager.GetUserData(user, i); if (userData.IsFavorite) { @@ -1005,7 +1005,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv var channel = GetInternalChannel(program.ChannelId); - var channelUserdata = _userDataManager.GetUserData(userId, channel.GetUserDataKey()); + var channelUserdata = _userDataManager.GetUserData(userId, channel); if (channelUserdata.Likes ?? false) { @@ -1036,7 +1036,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv if (genres.TryGetValue(i, out genre)) { - var genreUserdata = _userDataManager.GetUserData(userId, genre.GetUserDataKey()); + var genreUserdata = _userDataManager.GetUserData(userId, genre); if (genreUserdata.Likes ?? false) { diff --git a/MediaBrowser.Server.Implementations/Session/SessionManager.cs b/MediaBrowser.Server.Implementations/Session/SessionManager.cs index 88f11c3685..014e8babf9 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionManager.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionManager.cs @@ -601,11 +601,9 @@ namespace MediaBrowser.Server.Implementations.Session if (libraryItem != null) { - var key = libraryItem.GetUserDataKey(); - foreach (var user in users) { - await OnPlaybackStart(user.Id, key, libraryItem).ConfigureAwait(false); + await OnPlaybackStart(user.Id, libraryItem).ConfigureAwait(false); } } @@ -632,12 +630,11 @@ namespace MediaBrowser.Server.Implementations.Session /// Called when [playback start]. /// /// The user identifier. - /// The user data key. /// The item. /// Task. - private async Task OnPlaybackStart(Guid userId, string userDataKey, IHasUserData item) + private async Task OnPlaybackStart(Guid userId, IHasUserData item) { - var data = _userDataRepository.GetUserData(userId, userDataKey); + var data = _userDataRepository.GetUserData(userId, item); data.PlayCount++; data.LastPlayedDate = DateTime.UtcNow; @@ -676,11 +673,9 @@ namespace MediaBrowser.Server.Implementations.Session if (libraryItem != null) { - var key = libraryItem.GetUserDataKey(); - foreach (var user in users) { - await OnPlaybackProgress(user, key, libraryItem, info).ConfigureAwait(false); + await OnPlaybackProgress(user, libraryItem, info).ConfigureAwait(false); } } @@ -714,9 +709,9 @@ namespace MediaBrowser.Server.Implementations.Session StartIdleCheckTimer(); } - private async Task OnPlaybackProgress(User user, string userDataKey, BaseItem item, PlaybackProgressInfo info) + private async Task OnPlaybackProgress(User user, BaseItem item, PlaybackProgressInfo info) { - var data = _userDataRepository.GetUserData(user.Id, userDataKey); + var data = _userDataRepository.GetUserData(user.Id, item); var positionTicks = info.PositionTicks; @@ -811,11 +806,9 @@ namespace MediaBrowser.Server.Implementations.Session if (libraryItem != null) { - var key = libraryItem.GetUserDataKey(); - foreach (var user in users) { - playedToCompletion = await OnPlaybackStopped(user.Id, key, libraryItem, info.PositionTicks, info.Failed).ConfigureAwait(false); + playedToCompletion = await OnPlaybackStopped(user.Id, libraryItem, info.PositionTicks, info.Failed).ConfigureAwait(false); } } @@ -848,13 +841,13 @@ namespace MediaBrowser.Server.Implementations.Session await SendPlaybackStoppedNotification(session, CancellationToken.None).ConfigureAwait(false); } - private async Task OnPlaybackStopped(Guid userId, string userDataKey, BaseItem item, long? positionTicks, bool playbackFailed) + private async Task OnPlaybackStopped(Guid userId, BaseItem item, long? positionTicks, bool playbackFailed) { bool playedToCompletion = false; if (!playbackFailed) { - var data = _userDataRepository.GetUserData(userId, userDataKey); + var data = _userDataRepository.GetUserData(userId, item); if (positionTicks.HasValue) { diff --git a/MediaBrowser.Server.Implementations/Sorting/DatePlayedComparer.cs b/MediaBrowser.Server.Implementations/Sorting/DatePlayedComparer.cs index c881591beb..3edf23020a 100644 --- a/MediaBrowser.Server.Implementations/Sorting/DatePlayedComparer.cs +++ b/MediaBrowser.Server.Implementations/Sorting/DatePlayedComparer.cs @@ -47,7 +47,7 @@ namespace MediaBrowser.Server.Implementations.Sorting /// DateTime. private DateTime GetDate(BaseItem x) { - var userdata = UserDataRepository.GetUserData(User.Id, x.GetUserDataKey()); + var userdata = UserDataRepository.GetUserData(User, x); if (userdata != null && userdata.LastPlayedDate.HasValue) { diff --git a/MediaBrowser.Server.Implementations/Sorting/PlayCountComparer.cs b/MediaBrowser.Server.Implementations/Sorting/PlayCountComparer.cs index 1bc5261b44..8b14efffcf 100644 --- a/MediaBrowser.Server.Implementations/Sorting/PlayCountComparer.cs +++ b/MediaBrowser.Server.Implementations/Sorting/PlayCountComparer.cs @@ -34,7 +34,7 @@ namespace MediaBrowser.Server.Implementations.Sorting /// DateTime. private int GetValue(BaseItem x) { - var userdata = UserDataRepository.GetUserData(User.Id, x.GetUserDataKey()); + var userdata = UserDataRepository.GetUserData(User, x); return userdata == null ? 0 : userdata.PlayCount; } diff --git a/MediaBrowser.Server.Implementations/Sync/SyncManager.cs b/MediaBrowser.Server.Implementations/Sync/SyncManager.cs index fe1a7fb28f..38edc30240 100644 --- a/MediaBrowser.Server.Implementations/Sync/SyncManager.cs +++ b/MediaBrowser.Server.Implementations/Sync/SyncManager.cs @@ -687,7 +687,7 @@ namespace MediaBrowser.Server.Implementations.Sync private Task ReportOfflinePlayedItem(UserAction action) { var item = _libraryManager.GetItemById(action.ItemId); - var userData = _userDataManager.GetUserData(new Guid(action.UserId), item.GetUserDataKey()); + var userData = _userDataManager.GetUserData(action.UserId, item); userData.LastPlayedDate = action.Date; _userDataManager.UpdatePlayState(item, userData, action.PositionTicks); diff --git a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs index 3e43ebe9b8..dc880d84b5 100644 --- a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs +++ b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs @@ -85,7 +85,7 @@ namespace MediaBrowser.Server.Implementations.TV { var episode = i.Item1; - var seriesUserData = _userDataManager.GetUserData(user.Id, episode.Series.GetUserDataKey()); + var seriesUserData = _userDataManager.GetUserData(user, episode.Series); if (seriesUserData.IsFavorite) { @@ -128,7 +128,7 @@ namespace MediaBrowser.Server.Implementations.TV // Go back starting with the most recent episodes foreach (var episode in allEpisodes) { - var userData = _userDataManager.GetUserData(user.Id, episode.GetUserDataKey()); + var userData = _userDataManager.GetUserData(user, episode); if (userData.Played) { diff --git a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs index 6d15d168d1..d2e09d4ebf 100644 --- a/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs +++ b/MediaBrowser.XbmcMetadata/Savers/BaseNfoSaver.cs @@ -936,7 +936,7 @@ namespace MediaBrowser.XbmcMetadata.Savers return; } - var userdata = userDataRepo.GetUserData(user.Id, item.GetUserDataKey()); + var userdata = userDataRepo.GetUserData(user, item); writer.WriteElementString("isuserfavorite", userdata.IsFavorite.ToString().ToLower()); -- cgit v1.2.3 From fdc37a2b5879f4c96c59fa00d330385d919f8b8b Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 3 May 2016 00:17:57 -0400 Subject: update recording audio sync --- MediaBrowser.Model/Connect/ConnectUser.cs | 1 - MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs | 6 ++++++ .../LiveTv/EmbyTV/EncodedRecorder.cs | 4 ++-- .../LiveTv/TunerHosts/M3UTunerHost.cs | 4 +++- Nuget/MediaBrowser.Common.Internal.nuspec | 4 ++-- Nuget/MediaBrowser.Common.nuspec | 2 +- Nuget/MediaBrowser.Model.Signed.nuspec | 2 +- Nuget/MediaBrowser.Server.Core.nuspec | 4 ++-- 8 files changed, 17 insertions(+), 10 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Model/Connect/ConnectUser.cs b/MediaBrowser.Model/Connect/ConnectUser.cs index 383261a6b7..da290da120 100644 --- a/MediaBrowser.Model/Connect/ConnectUser.cs +++ b/MediaBrowser.Model/Connect/ConnectUser.cs @@ -8,6 +8,5 @@ namespace MediaBrowser.Model.Connect public string Email { get; set; } public bool IsActive { get; set; } public string ImageUrl { get; set; } - public bool IsSupporter { get; set; } } } diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index 351bc05af6..df15c38fdd 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -733,6 +733,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV else if (info.IsSeries) { recordPath = Path.Combine(recordPath, "Series", _fileSystem.GetValidFilename(info.Name).Trim()); + + if (info.SeasonNumber.HasValue) + { + var folderName = string.Format("Season {0}", info.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture)); + recordPath = Path.Combine(recordPath, folderName); + } } else if (info.IsKids) { diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index d589b2bc38..dec8ba83d2 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -121,7 +121,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { var maxBitrate = 25000000; videoArgs = string.Format( - "-codec:v:0 libx264 -force_key_frames expr:gte(t,n_forced*5) {0} -pix_fmt yuv420p -preset superfast -crf 23 -b:v {1} -maxrate {1} -bufsize ({1}*2) -vsync vfr -profile:v high -level 41", + "-codec:v:0 libx264 -force_key_frames expr:gte(t,n_forced*5) {0} -pix_fmt yuv420p -preset superfast -crf 23 -b:v {1} -maxrate {1} -bufsize ({1}*2) -vsync -1 -profile:v high -level 41", GetOutputSizeParam(), maxBitrate.ToString(CultureInfo.InvariantCulture)); } @@ -157,7 +157,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { audioChannels = audioStream.Channels ?? audioChannels; } - return "-codec:a:0 aac -strict experimental -ab 320000 -af \"async=1000\""; + return "-codec:a:0 aac -strict experimental -ab 320000"; } private bool EncodeVideo(MediaSourceInfo mediaSource) diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index c874e51b61..2a974b5459 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -134,7 +134,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts } }, RequiresOpening = false, - RequiresClosing = false + RequiresClosing = false, + + ReadAtNativeFramerate = true }; return new List { mediaSource }; diff --git a/Nuget/MediaBrowser.Common.Internal.nuspec b/Nuget/MediaBrowser.Common.Internal.nuspec index a561dbf4b3..b9da464dd5 100644 --- a/Nuget/MediaBrowser.Common.Internal.nuspec +++ b/Nuget/MediaBrowser.Common.Internal.nuspec @@ -2,7 +2,7 @@ MediaBrowser.Common.Internal - 3.0.645 + 3.0.646 MediaBrowser.Common.Internal Luke ebr,Luke,scottisafool @@ -12,7 +12,7 @@ Contains common components shared by Emby Theater and Emby Server. Not intended for plugin developer consumption. Copyright © Emby 2013 - + diff --git a/Nuget/MediaBrowser.Common.nuspec b/Nuget/MediaBrowser.Common.nuspec index b9bce00d02..e55b0f9af9 100644 --- a/Nuget/MediaBrowser.Common.nuspec +++ b/Nuget/MediaBrowser.Common.nuspec @@ -2,7 +2,7 @@ MediaBrowser.Common - 3.0.645 + 3.0.646 MediaBrowser.Common Emby Team ebr,Luke,scottisafool diff --git a/Nuget/MediaBrowser.Model.Signed.nuspec b/Nuget/MediaBrowser.Model.Signed.nuspec index 3af1b91e26..7ad4d7dac3 100644 --- a/Nuget/MediaBrowser.Model.Signed.nuspec +++ b/Nuget/MediaBrowser.Model.Signed.nuspec @@ -2,7 +2,7 @@ MediaBrowser.Model.Signed - 3.0.645 + 3.0.646 MediaBrowser.Model - Signed Edition Emby Team ebr,Luke,scottisafool diff --git a/Nuget/MediaBrowser.Server.Core.nuspec b/Nuget/MediaBrowser.Server.Core.nuspec index d48b421c56..e62cfd37e6 100644 --- a/Nuget/MediaBrowser.Server.Core.nuspec +++ b/Nuget/MediaBrowser.Server.Core.nuspec @@ -2,7 +2,7 @@ MediaBrowser.Server.Core - 3.0.645 + 3.0.646 Media Browser.Server.Core Emby Team ebr,Luke,scottisafool @@ -12,7 +12,7 @@ Contains core components required to build plugins for Emby Server. Copyright © Emby 2013 - + -- cgit v1.2.3 From 33c002684e30f910312eef7f796e2efc0607d4a5 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 4 May 2016 16:50:47 -0400 Subject: update recording saving --- MediaBrowser.Api/Library/LibraryHelpers.cs | 54 --- .../Library/LibraryStructureService.cs | 43 +- MediaBrowser.Api/MediaBrowser.Api.csproj | 1 - MediaBrowser.Controller/Library/ILibraryManager.cs | 2 + MediaBrowser.Model/LiveTv/LiveTvOptions.cs | 4 + .../Library/LibraryManager.cs | 68 +++ .../LiveTv/EmbyTV/EmbyTV.cs | 512 +++++++++++++-------- 7 files changed, 403 insertions(+), 281 deletions(-) delete mode 100644 MediaBrowser.Api/Library/LibraryHelpers.cs (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Api/Library/LibraryHelpers.cs b/MediaBrowser.Api/Library/LibraryHelpers.cs deleted file mode 100644 index 22a88e2bf1..0000000000 --- a/MediaBrowser.Api/Library/LibraryHelpers.cs +++ /dev/null @@ -1,54 +0,0 @@ -using MediaBrowser.Controller; -using System; -using System.IO; -using System.Linq; -using CommonIO; - -namespace MediaBrowser.Api.Library -{ - /// - /// Class LibraryHelpers - /// - public static class LibraryHelpers - { - /// - /// The shortcut file extension - /// - private const string ShortcutFileExtension = ".mblink"; - /// - /// The shortcut file search - /// - private const string ShortcutFileSearch = "*" + ShortcutFileExtension; - - /// - /// Deletes a shortcut from within a virtual folder, within either the default view or a user view - /// - /// The file system. - /// Name of the virtual folder. - /// The media path. - /// The app paths. - /// The media folder does not exist - public static void RemoveMediaPath(IFileSystem fileSystem, string virtualFolderName, string mediaPath, IServerApplicationPaths appPaths) - { - if (string.IsNullOrWhiteSpace(mediaPath)) - { - throw new ArgumentNullException("mediaPath"); - } - - var rootFolderPath = appPaths.DefaultUserViewsPath; - var path = Path.Combine(rootFolderPath, virtualFolderName); - - if (!fileSystem.DirectoryExists(path)) - { - throw new DirectoryNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName)); - } - - var shortcut = Directory.EnumerateFiles(path, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase)); - - if (!string.IsNullOrEmpty(shortcut)) - { - fileSystem.DeleteFile(shortcut); - } - } - } -} diff --git a/MediaBrowser.Api/Library/LibraryStructureService.cs b/MediaBrowser.Api/Library/LibraryStructureService.cs index 817fd9ce00..3cf0d5d937 100644 --- a/MediaBrowser.Api/Library/LibraryStructureService.cs +++ b/MediaBrowser.Api/Library/LibraryStructureService.cs @@ -268,46 +268,7 @@ namespace MediaBrowser.Api.Library /// The request. public void Delete(RemoveVirtualFolder request) { - if (string.IsNullOrWhiteSpace(request.Name)) - { - throw new ArgumentNullException("request"); - } - - var rootFolderPath = _appPaths.DefaultUserViewsPath; - - var path = Path.Combine(rootFolderPath, request.Name); - - if (!_fileSystem.DirectoryExists(path)) - { - throw new DirectoryNotFoundException("The media folder does not exist"); - } - - _libraryMonitor.Stop(); - - try - { - _fileSystem.DeleteDirectory(path, true); - } - finally - { - Task.Run(() => - { - // No need to start if scanning the library because it will handle it - if (request.RefreshLibrary) - { - _libraryManager.ValidateMediaLibrary(new Progress(), CancellationToken.None); - } - else - { - // Need to add a delay here or directory watchers may still pick up the changes - var task = Task.Delay(1000); - // Have to block here to allow exceptions to bubble - Task.WaitAll(task); - - _libraryMonitor.Start(); - } - }); - } + _libraryManager.RemoveVirtualFolder(request.Name, request.RefreshLibrary); } /// @@ -364,7 +325,7 @@ namespace MediaBrowser.Api.Library try { - LibraryHelpers.RemoveMediaPath(_fileSystem, request.Name, request.Path, _appPaths); + _libraryManager.RemoveMediaPath(request.Name, request.Path); } finally { diff --git a/MediaBrowser.Api/MediaBrowser.Api.csproj b/MediaBrowser.Api/MediaBrowser.Api.csproj index db8961a66c..77949d1793 100644 --- a/MediaBrowser.Api/MediaBrowser.Api.csproj +++ b/MediaBrowser.Api/MediaBrowser.Api.csproj @@ -129,7 +129,6 @@ - diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 07ba41b3d7..936b97c6e2 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -571,6 +571,8 @@ namespace MediaBrowser.Controller.Library bool IgnoreFile(FileSystemMetadata file, BaseItem parent); void AddVirtualFolder(string name, string collectionType, string[] mediaPaths, bool refreshLibrary); + void RemoveVirtualFolder(string name, bool refreshLibrary); void AddMediaPath(string virtualFolderName, string path); + void RemoveMediaPath(string virtualFolderName, string path); } } \ No newline at end of file diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs index fc2b155ecd..4211fbd59f 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs @@ -7,8 +7,11 @@ namespace MediaBrowser.Model.LiveTv public int? GuideDays { get; set; } public bool EnableMovieProviders { get; set; } public string RecordingPath { get; set; } + public string MovieRecordingPath { get; set; } + public string SeriesRecordingPath { get; set; } public bool EnableAutoOrganize { get; set; } public bool EnableRecordingEncoding { get; set; } + public bool EnableRecordingSubfolders { get; set; } public bool EnableOriginalAudioWithEncodedRecordings { get; set; } public List TunerHosts { get; set; } @@ -20,6 +23,7 @@ namespace MediaBrowser.Model.LiveTv public LiveTvOptions() { EnableMovieProviders = true; + EnableRecordingSubfolders = true; TunerHosts = new List(); ListingProviders = new List(); } diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 72132c4be1..95d47b380c 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -2640,7 +2640,52 @@ namespace MediaBrowser.Server.Implementations.Library } } + public void RemoveVirtualFolder(string name, bool refreshLibrary) + { + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentNullException("name"); + } + + var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; + + var path = Path.Combine(rootFolderPath, name); + + if (!_fileSystem.DirectoryExists(path)) + { + throw new DirectoryNotFoundException("The media folder does not exist"); + } + + _libraryMonitorFactory().Stop(); + + try + { + _fileSystem.DeleteDirectory(path, true); + } + finally + { + Task.Run(() => + { + // No need to start if scanning the library because it will handle it + if (refreshLibrary) + { + ValidateMediaLibrary(new Progress(), CancellationToken.None); + } + else + { + // Need to add a delay here or directory watchers may still pick up the changes + var task = Task.Delay(1000); + // Have to block here to allow exceptions to bubble + Task.WaitAll(task); + + _libraryMonitorFactory().Start(); + } + }); + } + } + private const string ShortcutFileExtension = ".mblink"; + private const string ShortcutFileSearch = "*" + ShortcutFileExtension; public void AddMediaPath(string virtualFolderName, string path) { if (string.IsNullOrWhiteSpace(path)) @@ -2668,5 +2713,28 @@ namespace MediaBrowser.Server.Implementations.Library _fileSystem.CreateShortcut(lnk, path); } + + public void RemoveMediaPath(string virtualFolderName, string mediaPath) + { + if (string.IsNullOrWhiteSpace(mediaPath)) + { + throw new ArgumentNullException("mediaPath"); + } + + var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; + var path = Path.Combine(rootFolderPath, virtualFolderName); + + if (!_fileSystem.DirectoryExists(path)) + { + throw new DirectoryNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName)); + } + + var shortcut = Directory.EnumerateFiles(path, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => _fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase)); + + if (!string.IsNullOrEmpty(shortcut)) + { + _fileSystem.DeleteFile(shortcut); + } + } } } \ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index df15c38fdd..c5920d3d6a 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -26,7 +26,10 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using CommonIO; +using MediaBrowser.Common.Events; using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Power; using Microsoft.Win32; @@ -40,7 +43,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV private readonly IServerConfigurationManager _config; private readonly IJsonSerializer _jsonSerializer; - private readonly ItemDataProvider _recordingProvider; private readonly ItemDataProvider _seriesTimerProvider; private readonly TimerManager _timerProvider; @@ -56,6 +58,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV public static EmbyTV Current; + public event EventHandler DataSourceChanged; + public event EventHandler RecordingStatusChanged; + + private readonly ConcurrentDictionary _activeRecordings = + new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + public EmbyTV(IApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ISecurityManager security, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IFileOrganizationService organizationService, IMediaEncoder mediaEncoder, IPowerManagement powerManagement) { Current = this; @@ -74,10 +82,19 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _liveTvManager = (LiveTvManager)liveTvManager; _jsonSerializer = jsonSerializer; - _recordingProvider = new ItemDataProvider(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "recordings"), (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase)); _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers")); _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), powerManagement, _logger); _timerProvider.TimerFired += _timerProvider_TimerFired; + + _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated; + } + + private void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e) + { + if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase)) + { + OnRecordingFoldersChanged(); + } } public void Start() @@ -85,6 +102,95 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _timerProvider.RestartTimers(); SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; + + CreateRecordingFolders(); + } + + private void OnRecordingFoldersChanged() + { + CreateRecordingFolders(); + } + + private void CreateRecordingFolders() + { + var recordingFolders = GetRecordingFolders(); + + var defaultRecordingPath = DefaultRecordingPath; + if (!recordingFolders.Any(i => i.Locations.Contains(defaultRecordingPath, StringComparer.OrdinalIgnoreCase))) + { + RemovePathFromLibrary(defaultRecordingPath); + } + + var virtualFolders = _libraryManager.GetVirtualFolders() + .ToList(); + + var allExistingPaths = virtualFolders.SelectMany(i => i.Locations).ToList(); + + foreach (var recordingFolder in recordingFolders) + { + var pathsToCreate = recordingFolder.Locations + .Where(i => !allExistingPaths.Contains(i, StringComparer.OrdinalIgnoreCase)) + .ToList(); + + if (pathsToCreate.Count == 0) + { + continue; + } + + try + { + _libraryManager.AddVirtualFolder(recordingFolder.Name, recordingFolder.CollectionType, pathsToCreate.ToArray(), true); + } + catch (Exception ex) + { + _logger.ErrorException("Error creating virtual folder", ex); + } + } + } + + private void RemovePathFromLibrary(string path) + { + var requiresRefresh = false; + var virtualFolders = _libraryManager.GetVirtualFolders() + .ToList(); + + foreach (var virtualFolder in virtualFolders) + { + if (!virtualFolder.Locations.Contains(path, StringComparer.OrdinalIgnoreCase)) + { + continue; + } + + if (virtualFolder.Locations.Count == 1) + { + // remove entire virtual folder + try + { + _libraryManager.RemoveVirtualFolder(virtualFolder.Name, true); + } + catch (Exception ex) + { + _logger.ErrorException("Error removing virtual folder", ex); + } + } + else + { + try + { + _libraryManager.RemoveMediaPath(virtualFolder.Name, path); + requiresRefresh = true; + } + catch (Exception ex) + { + _logger.ErrorException("Error removing media path", ex); + } + } + } + + if (requiresRefresh) + { + _libraryManager.ValidateMediaLibrary(new Progress(), CancellationToken.None); + } } void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e) @@ -97,13 +203,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV } } - public event EventHandler DataSourceChanged; - - public event EventHandler RecordingStatusChanged; - - private readonly ConcurrentDictionary _activeRecordings = - new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - public string Name { get { return "Emby"; } @@ -114,6 +213,26 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); } } + private string DefaultRecordingPath + { + get + { + return Path.Combine(DataPath, "recordings"); + } + } + + private string RecordingPath + { + get + { + var path = GetConfiguration().RecordingPath; + + return string.IsNullOrWhiteSpace(path) + ? DefaultRecordingPath + : path; + } + } + public string HomePageUrl { get { return "http://emby.media"; } @@ -280,49 +399,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV return Task.FromResult(true); } - public async Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken) + public Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken) { - var remove = _recordingProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, recordingId, StringComparison.OrdinalIgnoreCase)); - if (remove != null) - { - if (!string.IsNullOrWhiteSpace(remove.TimerId)) - { - var enableDelay = _activeRecordings.ContainsKey(remove.TimerId); - - CancelTimerInternal(remove.TimerId); - - if (enableDelay) - { - // A hack yes, but need to make sure the file is closed before attempting to delete it - await Task.Delay(3000, cancellationToken).ConfigureAwait(false); - } - } - - if (!string.IsNullOrWhiteSpace(remove.Path)) - { - try - { - _fileSystem.DeleteFile(remove.Path); - } - catch (DirectoryNotFoundException) - { - - } - catch (FileNotFoundException) - { - - } - catch (Exception ex) - { - _logger.ErrorException("Error deleting recording file {0}", ex, remove.Path); - } - } - _recordingProvider.Delete(remove); - } - else - { - throw new ResourceNotFoundException("Recording not found: " + recordingId); - } + return Task.FromResult(true); } public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken) @@ -424,29 +503,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV public async Task> GetRecordingsAsync(CancellationToken cancellationToken) { - var recordings = _recordingProvider.GetAll().ToList(); - var updated = false; - - foreach (var recording in recordings) - { - if (recording.Status == RecordingStatus.InProgress) - { - if (string.IsNullOrWhiteSpace(recording.TimerId) || !_activeRecordings.ContainsKey(recording.TimerId)) - { - recording.Status = RecordingStatus.Cancelled; - recording.DateLastUpdated = DateTime.UtcNow; - _recordingProvider.Update(recording); - updated = true; - } - } - } - - if (updated) - { - recordings = _recordingProvider.GetAll().ToList(); - } - - return recordings; + return new List(); } public Task> GetTimersAsync(CancellationToken cancellationToken) @@ -695,104 +752,124 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV } } - private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken) + private string GetRecordingPath(TimerInfo timer, ProgramInfo info) { - if (timer == null) - { - throw new ArgumentNullException("timer"); - } - - ProgramInfo info = null; - - if (string.IsNullOrWhiteSpace(timer.ProgramId)) - { - _logger.Info("Timer {0} has null programId", timer.Id); - } - else - { - info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId); - } - - if (info == null) - { - _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); - info = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate); - } - - if (info == null) - { - throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId)); - } - var recordPath = RecordingPath; + var config = GetConfiguration(); if (info.IsMovie) { - recordPath = Path.Combine(recordPath, "Movies", _fileSystem.GetValidFilename(info.Name).Trim()); + var customRecordingPath = config.MovieRecordingPath; + if ((string.IsNullOrWhiteSpace(customRecordingPath) || string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase)) && config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Movies"); + } + + var folderName = _fileSystem.GetValidFilename(info.Name).Trim(); + if (info.ProductionYear.HasValue) + { + folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")"; + } + recordPath = Path.Combine(recordPath, folderName); } else if (info.IsSeries) { - recordPath = Path.Combine(recordPath, "Series", _fileSystem.GetValidFilename(info.Name).Trim()); + var customRecordingPath = config.SeriesRecordingPath; + if ((string.IsNullOrWhiteSpace(customRecordingPath) || string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase)) && config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Series"); + } + + var folderName = _fileSystem.GetValidFilename(info.Name).Trim(); + var folderNameWithYear = folderName; + if (info.ProductionYear.HasValue) + { + folderNameWithYear += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")"; + } + + if (Directory.Exists(Path.Combine(recordPath, folderName))) + { + recordPath = Path.Combine(recordPath, folderName); + } + else + { + recordPath = Path.Combine(recordPath, folderNameWithYear); + } if (info.SeasonNumber.HasValue) { - var folderName = string.Format("Season {0}", info.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture)); + folderName = string.Format("Season {0}", info.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture)); recordPath = Path.Combine(recordPath, folderName); } } else if (info.IsKids) { - recordPath = Path.Combine(recordPath, "Kids", _fileSystem.GetValidFilename(info.Name).Trim()); + if (config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Kids"); + } + + var folderName = _fileSystem.GetValidFilename(info.Name).Trim(); + if (info.ProductionYear.HasValue) + { + folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")"; + } + recordPath = Path.Combine(recordPath, folderName); } else if (info.IsSports) { - recordPath = Path.Combine(recordPath, "Sports", _fileSystem.GetValidFilename(info.Name).Trim()); + if (config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Sports"); + } + recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim()); } else { - recordPath = Path.Combine(recordPath, "Other", _fileSystem.GetValidFilename(info.Name).Trim()); + if (config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Other"); + } + recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim()); } var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts"; - recordPath = Path.Combine(recordPath, recordingFileName); + return Path.Combine(recordPath, recordingFileName); + } - var recordingId = info.Id.GetMD5().ToString("N"); - var recording = _recordingProvider.GetAll().FirstOrDefault(x => string.Equals(x.Id, recordingId, StringComparison.OrdinalIgnoreCase)); + private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken) + { + if (timer == null) + { + throw new ArgumentNullException("timer"); + } - if (recording == null) + ProgramInfo info = null; + + if (string.IsNullOrWhiteSpace(timer.ProgramId)) { - recording = new RecordingInfo - { - ChannelId = info.ChannelId, - Id = recordingId, - StartDate = info.StartDate, - EndDate = info.EndDate, - Genres = info.Genres, - IsKids = info.IsKids, - IsLive = info.IsLive, - IsMovie = info.IsMovie, - IsHD = info.IsHD, - IsNews = info.IsNews, - IsPremiere = info.IsPremiere, - IsSeries = info.IsSeries, - IsSports = info.IsSports, - IsRepeat = !info.IsPremiere, - Name = info.Name, - EpisodeTitle = info.EpisodeTitle, - ProgramId = info.Id, - ImagePath = info.ImagePath, - ImageUrl = info.ImageUrl, - OriginalAirDate = info.OriginalAirDate, - Status = RecordingStatus.Scheduled, - Overview = info.Overview, - SeriesTimerId = timer.SeriesTimerId, - TimerId = timer.Id, - ShowId = info.ShowId - }; - _recordingProvider.AddOrUpdate(recording); + _logger.Info("Timer {0} has null programId", timer.Id); + } + else + { + info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId); + } + + if (info == null) + { + _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); + info = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate); } + if (info == null) + { + throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId)); + } + + var recordPath = GetRecordingPath(timer, info); + var recordingStatus = RecordingStatus.New; + try { var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None).ConfigureAwait(false); @@ -817,11 +894,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _libraryMonitor.ReportFileSystemChangeBeginning(recordPath); - recording.Path = recordPath; - recording.Status = RecordingStatus.InProgress; - recording.DateLastUpdated = DateTime.UtcNow; - _recordingProvider.AddOrUpdate(recording); - var duration = recordingEndDate - DateTime.UtcNow; _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); @@ -846,7 +918,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken).ConfigureAwait(false); - recording.Status = RecordingStatus.Completed; + recordingStatus = RecordingStatus.Completed; _logger.Info("Recording completed: {0}", recordPath); } finally @@ -862,12 +934,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV catch (OperationCanceledException) { _logger.Info("Recording stopped: {0}", recordPath); - recording.Status = RecordingStatus.Completed; + recordingStatus = RecordingStatus.Completed; } catch (Exception ex) { _logger.ErrorException("Error recording to {0}", ex, recordPath); - recording.Status = RecordingStatus.Error; + recordingStatus = RecordingStatus.Error; } finally { @@ -875,12 +947,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _activeRecordings.TryRemove(timer.Id, out removed); } - recording.DateLastUpdated = DateTime.UtcNow; - _recordingProvider.AddOrUpdate(recording); - - if (recording.Status == RecordingStatus.Completed) + if (recordingStatus == RecordingStatus.Completed) { - OnSuccessfulRecording(recording); + OnSuccessfulRecording(info.IsSeries, recordPath); _timerProvider.Delete(timer); } else if (DateTime.UtcNow < timer.EndDate) @@ -893,7 +962,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV else { _timerProvider.Delete(timer); - _recordingProvider.Delete(recording); } } @@ -948,11 +1016,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV return new DirectRecorder(_logger, _httpClient, _fileSystem); } - private async void OnSuccessfulRecording(RecordingInfo recording) + private async void OnSuccessfulRecording(bool isSeries, string path) { if (GetConfiguration().EnableAutoOrganize) { - if (recording.IsSeries) + if (isSeries) { try { @@ -962,12 +1030,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager); - var result = await organize.OrganizeEpisodeFile(recording.Path, CancellationToken.None).ConfigureAwait(false); - - if (result.Status == FileSortingStatus.Success) - { - _recordingProvider.Delete(recording); - } + var result = await organize.OrganizeEpisodeFile(path, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { @@ -991,18 +1054,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks); } - private string RecordingPath - { - get - { - var path = GetConfiguration().RecordingPath; - - return string.IsNullOrWhiteSpace(path) - ? Path.Combine(DataPath, "recordings") - : path; - } - } - private LiveTvOptions GetConfiguration() { return _config.GetConfiguration("livetv"); @@ -1010,7 +1061,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV private async Task UpdateTimersForSeriesTimer(List epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers) { - var newTimers = GetTimersForSeries(seriesTimer, epgData, _recordingProvider.GetAll()).ToList(); + var newTimers = GetTimersForSeries(seriesTimer, epgData, true).ToList(); var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false); @@ -1024,7 +1075,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV if (deleteInvalidTimers) { - var allTimers = GetTimersForSeries(seriesTimer, epgData, new List()) + var allTimers = GetTimersForSeries(seriesTimer, epgData, false) .Select(i => i.Id) .ToList(); @@ -1040,7 +1091,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV } } - private IEnumerable GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable allPrograms, IReadOnlyList currentRecordings) + private IEnumerable GetTimersForSeries(SeriesTimerInfo seriesTimer, + IEnumerable allPrograms, + bool filterByCurrentRecordings) { if (seriesTimer == null) { @@ -1050,23 +1103,71 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { throw new ArgumentNullException("allPrograms"); } - if (currentRecordings == null) - { - throw new ArgumentNullException("currentRecordings"); - } // Exclude programs that have already ended allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow && i.StartDate > DateTime.UtcNow); allPrograms = GetProgramsForSeries(seriesTimer, allPrograms); - var recordingShowIds = currentRecordings.Select(i => i.ProgramId).Where(i => !string.IsNullOrWhiteSpace(i)).ToList(); - - allPrograms = allPrograms.Where(i => !recordingShowIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase)); + if (filterByCurrentRecordings) + { + allPrograms = allPrograms.Where(i => !IsProgramAlreadyInLibrary(i)); + } return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer)); } + private bool IsProgramAlreadyInLibrary(ProgramInfo program) + { + if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle)) + { + var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery + { + IncludeItemTypes = new[] { typeof(Series).Name }, + Name = program.Name + + }).Select(i => i.ToString("N")).ToArray(); + + if (seriesIds.Length == 0) + { + return false; + } + + if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) + { + var result = _libraryManager.GetItemsResult(new InternalItemsQuery + { + IncludeItemTypes = new[] { typeof(Episode).Name }, + ParentIndexNumber = program.SeasonNumber.Value, + IndexNumber = program.EpisodeNumber.Value, + AncestorIds = seriesIds + }); + + if (result.TotalRecordCount > 0) + { + return true; + } + } + + if (!string.IsNullOrWhiteSpace(program.EpisodeTitle)) + { + var result = _libraryManager.GetItemsResult(new InternalItemsQuery + { + IncludeItemTypes = new[] { typeof(Episode).Name }, + Name = program.EpisodeTitle, + AncestorIds = seriesIds + }); + + if (result.TotalRecordCount > 0) + { + return true; + } + } + } + + return false; + } + private IEnumerable GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable allPrograms) { if (!seriesTimer.RecordAnyTime) @@ -1151,6 +1252,47 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV }); } + public List GetRecordingFolders() + { + var list = new List(); + + var defaultFolder = RecordingPath; + var defaultName = "Recordings"; + + if (Directory.Exists(defaultFolder)) + { + list.Add(new VirtualFolderInfo + { + Locations = new List { defaultFolder }, + Name = defaultName + }); + } + + var customPath = GetConfiguration().MovieRecordingPath; + if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath)) + { + list.Add(new VirtualFolderInfo + { + Locations = new List { customPath }, + Name = "Recorded Movies", + CollectionType = CollectionType.Movies + }); + } + + customPath = GetConfiguration().SeriesRecordingPath; + if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath)) + { + list.Add(new VirtualFolderInfo + { + Locations = new List { customPath }, + Name = "Recorded Series", + CollectionType = CollectionType.TvShows + }); + } + + return list; + } + class ActiveRecordingInfo { public string Path { get; set; } -- cgit v1.2.3 From 99084edabeb1787f28496dffa55fbb260e34ae81 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 8 May 2016 23:13:38 -0400 Subject: update windows ffmpeg --- MediaBrowser.Api/ApiEntryPoint.cs | 8 ++- MediaBrowser.Api/LiveTv/LiveTvService.cs | 20 ++++++- MediaBrowser.Api/Movies/MoviesService.cs | 1 - MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs | 5 +- MediaBrowser.Api/UserLibrary/ItemsService.cs | 3 +- MediaBrowser.Controller/Entities/Audio/Audio.cs | 6 --- .../Entities/Audio/MusicAlbum.cs | 9 ++++ .../Entities/Audio/MusicArtist.cs | 9 ++++ MediaBrowser.Controller/Entities/BaseItem.cs | 11 ++++ MediaBrowser.Controller/Entities/Folder.cs | 49 +++++++++++------ MediaBrowser.Controller/Entities/IHasMetadata.cs | 2 + .../Entities/InternalItemsQuery.cs | 2 + MediaBrowser.Controller/Entities/MusicVideo.cs | 6 --- MediaBrowser.Controller/Entities/TV/Season.cs | 9 ++++ MediaBrowser.Controller/Entities/TV/Series.cs | 9 ++++ MediaBrowser.Controller/Entities/UserRootFolder.cs | 5 -- MediaBrowser.Controller/Playlists/Playlist.cs | 9 ++++ MediaBrowser.Model/LiveTv/ProgramQuery.cs | 3 ++ .../LiveTv/RecommendedProgramQuery.cs | 9 +++- MediaBrowser.Providers/Manager/MetadataService.cs | 61 +++++++++++++++++++-- .../Music/MusicBrainzArtistProvider.cs | 29 +++++++--- .../Dto/DtoService.cs | 33 ++++-------- .../Library/LibraryManager.cs | 14 +++-- .../LiveTv/EmbyTV/EmbyTV.cs | 18 ++++++- .../LiveTv/LiveTvManager.cs | 10 ++-- .../Persistence/SqliteItemRepository.cs | 62 ++++++++++++++++++++-- .../Sorting/DateLastMediaAddedComparer.cs | 8 +-- .../MediaBrowser.ServerApplication.csproj | 2 - .../Native/WindowsApp.cs | 17 ++++-- .../ffmpeg/ffmpegx64.7z.REMOVED.git-id | 1 - .../ffmpeg/ffmpegx86.7z.REMOVED.git-id | 1 - 31 files changed, 330 insertions(+), 101 deletions(-) delete mode 100644 MediaBrowser.ServerApplication/ffmpeg/ffmpegx64.7z.REMOVED.git-id delete mode 100644 MediaBrowser.ServerApplication/ffmpeg/ffmpegx86.7z.REMOVED.git-id (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Api/ApiEntryPoint.cs b/MediaBrowser.Api/ApiEntryPoint.cs index 66ca8c25d4..a677bc6004 100644 --- a/MediaBrowser.Api/ApiEntryPoint.cs +++ b/MediaBrowser.Api/ApiEntryPoint.cs @@ -488,13 +488,17 @@ namespace MediaBrowser.Api { try { - Logger.Info("Killing ffmpeg process for {0}", job.Path); + Logger.Info("Stopping ffmpeg process with q command for {0}", job.Path); //process.Kill(); process.StandardInput.WriteLine("q"); // Need to wait because killing is asynchronous - process.WaitForExit(5000); + if (!process.WaitForExit(5000)) + { + Logger.Info("Killing ffmpeg process for {0}", job.Path); + process.Kill(); + } } catch (Exception ex) { diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs index ebcf8fbeac..d3a4558c88 100644 --- a/MediaBrowser.Api/LiveTv/LiveTvService.cs +++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs @@ -254,6 +254,8 @@ namespace MediaBrowser.Api.LiveTv [ApiMember(Name = "EnableImages", Description = "Optional, include image information in output", IsRequired = false, DataType = "boolean", ParameterType = "query", Verb = "GET")] public bool? EnableImages { get; set; } + public bool EnableTotalRecordCount { get; set; } + [ApiMember(Name = "ImageTypeLimit", Description = "Optional, the max number of images to return, per image type", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] public int? ImageTypeLimit { get; set; } @@ -266,12 +268,24 @@ namespace MediaBrowser.Api.LiveTv /// The fields. [ApiMember(Name = "Fields", Description = "Optional. Specify additional fields of information to return in the output. This allows multiple, comma delimeted. Options: Budget, Chapters, CriticRatingSummary, DateCreated, Genres, HomePageUrl, IndexOptions, MediaStreams, Overview, ParentId, Path, People, ProviderIds, PrimaryImageAspectRatio, Revenue, SortName, Studios, Taglines", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET", AllowMultiple = true)] public string Fields { get; set; } + + public GetPrograms() + { + EnableTotalRecordCount = true; + } } [Route("/LiveTv/Programs/Recommended", "GET", Summary = "Gets available live tv epgs..")] [Authenticated] public class GetRecommendedPrograms : IReturn>, IHasDtoOptions { + public bool EnableTotalRecordCount { get; set; } + + public GetRecommendedPrograms() + { + EnableTotalRecordCount = true; + } + [ApiMember(Name = "UserId", Description = "Optional filter by user id.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET,POST")] public string UserId { get; set; } @@ -662,7 +676,8 @@ namespace MediaBrowser.Api.LiveTv { ChannelIds = (request.ChannelIds ?? string.Empty).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToArray(), UserId = request.UserId, - HasAired = request.HasAired + HasAired = request.HasAired, + EnableTotalRecordCount = request.EnableTotalRecordCount }; if (!string.IsNullOrEmpty(request.MinStartDate)) @@ -709,7 +724,8 @@ namespace MediaBrowser.Api.LiveTv HasAired = request.HasAired, IsMovie = request.IsMovie, IsKids = request.IsKids, - IsSports = request.IsSports + IsSports = request.IsSports, + EnableTotalRecordCount = request.EnableTotalRecordCount }; var result = await _liveTvManager.GetRecommendedPrograms(query, GetDtoOptions(request), CancellationToken.None).ConfigureAwait(false); diff --git a/MediaBrowser.Api/Movies/MoviesService.cs b/MediaBrowser.Api/Movies/MoviesService.cs index 9590971d06..786615cc3e 100644 --- a/MediaBrowser.Api/Movies/MoviesService.cs +++ b/MediaBrowser.Api/Movies/MoviesService.cs @@ -196,7 +196,6 @@ namespace MediaBrowser.Api.Movies var parentIds = new string[] { }; var list = _libraryManager.GetItemList(query, parentIds) - .DistinctBy(i => i.PresentationUniqueKey, StringComparer.OrdinalIgnoreCase) .DistinctBy(i => i.GetProviderId(MetadataProviders.Imdb) ?? Guid.NewGuid().ToString("N")) .ToList(); diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs index 6867f6308c..aee1a8d545 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsRequest.cs @@ -12,6 +12,7 @@ namespace MediaBrowser.Api.UserLibrary protected BaseItemsRequest() { EnableImages = true; + EnableTotalRecordCount = true; } /// @@ -104,7 +105,9 @@ namespace MediaBrowser.Api.UserLibrary [ApiMember(Name = "IsInBoxSet", Description = "Optional filter by items that are in boxsets, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] public bool? IsInBoxSet { get; set; } - + + public bool EnableTotalRecordCount { get; set; } + /// /// Skips over a given number of items within the results. Use for paging. /// diff --git a/MediaBrowser.Api/UserLibrary/ItemsService.cs b/MediaBrowser.Api/UserLibrary/ItemsService.cs index 7d2029cabe..ff937078e6 100644 --- a/MediaBrowser.Api/UserLibrary/ItemsService.cs +++ b/MediaBrowser.Api/UserLibrary/ItemsService.cs @@ -230,7 +230,8 @@ namespace MediaBrowser.Api.UserLibrary ParentId = string.IsNullOrWhiteSpace(request.ParentId) ? (Guid?)null : new Guid(request.ParentId), ParentIndexNumber = request.ParentIndexNumber, AiredDuringSeason = request.AiredDuringSeason, - AlbumArtistStartsWithOrGreater = request.AlbumArtistStartsWithOrGreater + AlbumArtistStartsWithOrGreater = request.AlbumArtistStartsWithOrGreater, + EnableTotalRecordCount = request.EnableTotalRecordCount }; if (!string.IsNullOrWhiteSpace(request.Ids)) diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs index fd56a6746a..c34a884ff5 100644 --- a/MediaBrowser.Controller/Entities/Audio/Audio.cs +++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs @@ -40,12 +40,6 @@ namespace MediaBrowser.Controller.Entities.Audio public List AlbumArtists { get; set; } - /// - /// Gets or sets the album. - /// - /// The album. - public string Album { get; set; } - [IgnoreDataMember] public bool IsThemeMedia { diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs index 5cb4e8c9d1..615276e837 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs @@ -48,6 +48,15 @@ namespace MediaBrowser.Controller.Entities.Audio } } + [IgnoreDataMember] + public override bool SupportsCumulativeRunTimeTicks + { + get + { + return true; + } + } + [IgnoreDataMember] public List AllArtists { diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index 6f6f124dbb..6104976615 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -34,6 +34,15 @@ namespace MediaBrowser.Controller.Entities.Audio } } + [IgnoreDataMember] + public override bool SupportsCumulativeRunTimeTicks + { + get + { + return true; + } + } + [IgnoreDataMember] public override bool SupportsAddingToPlaylist { diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 2e968c8803..cd021d2ab5 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -69,6 +69,12 @@ namespace MediaBrowser.Controller.Entities public List ImageInfos { get; set; } + /// + /// Gets or sets the album. + /// + /// The album. + public string Album { get; set; } + /// /// Gets or sets the channel identifier. /// @@ -1175,6 +1181,11 @@ namespace MediaBrowser.Controller.Entities get { return Id.ToString("N"); } } + public virtual bool RequiresRefresh() + { + return false; + } + private string _userDataKey; /// /// Gets the user data key. diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 978fd7fedf..457a0b3abd 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -28,6 +28,9 @@ namespace MediaBrowser.Controller.Entities public List ThemeSongIds { get; set; } public List ThemeVideoIds { get; set; } + [IgnoreDataMember] + public DateTime? DateLastMediaAdded { get; set; } + public Folder() { LinkedChildren = new List(); @@ -55,6 +58,36 @@ namespace MediaBrowser.Controller.Entities } } + [IgnoreDataMember] + public virtual bool SupportsCumulativeRunTimeTicks + { + get + { + return false; + } + } + + [IgnoreDataMember] + public virtual bool SupportsDateLastMediaAdded + { + get + { + return false; + } + } + + public override bool RequiresRefresh() + { + var baseResult = base.RequiresRefresh(); + + if (SupportsCumulativeRunTimeTicks && !RunTimeTicks.HasValue) + { + baseResult = true; + } + + return baseResult; + } + [IgnoreDataMember] public override string FileNameWithoutExtension { @@ -789,11 +822,6 @@ namespace MediaBrowser.Controller.Entities Logger.Debug("Query requires post-filtering due to ItemSortBy.AiredEpisodeOrder"); return true; } - if (query.SortBy.Contains(ItemSortBy.Album, StringComparer.OrdinalIgnoreCase)) - { - Logger.Debug("Query requires post-filtering due to ItemSortBy.Album"); - return true; - } if (query.SortBy.Contains(ItemSortBy.AlbumArtist, StringComparer.OrdinalIgnoreCase)) { Logger.Debug("Query requires post-filtering due to ItemSortBy.AlbumArtist"); @@ -809,11 +837,6 @@ namespace MediaBrowser.Controller.Entities Logger.Debug("Query requires post-filtering due to ItemSortBy.Budget"); return true; } - if (query.SortBy.Contains(ItemSortBy.DateLastContentAdded, StringComparer.OrdinalIgnoreCase)) - { - Logger.Debug("Query requires post-filtering due to ItemSortBy.DateLastContentAdded"); - return true; - } if (query.SortBy.Contains(ItemSortBy.GameSystem, StringComparer.OrdinalIgnoreCase)) { Logger.Debug("Query requires post-filtering due to ItemSortBy.GameSystem"); @@ -1086,12 +1109,6 @@ namespace MediaBrowser.Controller.Entities return true; } - if (query.AlbumNames.Length > 0) - { - Logger.Debug("Query requires post-filtering due to AlbumNames"); - return true; - } - if (query.ArtistNames.Length > 0) { Logger.Debug("Query requires post-filtering due to ArtistNames"); diff --git a/MediaBrowser.Controller/Entities/IHasMetadata.cs b/MediaBrowser.Controller/Entities/IHasMetadata.cs index 1f680b35f3..c7940c8a97 100644 --- a/MediaBrowser.Controller/Entities/IHasMetadata.cs +++ b/MediaBrowser.Controller/Entities/IHasMetadata.cs @@ -49,5 +49,7 @@ namespace MediaBrowser.Controller.Entities /// /// true if [supports people]; otherwise, false. bool SupportsPeople { get; } + + bool RequiresRefresh(); } } diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs index 385ee81e9d..5236b0a278 100644 --- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs @@ -137,10 +137,12 @@ namespace MediaBrowser.Controller.Entities public string AncestorWithPresentationUniqueKey { get; set; } public bool GroupByPresentationUniqueKey { get; set; } + public bool EnableTotalRecordCount { get; set; } public InternalItemsQuery() { GroupByPresentationUniqueKey = true; + EnableTotalRecordCount = true; AlbumNames = new string[] { }; ArtistNames = new string[] { }; diff --git a/MediaBrowser.Controller/Entities/MusicVideo.cs b/MediaBrowser.Controller/Entities/MusicVideo.cs index bf4c2559c5..7119828e26 100644 --- a/MediaBrowser.Controller/Entities/MusicVideo.cs +++ b/MediaBrowser.Controller/Entities/MusicVideo.cs @@ -9,12 +9,6 @@ namespace MediaBrowser.Controller.Entities { public class MusicVideo : Video, IHasArtist, IHasMusicGenres, IHasProductionLocations, IHasBudget, IHasLookupInfo { - /// - /// Gets or sets the album. - /// - /// The album. - public string Album { get; set; } - /// /// Gets or sets the budget. /// diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index 4e6128527c..ac8cc0ee26 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -32,6 +32,15 @@ namespace MediaBrowser.Controller.Entities.TV } } + [IgnoreDataMember] + public override bool SupportsDateLastMediaAdded + { + get + { + return true; + } + } + [IgnoreDataMember] public override Guid? DisplayParentId { diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 680af1843c..f8cdab8ce6 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -48,6 +48,15 @@ namespace MediaBrowser.Controller.Entities.TV } } + [IgnoreDataMember] + public override bool SupportsDateLastMediaAdded + { + get + { + return true; + } + } + public bool DisplaySpecialsWithSeasons { get; set; } public List LocalTrailerIds { get; set; } diff --git a/MediaBrowser.Controller/Entities/UserRootFolder.cs b/MediaBrowser.Controller/Entities/UserRootFolder.cs index 8ce39c6979..b9e997d175 100644 --- a/MediaBrowser.Controller/Entities/UserRootFolder.cs +++ b/MediaBrowser.Controller/Entities/UserRootFolder.cs @@ -102,10 +102,5 @@ namespace MediaBrowser.Controller.Entities LibraryManager.RegisterItem(item); } } - - public override void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user) - { - // Nothing meaninful here and will only waste resources - } } } diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index cd0c5dc1c7..003cbcfcda 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -39,6 +39,15 @@ namespace MediaBrowser.Controller.Playlists } } + [IgnoreDataMember] + public override bool SupportsCumulativeRunTimeTicks + { + get + { + return true; + } + } + public override bool IsAuthorizedToDelete(User user) { return true; diff --git a/MediaBrowser.Model/LiveTv/ProgramQuery.cs b/MediaBrowser.Model/LiveTv/ProgramQuery.cs index 7a877e3561..0141191c18 100644 --- a/MediaBrowser.Model/LiveTv/ProgramQuery.cs +++ b/MediaBrowser.Model/LiveTv/ProgramQuery.cs @@ -14,8 +14,11 @@ namespace MediaBrowser.Model.LiveTv ChannelIds = new string[] { }; SortBy = new string[] { }; Genres = new string[] { }; + EnableTotalRecordCount = true; } + public bool EnableTotalRecordCount { get; set; } + /// /// Fields to return within the items, in addition to basic information /// diff --git a/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs b/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs index e83a8fda65..0e6d081a1d 100644 --- a/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs +++ b/MediaBrowser.Model/LiveTv/RecommendedProgramQuery.cs @@ -13,7 +13,14 @@ namespace MediaBrowser.Model.LiveTv public bool? EnableImages { get; set; } public int? ImageTypeLimit { get; set; } public ImageType[] EnableImageTypes { get; set; } - + + public bool EnableTotalRecordCount { get; set; } + + public RecommendedProgramQuery() + { + EnableTotalRecordCount = true; + } + /// /// Gets or sets the user identifier. /// diff --git a/MediaBrowser.Providers/Manager/MetadataService.cs b/MediaBrowser.Providers/Manager/MetadataService.cs index ae48c996a0..218127ab9e 100644 --- a/MediaBrowser.Providers/Manager/MetadataService.cs +++ b/MediaBrowser.Providers/Manager/MetadataService.cs @@ -310,6 +310,11 @@ namespace MediaBrowser.Providers.Manager return true; } + if (item is MusicVideo) + { + return true; + } + return false; } @@ -390,7 +395,6 @@ namespace MediaBrowser.Providers.Manager return _cachedTask; } - private readonly Task _cachedResult = Task.FromResult(ItemUpdateType.None); /// /// Befores the save. /// @@ -398,9 +402,58 @@ namespace MediaBrowser.Providers.Manager /// if set to true [is full refresh]. /// Type of the current update. /// ItemUpdateType. - protected virtual Task BeforeSave(TItemType item, bool isFullRefresh, ItemUpdateType currentUpdateType) + protected virtual async Task BeforeSave(TItemType item, bool isFullRefresh, ItemUpdateType currentUpdateType) + { + var updateType = ItemUpdateType.None; + + updateType |= SaveCumulativeRunTimeTicks(item, isFullRefresh, currentUpdateType); + updateType |= SaveDateLastMediaAdded(item, isFullRefresh, currentUpdateType); + + return updateType; + } + + private ItemUpdateType SaveCumulativeRunTimeTicks(TItemType item, bool isFullRefresh, ItemUpdateType currentUpdateType) + { + var updateType = ItemUpdateType.None; + + if (isFullRefresh || currentUpdateType > ItemUpdateType.None) + { + var folder = item as Folder; + if (folder != null && folder.SupportsCumulativeRunTimeTicks) + { + var ticks = folder.GetRecursiveChildren(i => !i.IsFolder).Select(i => i.RunTimeTicks ?? 0).Sum(); + + if (!folder.RunTimeTicks.HasValue || folder.RunTimeTicks.Value != ticks) + { + folder.RunTimeTicks = ticks; + updateType = ItemUpdateType.MetadataEdit; + } + } + } + + return updateType; + } + + private ItemUpdateType SaveDateLastMediaAdded(TItemType item, bool isFullRefresh, ItemUpdateType currentUpdateType) { - return _cachedResult; + var updateType = ItemUpdateType.None; + + if (isFullRefresh || currentUpdateType > ItemUpdateType.None) + { + var folder = item as Folder; + if (folder != null && folder.SupportsDateLastMediaAdded) + { + var date = folder.GetRecursiveChildren(i => !i.IsFolder).Select(i => i.DateCreated).Max(); + + if (!folder.DateLastMediaAdded.HasValue || folder.DateLastMediaAdded.Value != date) + { + folder.DateLastMediaAdded = date; + updateType = ItemUpdateType.MetadataEdit; + } + } + } + + return updateType; } /// @@ -420,7 +473,7 @@ namespace MediaBrowser.Providers.Manager : status.DateLastMetadataRefresh ?? default(DateTime); // Run all if either of these flags are true - var runAllProviders = options.ReplaceAllMetadata || options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || dateLastRefresh == default(DateTime); + var runAllProviders = options.ReplaceAllMetadata || options.MetadataRefreshMode == MetadataRefreshMode.FullRefresh || dateLastRefresh == default(DateTime) || item.RequiresRefresh(); if (!runAllProviders) { diff --git a/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs b/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs index ad900123ed..2eb65f4e57 100644 --- a/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs +++ b/MediaBrowser.Providers/Music/MusicBrainzArtistProvider.cs @@ -62,12 +62,25 @@ namespace MediaBrowser.Providers.Music private IEnumerable GetResultsFromResponse(XmlDocument doc) { - var ns = new XmlNamespaceManager(doc.NameTable); - ns.AddNamespace("mb", "https://musicbrainz.org/ns/mmd-2.0#"); + //var ns = new XmlNamespaceManager(doc.NameTable); + //ns.AddNamespace("mb", "https://musicbrainz.org/ns/mmd-2.0#"); var list = new List(); - var nodes = doc.SelectNodes("//mb:artist-list/mb:artist", ns); + var docElem = doc.DocumentElement; + + if (docElem == null) + { + return list; + } + + var artistList = docElem.FirstChild; + if (artistList == null) + { + return list; + } + + var nodes = artistList.ChildNodes; if (nodes != null) { @@ -79,11 +92,13 @@ namespace MediaBrowser.Providers.Music string mbzId = node.Attributes["id"].Value; - var nameNode = node.SelectSingleNode("//mb:name", ns); - - if (nameNode != null) + foreach (var child in node.ChildNodes.Cast()) { - name = nameNode.InnerText; + if (string.Equals(child.Name, "name", StringComparison.OrdinalIgnoreCase)) + { + name = node.InnerText; + break; + } } if (!string.IsNullOrWhiteSpace(mbzId) && !string.IsNullOrWhiteSpace(name)) diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index 0aec3230da..32610a6ad9 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -499,6 +499,16 @@ namespace MediaBrowser.Server.Implementations.Dto } } + if (fields.Contains(ItemFields.CumulativeRunTimeTicks)) + { + dto.CumulativeRunTimeTicks = dto.RunTimeTicks; + } + + if (fields.Contains(ItemFields.DateLastMediaAdded)) + { + dto.DateLastMediaAdded = folder.DateLastMediaAdded; + } + dto.UserData.Played = dto.UserData.PlayedPercentage.HasValue && dto.UserData.PlayedPercentage.Value >= 100; } @@ -1613,9 +1623,7 @@ namespace MediaBrowser.Server.Implementations.Dto { var recursiveItemCount = 0; var unplayed = 0; - long runtime = 0; - DateTime? dateLastMediaAdded = null; double totalPercentPlayed = 0; double totalSyncPercent = 0; var addSyncInfo = fields.Contains(ItemFields.SyncInfo); @@ -1632,15 +1640,6 @@ namespace MediaBrowser.Server.Implementations.Dto // Loop through each recursive child foreach (var child in children) { - if (!dateLastMediaAdded.HasValue) - { - dateLastMediaAdded = child.DateCreated; - } - else - { - dateLastMediaAdded = new[] { dateLastMediaAdded.Value, child.DateCreated }.Max(); - } - var userdata = _userDataRepository.GetUserData(user, child); recursiveItemCount++; @@ -1669,8 +1668,6 @@ namespace MediaBrowser.Server.Implementations.Dto unplayed++; } - runtime += child.RunTimeTicks ?? 0; - if (addSyncInfo) { double percent = 0; @@ -1709,16 +1706,6 @@ namespace MediaBrowser.Server.Implementations.Dto } } } - - if (runtime > 0 && fields.Contains(ItemFields.CumulativeRunTimeTicks)) - { - dto.CumulativeRunTimeTicks = runtime; - } - - if (fields.Contains(ItemFields.DateLastMediaAdded)) - { - dto.DateLastMediaAdded = dateLastMediaAdded; - } } /// diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index f9bf3446f4..c95b301722 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -1354,12 +1354,20 @@ namespace MediaBrowser.Server.Implementations.Library AddUserToQuery(query, query.User); } - var initialResult = ItemRepository.GetItemIds(query); + if (query.EnableTotalRecordCount) + { + var initialResult = ItemRepository.GetItemIds(query); + + return new QueryResult + { + TotalRecordCount = initialResult.TotalRecordCount, + Items = initialResult.Items.Select(GetItemById).Where(i => i != null).ToArray() + }; + } return new QueryResult { - TotalRecordCount = initialResult.TotalRecordCount, - Items = initialResult.Items.Select(GetItemById).Where(i => i != null).ToArray() + Items = ItemRepository.GetItemIdsList(query).Select(GetItemById).Where(i => i != null).ToArray() }; } diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index c5920d3d6a..b5e8ad79a5 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -760,7 +760,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV if (info.IsMovie) { var customRecordingPath = config.MovieRecordingPath; - if ((string.IsNullOrWhiteSpace(customRecordingPath) || string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase)) && config.EnableRecordingSubfolders) + var allowSubfolder = true; + if (!string.IsNullOrWhiteSpace(customRecordingPath)) + { + allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase); + recordPath = customRecordingPath; + } + + if (allowSubfolder && config.EnableRecordingSubfolders) { recordPath = Path.Combine(recordPath, "Movies"); } @@ -775,7 +782,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV else if (info.IsSeries) { var customRecordingPath = config.SeriesRecordingPath; - if ((string.IsNullOrWhiteSpace(customRecordingPath) || string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase)) && config.EnableRecordingSubfolders) + var allowSubfolder = true; + if (!string.IsNullOrWhiteSpace(customRecordingPath)) + { + allowSubfolder = string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase); + recordPath = customRecordingPath; + } + + if (allowSubfolder && config.EnableRecordingSubfolders) { recordPath = Path.Combine(recordPath, "Series"); } diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index eec8328f89..175eed66c0 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -886,7 +886,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv StartIndex = query.StartIndex, Limit = query.Limit, SortBy = query.SortBy, - SortOrder = query.SortOrder ?? SortOrder.Ascending + SortOrder = query.SortOrder ?? SortOrder.Ascending, + EnableTotalRecordCount = query.EnableTotalRecordCount }; if (query.HasAired.HasValue) @@ -924,7 +925,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv IsAiring = query.IsAiring, IsMovie = query.IsMovie, IsSports = query.IsSports, - IsKids = query.IsKids + IsKids = query.IsKids, + EnableTotalRecordCount = query.EnableTotalRecordCount }; if (query.HasAired.HasValue) @@ -1263,11 +1265,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv private async Task CleanDatabaseInternal(List currentIdList, string[] validTypes, IProgress progress, CancellationToken cancellationToken) { - var list = _itemRepo.GetItemIds(new InternalItemsQuery + var list = _itemRepo.GetItemIdsList(new InternalItemsQuery { IncludeItemTypes = validTypes - }).Items.ToList(); + }).ToList(); var numComplete = 0; diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index 09739f8a9d..180bd35479 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -85,7 +85,7 @@ namespace MediaBrowser.Server.Implementations.Persistence private IDbCommand _updateInheritedRatingCommand; private IDbCommand _updateInheritedTagsCommand; - public const int LatestSchemaVersion = 76; + public const int LatestSchemaVersion = 77; /// /// Initializes a new instance of the class. @@ -235,6 +235,9 @@ namespace MediaBrowser.Server.Implementations.Persistence _connection.AddColumn(Logger, "TypedBaseItems", "SlugName", "Text"); _connection.AddColumn(Logger, "TypedBaseItems", "OriginalTitle", "Text"); _connection.AddColumn(Logger, "TypedBaseItems", "PrimaryVersionId", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "DateLastMediaAdded", "DATETIME"); + _connection.AddColumn(Logger, "TypedBaseItems", "Album", "Text"); + _connection.AddColumn(Logger, "UserDataKeys", "Priority", "INT"); string[] postQueries = @@ -351,7 +354,9 @@ namespace MediaBrowser.Server.Implementations.Persistence "TrailerTypes", "DateModifiedDuringLastRefresh", "OriginalTitle", - "PrimaryVersionId" + "PrimaryVersionId", + "DateLastMediaAdded", + "Album" }; private readonly string[] _mediaStreamSaveColumns = @@ -463,7 +468,9 @@ namespace MediaBrowser.Server.Implementations.Persistence "PresentationUniqueKey", "SlugName", "OriginalTitle", - "PrimaryVersionId" + "PrimaryVersionId", + "DateLastMediaAdded", + "Album" }; _saveItemCommand = _connection.CreateCommand(); _saveItemCommand.CommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns.ToArray()) + ") values ("; @@ -824,6 +831,18 @@ namespace MediaBrowser.Server.Implementations.Persistence _saveItemCommand.GetParameter(index++).Value = null; } + var folder = item as Folder; + if (folder != null && folder.DateLastMediaAdded.HasValue) + { + _saveItemCommand.GetParameter(index++).Value = folder.DateLastMediaAdded.Value; + } + else + { + _saveItemCommand.GetParameter(index++).Value = null; + } + + _saveItemCommand.GetParameter(index++).Value = item.Album; + _saveItemCommand.Transaction = transaction; _saveItemCommand.ExecuteNonQuery(); @@ -1217,6 +1236,17 @@ namespace MediaBrowser.Server.Implementations.Persistence } } + var folder = item as Folder; + if (folder != null && !reader.IsDBNull(54)) + { + folder.DateLastMediaAdded = reader.GetDateTime(54).ToUniversalTime(); + } + + if (!reader.IsDBNull(55)) + { + item.Album = reader.GetString(55); + } + return item; } @@ -1777,6 +1807,10 @@ namespace MediaBrowser.Server.Implementations.Persistence { return new Tuple("played", false); } + if (string.Equals(name, ItemSortBy.DateLastContentAdded, StringComparison.OrdinalIgnoreCase)) + { + return new Tuple("DateLastMediaAdded", false); + } return new Tuple(name, false); } @@ -2484,7 +2518,7 @@ namespace MediaBrowser.Server.Implementations.Persistence if (query.MediaTypes.Length == 1) { whereClauses.Add("MediaType=@MediaTypes"); - cmd.Parameters.Add(cmd, "@MediaTypes", DbType.String).Value = query.MediaTypes[0].ToString(); + cmd.Parameters.Add(cmd, "@MediaTypes", DbType.String).Value = query.MediaTypes[0]; } if (query.MediaTypes.Length > 1) { @@ -2493,6 +2527,26 @@ namespace MediaBrowser.Server.Implementations.Persistence whereClauses.Add("MediaType in (" + val + ")"); } + if (query.AlbumNames.Length > 0) + { + var clause = "("; + + var index = 0; + foreach (var name in query.AlbumNames) + { + if (index > 0) + { + clause += " OR "; + } + clause += "Album=@AlbumName" + index; + index++; + cmd.Parameters.Add(cmd, "@AlbumName" + index, DbType.String).Value = name; + } + + clause += ")"; + whereClauses.Add(clause); + } + //var enableItemsByName = query.IncludeItemsByName ?? query.IncludeItemTypes.Length > 0; var enableItemsByName = query.IncludeItemsByName ?? false; diff --git a/MediaBrowser.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs b/MediaBrowser.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs index 68cd44ec94..5c51f5e0fc 100644 --- a/MediaBrowser.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs +++ b/MediaBrowser.Server.Implementations/Sorting/DateLastMediaAddedComparer.cs @@ -49,10 +49,10 @@ namespace MediaBrowser.Server.Implementations.Sorting if (folder != null) { - return folder.GetRecursiveChildren(User, i => !i.IsFolder) - .Select(i => i.DateCreated) - .OrderByDescending(i => i) - .FirstOrDefault(); + if (folder.DateLastMediaAdded.HasValue) + { + return folder.DateLastMediaAdded.Value; + } } return x.DateCreated; diff --git a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj index f544a149d8..366d4b6083 100644 --- a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj +++ b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj @@ -142,8 +142,6 @@ - - diff --git a/MediaBrowser.ServerApplication/Native/WindowsApp.cs b/MediaBrowser.ServerApplication/Native/WindowsApp.cs index 808c7558ec..271b02d9a7 100644 --- a/MediaBrowser.ServerApplication/Native/WindowsApp.cs +++ b/MediaBrowser.ServerApplication/Native/WindowsApp.cs @@ -158,9 +158,9 @@ namespace MediaBrowser.ServerApplication.Native info.FFMpegFilename = "ffmpeg.exe"; info.FFProbeFilename = "ffprobe.exe"; - info.Version = "20160401"; + info.Version = "20160508"; info.ArchiveType = "7z"; - info.IsEmbedded = true; + info.IsEmbedded = false; info.DownloadUrls = GetDownloadUrls(); return info; @@ -212,11 +212,18 @@ namespace MediaBrowser.ServerApplication.Native switch (Environment.SystemArchitecture) { case Architecture.X86_X64: - return new[] { "MediaBrowser.ServerApplication.ffmpeg.ffmpegx64.7z" }; + return new[] + { + "https://github.com/MediaBrowser/Emby.Resources/raw/master/ffmpeg/windows/ffmpeg-20160508-win64.7z", + "https://ffmpeg.zeranoe.com/builds/win64/static/ffmpeg-20160508-git-caee88d-win64-static.7z" + }; case Architecture.X86: - return new[] { "MediaBrowser.ServerApplication.ffmpeg.ffmpegx86.7z" }; + return new[] + { + "https://github.com/MediaBrowser/Emby.Resources/raw/master/ffmpeg/windows/ffmpeg-20160508-win32.7z", + "https://ffmpeg.zeranoe.com/builds/win32/static/ffmpeg-20160508-git-caee88d-win32-static.7z" + }; } - return new string[] { }; } } diff --git a/MediaBrowser.ServerApplication/ffmpeg/ffmpegx64.7z.REMOVED.git-id b/MediaBrowser.ServerApplication/ffmpeg/ffmpegx64.7z.REMOVED.git-id deleted file mode 100644 index b0542b75f3..0000000000 --- a/MediaBrowser.ServerApplication/ffmpeg/ffmpegx64.7z.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -9dc10b022537738edce7eb71aa8dd4adbfee2c7b \ No newline at end of file diff --git a/MediaBrowser.ServerApplication/ffmpeg/ffmpegx86.7z.REMOVED.git-id b/MediaBrowser.ServerApplication/ffmpeg/ffmpegx86.7z.REMOVED.git-id deleted file mode 100644 index 3939ec44d6..0000000000 --- a/MediaBrowser.ServerApplication/ffmpeg/ffmpegx86.7z.REMOVED.git-id +++ /dev/null @@ -1 +0,0 @@ -00fa1afa35fbd0a7e97ad7956e42ae17f6882f64 \ No newline at end of file -- cgit v1.2.3 From 287f797d996c2080c8b9d7c438ad977ec6e5c45f Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 10 May 2016 01:00:50 -0400 Subject: update recording editor --- MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index b5e8ad79a5..ac8c99acec 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -1154,7 +1154,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV IncludeItemTypes = new[] { typeof(Episode).Name }, ParentIndexNumber = program.SeasonNumber.Value, IndexNumber = program.EpisodeNumber.Value, - AncestorIds = seriesIds + AncestorIds = seriesIds, + ExcludeLocationTypes = new[] { LocationType.Virtual } }); if (result.TotalRecordCount > 0) @@ -1169,7 +1170,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { IncludeItemTypes = new[] { typeof(Episode).Name }, Name = program.EpisodeTitle, - AncestorIds = seriesIds + AncestorIds = seriesIds, + ExcludeLocationTypes = new[] { LocationType.Virtual } }); if (result.TotalRecordCount > 0) -- cgit v1.2.3 From 9edda5782b6c6221e1b1def4e209b08c2f94ad9c Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 10 May 2016 01:15:06 -0400 Subject: update recording path --- .../LiveTv/EmbyTV/DirectRecorder.cs | 5 +++++ MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs | 5 +---- .../LiveTv/EmbyTV/EncodedRecorder.cs | 10 ++++++++++ MediaBrowser.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs | 2 ++ 4 files changed, 18 insertions(+), 4 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs index 54443d9ca3..b21aa904b9 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -23,6 +23,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _fileSystem = fileSystem; } + public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile) + { + return targetFile; + } + public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) { var httpRequestOptions = new HttpRequestOptions() diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index ac8c99acec..2de51479f2 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -898,10 +898,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV var recorder = await GetRecorder().ConfigureAwait(false); - if (recorder is EncodedRecorder) - { - recordPath = Path.ChangeExtension(recordPath, ".mp4"); - } + recordPath = recorder.GetOutputPath(mediaStreamInfo, recordPath); recordPath = EnsureFileUnique(recordPath, timer.Id); _fileSystem.CreateDirectory(Path.GetDirectoryName(recordPath)); activeRecordingInfo.Path = recordPath; diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index dec8ba83d2..85b6ead07b 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -42,6 +42,16 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _liveTvOptions = liveTvOptions; } + public string GetOutputPath(MediaSourceInfo mediaSource, string targetFile) + { + if (_liveTvOptions.EnableOriginalAudioWithEncodedRecordings) + { + return Path.ChangeExtension(targetFile, ".mkv"); + } + + return Path.ChangeExtension(targetFile, ".mp4"); + } + public async Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken) { if (mediaSource.RunTimeTicks.HasValue) diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs index 268a4f7512..5706b6ae9e 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs @@ -17,5 +17,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV /// The cancellation token. /// Task. Task Record(MediaSourceInfo mediaSource, string targetFile, TimeSpan duration, Action onStarted, CancellationToken cancellationToken); + + string GetOutputPath(MediaSourceInfo mediaSource, string targetFile); } } -- cgit v1.2.3 From 761a476ea09bfe657ca824d15b1a71a8f9f3206e Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 11 May 2016 13:46:44 -0400 Subject: use shared itemHelper --- MediaBrowser.Model/Dto/BaseItemDto.cs | 3 ++- MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Model/Dto/BaseItemDto.cs b/MediaBrowser.Model/Dto/BaseItemDto.cs index 49ec9f8ef4..146fcc74e8 100644 --- a/MediaBrowser.Model/Dto/BaseItemDto.cs +++ b/MediaBrowser.Model/Dto/BaseItemDto.cs @@ -297,7 +297,8 @@ namespace MediaBrowser.Model.Dto /// /// The number. public string Number { get; set; } - + public string ChannelNumber { get; set; } + /// /// Gets or sets the index number. /// diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index 175eed66c0..b3972a6778 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1515,6 +1515,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv { dto.ChannelName = channel.Name; dto.MediaType = channel.MediaType; + dto.ChannelNumber = channel.Number; if (channel.HasImage(ImageType.Primary)) { @@ -1854,6 +1855,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv var channel = tuple.Item2; dto.Number = channel.Number; + dto.ChannelNumber = channel.Number; dto.ChannelType = channel.ChannelType; dto.ServiceName = GetService(channel).Name; -- cgit v1.2.3 From c4e3bbaf4a9446250463f79c2b93728e8dfcd739 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 11 May 2016 18:08:19 -0400 Subject: import shared media info component --- .../Entities/Audio/MusicArtist.cs | 24 ++++++++++++++++++++-- .../LiveTv/EmbyTV/EncodedRecorder.cs | 7 ++++++- .../LiveTv/LiveTvManager.cs | 3 ++- 3 files changed, 30 insertions(+), 4 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index 6104976615..fb8a24061a 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -61,11 +61,31 @@ namespace MediaBrowser.Controller.Entities.Audio if (query.User != null) { return query.User.RootFolder - .GetRecursiveChildren(query.User, i => !i.IsFolder && itemByNameFilter(i)); + .GetRecursiveChildren(query.User, i => + { + if (query.IsFolder.HasValue) + { + if (query.IsFolder.Value != i.IsFolder) + { + return false; + } + } + return itemByNameFilter(i); + }); } return LibraryManager.RootFolder - .GetRecursiveChildren(i => !i.IsFolder && itemByNameFilter(i)); + .GetRecursiveChildren(i => + { + if (query.IsFolder.HasValue) + { + if (query.IsFolder.Value != i.IsFolder) + { + return false; + } + } + return itemByNameFilter(i); + }); } protected override IEnumerable ActualChildren diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs index 85b6ead07b..e9ea49fa32 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -46,7 +46,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { if (_liveTvOptions.EnableOriginalAudioWithEncodedRecordings) { - return Path.ChangeExtension(targetFile, ".mkv"); + // if the audio is aac_latm, stream copying to mp4 will fail + var streams = mediaSource.MediaStreams ?? new List(); + if (streams.Any(i => i.Type == MediaStreamType.Audio && (i.Codec ?? string.Empty).IndexOf("aac", StringComparison.OrdinalIgnoreCase) != -1)) + { + return Path.ChangeExtension(targetFile, ".mkv"); + } } return Path.ChangeExtension(targetFile, ".mp4"); diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index b3972a6778..f85be5100b 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -135,7 +135,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv var channels = _libraryManager.GetItemList(new InternalItemsQuery { - IncludeItemTypes = new[] { typeof(LiveTvChannel).Name } + IncludeItemTypes = new[] { typeof(LiveTvChannel).Name }, + SortBy = new[] { ItemSortBy.SortName } }).Cast(); -- cgit v1.2.3 From 995c34437e65b40576881a26c18f2ecf8b84ac89 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 15 May 2016 12:30:32 -0400 Subject: update tabs --- MediaBrowser.Dlna/Channels/DlnaChannelFactory.cs | 393 ++++++++++----------- MediaBrowser.Dlna/Main/DlnaEntryPoint.cs | 4 + .../Probing/ProbeResultNormalizer.cs | 3 +- .../LiveTv/LiveTvManager.cs | 33 +- 4 files changed, 225 insertions(+), 208 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Dlna/Channels/DlnaChannelFactory.cs b/MediaBrowser.Dlna/Channels/DlnaChannelFactory.cs index b6ee3d4341..a8e778751d 100644 --- a/MediaBrowser.Dlna/Channels/DlnaChannelFactory.cs +++ b/MediaBrowser.Dlna/Channels/DlnaChannelFactory.cs @@ -1,37 +1,190 @@ -namespace MediaBrowser.Dlna.Channels +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Channels; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Dlna; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Dlna.ContentDirectory; +using MediaBrowser.Dlna.PlayTo; +using MediaBrowser.Model.Channels; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Logging; + +namespace MediaBrowser.Dlna.Channels { - //public class DlnaChannelFactory : IChannelFactory, IDisposable + //public class DlnaChannel : IChannel, IDisposable //{ - // private readonly IServerConfigurationManager _config; // private readonly ILogger _logger; // private readonly IHttpClient _httpClient; + // private readonly IServerConfigurationManager _config; + // private List _servers = new List(); // private readonly IDeviceDiscovery _deviceDiscovery; - // private readonly SemaphoreSlim _syncLock = new SemaphoreSlim(1, 1); - // private List _servers = new List(); - - // public static DlnaChannelFactory Instance; - // private Func> _localServersLookup; - // public DlnaChannelFactory(IServerConfigurationManager config, IHttpClient httpClient, ILogger logger, IDeviceDiscovery deviceDiscovery) + // public static DlnaChannel Current; + + // public DlnaChannel(ILogger logger, IHttpClient httpClient, IDeviceDiscovery deviceDiscovery, IServerConfigurationManager config) // { - // _config = config; - // _httpClient = httpClient; // _logger = logger; + // _httpClient = httpClient; // _deviceDiscovery = deviceDiscovery; - // Instance = this; + // _config = config; + // Current = this; + // } + + // public string Name + // { + // get { return "Devices"; } + // } + + // public string Description + // { + // get { return string.Empty; } + // } + + // public string DataVersion + // { + // get { return DateTime.UtcNow.Ticks.ToString(); } + // } + + // public string HomePageUrl + // { + // get { return string.Empty; } + // } + + // public ChannelParentalRating ParentalRating + // { + // get { return ChannelParentalRating.GeneralAudience; } + // } + + // public InternalChannelFeatures GetChannelFeatures() + // { + // return new InternalChannelFeatures + // { + // ContentTypes = new List + // { + // ChannelMediaContentType.Song, + // ChannelMediaContentType.Clip + // }, + + // MediaTypes = new List + // { + // ChannelMediaType.Audio, + // ChannelMediaType.Video, + // ChannelMediaType.Photo + // } + // }; + // } + + // public bool IsEnabledFor(string userId) + // { + // return true; + // } + + // public Task GetChannelImage(ImageType type, CancellationToken cancellationToken) + // { + // throw new NotImplementedException(); + // } + + // public IEnumerable GetSupportedChannelImages() + // { + // return new List + // { + // ImageType.Primary + // }; // } - // internal void Start(Func> localServersLookup) + // public void Start(Func> localServersLookup) // { // _localServersLookup = localServersLookup; - // //deviceDiscovery.DeviceDiscovered += deviceDiscovery_DeviceDiscovered; + // _deviceDiscovery.DeviceDiscovered -= deviceDiscovery_DeviceDiscovered; + // _deviceDiscovery.DeviceLeft -= deviceDiscovery_DeviceLeft; + + // _deviceDiscovery.DeviceDiscovered += deviceDiscovery_DeviceDiscovered; // _deviceDiscovery.DeviceLeft += deviceDiscovery_DeviceLeft; // } + // public async Task GetChannelItems(InternalChannelItemQuery query, CancellationToken cancellationToken) + // { + // if (string.IsNullOrWhiteSpace(query.FolderId)) + // { + // return await GetServers(query, cancellationToken).ConfigureAwait(false); + // } + + // return new ChannelItemResult(); + + // //var idParts = query.FolderId.Split('|'); + // //var folderId = idParts.Length == 2 ? idParts[1] : null; + + // //var result = await new ContentDirectoryBrowser(_httpClient, _logger).Browse(new ContentDirectoryBrowseRequest + // //{ + // // Limit = query.Limit, + // // StartIndex = query.StartIndex, + // // ParentId = folderId, + // // ContentDirectoryUrl = ControlUrl + + // //}, cancellationToken).ConfigureAwait(false); + + // //items = result.Items.ToList(); + + // //var list = items.ToList(); + // //var count = list.Count; + + // //list = ApplyPaging(list, query).ToList(); + + // //return new ChannelItemResult + // //{ + // // Items = list, + // // TotalRecordCount = count + // //}; + // } + + // public async Task GetServers(InternalChannelItemQuery query, CancellationToken cancellationToken) + // { + // await _syncLock.WaitAsync(cancellationToken).ConfigureAwait(false); + + // try + // { + // var items = _servers.Select(i => + // { + // var service = i.Properties.Services + // .FirstOrDefault(s => string.Equals(s.ServiceType, "urn:schemas-upnp-org:service:ContentDirectory:1", StringComparison.OrdinalIgnoreCase)); + + // var controlUrl = service == null ? null : (_servers[0].Properties.BaseUrl.TrimEnd('/') + "/" + service.ControlUrl.TrimStart('/')); + + // if (string.IsNullOrWhiteSpace(controlUrl)) + // { + // return null; + // } + + // return new ChannelItemInfo + // { + // Id = i.Properties.UUID, + // Name = i.Properties.Name, + // Type = ChannelItemType.Folder + // }; + + // }).Where(i => i != null).ToList(); + + // return new ChannelItemResult + // { + // TotalRecordCount = items.Count, + // Items = items + // }; + // } + // finally + // { + // _syncLock.Release(); + // } + // } + // async void deviceDiscovery_DeviceDiscovered(object sender, SsdpMessageEventArgs e) // { // string usn; @@ -57,16 +210,13 @@ // } // } - // if (GetExistingServers(usn).Any()) - // { - // return; - // } - // await _syncLock.WaitAsync().ConfigureAwait(false); + // var serverList = _servers.ToList(); + // try // { - // if (GetExistingServers(usn).Any()) + // if (GetExistingServers(serverList, usn).Any()) // { // return; // } @@ -74,9 +224,9 @@ // var device = await Device.CreateuPnpDeviceAsync(new Uri(location), _httpClient, _config, _logger) // .ConfigureAwait(false); - // if (!_servers.Any(i => string.Equals(i.Properties.UUID, device.Properties.UUID, StringComparison.OrdinalIgnoreCase))) + // if (!serverList.Any(i => string.Equals(i.Properties.UUID, device.Properties.UUID, StringComparison.OrdinalIgnoreCase))) // { - // _servers.Add(device); + // serverList.Add(device); // } // } // catch (Exception ex) @@ -102,23 +252,22 @@ // return; // } - // if (!GetExistingServers(usn).Any()) - // { - // return; - // } - // await _syncLock.WaitAsync().ConfigureAwait(false); // try // { - // var list = _servers.ToList(); + // var serverList = _servers.ToList(); - // foreach (var device in GetExistingServers(usn).ToList()) + // var matchingServers = GetExistingServers(serverList, usn); + // if (matchingServers.Count > 0) // { - // list.Remove(device); - // } + // foreach (var device in matchingServers) + // { + // serverList.Remove(device); + // } - // _servers = list; + // _servers = serverList; + // } // } // finally // { @@ -140,185 +289,17 @@ // return true; // } - // private IEnumerable GetExistingServers(string usn) - // { - // return _servers - // .Where(i => usn.IndexOf(i.Properties.UUID, StringComparison.OrdinalIgnoreCase) != -1); - // } - - // public IEnumerable GetChannels() + // private List GetExistingServers(List allDevices, string usn) // { - // //if (_servers.Count > 0) - // //{ - // // var service = _servers[0].Properties.Services - // // .FirstOrDefault(i => string.Equals(i.ServiceType, "urn:schemas-upnp-org:service:ContentDirectory:1", StringComparison.OrdinalIgnoreCase)); - - // // var controlUrl = service == null ? null : (_servers[0].Properties.BaseUrl.TrimEnd('/') + "/" + service.ControlUrl.TrimStart('/')); - - // // if (!string.IsNullOrEmpty(controlUrl)) - // // { - // // return new List - // // { - // // new ServerChannel(_servers.ToList(), _httpClient, _logger, controlUrl) - // // }; - // // } - // //} - - // return new List(); + // return allDevices + // .Where(i => usn.IndexOf(i.Properties.UUID, StringComparison.OrdinalIgnoreCase) != -1) + // .ToList(); // } // public void Dispose() // { - // if (_deviceDiscovery != null) - // { - // _deviceDiscovery.DeviceDiscovered -= deviceDiscovery_DeviceDiscovered; - // _deviceDiscovery.DeviceLeft -= deviceDiscovery_DeviceLeft; - // } - // } - //} - - //public class ServerChannel : IChannel, IFactoryChannel - //{ - // private readonly IHttpClient _httpClient; - // private readonly ILogger _logger; - // public string ControlUrl { get; set; } - // public List Servers { get; set; } - - // public ServerChannel(IHttpClient httpClient, ILogger logger) - // { - // _httpClient = httpClient; - // _logger = logger; - // Servers = new List(); - // } - - // public string Name - // { - // get { return "Devices"; } - // } - - // public string Description - // { - // get { return string.Empty; } - // } - - // public string DataVersion - // { - // get { return DateTime.UtcNow.Ticks.ToString(); } - // } - - // public string HomePageUrl - // { - // get { return string.Empty; } - // } - - // public ChannelParentalRating ParentalRating - // { - // get { return ChannelParentalRating.GeneralAudience; } - // } - - // public InternalChannelFeatures GetChannelFeatures() - // { - // return new InternalChannelFeatures - // { - // ContentTypes = new List - // { - // ChannelMediaContentType.Song, - // ChannelMediaContentType.Clip - // }, - - // MediaTypes = new List - // { - // ChannelMediaType.Audio, - // ChannelMediaType.Video, - // ChannelMediaType.Photo - // } - // }; - // } - - // public bool IsEnabledFor(string userId) - // { - // return true; - // } - - // public async Task GetChannelItems(InternalChannelItemQuery query, CancellationToken cancellationToken) - // { - // IEnumerable items; - - // if (string.IsNullOrWhiteSpace(query.FolderId)) - // { - // items = Servers.Select(i => new ChannelItemInfo - // { - // FolderType = ChannelFolderType.Container, - // Id = GetServerId(i), - // Name = i.Properties.Name, - // Overview = i.Properties.ModelDescription, - // Type = ChannelItemType.Folder - // }); - // } - // else - // { - // var idParts = query.FolderId.Split('|'); - // var folderId = idParts.Length == 2 ? idParts[1] : null; - - // var result = await new ContentDirectoryBrowser(_httpClient, _logger).Browse(new ContentDirectoryBrowseRequest - // { - // Limit = query.Limit, - // StartIndex = query.StartIndex, - // ParentId = folderId, - // ContentDirectoryUrl = ControlUrl - - // }, cancellationToken).ConfigureAwait(false); - - // items = result.Items.ToList(); - // } - - // var list = items.ToList(); - // var count = list.Count; - - // list = ApplyPaging(list, query).ToList(); - - // return new ChannelItemResult - // { - // Items = list, - // TotalRecordCount = count - // }; - // } - - // private string GetServerId(Device device) - // { - // return device.Properties.UUID.GetMD5().ToString("N"); - // } - - // private IEnumerable ApplyPaging(IEnumerable items, InternalChannelItemQuery query) - // { - // if (query.StartIndex.HasValue) - // { - // items = items.Skip(query.StartIndex.Value); - // } - - // if (query.Limit.HasValue) - // { - // items = items.Take(query.Limit.Value); - // } - - // return items; - // } - - // public Task GetChannelImage(ImageType type, CancellationToken cancellationToken) - // { - // // TODO: Implement - // return Task.FromResult(new DynamicImageResponse - // { - // HasImage = false - // }); - // } - - // public IEnumerable GetSupportedChannelImages() - // { - // return new List - // { - // ImageType.Primary - // }; + // _deviceDiscovery.DeviceDiscovered -= deviceDiscovery_DeviceDiscovered; + // _deviceDiscovery.DeviceLeft -= deviceDiscovery_DeviceLeft; // } //} } diff --git a/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs b/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs index a2e9cd60e7..22f308979f 100644 --- a/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs +++ b/MediaBrowser.Dlna/Main/DlnaEntryPoint.cs @@ -14,7 +14,9 @@ using MediaBrowser.Dlna.Ssdp; using MediaBrowser.Model.Logging; using System; using System.Collections.Generic; +using System.Linq; using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Dlna.Channels; namespace MediaBrowser.Dlna.Main { @@ -167,6 +169,8 @@ namespace MediaBrowser.Dlna.Main try { ((DeviceDiscovery)_deviceDiscovery).Start(_ssdpHandler); + + //DlnaChannel.Current.Start(() => _registeredServerIds.ToList()); } catch (Exception ex) { diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index 1a95bdf9d7..44c69d4c1b 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -548,7 +548,8 @@ namespace MediaBrowser.MediaEncoding.Probing private void NormalizeStreamTitle(MediaStream stream) { - if (string.Equals(stream.Title, "sdh", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(stream.Title, "sdh", StringComparison.OrdinalIgnoreCase) || + string.Equals(stream.Title, "cc", StringComparison.OrdinalIgnoreCase)) { stream.Title = null; } diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index f85be5100b..99ab07648d 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1383,6 +1383,28 @@ namespace MediaBrowser.Server.Implementations.LiveTv } } + private QueryResult GetEmbyRecordings(RecordingQuery query, User user) + { + var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders() + .SelectMany(i => i.Locations) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Select(i => _libraryManager.FindByPath(i, true)) + .Where(i => i != null) + .Where(i => i.IsVisibleStandalone(user)) + .ToList(); + + var items = _libraryManager.GetItemsResult(new InternalItemsQuery(user) + { + MediaTypes = new[] { MediaType.Video }, + Recursive = true, + AncestorIds = folders.Select(i => i.Id.ToString("N")).ToArray(), + ExcludeLocationTypes = new[] { LocationType.Virtual }, + Limit = Math.Min(10, query.Limit ?? int.MaxValue) + }); + + return items; + } + public async Task> GetInternalRecordings(RecordingQuery query, CancellationToken cancellationToken) { var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId); @@ -1391,6 +1413,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv return new QueryResult(); } + if (user != null && !(query.IsInProgress ?? false)) + { + var initialResult = GetEmbyRecordings(query, user); + if (initialResult.TotalRecordCount > 0) + { + return initialResult; + } + } + await RefreshRecordings(cancellationToken).ConfigureAwait(false); var internalQuery = new InternalItemsQuery(user) @@ -2060,7 +2091,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv }, cancellationToken).ConfigureAwait(false); - var recordings = recordingResult.Items.Cast().ToList(); + var recordings = recordingResult.Items.OfType().ToList(); var groups = new List(); -- cgit v1.2.3 From 233f9cb238201c7dfdb060b718ff635947161f30 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 15 May 2016 21:22:22 -0400 Subject: update shared components --- MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs | 13 +++++++------ .../Notifications/SqliteNotificationsRepository.cs | 3 ++- 2 files changed, 9 insertions(+), 7 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index 99ab07648d..9251ccb9ee 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -1385,6 +1385,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv private QueryResult GetEmbyRecordings(RecordingQuery query, User user) { + if (user == null || (query.IsInProgress ?? false)) + { + return new QueryResult(); + } + var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders() .SelectMany(i => i.Locations) .Distinct(StringComparer.OrdinalIgnoreCase) @@ -1413,13 +1418,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv return new QueryResult(); } - if (user != null && !(query.IsInProgress ?? false)) + if (_services.Count == 1) { - var initialResult = GetEmbyRecordings(query, user); - if (initialResult.TotalRecordCount > 0) - { - return initialResult; - } + return GetEmbyRecordings(query, user); } await RefreshRecordings(cancellationToken).ConfigureAwait(false); diff --git a/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs b/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs index cecf03ddfe..10e8c5699e 100644 --- a/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs +++ b/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs @@ -41,7 +41,8 @@ namespace MediaBrowser.Server.Implementations.Notifications string[] queries = { "create table if not exists Notifications (Id GUID NOT NULL, UserId GUID NOT NULL, Date DATETIME NOT NULL, Name TEXT NOT NULL, Description TEXT, Url TEXT, Level TEXT NOT NULL, IsRead BOOLEAN NOT NULL, Category TEXT NOT NULL, RelatedId TEXT, PRIMARY KEY (Id, UserId))", - "create index if not exists idx_Notifications on Notifications(Id, UserId)", + "create index if not exists idx_Notifications1 on Notifications(Id)", + "create index if not exists idx_Notifications2 on Notifications(UserId)", //pragmas "pragma temp_store = memory", -- cgit v1.2.3 From da29fc8c687dd80f2183f49c3b3caf125e9b5466 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Tue, 17 May 2016 15:18:50 -0400 Subject: update channel display --- MediaBrowser.Model/Querying/ItemQuery.cs | 4 ++++ .../LiveTv/LiveTvManager.cs | 14 +++++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Model/Querying/ItemQuery.cs b/MediaBrowser.Model/Querying/ItemQuery.cs index 5a88c0d43e..11c0464522 100644 --- a/MediaBrowser.Model/Querying/ItemQuery.cs +++ b/MediaBrowser.Model/Querying/ItemQuery.cs @@ -288,6 +288,8 @@ namespace MediaBrowser.Model.Querying [Obsolete] public string Person { get; set; } + public bool EnableTotalRecordCount { get; set; } + /// /// Initializes a new instance of the class. /// @@ -306,6 +308,8 @@ namespace MediaBrowser.Model.Querying VideoTypes = new VideoType[] { }; + EnableTotalRecordCount = true; + Artists = new string[] { }; Studios = new string[] { }; diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index 9251ccb9ee..dc347c1dc8 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -527,6 +527,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv private async Task GetChannel(ChannelInfo channelInfo, string serviceName, Guid parentFolderId, CancellationToken cancellationToken) { var isNew = false; + var forceUpdate = false; var id = _tvDtoService.GetInternalChannelId(serviceName, channelInfo.Id); @@ -576,10 +577,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv if (!string.IsNullOrWhiteSpace(channelInfo.ImagePath)) { item.SetImagePath(ImageType.Primary, channelInfo.ImagePath); + forceUpdate = true; } else if (!string.IsNullOrWhiteSpace(channelInfo.ImageUrl)) { item.SetImagePath(ImageType.Primary, channelInfo.ImageUrl); + forceUpdate = true; } } @@ -588,9 +591,18 @@ namespace MediaBrowser.Server.Implementations.LiveTv item.Name = channelInfo.Name; } + if (isNew) + { + await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false); + } + else if (forceUpdate) + { + await _libraryManager.UpdateItem(item, ItemUpdateType.MetadataImport, cancellationToken).ConfigureAwait(false); + } + await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) { - ForceSave = isNew + ForceSave = isNew || forceUpdate }, cancellationToken); -- cgit v1.2.3 From d1d0487feee578822e76ca48e88dc61b94080570 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 18 May 2016 01:34:10 -0400 Subject: update artist queries --- MediaBrowser.Api/FilterService.cs | 3 +- MediaBrowser.Api/GamesService.cs | 5 +- .../UserLibrary/BaseItemsByNameService.cs | 9 +- MediaBrowser.Api/UserLibrary/ItemsService.cs | 12 +-- .../Entities/Audio/MusicArtist.cs | 36 ++------ MediaBrowser.Controller/Entities/Folder.cs | 71 ++++++++------- MediaBrowser.Controller/Entities/IItemByName.cs | 6 -- .../Entities/InternalItemsQuery.cs | 3 +- MediaBrowser.Controller/Entities/TV/Series.cs | 12 ++- MediaBrowser.Controller/Entities/UserView.cs | 11 ++- .../Entities/UserViewBuilder.cs | 45 +++++---- MediaBrowser.Controller/Playlists/Playlist.cs | 12 ++- .../ContentDirectory/ControlHandler.cs | 33 ++----- .../Library/LibraryManager.cs | 8 +- .../Library/MusicManager.cs | 20 +++- .../LiveTv/LiveTvManager.cs | 4 +- .../Persistence/SqliteItemRepository.cs | 101 ++++++++++++++++++++- 17 files changed, 245 insertions(+), 146 deletions(-) (limited to 'MediaBrowser.Server.Implementations/LiveTv') diff --git a/MediaBrowser.Api/FilterService.cs b/MediaBrowser.Api/FilterService.cs index 6d1c5d868d..c4419531c5 100644 --- a/MediaBrowser.Api/FilterService.cs +++ b/MediaBrowser.Api/FilterService.cs @@ -103,7 +103,8 @@ namespace MediaBrowser.Api User = user, MediaTypes = request.GetMediaTypes(), IncludeItemTypes = request.GetIncludeItemTypes(), - Recursive = true + Recursive = true, + EnableTotalRecordCount = false }; return query; diff --git a/MediaBrowser.Api/GamesService.cs b/MediaBrowser.Api/GamesService.cs index 040872fcc8..387771b6d5 100644 --- a/MediaBrowser.Api/GamesService.cs +++ b/MediaBrowser.Api/GamesService.cs @@ -162,7 +162,10 @@ namespace MediaBrowser.Api var items = user == null ? system.GetRecursiveChildren(i => i is Game) : - system.GetRecursiveChildren(user, i => i is Game); + system.GetRecursiveChildren(user, new InternalItemsQuery(user) + { + IncludeItemTypes = new[] { typeof(Game).Name } + }); var games = items.Cast().ToList(); diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs index b3164ce3f7..565bed0531 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs @@ -121,6 +121,13 @@ namespace MediaBrowser.Api.UserLibrary var includeItemTypes = request.GetIncludeItemTypes(); var mediaTypes = request.GetMediaTypes(); + var query = new InternalItemsQuery(user) + { + ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = includeItemTypes, + MediaTypes = mediaTypes + }; + Func filter = i => FilterItem(request, i, excludeItemTypes, includeItemTypes, mediaTypes); if (parentItem.IsFolder) @@ -130,7 +137,7 @@ namespace MediaBrowser.Api.UserLibrary if (!string.IsNullOrWhiteSpace(request.UserId)) { items = request.Recursive ? - folder.GetRecursiveChildren(user, filter) : + folder.GetRecursiveChildren(user, query) : folder.GetChildren(user, true).Where(filter); } else diff --git a/MediaBrowser.Api/UserLibrary/ItemsService.cs b/MediaBrowser.Api/UserLibrary/ItemsService.cs index ff937078e6..dac1a6b1a8 100644 --- a/MediaBrowser.Api/UserLibrary/ItemsService.cs +++ b/MediaBrowser.Api/UserLibrary/ItemsService.cs @@ -138,25 +138,19 @@ namespace MediaBrowser.Api.UserLibrary if (request.Recursive) { - var result = await ((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false); - - return result; + return await ((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false); } if (user == null) { - var result = await ((Folder)item).GetItems(GetItemsQuery(request, null)).ConfigureAwait(false); - - return result; + return await ((Folder)item).GetItems(GetItemsQuery(request, null)).ConfigureAwait(false); } var userRoot = item as UserRootFolder; if (userRoot == null) { - var result = await ((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false); - - return result; + return await ((Folder)item).GetItems(GetItemsQuery(request, user)).ConfigureAwait(false); } IEnumerable items = ((Folder)item).GetChildren(user, true); diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index fb8a24061a..df46e42086 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -56,36 +56,20 @@ namespace MediaBrowser.Controller.Entities.Audio public IEnumerable GetTaggedItems(InternalItemsQuery query) { - var itemByNameFilter = GetItemFilter(); + if (query.IncludeItemTypes.Length == 0) + { + query.IncludeItemTypes = new[] { typeof(Audio).Name, typeof(MusicVideo).Name, typeof(MusicAlbum).Name }; + query.ArtistNames = new[] { Name }; + } - if (query.User != null) + // Need this for now since the artist filter isn't yet supported by the db + if (ConfigurationManager.Configuration.SchemaVersion < 79) { - return query.User.RootFolder - .GetRecursiveChildren(query.User, i => - { - if (query.IsFolder.HasValue) - { - if (query.IsFolder.Value != i.IsFolder) - { - return false; - } - } - return itemByNameFilter(i); - }); + var filter = GetItemFilter(); + return LibraryManager.GetItemList(query).Where(filter); } - return LibraryManager.RootFolder - .GetRecursiveChildren(i => - { - if (query.IsFolder.HasValue) - { - if (query.IsFolder.Value != i.IsFolder) - { - return false; - } - } - return itemByNameFilter(i); - }); + return LibraryManager.GetItemList(query); } protected override IEnumerable ActualChildren diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 77e3624191..57b218b4d2 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -749,7 +749,7 @@ namespace MediaBrowser.Controller.Entities { var user = query.User; - if (RequiresPostFiltering(query)) + if (!query.ForceDirect && RequiresPostFiltering(query)) { IEnumerable items; Func filter = i => UserViewBuilder.Filter(i, user, query, UserDataManager, LibraryManager); @@ -760,7 +760,7 @@ namespace MediaBrowser.Controller.Entities } else { - items = GetRecursiveChildren(user, filter); + items = GetRecursiveChildren(user, query); } return PostFilterAndSort(items, query); @@ -817,19 +817,24 @@ namespace MediaBrowser.Controller.Entities return true; } } - if (query.SortBy.Contains(ItemSortBy.AiredEpisodeOrder, StringComparer.OrdinalIgnoreCase)) - { - Logger.Debug("Query requires post-filtering due to ItemSortBy.AiredEpisodeOrder"); - return true; - } - if (query.SortBy.Contains(ItemSortBy.AlbumArtist, StringComparer.OrdinalIgnoreCase)) + + if (ConfigurationManager.Configuration.SchemaVersion < 79) { - Logger.Debug("Query requires post-filtering due to ItemSortBy.AlbumArtist"); - return true; + if (query.SortBy.Contains(ItemSortBy.AlbumArtist, StringComparer.OrdinalIgnoreCase)) + { + Logger.Debug("Query requires post-filtering due to ItemSortBy.AlbumArtist"); + return true; + } + if (query.SortBy.Contains(ItemSortBy.Artist, StringComparer.OrdinalIgnoreCase)) + { + Logger.Debug("Query requires post-filtering due to ItemSortBy.Artist"); + return true; + } } - if (query.SortBy.Contains(ItemSortBy.Artist, StringComparer.OrdinalIgnoreCase)) + + if (query.SortBy.Contains(ItemSortBy.AiredEpisodeOrder, StringComparer.OrdinalIgnoreCase)) { - Logger.Debug("Query requires post-filtering due to ItemSortBy.Artist"); + Logger.Debug("Query requires post-filtering due to ItemSortBy.AiredEpisodeOrder"); return true; } if (query.SortBy.Contains(ItemSortBy.Budget, StringComparer.OrdinalIgnoreCase)) @@ -1109,10 +1114,13 @@ namespace MediaBrowser.Controller.Entities return true; } - if (query.ArtistNames.Length > 0) + if (ConfigurationManager.Configuration.SchemaVersion < 79) { - Logger.Debug("Query requires post-filtering due to ArtistNames"); - return true; + if (query.ArtistNames.Length > 0) + { + Logger.Debug("Query requires post-filtering due to ArtistNames"); + return true; + } } return false; @@ -1178,7 +1186,7 @@ namespace MediaBrowser.Controller.Entities else { items = query.Recursive - ? GetRecursiveChildren(user, filter) + ? GetRecursiveChildren(user, query) : GetChildren(user, true).Where(filter); } @@ -1215,19 +1223,14 @@ namespace MediaBrowser.Controller.Entities /// /// Adds the children to list. /// - /// The user. - /// if set to true [include linked children]. - /// The result. - /// if set to true [recursive]. - /// The filter. /// true if XXXX, false otherwise - private void AddChildren(User user, bool includeLinkedChildren, Dictionary result, bool recursive, Func filter) + private void AddChildren(User user, bool includeLinkedChildren, Dictionary result, bool recursive, InternalItemsQuery query) { foreach (var child in GetEligibleChildrenForRecursiveChildren(user)) { if (child.IsVisible(user)) { - if (filter == null || filter(child)) + if (query == null || UserViewBuilder.FilterItem(child, query)) { result[child.Id] = child; } @@ -1236,7 +1239,7 @@ namespace MediaBrowser.Controller.Entities { var folder = (Folder)child; - folder.AddChildren(user, includeLinkedChildren, result, true, filter); + folder.AddChildren(user, includeLinkedChildren, result, true, query); } } } @@ -1247,7 +1250,7 @@ namespace MediaBrowser.Controller.Entities { if (child.IsVisible(user)) { - if (filter == null || filter(child)) + if (query == null || UserViewBuilder.FilterItem(child, query)) { result[child.Id] = child; } @@ -1265,10 +1268,10 @@ namespace MediaBrowser.Controller.Entities /// public IEnumerable GetRecursiveChildren(User user, bool includeLinkedChildren = true) { - return GetRecursiveChildren(user, i => true); + return GetRecursiveChildren(user, null); } - public virtual IEnumerable GetRecursiveChildren(User user, Func filter) + public virtual IEnumerable GetRecursiveChildren(User user, InternalItemsQuery query) { if (user == null) { @@ -1277,7 +1280,7 @@ namespace MediaBrowser.Controller.Entities var result = new Dictionary(); - AddChildren(user, true, result, true, filter); + AddChildren(user, true, result, true, query); return result.Values; } @@ -1534,7 +1537,8 @@ namespace MediaBrowser.Controller.Entities User = user, Recursive = true, IsFolder = false, - IsUnaired = false + IsUnaired = false, + EnableTotalRecordCount = false }; @@ -1562,7 +1566,8 @@ namespace MediaBrowser.Controller.Entities { User = user, Recursive = true, - IsFolder = false + IsFolder = false, + EnableTotalRecordCount = false }).ConfigureAwait(false); @@ -1578,7 +1583,8 @@ namespace MediaBrowser.Controller.Entities { Recursive = true, IsFolder = false, - ExcludeLocationTypes = new[] { LocationType.Virtual } + ExcludeLocationTypes = new[] { LocationType.Virtual }, + EnableTotalRecordCount = false }).Result; @@ -1630,7 +1636,8 @@ namespace MediaBrowser.Controller.Entities { Recursive = true, IsFolder = false, - ExcludeLocationTypes = new[] { LocationType.Virtual } + ExcludeLocationTypes = new[] { LocationType.Virtual }, + EnableTotalRecordCount = false }).Result; diff --git a/MediaBrowser.Controller/Entities/IItemByName.cs b/MediaBrowser.Controller/Entities/IItemByName.cs index 7747e738cb..2ac4af1af7 100644 --- a/MediaBrowser.Controller/Entities/IItemByName.cs +++ b/MediaBrowser.Controller/Entities/IItemByName.cs @@ -15,12 +15,6 @@ namespace MediaBrowser.Controller.Entities /// IEnumerable{BaseItem}. IEnumerable GetTaggedItems(IEnumerable inputItems); - /// - /// Gets the item filter. - /// - /// Func<BaseItem, System.Boolean>. - Func GetItemFilter(); - IEnumerable GetTaggedItems(InternalItemsQuery query); } diff --git a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs index ae38f6143d..823f4066c4 100644 --- a/MediaBrowser.Controller/Entities/InternalItemsQuery.cs +++ b/MediaBrowser.Controller/Entities/InternalItemsQuery.cs @@ -19,8 +19,6 @@ namespace MediaBrowser.Controller.Entities public User User { get; set; } - public Func Filter { get; set; } - public bool? IsFolder { get; set; } public bool? IsFavorite { get; set; } public bool? IsFavoriteOrLiked { get; set; } @@ -138,6 +136,7 @@ namespace MediaBrowser.Controller.Entities public bool GroupByPresentationUniqueKey { get; set; } public bool EnableTotalRecordCount { get; set; } + public bool ForceDirect { get; set; } public InternalItemsQuery() { diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 82ab99980d..4a1982edca 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -381,14 +381,18 @@ namespace MediaBrowser.Controller.Entities.TV } else { - episodes = GetRecursiveChildren(user, i => i is Episode) - .Cast(); + episodes = GetRecursiveChildren(user, new InternalItemsQuery(user) + { + IncludeItemTypes = new[] { typeof(Episode).Name } + }).Cast(); } } else { - episodes = GetRecursiveChildren(user, i => i is Episode) - .Cast(); + episodes = GetRecursiveChildren(user, new InternalItemsQuery(user) + { + IncludeItemTypes = new[] { typeof(Episode).Name } + }).Cast(); } episodes = FilterEpisodesBySeason(episodes, seasonNumber, DisplaySpecialsWithSeasons); diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index 40fec3e288..e40d9ca381 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -66,7 +66,8 @@ namespace MediaBrowser.Controller.Entities { var result = GetItems(new InternalItemsQuery { - User = user + User = user, + EnableTotalRecordCount = false }).Result; @@ -83,17 +84,19 @@ namespace MediaBrowser.Controller.Entities return true; } - public override IEnumerable GetRecursiveChildren(User user, Func filter) + public override IEnumerable GetRecursiveChildren(User user, InternalItemsQuery query) { var result = GetItems(new InternalItemsQuery { User = user, Recursive = true, - Filter = filter + EnableTotalRecordCount = false, + + ForceDirect = true }).Result; - return result.Items; + return result.Items.Where(i => UserViewBuilder.FilterItem(i, query)); } protected override IEnumerable GetEligibleChildrenForRecursiveChildren(User user) diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index b9f6babfde..682eafb373 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -128,7 +128,11 @@ namespace MediaBrowser.Controller.Entities { if (query.Recursive) { - return GetResult(queryParent.GetRecursiveChildren(user, true), queryParent, query); + query.Recursive = true; + query.ParentId = queryParent.Id; + query.SetUser(user); + + return _libraryManager.GetItemsResult(query); } return GetResult(queryParent.GetChildren(user, true), queryParent, query); } @@ -328,9 +332,13 @@ namespace MediaBrowser.Controller.Entities private QueryResult GetMusicAlbumArtists(Folder parent, User user, InternalItemsQuery query) { - var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos }) - .Where(i => !i.IsFolder) - .OfType(); + var items = _libraryManager.GetItemList(new InternalItemsQuery(user) + { + Recursive = true, + ParentId = parent.Id, + IncludeItemTypes = new[] { typeof(Audio.Audio).Name } + + }).Cast(); var artists = _libraryManager.GetAlbumArtists(items); @@ -339,9 +347,13 @@ namespace MediaBrowser.Controller.Entities private QueryResult GetMusicArtists(Folder parent, User user, InternalItemsQuery query) { - var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos }) - .Where(i => !i.IsFolder) - .OfType(); + var items = _libraryManager.GetItemList(new InternalItemsQuery(user) + { + Recursive = true, + ParentId = parent.Id, + IncludeItemTypes = new[] { typeof(Audio.Audio).Name, typeof(MusicVideo).Name } + + }).Cast(); var artists = _libraryManager.GetArtists(items); @@ -350,9 +362,13 @@ namespace MediaBrowser.Controller.Entities private QueryResult GetFavoriteArtists(Folder parent, User user, InternalItemsQuery query) { - var items = GetRecursiveChildren(parent, user, new[] { CollectionType.Music, CollectionType.MusicVideos }) - .Where(i => !i.IsFolder) - .OfType(); + var items = _libraryManager.GetItemList(new InternalItemsQuery(user) + { + Recursive = true, + ParentId = parent.Id, + IncludeItemTypes = new[] { typeof(Audio.Audio).Name } + + }).Cast(); var artists = _libraryManager.GetAlbumArtists(items).Where(i => _userDataManager.GetUserData(user, i).IsFavorite); @@ -753,9 +769,9 @@ namespace MediaBrowser.Controller.Entities return PostFilterAndSort(items, queryParent, null, query, _libraryManager); } - public bool FilterItem(BaseItem item, InternalItemsQuery query) + public static bool FilterItem(BaseItem item, InternalItemsQuery query) { - return Filter(item, query.User, query, _userDataManager, _libraryManager); + return Filter(item, query.User, query, BaseItem.UserDataManager, BaseItem.LibraryManager); } private QueryResult PostFilterAndSort(IEnumerable items, @@ -1274,11 +1290,6 @@ namespace MediaBrowser.Controller.Entities return false; } - if (query.Filter != null && !query.Filter(item)) - { - return false; - } - UserItemData userData = null; if (query.IsLiked.HasValue) diff --git a/MediaBrowser.Controller/Playlists/Playlist.cs b/MediaBrowser.Controller/Playlists/Playlist.cs index 67b1d479b9..5ffe3d5daf 100644 --- a/MediaBrowser.Controller/Playlists/Playlist.cs +++ b/MediaBrowser.Controller/Playlists/Playlist.cs @@ -63,13 +63,13 @@ namespace MediaBrowser.Controller.Playlists return GetPlayableItems(user).Result; } - public override IEnumerable GetRecursiveChildren(User user, Func filter) + public override IEnumerable GetRecursiveChildren(User user, InternalItemsQuery query) { var items = GetPlayableItems(user).Result; - if (filter != null) + if (query != null) { - items = items.Where(filter); + items = items.Where(i => UserViewBuilder.FilterItem(i, query)); } return items; @@ -129,7 +129,11 @@ namespace MediaBrowser.Controller.Playlists var items = user == null ? LibraryManager.RootFolder.GetRecursiveChildren(filter) - : user.RootFolder.GetRecursiveChildren(user, filter); + : user.RootFolder.GetRecursiveChildren(user, new InternalItemsQuery(user) + { + IncludeItemTypes = new[] { typeof(Audio).Name }, + ArtistNames = new[] { musicArtist.Name } + }); return LibraryManager.Sort(items, user, new[] { ItemSortBy.AlbumArtist, ItemSortBy.Album, ItemSortBy.SortName }, SortOrder.Ascending); } diff --git a/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs b/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs index bc9fa1d7e7..233ec9546f 100644 --- a/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs +++ b/MediaBrowser.Dlna/ContentDirectory/ControlHandler.cs @@ -401,10 +401,10 @@ namespace MediaBrowser.Dlna.ContentDirectory SortOrder = sort.SortOrder, User = user, Recursive = true, - Filter = FilterUnsupportedContent, + IsMissing = false, + ExcludeItemTypes = new[] { typeof(Game).Name, typeof(Book).Name }, IsFolder = isFolder, MediaTypes = mediaTypes.ToArray() - }); } @@ -461,8 +461,10 @@ namespace MediaBrowser.Dlna.ContentDirectory SortBy = sortOrders.ToArray(), SortOrder = sort.SortOrder, User = user, - Filter = FilterUnsupportedContent, - PresetViews = new[] { CollectionType.Movies, CollectionType.TvShows, CollectionType.Music } + IsMissing = false, + PresetViews = new[] { CollectionType.Movies, CollectionType.TvShows, CollectionType.Music }, + ExcludeItemTypes = new[] { typeof(Game).Name, typeof(Book).Name }, + IsPlaceHolder = false }).ConfigureAwait(false); @@ -579,29 +581,6 @@ namespace MediaBrowser.Dlna.ContentDirectory }); } - private bool FilterUnsupportedContent(BaseItem i) - { - // Unplayable - if (i.LocationType == LocationType.Virtual && !i.IsFolder) - { - return false; - } - - // Unplayable - var supportsPlaceHolder = i as ISupportsPlaceHolders; - if (supportsPlaceHolder != null && supportsPlaceHolder.IsPlaceHolder) - { - return false; - } - - if (i is Game || i is Book) - { - //return false; - } - - return true; - } - private ServerItem GetItemFromObjectId(string id, User user) { return DidlBuilder.IsIdRoot(id) diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 1407cdce30..f61bac42dc 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -1448,8 +1448,12 @@ namespace MediaBrowser.Server.Implementations.Library // Handle grouping if (user != null && !string.IsNullOrWhiteSpace(view.ViewType) && UserView.IsEligibleForGrouping(view.ViewType)) { - var collectionFolders = user.RootFolder.GetChildren(user, true).OfType().Where(i => string.IsNullOrWhiteSpace(i.CollectionType) || string.Equals(i.CollectionType, view.ViewType, StringComparison.OrdinalIgnoreCase)); - return collectionFolders.SelectMany(i => GetTopParentsForQuery(i, user)); + return user.RootFolder + .GetChildren(user, true) + .OfType() + .Where(i => string.IsNullOrWhiteSpace(i.CollectionType) || string.Equals(i.CollectionType, view.ViewType, StringComparison.OrdinalIgnoreCase)) + .Where(i => user.Configuration.GroupedFolders.Contains(i.Id.ToString("N"), StringComparer.OrdinalIgnoreCase)) + .SelectMany(i => GetTopParentsForQuery(i, user)); } return new BaseItem[] { }; } diff --git a/MediaBrowser.Server.Implementations/Library/MusicManager.cs b/MediaBrowser.Server.Implementations/Library/MusicManager.cs index c82c4cdf7b..ef13ba9960 100644 --- a/MediaBrowser.Server.Implementations/Library/MusicManager.cs +++ b/MediaBrowser.Server.Implementations/Library/MusicManager.cs @@ -30,7 +30,10 @@ namespace MediaBrowser.Server.Implementations.Library public IEnumerable