Beispiel #1
0
        public HlsItem(HlsManager manager, string sessionId, Dictionary <string, string> parameters, CultureInfo cultureInfo)
        {
            this.sessionId = sessionId;
            this.manager   = manager;

            this.segmentTime = uint.Parse(parameters["hlsSegmentTime"]);

            this.streamItems.Add(0, new StreamItem()
            {
                Duration = this.segmentTime
            });

            string playlistPipeName = "HMC_" + sessionId;

            parameters["hlsPlaylistUrl"] = "\\\\.\\pipe\\" + playlistPipeName;
            this.playlistPipe            = CreatePipe(playlistPipeName);

            this.filePipe            = CreatePipe("HMC_" + (this.nextFilePipeIdx++) + "_" + this.sessionId);
            parameters["hlsFileUrl"] = "\\\\.\\pipe\\HMC_%d_" + sessionId;

            this.encoder = EncoderBuilder.GetEncoder(parameters);

            this.playlistPipeThread = new Thread(new ThreadStart(ListenPlaylistPipe));
            this.filePipeThread     = new Thread(new ThreadStart(ListenFilePipe));
            this.encoderThread      = new Thread(new ThreadStart(Encoder));
            if (cultureInfo != null)
            {
                this.playlistPipeThread.CurrentCulture = this.playlistPipeThread.CurrentUICulture = cultureInfo;
                this.filePipeThread.CurrentCulture     = this.filePipeThread.CurrentUICulture = cultureInfo;
                this.encoderThread.CurrentCulture      = this.encoderThread.CurrentUICulture = cultureInfo;
            }

            this.lastRequest = DateTime.Now;
        }
Beispiel #2
0
            public void LoadSettings(XmlDocument xmlReader)
            {
                this.encode = xmlReader.SelectNodes("/HomeMediaCenter/" + this.prefix + "/Parameters/*").Cast <XmlNode>().Select(
                    a => EncoderBuilder.GetEncoder(a.InnerText)).ToList().AsReadOnly();

                LoadSpecificSettings(xmlReader);
            }
Beispiel #3
0
        public MediaSettings(MediaServerDevice upnpDevice)
        {
            this.audio = new MediaSettingsAV(upnpDevice, "AudioSettings",
                                             true,
                                             "DLNA.ORG_OP=01;DLNA.ORG_FLAGS=01500000000000000000000000000000",
                                             "DLNA.ORG_OP=10;DLNA.ORG_FLAGS=01500000000000000000000000000000",
                                             "DLNA.ORG_OP=00;DLNA.ORG_FLAGS=01500000000000000000000000000000",
                                             EncoderBuilder.GetEncoder("&codec=mp3_ts&audbitrate=128&video=0&quality=100&obufsize=1024"));

            this.image = new MediaSettingsIMG(upnpDevice, "ImageSettings",
                                              true,
                                              "DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00d00000000000000000000000000000",
                                              "DLNA.ORG_OP=01;DLNA.ORG_FLAGS=00d00000000000000000000000000000",
                                              EncoderBuilder.GetEncoder("&codec=jpeg&width=160&height=160&keepaspect"));

            this.video = new MediaSettingsAV(upnpDevice, "VideoSettings",
                                             true,
                                             "DLNA.ORG_OP=01;DLNA.ORG_FLAGS=01500000000000000000000000000000",
                                             "DLNA.ORG_OP=10;DLNA.ORG_CI=1;DLNA.ORG_FLAGS=01500000000000000000000000000000",
                                             "DLNA.ORG_OP=00;DLNA.ORG_CI=1;DLNA.ORG_FLAGS=01500000000000000000000000000000",
                                             EncoderBuilder.GetEncoder("&codec=mpeg2_ps&vidbitrate=3000&audbitrate=128&width=720&height=576&fps=25&obufsize=2048"));

            this.stream = new MediaSettingBase(upnpDevice, "StreamSettings",
                                               EncoderBuilder.GetEncoder("&codec=mpeg2_ps&vidbitrate=3000&audbitrate=128&width=720&height=576&fps=25&obufsize=2048"),
                                               EncoderBuilder.GetEncoder("&codec=mpeg2_ps&vidbitrate=5000&audbitrate=128&width=1280&height=768&fps=25&audio=0&obufsize=2048"),
                                               EncoderBuilder.GetEncoder("&codec=mpeg2_ps&vidbitrate=8000&audbitrate=128&width=1920&height=1080&fps=25&audio=0&obufsize=2048"),
                                               EncoderBuilder.GetEncoder("&codec=mp3_ts&audbitrate=128&video=0&quality=100&obufsize=1024"));
        }
