From c2537a57ebb4f3b55310234dd9914765da854df7 Mon Sep 17 00:00:00 2001 From: Thomas Gillen Date: Thu, 27 Mar 2014 02:14:06 +0000 Subject: Support anime series ordering with core providers --- .../MediaBrowser.Controller.csproj | 1 + .../Providers/ISeriesOrderManager.cs | 26 ++++++++++++++++ .../Manager/SeriesOrderManager.cs | 36 ++++++++++++++++++++++ .../MediaBrowser.Providers.csproj | 1 + MediaBrowser.Providers/TV/FanArtSeasonProvider.cs | 12 +++++++- .../TV/TvdbEpisodeImageProvider.cs | 3 +- MediaBrowser.Providers/TV/TvdbEpisodeProvider.cs | 9 +++--- .../TV/TvdbSeasonImageProvider.cs | 29 +++++++++++------ .../TV/TvdbSeriesImageProvider.cs | 4 +++ MediaBrowser.Providers/TV/TvdbSeriesProvider.cs | 30 +++++++++++++++++- MediaBrowser.ServerApplication/ApplicationHost.cs | 6 ++++ MediaBrowser.sln | 3 -- 12 files changed, 141 insertions(+), 19 deletions(-) create mode 100644 MediaBrowser.Controller/Providers/ISeriesOrderManager.cs create mode 100644 MediaBrowser.Providers/Manager/SeriesOrderManager.cs diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 5e6297d06..2e0d44e40 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -187,6 +187,7 @@ + diff --git a/MediaBrowser.Controller/Providers/ISeriesOrderManager.cs b/MediaBrowser.Controller/Providers/ISeriesOrderManager.cs new file mode 100644 index 000000000..a3adab1b9 --- /dev/null +++ b/MediaBrowser.Controller/Providers/ISeriesOrderManager.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using MediaBrowser.Common; + +namespace MediaBrowser.Controller.Providers +{ + public interface ISeriesOrderProvider + { + string OrderType { get; } + Task FindSeriesIndex(string seriesName); + } + + public static class SeriesOrderTypes + { + public const string Anime = "Anime"; + } + + public interface ISeriesOrderManager + { + Task FindSeriesIndex(string orderType, string seriesName); + void AddParts(IEnumerable orderProviders); + } +} diff --git a/MediaBrowser.Providers/Manager/SeriesOrderManager.cs b/MediaBrowser.Providers/Manager/SeriesOrderManager.cs new file mode 100644 index 000000000..39175d1f9 --- /dev/null +++ b/MediaBrowser.Providers/Manager/SeriesOrderManager.cs @@ -0,0 +1,36 @@ +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using MediaBrowser.Common; +using MediaBrowser.Controller.Providers; + +namespace MediaBrowser.Providers.Manager +{ + public class SeriesOrderManager : ISeriesOrderManager + { + private Dictionary _providers; + + public void AddParts(IEnumerable orderProviders) + { + _providers = orderProviders + .GroupBy(p => p.OrderType) + .ToDictionary(g => g.Key, g => g.ToArray()); + } + + public async Task FindSeriesIndex(string orderType, string seriesName) + { + ISeriesOrderProvider[] providers; + if (!_providers.TryGetValue(orderType, out providers)) + return null; + + foreach (ISeriesOrderProvider provider in providers) + { + int? index = await provider.FindSeriesIndex(seriesName); + if (index != null) + return index; + } + + return null; + } + } +} \ No newline at end of file diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index f347e7229..ff39ec70d 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -103,6 +103,7 @@ + diff --git a/MediaBrowser.Providers/TV/FanArtSeasonProvider.cs b/MediaBrowser.Providers/TV/FanArtSeasonProvider.cs index 470bd7b3a..5bc58af91 100644 --- a/MediaBrowser.Providers/TV/FanArtSeasonProvider.cs +++ b/MediaBrowser.Providers/TV/FanArtSeasonProvider.cs @@ -77,7 +77,8 @@ namespace MediaBrowser.Providers.TV try { - AddImages(list, season.IndexNumber.Value, xmlPath, cancellationToken); + int seasonNumber = AdjustForSeriesOffset(series, season.IndexNumber.Value); + AddImages(list, seasonNumber, xmlPath, cancellationToken); } catch (FileNotFoundException) { @@ -115,6 +116,15 @@ namespace MediaBrowser.Providers.TV .ThenByDescending(i => i.VoteCount ?? 0); } + private int AdjustForSeriesOffset(Series series, int seasonNumber) + { + var offset = TvdbSeriesProvider.GetSeriesOffset(series.ProviderIds); + if (offset != null) + return (int)(seasonNumber + offset); + + return seasonNumber; + } + private void AddImages(List list, int seasonNumber, string xmlPath, CancellationToken cancellationToken) { using (var streamReader = new StreamReader(xmlPath, Encoding.UTF8)) diff --git a/MediaBrowser.Providers/TV/TvdbEpisodeImageProvider.cs b/MediaBrowser.Providers/TV/TvdbEpisodeImageProvider.cs index 36e349f60..ef3778450 100644 --- a/MediaBrowser.Providers/TV/TvdbEpisodeImageProvider.cs +++ b/MediaBrowser.Providers/TV/TvdbEpisodeImageProvider.cs @@ -62,8 +62,9 @@ namespace MediaBrowser.Providers.TV { // Process images var seriesDataPath = TvdbSeriesProvider.GetSeriesDataPath(_config.ApplicationPaths, seriesId); + var indexOffset = TvdbSeriesProvider.GetSeriesOffset(series.ProviderIds) ?? 0; - var files = TvdbEpisodeProvider.Current.GetEpisodeXmlFiles(episode.ParentIndexNumber, episode.IndexNumber, episode.IndexNumberEnd, seriesDataPath); + var files = TvdbEpisodeProvider.Current.GetEpisodeXmlFiles(episode.ParentIndexNumber + indexOffset, episode.IndexNumber, episode.IndexNumberEnd, seriesDataPath); var result = files.Select(i => GetImageInfo(i, cancellationToken)) .Where(i => i != null); diff --git a/MediaBrowser.Providers/TV/TvdbEpisodeProvider.cs b/MediaBrowser.Providers/TV/TvdbEpisodeProvider.cs index 5f6bdfa04..922c29fe9 100644 --- a/MediaBrowser.Providers/TV/TvdbEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/TvdbEpisodeProvider.cs @@ -52,7 +52,7 @@ namespace MediaBrowser.Providers.TV try { - var item = FetchEpisodeData(searchInfo, seriesDataPath, cancellationToken); + var item = FetchEpisodeData(searchInfo, seriesDataPath, searchInfo.SeriesProviderIds, cancellationToken); if (item != null) { @@ -96,7 +96,7 @@ namespace MediaBrowser.Providers.TV try { - result.Item = FetchEpisodeData(searchInfo, seriesDataPath, cancellationToken); + result.Item = FetchEpisodeData(searchInfo, seriesDataPath, searchInfo.SeriesProviderIds, cancellationToken); result.HasMetadata = result.Item != null; } catch (FileNotFoundException) @@ -213,7 +213,7 @@ namespace MediaBrowser.Providers.TV /// The series data path. /// The cancellation token. /// Task{System.Boolean}. - private Episode FetchEpisodeData(EpisodeInfo id, string seriesDataPath, CancellationToken cancellationToken) + private Episode FetchEpisodeData(EpisodeInfo id, string seriesDataPath, Dictionary seriesProviderIds, CancellationToken cancellationToken) { if (id.IndexNumber == null) { @@ -221,7 +221,8 @@ namespace MediaBrowser.Providers.TV } var episodeNumber = id.IndexNumber.Value; - var seasonNumber = id.ParentIndexNumber; + var seasonOffset = TvdbSeriesProvider.GetSeriesOffset(seriesProviderIds) ?? 0; + var seasonNumber = id.ParentIndexNumber + seasonOffset; if (seasonNumber == null) { diff --git a/MediaBrowser.Providers/TV/TvdbSeasonImageProvider.cs b/MediaBrowser.Providers/TV/TvdbSeasonImageProvider.cs index c0c103b7f..5a9981c6e 100644 --- a/MediaBrowser.Providers/TV/TvdbSeasonImageProvider.cs +++ b/MediaBrowser.Providers/TV/TvdbSeasonImageProvider.cs @@ -22,8 +22,9 @@ namespace MediaBrowser.Providers.TV { public class TvdbSeasonImageProvider : IRemoteImageProvider, IHasOrder, IHasChangeMonitor { + private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); + private readonly IServerConfigurationManager _config; - private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly IHttpClient _httpClient; private readonly IFileSystem _fileSystem; @@ -77,7 +78,8 @@ namespace MediaBrowser.Providers.TV try { - return GetImages(path, item.GetPreferredMetadataLanguage(), season.IndexNumber.Value, cancellationToken); + int seasonNumber = AdjustForSeriesOffset(series, season.IndexNumber.Value); + return GetImages(path, item.GetPreferredMetadataLanguage(), seasonNumber, cancellationToken); } catch (FileNotFoundException) { @@ -88,7 +90,16 @@ namespace MediaBrowser.Providers.TV return new RemoteImageInfo[] { }; } - private IEnumerable GetImages(string xmlPath, string preferredLanguage, int seasonNumber, CancellationToken cancellationToken) + private int AdjustForSeriesOffset(Series series, int seasonNumber) + { + var offset = TvdbSeriesProvider.GetSeriesOffset(series.ProviderIds); + if (offset != null) + return (int) (seasonNumber + offset); + + return seasonNumber; + } + + internal static IEnumerable GetImages(string xmlPath, string preferredLanguage, int seasonNumber, CancellationToken cancellationToken) { var settings = new XmlReaderSettings { @@ -159,7 +170,7 @@ namespace MediaBrowser.Providers.TV .ToList(); } - private void AddImage(XmlReader reader, List images, int seasonNumber) + private static void AddImage(XmlReader reader, List images, int seasonNumber) { reader.MoveToContent(); @@ -186,7 +197,7 @@ namespace MediaBrowser.Providers.TV double rval; - if (double.TryParse(val, NumberStyles.Any, _usCulture, out rval)) + if (double.TryParse(val, NumberStyles.Any, UsCulture, out rval)) { rating = rval; } @@ -200,7 +211,7 @@ namespace MediaBrowser.Providers.TV int rval; - if (int.TryParse(val, NumberStyles.Integer, _usCulture, out rval)) + if (int.TryParse(val, NumberStyles.Integer, UsCulture, out rval)) { voteCount = rval; } @@ -237,12 +248,12 @@ namespace MediaBrowser.Providers.TV { int rval; - if (int.TryParse(resolutionParts[0], NumberStyles.Integer, _usCulture, out rval)) + if (int.TryParse(resolutionParts[0], NumberStyles.Integer, UsCulture, out rval)) { width = rval; } - if (int.TryParse(resolutionParts[1], NumberStyles.Integer, _usCulture, out rval)) + if (int.TryParse(resolutionParts[1], NumberStyles.Integer, UsCulture, out rval)) { height = rval; } @@ -285,7 +296,7 @@ namespace MediaBrowser.Providers.TV CommunityRating = rating, VoteCount = voteCount, Url = TVUtils.BannerUrl + url, - ProviderName = Name, + ProviderName = ProviderName, Language = language, Width = width, Height = height diff --git a/MediaBrowser.Providers/TV/TvdbSeriesImageProvider.cs b/MediaBrowser.Providers/TV/TvdbSeriesImageProvider.cs index 761c77443..d1171f34b 100644 --- a/MediaBrowser.Providers/TV/TvdbSeriesImageProvider.cs +++ b/MediaBrowser.Providers/TV/TvdbSeriesImageProvider.cs @@ -77,6 +77,10 @@ namespace MediaBrowser.Providers.TV try { + var seriesOffset = TvdbSeriesProvider.GetSeriesOffset(series.ProviderIds); + if (seriesOffset != null) + return TvdbSeasonImageProvider.GetImages(path, language, seriesOffset.Value + 1, cancellationToken); + return GetImages(path, language, cancellationToken); } catch (FileNotFoundException) diff --git a/MediaBrowser.Providers/TV/TvdbSeriesProvider.cs b/MediaBrowser.Providers/TV/TvdbSeriesProvider.cs index 4b78c1a96..a76e10111 100644 --- a/MediaBrowser.Providers/TV/TvdbSeriesProvider.cs +++ b/MediaBrowser.Providers/TV/TvdbSeriesProvider.cs @@ -25,6 +25,8 @@ namespace MediaBrowser.Providers.TV { public class TvdbSeriesProvider : IRemoteMetadataProvider, IHasOrder { + internal const string TvdbSeriesOffset = "TvdbSeriesOffset"; + internal readonly SemaphoreSlim TvDbResourcePool = new SemaphoreSlim(2, 2); internal static TvdbSeriesProvider Current { get; private set; } private readonly IZipClient _zipClient; @@ -33,14 +35,16 @@ namespace MediaBrowser.Providers.TV private readonly IServerConfigurationManager _config; private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private readonly ILogger _logger; + private readonly ISeriesOrderManager _seriesOrder; - public TvdbSeriesProvider(IZipClient zipClient, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager config, ILogger logger) + public TvdbSeriesProvider(IZipClient zipClient, IHttpClient httpClient, IFileSystem fileSystem, IServerConfigurationManager config, ILogger logger, ISeriesOrderManager seriesOrder) { _zipClient = zipClient; _httpClient = httpClient; _fileSystem = fileSystem; _config = config; _logger = logger; + _seriesOrder = seriesOrder; Current = this; } @@ -92,11 +96,35 @@ namespace MediaBrowser.Providers.TV result.HasMetadata = true; FetchSeriesData(result.Item, seriesId, cancellationToken); + await FindAnimeSeriesIndex(result.Item, itemId).ConfigureAwait(false); } return result; } + private async Task FindAnimeSeriesIndex(Series series, SeriesInfo info) + { + var index = await _seriesOrder.FindSeriesIndex(SeriesOrderTypes.Anime, series.Name); + if (index == null) + return; + + var offset = info.AnimeSeriesIndex - index; + series.SetProviderId(TvdbSeriesOffset, offset.ToString()); + } + + internal static int? GetSeriesOffset(Dictionary seriesProviderIds) + { + string offsetString; + if (!seriesProviderIds.TryGetValue(TvdbSeriesOffset, out offsetString)) + return null; + + int offset; + if (int.TryParse(offsetString, out offset)) + return offset; + + return null; + } + /// /// Fetches the series data. /// diff --git a/MediaBrowser.ServerApplication/ApplicationHost.cs b/MediaBrowser.ServerApplication/ApplicationHost.cs index fe7b17d1d..06ffa37a1 100644 --- a/MediaBrowser.ServerApplication/ApplicationHost.cs +++ b/MediaBrowser.ServerApplication/ApplicationHost.cs @@ -157,6 +157,7 @@ namespace MediaBrowser.ServerApplication private IHttpServer HttpServer { get; set; } private IDtoService DtoService { get; set; } private IImageProcessor ImageProcessor { get; set; } + private ISeriesOrderManager SeriesOrderManager { get; set; } /// /// Gets or sets the media encoder. @@ -453,6 +454,9 @@ namespace MediaBrowser.ServerApplication ProviderManager = new ProviderManager(HttpClient, ServerConfigurationManager, LibraryMonitor, LogManager, FileSystemManager); RegisterSingleInstance(ProviderManager); + SeriesOrderManager = new SeriesOrderManager(); + RegisterSingleInstance(SeriesOrderManager); + RegisterSingleInstance(() => new SearchEngine(LogManager, LibraryManager, UserManager)); SessionManager = new SessionManager(UserDataManager, ServerConfigurationManager, Logger, UserRepository, LibraryManager, UserManager); @@ -680,6 +684,8 @@ namespace MediaBrowser.ServerApplication GetExports(), GetExports()); + SeriesOrderManager.AddParts(GetExports()); + ImageProcessor.AddParts(GetExports()); LiveTvManager.AddParts(GetExports()); diff --git a/MediaBrowser.sln b/MediaBrowser.sln index 7ac158065..e05b8ae6a 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -251,7 +251,4 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection - GlobalSection(Performance) = preSolution - HasPerformanceSessions = true - EndGlobalSection EndGlobal -- cgit v1.2.3 From fb22901d38832dcea332136ac748305ba74eb5db Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 27 Mar 2014 15:30:21 -0400 Subject: create separate media encoding project --- MediaBrowser.Api/Playback/BaseStreamingService.cs | 38 +- MediaBrowser.Api/Playback/Hls/BaseHlsService.cs | 2 +- .../Progressive/BaseProgressiveStreamingService.cs | 5 + .../MediaEncoding/IMediaEncoder.cs | 13 +- MediaBrowser.Dlna/DlnaManager.cs | 2 +- MediaBrowser.Dlna/PlayTo/Device.cs | 2 +- MediaBrowser.Dlna/Profiles/DefaultProfile.cs | 18 - MediaBrowser.Dlna/Profiles/Xbox360Profile.cs | 14 - MediaBrowser.Dlna/Profiles/Xml/Default.xml | 7 - MediaBrowser.Dlna/Profiles/Xml/Denon AVR.xml | 7 - MediaBrowser.Dlna/Profiles/Xml/Linksys DMA2100.xml | 7 - MediaBrowser.Dlna/Profiles/Xml/Xbox 360.xml | 2 - MediaBrowser.Dlna/Profiles/Xml/Xbox One.xml | 7 - MediaBrowser.Dlna/Profiles/Xml/foobar2000.xml | 7 - .../BdInfo/BdInfoExaminer.cs | 185 ++++ MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 981 +++++++++++++++++++++ .../MediaBrowser.MediaEncoding.csproj | 80 ++ .../Properties/AssemblyInfo.cs | 36 + MediaBrowser.MediaEncoding/packages.config | 4 + .../MediaInfo/AudioImageProvider.cs | 2 +- .../MediaInfo/FFProbeVideoInfo.cs | 2 - .../MediaInfo/VideoImageProvider.cs | 2 +- .../BdInfo/BdInfoExaminer.cs | 185 ---- .../IO/LibraryMonitor.cs | 58 +- .../MediaBrowser.Server.Implementations.csproj | 10 - .../MediaEncoder/EncodingManager.cs | 2 +- .../MediaEncoder/MediaEncoder.cs | 958 -------------------- .../Persistence/SqliteMediaStreamsRepository.cs | 2 + .../packages.config | 1 - MediaBrowser.ServerApplication/ApplicationHost.cs | 8 +- .../MediaBrowser.ServerApplication.csproj | 4 + MediaBrowser.sln | 16 + 32 files changed, 1380 insertions(+), 1287 deletions(-) create mode 100644 MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs create mode 100644 MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs create mode 100644 MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj create mode 100644 MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs create mode 100644 MediaBrowser.MediaEncoding/packages.config delete mode 100644 MediaBrowser.Server.Implementations/BdInfo/BdInfoExaminer.cs delete mode 100644 MediaBrowser.Server.Implementations/MediaEncoder/MediaEncoder.cs diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index 2002e594c..ceb96d226 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -316,6 +316,7 @@ namespace MediaBrowser.Api.Playback /// /// The state. /// The video codec. + /// if set to true [is HLS]. /// System.String. protected string GetVideoQualityParam(StreamState state, string videoCodec, bool isHls) { @@ -340,20 +341,17 @@ namespace MediaBrowser.Api.Playback break; } - if (!isHls) + switch (qualitySetting) { - switch (qualitySetting) - { - case EncodingQuality.HighSpeed: - param += " -crf 23"; - break; - case EncodingQuality.HighQuality: - param += " -crf 20"; - break; - case EncodingQuality.MaxQuality: - param += " -crf 18"; - break; - } + case EncodingQuality.HighSpeed: + param += " -crf 23"; + break; + case EncodingQuality.HighQuality: + param += " -crf 20"; + break; + case EncodingQuality.MaxQuality: + param += " -crf 18"; + break; } } @@ -1032,11 +1030,6 @@ namespace MediaBrowser.Api.Playback { var hasFixedResolution = state.VideoRequest.HasFixedResolution; - if (isHls) - { - return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture)); - } - if (string.Equals(videoCodec, "libvpx", StringComparison.OrdinalIgnoreCase)) { if (hasFixedResolution) @@ -1047,7 +1040,6 @@ namespace MediaBrowser.Api.Playback // With vpx when crf is used, b:v becomes a max rate // https://trac.ffmpeg.org/wiki/vpxEncodingGuide return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture)); - //return string.Format(" -minrate:v ({0}*.95) -maxrate:v ({0}*1.05) -bufsize:v {0} -b:v {0}", bitrate.Value.ToString(UsCulture)); } if (string.Equals(videoCodec, "msmpeg4", StringComparison.OrdinalIgnoreCase)) @@ -1055,13 +1047,17 @@ namespace MediaBrowser.Api.Playback return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture)); } - // H264 if (hasFixedResolution) { + if (isHls) + { + return string.Format(" -b:v {0} -maxrate ({0}*.80) -bufsize {0}", bitrate.Value.ToString(UsCulture)); + } + return string.Format(" -b:v {0}", bitrate.Value.ToString(UsCulture)); } - + return string.Format(" -maxrate {0} -bufsize {1}", bitrate.Value.ToString(UsCulture), (bitrate.Value * 2).ToString(UsCulture)); diff --git a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs index 198376d6a..96b36ac7f 100644 --- a/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs +++ b/MediaBrowser.Api/Playback/Hls/BaseHlsService.cs @@ -200,7 +200,7 @@ namespace MediaBrowser.Api.Playback.Hls builder.AppendLine("#EXTM3U"); // Pad a little to satisfy the apple hls validator - var paddedBitrate = Convert.ToInt32(bitrate * 1.05); + var paddedBitrate = Convert.ToInt32(bitrate * 1.15); // Main stream builder.AppendLine("#EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=" + paddedBitrate.ToString(UsCulture)); diff --git a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs index 78b3f2948..b4fe9a094 100644 --- a/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs +++ b/MediaBrowser.Api/Playback/Progressive/BaseProgressiveStreamingService.cs @@ -266,6 +266,11 @@ namespace MediaBrowser.Api.Playback.Progressive return result; } + /// + /// Gets the length of the estimated content. + /// + /// The state. + /// System.Nullable{System.Int64}. private long? GetEstimatedContentLength(StreamState state) { var totalBitrate = 0; diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index 119688fa7..657e52e5a 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -24,16 +24,23 @@ namespace MediaBrowser.Controller.MediaEncoding string Version { get; } /// - /// Extracts the image. + /// Extracts the audio image. + /// + /// The path. + /// The cancellation token. + /// Task{Stream}. + Task ExtractAudioImage(string path, CancellationToken cancellationToken); + + /// + /// Extracts the video image. /// /// The input files. /// The type. - /// if set to true [is audio]. /// The threed format. /// The offset. /// The cancellation token. /// Task{Stream}. - Task ExtractImage(string[] inputFiles, InputType type, bool isAudio, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken); + Task ExtractVideoImage(string[] inputFiles, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken); /// /// Extracts the text subtitle. diff --git a/MediaBrowser.Dlna/DlnaManager.cs b/MediaBrowser.Dlna/DlnaManager.cs index edccc71c9..ec9ecb9ef 100644 --- a/MediaBrowser.Dlna/DlnaManager.cs +++ b/MediaBrowser.Dlna/DlnaManager.cs @@ -197,7 +197,7 @@ namespace MediaBrowser.Dlna throw new ArgumentNullException("headers"); } - return GetProfiles().FirstOrDefault(i => IsMatch(headers, i.Identification)); + return GetProfiles().FirstOrDefault(i => i.Identification != null && IsMatch(headers, i.Identification)); } private bool IsMatch(IDictionary headers, DeviceIdentification profileInfo) diff --git a/MediaBrowser.Dlna/PlayTo/Device.cs b/MediaBrowser.Dlna/PlayTo/Device.cs index fa0bfbca8..c0f88f285 100644 --- a/MediaBrowser.Dlna/PlayTo/Device.cs +++ b/MediaBrowser.Dlna/PlayTo/Device.cs @@ -631,7 +631,7 @@ namespace MediaBrowser.Dlna.PlayTo RendererCommands = TransportCommands.Create(document); } - internal TransportCommands AvCommands + private TransportCommands AvCommands { get; set; diff --git a/MediaBrowser.Dlna/Profiles/DefaultProfile.cs b/MediaBrowser.Dlna/Profiles/DefaultProfile.cs index 0efe18755..6b5513e28 100644 --- a/MediaBrowser.Dlna/Profiles/DefaultProfile.cs +++ b/MediaBrowser.Dlna/Profiles/DefaultProfile.cs @@ -57,24 +57,6 @@ namespace MediaBrowser.Dlna.Profiles Type = DlnaProfileType.Video } }; - - CodecProfiles = new[] - { - new CodecProfile - { - Type = CodecType.VideoCodec, - Conditions = new [] - { - new ProfileCondition - { - Condition = ProfileConditionType.LessThanEqual, - Property = ProfileConditionValue.VideoLevel, - Value = "3", - IsRequired = false - } - } - } - }; } } } diff --git a/MediaBrowser.Dlna/Profiles/Xbox360Profile.cs b/MediaBrowser.Dlna/Profiles/Xbox360Profile.cs index 640317fbc..ed9edeb27 100644 --- a/MediaBrowser.Dlna/Profiles/Xbox360Profile.cs +++ b/MediaBrowser.Dlna/Profiles/Xbox360Profile.cs @@ -229,13 +229,6 @@ namespace MediaBrowser.Dlna.Profiles Property = ProfileConditionValue.VideoBitrate, Value = "10240000", IsRequired = false - }, - new ProfileCondition - { - Condition = ProfileConditionType.LessThanEqual, - Property = ProfileConditionValue.VideoLevel, - Value = "3", - IsRequired = false } } }, @@ -271,13 +264,6 @@ namespace MediaBrowser.Dlna.Profiles Property = ProfileConditionValue.VideoBitrate, Value = "15360000", IsRequired = false - }, - new ProfileCondition - { - Condition = ProfileConditionType.LessThanEqual, - Property = ProfileConditionValue.VideoLevel, - Value = "3", - IsRequired = false } } }, diff --git a/MediaBrowser.Dlna/Profiles/Xml/Default.xml b/MediaBrowser.Dlna/Profiles/Xml/Default.xml index 52b92c6f3..60f22a64a 100644 --- a/MediaBrowser.Dlna/Profiles/Xml/Default.xml +++ b/MediaBrowser.Dlna/Profiles/Xml/Default.xml @@ -30,12 +30,5 @@ - - - - - - - \ No newline at end of file diff --git a/MediaBrowser.Dlna/Profiles/Xml/Denon AVR.xml b/MediaBrowser.Dlna/Profiles/Xml/Denon AVR.xml index 3332e4d45..28bb3289e 100644 --- a/MediaBrowser.Dlna/Profiles/Xml/Denon AVR.xml +++ b/MediaBrowser.Dlna/Profiles/Xml/Denon AVR.xml @@ -34,12 +34,5 @@ - - - - - - - \ No newline at end of file diff --git a/MediaBrowser.Dlna/Profiles/Xml/Linksys DMA2100.xml b/MediaBrowser.Dlna/Profiles/Xml/Linksys DMA2100.xml index b19cb0f7b..477fee2dd 100644 --- a/MediaBrowser.Dlna/Profiles/Xml/Linksys DMA2100.xml +++ b/MediaBrowser.Dlna/Profiles/Xml/Linksys DMA2100.xml @@ -34,12 +34,5 @@ - - - - - - - \ No newline at end of file diff --git a/MediaBrowser.Dlna/Profiles/Xml/Xbox 360.xml b/MediaBrowser.Dlna/Profiles/Xml/Xbox 360.xml index e7839ca77..ea2539197 100644 --- a/MediaBrowser.Dlna/Profiles/Xml/Xbox 360.xml +++ b/MediaBrowser.Dlna/Profiles/Xml/Xbox 360.xml @@ -73,7 +73,6 @@ - @@ -82,7 +81,6 @@ - diff --git a/MediaBrowser.Dlna/Profiles/Xml/Xbox One.xml b/MediaBrowser.Dlna/Profiles/Xml/Xbox One.xml index 5243218fb..ef4fec99a 100644 --- a/MediaBrowser.Dlna/Profiles/Xml/Xbox One.xml +++ b/MediaBrowser.Dlna/Profiles/Xml/Xbox One.xml @@ -32,13 +32,6 @@ - - - - - - - diff --git a/MediaBrowser.Dlna/Profiles/Xml/foobar2000.xml b/MediaBrowser.Dlna/Profiles/Xml/foobar2000.xml index 126d7fe73..3e6623ac4 100644 --- a/MediaBrowser.Dlna/Profiles/Xml/foobar2000.xml +++ b/MediaBrowser.Dlna/Profiles/Xml/foobar2000.xml @@ -36,12 +36,5 @@ - - - - - - - \ No newline at end of file diff --git a/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs b/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs new file mode 100644 index 000000000..b15b8d15d --- /dev/null +++ b/MediaBrowser.MediaEncoding/BdInfo/BdInfoExaminer.cs @@ -0,0 +1,185 @@ +using BDInfo; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.MediaInfo; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace MediaBrowser.MediaEncoding.BdInfo +{ + /// + /// Class BdInfoExaminer + /// + public class BdInfoExaminer : IBlurayExaminer + { + /// + /// Gets the disc info. + /// + /// The path. + /// BlurayDiscInfo. + public BlurayDiscInfo GetDiscInfo(string path) + { + var bdrom = new BDROM(path); + + bdrom.Scan(); + + // Get the longest playlist + var playlist = bdrom.PlaylistFiles.Values.OrderByDescending(p => p.TotalLength).FirstOrDefault(p => p.IsValid); + + var outputStream = new BlurayDiscInfo + { + MediaStreams = new List() + }; + + if (playlist == null) + { + return outputStream; + } + + outputStream.Chapters = playlist.Chapters; + + outputStream.RunTimeTicks = TimeSpan.FromSeconds(playlist.TotalLength).Ticks; + + var mediaStreams = new List { }; + + foreach (var stream in playlist.SortedStreams) + { + var videoStream = stream as TSVideoStream; + + if (videoStream != null) + { + AddVideoStream(mediaStreams, videoStream); + continue; + } + + var audioStream = stream as TSAudioStream; + + if (audioStream != null) + { + AddAudioStream(mediaStreams, audioStream); + continue; + } + + var textStream = stream as TSTextStream; + + if (textStream != null) + { + AddSubtitleStream(mediaStreams, textStream); + continue; + } + + var graphicsStream = stream as TSGraphicsStream; + + if (graphicsStream != null) + { + AddSubtitleStream(mediaStreams, graphicsStream); + } + } + + outputStream.MediaStreams = mediaStreams; + + outputStream.PlaylistName = playlist.Name; + + if (playlist.StreamClips != null && playlist.StreamClips.Any()) + { + // Get the files in the playlist + outputStream.Files = playlist.StreamClips.Select(i => i.StreamFile.Name).ToList(); + } + + return outputStream; + } + + /// + /// Adds the video stream. + /// + /// The streams. + /// The video stream. + private void AddVideoStream(List streams, TSVideoStream videoStream) + { + var mediaStream = new MediaStream + { + BitRate = Convert.ToInt32(videoStream.BitRate), + Width = videoStream.Width, + Height = videoStream.Height, + Codec = videoStream.CodecShortName, + IsInterlaced = videoStream.IsInterlaced, + Type = MediaStreamType.Video, + Index = streams.Count + }; + + if (videoStream.FrameRateDenominator > 0) + { + float frameRateEnumerator = videoStream.FrameRateEnumerator; + float frameRateDenominator = videoStream.FrameRateDenominator; + + mediaStream.AverageFrameRate = mediaStream.RealFrameRate = frameRateEnumerator / frameRateDenominator; + } + + streams.Add(mediaStream); + } + + /// + /// Adds the audio stream. + /// + /// The streams. + /// The audio stream. + private void AddAudioStream(List streams, TSAudioStream audioStream) + { + var stream = new MediaStream + { + Codec = audioStream.CodecShortName, + Language = audioStream.LanguageCode, + Channels = audioStream.ChannelCount, + SampleRate = audioStream.SampleRate, + Type = MediaStreamType.Audio, + Index = streams.Count + }; + + var bitrate = Convert.ToInt32(audioStream.BitRate); + + if (bitrate > 0) + { + stream.BitRate = bitrate; + } + + if (audioStream.LFE > 0) + { + stream.Channels = audioStream.ChannelCount + 1; + } + + streams.Add(stream); + } + + /// + /// Adds the subtitle stream. + /// + /// The streams. + /// The text stream. + private void AddSubtitleStream(List streams, TSTextStream textStream) + { + streams.Add(new MediaStream + { + Language = textStream.LanguageCode, + Codec = textStream.CodecShortName, + Type = MediaStreamType.Subtitle, + Index = streams.Count + }); + } + + /// + /// Adds the subtitle stream. + /// + /// The streams. + /// The text stream. + private void AddSubtitleStream(List streams, TSGraphicsStream textStream) + { + streams.Add(new MediaStream + { + Language = textStream.LanguageCode, + Codec = textStream.CodecShortName, + Type = MediaStreamType.Subtitle, + Index = streams.Count + }); + } + } +} diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs new file mode 100644 index 000000000..7cabf23c4 --- /dev/null +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -0,0 +1,981 @@ +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.IO; +using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; +using System; +using System.Collections.Concurrent; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.MediaEncoding.Encoder +{ + /// + /// Class MediaEncoder + /// + public class MediaEncoder : IMediaEncoder, IDisposable + { + /// + /// The _logger + /// + private readonly ILogger _logger; + + /// + /// The _app paths + /// + private readonly IApplicationPaths _appPaths; + + /// + /// Gets the json serializer. + /// + /// The json serializer. + private readonly IJsonSerializer _jsonSerializer; + + /// + /// The video image resource pool + /// + private readonly SemaphoreSlim _videoImageResourcePool = new SemaphoreSlim(1, 1); + + /// + /// The audio image resource pool + /// + private readonly SemaphoreSlim _audioImageResourcePool = new SemaphoreSlim(2, 2); + + /// + /// The FF probe resource pool + /// + private readonly SemaphoreSlim _ffProbeResourcePool = new SemaphoreSlim(2, 2); + + private readonly IFileSystem _fileSystem; + + public string FFMpegPath { get; private set; } + + public string FFProbePath { get; private set; } + + public string Version { get; private set; } + + public MediaEncoder(ILogger logger, IApplicationPaths appPaths, + IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, string version, + IFileSystem fileSystem) + { + _logger = logger; + _appPaths = appPaths; + _jsonSerializer = jsonSerializer; + Version = version; + _fileSystem = fileSystem; + FFProbePath = ffProbePath; + FFMpegPath = ffMpegPath; + } + + /// + /// Gets the encoder path. + /// + /// The encoder path. + public string EncoderPath + { + get { return FFMpegPath; } + } + + /// + /// The _semaphoreLocks + /// + private readonly ConcurrentDictionary _semaphoreLocks = + new ConcurrentDictionary(); + + /// + /// Gets the lock. + /// + /// The filename. + /// System.Object. + private SemaphoreSlim GetLock(string filename) + { + return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1)); + } + + /// + /// Gets the media info. + /// + /// The input files. + /// The type. + /// if set to true [is audio]. + /// The cancellation token. + /// Task. + public Task GetMediaInfo(string[] inputFiles, InputType type, bool isAudio, + CancellationToken cancellationToken) + { + return GetMediaInfoInternal(GetInputArgument(inputFiles, type), !isAudio, + GetProbeSizeArgument(type), cancellationToken); + } + + /// + /// Gets the input argument. + /// + /// The input files. + /// The type. + /// System.String. + /// Unrecognized InputType + public string GetInputArgument(string[] inputFiles, InputType type) + { + string inputPath; + + switch (type) + { + case InputType.Bluray: + case InputType.Dvd: + case InputType.File: + inputPath = GetConcatInputArgument(inputFiles); + break; + case InputType.Url: + inputPath = GetHttpInputArgument(inputFiles); + break; + default: + throw new ArgumentException("Unrecognized InputType"); + } + + return inputPath; + } + + /// + /// Gets the HTTP input argument. + /// + /// The input files. + /// System.String. + private string GetHttpInputArgument(string[] inputFiles) + { + var url = inputFiles[0]; + + return string.Format("\"{0}\"", url); + } + + /// + /// Gets the probe size argument. + /// + /// The type. + /// System.String. + public string GetProbeSizeArgument(InputType type) + { + return type == InputType.Dvd ? "-probesize 1G -analyzeduration 200M" : string.Empty; + } + + /// + /// Gets the media info internal. + /// + /// The input path. + /// if set to true [extract chapters]. + /// The probe size argument. + /// The cancellation token. + /// Task{MediaInfoResult}. + /// + private async Task GetMediaInfoInternal(string inputPath, bool extractChapters, + string probeSizeArgument, + CancellationToken cancellationToken) + { + var args = extractChapters + ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format" + : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format"; + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + + // Must consume both or ffmpeg may hang due to deadlocks. See comments below. + RedirectStandardOutput = true, + RedirectStandardError = true, + FileName = FFProbePath, + Arguments = string.Format(args, + probeSizeArgument, inputPath).Trim(), + + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + }, + + EnableRaisingEvents = true + }; + + _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + + process.Exited += ProcessExited; + + await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); + + InternalMediaInfoResult result; + + try + { + process.Start(); + } + catch (Exception ex) + { + _ffProbeResourcePool.Release(); + + _logger.ErrorException("Error starting ffprobe", ex); + + throw; + } + + try + { + process.BeginErrorReadLine(); + + result = + _jsonSerializer.DeserializeFromStream(process.StandardOutput.BaseStream); + } + catch + { + // Hate having to do this + try + { + process.Kill(); + } + catch (Exception ex1) + { + _logger.ErrorException("Error killing ffprobe", ex1); + } + + throw; + } + finally + { + _ffProbeResourcePool.Release(); + } + + if (result == null) + { + throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath)); + } + + cancellationToken.ThrowIfCancellationRequested(); + + if (result.streams != null) + { + // Normalize aspect ratio if invalid + foreach (var stream in result.streams) + { + if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase)) + { + stream.display_aspect_ratio = string.Empty; + } + if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase)) + { + stream.sample_aspect_ratio = string.Empty; + } + } + } + + return result; + } + + /// + /// The us culture + /// + protected readonly CultureInfo UsCulture = new CultureInfo("en-US"); + + /// + /// Processes the exited. + /// + /// The sender. + /// The instance containing the event data. + private void ProcessExited(object sender, EventArgs e) + { + ((Process)sender).Dispose(); + } + + /// + /// Converts the text subtitle to ass. + /// + /// The input path. + /// The output path. + /// The language. + /// The cancellation token. + /// Task. + public async Task ConvertTextSubtitleToAss(string inputPath, string outputPath, string language, + CancellationToken cancellationToken) + { + var semaphore = GetLock(outputPath); + + await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + if (!File.Exists(outputPath)) + { + await ConvertTextSubtitleToAssInternal(inputPath, outputPath, language).ConfigureAwait(false); + } + } + finally + { + semaphore.Release(); + } + } + + private const int FastSeekOffsetSeconds = 1; + + /// + /// Converts the text subtitle to ass. + /// + /// The input path. + /// The output path. + /// The language. + /// Task. + /// inputPath + /// or + /// outputPath + /// + private async Task ConvertTextSubtitleToAssInternal(string inputPath, string outputPath, string language) + { + if (string.IsNullOrEmpty(inputPath)) + { + throw new ArgumentNullException("inputPath"); + } + + if (string.IsNullOrEmpty(outputPath)) + { + throw new ArgumentNullException("outputPath"); + } + + + var encodingParam = string.IsNullOrEmpty(language) + ? string.Empty + : GetSubtitleLanguageEncodingParam(language) + " "; + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + RedirectStandardOutput = false, + RedirectStandardError = true, + + CreateNoWindow = true, + UseShellExecute = false, + FileName = FFMpegPath, + Arguments = + string.Format("{0} -i \"{1}\" -c:s ass \"{2}\"", encodingParam, inputPath, outputPath), + + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + } + }; + + _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + + var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt"); + Directory.CreateDirectory(Path.GetDirectoryName(logFilePath)); + + var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, + true); + + try + { + process.Start(); + } + catch (Exception ex) + { + logFileStream.Dispose(); + + _logger.ErrorException("Error starting ffmpeg", ex); + + throw; + } + + var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream); + + var ranToCompletion = process.WaitForExit(60000); + + if (!ranToCompletion) + { + try + { + _logger.Info("Killing ffmpeg subtitle conversion process"); + + process.Kill(); + + process.WaitForExit(1000); + + await logTask.ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.ErrorException("Error killing subtitle conversion process", ex); + } + finally + { + logFileStream.Dispose(); + } + } + + var exitCode = ranToCompletion ? process.ExitCode : -1; + + process.Dispose(); + + var failed = false; + + if (exitCode == -1) + { + failed = true; + + if (File.Exists(outputPath)) + { + try + { + _logger.Info("Deleting converted subtitle due to failure: ", outputPath); + File.Delete(outputPath); + } + catch (IOException ex) + { + _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath); + } + } + } + else if (!File.Exists(outputPath)) + { + failed = true; + } + + if (failed) + { + var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath); + + _logger.Error(msg); + + throw new ApplicationException(msg); + } + await SetAssFont(outputPath).ConfigureAwait(false); + } + + protected string GetFastSeekCommandLineParameter(TimeSpan offset) + { + var seconds = offset.TotalSeconds - FastSeekOffsetSeconds; + + if (seconds > 0) + { + return string.Format("-ss {0} ", seconds.ToString(UsCulture)); + } + + return string.Empty; + } + + protected string GetSlowSeekCommandLineParameter(TimeSpan offset) + { + if (offset.TotalSeconds - FastSeekOffsetSeconds > 0) + { + return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture)); + } + + return string.Empty; + } + + /// + /// Gets the subtitle language encoding param. + /// + /// The language. + /// System.String. + private string GetSubtitleLanguageEncodingParam(string language) + { + switch (language.ToLower()) + { + case "pol": + case "cze": + case "ces": + case "slo": + case "slk": + case "hun": + case "slv": + case "srp": + case "hrv": + case "rum": + case "ron": + case "rup": + case "alb": + case "sqi": + return "-sub_charenc windows-1250"; + case "ara": + return "-sub_charenc windows-1256"; + case "heb": + return "-sub_charenc windows-1255"; + case "grc": + case "gre": + return "-sub_charenc windows-1253"; + case "crh": + case "ota": + case "tur": + return "-sub_charenc windows-1254"; + case "rus": + return "-sub_charenc windows-1251"; + case "vie": + return "-sub_charenc windows-1258"; + case "kor": + return "-sub_charenc cp949"; + default: + return "-sub_charenc windows-1252"; + } + } + + /// + /// Extracts the text subtitle. + /// + /// The input files. + /// The type. + /// Index of the subtitle stream. + /// if set to true, copy stream instead of converting. + /// The output path. + /// The cancellation token. + /// Task. + /// Must use inputPath list overload + public async Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, + bool copySubtitleStream, string outputPath, CancellationToken cancellationToken) + { + var semaphore = GetLock(outputPath); + + await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + if (!File.Exists(outputPath)) + { + await + ExtractTextSubtitleInternal(GetInputArgument(inputFiles, type), subtitleStreamIndex, + copySubtitleStream, outputPath, cancellationToken).ConfigureAwait(false); + } + } + finally + { + semaphore.Release(); + } + } + + /// + /// Extracts the text subtitle. + /// + /// The input path. + /// Index of the subtitle stream. + /// if set to true, copy stream instead of converting. + /// The output path. + /// The cancellation token. + /// Task. + /// inputPath + /// or + /// outputPath + /// or + /// cancellationToken + /// + private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex, + bool copySubtitleStream, string outputPath, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(inputPath)) + { + throw new ArgumentNullException("inputPath"); + } + + if (string.IsNullOrEmpty(outputPath)) + { + throw new ArgumentNullException("outputPath"); + } + + string processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s ass \"{2}\"", inputPath, + subtitleStreamIndex, outputPath); + + if (copySubtitleStream) + { + processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s copy \"{2}\"", inputPath, + subtitleStreamIndex, outputPath); + } + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + + RedirectStandardOutput = false, + RedirectStandardError = true, + + FileName = FFMpegPath, + Arguments = processArgs, + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + } + }; + + _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); + + var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt"); + Directory.CreateDirectory(Path.GetDirectoryName(logFilePath)); + + var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, + true); + + try + { + process.Start(); + } + catch (Exception ex) + { + logFileStream.Dispose(); + + _logger.ErrorException("Error starting ffmpeg", ex); + + throw; + } + + process.StandardError.BaseStream.CopyToAsync(logFileStream); + + var ranToCompletion = process.WaitForExit(60000); + + if (!ranToCompletion) + { + try + { + _logger.Info("Killing ffmpeg subtitle extraction process"); + + process.Kill(); + + process.WaitForExit(1000); + } + catch (Exception ex) + { + _logger.ErrorException("Error killing subtitle extraction process", ex); + } + finally + { + logFileStream.Dispose(); + } + } + + var exitCode = ranToCompletion ? process.ExitCode : -1; + + process.Dispose(); + + var failed = false; + + if (exitCode == -1) + { + failed = true; + + if (File.Exists(outputPath)) + { + try + { + _logger.Info("Deleting extracted subtitle due to failure: ", outputPath); + File.Delete(outputPath); + } + catch (IOException ex) + { + _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath); + } + } + } + else if (!File.Exists(outputPath)) + { + failed = true; + } + + if (failed) + { + var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath); + + _logger.Error(msg); + + throw new ApplicationException(msg); + } + else + { + var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath); + + _logger.Info(msg); + } + + await SetAssFont(outputPath).ConfigureAwait(false); + } + + /// + /// Sets the ass font. + /// + /// The file. + /// Task. + private async Task SetAssFont(string file) + { + _logger.Info("Setting ass font within {0}", file); + + string text; + Encoding encoding; + + using (var reader = new StreamReader(file, detectEncodingFromByteOrderMarks: true)) + { + encoding = reader.CurrentEncoding; + + text = await reader.ReadToEndAsync().ConfigureAwait(false); + } + + var newText = text.Replace(",Arial,", ",Arial Unicode MS,"); + + if (!string.Equals(text, newText)) + { + using (var writer = new StreamWriter(file, false, encoding)) + { + writer.Write(newText); + } + } + } + + public Task ExtractAudioImage(string path, CancellationToken cancellationToken) + { + return ExtractImage(new[] { path }, InputType.File, true, null, null, cancellationToken); + } + + public Task ExtractVideoImage(string[] inputFiles, InputType type, Video3DFormat? threedFormat, + TimeSpan? offset, CancellationToken cancellationToken) + { + return ExtractImage(inputFiles, type, false, threedFormat, offset, cancellationToken); + } + + private async Task ExtractImage(string[] inputFiles, InputType type, bool isAudio, + Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken) + { + var resourcePool = isAudio ? _audioImageResourcePool : _videoImageResourcePool; + + var inputArgument = GetInputArgument(inputFiles, type); + + if (!isAudio) + { + try + { + return await ExtractImageInternal(inputArgument, type, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false); + } + catch + { + _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument); + } + } + + return await ExtractImageInternal(inputArgument, type, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false); + } + + private async Task ExtractImageInternal(string inputPath, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(inputPath)) + { + throw new ArgumentNullException("inputPath"); + } + + // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600. + // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar + var vf = "scale=600:trunc(600/dar/2)*2"; + //crop=min(iw\,ih*dar):min(ih\,iw/dar):(iw-min(iw\,iw*sar))/2:(ih - min (ih\,ih/sar))/2,scale=600:(600/dar),thumbnail" -f image2 + + if (threedFormat.HasValue) + { + switch (threedFormat.Value) + { + case Video3DFormat.HalfSideBySide: + vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; + // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not. + break; + case Video3DFormat.FullSideBySide: + vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; + //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600. + break; + case Video3DFormat.HalfTopAndBottom: + vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; + //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600 + break; + case Video3DFormat.FullTopAndBottom: + vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; + // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600 + break; + } + } + + // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. + var args = useIFrame ? string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2},thumbnail=80\" -f image2 \"{1}\"", inputPath, "-", vf) : + string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf); + + var probeSize = GetProbeSizeArgument(type); + + if (!string.IsNullOrEmpty(probeSize)) + { + args = probeSize + " " + args; + } + + if (offset.HasValue) + { + args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)).ToString(UsCulture) + args; + } + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + FileName = FFMpegPath, + Arguments = args, + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false, + RedirectStandardOutput = true, + RedirectStandardError = true + } + }; + + await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); + + process.Start(); + + var memoryStream = new MemoryStream(); + +#pragma warning disable 4014 + // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback + process.StandardOutput.BaseStream.CopyToAsync(memoryStream); +#pragma warning restore 4014 + + // MUST read both stdout and stderr asynchronously or a deadlock may occurr + process.BeginErrorReadLine(); + + var ranToCompletion = process.WaitForExit(10000); + + if (!ranToCompletion) + { + try + { + _logger.Info("Killing ffmpeg process"); + + process.Kill(); + + process.WaitForExit(1000); + } + catch (Exception ex) + { + _logger.ErrorException("Error killing process", ex); + } + } + + resourcePool.Release(); + + var exitCode = ranToCompletion ? process.ExitCode : -1; + + process.Dispose(); + + if (exitCode == -1 || memoryStream.Length == 0) + { + memoryStream.Dispose(); + + var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath); + + _logger.Error(msg); + + throw new ApplicationException(msg); + } + + memoryStream.Position = 0; + return memoryStream; + } + + /// + /// Starts the and wait for process. + /// + /// The process. + /// The timeout. + /// true if XXXX, false otherwise + private bool StartAndWaitForProcess(Process process, int timeout = 10000) + { + process.Start(); + + var ranToCompletion = process.WaitForExit(timeout); + + if (!ranToCompletion) + { + try + { + _logger.Info("Killing ffmpeg process"); + + process.Kill(); + + process.WaitForExit(1000); + } + catch (Win32Exception ex) + { + _logger.ErrorException("Error killing process", ex); + } + catch (InvalidOperationException ex) + { + _logger.ErrorException("Error killing process", ex); + } + catch (NotSupportedException ex) + { + _logger.ErrorException("Error killing process", ex); + } + } + + return ranToCompletion; + } + + /// + /// Gets the file input argument. + /// + /// The path. + /// System.String. + private string GetFileInputArgument(string path) + { + return string.Format("file:\"{0}\"", path); + } + + /// + /// Gets the concat input argument. + /// + /// The playable stream files. + /// System.String. + private string GetConcatInputArgument(string[] playableStreamFiles) + { + // Get all streams + // If there's more than one we'll need to use the concat command + if (playableStreamFiles.Length > 1) + { + var files = string.Join("|", playableStreamFiles); + + return string.Format("concat:\"{0}\"", files); + } + + // Determine the input path for video files + return GetFileInputArgument(playableStreamFiles[0]); + } + + /// + /// Gets the bluray input argument. + /// + /// The bluray root. + /// System.String. + private string GetBlurayInputArgument(string blurayRoot) + { + return string.Format("bluray:\"{0}\"", blurayRoot); + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + Dispose(true); + } + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool dispose) + { + if (dispose) + { + _videoImageResourcePool.Dispose(); + } + } + } +} diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj new file mode 100644 index 000000000..d92522bf0 --- /dev/null +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -0,0 +1,80 @@ + + + + + Debug + AnyCPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451} + Library + Properties + MediaBrowser.MediaEncoding + MediaBrowser.MediaEncoding + v4.5 + 512 + ..\ + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + ..\packages\MediaBrowser.BdInfo.1.0.0.10\lib\net35\BDInfo.dll + + + ..\packages\MediaBrowser.BdInfo.1.0.0.10\lib\net35\DvdLib.dll + + + + + + + + + + + + + + + + + {9142eefa-7570-41e1-bfcc-468bb571af2f} + MediaBrowser.Common + + + {17e1f4e6-8abd-4fe5-9ecf-43d4b6087ba2} + MediaBrowser.Controller + + + {7eeeb4bb-f3e8-48fc-b4c5-70f0fff8329b} + MediaBrowser.Model + + + + + + + + + \ No newline at end of file diff --git a/MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs b/MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..6616e46ac --- /dev/null +++ b/MediaBrowser.MediaEncoding/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("MediaBrowser.MediaEncoding")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("MediaBrowser.MediaEncoding")] +[assembly: AssemblyCopyright("Copyright © 2014")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("05f49ab9-2a90-4332-9d41-7817a9cccd90")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/MediaBrowser.MediaEncoding/packages.config b/MediaBrowser.MediaEncoding/packages.config new file mode 100644 index 000000000..6e52b72b8 --- /dev/null +++ b/MediaBrowser.MediaEncoding/packages.config @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs index b3c3f278e..b2ca97f55 100644 --- a/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/AudioImageProvider.cs @@ -94,7 +94,7 @@ namespace MediaBrowser.Providers.MediaInfo { Directory.CreateDirectory(Path.GetDirectoryName(path)); - using (var stream = await _mediaEncoder.ExtractImage(new[] { item.Path }, InputType.File, true, null, null, cancellationToken).ConfigureAwait(false)) + using (var stream = await _mediaEncoder.ExtractAudioImage(item.Path, cancellationToken).ConfigureAwait(false)) { using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true)) { diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs index 58fe7f66d..cb326c5ad 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs @@ -113,8 +113,6 @@ namespace MediaBrowser.Providers.MediaInfo { cancellationToken.ThrowIfCancellationRequested(); - cancellationToken.ThrowIfCancellationRequested(); - var idString = item.Id.ToString("N"); var cachePath = Path.Combine(_appPaths.CachePath, "ffprobe-video", diff --git a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs index 354758497..70daa3f51 100644 --- a/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs +++ b/MediaBrowser.Providers/MediaInfo/VideoImageProvider.cs @@ -93,7 +93,7 @@ namespace MediaBrowser.Providers.MediaInfo var inputPath = MediaEncoderHelpers.GetInputArgument(item.Path, item.LocationType == LocationType.Remote, item.VideoType, item.IsoType, isoMount, item.PlayableStreamFileNames, out type); - var stream = await _mediaEncoder.ExtractImage(inputPath, type, false, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false); + var stream = await _mediaEncoder.ExtractVideoImage(inputPath, type, item.Video3DFormat, imageOffset, cancellationToken).ConfigureAwait(false); return new DynamicImageResponse { diff --git a/MediaBrowser.Server.Implementations/BdInfo/BdInfoExaminer.cs b/MediaBrowser.Server.Implementations/BdInfo/BdInfoExaminer.cs deleted file mode 100644 index 18f1b92fe..000000000 --- a/MediaBrowser.Server.Implementations/BdInfo/BdInfoExaminer.cs +++ /dev/null @@ -1,185 +0,0 @@ -using BDInfo; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.MediaInfo; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace MediaBrowser.Server.Implementations.BdInfo -{ - /// - /// Class BdInfoExaminer - /// - public class BdInfoExaminer : IBlurayExaminer - { - /// - /// Gets the disc info. - /// - /// The path. - /// BlurayDiscInfo. - public BlurayDiscInfo GetDiscInfo(string path) - { - var bdrom = new BDROM(path); - - bdrom.Scan(); - - // Get the longest playlist - var playlist = bdrom.PlaylistFiles.Values.OrderByDescending(p => p.TotalLength).FirstOrDefault(p => p.IsValid); - - var outputStream = new BlurayDiscInfo - { - MediaStreams = new List() - }; - - if (playlist == null) - { - return outputStream; - } - - outputStream.Chapters = playlist.Chapters; - - outputStream.RunTimeTicks = TimeSpan.FromSeconds(playlist.TotalLength).Ticks; - - var mediaStreams = new List { }; - - foreach (var stream in playlist.SortedStreams) - { - var videoStream = stream as TSVideoStream; - - if (videoStream != null) - { - AddVideoStream(mediaStreams, videoStream); - continue; - } - - var audioStream = stream as TSAudioStream; - - if (audioStream != null) - { - AddAudioStream(mediaStreams, audioStream); - continue; - } - - var textStream = stream as TSTextStream; - - if (textStream != null) - { - AddSubtitleStream(mediaStreams, textStream); - continue; - } - - var graphicsStream = stream as TSGraphicsStream; - - if (graphicsStream != null) - { - AddSubtitleStream(mediaStreams, graphicsStream); - } - } - - outputStream.MediaStreams = mediaStreams; - - outputStream.PlaylistName = playlist.Name; - - if (playlist.StreamClips != null && playlist.StreamClips.Any()) - { - // Get the files in the playlist - outputStream.Files = playlist.StreamClips.Select(i => i.StreamFile.Name).ToList(); - } - - return outputStream; - } - - /// - /// Adds the video stream. - /// - /// The streams. - /// The video stream. - private void AddVideoStream(List streams, TSVideoStream videoStream) - { - var mediaStream = new MediaStream - { - BitRate = Convert.ToInt32(videoStream.BitRate), - Width = videoStream.Width, - Height = videoStream.Height, - Codec = videoStream.CodecShortName, - IsInterlaced = videoStream.IsInterlaced, - Type = MediaStreamType.Video, - Index = streams.Count - }; - - if (videoStream.FrameRateDenominator > 0) - { - float frameRateEnumerator = videoStream.FrameRateEnumerator; - float frameRateDenominator = videoStream.FrameRateDenominator; - - mediaStream.AverageFrameRate = mediaStream.RealFrameRate = frameRateEnumerator / frameRateDenominator; - } - - streams.Add(mediaStream); - } - - /// - /// Adds the audio stream. - /// - /// The streams. - /// The audio stream. - private void AddAudioStream(List streams, TSAudioStream audioStream) - { - var stream = new MediaStream - { - Codec = audioStream.CodecShortName, - Language = audioStream.LanguageCode, - Channels = audioStream.ChannelCount, - SampleRate = audioStream.SampleRate, - Type = MediaStreamType.Audio, - Index = streams.Count - }; - - var bitrate = Convert.ToInt32(audioStream.BitRate); - - if (bitrate > 0) - { - stream.BitRate = bitrate; - } - - if (audioStream.LFE > 0) - { - stream.Channels = audioStream.ChannelCount + 1; - } - - streams.Add(stream); - } - - /// - /// Adds the subtitle stream. - /// - /// The streams. - /// The text stream. - private void AddSubtitleStream(List streams, TSTextStream textStream) - { - streams.Add(new MediaStream - { - Language = textStream.LanguageCode, - Codec = textStream.CodecShortName, - Type = MediaStreamType.Subtitle, - Index = streams.Count - }); - } - - /// - /// Adds the subtitle stream. - /// - /// The streams. - /// The text stream. - private void AddSubtitleStream(List streams, TSGraphicsStream textStream) - { - streams.Add(new MediaStream - { - Language = textStream.LanguageCode, - Codec = textStream.CodecShortName, - Type = MediaStreamType.Subtitle, - Index = streams.Count - }); - } - } -} diff --git a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs index 0a0b3f4bc..9279fd8d7 100644 --- a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs +++ b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs @@ -249,17 +249,24 @@ namespace MediaBrowser.Server.Implementations.IO // Creating a FileSystemWatcher over the LAN can take hundreds of milliseconds, so wrap it in a Task to do them all in parallel Task.Run(() => { - var newWatcher = new FileSystemWatcher(path, "*") { IncludeSubdirectories = true, InternalBufferSize = 32767 }; + try + { + var newWatcher = new FileSystemWatcher(path, "*") + { + IncludeSubdirectories = true, + InternalBufferSize = 32767 + }; - newWatcher.Created += watcher_Changed; - newWatcher.Deleted += watcher_Changed; - newWatcher.Renamed += watcher_Changed; - newWatcher.Changed += watcher_Changed; + newWatcher.NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.DirectoryName | + NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size; - newWatcher.Error += watcher_Error; + newWatcher.Created += watcher_Changed; + newWatcher.Deleted += watcher_Changed; + newWatcher.Renamed += watcher_Changed; + newWatcher.Changed += watcher_Changed; + + newWatcher.Error += watcher_Error; - try - { if (_fileSystemWatchers.TryAdd(path, newWatcher)) { newWatcher.EnableRaisingEvents = true; @@ -272,11 +279,7 @@ namespace MediaBrowser.Server.Implementations.IO } } - catch (IOException ex) - { - Logger.ErrorException("Error watching path: {0}", ex, path); - } - catch (PlatformNotSupportedException ex) + catch (Exception ex) { Logger.ErrorException("Error watching path: {0}", ex, path); } @@ -346,7 +349,9 @@ namespace MediaBrowser.Server.Implementations.IO { try { - OnWatcherChanged(e); + Logger.Debug("Watcher sees change of type " + e.ChangeType + " to " + e.FullPath); + + ReportFileSystemChanged(e.FullPath); } catch (Exception ex) { @@ -354,13 +359,6 @@ namespace MediaBrowser.Server.Implementations.IO } } - private void OnWatcherChanged(FileSystemEventArgs e) - { - Logger.Debug("Watcher sees change of type " + e.ChangeType + " to " + e.FullPath); - - ReportFileSystemChanged(e.FullPath); - } - public void ReportFileSystemChanged(string path) { if (string.IsNullOrEmpty(path)) @@ -370,12 +368,9 @@ namespace MediaBrowser.Server.Implementations.IO var filename = Path.GetFileName(path); - // Ignore certain files - if (!string.IsNullOrEmpty(filename) && _alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase)) - { - return; - } + var monitorPath = !(!string.IsNullOrEmpty(filename) && _alwaysIgnoreFiles.Contains(filename, StringComparer.OrdinalIgnoreCase)); + // Ignore certain files var tempIgnorePaths = _tempIgnoredPaths.Keys.ToList(); // If the parent of an ignored path has a change event, ignore that too @@ -416,12 +411,15 @@ namespace MediaBrowser.Server.Implementations.IO })) { - return; + monitorPath = false; } - // Avoid implicitly captured closure - var affectedPath = path; - _affectedPaths.AddOrUpdate(path, path, (key, oldValue) => affectedPath); + if (monitorPath) + { + // Avoid implicitly captured closure + var affectedPath = path; + _affectedPaths.AddOrUpdate(path, path, (key, oldValue) => affectedPath); + } lock (_timerLock) { diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index 73a12caf2..ea7ef2ed6 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -48,14 +48,6 @@ ..\packages\Alchemy.2.2.1\lib\net40\Alchemy.dll - - False - ..\packages\MediaBrowser.BdInfo.1.0.0.10\lib\net35\BDInfo.dll - - - False - ..\packages\MediaBrowser.BdInfo.1.0.0.10\lib\net35\DvdLib.dll - False ..\packages\Mono.Nat.1.2.3\lib\Net40\Mono.Nat.dll @@ -105,7 +97,6 @@ Properties\SharedVersion.cs - @@ -191,7 +182,6 @@ - diff --git a/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs b/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs index f74865d2c..7237ffee5 100644 --- a/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -178,7 +178,7 @@ namespace MediaBrowser.Server.Implementations.MediaEncoder { Directory.CreateDirectory(Path.GetDirectoryName(path)); - using (var stream = await _encoder.ExtractImage(inputPath, type, false, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false)) + using (var stream = await _encoder.ExtractVideoImage(inputPath, type, video.Video3DFormat, time, cancellationToken).ConfigureAwait(false)) { using (var fileStream = _fileSystem.GetFileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read, true)) { diff --git a/MediaBrowser.Server.Implementations/MediaEncoder/MediaEncoder.cs b/MediaBrowser.Server.Implementations/MediaEncoder/MediaEncoder.cs deleted file mode 100644 index c646d80bc..000000000 --- a/MediaBrowser.Server.Implementations/MediaEncoder/MediaEncoder.cs +++ /dev/null @@ -1,958 +0,0 @@ -using MediaBrowser.Common.Configuration; -using MediaBrowser.Common.IO; -using MediaBrowser.Controller.MediaEncoding; -using MediaBrowser.Model.Entities; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Serialization; -using System; -using System.Collections.Concurrent; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace MediaBrowser.Server.Implementations.MediaEncoder -{ - /// - /// Class MediaEncoder - /// - public class MediaEncoder : IMediaEncoder, IDisposable - { - /// - /// The _logger - /// - private readonly ILogger _logger; - - /// - /// The _app paths - /// - private readonly IApplicationPaths _appPaths; - - /// - /// Gets the json serializer. - /// - /// The json serializer. - private readonly IJsonSerializer _jsonSerializer; - - /// - /// The video image resource pool - /// - private readonly SemaphoreSlim _videoImageResourcePool = new SemaphoreSlim(1, 1); - - /// - /// The audio image resource pool - /// - private readonly SemaphoreSlim _audioImageResourcePool = new SemaphoreSlim(2, 2); - - /// - /// The FF probe resource pool - /// - private readonly SemaphoreSlim _ffProbeResourcePool = new SemaphoreSlim(2, 2); - private readonly IFileSystem _fileSystem; - - public string FFMpegPath { get; private set; } - - public string FFProbePath { get; private set; } - - public string Version { get; private set; } - - public MediaEncoder(ILogger logger, IApplicationPaths appPaths, - IJsonSerializer jsonSerializer, string ffMpegPath, string ffProbePath, string version, IFileSystem fileSystem) - { - _logger = logger; - _appPaths = appPaths; - _jsonSerializer = jsonSerializer; - Version = version; - _fileSystem = fileSystem; - FFProbePath = ffProbePath; - FFMpegPath = ffMpegPath; - } - - /// - /// Gets the encoder path. - /// - /// The encoder path. - public string EncoderPath - { - get { return FFMpegPath; } - } - - /// - /// The _semaphoreLocks - /// - private readonly ConcurrentDictionary _semaphoreLocks = new ConcurrentDictionary(); - - /// - /// Gets the lock. - /// - /// The filename. - /// System.Object. - private SemaphoreSlim GetLock(string filename) - { - return _semaphoreLocks.GetOrAdd(filename, key => new SemaphoreSlim(1, 1)); - } - - /// - /// Gets the media info. - /// - /// The input files. - /// The type. - /// if set to true [is audio]. - /// The cancellation token. - /// Task. - public Task GetMediaInfo(string[] inputFiles, InputType type, bool isAudio, - CancellationToken cancellationToken) - { - return GetMediaInfoInternal(GetInputArgument(inputFiles, type), !isAudio, - GetProbeSizeArgument(type), cancellationToken); - } - - /// - /// Gets the input argument. - /// - /// The input files. - /// The type. - /// System.String. - /// Unrecognized InputType - public string GetInputArgument(string[] inputFiles, InputType type) - { - string inputPath; - - switch (type) - { - case InputType.Bluray: - case InputType.Dvd: - case InputType.File: - inputPath = GetConcatInputArgument(inputFiles); - break; - case InputType.Url: - inputPath = GetHttpInputArgument(inputFiles); - break; - default: - throw new ArgumentException("Unrecognized InputType"); - } - - return inputPath; - } - - /// - /// Gets the HTTP input argument. - /// - /// The input files. - /// System.String. - private string GetHttpInputArgument(string[] inputFiles) - { - var url = inputFiles[0]; - - return string.Format("\"{0}\"", url); - } - - /// - /// Gets the probe size argument. - /// - /// The type. - /// System.String. - public string GetProbeSizeArgument(InputType type) - { - return type == InputType.Dvd ? "-probesize 1G -analyzeduration 200M" : string.Empty; - } - - /// - /// Gets the media info internal. - /// - /// The input path. - /// if set to true [extract chapters]. - /// The probe size argument. - /// The cancellation token. - /// Task{MediaInfoResult}. - /// - private async Task GetMediaInfoInternal(string inputPath, bool extractChapters, - string probeSizeArgument, - CancellationToken cancellationToken) - { - var args = extractChapters - ? "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_chapters -show_format" - : "{0} -i {1} -threads 0 -v info -print_format json -show_streams -show_format"; - - var process = new Process - { - StartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - - // Must consume both or ffmpeg may hang due to deadlocks. See comments below. - RedirectStandardOutput = true, - RedirectStandardError = true, - FileName = FFProbePath, - Arguments = string.Format(args, - probeSizeArgument, inputPath).Trim(), - - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - }, - - EnableRaisingEvents = true - }; - - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - - process.Exited += ProcessExited; - - await _ffProbeResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); - - InternalMediaInfoResult result; - - try - { - process.Start(); - } - catch (Exception ex) - { - _ffProbeResourcePool.Release(); - - _logger.ErrorException("Error starting ffprobe", ex); - - throw; - } - - try - { - process.BeginErrorReadLine(); - - result = _jsonSerializer.DeserializeFromStream(process.StandardOutput.BaseStream); - } - catch - { - // Hate having to do this - try - { - process.Kill(); - } - catch (Exception ex1) - { - _logger.ErrorException("Error killing ffprobe", ex1); - } - - throw; - } - finally - { - _ffProbeResourcePool.Release(); - } - - if (result == null) - { - throw new ApplicationException(string.Format("FFProbe failed for {0}", inputPath)); - } - - cancellationToken.ThrowIfCancellationRequested(); - - if (result.streams != null) - { - // Normalize aspect ratio if invalid - foreach (var stream in result.streams) - { - if (string.Equals(stream.display_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase)) - { - stream.display_aspect_ratio = string.Empty; - } - if (string.Equals(stream.sample_aspect_ratio, "0:1", StringComparison.OrdinalIgnoreCase)) - { - stream.sample_aspect_ratio = string.Empty; - } - } - } - - return result; - } - - /// - /// The us culture - /// - protected readonly CultureInfo UsCulture = new CultureInfo("en-US"); - - /// - /// Processes the exited. - /// - /// The sender. - /// The instance containing the event data. - private void ProcessExited(object sender, EventArgs e) - { - ((Process)sender).Dispose(); - } - - /// - /// Converts the text subtitle to ass. - /// - /// The input path. - /// The output path. - /// The language. - /// The cancellation token. - /// Task. - public async Task ConvertTextSubtitleToAss(string inputPath, string outputPath, string language, CancellationToken cancellationToken) - { - var semaphore = GetLock(outputPath); - - await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); - - try - { - if (!File.Exists(outputPath)) - { - await ConvertTextSubtitleToAssInternal(inputPath, outputPath, language).ConfigureAwait(false); - } - } - finally - { - semaphore.Release(); - } - } - - private const int FastSeekOffsetSeconds = 1; - - /// - /// Converts the text subtitle to ass. - /// - /// The input path. - /// The output path. - /// The language. - /// Task. - /// inputPath - /// or - /// outputPath - /// - private async Task ConvertTextSubtitleToAssInternal(string inputPath, string outputPath, string language) - { - if (string.IsNullOrEmpty(inputPath)) - { - throw new ArgumentNullException("inputPath"); - } - - if (string.IsNullOrEmpty(outputPath)) - { - throw new ArgumentNullException("outputPath"); - } - - - var encodingParam = string.IsNullOrEmpty(language) ? string.Empty : - GetSubtitleLanguageEncodingParam(language) + " "; - - var process = new Process - { - StartInfo = new ProcessStartInfo - { - RedirectStandardOutput = false, - RedirectStandardError = true, - - CreateNoWindow = true, - UseShellExecute = false, - FileName = FFMpegPath, - Arguments = - string.Format("{0} -i \"{1}\" -c:s ass \"{2}\"", encodingParam, inputPath, outputPath), - - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - } - }; - - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - - var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-convert-" + Guid.NewGuid() + ".txt"); - Directory.CreateDirectory(Path.GetDirectoryName(logFilePath)); - - var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true); - - try - { - process.Start(); - } - catch (Exception ex) - { - logFileStream.Dispose(); - - _logger.ErrorException("Error starting ffmpeg", ex); - - throw; - } - - var logTask = process.StandardError.BaseStream.CopyToAsync(logFileStream); - - var ranToCompletion = process.WaitForExit(60000); - - if (!ranToCompletion) - { - try - { - _logger.Info("Killing ffmpeg subtitle conversion process"); - - process.Kill(); - - process.WaitForExit(1000); - - await logTask.ConfigureAwait(false); - } - catch (Exception ex) - { - _logger.ErrorException("Error killing subtitle conversion process", ex); - } - finally - { - logFileStream.Dispose(); - } - } - - var exitCode = ranToCompletion ? process.ExitCode : -1; - - process.Dispose(); - - var failed = false; - - if (exitCode == -1) - { - failed = true; - - if (File.Exists(outputPath)) - { - try - { - _logger.Info("Deleting converted subtitle due to failure: ", outputPath); - File.Delete(outputPath); - } - catch (IOException ex) - { - _logger.ErrorException("Error deleting converted subtitle {0}", ex, outputPath); - } - } - } - else if (!File.Exists(outputPath)) - { - failed = true; - } - - if (failed) - { - var msg = string.Format("ffmpeg subtitle converted failed for {0}", inputPath); - - _logger.Error(msg); - - throw new ApplicationException(msg); - } - await SetAssFont(outputPath).ConfigureAwait(false); - } - - protected string GetFastSeekCommandLineParameter(TimeSpan offset) - { - var seconds = offset.TotalSeconds - FastSeekOffsetSeconds; - - if (seconds > 0) - { - return string.Format("-ss {0} ", seconds.ToString(UsCulture)); - } - - return string.Empty; - } - - protected string GetSlowSeekCommandLineParameter(TimeSpan offset) - { - if (offset.TotalSeconds - FastSeekOffsetSeconds > 0) - { - return string.Format(" -ss {0}", FastSeekOffsetSeconds.ToString(UsCulture)); - } - - return string.Empty; - } - - /// - /// Gets the subtitle language encoding param. - /// - /// The language. - /// System.String. - private string GetSubtitleLanguageEncodingParam(string language) - { - switch (language.ToLower()) - { - case "pol": - case "cze": - case "ces": - case "slo": - case "slk": - case "hun": - case "slv": - case "srp": - case "hrv": - case "rum": - case "ron": - case "rup": - case "alb": - case "sqi": - return "-sub_charenc windows-1250"; - case "ara": - return "-sub_charenc windows-1256"; - case "heb": - return "-sub_charenc windows-1255"; - case "grc": - case "gre": - return "-sub_charenc windows-1253"; - case "crh": - case "ota": - case "tur": - return "-sub_charenc windows-1254"; - case "rus": - return "-sub_charenc windows-1251"; - case "vie": - return "-sub_charenc windows-1258"; - case "kor": - return "-sub_charenc cp949"; - default: - return "-sub_charenc windows-1252"; - } - } - - /// - /// Extracts the text subtitle. - /// - /// The input files. - /// The type. - /// Index of the subtitle stream. - /// if set to true, copy stream instead of converting. - /// The output path. - /// The cancellation token. - /// Task. - /// Must use inputPath list overload - public async Task ExtractTextSubtitle(string[] inputFiles, InputType type, int subtitleStreamIndex, bool copySubtitleStream, string outputPath, CancellationToken cancellationToken) - { - var semaphore = GetLock(outputPath); - - await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); - - try - { - if (!File.Exists(outputPath)) - { - await ExtractTextSubtitleInternal(GetInputArgument(inputFiles, type), subtitleStreamIndex, copySubtitleStream, outputPath, cancellationToken).ConfigureAwait(false); - } - } - finally - { - semaphore.Release(); - } - } - - /// - /// Extracts the text subtitle. - /// - /// The input path. - /// Index of the subtitle stream. - /// if set to true, copy stream instead of converting. - /// The output path. - /// The cancellation token. - /// Task. - /// inputPath - /// or - /// outputPath - /// or - /// cancellationToken - /// - private async Task ExtractTextSubtitleInternal(string inputPath, int subtitleStreamIndex, bool copySubtitleStream, string outputPath, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(inputPath)) - { - throw new ArgumentNullException("inputPath"); - } - - if (string.IsNullOrEmpty(outputPath)) - { - throw new ArgumentNullException("outputPath"); - } - - string processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s ass \"{2}\"", inputPath, subtitleStreamIndex, outputPath); - - if (copySubtitleStream) - { - processArgs = string.Format("-i {0} -map 0:{1} -an -vn -c:s copy \"{2}\"", inputPath, subtitleStreamIndex, outputPath); - } - - var process = new Process - { - StartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - - RedirectStandardOutput = false, - RedirectStandardError = true, - - FileName = FFMpegPath, - Arguments = processArgs, - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false - } - }; - - _logger.Debug("{0} {1}", process.StartInfo.FileName, process.StartInfo.Arguments); - - var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "ffmpeg-sub-extract-" + Guid.NewGuid() + ".txt"); - Directory.CreateDirectory(Path.GetDirectoryName(logFilePath)); - - var logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true); - - try - { - process.Start(); - } - catch (Exception ex) - { - logFileStream.Dispose(); - - _logger.ErrorException("Error starting ffmpeg", ex); - - throw; - } - - process.StandardError.BaseStream.CopyToAsync(logFileStream); - - var ranToCompletion = process.WaitForExit(60000); - - if (!ranToCompletion) - { - try - { - _logger.Info("Killing ffmpeg subtitle extraction process"); - - process.Kill(); - - process.WaitForExit(1000); - } - catch (Exception ex) - { - _logger.ErrorException("Error killing subtitle extraction process", ex); - } - finally - { - logFileStream.Dispose(); - } - } - - var exitCode = ranToCompletion ? process.ExitCode : -1; - - process.Dispose(); - - var failed = false; - - if (exitCode == -1) - { - failed = true; - - if (File.Exists(outputPath)) - { - try - { - _logger.Info("Deleting extracted subtitle due to failure: ", outputPath); - File.Delete(outputPath); - } - catch (IOException ex) - { - _logger.ErrorException("Error deleting extracted subtitle {0}", ex, outputPath); - } - } - } - else if (!File.Exists(outputPath)) - { - failed = true; - } - - if (failed) - { - var msg = string.Format("ffmpeg subtitle extraction failed for {0} to {1}", inputPath, outputPath); - - _logger.Error(msg); - - throw new ApplicationException(msg); - } - else - { - var msg = string.Format("ffmpeg subtitle extraction completed for {0} to {1}", inputPath, outputPath); - - _logger.Info(msg); - } - - await SetAssFont(outputPath).ConfigureAwait(false); - } - - /// - /// Sets the ass font. - /// - /// The file. - /// Task. - private async Task SetAssFont(string file) - { - _logger.Info("Setting ass font within {0}", file); - - string text; - Encoding encoding; - - using (var reader = new StreamReader(file, detectEncodingFromByteOrderMarks: true)) - { - encoding = reader.CurrentEncoding; - - text = await reader.ReadToEndAsync().ConfigureAwait(false); - } - - var newText = text.Replace(",Arial,", ",Arial Unicode MS,"); - - if (!string.Equals(text, newText)) - { - using (var writer = new StreamWriter(file, false, encoding)) - { - writer.Write(newText); - } - } - } - - public async Task ExtractImage(string[] inputFiles, InputType type, bool isAudio, - Video3DFormat? threedFormat, TimeSpan? offset, CancellationToken cancellationToken) - { - var resourcePool = isAudio ? _audioImageResourcePool : _videoImageResourcePool; - - var inputArgument = GetInputArgument(inputFiles, type); - - if (!isAudio) - { - try - { - return await ExtractImageInternal(inputArgument, type, threedFormat, offset, true, resourcePool, cancellationToken).ConfigureAwait(false); - } - catch - { - _logger.Error("I-frame image extraction failed, will attempt standard way. Input: {0}", inputArgument); - } - } - - return await ExtractImageInternal(inputArgument, type, threedFormat, offset, false, resourcePool, cancellationToken).ConfigureAwait(false); - } - - private async Task ExtractImageInternal(string inputPath, InputType type, Video3DFormat? threedFormat, TimeSpan? offset, bool useIFrame, SemaphoreSlim resourcePool, CancellationToken cancellationToken) - { - if (string.IsNullOrEmpty(inputPath)) - { - throw new ArgumentNullException("inputPath"); - } - - // apply some filters to thumbnail extracted below (below) crop any black lines that we made and get the correct ar then scale to width 600. - // This filter chain may have adverse effects on recorded tv thumbnails if ar changes during presentation ex. commercials @ diff ar - var vf = "scale=600:trunc(600/dar/2)*2"; - //crop=min(iw\,ih*dar):min(ih\,iw/dar):(iw-min(iw\,iw*sar))/2:(ih - min (ih\,ih/sar))/2,scale=600:(600/dar),thumbnail" -f image2 - - if (threedFormat.HasValue) - { - switch (threedFormat.Value) - { - case Video3DFormat.HalfSideBySide: - vf = "crop=iw/2:ih:0:0,scale=(iw*2):ih,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; - // hsbs crop width in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600. Work out the correct height based on the display aspect it will maintain the aspect where -1 in this case (3d) may not. - break; - case Video3DFormat.FullSideBySide: - vf = "crop=iw/2:ih:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; - //fsbs crop width in half,set the display aspect,crop out any black bars we may have made the scale width to 600. - break; - case Video3DFormat.HalfTopAndBottom: - vf = "crop=iw:ih/2:0:0,scale=(iw*2):ih),setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; - //htab crop heigh in half,scale to correct size, set the display aspect,crop out any black bars we may have made the scale width to 600 - break; - case Video3DFormat.FullTopAndBottom: - vf = "crop=iw:ih/2:0:0,setdar=dar=a,crop=min(iw\\,ih*dar):min(ih\\,iw/dar):(iw-min(iw\\,iw*sar))/2:(ih - min (ih\\,ih/sar))/2,setsar=sar=1,scale=600:trunc(600/dar/2)*2"; - // ftab crop heigt in half, set the display aspect,crop out any black bars we may have made the scale width to 600 - break; - } - } - - // Use ffmpeg to sample 100 (we can drop this if required using thumbnail=50 for 50 frames) frames and pick the best thumbnail. Have a fall back just in case. - var args = useIFrame ? string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2},thumbnail\" -f image2 \"{1}\"", inputPath, "-", vf) : - string.Format("-i {0} -threads 0 -v quiet -vframes 1 -vf \"{2}\" -f image2 \"{1}\"", inputPath, "-", vf); - - var probeSize = GetProbeSizeArgument(type); - - if (!string.IsNullOrEmpty(probeSize)) - { - args = probeSize + " " + args; - } - - if (offset.HasValue) - { - args = string.Format("-ss {0} ", Convert.ToInt32(offset.Value.TotalSeconds)).ToString(UsCulture) + args; - } - - var process = new Process - { - StartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - UseShellExecute = false, - FileName = FFMpegPath, - Arguments = args, - WindowStyle = ProcessWindowStyle.Hidden, - ErrorDialog = false, - RedirectStandardOutput = true, - RedirectStandardError = true - } - }; - - await resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); - - process.Start(); - - var memoryStream = new MemoryStream(); - -#pragma warning disable 4014 - // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback - process.StandardOutput.BaseStream.CopyToAsync(memoryStream); -#pragma warning restore 4014 - - // MUST read both stdout and stderr asynchronously or a deadlock may occurr - process.BeginErrorReadLine(); - - var ranToCompletion = process.WaitForExit(10000); - - if (!ranToCompletion) - { - try - { - _logger.Info("Killing ffmpeg process"); - - process.Kill(); - - process.WaitForExit(1000); - } - catch (Exception ex) - { - _logger.ErrorException("Error killing process", ex); - } - } - - resourcePool.Release(); - - var exitCode = ranToCompletion ? process.ExitCode : -1; - - process.Dispose(); - - if (exitCode == -1 || memoryStream.Length == 0) - { - memoryStream.Dispose(); - - var msg = string.Format("ffmpeg image extraction failed for {0}", inputPath); - - _logger.Error(msg); - - throw new ApplicationException(msg); - } - - memoryStream.Position = 0; - return memoryStream; - } - - /// - /// Starts the and wait for process. - /// - /// The process. - /// The timeout. - /// true if XXXX, false otherwise - private bool StartAndWaitForProcess(Process process, int timeout = 10000) - { - process.Start(); - - var ranToCompletion = process.WaitForExit(timeout); - - if (!ranToCompletion) - { - try - { - _logger.Info("Killing ffmpeg process"); - - process.Kill(); - - process.WaitForExit(1000); - } - catch (Win32Exception ex) - { - _logger.ErrorException("Error killing process", ex); - } - catch (InvalidOperationException ex) - { - _logger.ErrorException("Error killing process", ex); - } - catch (NotSupportedException ex) - { - _logger.ErrorException("Error killing process", ex); - } - } - - return ranToCompletion; - } - - /// - /// Gets the file input argument. - /// - /// The path. - /// System.String. - private string GetFileInputArgument(string path) - { - return string.Format("file:\"{0}\"", path); - } - - /// - /// Gets the concat input argument. - /// - /// The playable stream files. - /// System.String. - private string GetConcatInputArgument(string[] playableStreamFiles) - { - // Get all streams - // If there's more than one we'll need to use the concat command - if (playableStreamFiles.Length > 1) - { - var files = string.Join("|", playableStreamFiles); - - return string.Format("concat:\"{0}\"", files); - } - - // Determine the input path for video files - return GetFileInputArgument(playableStreamFiles[0]); - } - - /// - /// Gets the bluray input argument. - /// - /// The bluray root. - /// System.String. - private string GetBlurayInputArgument(string blurayRoot) - { - return string.Format("bluray:\"{0}\"", blurayRoot); - } - - /// - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// - public void Dispose() - { - Dispose(true); - } - - /// - /// Releases unmanaged and - optionally - managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. - protected virtual void Dispose(bool dispose) - { - if (dispose) - { - _videoImageResourcePool.Dispose(); - } - } - } -} diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteMediaStreamsRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteMediaStreamsRepository.cs index f4e7fd0a6..fde1e7f21 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteMediaStreamsRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteMediaStreamsRepository.cs @@ -37,6 +37,8 @@ namespace MediaBrowser.Server.Implementations.Persistence var createTableCommand = "create table if not exists mediastreams "; + // Add PixelFormat column + createTableCommand += "(ItemId GUID, StreamIndex INT, StreamType TEXT, Codec TEXT, Language TEXT, ChannelLayout TEXT, Profile TEXT, AspectRatio TEXT, Path TEXT, IsInterlaced BIT, BitRate INT NULL, Channels INT NULL, SampleRate INT NULL, IsDefault BIT, IsForced BIT, IsExternal BIT, Height INT NULL, Width INT NULL, AverageFrameRate FLOAT NULL, RealFrameRate FLOAT NULL, Level FLOAT NULL, PRIMARY KEY (ItemId, StreamIndex))"; string[] queries = { diff --git a/MediaBrowser.Server.Implementations/packages.config b/MediaBrowser.Server.Implementations/packages.config index f04536190..d82e880c9 100644 --- a/MediaBrowser.Server.Implementations/packages.config +++ b/MediaBrowser.Server.Implementations/packages.config @@ -1,7 +1,6 @@  - diff --git a/MediaBrowser.ServerApplication/ApplicationHost.cs b/MediaBrowser.ServerApplication/ApplicationHost.cs index 06ffa37a1..6083158bc 100644 --- a/MediaBrowser.ServerApplication/ApplicationHost.cs +++ b/MediaBrowser.ServerApplication/ApplicationHost.cs @@ -33,13 +33,14 @@ using MediaBrowser.Controller.Sorting; using MediaBrowser.Controller.Themes; using MediaBrowser.Dlna; using MediaBrowser.Dlna.PlayTo; +using MediaBrowser.MediaEncoding.BdInfo; +using MediaBrowser.MediaEncoding.Encoder; using MediaBrowser.Model.Logging; using MediaBrowser.Model.MediaInfo; using MediaBrowser.Model.System; using MediaBrowser.Model.Updates; using MediaBrowser.Providers.Manager; using MediaBrowser.Server.Implementations; -using MediaBrowser.Server.Implementations.BdInfo; using MediaBrowser.Server.Implementations.Channels; using MediaBrowser.Server.Implementations.Collections; using MediaBrowser.Server.Implementations.Configuration; @@ -821,7 +822,10 @@ namespace MediaBrowser.ServerApplication // Server implementations list.Add(typeof(ServerApplicationPaths).Assembly); - // Dlna implementations + // MediaEncoding + list.Add(typeof(MediaEncoder).Assembly); + + // Dlna list.Add(typeof(PlayToServerEntryPoint).Assembly); list.AddRange(Assemblies.GetAssembliesWithParts()); diff --git a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj index 227d0dd1d..d999841ca 100644 --- a/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj +++ b/MediaBrowser.ServerApplication/MediaBrowser.ServerApplication.csproj @@ -195,6 +195,10 @@ {734098eb-6dc1-4dd0-a1ca-3140dcd2737c} MediaBrowser.Dlna + + {0bd82fa6-eb8a-4452-8af5-74f9c3849451} + MediaBrowser.MediaEncoding + {7eeeb4bb-f3e8-48fc-b4c5-70f0fff8329b} MediaBrowser.Model diff --git a/MediaBrowser.sln b/MediaBrowser.sln index e05b8ae6a..c2f9dff59 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -41,6 +41,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.ServerApplicat EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.Dlna", "MediaBrowser.Dlna\MediaBrowser.Dlna.csproj", "{734098EB-6DC1-4DD0-A1CA-3140DCD2737C}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MediaBrowser.MediaEncoding", "MediaBrowser.MediaEncoding\MediaBrowser.MediaEncoding.csproj", "{0BD82FA6-EB8A-4452-8AF5-74F9C3849451}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -247,6 +249,20 @@ Global {734098EB-6DC1-4DD0-A1CA-3140DCD2737C}.Release|Win32.ActiveCfg = Release|Any CPU {734098EB-6DC1-4DD0-A1CA-3140DCD2737C}.Release|x64.ActiveCfg = Release|Any CPU {734098EB-6DC1-4DD0-A1CA-3140DCD2737C}.Release|x86.ActiveCfg = Release|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Debug|Any CPU.Build.0 = Debug|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Debug|Win32.ActiveCfg = Debug|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Debug|x64.ActiveCfg = Debug|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Debug|x86.ActiveCfg = Debug|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Release|Any CPU.ActiveCfg = Release|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Release|Any CPU.Build.0 = Release|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Release|Win32.ActiveCfg = Release|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Release|x64.ActiveCfg = Release|Any CPU + {0BD82FA6-EB8A-4452-8AF5-74F9C3849451}.Release|x86.ActiveCfg = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE -- cgit v1.2.3 From 0aec40966e281a1ffefe78ad6461b2f6582ce628 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 27 Mar 2014 19:01:42 -0400 Subject: add image encoder based on ffmpeg --- MediaBrowser.Api/Playback/BaseStreamingService.cs | 9 +- .../MediaBrowser.Controller.csproj | 1 + .../MediaEncoding/IMediaEncoder.cs | 8 ++ .../MediaEncoding/ImageEncodingOptions.cs | 18 +++ MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs | 158 +++++++++++++++++++++ MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 9 +- .../MediaBrowser.MediaEncoding.csproj | 1 + 7 files changed, 192 insertions(+), 12 deletions(-) create mode 100644 MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs create mode 100644 MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index ceb96d226..b510a640e 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -503,14 +503,13 @@ namespace MediaBrowser.Api.Playback return string.Format("{4} -vf \"{0}scale=trunc({1}/2)*2:trunc({2}/2)*2{3}\"", yadifParam, widthParam, heightParam, assSubtitleParam, copyTsParam); } - // If Max dimensions were supplied - //this makes my brain hurt. For width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size + // If Max dimensions were supplied, for width selects lowest even number between input width and width req size and selects lowest even number from in width*display aspect and requested size if (request.MaxWidth.HasValue && request.MaxHeight.HasValue) { - var MaxwidthParam = request.MaxWidth.Value.ToString(UsCulture); - var MaxheightParam = request.MaxHeight.Value.ToString(UsCulture); + var maxWidthParam = request.MaxWidth.Value.ToString(UsCulture); + var maxHeightParam = request.MaxHeight.Value.ToString(UsCulture); - return string.Format("{4} -vf \"{0}scale=trunc(min(iw\\,{1})/2)*2:trunc(min((iw/dar)\\,{2})/2)*2{3}\"", yadifParam, MaxwidthParam, MaxheightParam, assSubtitleParam, copyTsParam); + return string.Format("{4} -vf \"{0}scale=trunc(min(iw\\,{1})/2)*2:trunc(min((iw/dar)\\,{2})/2)*2{3}\"", yadifParam, maxWidthParam, maxHeightParam, assSubtitleParam, copyTsParam); } var isH264Output = outputVideoCodec.Equals("libx264", StringComparison.OrdinalIgnoreCase); diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 2e0d44e40..9915ac044 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -157,6 +157,7 @@ + diff --git a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs index 657e52e5a..e9081fe8a 100644 --- a/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs +++ b/MediaBrowser.Controller/MediaEncoding/IMediaEncoder.cs @@ -88,6 +88,14 @@ namespace MediaBrowser.Controller.MediaEncoding /// The type. /// System.String. string GetInputArgument(string[] inputFiles, InputType type); + + /// + /// Encodes the image. + /// + /// The options. + /// The cancellation token. + /// Task{Stream}. + Task EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken); } /// diff --git a/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs b/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs new file mode 100644 index 000000000..c76977f29 --- /dev/null +++ b/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs @@ -0,0 +1,18 @@ + +namespace MediaBrowser.Controller.MediaEncoding +{ + public class ImageEncodingOptions + { + public string InputPath { get; set; } + + public int? Width { get; set; } + + public int? Height { get; set; } + + public int? MaxWidth { get; set; } + + public int? MaxHeight { get; set; } + + public string Format { get; set; } + } +} diff --git a/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs new file mode 100644 index 000000000..5e4221b0f --- /dev/null +++ b/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs @@ -0,0 +1,158 @@ +using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Model.Logging; +using System; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.MediaEncoding.Encoder +{ + public class ImageEncoder + { + private readonly string _ffmpegPath; + private readonly ILogger _logger; + private readonly CultureInfo _usCulture = new CultureInfo("en-US"); + + private static readonly SemaphoreSlim ResourcePool = new SemaphoreSlim(5, 5); + + public ImageEncoder(string ffmpegPath, ILogger logger) + { + _ffmpegPath = ffmpegPath; + _logger = logger; + } + + public async Task EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken) + { + ValidateInput(options); + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + FileName = _ffmpegPath, + Arguments = GetArguments(options), + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false, + RedirectStandardOutput = true, + RedirectStandardError = true + } + }; + + await ResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); + + process.Start(); + + var memoryStream = new MemoryStream(); + +#pragma warning disable 4014 + // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback + process.StandardOutput.BaseStream.CopyToAsync(memoryStream); +#pragma warning restore 4014 + + // MUST read both stdout and stderr asynchronously or a deadlock may occurr + process.BeginErrorReadLine(); + + var ranToCompletion = process.WaitForExit(5000); + + if (!ranToCompletion) + { + try + { + _logger.Info("Killing ffmpeg process"); + + process.Kill(); + + process.WaitForExit(1000); + } + catch (Exception ex) + { + _logger.ErrorException("Error killing process", ex); + } + } + + ResourcePool.Release(); + + var exitCode = ranToCompletion ? process.ExitCode : -1; + + process.Dispose(); + + if (exitCode == -1 || memoryStream.Length == 0) + { + memoryStream.Dispose(); + + var msg = string.Format("ffmpeg image encoding failed for {0}", options.InputPath); + + _logger.Error(msg); + + throw new ApplicationException(msg); + } + + memoryStream.Position = 0; + return memoryStream; + } + + private string GetArguments(ImageEncodingOptions options) + { + var vfScale = GetFilterGraph(options); + var outputFormat = GetOutputFormat(options); + + return string.Format("-i file:\"{0}\" {1} -f {2}", + options.InputPath, + vfScale, + outputFormat); + } + + private string GetFilterGraph(ImageEncodingOptions options) + { + if (!options.Width.HasValue && + !options.Height.HasValue && + !options.MaxHeight.HasValue && + !options.MaxWidth.HasValue) + { + return string.Empty; + } + + var widthScale = "-1"; + var heightScale = "-1"; + + if (options.MaxWidth.HasValue) + { + widthScale = "min(iw," + options.MaxWidth.Value.ToString(_usCulture) + ")"; + } + else if (options.Width.HasValue) + { + widthScale = options.Width.Value.ToString(_usCulture); + } + + if (options.MaxHeight.HasValue) + { + heightScale = "min(ih," + options.MaxHeight.Value.ToString(_usCulture) + ")"; + } + else if (options.Height.HasValue) + { + heightScale = options.Height.Value.ToString(_usCulture); + } + + var scaleMethod = "lanczos"; + + return string.Format("-vf scale=\"{0}:{1}\" -sws_flags {2}", + widthScale, + heightScale, + scaleMethod); + } + + private string GetOutputFormat(ImageEncodingOptions options) + { + return options.Format; + } + + private void ValidateInput(ImageEncodingOptions options) + { + + } + } +} diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 7cabf23c4..55035a4ca 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -948,14 +948,9 @@ namespace MediaBrowser.MediaEncoding.Encoder return GetFileInputArgument(playableStreamFiles[0]); } - /// - /// Gets the bluray input argument. - /// - /// The bluray root. - /// System.String. - private string GetBlurayInputArgument(string blurayRoot) + public Task EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken) { - return string.Format("bluray:\"{0}\"", blurayRoot); + return new ImageEncoder(FFMpegPath, _logger).EncodeImage(options, cancellationToken); } /// diff --git a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj index d92522bf0..fb1041f89 100644 --- a/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj +++ b/MediaBrowser.MediaEncoding/MediaBrowser.MediaEncoding.csproj @@ -48,6 +48,7 @@ + -- cgit v1.2.3 From 87c8c429e7d29c94e3722e69d4d31f505c48cfb0 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 27 Mar 2014 23:32:43 -0400 Subject: added image encoder methods --- .../MediaEncoding/ImageEncodingOptions.cs | 2 + MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs | 65 +++++++++++----- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 41 +--------- .../Drawing/ImageProcessor.cs | 87 ++++++++++++++-------- MediaBrowser.ServerApplication/ApplicationHost.cs | 14 ++-- MediaBrowser.sln | 3 + 6 files changed, 117 insertions(+), 95 deletions(-) diff --git a/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs b/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs index c76977f29..a8d1e5a0f 100644 --- a/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs +++ b/MediaBrowser.Controller/MediaEncoding/ImageEncodingOptions.cs @@ -13,6 +13,8 @@ namespace MediaBrowser.Controller.MediaEncoding public int? MaxHeight { get; set; } + public int? Quality { get; set; } + public string Format { get; set; } } } diff --git a/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs index 5e4221b0f..d259c631d 100644 --- a/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Common.IO; +using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Logging; using System; using System.Diagnostics; @@ -13,20 +14,39 @@ namespace MediaBrowser.MediaEncoding.Encoder { private readonly string _ffmpegPath; private readonly ILogger _logger; + private readonly IFileSystem _fileSystem; + private readonly CultureInfo _usCulture = new CultureInfo("en-US"); - private static readonly SemaphoreSlim ResourcePool = new SemaphoreSlim(5, 5); + private static readonly SemaphoreSlim ResourcePool = new SemaphoreSlim(10, 10); - public ImageEncoder(string ffmpegPath, ILogger logger) + public ImageEncoder(string ffmpegPath, ILogger logger, IFileSystem fileSystem) { _ffmpegPath = ffmpegPath; _logger = logger; + _fileSystem = fileSystem; } public async Task EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken) { ValidateInput(options); + await ResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); + + try + { + return await EncodeImageInternal(options, cancellationToken).ConfigureAwait(false); + } + finally + { + ResourcePool.Release(); + } + } + + private async Task EncodeImageInternal(ImageEncodingOptions options, CancellationToken cancellationToken) + { + ValidateInput(options); + var process = new Process { StartInfo = new ProcessStartInfo @@ -38,11 +58,12 @@ namespace MediaBrowser.MediaEncoding.Encoder WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false, RedirectStandardOutput = true, - RedirectStandardError = true + RedirectStandardError = true, + WorkingDirectory = Path.GetDirectoryName(options.InputPath) } }; - await ResourcePool.WaitAsync(cancellationToken).ConfigureAwait(false); + _logger.Debug("ffmpeg " + process.StartInfo.Arguments); process.Start(); @@ -74,8 +95,6 @@ namespace MediaBrowser.MediaEncoding.Encoder } } - ResourcePool.Release(); - var exitCode = ranToCompletion ? process.ExitCode : -1; process.Dispose(); @@ -94,16 +113,21 @@ namespace MediaBrowser.MediaEncoding.Encoder memoryStream.Position = 0; return memoryStream; } - + private string GetArguments(ImageEncodingOptions options) { var vfScale = GetFilterGraph(options); - var outputFormat = GetOutputFormat(options); + var outputFormat = GetOutputFormat(options.Format); + + var quality = (options.Quality ?? 100) * .3; + quality = 31 - quality; + var qualityValue = Convert.ToInt32(Math.Max(quality, 1)); - return string.Format("-i file:\"{0}\" {1} -f {2}", - options.InputPath, + return string.Format("-f image2 -i file:\"{3}\" -q:v {0} {1} -f image2pipe -vcodec {2} -", + qualityValue.ToString(_usCulture), vfScale, - outputFormat); + outputFormat, + Path.GetFileName(options.InputPath)); } private string GetFilterGraph(ImageEncodingOptions options) @@ -121,7 +145,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (options.MaxWidth.HasValue) { - widthScale = "min(iw," + options.MaxWidth.Value.ToString(_usCulture) + ")"; + widthScale = "min(iw\\," + options.MaxWidth.Value.ToString(_usCulture) + ")"; } else if (options.Width.HasValue) { @@ -130,7 +154,7 @@ namespace MediaBrowser.MediaEncoding.Encoder if (options.MaxHeight.HasValue) { - heightScale = "min(ih," + options.MaxHeight.Value.ToString(_usCulture) + ")"; + heightScale = "min(ih\\," + options.MaxHeight.Value.ToString(_usCulture) + ")"; } else if (options.Height.HasValue) { @@ -139,15 +163,20 @@ namespace MediaBrowser.MediaEncoding.Encoder var scaleMethod = "lanczos"; - return string.Format("-vf scale=\"{0}:{1}\" -sws_flags {2}", - widthScale, + return string.Format("-vf scale=\"{0}:{1}\" -sws_flags {2}", + widthScale, heightScale, scaleMethod); } - private string GetOutputFormat(ImageEncodingOptions options) + private string GetOutputFormat(string format) { - return options.Format; + if (string.Equals(format, "jpeg", StringComparison.OrdinalIgnoreCase) || + string.Equals(format, "jpg", StringComparison.OrdinalIgnoreCase)) + { + return "mjpeg"; + } + return format; } private void ValidateInput(ImageEncodingOptions options) diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 55035a4ca..8b41d2105 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -879,45 +879,6 @@ namespace MediaBrowser.MediaEncoding.Encoder return memoryStream; } - /// - /// Starts the and wait for process. - /// - /// The process. - /// The timeout. - /// true if XXXX, false otherwise - private bool StartAndWaitForProcess(Process process, int timeout = 10000) - { - process.Start(); - - var ranToCompletion = process.WaitForExit(timeout); - - if (!ranToCompletion) - { - try - { - _logger.Info("Killing ffmpeg process"); - - process.Kill(); - - process.WaitForExit(1000); - } - catch (Win32Exception ex) - { - _logger.ErrorException("Error killing process", ex); - } - catch (InvalidOperationException ex) - { - _logger.ErrorException("Error killing process", ex); - } - catch (NotSupportedException ex) - { - _logger.ErrorException("Error killing process", ex); - } - } - - return ranToCompletion; - } - /// /// Gets the file input argument. /// @@ -950,7 +911,7 @@ namespace MediaBrowser.MediaEncoding.Encoder public Task EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken) { - return new ImageEncoder(FFMpegPath, _logger).EncodeImage(options, cancellationToken); + return new ImageEncoder(FFMpegPath, _logger, _fileSystem).EncodeImage(options, cancellationToken); } /// diff --git a/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs b/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs index 12d3eadfd..408d8c9b1 100644 --- a/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs +++ b/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs @@ -3,6 +3,7 @@ using MediaBrowser.Common.IO; using MediaBrowser.Controller; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Drawing; using MediaBrowser.Model.Entities; @@ -52,12 +53,14 @@ namespace MediaBrowser.Server.Implementations.Drawing private readonly IFileSystem _fileSystem; private readonly IJsonSerializer _jsonSerializer; private readonly IServerApplicationPaths _appPaths; + private readonly IMediaEncoder _mediaEncoder; - public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer) + public ImageProcessor(ILogger logger, IServerApplicationPaths appPaths, IFileSystem fileSystem, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder) { _logger = logger; _fileSystem = fileSystem; _jsonSerializer = jsonSerializer; + _mediaEncoder = mediaEncoder; _appPaths = appPaths; _saveImageSizeTimer = new Timer(SaveImageSizeCallback, null, Timeout.Infinite, Timeout.Infinite); @@ -66,7 +69,7 @@ namespace MediaBrowser.Server.Implementations.Drawing try { - sizeDictionary = jsonSerializer.DeserializeFromFile>(ImageSizeFile) ?? + sizeDictionary = jsonSerializer.DeserializeFromFile>(ImageSizeFile) ?? new Dictionary(); } catch (FileNotFoundException) @@ -213,6 +216,39 @@ namespace MediaBrowser.Server.Implementations.Drawing try { + var hasPostProcessing = !string.IsNullOrEmpty(options.BackgroundColor) || options.UnplayedCount.HasValue || options.AddPlayedIndicator || options.PercentPlayed.HasValue; + + if (!hasPostProcessing) + { + using (var outputStream = await _mediaEncoder.EncodeImage(new ImageEncodingOptions + { + InputPath = originalImagePath, + MaxHeight = options.MaxHeight, + MaxWidth = options.MaxWidth, + Height = options.Height, + Width = options.Width, + Quality = options.Quality, + Format = options.OutputFormat == ImageOutputFormat.Original ? Path.GetExtension(originalImagePath).TrimStart('.') : options.OutputFormat.ToString().ToLower() + + }, CancellationToken.None).ConfigureAwait(false)) + { + using (var outputMemoryStream = new MemoryStream()) + { + // Save to the memory stream + await outputStream.CopyToAsync(outputMemoryStream).ConfigureAwait(false); + + var bytes = outputMemoryStream.ToArray(); + + await toStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); + + // kick off a task to cache the result + await CacheResizedImage(cacheFilePath, bytes).ConfigureAwait(false); + } + + return; + } + } + using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true)) { // Copy to memory stream to avoid Image locking file @@ -241,8 +277,8 @@ namespace MediaBrowser.Server.Implementations.Drawing thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality; thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; thumbnailGraph.PixelOffsetMode = PixelOffsetMode.HighQuality; - thumbnailGraph.CompositingMode = string.IsNullOrEmpty(options.BackgroundColor) && !options.UnplayedCount.HasValue && !options.AddPlayedIndicator && !options.PercentPlayed.HasValue ? - CompositingMode.SourceCopy : + thumbnailGraph.CompositingMode = !hasPostProcessing ? + CompositingMode.SourceCopy : CompositingMode.SourceOver; SetBackgroundColor(thumbnailGraph, options); @@ -263,7 +299,7 @@ namespace MediaBrowser.Server.Implementations.Drawing await toStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); // kick off a task to cache the result - CacheResizedImage(cacheFilePath, bytes, semaphore); + await CacheResizedImage(cacheFilePath, bytes).ConfigureAwait(false); } } } @@ -272,11 +308,9 @@ namespace MediaBrowser.Server.Implementations.Drawing } } } - catch + finally { semaphore.Release(); - - throw; } } @@ -285,33 +319,26 @@ namespace MediaBrowser.Server.Implementations.Drawing /// /// The cache file path. /// The bytes. - /// The semaphore. - private void CacheResizedImage(string cacheFilePath, byte[] bytes, SemaphoreSlim semaphore) + /// Task. + private async Task CacheResizedImage(string cacheFilePath, byte[] bytes) { - Task.Run(async () => + try { - try - { - var parentPath = Path.GetDirectoryName(cacheFilePath); + var parentPath = Path.GetDirectoryName(cacheFilePath); - Directory.CreateDirectory(parentPath); + Directory.CreateDirectory(parentPath); - // Save to the cache location - using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true)) - { - // Save to the filestream - await cacheFileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); - } - } - catch (Exception ex) - { - _logger.ErrorException("Error writing to image cache file {0}", ex, cacheFilePath); - } - finally + // Save to the cache location + using (var cacheFileStream = _fileSystem.GetFileStream(cacheFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true)) { - semaphore.Release(); + // Save to the filestream + await cacheFileStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); } - }); + } + catch (Exception ex) + { + _logger.ErrorException("Error writing to image cache file {0}", ex, cacheFilePath); + } } /// @@ -519,7 +546,7 @@ namespace MediaBrowser.Server.Implementations.Drawing { filename += "iv=" + IndicatorVersion; } - + if (!string.IsNullOrEmpty(backgroundColor)) { filename += "b=" + backgroundColor; diff --git a/MediaBrowser.ServerApplication/ApplicationHost.cs b/MediaBrowser.ServerApplication/ApplicationHost.cs index 6083158bc..b7e9017d6 100644 --- a/MediaBrowser.ServerApplication/ApplicationHost.cs +++ b/MediaBrowser.ServerApplication/ApplicationHost.cs @@ -473,7 +473,13 @@ namespace MediaBrowser.ServerApplication LocalizationManager = new LocalizationManager(ServerConfigurationManager, FileSystemManager); RegisterSingleInstance(LocalizationManager); - ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer); + var innerProgress = new ActionableProgress(); + innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15)); + + await RegisterMediaEncoder(innerProgress).ConfigureAwait(false); + progress.Report(90); + + ImageProcessor = new ImageProcessor(LogManager.GetLogger("ImageProcessor"), ServerConfigurationManager.ApplicationPaths, FileSystemManager, JsonSerializer, MediaEncoder); RegisterSingleInstance(ImageProcessor); DtoService = new DtoService(Logger, LibraryManager, UserManager, UserDataManager, ItemRepository, ImageProcessor, ServerConfigurationManager, FileSystemManager, ProviderManager); @@ -487,12 +493,6 @@ namespace MediaBrowser.ServerApplication progress.Report(15); - var innerProgress = new ActionableProgress(); - innerProgress.RegisterAction(p => progress.Report((.75 * p) + 15)); - - await RegisterMediaEncoder(innerProgress).ConfigureAwait(false); - progress.Report(90); - EncodingManager = new EncodingManager(ServerConfigurationManager, FileSystemManager, Logger, ItemRepository, MediaEncoder); RegisterSingleInstance(EncodingManager); diff --git a/MediaBrowser.sln b/MediaBrowser.sln index c2f9dff59..7dc06fb0c 100644 --- a/MediaBrowser.sln +++ b/MediaBrowser.sln @@ -267,4 +267,7 @@ Global GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(Performance) = preSolution + HasPerformanceSessions = true + EndGlobalSection EndGlobal -- cgit v1.2.3 From b95f8f5f5cd59d7c2e50e4eee018eccc7fd05216 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 28 Mar 2014 00:24:11 -0400 Subject: correct dlna param positions --- MediaBrowser.Api/Playback/BaseStreamingService.cs | 17 ++++-- MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs | 66 +++++++++++++++++++--- MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 2 +- MediaBrowser.Model/Drawing/ImageOutputFormat.cs | 3 +- .../Music/LastfmArtistProvider.cs | 24 -------- .../Drawing/ImageProcessor.cs | 60 ++++++++++---------- 6 files changed, 101 insertions(+), 71 deletions(-) diff --git a/MediaBrowser.Api/Playback/BaseStreamingService.cs b/MediaBrowser.Api/Playback/BaseStreamingService.cs index b510a640e..519ff7947 100644 --- a/MediaBrowser.Api/Playback/BaseStreamingService.cs +++ b/MediaBrowser.Api/Playback/BaseStreamingService.cs @@ -967,8 +967,6 @@ namespace MediaBrowser.Api.Playback private async void StreamToStandardInput(Process process, StreamState state) { - state.StandardInputCancellationTokenSource = new CancellationTokenSource(); - try { await StreamToStandardInputInternal(process, state).ConfigureAwait(false); @@ -1263,31 +1261,38 @@ namespace MediaBrowser.Api.Playback { if (videoRequest != null) { - videoRequest.MaxWidth = int.Parse(val, UsCulture); + videoRequest.MaxFramerate = double.Parse(val, UsCulture); } } else if (i == 12) { if (videoRequest != null) { - videoRequest.MaxHeight = int.Parse(val, UsCulture); + videoRequest.MaxWidth = int.Parse(val, UsCulture); } } else if (i == 13) { if (videoRequest != null) { - videoRequest.Framerate = int.Parse(val, UsCulture); + videoRequest.MaxHeight = int.Parse(val, UsCulture); } } else if (i == 14) { if (videoRequest != null) { - request.StartTimeTicks = long.Parse(val, UsCulture); + videoRequest.Framerate = int.Parse(val, UsCulture); } } else if (i == 15) + { + if (videoRequest != null) + { + request.StartTimeTicks = long.Parse(val, UsCulture); + } + } + else if (i == 16) { if (videoRequest != null) { diff --git a/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs index d259c631d..e0ca86c41 100644 --- a/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/ImageEncoder.cs @@ -1,10 +1,13 @@ -using MediaBrowser.Common.IO; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.IO; using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Logging; using System; using System.Diagnostics; using System.Globalization; using System.IO; +using System.Linq; +using System.Text; using System.Threading; using System.Threading.Tasks; @@ -15,16 +18,18 @@ namespace MediaBrowser.MediaEncoding.Encoder private readonly string _ffmpegPath; private readonly ILogger _logger; private readonly IFileSystem _fileSystem; + private readonly IApplicationPaths _appPaths; private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private static readonly SemaphoreSlim ResourcePool = new SemaphoreSlim(10, 10); - public ImageEncoder(string ffmpegPath, ILogger logger, IFileSystem fileSystem) + public ImageEncoder(string ffmpegPath, ILogger logger, IFileSystem fileSystem, IApplicationPaths appPaths) { _ffmpegPath = ffmpegPath; _logger = logger; _fileSystem = fileSystem; + _appPaths = appPaths; } public async Task EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken) @@ -47,6 +52,15 @@ namespace MediaBrowser.MediaEncoding.Encoder { ValidateInput(options); + var inputPath = options.InputPath; + var filename = Path.GetFileName(inputPath); + + if (HasDiacritics(filename)) + { + inputPath = GetTempFile(inputPath); + filename = Path.GetFileName(inputPath); + } + var process = new Process { StartInfo = new ProcessStartInfo @@ -54,12 +68,12 @@ namespace MediaBrowser.MediaEncoding.Encoder CreateNoWindow = true, UseShellExecute = false, FileName = _ffmpegPath, - Arguments = GetArguments(options), + Arguments = GetArguments(options, filename), WindowStyle = ProcessWindowStyle.Hidden, ErrorDialog = false, RedirectStandardOutput = true, RedirectStandardError = true, - WorkingDirectory = Path.GetDirectoryName(options.InputPath) + WorkingDirectory = Path.GetDirectoryName(inputPath) } }; @@ -113,8 +127,19 @@ namespace MediaBrowser.MediaEncoding.Encoder memoryStream.Position = 0; return memoryStream; } + + private string GetTempFile(string path) + { + var extension = Path.GetExtension(path) ?? string.Empty; + + var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid().ToString("N") + extension); + + File.Copy(path, tempPath); + + return tempPath; + } - private string GetArguments(ImageEncodingOptions options) + private string GetArguments(ImageEncodingOptions options, string inputFilename) { var vfScale = GetFilterGraph(options); var outputFormat = GetOutputFormat(options.Format); @@ -127,7 +152,7 @@ namespace MediaBrowser.MediaEncoding.Encoder qualityValue.ToString(_usCulture), vfScale, outputFormat, - Path.GetFileName(options.InputPath)); + inputFilename); } private string GetFilterGraph(ImageEncodingOptions options) @@ -163,10 +188,9 @@ namespace MediaBrowser.MediaEncoding.Encoder var scaleMethod = "lanczos"; - return string.Format("-vf scale=\"{0}:{1}\" -sws_flags {2}", + return string.Format("-vf scale=\"{0}:{1}\"", widthScale, - heightScale, - scaleMethod); + heightScale); } private string GetOutputFormat(string format) @@ -183,5 +207,29 @@ namespace MediaBrowser.MediaEncoding.Encoder { } + + /// + /// Determines whether the specified text has diacritics. + /// + /// The text. + /// true if the specified text has diacritics; otherwise, false. + private bool HasDiacritics(string text) + { + return !String.Equals(text, RemoveDiacritics(text), StringComparison.Ordinal); + } + + /// + /// Removes the diacritics. + /// + /// The text. + /// System.String. + private string RemoveDiacritics(string text) + { + return String.Concat( + text.Normalize(NormalizationForm.FormD) + .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) != + UnicodeCategory.NonSpacingMark) + ).Normalize(NormalizationForm.FormC); + } } } diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs index 8b41d2105..fac54ecff 100644 --- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs +++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs @@ -911,7 +911,7 @@ namespace MediaBrowser.MediaEncoding.Encoder public Task EncodeImage(ImageEncodingOptions options, CancellationToken cancellationToken) { - return new ImageEncoder(FFMpegPath, _logger, _fileSystem).EncodeImage(options, cancellationToken); + return new ImageEncoder(FFMpegPath, _logger, _fileSystem, _appPaths).EncodeImage(options, cancellationToken); } /// diff --git a/MediaBrowser.Model/Drawing/ImageOutputFormat.cs b/MediaBrowser.Model/Drawing/ImageOutputFormat.cs index 6cbe75a7a..824970073 100644 --- a/MediaBrowser.Model/Drawing/ImageOutputFormat.cs +++ b/MediaBrowser.Model/Drawing/ImageOutputFormat.cs @@ -25,6 +25,7 @@ namespace MediaBrowser.Model.Drawing /// /// The PNG /// - Png + Png, + Webp } } diff --git a/MediaBrowser.Providers/Music/LastfmArtistProvider.cs b/MediaBrowser.Providers/Music/LastfmArtistProvider.cs index a50e5f9d5..95169aef0 100644 --- a/MediaBrowser.Providers/Music/LastfmArtistProvider.cs +++ b/MediaBrowser.Providers/Music/LastfmArtistProvider.cs @@ -130,30 +130,6 @@ namespace MediaBrowser.Providers.Music } } - /// - /// Determines whether the specified text has diacritics. - /// - /// The text. - /// true if the specified text has diacritics; otherwise, false. - private bool HasDiacritics(string text) - { - return !String.Equals(text, RemoveDiacritics(text), StringComparison.Ordinal); - } - - /// - /// Removes the diacritics. - /// - /// The text. - /// System.String. - private string RemoveDiacritics(string text) - { - return String.Concat( - text.Normalize(NormalizationForm.FormD) - .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) != - UnicodeCategory.NonSpacingMark) - ).Normalize(NormalizationForm.FormC); - } - /// /// Encodes an URL. /// diff --git a/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs b/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs index 408d8c9b1..c6c1ec050 100644 --- a/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs +++ b/MediaBrowser.Server.Implementations/Drawing/ImageProcessor.cs @@ -218,36 +218,36 @@ namespace MediaBrowser.Server.Implementations.Drawing { var hasPostProcessing = !string.IsNullOrEmpty(options.BackgroundColor) || options.UnplayedCount.HasValue || options.AddPlayedIndicator || options.PercentPlayed.HasValue; - if (!hasPostProcessing) - { - using (var outputStream = await _mediaEncoder.EncodeImage(new ImageEncodingOptions - { - InputPath = originalImagePath, - MaxHeight = options.MaxHeight, - MaxWidth = options.MaxWidth, - Height = options.Height, - Width = options.Width, - Quality = options.Quality, - Format = options.OutputFormat == ImageOutputFormat.Original ? Path.GetExtension(originalImagePath).TrimStart('.') : options.OutputFormat.ToString().ToLower() - - }, CancellationToken.None).ConfigureAwait(false)) - { - using (var outputMemoryStream = new MemoryStream()) - { - // Save to the memory stream - await outputStream.CopyToAsync(outputMemoryStream).ConfigureAwait(false); - - var bytes = outputMemoryStream.ToArray(); - - await toStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); - - // kick off a task to cache the result - await CacheResizedImage(cacheFilePath, bytes).ConfigureAwait(false); - } - - return; - } - } + //if (!hasPostProcessing) + //{ + // using (var outputStream = await _mediaEncoder.EncodeImage(new ImageEncodingOptions + // { + // InputPath = originalImagePath, + // MaxHeight = options.MaxHeight, + // MaxWidth = options.MaxWidth, + // Height = options.Height, + // Width = options.Width, + // Quality = options.Quality, + // Format = options.OutputFormat == ImageOutputFormat.Original ? Path.GetExtension(originalImagePath).TrimStart('.') : options.OutputFormat.ToString().ToLower() + + // }, CancellationToken.None).ConfigureAwait(false)) + // { + // using (var outputMemoryStream = new MemoryStream()) + // { + // // Save to the memory stream + // await outputStream.CopyToAsync(outputMemoryStream).ConfigureAwait(false); + + // var bytes = outputMemoryStream.ToArray(); + + // await toStream.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); + + // // kick off a task to cache the result + // await CacheResizedImage(cacheFilePath, bytes).ConfigureAwait(false); + // } + + // return; + // } + //} using (var fileStream = _fileSystem.GetFileStream(originalImagePath, FileMode.Open, FileAccess.Read, FileShare.Read, true)) { -- cgit v1.2.3 From 1aa7eb4c6276ac80b3a77f66afb244083bdb77a4 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 28 Mar 2014 22:28:02 -0400 Subject: implement direct play profile edit --- MediaBrowser.Api/LiveTv/LiveTvService.cs | 6 +++++- MediaBrowser.Model/LiveTv/ChannelQuery.cs | 6 ++++++ MediaBrowser.Server.Implementations/Dto/DtoService.cs | 4 ++-- MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs | 8 ++++++++ 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/MediaBrowser.Api/LiveTv/LiveTvService.cs b/MediaBrowser.Api/LiveTv/LiveTvService.cs index 96fe01ab3..abeaba910 100644 --- a/MediaBrowser.Api/LiveTv/LiveTvService.cs +++ b/MediaBrowser.Api/LiveTv/LiveTvService.cs @@ -39,6 +39,9 @@ namespace MediaBrowser.Api.LiveTv /// The limit. [ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")] public int? Limit { get; set; } + + [ApiMember(Name = "IsFavorite", Description = "Filter by channels that are favorites, or not.", IsRequired = false, DataType = "bool", ParameterType = "query", Verb = "GET")] + public bool? IsFavorite { get; set; } } [Route("/LiveTv/Channels/{Id}", "GET", Summary = "Gets a live tv channel")] @@ -290,7 +293,8 @@ namespace MediaBrowser.Api.LiveTv ChannelType = request.Type, UserId = request.UserId, StartIndex = request.StartIndex, - Limit = request.Limit + Limit = request.Limit, + IsFavorite = request.IsFavorite }, CancellationToken.None).Result; diff --git a/MediaBrowser.Model/LiveTv/ChannelQuery.cs b/MediaBrowser.Model/LiveTv/ChannelQuery.cs index eb3b20ce3..9079ebacd 100644 --- a/MediaBrowser.Model/LiveTv/ChannelQuery.cs +++ b/MediaBrowser.Model/LiveTv/ChannelQuery.cs @@ -12,6 +12,12 @@ namespace MediaBrowser.Model.LiveTv /// The type of the channel. public ChannelType? ChannelType { get; set; } + /// + /// Gets or sets a value indicating whether this instance is favorite. + /// + /// null if [is favorite] contains no value, true if [is favorite]; otherwise, false. + public bool? IsFavorite { get; set; } + /// /// Gets or sets the user identifier. /// diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index 1833b708f..2e0b3cb17 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -1297,7 +1297,7 @@ namespace MediaBrowser.Server.Implementations.Dto { var result = new List { - GetVersionInfo(item, true) + GetVersionInfo(item) }; return result; @@ -1321,7 +1321,7 @@ namespace MediaBrowser.Server.Implementations.Dto }; } - private MediaSourceInfo GetVersionInfo(Audio i, bool isPrimary) + private MediaSourceInfo GetVersionInfo(Audio i) { return new MediaSourceInfo { diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index db8786d62..b828dc0de 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -134,6 +134,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv return number; }); + + if (query.IsFavorite.HasValue) + { + var val = query.IsFavorite.Value; + + channels = channels + .Where(i => _userDataManager.GetUserData(user.Id, i.GetUserDataKey()).IsFavorite == val); + } } channels = channels.OrderBy(i => -- cgit v1.2.3 From ca9a0edd173cb16b823fa4872e364aab6c68729f Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 28 Mar 2014 22:38:22 -0400 Subject: implement profile create/edit --- MediaBrowser.Dlna/DlnaManager.cs | 60 ++++++++++++++++++++++- MediaBrowser.ServerApplication/ApplicationHost.cs | 2 +- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/MediaBrowser.Dlna/DlnaManager.cs b/MediaBrowser.Dlna/DlnaManager.cs index ec9ecb9ef..958188f37 100644 --- a/MediaBrowser.Dlna/DlnaManager.cs +++ b/MediaBrowser.Dlna/DlnaManager.cs @@ -20,13 +20,15 @@ namespace MediaBrowser.Dlna private readonly IXmlSerializer _xmlSerializer; private readonly IFileSystem _fileSystem; private readonly ILogger _logger; + private readonly IJsonSerializer _jsonSerializer; - public DlnaManager(IXmlSerializer xmlSerializer, IFileSystem fileSystem, IApplicationPaths appPaths, ILogger logger) + public DlnaManager(IXmlSerializer xmlSerializer, IFileSystem fileSystem, IApplicationPaths appPaths, ILogger logger, IJsonSerializer jsonSerializer) { _xmlSerializer = xmlSerializer; _fileSystem = fileSystem; _appPaths = appPaths; _logger = logger; + _jsonSerializer = jsonSerializer; //DumpProfiles(); } @@ -381,10 +383,66 @@ namespace MediaBrowser.Dlna public void CreateProfile(DeviceProfile profile) { + profile = ReserializeProfile(profile); + + if (string.IsNullOrWhiteSpace(profile.Name)) + { + throw new ArgumentException("Profile is missing Name"); + } + + var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml"; + var path = Path.Combine(UserProfilesPath, newFilename); + + _xmlSerializer.SerializeToFile(profile, path); } public void UpdateProfile(DeviceProfile profile) { + profile = ReserializeProfile(profile); + + if (string.IsNullOrWhiteSpace(profile.Id)) + { + throw new ArgumentException("Profile is missing Id"); + } + if (string.IsNullOrWhiteSpace(profile.Name)) + { + throw new ArgumentException("Profile is missing Name"); + } + + var current = GetProfileInfosInternal().First(i => string.Equals(i.Info.Id, profile.Id, StringComparison.OrdinalIgnoreCase)); + + if (current.Info.Type == DeviceProfileType.System) + { + throw new ArgumentException("System profiles are readonly"); + } + + var newFilename = _fileSystem.GetValidFilename(profile.Name) + ".xml"; + var path = Path.Combine(UserProfilesPath, newFilename); + + if (!string.Equals(path, current.Path, StringComparison.Ordinal)) + { + File.Delete(current.Path); + } + + _xmlSerializer.SerializeToFile(profile, path); + } + + /// + /// Recreates the object using serialization, to ensure it's not a subclass. + /// If it's a subclass it may not serlialize properly to xml (different root element tag name) + /// + /// + /// + private DeviceProfile ReserializeProfile(DeviceProfile profile) + { + if (profile.GetType() == typeof(DeviceProfile)) + { + return profile; + } + + var json = _jsonSerializer.SerializeToString(profile); + + return _jsonSerializer.DeserializeFromString(json); } class InternalProfileInfo diff --git a/MediaBrowser.ServerApplication/ApplicationHost.cs b/MediaBrowser.ServerApplication/ApplicationHost.cs index b7e9017d6..d9d5e007e 100644 --- a/MediaBrowser.ServerApplication/ApplicationHost.cs +++ b/MediaBrowser.ServerApplication/ApplicationHost.cs @@ -503,7 +503,7 @@ namespace MediaBrowser.ServerApplication var appThemeManager = new AppThemeManager(ApplicationPaths, FileSystemManager, JsonSerializer, Logger); RegisterSingleInstance(appThemeManager); - var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("DLNA")); + var dlnaManager = new DlnaManager(XmlSerializer, FileSystemManager, ApplicationPaths, LogManager.GetLogger("DLNA"), JsonSerializer); RegisterSingleInstance(dlnaManager); var collectionManager = new CollectionManager(LibraryManager, FileSystemManager, LibraryMonitor); -- cgit v1.2.3 From 0c32267717e1b7885addf132fe70adde787dbcd2 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 29 Mar 2014 11:40:32 -0400 Subject: stub out web client media controller --- MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs | 12 ++---------- MediaBrowser.WebDashboard/Api/DashboardService.cs | 8 ++++---- MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj | 3 +++ 3 files changed, 9 insertions(+), 14 deletions(-) diff --git a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs index 9279fd8d7..08add952a 100644 --- a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs +++ b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs @@ -349,13 +349,13 @@ namespace MediaBrowser.Server.Implementations.IO { try { - Logger.Debug("Watcher sees change of type " + e.ChangeType + " to " + e.FullPath); + Logger.Debug("Changed detected of type " + e.ChangeType + " to " + e.FullPath); ReportFileSystemChanged(e.FullPath); } catch (Exception ex) { - Logger.ErrorException("Exception in watcher changed. Path: {0}", ex, e.FullPath); + Logger.ErrorException("Exception in ReportFileSystemChanged. Path: {0}", ex, e.FullPath); } } @@ -397,14 +397,6 @@ namespace MediaBrowser.Server.Implementations.IO Logger.Debug("Ignoring change to {0}", path); return true; } - - // Go up another level - parent = Path.GetDirectoryName(i); - if (string.Equals(parent, path, StringComparison.OrdinalIgnoreCase)) - { - Logger.Debug("Ignoring change to {0}", path); - return true; - } } return false; diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index 99afbbdd7..f102dddaa 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -404,6 +404,10 @@ namespace MediaBrowser.WebDashboard.Api //"chromecast.js", "contextmenu.js", + "mediacontroller.js", + "mediaplayer.js", + "mediaplayer-video.js", + "ratingdialog.js", "aboutpage.js", "allusersettings.js", @@ -461,10 +465,6 @@ namespace MediaBrowser.WebDashboard.Api "loginpage.js", "logpage.js", "medialibrarypage.js", - "mediaplayer.js", - - "mediaplayer-video.js", - "metadataconfigurationpage.js", "metadataimagespage.js", "moviegenres.js", diff --git a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj index 6a8cc49b1..6c6487cc2 100644 --- a/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj +++ b/MediaBrowser.WebDashboard/MediaBrowser.WebDashboard.csproj @@ -587,6 +587,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest -- cgit v1.2.3 From 9f5101dee2641f99a7a4945475ebb0aa49fb1913 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 29 Mar 2014 14:20:42 -0400 Subject: add shuffle and instant mix commands --- MediaBrowser.Model/Session/PlayRequest.cs | 14 +++++-- .../Session/SessionManager.cs | 45 ++++++++++++++++++---- 2 files changed, 49 insertions(+), 10 deletions(-) diff --git a/MediaBrowser.Model/Session/PlayRequest.cs b/MediaBrowser.Model/Session/PlayRequest.cs index 949274a5d..74d7a70a3 100644 --- a/MediaBrowser.Model/Session/PlayRequest.cs +++ b/MediaBrowser.Model/Session/PlayRequest.cs @@ -39,14 +39,22 @@ namespace MediaBrowser.Model.Session /// /// The play now /// - PlayNow, + PlayNow = 0, /// /// The play next /// - PlayNext, + PlayNext = 1, /// /// The play last /// - PlayLast + PlayLast = 2, + /// + /// The play instant mix + /// + PlayInstantMix = 3, + /// + /// The play shuffle + /// + PlayShuffle = 4 } } \ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/Session/SessionManager.cs b/MediaBrowser.Server.Implementations/Session/SessionManager.cs index 9d405a175..4f748a6a8 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionManager.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionManager.cs @@ -3,6 +3,8 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Persistence; using MediaBrowser.Controller.Session; @@ -564,7 +566,7 @@ namespace MediaBrowser.Server.Implementations.Session return playedToCompletion; } - + /// /// Updates playstate position for an item but does not save /// @@ -666,7 +668,7 @@ namespace MediaBrowser.Server.Implementations.Session var controllingSession = GetSession(controllingSessionId); AssertCanControl(session, controllingSession); - + return session.SessionController.SendSystemCommand(command, cancellationToken); } @@ -676,7 +678,7 @@ namespace MediaBrowser.Server.Implementations.Session var controllingSession = GetSession(controllingSessionId); AssertCanControl(session, controllingSession); - + return session.SessionController.SendMessageCommand(command, cancellationToken); } @@ -684,14 +686,22 @@ namespace MediaBrowser.Server.Implementations.Session { var session = GetSessionForRemoteControl(sessionId); - var items = command.ItemIds.Select(i => _libraryManager.GetItemById(new Guid(i))) + var user = session.UserId.HasValue ? _userManager.GetUserById(session.UserId.Value) : null; + + var items = command.ItemIds.SelectMany(i => TranslateItemForPlayback(i, user)) .Where(i => i.LocationType != LocationType.Virtual) .ToList(); - if (session.UserId.HasValue) + if (command.PlayCommand == PlayCommand.PlayShuffle) { - var user = _userManager.GetUserById(session.UserId.Value); + items = items.OrderBy(i => Guid.NewGuid()).ToList(); + command.PlayCommand = PlayCommand.PlayNow; + } + + command.ItemIds = items.Select(i => i.Id.ToString("N")).ToArray(); + if (user != null) + { if (items.Any(i => i.GetPlayAccess(user) != PlayAccess.Full)) { throw new ArgumentException(string.Format("{0} is not allowed to play media.", user.Name)); @@ -723,13 +733,34 @@ namespace MediaBrowser.Server.Implementations.Session return session.SessionController.SendPlayCommand(command, cancellationToken); } + private IEnumerable TranslateItemForPlayback(string id, User user) + { + var item = _libraryManager.GetItemById(new Guid(id)); + + if (item.IsFolder) + { + var folder = (Folder)item; + + var items = user == null ? folder.RecursiveChildren: + folder.GetRecursiveChildren(user); + + items = items.Where(i => !i.IsFolder); + + items = items.OrderBy(i => i.SortName); + + return items; + } + + return new[] { item }; + } + public Task SendBrowseCommand(Guid controllingSessionId, Guid sessionId, BrowseRequest command, CancellationToken cancellationToken) { var session = GetSessionForRemoteControl(sessionId); var controllingSession = GetSession(controllingSessionId); AssertCanControl(session, controllingSession); - + return session.SessionController.SendBrowseCommand(command, cancellationToken); } -- cgit v1.2.3 From c34521538a1303f1ab918a052a41c3f1e2a1ff11 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 29 Mar 2014 15:02:43 -0400 Subject: support folder playback --- MediaBrowser.Server.Implementations/Roku/RokuSessionController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.Server.Implementations/Roku/RokuSessionController.cs b/MediaBrowser.Server.Implementations/Roku/RokuSessionController.cs index d806db1e0..7c8d71b4f 100644 --- a/MediaBrowser.Server.Implementations/Roku/RokuSessionController.cs +++ b/MediaBrowser.Server.Implementations/Roku/RokuSessionController.cs @@ -30,7 +30,7 @@ namespace MediaBrowser.Server.Implementations.Roku public bool SupportsMediaRemoteControl { - get { return true; } + get { return false; } } public bool IsSessionActive -- cgit v1.2.3 From a90d892ecab78a8f11fa7a4efda65ee70eceafe1 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sat, 29 Mar 2014 15:23:47 -0400 Subject: re-enable chromecast, although it's not doing anything yet --- MediaBrowser.WebDashboard/Api/DashboardService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MediaBrowser.WebDashboard/Api/DashboardService.cs b/MediaBrowser.WebDashboard/Api/DashboardService.cs index f102dddaa..369fb2a07 100644 --- a/MediaBrowser.WebDashboard/Api/DashboardService.cs +++ b/MediaBrowser.WebDashboard/Api/DashboardService.cs @@ -401,7 +401,7 @@ namespace MediaBrowser.WebDashboard.Api "librarylist.js", "editorsidebar.js", "librarymenu.js", - //"chromecast.js", + "chromecast.js", "contextmenu.js", "mediacontroller.js", -- cgit v1.2.3 From c91109a69f8fab27a9b43d05fc43305bbeee364d Mon Sep 17 00:00:00 2001 From: Thomas Gillen Date: Sun, 30 Mar 2014 03:44:03 +0100 Subject: Support series offset in missing episode provider --- .../TV/MissingEpisodeProvider.cs | 110 ++++++++++++++------- MediaBrowser.Providers/TV/SeriesPostScanTask.cs | 59 +++++++++-- MediaBrowser.Providers/TV/TvdbSeriesProvider.cs | 16 ++- 3 files changed, 141 insertions(+), 44 deletions(-) diff --git a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs index ff8f6a2e6..c33b9d549 100644 --- a/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs +++ b/MediaBrowser.Providers/TV/MissingEpisodeProvider.cs @@ -174,11 +174,21 @@ namespace MediaBrowser.Providers.TV /// Task. private async Task AddMissingEpisodes(List series, string seriesDataPath, IEnumerable> episodeLookup, CancellationToken cancellationToken) { - var existingEpisodes = series.SelectMany(s => s.RecursiveChildren.OfType()).ToList(); + var existingEpisodes = (from s in series + let seasonOffset = TvdbSeriesProvider.GetSeriesOffset(s.ProviderIds) ?? ((s.AnimeSeriesIndex ?? 1) - 1) + from c in s.RecursiveChildren.OfType() + select new Tuple((c.ParentIndexNumber ?? 0) + seasonOffset, c)) + .ToList(); + + var lookup = episodeLookup as IList> ?? episodeLookup.ToList(); + + var seasonCounts = (from e in lookup + group e by e.Item1 into g select g) + .ToDictionary(g => g.Key, g => g.Count()); var hasChanges = false; - foreach (var tuple in episodeLookup) + foreach (var tuple in lookup) { if (tuple.Item1 <= 0) { @@ -192,7 +202,7 @@ namespace MediaBrowser.Providers.TV continue; } - var existingEpisode = GetExistingEpisode(existingEpisodes, tuple); + var existingEpisode = GetExistingEpisode(existingEpisodes, seasonCounts, tuple); if (existingEpisode != null) { @@ -208,13 +218,13 @@ namespace MediaBrowser.Providers.TV var now = DateTime.UtcNow; var targetSeries = DetermineAppropriateSeries(series, tuple.Item1); + var seasonOffset = TvdbSeriesProvider.GetSeriesOffset(targetSeries.ProviderIds) ?? ((targetSeries.AnimeSeriesIndex ?? 1) - 1); if (airDate.Value < now) { // tvdb has a lot of nearly blank episodes _logger.Info("Creating virtual missing episode {0} {1}x{2}", targetSeries.Name, tuple.Item1, tuple.Item2); - - await AddEpisode(targetSeries, tuple.Item1, tuple.Item2, cancellationToken).ConfigureAwait(false); + await AddEpisode(targetSeries, tuple.Item1 - seasonOffset, tuple.Item2, cancellationToken).ConfigureAwait(false); hasChanges = true; } @@ -222,8 +232,7 @@ namespace MediaBrowser.Providers.TV { // tvdb has a lot of nearly blank episodes _logger.Info("Creating virtual unaired episode {0} {1}x{2}", targetSeries.Name, tuple.Item1, tuple.Item2); - - await AddEpisode(targetSeries, tuple.Item1, tuple.Item2, cancellationToken).ConfigureAwait(false); + await AddEpisode(targetSeries, tuple.Item1 - seasonOffset, tuple.Item2, cancellationToken).ConfigureAwait(false); hasChanges = true; } @@ -232,40 +241,48 @@ namespace MediaBrowser.Providers.TV return hasChanges; } - private Series DetermineAppropriateSeries(List series, int seasonNumber) + private Series DetermineAppropriateSeries(IEnumerable series, int seasonNumber) { - return series.FirstOrDefault(s => s.RecursiveChildren.OfType().Any(season => season.IndexNumber == seasonNumber)) ?? - series.FirstOrDefault(s => s.RecursiveChildren.OfType().Any(season => season.IndexNumber == 1)) ?? - series.OrderBy(s => s.RecursiveChildren.OfType().Select(season => season.IndexNumber).Min()).First(); - } + var seriesAndOffsets = series.Select(s => new { Series = s, SeasonOffset = TvdbSeriesProvider.GetSeriesOffset(s.ProviderIds) ?? ((s.AnimeSeriesIndex ?? 1) - 1) }).ToList(); + var bestMatch = seriesAndOffsets.FirstOrDefault(s => s.Series.RecursiveChildren.OfType().Any(season => (season.IndexNumber + s.SeasonOffset) == seasonNumber)) ?? + seriesAndOffsets.FirstOrDefault(s => s.Series.RecursiveChildren.OfType().Any(season => (season.IndexNumber + s.SeasonOffset) == 1)) ?? + seriesAndOffsets.OrderBy(s => s.Series.RecursiveChildren.OfType().Select(season => season.IndexNumber + s.SeasonOffset).Min()).First(); + + return bestMatch.Series; + } + /// /// Removes the virtual entry after a corresponding physical version has been added /// private async Task RemoveObsoleteOrMissingEpisodes(IEnumerable series, IEnumerable> episodeLookup, CancellationToken cancellationToken) { - var existingEpisodes = series.SelectMany(s => s.RecursiveChildren.OfType()).ToList(); + var existingEpisodes = (from s in series + let seasonOffset = TvdbSeriesProvider.GetSeriesOffset(s.ProviderIds) ?? ((s.AnimeSeriesIndex ?? 1) - 1) + from c in s.RecursiveChildren.OfType() + select new { SeasonOffset = seasonOffset, Episode = c }) + .ToList(); var physicalEpisodes = existingEpisodes - .Where(i => i.LocationType != LocationType.Virtual) + .Where(i => i.Episode.LocationType != LocationType.Virtual) .ToList(); var virtualEpisodes = existingEpisodes - .Where(i => i.LocationType == LocationType.Virtual) + .Where(i => i.Episode.LocationType == LocationType.Virtual) .ToList(); var episodesToRemove = virtualEpisodes .Where(i => { - if (i.IndexNumber.HasValue && i.ParentIndexNumber.HasValue) + if (i.Episode.IndexNumber.HasValue && i.Episode.ParentIndexNumber.HasValue) { - var seasonNumber = i.ParentIndexNumber.Value; - var episodeNumber = i.IndexNumber.Value; + var seasonNumber = i.Episode.ParentIndexNumber.Value + i.SeasonOffset; + var episodeNumber = i.Episode.IndexNumber.Value; // If there's a physical episode with the same season and episode number, delete it if (physicalEpisodes.Any(p => - p.ParentIndexNumber.HasValue && p.ParentIndexNumber.Value == seasonNumber && - p.ContainsEpisodeNumber(episodeNumber))) + p.Episode.ParentIndexNumber.HasValue && (p.Episode.ParentIndexNumber.Value + p.SeasonOffset) == seasonNumber && + p.Episode.ContainsEpisodeNumber(episodeNumber))) { return true; } @@ -285,7 +302,7 @@ namespace MediaBrowser.Providers.TV var hasChanges = false; - foreach (var episodeToRemove in episodesToRemove) + foreach (var episodeToRemove in episodesToRemove.Select(e => e.Episode)) { _logger.Info("Removing missing/unaired episode {0} {1}x{2}", episodeToRemove.Series.Name, episodeToRemove.ParentIndexNumber, episodeToRemove.IndexNumber); @@ -306,25 +323,29 @@ namespace MediaBrowser.Providers.TV /// Task{System.Boolean}. private async Task RemoveObsoleteOrMissingSeasons(IEnumerable series, IEnumerable> episodeLookup, CancellationToken cancellationToken) { - var existingSeasons = series.SelectMany(s => s.Children.OfType()).ToList(); + var existingSeasons = (from s in series + let seasonOffset = TvdbSeriesProvider.GetSeriesOffset(s.ProviderIds) ?? ((s.AnimeSeriesIndex ?? 1) - 1) + from c in s.Children.OfType() + select new { SeasonOffset = seasonOffset, Season = c }) + .ToList(); var physicalSeasons = existingSeasons - .Where(i => i.LocationType != LocationType.Virtual) + .Where(i => i.Season.LocationType != LocationType.Virtual) .ToList(); var virtualSeasons = existingSeasons - .Where(i => i.LocationType == LocationType.Virtual) + .Where(i => i.Season.LocationType == LocationType.Virtual) .ToList(); var seasonsToRemove = virtualSeasons .Where(i => { - if (i.IndexNumber.HasValue) + if (i.Season.IndexNumber.HasValue) { - var seasonNumber = i.IndexNumber.Value; + var seasonNumber = i.Season.IndexNumber.Value + i.SeasonOffset; // If there's a physical season with the same number, delete it - if (physicalSeasons.Any(p => p.IndexNumber.HasValue && p.IndexNumber.Value == seasonNumber)) + if (physicalSeasons.Any(p => p.Season.IndexNumber.HasValue && (p.Season.IndexNumber.Value + p.SeasonOffset) == seasonNumber)) { return true; } @@ -344,7 +365,7 @@ namespace MediaBrowser.Providers.TV var hasChanges = false; - foreach (var seasonToRemove in seasonsToRemove) + foreach (var seasonToRemove in seasonsToRemove.Select(s => s.Season)) { _logger.Info("Removing virtual season {0} {1}", seasonToRemove.Series.Name, seasonToRemove.IndexNumber); @@ -417,9 +438,7 @@ namespace MediaBrowser.Providers.TV await series.AddChild(season, cancellationToken).ConfigureAwait(false); - await season.RefreshMetadata(new MetadataRefreshOptions - { - }, cancellationToken).ConfigureAwait(false); + await season.RefreshMetadata(new MetadataRefreshOptions(), cancellationToken).ConfigureAwait(false); return season; } @@ -428,12 +447,37 @@ namespace MediaBrowser.Providers.TV /// Gets the existing episode. /// /// The existing episodes. + /// /// The tuple. /// Episode. - private Episode GetExistingEpisode(IEnumerable existingEpisodes, Tuple tuple) + private Episode GetExistingEpisode(IList> existingEpisodes, Dictionary seasonCounts, Tuple tuple) + { + var s = tuple.Item1; + var e = tuple.Item2; + + while (true) + { + var episode = GetExistingEpisode(existingEpisodes, s, e); + if (episode != null) + return episode; + + s--; + + if (seasonCounts.ContainsKey(s)) + e += seasonCounts[s]; + else + break; + } + + return null; + } + + private static Episode GetExistingEpisode(IEnumerable> existingEpisodes, int season, int episode) { return existingEpisodes - .FirstOrDefault(i => (i.ParentIndexNumber ?? -1) == tuple.Item1 && i.ContainsEpisodeNumber(tuple.Item2)); + .Where(i => i.Item1 == season && i.Item2.ContainsEpisodeNumber(episode)) + .Select(i => i.Item2) + .FirstOrDefault(); } /// diff --git a/MediaBrowser.Providers/TV/SeriesPostScanTask.cs b/MediaBrowser.Providers/TV/SeriesPostScanTask.cs index 8c9b8672c..d350d2fe4 100644 --- a/MediaBrowser.Providers/TV/SeriesPostScanTask.cs +++ b/MediaBrowser.Providers/TV/SeriesPostScanTask.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Controller.Configuration; +using System.Collections.Generic; +using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Providers; @@ -11,6 +12,11 @@ using System.Threading.Tasks; namespace MediaBrowser.Providers.TV { + class SeriesGroup : List, IGrouping + { + public string Key { get; set; } + } + class SeriesPostScanTask : ILibraryPostScanTask, IHasOrder { /// @@ -39,11 +45,7 @@ namespace MediaBrowser.Providers.TV .OfType() .ToList(); - var seriesGroups = from series in seriesList - let tvdbId = series.GetProviderId(MetadataProviders.Tvdb) - where !string.IsNullOrEmpty(tvdbId) - group series by tvdbId into g - select g; + var seriesGroups = FindSeriesGroups(seriesList).Where(g => !string.IsNullOrEmpty(g.Key)).ToList(); await new MissingEpisodeProvider(_logger, _config, _libraryManager).Run(seriesGroups, cancellationToken).ConfigureAwait(false); @@ -84,6 +86,51 @@ namespace MediaBrowser.Providers.TV } } + private IEnumerable> FindSeriesGroups(List seriesList) + { + var links = seriesList.ToDictionary(s => s, s => seriesList.Where(c => c != s && ShareProviderId(s, c)).ToList()); + + var visited = new HashSet(); + + foreach (var series in seriesList) + { + if (!visited.Contains(series)) + { + var group = new SeriesGroup(); + FindAllLinked(series, visited, links, group); + + group.Key = group.Select(s => s.GetProviderId(MetadataProviders.Tvdb)).FirstOrDefault(id => !string.IsNullOrEmpty(id)); + + yield return group; + } + } + } + + private void FindAllLinked(Series series, HashSet visited, IDictionary> linksMap, List results) + { + results.Add(series); + visited.Add(series); + + var links = linksMap[series]; + + foreach (var s in links) + { + if (!visited.Contains(s)) + { + FindAllLinked(s, visited, linksMap, results); + } + } + } + + private bool ShareProviderId(Series a, Series b) + { + return a.ProviderIds.Any(id => + { + string value; + return b.ProviderIds.TryGetValue(id.Key, out value) && id.Value == value; + }); + } + public int Order { get diff --git a/MediaBrowser.Providers/TV/TvdbSeriesProvider.cs b/MediaBrowser.Providers/TV/TvdbSeriesProvider.cs index a76e10111..f9ebaddf8 100644 --- a/MediaBrowser.Providers/TV/TvdbSeriesProvider.cs +++ b/MediaBrowser.Providers/TV/TvdbSeriesProvider.cs @@ -25,7 +25,8 @@ namespace MediaBrowser.Providers.TV { public class TvdbSeriesProvider : IRemoteMetadataProvider, IHasOrder { - internal const string TvdbSeriesOffset = "TvdbSeriesOffset"; + private const string TvdbSeriesOffset = "TvdbSeriesOffset"; + private const string TvdbSeriesOffsetFormat = "{0}-{1}"; internal readonly SemaphoreSlim TvDbResourcePool = new SemaphoreSlim(2, 2); internal static TvdbSeriesProvider Current { get; private set; } @@ -109,17 +110,22 @@ namespace MediaBrowser.Providers.TV return; var offset = info.AnimeSeriesIndex - index; - series.SetProviderId(TvdbSeriesOffset, offset.ToString()); + var id = string.Format(TvdbSeriesOffsetFormat, series.GetProviderId(MetadataProviders.Tvdb), offset); + series.SetProviderId(TvdbSeriesOffset, id); } internal static int? GetSeriesOffset(Dictionary seriesProviderIds) { - string offsetString; - if (!seriesProviderIds.TryGetValue(TvdbSeriesOffset, out offsetString)) + string idString; + if (!seriesProviderIds.TryGetValue(TvdbSeriesOffset, out idString)) + return null; + + var parts = idString.Split('-'); + if (parts.Length < 2) return null; int offset; - if (int.TryParse(offsetString, out offset)) + if (int.TryParse(parts[1], out offset)) return offset; return null; -- cgit v1.2.3 From f756e39b9d5b461e6bcaa4e71006038983d28213 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 30 Mar 2014 12:49:40 -0400 Subject: restored live tv playback in the web client --- MediaBrowser.Api/MediaBrowser.Api.csproj | 1 + MediaBrowser.Api/Music/InstantMixService.cs | 75 ++--- MediaBrowser.Api/Playback/BaseStreamingService.cs | 50 +--- .../Playback/ProgressiveStreamService.cs | 73 +++++ MediaBrowser.Api/Playback/StreamRequest.cs | 5 - MediaBrowser.Api/Playback/StreamState.cs | 2 - MediaBrowser.Controller/Dto/IDtoService.cs | 7 + MediaBrowser.Controller/Library/IMusicManager.cs | 38 +++ MediaBrowser.Controller/LiveTv/ILiveTvRecording.cs | 4 +- .../MediaBrowser.Controller.csproj | 4 + .../MediaEncoding/EncodingOptions.cs | 79 +++++ .../MediaEncoding/EncodingResult.cs | 13 + .../MediaEncoding/VideoEncodingOptions.cs | 26 ++ MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs | 91 ++++++ .../Encoder/EncodingUtils.cs | 233 +++++++++++++++ .../Encoder/FFMpegProcess.cs | 168 +++++++++++ .../Encoder/InternalEncodingTask.cs | 95 ++++++ .../Encoder/InternalEncodingTaskFactory.cs | 323 +++++++++++++++++++++ MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs | 64 +--- .../MediaBrowser.MediaEncoding.csproj | 5 + MediaBrowser.Model/LiveTv/ChannelInfoDto.cs | 3 + MediaBrowser.Model/LiveTv/RecordingInfoDto.cs | 11 +- .../Dto/DtoService.cs | 48 ++- .../Library/MusicManager.cs | 67 +++++ .../Library/Resolvers/Audio/AudioResolver.cs | 3 +- .../LiveTv/LiveTvDtoService.cs | 11 +- .../MediaBrowser.Server.Implementations.csproj | 1 + .../Session/SessionManager.cs | 59 +++- MediaBrowser.ServerApplication/ApplicationHost.cs | 2 + MediaBrowser.WebDashboard/ApiClient.js | 2 +- MediaBrowser.WebDashboard/packages.config | 2 +- 31 files changed, 1373 insertions(+), 192 deletions(-) create mode 100644 MediaBrowser.Api/Playback/ProgressiveStreamService.cs create mode 100644 MediaBrowser.Controller/Library/IMusicManager.cs create mode 100644 MediaBrowser.Controller/MediaEncoding/EncodingOptions.cs create mode 100644 MediaBrowser.Controller/MediaEncoding/EncodingResult.cs create mode 100644 MediaBrowser.Controller/MediaEncoding/VideoEncodingOptions.cs create mode 100644 MediaBrowser.MediaEncoding/Encoder/AudioEncoder.cs create mode 100644 MediaBrowser.MediaEncoding/Encoder/EncodingUtils.cs create mode 100644 MediaBrowser.MediaEncoding/Encoder/FFMpegProcess.cs create mode 100644 MediaBrowser.MediaEncoding/Encoder/InternalEncodingTask.cs create mode 100644 MediaBrowser.MediaEncoding/Encoder/InternalEncodingTaskFactory.cs create mode 100644 MediaBrowser.Server.Implementations/Library/MusicManager.cs diff --git a/MediaBrowser.Api/MediaBrowser.Api.csproj b/MediaBrowser.Api/MediaBrowser.Api.csproj index 18559a68d..c03eddf99 100644 --- a/MediaBrowser.Api/MediaBrowser.Api.csproj +++ b/MediaBrowser.Api/MediaBrowser.Api.csproj @@ -103,6 +103,7 @@ + diff --git a/MediaBrowser.Api/Music/InstantMixService.cs b/MediaBrowser.Api/Music/InstantMixService.cs index 9b9df3a92..c39811bb6 100644 --- a/MediaBrowser.Api/Music/InstantMixService.cs +++ b/MediaBrowser.Api/Music/InstantMixService.cs @@ -1,9 +1,9 @@ using MediaBrowser.Controller.Dto; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Querying; using ServiceStack; -using System; using System.Collections.Generic; using System.Linq; @@ -36,103 +36,74 @@ namespace MediaBrowser.Api.Music public class InstantMixService : BaseApiService { private readonly IUserManager _userManager; - private readonly ILibraryManager _libraryManager; private readonly IDtoService _dtoService; + private readonly IMusicManager _musicManager; - public InstantMixService(IUserManager userManager, ILibraryManager libraryManager, IDtoService dtoService) + public InstantMixService(IUserManager userManager, IDtoService dtoService, IMusicManager musicManager) { _userManager = userManager; - _libraryManager = libraryManager; _dtoService = dtoService; + _musicManager = musicManager; } public object Get(GetInstantMixFromSong request) { - var item = _dtoService.GetItemByDtoId(request.Id); + var item = (Audio)_dtoService.GetItemByDtoId(request.Id); - var result = GetInstantMixResult(request, item.Genres); + var user = _userManager.GetUserById(request.UserId.Value); - return ToOptimizedSerializedResultUsingCache(result); + var items = _musicManager.GetInstantMixFromSong(item, user); + + return GetResult(items, user, request); } public object Get(GetInstantMixFromAlbum request) { var album = (MusicAlbum)_dtoService.GetItemByDtoId(request.Id); - var genres = album - .RecursiveChildren - .OfType