Ejemplo n.º 1
0
        public static WebMediaInfo GetMediaInfo(MediaSource source)
        {
            // we can't use our persistent cache for TV unfortunately, but we do cache them in memory for 60 seconds
            if (source.MediaType == WebMediaType.TV)
            {
                if (tvCache.ContainsKey(source.Id) && DateTime.Now - tvCache[source.Id].Item1 > TimeSpan.FromSeconds(60))
                {
                    return tvCache[source.Id].Item2;
                }

                // save it to our memory cache for a while
                TsBuffer buf = new TsBuffer(source.Id);
                string path = buf.GetCurrentFilePath();
                Log.Debug("Using path {0} from TS buffer {1} as source for {2}", path, source.Id, source.GetDebugName());
                WebMediaInfo info = DoLoadMediaInfo(buf.GetCurrentFilePath(), true);
                tvCache[source.Id] = new Tuple<DateTime, WebMediaInfo>(DateTime.Now, info);
                return info;
            }

            // load this item from persistent disk cache, if possible
            if (persistentCache.HasForSource(source))
            {
                return persistentCache.GetForSource(source);
            }

            // some checks that only matter when we are actually going to load it from disk
            if (!source.Exists)
            {
                Log.Warn("Trying to load mediainfo for {0}, which doesn't seem to exist", source.GetDebugName());
                return null;
            }
            else if (!source.SupportsDirectAccess)
            {
                // not (yet?) supported
                Log.Warn("Loading mediainfo for non-direct access source {0} isn't supported yet", source.GetDebugName());
                return null;
            }

            // actually load it
            WebMediaInfo outInfo;
            using (NetworkShareImpersonator impersonator = new NetworkShareImpersonator(source.NeedsImpersonation))
            {
                outInfo = DoLoadMediaInfo(source.GetPath(), false);
            }
            if (outInfo != null)
            {
                persistentCache.Save(source, outInfo);
            }
            return outInfo;
        }
Ejemplo n.º 2
0
        public static WebMediaInfo GetMediaInfo(MediaSource source)
        {
            // we can't cache it for TV, unfortunately
            if (source.MediaType == WebStreamMediaType.TV)
            {
                // cache tv files for 60 seconds
                if (tvCache.ContainsKey(source.Id) && DateTime.Now - tvCache[source.Id].Item1 > TimeSpan.FromSeconds(60))
                {
                    // cache is valid, use it
                    return tvCache[source.Id].Item2;
                }

                // get media info and save it to the cache
                TsBuffer buf = new TsBuffer(source.Id);
                string path = buf.GetCurrentFilePath();
                Log.Debug("Using path {0} from TS buffer {1} as source for {2}", path, source.Id, source.GetDebugName());
                WebMediaInfo info = DoLoadMediaInfo(buf.GetCurrentFilePath(), true);
                tvCache[source.Id] = new Tuple<DateTime, WebMediaInfo>(DateTime.Now, info);
                return info;
            }

            // load this item from cache, if possible
            if (persistentCache.HasForSource(source))
            {
                return persistentCache.GetForSource(source);
            }

            // some checks that only matter when we are actually going to load it from disk
            if (!source.Exists)
            {
                Log.Warn("Trying to load mediainfo for {0}, which doesn't seem to exist", source.GetDebugName());
                throw new FileNotFoundException();
            }
            else if (!source.SupportsDirectAccess)
            {
                // not (yet?) supported
                Log.Warn("Loading mediainfo for non-direct access source {0} isn't supported yet", source.GetDebugName());
                throw new NotSupportedException();
            }

            // actually load it
            WebMediaInfo outInfo;
            using (var impersonator = source.GetImpersonator())
            {
                outInfo = DoLoadMediaInfo(source.GetPath(), false);
            }
            persistentCache.Save(source, outInfo);
            return outInfo;
        }