Beispiel #4
0
        public override void BrowseMetadata(XmlWriter writer, MediaSettings settings, string host, string idParams, HashSet <string> filterSet, int parentId)
        {
            EncoderBuilder encBuilder = EncoderBuilder.GetEncoder(this.SubtitlesPath);

            writer.WriteStartElement("item");

            writer.WriteAttributeString("id", this.Id.ToString());
            writer.WriteAttributeString("restricted", "true");
            writer.WriteAttributeString("parentID", parentId + "_" + (this.Audio ? AudioIndex : VideoIndex));

            //Povinne hodnoty
            writer.WriteElementString("dc", "title", null, this.Title);
            writer.WriteElementString("upnp", "class", null, this.Audio ? "object.item.audioItem" : "object.item.videoItem");

            //Volitelne hodnoty
            if (filterSet == null || filterSet.Contains("dc:date"))
            {
                writer.WriteElementString("dc", "date", null, this.Date.ToString("yyyy-MM-dd"));
            }

            if (filterSet == null || filterSet.Any(a => a.StartsWith("res")))
            {
                writer.WriteStartElement("res");

                if (filterSet == null || filterSet.Contains("res@duration"))
                {
                    writer.WriteAttributeString("duration", "0:00:00.000");
                }

                if (this.Audio)
                {
                    if (encBuilder.AudBitrate != null && (filterSet == null || filterSet.Contains("res@bitrate")))
                    {
                        writer.WriteAttributeString("bitrate", encBuilder.AudBitrate);
                    }

                    writer.WriteAttributeString("protocolInfo", string.Format("http-get:*:{0}:{1}{2}", this.Mime, encBuilder.GetDlnaType(), settings.Audio.StreamFeature));
                    writer.WriteValue(host + "/encode/audio?id=" + this.Id + this.SubtitlesPath);
                }
                else
                {
                    if (encBuilder.VidBitrate != null && (filterSet == null || filterSet.Contains("res@bitrate")))
                    {
                        writer.WriteAttributeString("bitrate", encBuilder.VidBitrate);
                    }

                    if (this.Resolution != null && (filterSet == null || filterSet.Contains("res@resolution")))
                    {
                        writer.WriteAttributeString("resolution", this.Resolution);
                    }

                    writer.WriteAttributeString("protocolInfo", string.Format("http-get:*:{0}:{1}{2}", this.Mime, encBuilder.GetDlnaType(), settings.Video.StreamFeature));
                    writer.WriteValue(host + "/encode/video?id=" + this.Id + this.SubtitlesPath);
                }
                writer.WriteEndElement();
            }

            writer.WriteEndElement();
        }
Beispiel #5
0
 public ItemVideoStream(ItemContainer parent, string path, string title, EncoderBuilder settings)
     : base(string.Format("{0} {1} {2}kBps {3}", title, settings.Resolution, settings.VidBitrate, settings.Audio), parent)
 {
     this.path        = path;
     this.mime        = settings.GetMime();
     this.date        = DateTime.Now;
     this.bitrate     = settings.VidBitrate;
     this.resolution  = settings.Resolution;
     this.queryString = settings.GetParamString();
     this.dlnaType    = settings.GetDlnaType();
 }
Beispiel #6
0
        public ItemStream(string title, ItemContainer parent, EncoderBuilder encBuilder)
            : base(GetTitle(title, encBuilder.Resolution, encBuilder.Video ? encBuilder.VidBitrate : encBuilder.AudBitrate, encBuilder.Audio), null, parent)
        {
            this.Mime          = encBuilder.GetMime();
            this.Date          = DateTime.Now;
            this.Resolution    = encBuilder.Resolution;
            this.SubtitlesPath = encBuilder.GetParamString();
            this.Audio         = encBuilder.Audio && !encBuilder.Video;
            this.Video         = encBuilder.Video;

            parent.SetMediaType(this.Audio ? MediaType.Audio : MediaType.Video);
        }