Ejemplo n.º 3
0
        public bool InitStream(string identifier, string clientDescription, MediaSource source, int timeout)
        {
            if (!source.Exists)
            {
                Log.Warn("Tried to start stream for non-existing file {0}", source.GetDebugName());
                return(false);
            }

            ActiveStream stream = new ActiveStream();

            stream.Identifier            = identifier;
            stream.ClientDescription     = clientDescription;
            stream.StartTime             = DateTime.Now;
            stream.Timeout               = timeout;
            stream.LastActivity          = DateTime.Now;
            stream.UseActivityForTimeout = false;
            stream.Context               = new StreamContext();
            stream.Context.Source        = source;
            stream.Context.IsTv          = source.MediaType == WebMediaType.TV;

            // Some clients such as WebMP proxy the streams before relying it to the client. We should give these clients the option to
            // forward the real IP address, so that we can show that one in the configurator too. However, to avoid abuse, we should show
            // the real IP of the client too, so make up some nice text string.
            string realIp = WCFUtil.GetHeaderValue("forwardedFor", "X-Forwarded-For");

            stream.ClientIP = realIp == null?WCFUtil.GetClientIPAddress() : String.Format("{0} (via {1})", realIp, WCFUtil.GetClientIPAddress());

            Streams[identifier] = stream;
            return(true);
        }
Ejemplo n.º 4
0
        public static WebMediaInfo GetMediaInfo(MediaSource source)
        {
            // Timeshiftings are a special case, as they can't be cached and need an additional path resolving step
            if (source.MediaType == WebMediaType.TV)
            {
                if (tvCache.ContainsKey(source.Id) && DateTime.Now - tvCache[source.Id].Item1 > TimeSpan.FromSeconds(60))
                    return tvCache[source.Id].Item2;

                TsBuffer tsBuffer = new TsBuffer(source.Id);
                Log.Debug("Using path {0} from TS buffer {1} as source for {2}", tsBuffer.GetCurrentFilePath(), source.Id, source.GetDebugName());
                WebMediaInfo info = LoadMediaInfo(tsBuffer.GetCurrentFilePath());
                tvCache[source.Id] = new Tuple<DateTime, WebMediaInfo>(DateTime.Now, info);
                return info;
            }

            using (var context = source.CreateNetworkContext())
            {
                // verify the file actually exists and is accessible over the local file system
                if (!source.Exists)
                {
                    Log.Warn("Trying to load MediaInfo for {0}, which does not exist or is inaccessible", source.GetDebugName());
                    return null;
                }
                else if (!source.SupportsDirectAccess)
                {
                    Log.Warn("Loading MediaInfo for non-direct access source {0} isn't supported yet", source.GetDebugName());
                    return null;
                }

                // if we got the file in the cache, return it if we have it and the file hasn't been changed
                var fileInfo = source.GetFileInfo();
                if (source.MediaType != WebMediaType.TV && persistentCache.HasForSource(source))
                {
                    var cachedItem = persistentCache.GetForSource(source);
                    if (cachedItem.Size == fileInfo.Size && cachedItem.CachedDate >= fileInfo.LastModifiedTime)
                        return cachedItem.Info;
                }

                var info = LoadMediaInfo(context.RewritePath(source.GetPath()));
                if (info != null)
                    persistentCache.Save(source, new CachedInfoWrapper(info, fileInfo));

                return info;
            }
        }
Ejemplo n.º 5
0
        public static Stream ExtractImage(MediaSource source, long position, int? maxWidth, int? maxHeight, string borders, string format)
        {
            if (!source.Exists)
            {
                Log.Warn("ExtractImage: Source {0} (resolved to path {1}) doesn't exists", source.GetDebugName(), source.GetPath());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return Stream.Null;
            }

            if (!source.SupportsDirectAccess)
            {
                Log.Warn("ExtractImage: Extracting images from remote sources isn't supported yet", source.MediaType, source.Id);
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotImplemented);
                return Stream.Null;
            }

            // get temporary filename
            string filename = String.Format("extract_{0}_{1}.jpg", source.GetUniqueIdentifier(), position);
            string tempFile = cache.GetPath(filename);

            // maybe it exists in cache, return that then
            if (cache.Contains(filename))
            {
                return StreamPostprocessedImage(new ImageMediaSource(tempFile), maxWidth, maxHeight, borders, format);
            }

            // execute it
            ProcessStartInfo info = new ProcessStartInfo();
            using (var impersonator = source.GetImpersonator())
            {
                info.Arguments = String.Format("-ss {0} -i \"{1}\" -vframes 1 -f image2 {2}", position, source.GetPath(), tempFile);
                info.FileName = Configuration.StreamingProfiles.FFMpegPath;
                info.CreateNoWindow = true;
                info.UseShellExecute = false;
                Process proc = new Process();
                proc.StartInfo = info;
                proc.Start();
                proc.WaitForExit();
            }

            // log when failed
            if (!File.Exists(tempFile))
            {
                Log.Warn("Failed to extract image to temporary file {0} with command {1}", tempFile, info.Arguments);
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError);
                return Stream.Null;
            }

            return StreamPostprocessedImage(new ImageMediaSource(tempFile), maxWidth, maxHeight, borders, format);
        }
Ejemplo n.º 6
0
        public static decimal DEFAULT_ASPECT_RATIO = (decimal)16 / 9; // most new material is 16:9 these days

        public static WebMediaInfo LoadMediaInfoOrSurrogate(MediaSource source)
        {
            WebMediaInfo info;

            try
            {
                info = MediaInfoWrapper.GetMediaInfo(source);
                if (info != null)
                {
                    return(info);
                }
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Failed to load MediaInfo for {0}", source.GetDebugName()), ex);
            }

            WebMediaInfo surr = new WebMediaInfo();

            surr.Duration        = 0;
            surr.SubtitleStreams = new List <WebSubtitleStream>();
            surr.AudioStreams    = new List <WebAudioStream>()
            {
                new WebAudioStream()
                {
                    Channels     = 2,
                    Codec        = "Unknown",
                    ID           = 1,
                    Index        = 0,
                    Language     = "und", // yes, that's valid ISO 639 (I think)
                    LanguageFull = "Unknown",
                }
            };
            surr.VideoStreams = new List <WebVideoStream>()
            {
                new WebVideoStream()
                {
                    Codec = "Unknown",
                    DisplayAspectRatio       = DEFAULT_ASPECT_RATIO,
                    DisplayAspectRatioString = "16:9",
                    ID     = 2,
                    Index  = 0,
                    Height = 720,
                    Width  = 1280
                }
            };
            return(surr);
        }
Ejemplo n.º 7
0
        public static decimal DEFAULT_ASPECT_RATIO = (decimal)16 / 9; // most new material is 16:9 these days

        #endregion Fields

        #region Methods

        public static WebMediaInfo LoadMediaInfoOrSurrogate(MediaSource source)
        {
            WebMediaInfo info;
            try
            {
                info = MediaInfoWrapper.GetMediaInfo(source);
                if (info != null)
                {
                    return info;
                }
            }
            catch (Exception ex)
            {
                Log.Warn(String.Format("Failed to load MediaInfo for {0}", source.GetDebugName()), ex);
            }

            WebMediaInfo surr = new WebMediaInfo();
            surr.Duration = 0;
            surr.SubtitleStreams = new List<WebSubtitleStream>();
            surr.AudioStreams = new List<WebAudioStream>()
            {
                new WebAudioStream()
                {
                    Channels = 2,
                    Codec = "Unknown",
                    ID = 1,
                    Index = 0,
                    Language = "und", // yes, that's valid ISO 639 (I think)
                    LanguageFull = "Unknown",
                }
            };
            surr.VideoStreams = new List<WebVideoStream>()
            {
                new WebVideoStream()
                {
                    Codec = "Unknown",
                    DisplayAspectRatio = DEFAULT_ASPECT_RATIO,
                    DisplayAspectRatioString = "16:9",
                    ID = 2,
                    Index = 0,
                    Height = 1280, // gives this any problems?
                    Width = 720
                }
            };
            return surr;
        }