Beispiel #7
0
        public static EncoderBuilder GetEncoder(string paramString)
        {
            Dictionary <string, string> parameters = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (string parameter in paramString.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
            {
                string[] keyValue = parameter.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
                parameters[keyValue[0]] = (keyValue.Length == 2) ? keyValue[1] : string.Empty;
            }

            EncoderBuilder encoder = GetEncoder(parameters);

            encoder.paramString = paramString;

            return(encoder);
        }
Beispiel #8
0
            public void SetEncodeStrings(string[] encode)
            {
                if (encode == null)
                {
                    return;
                }

                this.device.CheckStopped();

                this.encode = encode.Select(delegate(string a) {
                    try { return(EncoderBuilder.GetEncoder(a)); }
                    catch { return(null); }
                }).Where(a => (a != null)).ToList().AsReadOnly();

                this.device.SettingsChanged();
            }
Beispiel #9
0
        public override void RefreshMe(DataContext context, ItemManager manager, bool recursive)
        {
            if (manager.UpnpDevice.Stopping)
            {
                return;
            }

            //Rozdielova obnova parametrov poloziek v tomto kontajnery
            IEnumerable <string> paramString = manager.MediaSettings.Stream.Encode.Select(a => a.GetParamString()).ToArray();

            Item[]   toRemove = this.Items.Except(paramString, new SubtitlesPathItemEqualityComparer()).Cast <Item>().ToArray();
            string[] toAdd    = paramString.Except(this.Items.OfType <ItemStream>().Select(a => a.SubtitlesPath)).ToArray();

            RemoveRange(context, manager, toRemove);

            foreach (string param in toAdd)
            {
                new ItemStream(this.Title, this, EncoderBuilder.GetEncoder(param));
            }
        }
Beispiel #10
0
        private void SendResource(HttpRequest request, string mime, bool encode = false)
        {
            HttpResponse response = request.GetResponse();

            string name = request.Url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries).Last();

            using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("HomeMediaCenter.Resources." + name))
            {
                if (encode)
                {
                    EncoderBuilder builder = EncoderBuilder.GetEncoder(request.UrlParams);

                    using (MemoryStream memStream = new MemoryStream())
                    {
                        builder.StartEncode(resourceStream, memStream);

                        response.AddHreader(HttpHeader.ContentLength, memStream.Length.ToString());
                        response.AddHreader(HttpHeader.ContentType, builder.GetMime());
                        response.SendHeaders();

                        if (request.Method == "GET")
                        {
                            memStream.Position = 0;
                            memStream.CopyTo(response.GetStream());
                        }
                    }
                }
                else
                {
                    response.AddHreader(HttpHeader.ContentLength, resourceStream.Length.ToString());
                    response.AddHreader(HttpHeader.ContentType, mime);
                    response.SendHeaders();

                    if (request.Method == "GET")
                    {
                        resourceStream.CopyTo(response.GetStream());
                    }
                }
            }
        }
Beispiel #11
0
        private void GetEncode(HttpRequest request)
        {
            uint index;

            string[] values = request.GetFileName().Split(new char[] { '_' }, 2);
            if (values.Length < 2 || !uint.TryParse(values[0], out index))
            {
                throw new HttpException(404, "HLS file not found");
            }

            string sessionId;
            int    extIndex = values[1].ToLower().LastIndexOf(".ts");

            if (extIndex < 1)
            {
                throw new HttpException(404, "Unknown session id");
            }
            sessionId = values[1].Substring(0, extIndex);

            HlsItem item;

            this.itemsLock.EnterReadLock();
            try
            {
                if (!this.items.ContainsKey(sessionId))
                {
                    throw new HttpException(404, "Session id not found");
                }
                item = this.items[sessionId];
            }
            finally
            {
                this.itemsLock.ExitReadLock();
            }

            HttpResponse response = request.GetResponse();

            response.AddHreader(HttpHeader.ContentType, "video/MP2T");

            if (index == 0)
            {
                //Poslanie nulteho suboru so statickym obrazom, je pripraveny hned na stiahnutie
                //Jeho dlzka je rovnaka ako dlzka segmentu
                response.SendHeaders();

                Dictionary <string, string> parameters = item.GetParamCopy();
                parameters.Remove("starttime");
                parameters.Remove("subtitles");
                parameters.Remove("id");
                parameters["source"]  = "static";
                parameters["codec"]   = "mpeg2_ts_h264";
                parameters["endtime"] = parameters["hlsSegmentTime"];

                EncoderBuilder encoder = EncoderBuilder.GetEncoder(parameters);
                encoder.StartEncode(response.GetStream());
            }
            else
            {
                //Posielanie segmentovanych suborov pozadovaneho zdroja
                byte[] fileData = item.GetFileData(index);

                response.AddHreader(HttpHeader.ContentLength, fileData.Length.ToString());
                response.SendHeaders();
                response.GetStream().Write(fileData, 0, fileData.Length);
            }
        }