Ejemplo n.º 8
0
        private static bool ExecuteFFMpegExtraction(MediaSource source, string path, long position, string tempFile)
        {
            var info = new ProcessStartInfo();

            info.Arguments              = String.Format("-ss {0} -i \"{1}\" -vframes 1 -vf \"yadif,scale=ih*dar:ih\" -f image2 \"{2}\"", position, path, tempFile);
            info.FileName               = Configuration.StreamingProfiles.FFMpegPath;
            info.CreateNoWindow         = true;
            info.UseShellExecute        = false;
            info.RedirectStandardError  = Log.IsEnabled(LogLevel.Trace);
            info.RedirectStandardOutput = Log.IsEnabled(LogLevel.Trace);

            TranscoderProcess proc = new TranscoderProcess();

            proc.StartInfo = info;
            if (source.NeedsImpersonation)
            {
                proc.StartAsUser(Configuration.Services.NetworkImpersonation.Domain, Configuration.Services.NetworkImpersonation.Username, Configuration.Services.NetworkImpersonation.GetPassword());
            }
            else
            {
                proc.Start();
            }

            if (Log.IsEnabled(LogLevel.Trace))
            {
                Log.Trace("ExtractImage: executing path={0} arguments={1}", info.FileName, info.Arguments);
                StreamCopy.AsyncStreamRead(proc.StandardError, l => Log.Trace("ExtractImage: stderr: {0}", l));
                StreamCopy.AsyncStreamRead(proc.StandardOutput, l => Log.Trace("ExtractImage: stdout: {0}", l));
            }
            proc.WaitForExit();

            if (!File.Exists(tempFile))
            {
                Log.Warn("Failed to extract image from {0} with {1} {2}", source.GetDebugName(), info.FileName, info.Arguments);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 9
0
        public bool InitStream(string identifier, string clientDescription, MediaSource source)
        {
            if (!source.Exists)
            {
                Log.Warn("Tried to start stream for non-existing file {0}", source.GetDebugName());
                return(false);
            }

            ActiveStream stream = new ActiveStream();

            stream.Identifier        = identifier;
            stream.ClientDescription = clientDescription;
            stream.ClientIP          = WCFUtil.GetClientIPAddress();
            stream.StartTime         = DateTime.Now;
            stream.Context           = new StreamContext();
            stream.Context.Source    = source;
            stream.Context.IsTv      = source.MediaType == WebStreamMediaType.TV;

            lock (Streams)
            {
                Streams[identifier] = stream;
            }
            return(true);
        }
Ejemplo n.º 10
0
 public Stream GetMediaItem(WebStreamMediaType type, int? provider, string itemId)
 {
     MediaSource source = new MediaSource(type, provider, itemId);
     try
     {
         if (!source.Exists)
         {
             throw new FileNotFoundException();
         }
         return source.Retrieve();
     }
     catch (Exception ex)
     {
         WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
         Log.Info(String.Format("GetMediaItem() failed for {0}", source.GetDebugName()), ex);
         return Stream.Null;
     }
 }
Ejemplo n.º 11
0
        public static Stream ExtractImage(MediaSource source, long startPosition, int?maxWidth, int?maxHeight)
        {
            if (!source.Exists)
            {
                Log.Warn("ExtractImage: Source {0} (resolved to path {1}) doesn't exists", source.GetDebugName(), source.GetPath());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return(Stream.Null);
            }

            if (!source.SupportsDirectAccess)
            {
                Log.Warn("ExtractImage: Extracting images from remote sources isn't supported yet", source.MediaType, source.Id);
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotImplemented);
                return(Stream.Null);
            }

            // calculate size
            string ffmpegResize = "";

            if (maxWidth != null || maxHeight != null)
            {
                try
                {
                    decimal resolution = MediaInfoWrapper.GetMediaInfo(source).VideoStreams.First().DisplayAspectRatio;
                    ffmpegResize = "-s " + Resolution.Calculate(resolution, maxWidth, maxHeight).ToString();
                }
                catch (Exception ex)
                {
                    Log.Error("Error while getting resolution of video stream, not resizing", ex);
                }
            }

            // get temporary filename
            string filename = String.Format("extract_{0}_{1}_{2}_{3}.jpg", source.GetUniqueIdentifier(), startPosition,
                                            maxWidth == null ? "null" : maxWidth.ToString(), maxHeight == null ? "null" : maxHeight.ToString());
            string tempFile = cache.GetPath(filename);

            // maybe it exists in cache, return that then
            if (cache.Contains(filename))
            {
                return(StreamImage(new ImageMediaSource(tempFile)));
            }

            // execute it
            ProcessStartInfo info = new ProcessStartInfo();

            using (var impersonator = source.GetImpersonator())
            {
                info.Arguments       = String.Format("-ss {0} -i \"{1}\" {2} -vframes 1 -f image2 {3}", startPosition, source.GetPath(), ffmpegResize, tempFile);
                info.FileName        = Configuration.Streaming.FFMpegPath;
                info.CreateNoWindow  = true;
                info.UseShellExecute = false;
                Process proc = new Process();
                proc.StartInfo = info;
                proc.Start();
                proc.WaitForExit();
            }

            // log when failed
            if (!File.Exists(tempFile))
            {
                Log.Warn("Failed to extract image to temporary file {0} with command {1}", tempFile, info.Arguments);
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError);
                return(Stream.Null);
            }

            return(StreamImage(new ImageMediaSource(tempFile)));
        }
Ejemplo n.º 12
0
        public Stream GetMediaItem(WebStreamMediaType type, int? provider, string itemId)
        {
            if (!_authorizedHosts.Contains(WCFUtil.GetClientIPAddress()) && !NetworkInformation.IsLocalAddress(WCFUtil.GetClientIPAddress()))
            {
                Log.Warn("Host {0} isn't authorized to call GetMediaItem", WCFUtil.GetClientIPAddress());
                WCFUtil.SetResponseCode(HttpStatusCode.Unauthorized);
                return Stream.Null;
            }

            MediaSource source = new MediaSource(type, provider, itemId);
            try
            {
                if (!source.Exists)
                {
                    throw new FileNotFoundException();
                }

                WCFUtil.AddHeader("Content-Disposition", "attachment; filename=\"" + source.GetFileInfo().Name + "\"");
                WCFUtil.SetContentLength(source.GetFileInfo().Size);

                // there has to be a better way to do this
                object mime = RegistryReader.ReadKey(Microsoft.Win32.RegistryHive.ClassesRoot, Path.GetExtension(source.GetFileInfo().Name), "Content Type");
                if (mime != null)
                {
                    WCFUtil.SetContentType(mime.ToString());
                }

                return source.Retrieve();
            }
            catch (Exception ex)
            {
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                Log.Info(String.Format("GetMediaItem() failed for {0}", source.GetDebugName()), ex);
                return Stream.Null;
            }
        }
Ejemplo n.º 13
0
        public static Stream ExtractImage(MediaSource source, int startPosition, int? maxWidth, int? maxHeight)
        {
            if (!source.Exists)
            {
                Log.Warn("ExtractImage: Source {0} (resolved to path {1}) doesn't exists", source.GetDebugName(), source.GetPath());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return Stream.Null;
            }

            if (!source.SupportsDirectAccess)
            {
                Log.Warn("ExtractImage: Extracting images from remote sources isn't supported yet", source.MediaType, source.Id);
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotImplemented);
                return Stream.Null;
            }

            // calculate size
            string ffmpegResize = "";
            if (maxWidth != null || maxHeight != null)
            {
                try
                {
                    decimal resolution = MediaInfoWrapper.GetMediaInfo(source).VideoStreams.First().DisplayAspectRatio;
                    ffmpegResize = "-s " + Resolution.Calculate(resolution, maxWidth, maxHeight).ToString();
                }
                catch (Exception ex)
                {
                    Log.Error("Error while getting resolution of video stream, not resizing", ex);
                }
            }

            // get temporary filename
            string tempDir = Path.Combine(Path.GetTempPath(), "MPExtended", "imagecache");
            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            string filename = String.Format("ex_{0}_{1}_{2}_{3}.jpg", source.GetUniqueIdentifier(), startPosition,
                maxWidth == null ? "null" : maxWidth.ToString(), maxHeight == null ? "null" : maxHeight.ToString());
            string tempFile = Path.Combine(tempDir, filename);

            // maybe it exists in cache, return that then
            if (File.Exists(tempFile))
            {
                return StreamImage(new ImageMediaSource(tempFile));
            }

            // execute it
            ProcessStartInfo info = new ProcessStartInfo();
            using (var impersonator = source.GetImpersonator())
            {
                info.Arguments = String.Format("-ss {0} -i \"{1}\" {2} -vframes 1 -f image2 {3}", startPosition, source.GetPath(), ffmpegResize, tempFile);
                info.FileName = Configuration.Streaming.FFMpegPath;
                info.CreateNoWindow = true;
                info.UseShellExecute = false;
                Process proc = new Process();
                proc.StartInfo = info;
                proc.Start();
                proc.WaitForExit();
            }

            // log when failed
            if (!File.Exists(tempFile))
            {
                Log.Warn("Failed to extract image to temporary file {0} with command {1}", tempFile, info.Arguments);
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError);
                return Stream.Null;
            }

            return StreamImage(new ImageMediaSource(tempFile));
        }