Beispiel #12
0
        private void GetEncode(HttpRequest request, string path, string subtitlesPath, string encodeFeature, TimeSpan?duration)
        {
            HttpResponse response = request.GetResponse();

            request.UrlParams["source"] = path;
            if (subtitlesPath != null)
            {
                request.UrlParams["subtitles"] = subtitlesPath;
            }
            if (encodeFeature != null)
            {
                response.AddHreader("ContentFeatures.dlna.org", encodeFeature);
            }

            if (duration.HasValue)
            {
                //Je mozne seekovanie pomocou casu

                double startTimeParam = 0;
                if (request.UrlParams.ContainsKey("starttime") && double.TryParse(request.UrlParams["starttime"],
                                                                                  System.Globalization.NumberStyles.Float | System.Globalization.NumberStyles.AllowThousands,
                                                                                  System.Globalization.CultureInfo.InvariantCulture, out startTimeParam))
                {
                    //Ak je nastaveny url parameter pozicie - treba upravit dlzku
                    duration -= TimeSpan.FromSeconds(startTimeParam);
                }

                response.AddHreader("X-AvailableSeekRange", string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                                          "1 npt=0.0-{0:0.000}", duration.Value.TotalSeconds));

                if (request.Headers.ContainsKey("TimeSeekRange.dlna.org"))
                {
                    //Zistenie a nastavenie pozicie
                    string[] range = request.Headers["TimeSeekRange.dlna.org"].Split('=').Last().Split('-').Select(a => a.Trim()).ToArray();
                    double   end, start;

                    //Cas moze byt vo formate 0.000 sekundy alebo 0:00:00.0
                    if (!double.TryParse(range[0], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out start))
                    {
                        start = TimeSpan.Parse(range[0]).TotalSeconds;
                    }
                    if (start < 0)
                    {
                        start += duration.Value.TotalSeconds;
                    }

                    if (range.Length < 2)
                    {
                        end = duration.Value.TotalSeconds;
                    }
                    else
                    {
                        TimeSpan endSpan;
                        if (double.TryParse(range[1], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out end))
                        {
                            request.UrlParams["endtime"] = end.ToString(System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else if (TimeSpan.TryParse(range[1], out endSpan))
                        {
                            request.UrlParams["endtime"] = endSpan.TotalSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            end = duration.Value.TotalSeconds;
                        }
                    }

                    request.UrlParams["starttime"] = (start + startTimeParam).ToString(System.Globalization.CultureInfo.InvariantCulture);

                    response.AddHreader("Vary", "TimeSeekRange.dlna.org");
                    response.AddHreader("TimeSeekRange.dlna.org", string.Format(System.Globalization.CultureInfo.InvariantCulture,
                                                                                "npt={0:0.000}-{1:0.000}/{2:0.000}", start, end, duration.Value.TotalSeconds));
                }
            }

            string prefDsDemuxStr = GetPrefDsDemux();

            if (prefDsDemuxStr != null)
            {
                request.UrlParams["prefDsDemux"] = prefDsDemuxStr;
            }

            EncoderBuilder builder = EncoderBuilder.GetEncoder(request.UrlParams);

            response.AddHreader(HttpHeader.ContentType, builder.GetMime());
            response.AddHreader(HttpHeader.AcceptRanges, "none");
            response.AddHreader("TransferMode.dlna.org", "Streaming");
            response.SendHeaders();

            if (request.Method == "GET")
            {
                OnLogEvent(string.Format("Starting encode {0} as {1}", request.UrlParams["source"], builder.GetMime()));
                builder.StartEncode(response.GetStream());
            }
        }