Ejemplo n.º 14
0
        private static bool ExecuteFFMpegExtraction(MediaSource source, string path, long position, string tempFile)
        {
            var info = new ProcessStartInfo();
            info.Arguments = String.Format("-ss {0} -i \"{1}\" -vframes 1 -vf \"yadif,scale=ih*dar:ih\" -f image2 \"{2}\"", position, path, tempFile);
            info.FileName = Configuration.StreamingProfiles.FFMpegPath;
            info.CreateNoWindow = true;
            info.UseShellExecute = false;
            info.RedirectStandardError = Log.IsEnabled(LogLevel.Trace);
            info.RedirectStandardOutput = Log.IsEnabled(LogLevel.Trace);

            TranscoderProcess proc = new TranscoderProcess();
            proc.StartInfo = info;
            if (source.NeedsImpersonation)
                proc.StartAsUser(Configuration.Services.NetworkImpersonation.Domain, Configuration.Services.NetworkImpersonation.Username, Configuration.Services.NetworkImpersonation.GetPassword());
            else
                proc.Start();

            if (Log.IsEnabled(LogLevel.Trace))
            {
                Log.Trace("ExtractImage: executing path={0} arguments={1}", info.FileName, info.Arguments);
                StreamCopy.AsyncStreamRead(proc.StandardError, l => Log.Trace("ExtractImage: stderr: {0}", l));
                StreamCopy.AsyncStreamRead(proc.StandardOutput, l => Log.Trace("ExtractImage: stdout: {0}", l));
            }
            proc.WaitForExit();

            if (!File.Exists(tempFile))
            {
                Log.Warn("Failed to extract image from {0} with {1} {2}", source.GetDebugName(), info.FileName, info.Arguments);
                return false;
            }

            return true;
        }
Ejemplo n.º 15
0
        private static ImageSource ConvertToImageSource(MediaSource source, WebArtworkType artworktype)
        {
            // handle tv and recordings specially
            if (source.MediaType == WebStreamMediaType.TV || source.MediaType == WebStreamMediaType.Recording)
            {
                if (artworktype != WebArtworkType.Logo)
                {
                    Log.Info("Requested invalid artwork mediatype={0} artworktype={1}", source.MediaType, artworktype);
                    return null;
                }

                // get display name
                int idChannel = source.MediaType == WebStreamMediaType.TV ?
                    Int32.Parse(source.Id) :
                    MPEServices.TAS.GetRecordingById(Int32.Parse(source.Id)).IdChannel;
                string channelName = MPEServices.TAS.GetChannelBasicById(idChannel).DisplayName;

                // find directory
                string tvLogoDir = Configuration.Streaming.TVLogoDirectory;
                if (!Directory.Exists(tvLogoDir))
                {
                    Log.Warn("TV logo directory {0} does not exists", tvLogoDir);
                    return null;
                }

                // find image
                DirectoryInfo dirinfo = new DirectoryInfo(tvLogoDir);
                var matched = dirinfo.GetFiles().Where(x => Path.GetFileNameWithoutExtension(x.Name).ToLowerInvariant() == channelName.ToLowerInvariant());
                if(matched.Count() == 0)
                {
                    Log.Debug("Did not find tv logo for channel {0}", channelName);
                    return null;
                }

                // great, return it
                return new ImageSource(matched.First().FullName);
            }

            // handle all 'standard' media cases
            // validate arguments
            var pathlist = MPEServices.MAS.GetPathList(source.Provider, (WebMediaType)source.MediaType, (WebFileType)artworktype, source.Id);
            if (pathlist == null || pathlist.Count <= source.Offset)
            {
                Log.Info("Requested unavailable artwork (offset not found) artworktype={0} {1}", artworktype, source.GetDebugName());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return null;
            }
            string path = pathlist.ElementAt(source.Offset);

            Stream data = null;
            WebFileInfo info = MPEServices.MAS.GetFileInfo(source.Provider, (WebMediaType)source.MediaType, (WebFileType)artworktype, source.Id, source.Offset);
            if (!info.Exists)
            {
                Log.Info("Requested unavailable artwork (file not found) artworktype={0} {1}", artworktype, source.GetDebugName());
                return null;
            }
            else if (!info.IsLocalFile)
            {
                data = MPEServices.MAS.RetrieveFile(source.Provider, (WebMediaType)source.MediaType, (WebFileType)artworktype, source.Id, source.Offset);
                return new ImageSource(data);
            }
            else
            {
                return new ImageSource(path);
            }
        }
Ejemplo n.º 16
0
        public static Stream ExtractImage(MediaSource source, long position, int?maxWidth, int?maxHeight, string borders, string format)
        {
            if (!source.Exists)
            {
                Log.Warn("ExtractImage: Source {0} (resolved to path {1}) doesn't exists", source.GetDebugName(), source.GetPath());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return(Stream.Null);
            }

            if (!source.SupportsDirectAccess)
            {
                Log.Warn("ExtractImage: Extracting images from remote sources isn't supported yet", source.MediaType, source.Id);
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotImplemented);
                return(Stream.Null);
            }

            // get temporary filename
            string filename = String.Format("extract_{0}_{1}.jpg", source.GetUniqueIdentifier(), position);
            string tempFile = cache.GetPath(filename);

            // maybe it exists in cache, return that then
            if (cache.Contains(filename))
            {
                // if source is newer, cached image needs to be recreated
                if (source.GetFileInfo().LastModifiedTime > cache.GetLastModifiedTime(tempFile))
                {
                    cache.Invalidate(filename);
                }
                else
                {
                    return(StreamPostprocessedImage(new ImageMediaSource(tempFile), maxWidth, maxHeight, borders, format));
                }
            }

            // We need to impersonate to access the network drive and check if the thumbnail already exists. However, because
            // impersonation is lost when starting a process, we can't start ffmpeg from in here. We need to check whether the
            // file is accessible from outside the impersonation context again, and start the ffmpeg process as a different user
            // if that is the case.
            string fullPath;

            using (var context = source.CreateNetworkContext())
            {
                fullPath = context.RewritePath(source.GetPath());

                // stream a pre-existing thumbnail, if possible
                if (source.MediaType == WebMediaType.Recording && Path.GetExtension(fullPath).ToLower() == ".ts")
                {
                    var thumbnailFileInfo = new FileInfo(Path.ChangeExtension(fullPath, ".jpg"));
                    if (thumbnailFileInfo.Exists && thumbnailFileInfo.Length > 0)
                    {
                        return(StreamPostprocessedImage(new ImageMediaSource(thumbnailFileInfo.FullName), maxWidth, maxHeight, borders, format));
                    }
                }
            }

            // finally, extract the image with ffmpeg if everything else has failed
            bool extractResult = ExecuteFFMpegExtraction(source, fullPath, position, tempFile);

            if (!extractResult)
            {
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError);
                return(Stream.Null);
            }

            return(StreamPostprocessedImage(new ImageMediaSource(tempFile), maxWidth, maxHeight, borders, format));
        }
Ejemplo n.º 17
0
        public static Stream ExtractImage(MediaSource source, long position, int? maxWidth, int? maxHeight, string borders, string format)
        {
            if (!source.Exists)
            {
                Log.Warn("ExtractImage: Source {0} (resolved to path {1}) doesn't exists", source.GetDebugName(), source.GetPath());
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                return Stream.Null;
            }

            if (!source.SupportsDirectAccess)
            {
                Log.Warn("ExtractImage: Extracting images from remote sources isn't supported yet", source.MediaType, source.Id);
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotImplemented);
                return Stream.Null;
            }

            // get temporary filename
            string filename = String.Format("extract_{0}_{1}.jpg", source.GetUniqueIdentifier(), position);
            string tempFile = cache.GetPath(filename);

            // maybe it exists in cache, return that then
            if (cache.Contains(filename))
            {
                // if source is newer, cached image needs to be recreated
                if (source.GetFileInfo().LastModifiedTime > cache.GetLastModifiedTime(tempFile))
                {
                    cache.Invalidate(filename);
                }
                else
                {
                    return StreamPostprocessedImage(new ImageMediaSource(tempFile), maxWidth, maxHeight, borders, format);
                }
            }

            // We need to impersonate to access the network drive and check if the thumbnail already exists. However, because
            // impersonation is lost when starting a process, we can't start ffmpeg from in here. We need to check whether the
            // file is accessible from outside the impersonation context again, and start the ffmpeg process as a different user
            // if that is the case.
            string fullPath;
            using (var context = source.CreateNetworkContext())
            {
                fullPath = context.RewritePath(source.GetPath());

                // stream a pre-existing thumbnail, if possible
                if (source.MediaType == WebMediaType.Recording && Path.GetExtension(fullPath).ToLower() == ".ts")
                {
                    var thumbnailFileInfo = new FileInfo(Path.ChangeExtension(fullPath, ".jpg"));
                    if (thumbnailFileInfo.Exists && thumbnailFileInfo.Length > 0)
                        return StreamPostprocessedImage(new ImageMediaSource(thumbnailFileInfo.FullName), maxWidth, maxHeight, borders, format);
                }
            }

            // finally, extract the image with ffmpeg if everything else has failed
            bool extractResult = ExecuteFFMpegExtraction(source, fullPath, position, tempFile);
            if (!extractResult)
            {
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.InternalServerError);
                return Stream.Null;
            }

            return StreamPostprocessedImage(new ImageMediaSource(tempFile), maxWidth, maxHeight, borders, format);
        }
Ejemplo n.º 18
0
        public bool InitStream(string identifier, string clientDescription, MediaSource source)
        {
            if (!source.Exists)
            {
                Log.Warn("Tried to start stream for non-existing file {0}", source.GetDebugName());
                return false;
            }

            ActiveStream stream = new ActiveStream();
            stream.Identifier = identifier;
            stream.ClientDescription = clientDescription;
            stream.ClientIP = WCFUtil.GetClientIPAddress();
            stream.StartTime = DateTime.Now;
            stream.Context = new StreamContext();
            stream.Context.Source = source;
            stream.Context.IsTv = source.MediaType == WebStreamMediaType.TV;

            lock (Streams)
            {
                Streams[identifier] = stream;
            }
            return true;
        }
Ejemplo n.º 19
0
        public bool InitStream(string identifier, string clientDescription, MediaSource source, int timeout)
        {
            if (!source.Exists)
            {
                StreamLog.Warn(identifier, "Tried to start stream for non-existing file {0}", source.GetDebugName());
                return false;
            }

            ActiveStream stream = new ActiveStream();
            stream.Identifier = identifier;
            stream.ClientDescription = clientDescription;
            stream.StartTime = DateTime.Now;
            stream.Timeout = timeout;
            stream.LastActivity = DateTime.Now;
            stream.UseActivityForTimeout = false;
            stream.Context = new StreamContext();
            stream.Context.Identifier = identifier;
            stream.Context.Source = source;
            stream.Context.IsTv = source.MediaType == WebMediaType.TV;

            // Some clients such as WebMP proxy the streams before relying it to the client. We should give these clients the option to
            // forward the real IP address, so that we can show that one in the configurator too. However, to avoid abuse, we should show
            // the real IP of the client too, so make up some nice text string.
            string realIp = WCFUtil.GetHeaderValue("forwardedFor", "X-Forwarded-For");
            stream.ClientIP = realIp == null ? WCFUtil.GetClientIPAddress() : String.Format("{0} (via {1})", realIp, WCFUtil.GetClientIPAddress());

            Streams[identifier] = stream;
            return true;
        }
Ejemplo n.º 20
0
        public Stream GetMediaItem(WebStreamMediaType type, int? provider, string itemId)
        {
            MediaSource source = new MediaSource(type, provider, itemId);
            try
            {
                if (!source.Exists)
                {
                    throw new FileNotFoundException();
                }

                WCFUtil.AddHeader("Content-Disposition", "attachment; filename=\"" + source.GetFileInfo().Name + "\"");

                // there has to be a better way to do this
                object mime = RegistryReader.ReadKey(Microsoft.Win32.RegistryHive.ClassesRoot, Path.GetExtension(source.GetFileInfo().Name), "Content Type");
                if (mime != null)
                {
                    WCFUtil.AddHeader("Content-Type", mime.ToString());
                }

                return source.Retrieve();
            }
            catch (Exception ex)
            {
                WCFUtil.SetResponseCode(System.Net.HttpStatusCode.NotFound);
                Log.Info(String.Format("GetMediaItem() failed for {0}", source.GetDebugName()), ex);
                return Stream.Null;
            }
        }