public override string GetVideoUrl(VideoInfo video)
        {
            string webdata = GetWebData(video.VideoUrl);
            var doc = new HtmlDocument();
            doc.LoadHtml(webdata);
            var node = doc.DocumentNode.SelectSingleNode(@"//div[@data-media]");
            string js = HttpUtility.HtmlDecode(node.Attributes["data-media"].Value);
            JToken data = JObject.Parse(js) as JToken;
            JToken sources = data["sources"];
            video.PlaybackOptions = new Dictionary<string, string>();
            AddOption("high", sources, video.PlaybackOptions);
            AddOption("web", sources, video.PlaybackOptions);
            AddOption("mobile", sources, video.PlaybackOptions);

            if (video.PlaybackOptions.Count == 0) return null;
            else
                if (video.PlaybackOptions.Count == 1)
                {
                    string resultUrl = video.PlaybackOptions.First().Value;
                    video.PlaybackOptions = null;// only one url found, PlaybackOptions not needed
                    return resultUrl;
                }
                else
                {
                    return video.PlaybackOptions.First().Value;
                }
        }
Beispiel #2
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="src">视频源文件</param>
 public Video(string src)
 {
     if (!System.IO.File.Exists(src))
         throw new Exception(src + " Not Found.");
     _Source = src;
     Info = MediaHelper.GetVideoInfo(src);
 }
        public override List<VideoInfo> GetVideos(Category category)
        {
            string webdata = GetWebData(((RssLink)category).Url);
            var doc = new HtmlDocument();
            doc.LoadHtml(webdata);

            List<VideoInfo> res = new List<VideoInfo>();
            var vidnodes = doc.DocumentNode.SelectNodes(@".//section[@class='js-item-container']//article");
            foreach (var vidnode in vidnodes)
                if (vidnode.Attributes["data-id"] != null)
                {
                    VideoInfo video = new VideoInfo();
                    video.Title = vidnode.SelectSingleNode(@"./header/h3/a").InnerText;
                    var tmNode = vidnode.SelectSingleNode(@".//time");
                    if (tmNode != null)
                        video.Airdate = tmNode.InnerText;
                    video.VideoUrl = @"http://www.rtbf.be/auvio/embed/media?id=" + vidnode.Attributes["data-id"].Value;
                    string img = vidnode.SelectSingleNode(@".//img").Attributes["data-srcset"].Value;
                    var arr1 = img.Split(',');
                    var arr2 = arr1.Last<string>().Split(' ');
                    video.Thumb = arr2[0];

                    res.Add(video);
                }
            return res;
        }
Beispiel #4
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="bytes">视频文件字节集</param>
 /// <param name="extension">扩展名(如.png)</param>
 public Video(byte[] bytes, string extension)
 {
     var fname = Path.GetTempPath() + "codecomb_" + Guid.NewGuid().ToString().Replace("-", "") + extension;
     System.IO.File.WriteAllBytes(fname, bytes);
     _Source = fname;
     Info = MediaHelper.GetImageInfo(fname);
 }
        public override string GetVideoUrl(VideoInfo video)
        {
            string res = base.GetVideoUrl(video);
            XmlDocument doc = new XmlDocument();
            string[] urlParts = video.VideoUrl.Split('.');

            if (urlParts[1] == "four")
                res = res.Replace("@@", "c4");
            else
                res = res.Replace("@@", "tv3");

            doc.Load(res);

            video.PlaybackOptions = new Dictionary<string, string>();

            string meta_base = @"rtmpe://202.49.175.79/vod/_definst_"; // found with wireshark. apparently value in 
            //meta/base (rtmpe://vod-geo.mediaworks.co.nz/vod/_definst_) is just a decoy

            //old: doc.SelectSingleNode("//smil/head/meta").Attributes["base"].Value;

            foreach (XmlNode node in doc.SelectNodes("//smil/body/switch/video"))
            {
                int bitRate = int.Parse(node.Attributes["system-bitrate"].Value) / 1024;

                RtmpUrl rtmpUrl = new RtmpUrl(meta_base + "/" + node.Attributes["src"].Value)
                {
                    SwfVerify = true,
                    SwfUrl = @"http://static.mediaworks.co.nz/video/jw/6.50/jwplayer.flash.swf"
                };

                video.PlaybackOptions.Add(bitRate.ToString() + "K", rtmpUrl.ToString());
            }

            return video.PlaybackOptions.Last().Value;
        }
Beispiel #6
0
 /******************************************/
 /******************************************/
 /// <summary>内部生成時、使用される</summary>
 /// <param name="Target">ターゲット動画</param>
 /// <param name="Host">生成元</param>
 /// <param name="Context">コンテキスト</param>
 internal VideoPage(VideoInfo Target, VideoService Host, Context Context)
 {
     target = Target;
     host = Host;
     context = Context;
     converter = new Serial.Converter(context);
 }
        public override string GetVideoUrl(VideoInfo video)
        {
            var json = JObject.Parse(Regex.Match(GetWebData(video.VideoUrl), "var info = (?<json>{.*),").Groups["json"].Value);

            video.PlaybackOptions = new Dictionary<string,string>();
            
            var url = json.Value<string>("stream_h264_ld_url");
            if (!string.IsNullOrEmpty(url))
                video.PlaybackOptions.Add("Low - 320x240", url);
            
            url = json.Value<string>("stream_h264_url");
            if (!string.IsNullOrEmpty(url))
                video.PlaybackOptions.Add("Normal - 512x384", url);

            url = json.Value<string>("stream_h264_hq_url");
            if (!string.IsNullOrEmpty(url))
                video.PlaybackOptions.Add("High - 848x480", url);

            url = json.Value<string>("stream_h264_hd_url");
            if (!string.IsNullOrEmpty(url))
                video.PlaybackOptions.Add("HD - 1280x720", url);

            url = json.Value<string>("stream_h264_hd1080_url");
            if (!string.IsNullOrEmpty(url))
                video.PlaybackOptions.Add("Full HD - 1920x1080", url);

            return video.PlaybackOptions.Last().Value;
        }
Beispiel #8
0
 /// <summary>動画へアクセスするページを取得する</summary>
 /// <param name="Target">ターゲット動画</param>
 public VideoPage GetVideoPage(VideoInfo Target)
 {
     if (Target.videoPage != null)
         return Target.videoPage;
     else
         return Target.videoPage = new VideoPage(Target, context);
 }
        public static bool ProcessVideo(VideoInfo videoInfoInput, bool rmSound)
        {
            WebClient webClient = new WebClient();
            videoInfo = videoInfoInput;
            removeSound = rmSound;
            logger.Info("videoinfo.filename " + videoInfo.Filename + "\n" + videoInfoInput.Filename);

            filepath = PATH + videoInfo.Filename;

            logger.Info("Server.MapPath(..\\) + filename: " + filepath);
            if (Path.HasExtension(filepath) == false)
                filepath += ".mp4"; // todo change to .mp4
            else
                filepath = Path.ChangeExtension(filepath, "mp4"); // download as mp4 extension
            logger.Info("Download video: " + filepath);
            try
            {
                webClient.DownloadFileCompleted += DownloadCompleted;
                webClient.DownloadFileAsync(new Uri(videoInfo.DownloadUrl), filepath);
                Timer t = new Timer();
                t.Start();
                t.Interval = DownloadTimeout;
                t.Elapsed += delegate { webClient.CancelAsync(); };
            }
            catch (WebException ex)
            {
                logger.Error(ex.Status);
                logger.Error(ex.Response);
            }

            return false;
        }
Beispiel #10
0
        public VideoInfo GetInfo( String url )
        {
            String vid = strUtil.TrimStart( url, "http://v.youku.com/v_show/id_" );
            vid = strUtil.TrimEnd( vid, ".html" );

            String flashUrl = string.Format( "http://player.youku.com/player.php/sid/{0}/v.swf", vid );

            VideoInfo vi = new VideoInfo();
            vi.PlayUrl = url;
            vi.FlashUrl = flashUrl;
            vi.FlashId = vid;

            try {
                String pageBody = PageLoader.Download( url );

                Match mt = Regex.Match( pageBody, "<title>([^<]+?)</title>" );
                String title = VideoHelper.GetTitle( mt.Groups[1].Value );

                Match m = Regex.Match( pageBody, "pic=(http://[^:]+?.ykimg.com.+?)\"" );

                String picUrl = m.Groups[1].Value;

                vi.Title = title;
                vi.PicUrl = picUrl;

                return vi;

            }
            catch (Exception ex) {
                logger.Error( "getUrl=" + url );
                logger.Error( ex.Message );
                return vi;
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Uri ur = new Uri("http://gdata.youtube.com/feeds/api/videos/fSgGV1llVHM&f=gdata_playlists&c=ytapi-DukaIstvan-MyYouTubeVideosF-d1ogtvf7-0&d=U1YkMvELc_arPNsH4kYosmD9LlbsOl3qUImVMV6ramM");
              YouTubeQuery query = new YouTubeQuery("http://gdata.youtube.com/feeds/api/channels?q=vevo");

              YouTubeFeed videoFeed = service.Query(query);
              YouTubeEntry en = (YouTubeEntry)videoFeed.Entries[0];

              Video video = request.Retrieve<Video>(new Uri("http://gdata.youtube.com/feeds/api/videos/" + en.VideoId));
              Feed<Comment> comments = request.GetComments(video);
            string cm = "";
            foreach (Comment c in comments.Entries)
            {
              cm +=  c.Content + "\n------------------------------------------\n";
            }

              VideoInfo info = new VideoInfo();
              info.Get("yUHNUjEs7rQ");
              //Video v = request.Retrieve<Video>(videoEntryUrl);

              //Feed<Comment> comments = request.GetComments(v);

              //string cm = "";
              //foreach (Comment c in comments.Entries)
              //{
              //  cm += c.Author + c.Content + "------------------------------------------";
              //}
        }
Beispiel #12
0
        public static VideoInfo TryReadVideoInfoViaAviHeader(string fileName)
        {
            var info = new VideoInfo { Success = false };

            try
            {
                using (var rp = new RiffParser())
                {
                    if (rp.TryOpenFile(fileName) && rp.FileType == RiffParser.ckidAVI)
                    {
                        var dh = new RiffDecodeHeader(rp);
                        dh.ProcessMainAVI();
                        info.FileType = RiffParser.FromFourCC(rp.FileType);
                        info.Width = dh.Width;
                        info.Height = dh.Height;
                        info.FramesPerSecond = dh.FrameRate;
                        info.TotalFrames = dh.TotalFrames;
                        info.TotalMilliseconds = dh.TotalMilliseconds;
                        info.TotalSeconds = info.TotalMilliseconds / TimeCode.BaseUnit;
                        info.VideoCodec = dh.VideoHandler;
                        info.Success = true;
                    }
                }
            }
            catch
            {
            }
            return info;
        }
Beispiel #13
0
        public EncodeInfo()
        {
            JobName = string.Empty;
            InputFile = string.Empty;
            Input = InputType.InputUndefined;
            OutputFile = string.Empty;
            AudioStreams = new List<AudioInfo>();
            SubtitleStreams = new List<SubtitleInfo>();
            Chapters = new List<TimeSpan>();
            NextStep = EncodingStep.NotSet;
            CompletedStep = EncodingStep.NotSet;
            MediaInfo = null;
            VideoStream = new VideoInfo();
            StereoVideoStream = new StereoVideoInfo();
            StreamId = int.MinValue;
            TrackId = int.MinValue;
            TempInput = string.Empty;
            TempOutput = string.Empty;
            DumpOutput = string.Empty;
            SelectedDvdChapters = string.Empty;
            TempFiles = new List<string>();
            ExitCode = int.MinValue;

            FfIndexFile = string.Empty;
            AviSynthScript = string.Empty;
            AviSynthStereoConfig = string.Empty;
        }
Beispiel #14
0
 public OsdbSearchSubtitleResponse SearchSubtitles(string token, VideoInfo[] videoInfoList)
 {
     lock (SyncRoot)
     {
         return _proxy.SearchSubtitles(token, videoInfoList);
     }
 }
Beispiel #15
0
 /// <summary>
 /// 添加视频
 /// </summary>
 /// <param name="model"></param>
 /// <returns>返回VideoId</returns>
 public static int Insert(VideoInfo model) {
     string strSQL = "INSERT INTO Videos(CategoryId,Title,Remark,VideoUrl,ImageUrl,IsTop,Tags,PublishDateTime,IsDeleted) VALUES(@CategoryId,@Title,@Remark,@VideoUrl,@ImageUrl,@IsTop,@Tags,@PublishDateTime,@IsDeleted);SELECT @@IDENTITY;";
     SqlParameter[] parms = { 
                             new SqlParameter("Id",SqlDbType.Int),
                             new SqlParameter("CategoryId",SqlDbType.Int),
                             new SqlParameter("Title",SqlDbType.NVarChar),
                             new SqlParameter("Remark",SqlDbType.NVarChar),
                             new SqlParameter("VideoUrl",SqlDbType.NVarChar),
                             new SqlParameter("ImageUrl",SqlDbType.NVarChar),
                             new SqlParameter("IsTop",SqlDbType.Int),
                             new SqlParameter("Tags",SqlDbType.NVarChar),
                             new SqlParameter("PublishDateTime",SqlDbType.DateTime),
                             new SqlParameter("IsDeleted",SqlDbType.Int),
                            };
     parms[0].Value = model.Id;
     parms[1].Value = model.CategoryId;
     parms[2].Value = string.IsNullOrEmpty(model.Title) ? string.Empty : model.Title;
     parms[3].Value = string.IsNullOrEmpty(model.Remark) ? string.Empty : model.Remark;
     parms[4].Value = string.IsNullOrEmpty(model.VideoUrl) ? string.Empty : model.VideoUrl;
     parms[5].Value = string.IsNullOrEmpty(model.ImageUrl) ? string.Empty : model.ImageUrl;
     parms[6].Value = model.IsTop ? 1 : 0;
     parms[7].Value = string.IsNullOrEmpty(model.Tags) ? string.Empty : model.Tags;
     parms[8].Value = model.PublishDateTime;
     parms[9].Value = model.IsDeleted ? 1 : 0;
     return Convert.ToInt32(SQLPlus.ExecuteScalar(CommandType.Text,strSQL,parms));
 }
 public VideoInfo(VideoInfo info)
 {
     Init();
     this.Entry = info.Entry;
     this.Quality = info.Quality;
     this.Date = info.Date;
 }
    private void UploadFile(string filetype)
    {
        if (filetype == "VIDEO") //TODO:CONFIG
            RadUpload1.TargetFolder = ConfigurationManager.AppSettings["VideoUploadPath"].ToString(); //TODO:CONFIG
        if (filetype == "AUDIO") //TODO:CONFIG
            RadUpload1.TargetFolder = ConfigurationManager.AppSettings["AudioUploadPath"].ToString(); //TODO:CONFIG
        if (filetype != "")
        {
            string path = string.Empty;
            string name = hdnName.Value;
            string fn = System.IO.Path.GetFileName(name);
            string extension = fn.Substring(fn.IndexOf("."));
            string savefile = Guid.NewGuid().ToString() + extension;
            string SaveLocation = path + savefile;
            //FileUpload.PostedFile.SaveAs(SaveLocation);
            //Session["FileName"] = savefile;
            WebClient Client = new WebClient();
            //RadUpload1.AllowedFileExtensions = {'.flv'};
            //Client.UploadFile(Server.MapPath(RadUpload1.TargetFolder) + savefile, name);
            Client.UploadFile(RadUpload1.TargetFolder + savefile, name);
            //Session.Remove("PostedFile");

            //Make database entry.
            //if (FilePathFileUpload.HasFile)
            //{
            VideoInfo entity = new VideoInfo();
            //string appPath = Server.MapPath(ConfigurationManager.AppSettings.Get("VideoUploadPath"));
            //string extension = FilePathFileUpload.PostedFile.FileName.Substring(FilePathFileUpload.PostedFile.FileName.LastIndexOf("."));
            //entity.FilePath = System.Guid.NewGuid().ToString() + extension;
            //FilePathFileUpload.SaveAs(appPath + entity.FilePath);
            //if (Session["FileName"] != null)
            if (savefile != "")
            {
                //entity.FilePath = Session["FileName"].ToString();
                //Session["FileName"] = null;
                entity.FilePath = savefile;
            }
            entity.ClassId = this.ClassId;
            entity.Title = TitleTextBox.Text;
            entity.Description = DescriptionTextBox.Value;
            //entity.Speakers = SpeakerTextBox.Text;
            entity.Visible = VisibleCheckBox.Checked;
            entity.CreatedTimestamp = DateTime.Now;
            entity.UpdatedTimestamp = DateTime.Now;

            bool result = VideoInfo.InsertVideo(ref entity);

            if (result)
            {
                //CreateVideoDialog.Reset();
                DataBind();
                OnVideoCreated(EventArgs.Empty);
                entity = null;
                //Session.Remove("FileName");
                Response.Redirect(this.Page.Request.Url.AbsoluteUri);
            }
        }


    }
Beispiel #18
0
    protected void CreateVideoDialog_OkButtonClicked(object sender, EventArgs e)
    {
        //Upload file.
        if (UploadFile())
        {
            Page.Validate("create_video");
            if (Page.IsValid)
            {
                if (this.ClassId > 0)
                {
                    //if (FilePathFileUpload.HasFile)
                    //{
                    if (RadUpload1.UploadedFiles.Count > 0)
                    {


                        VideoInfo entity = new VideoInfo();
                        if (savefile != "")
                        {
                            entity.FilePath = savefile;
                        }
                        else
                        {
                            entity.FilePath = "";
                        }
                        entity.ClassId = this.ClassId;
                        entity.Title = TitleTextBox.Text;
                        entity.Description = DescriptionTextBox.Value;
                        entity.Visible = VisibleCheckBox.Checked;
                        entity.CreatedTimestamp = DateTime.Now;
                        entity.UpdatedTimestamp = DateTime.Now;

                        bool result = VideoInfo.InsertVideo(ref entity);

                        if (result)
                        {
                            DataBind();
                            OnVideoCreated(EventArgs.Empty);
                            entity = null;
                            Response.Redirect("~/Admin/Classroom/Videos.aspx?ClassId=" + this.ClassId);
                        }

                    }
                }
                else
                {
                    ValidationHelper.SetFocusToFirstError(this.Page, "create_video");
                }

            }
            else
            {
                ValidationHelper.SetFocusToFirstError(this.Page, "create_video");
            }
        }
        else
        {
            ValidationHelper.SetFocusToFirstError(this.Page, "create_video");
        }
    }
Beispiel #19
0
        private static VideoInfo TryReadVideoInfoViaMatroskaHeader(string fileName)
        {
            var info = new VideoInfo { Success = false };

            try
            {
                bool hasConstantFrameRate = false;
                bool success = false;
                double frameRate = 0;
                int width = 0;
                int height = 0;
                double milliseconds = 0;
                string videoCodec = string.Empty;

                var matroskaParser = new Matroska();
                matroskaParser.GetMatroskaInfo(fileName, ref success, ref hasConstantFrameRate, ref frameRate, ref width, ref height, ref milliseconds, ref videoCodec);
                if (success)
                {
                    info.Width = width;
                    info.Height = height;
                    info.FramesPerSecond = frameRate;
                    info.Success = true;
                    info.TotalMilliseconds = milliseconds;
                    info.TotalSeconds = milliseconds / 1000.0;
                    info.TotalFrames = info.TotalSeconds * frameRate;
                    info.VideoCodec = videoCodec;
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
            return info;
        }
Beispiel #20
0
        protected override List<SubtitleInfo> DoGetSubtitles(VideoInfo vi)
        {
            List<SubtitleInfo> retVal = new List<SubtitleInfo>();

            SearchResult res = _wsdl.searchSubtitles(_sessionToken, vi.moviehash, (long)vi.moviebytesize, vi.sublanguageid, vi.imdbid);
            if (res.data != null && res.data.Length > 0)
            {
                foreach (SubtitleData sd in res.data)
                {
                    SubtitleInfo si = new SubtitleInfo();

                    si.IDSubtitleFile = sd.subID.ToString();
                    si.SubFileName = sd.subName;
                    si.MovieName = sd.movieName;
                    si.SubHash = sd.subHash;

                    si.LanguageName = OPMedia.Core.Language.ThreeLetterISOLanguageNameToEnglishName(sd.subLang);

                    si.MovieHash = vi.moviehash;
                    si.SubDownloadLink = sd.subDownloadLink;
                    si.SubFormat = sd.subFormat;

                    retVal.Add(si);
                }
            }

            return retVal;
        }
Beispiel #21
0
        public VideoInfo GetInfo( String url ) {

            String vid = strUtil.TrimStart( url, "http://www.tudou.com/programs/view/" ).TrimEnd( '/' );

            String flashUrl = string.Format( "http://www.tudou.com/v/{0}/v.swf", vid );

            VideoInfo vi = new VideoInfo();
            vi.PlayUrl = url;
            vi.FlashId = vid;
            vi.FlashUrl = flashUrl;

            try {
                String pageBody = PageLoader.Download( url );

                Match mt = Regex.Match( pageBody, "<title>([^<]+?)</title>" );
                String title = VideoHelper.GetTitle( mt.Groups[1].Value );

                Match m = Regex.Match( pageBody, "thumbnail[^']+?'([^']+?)'" );
                String picUrl = m.Groups[1].Value;

                vi.Title = title;
                vi.PicUrl = picUrl;

                return vi;

            }
            catch (Exception ex) {

                logger.Error( "getUrl=" + url );
                logger.Error( ex.Message );

                return vi;
            }

        }
        public override List<VideoInfo> GetVideos(Category category)
        {
            List<VideoInfo> listVideos = new List<VideoInfo>();
            string url = (category as RssLink).Url;
            string webData = GetWebData((category as RssLink).Url);

            Regex r = new Regex(@"href=""(?<url>[^""]*)""></a><span\sclass=""play_video""></span>\s*<img\ssrc=""(?<thumb>[^""]*)""\swidth=""120""\sheight=""90""\salt=""""\s/>\s*</div>\s*<p>\s*<strong>(?<title>[^<]*)</strong>\s*<span>(?<description>[^<]*)<br/>(?<description2>[^<]*)</span>\s*</p>",
                    RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);

            Match m = r.Match(webData);
            while (m.Success)
            {
                VideoInfo video = new VideoInfo()
                {
                    VideoUrl = m.Groups["url"].Value,
                    Title = m.Groups["title"].Value,
                    Thumb = m.Groups["thumb"].Value,
                    Description = m.Groups["description"].Value.Trim() + "\n" + m.Groups["description2"].Value.Trim()
                };

                listVideos.Add(video);
                m = m.NextMatch();
            }

            return listVideos;
        }
Beispiel #23
0
        public VideoInfo GetInfo( string playUrl )
        {
            VideoInfo vi = new VideoInfo();
            vi.PlayUrl = playUrl;

            try {

                String pageBody = PageLoader.Download( playUrl );

                Match mt = Regex.Match( pageBody, "video : {(" + "." + "+?)\\}[^,]", RegexOptions.Singleline );
                String strJson = "{" + mt.Groups[1].Value + "}";

                Dictionary<String, Object> dic = JSON.ToDictionary( strJson );

                vi.PicUrl = dic.ContainsKey( "pic" ) ? dic["pic"].ToString() : "";
                vi.FlashUrl = dic.ContainsKey( "swfOutsideUrl" ) ? dic["swfOutsideUrl"].ToString() : "";
                vi.Title = dic.ContainsKey( "title" ) ? dic["title"].ToString() : "";

                return vi;

            }
            catch (Exception ex) {

                logger.Error( "getUrl=" + playUrl );
                logger.Error( ex.Message );

                return vi;
            }
        }
Beispiel #24
0
        public VideoInfo GetInfo( string playUrl ) {

            String[] arrItem = strUtil.TrimEnd( playUrl, ".shtml" ).Split( '/' );
            String flashId = arrItem[arrItem.Length - 1];

            VideoInfo vi = new VideoInfo();
            vi.PlayUrl = playUrl;
            vi.FlashId = flashId;
            vi.FlashUrl = string.Format( "http://v.ifeng.com/include/exterior.swf?guid={0}&AutoPlay=false", flashId );


            try {
                String pageBody = PageLoader.Download( playUrl, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)", "utf-8" );

                Match mt = Regex.Match( pageBody, "var videoinfo=({.+?});" );
                String strJson = mt.Groups[1].Value;

                Dictionary<String, Object> dic = JSON.ToDictionary( strJson );

                vi.PicUrl = dic.ContainsKey( "img" ) ? dic["img"].ToString() : "";
                vi.Title = dic.ContainsKey( "name" ) ? dic["name"].ToString() : "";


                return vi;
            }
            catch (Exception ex) {
                logger.Error( "getUrl=" + playUrl );
                logger.Error( ex.Message );
                return vi;
            }


        }
Beispiel #25
0
        public VideoInfo GetInfo( String url )
        {
            String vid = strUtil.TrimStart( url, "http://v.ku6.com/show/" );
            vid = strUtil.TrimEnd( vid, ".html" );

            String flashUrl = string.Format( "http://player.ku6.com/refer/{0}/v.swf", vid );

            VideoInfo vi = new VideoInfo();
            vi.PlayUrl = url;
            vi.FlashUrl = flashUrl;
            vi.FlashId = vid;

            try {
                String pageBody = PageLoader.Download( url );

                Match mt = Regex.Match( pageBody, "<title>([^<]+?)</title>" );
                String title = VideoHelper.GetTitle( mt.Groups[1].Value );

                Match m = Regex.Match( pageBody, "<span class=\"s_pic\">([^<]+?)</span>" );
                String picUrl = m.Groups[1].Value;

                vi.Title = title;
                vi.PicUrl = picUrl;

                return vi;
            }
            catch (Exception ex) {
                logger.Error( "getUrl=" + url );
                logger.Error( ex.Message );
                return vi;
            }
        }
Beispiel #26
0
 /// <summary>
 /// 更新视频
 /// </summary>
 /// <param name="model">返回影响的行数</param>
 public static int Update(VideoInfo model) {
     string strSQL = "UPDATE Videos SET CategoryId = @CategoryId ,Title = @Title,Remark = @Remark,VideoUrl = @VideoUrl,ImageUrl = @ImageUrl,IsTop = @IsTop,Tags = @Tags ,PublishDateTime = @PublishDateTime ,IsDeleted = @IsDeleted WHERE Id = @Id";
     SqlParameter[] parms = { 
                             new SqlParameter("Id",SqlDbType.Int),
                             new SqlParameter("CategoryId",SqlDbType.Int),
                             new SqlParameter("Title",SqlDbType.NVarChar),
                             new SqlParameter("Remark",SqlDbType.NVarChar),
                             new SqlParameter("VideoUrl",SqlDbType.NVarChar),
                             new SqlParameter("ImageUrl",SqlDbType.NVarChar),
                             new SqlParameter("IsTop",SqlDbType.Int),
                             new SqlParameter("Tags",SqlDbType.NVarChar),
                             new SqlParameter("PublishDateTime",SqlDbType.DateTime),
                             new SqlParameter("IsDeleted",SqlDbType.Int),
                            };
     parms[0].Value = model.Id;
     parms[1].Value = model.CategoryId;
     parms[2].Value = string.IsNullOrEmpty(model.Title) ? string.Empty : model.Title;
     parms[3].Value = string.IsNullOrEmpty(model.Remark) ? string.Empty : model.Remark;
     parms[4].Value = string.IsNullOrEmpty(model.VideoUrl) ? string.Empty : model.VideoUrl;
     parms[5].Value = string.IsNullOrEmpty(model.ImageUrl) ? string.Empty : model.ImageUrl;
     parms[6].Value = model.IsTop ? 1 : 0;
     parms[7].Value = string.IsNullOrEmpty(model.Tags) ? string.Empty : model.Tags;
     parms[8].Value = model.PublishDateTime;
     parms[9].Value = model.IsDeleted ? 1 : 0;
     return SQLPlus.ExecuteNonQuery(CommandType.Text, strSQL, parms);
 }
        public static int Delete(Database db, int id)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                DataSet dataSet = GetVideoInfoById(db, id);
                if (dataSet.Tables[0].Rows.Count == 0)
                {
                    return 0;
                }
                //删除相应的文件
                VideoInfo videoInfo;
                foreach (DataRow dr in dataSet.Tables[0].Rows)
                {

                    videoInfo = new VideoInfo(dr);
                    if (File.Exists(videoInfo.FilePath))
                    {
                        File.Delete(videoInfo.FilePath);
                    }
                }
                //删除出数据库中的记录
                sb.Append("delete from VideoInfo ");
                sb.AppendFormat(" where Id={0}", id);
                string cmdText = sb.ToString();
                return db.ExecuteNonQuery(CommandType.Text, cmdText);

            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
        public static TraktEpisodeScrobble CreateEpisodeScrobbleData(VideoInfo info)
        {
            try
            {
                // create scrobble data
                TraktEpisodeScrobble scrobbleData = new TraktEpisodeScrobble
                {
                    Title = info.Title,
                    Year = info.Year,
                    Season = info.SeasonIdx,
                    Episode = info.EpisodeIdx,
                    PluginVersion = TraktSettings.Version,
                    MediaCenter = "Mediaportal",
                    MediaCenterVersion = System.Reflection.Assembly.GetEntryAssembly().GetName().Version.ToString(),
                    MediaCenterBuildDate = String.Empty,
                    UserName = TraktSettings.Username,
                    Password = TraktSettings.Password
                };

                return scrobbleData;
            }
            catch (Exception e)
            {
                TraktLogger.Error("Error creating scrobble data: {0}", e.Message);
                return null;
            }
        }
        public void AttributeDiscriminator_SerializeVideo()
        {
            var r = new VideoInfo() { ResourceProperty = "Maestro", VideoProperty = "Soy Video" };

            var xml = InheritanceSerializer.Serialize(r);

            Assert.AreEqual(videoResourceXml, xml);
        }
 public static Info GetInfo(VideoInfo video)
 {
     Info inf = new Info();
     inf.VideoFileName = RemoveIllegalPathCharacters(video.Title) + video.VideoExtension;
     inf.isExternalAudio = video.AudioBitrate == 0;
     inf.AudioFileName = RemoveIllegalPathCharacters(video.Title) + ".audio"+video.VideoExtension;
     return inf;
 }
        public override string getUrl(VideoInfo video)
        {
            String baseWebData = GetWebData(video.VideoUrl, null, null, null, true);
            String playerJs    = GetWebData(SlovenskaTeleviziaUtil.playerJsUrl, null, video.VideoUrl, null, true);

            video.PlaybackOptions = new Dictionary <string, string>();

            int startIndex = baseWebData.IndexOf(SlovenskaTeleviziaUtil.videoStart);

            if (startIndex >= 0)
            {
                int endIndex = baseWebData.IndexOf(SlovenskaTeleviziaUtil.videoEnd, startIndex);
                if (endIndex >= 0)
                {
                    String videoData = baseWebData.Substring(startIndex, endIndex - startIndex);

                    Match match = Regex.Match(videoData, SlovenskaTeleviziaUtil.videoStreamRegex);
                    if (match.Success)
                    {
                        String streamId = match.Groups["streamId"].Value;

                        startIndex = playerJs.IndexOf(SlovenskaTeleviziaUtil.videoUrlFormatStart);
                        if (startIndex >= 0)
                        {
                            endIndex = playerJs.IndexOf(SlovenskaTeleviziaUtil.videoUrlFormatEnd, startIndex);
                            if (endIndex >= 0)
                            {
                                String playerData = playerJs.Substring(startIndex, endIndex - startIndex);

                                match = Regex.Match(playerData, SlovenskaTeleviziaUtil.videoUrlFormatRegex);
                                if (match.Success)
                                {
                                    String videoUrlPart1 = match.Groups["videoUrlPart1"].Value;
                                    String videoUrlPart2 = match.Groups["videoUrlPart2"].Value;

                                    String rtmpUrl    = videoUrlPart1 + streamId + videoUrlPart2;
                                    String streamPart = "mp4:" + streamId;

                                    String playPath = rtmpUrl.Substring(rtmpUrl.IndexOf(streamPart));
                                    String tcUrl    = rtmpUrl.Remove(rtmpUrl.IndexOf(streamPart) - 1, streamPart.Length + 1);
                                    String app      = tcUrl.Substring(tcUrl.IndexOf("/", tcUrl.IndexOf("/") + 2) + 1);

                                    String resultUrl = new OnlineVideos.MPUrlSourceFilter.RtmpUrl(rtmpUrl)
                                    {
                                        TcUrl = tcUrl, App = app, PlayPath = playPath
                                    }.ToString();

                                    video.PlaybackOptions.Add(video.Title, resultUrl);
                                }
                            }
                        }
                    }
                }
            }

            //Match match = Regex.Match(baseWebData, SlovenskaTeleviziaUtil.flashVarsRegex);
            //if (match.Success)
            //{
            //    baseWebData = GetWebData(match.Groups["playListFile"].Value.Replace("%26", "&"), null, null, null, true).Replace("xmlns=\"http://xspf.org/ns/0/\"", "");
            //    XmlDocument movieData = new XmlDocument();
            //    movieData.LoadXml(baseWebData);

            //    XmlNode location = movieData.SelectSingleNode("//location");
            //    XmlNode stream = movieData.SelectSingleNode("//meta[@rel = \"streamer\"]");

            //    if ((location != null) && (stream != null))
            //    {
            //        String movieUrl = stream.InnerText + "/" + location.InnerText;

            //        string host = String.Empty;
            //        string port = "1935";
            //        string firstSlash = movieUrl.Substring(movieUrl.IndexOf(":") + 3, movieUrl.IndexOf("/", movieUrl.IndexOf(":") + 3) - (movieUrl.IndexOf(":") + 3));

            //        String[] parts = firstSlash.Split(':');
            //        if (parts.Length == 2)
            //        {
            //            // host name and port
            //            host = parts[0];
            //            port = parts[1];
            //        }
            //        else
            //        {
            //            host = firstSlash;
            //        }

            //        string app = movieUrl.Substring(movieUrl.IndexOf("/", host.Length) + 1, movieUrl.IndexOf("/", movieUrl.IndexOf("/", host.Length) + 1) - movieUrl.IndexOf("/", host.Length) - 1);
            //        string tcUrl = "rtmp://" + host + "/" + app;
            //        string playPath = "mp4:" + movieUrl.Substring(movieUrl.IndexOf(app) + app.Length + 1);

            //        string resultUrl = new OnlineVideos.MPUrlSourceFilter.RtmpUrl(movieUrl) { TcUrl = tcUrl, App = app, PlayPath = playPath }.ToString();

            //        video.PlaybackOptions.Add(video.Title, resultUrl);
            //    }
            //}

            if (video.PlaybackOptions != null && video.PlaybackOptions.Count > 0)
            {
                var enumer = video.PlaybackOptions.GetEnumerator();
                enumer.MoveNext();
                return(enumer.Current.Value);
            }
            return("");
        }
Beispiel #32
0
        private async void BT_Start_Click(object sender, RoutedEventArgs e)
        {
            string originalButtonContent = (string)BT_Start.Content;

            BT_Start.Content   = "This process take a while...";
            BT_Start.IsEnabled = false;
            string path = TBX_Path.Text;

            if (File.Exists(path))
            {
                PB_Main.Visibility      = Visibility.Visible;
                PB_Main.IsIndeterminate = true;
                if (Directory.Exists("pre-process"))
                {
                    Directory.Delete("pre-process", true);
                }
                Directory.CreateDirectory("pre-process");
                var uri    = new System.Uri(GetLocalFullPath("complete.wav"));
                var player = new MediaPlayer
                {
                    Volume = 0
                };
                player.Open(uri);
                var    video       = new VideoInfo(path);
                int    totalFrames = 0;
                double fps         = video.FrameRate;
                string ffmpegPath  = GetLocalFullPath("assets\\x86\\ffmpeg.exe");
                string ffprobePath = GetLocalFullPath("assets\\x86\\ffprobe.exe");
                string ffmpegArgs  = $"-i \"{path}\" -vf fps={fps} \"{GetLocalFullPath("pre-process\\out%07d.png")}\"";
                string ffprobeArgs = $"-i \"{path}\" -print_format json -loglevel fatal -show_streams -count_frames -select_streams v";

                string dainPath       = GetLocalFullPath("assets\\dain-ncnn-vulkan.exe");
                string dainInputPath  = GetLocalFullPath("pre-process");
                string dainOutputPath = GetLocalFullPath("output-frames");
                string audioPath      = GetLocalFullPath("output.mp3");

                FileInfo outputFileWithAudio = new FileInfo(GetLocalFullPath("output.mp4"));
                string   ffmpegJoinArgs      = $"-r {fps*2} -i \"{dainOutputPath}\\%08d.png\" -i \"{audioPath}\" \"{outputFileWithAudio}\" -c:a copy -c:v libx264 -pix_fmt yuv420p -crf 24 -y";

                ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController");
                int gpuCount = 0;
                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["CurrentBitsPerPixel"] != null && obj["CurrentHorizontalResolution"] != null)
                    {
                        gpuCount++;
                    }
                }
                StringBuilder graphicsOptionBuilder = new StringBuilder();
                for (int i = 0; i < gpuCount; i++)
                {
                    graphicsOptionBuilder.Append(i.ToString());
                    if (i != gpuCount - 1)
                    {
                        graphicsOptionBuilder.Append(",");
                    }
                }

                string   dainArgs      = $"-i \"{dainInputPath}\" -o \"{dainOutputPath}\" -g {graphicsOptionBuilder} -v";
                FileInfo audioFileInfo = null;
                await Task.Run(() =>
                {
                    if (File.Exists(audioPath))
                    {
                        File.Delete(audioPath);
                    }
                    audioFileInfo         = new FFMpeg().ExtractAudio(video, new FileInfo(audioPath));
                    ProcessStartInfo info = new ProcessStartInfo(ffmpegPath, ffmpegArgs);
                    StartProcess(info);
                });

                await Task.Run(() =>
                {
                    ProcessStartInfo info       = new ProcessStartInfo(ffprobePath, ffprobeArgs);
                    info.RedirectStandardOutput = true;
                    info.UseShellExecute        = false;
                    info.WindowStyle            = ProcessWindowStyle.Hidden;
                    var process = Process.Start(info);
                    childs.Add(process);
                    process.WaitForExit();

                    string infoStr = process.StandardOutput.ReadToEnd();
                    var videoInfo  = JsonConvert.DeserializeObject <JsonArgs.VideoInfo.Root>(infoStr);
                    int.TryParse(videoInfo.streams[0].nb_frames, out totalFrames);
                });

                if (Directory.Exists("output-frames"))
                {
                    Directory.Delete("output-frames", true);
                }
                Directory.CreateDirectory("output-frames");
                bool isCompleted = false;
                await Task.Run(async() =>
                {
                    ProcessStartInfo info = new ProcessStartInfo(dainPath, dainArgs);
                    await Dispatcher.InvokeAsync(() => {
                        PB_Main.IsIndeterminate = false;
                    });
                    _ = Task.Run(async() =>
                    {
                        while (!isCompleted)
                        {
                            int maxFrame      = totalFrames * 2;
                            int currentFrame  = Directory.GetFiles("output-frames").Length; await Task.Delay(1000);
                            double percentage = ((double)currentFrame / maxFrame) * 100.0;
                            await Dispatcher.InvokeAsync(() =>
                            {
                                PB_Main.Value = percentage;
                            });
                            await Task.Delay(500);
                        }
                    });
                    StartProcess(info);
                    isCompleted = true;
                    await Dispatcher.InvokeAsync(() =>
                    {
                        PB_Main.IsIndeterminate = true;
                    });
                });

                Directory.Delete(GetLocalFullPath("pre-process"), true);
                Clipboard.SetText("\"" + ffmpegPath + "\" " + ffmpegJoinArgs);
                await Task.Run(() =>
                {
                    ProcessStartInfo info = new ProcessStartInfo(ffmpegPath, ffmpegJoinArgs);
                    StartProcess(info);
                    File.Delete(audioFileInfo.FullName);
                    Directory.Delete(GetLocalFullPath("output-frames"), true);
                    File.Delete(audioPath);
                });

                player.Volume = 1;
                player.Play();
                PB_Main.Visibility = Visibility.Collapsed;

                string         outputDefaultFileName = System.IO.Path.GetFileNameWithoutExtension(path);
                SaveFileDialog sfd = new SaveFileDialog
                {
                    DefaultExt = "mp4",
                    Filter     = "Video file (*.mp4)|*.mp4|All files (*.*)|*.*",
                    FileName   = $"{outputDefaultFileName}-2x.mp4"
                };
                if (sfd.ShowDialog() == true)
                {
                    File.Move(outputFileWithAudio.FullName, sfd.FileName);
                }
                else
                {
                    outputFileWithAudio.Delete();
                }

                BT_Start.IsEnabled = true;
                BT_Start.Content   = originalButtonContent;
            }
            else
            {
                MessageBox.Show("Target file does not exist", "Error", MessageBoxButton.OK, MessageBoxImage.Error); BT_Start.IsEnabled = true;
            }
        }
Beispiel #33
0
        public override List <VideoInfo> GetVideos(Category category)
        {
            List <VideoInfo> res = new List <VideoInfo>();

            string[] myString = category.Other.ToString().Split(',');
            if (myString[0] == "drlive")
            {
                return(getlivestreams());
            }

            if (myString[0] == "search")
            {
                string url = baseUrlDrNu + "/search/tv/programcards-with-asset/title/" + myString[1] + "?limit=75";
                Log.Debug("DR NU url: " + url);
                string  json        = GetWebData(url);
                JObject contentData = JObject.Parse(json);
                return(getVideos(contentData));
            }

            if (myString[0] == "drnulist_card")
            {
                string url = baseUrlDrNu + "/list/" + myString[1] + "?limit=75";
                Log.Debug("DR NU url: " + url);
                string  json        = GetWebData(url);
                JObject contentData = JObject.Parse(json);
                return(getVideos(contentData));
            }

            if (myString[0] == "drnulastchance")
            {
                string url = baseUrlDrNu + "/list/view/LastChance?limit=10";
                Log.Debug("DR NU url: " + url);
                string  json        = GetWebData(url);
                JObject contentData = JObject.Parse(json);
                return(getVideos(contentData));
            }

            if (myString[0] == "drnumostviewed")
            {
                string url = baseUrlDrNu + "/list/view/mostviewed?limit=10";
                Log.Debug("DR NU url: " + url);
                string  json        = GetWebData(url);
                JObject contentData = JObject.Parse(json);
                return(getVideos(contentData));
            }

            if (myString[0] == "drnuspot")
            {
                string url = baseUrlDrNu + "/list/view/selectedlist?limit=10";
                Log.Debug("DR NU url: " + url);
                string  json        = GetWebData(url);
                JObject contentData = JObject.Parse(json);
                return(getVideos(contentData));
            }

            if (myString[0] == "bonanza")
            {
                string url  = ((RssLink)category).Url;
                string data = GetWebData(url);
                if (data.Length > 0)
                {
                    Match m = regEx_bonanzaVideolist.Match(data);
                    while (m.Success)
                    {
                        VideoInfo videoInfo = new VideoInfo()
                        {
                            Title = m.Groups["title"].Value, Length = m.Groups["length"].Value, Thumb = m.Groups["thumb"].Value
                        };

                        var info = JObject.Parse(HttpUtility.HtmlDecode(m.Groups["url"].Value));
                        if (info != null)
                        {
                            videoInfo.Description = info.Value <string>("Description");
                            DateTime parsedDate;
                            if (DateTime.TryParse(info.Value <string>("FirstPublished"), out parsedDate))
                            {
                                videoInfo.Airdate = parsedDate.ToString("g", OnlineVideoSettings.Instance.Locale);
                            }
                            foreach (var file in info["Files"])
                            {
                                if (file.Value <string>("Type").StartsWith("Video"))
                                {
                                    videoInfo.VideoUrl += (videoInfo.VideoUrl.Length > 0 ? "|" : "") + file.Value <string>("Type").Substring(5) + "+" + file.Value <string>("Location");
                                }
                            }
                            res.Add(videoInfo);
                        }
                        m = m.NextMatch();
                    }
                }
            }
            return(res);
        }
Beispiel #34
0
        private VideoInfo ParseVideoInfoInternal(VideoInfo info, string probeOutput)
        {
            var metadata = JsonConvert.DeserializeObject <FFMpegStreamMetadata>(probeOutput);

            if (metadata.Streams == null || metadata.Streams.Count == 0)
            {
                throw new FFMpegException(FFMpegExceptionType.File, $"No video or audio streams could be detected. Source: ${info.FullName}");
            }

            var video = metadata.Streams.Find(s => s.CodecType == "video");
            var audio = metadata.Streams.Find(s => s.CodecType == "audio");

            double videoSize = 0d;
            double audioSize = 0d;

            string   sDuration = (video ?? audio).Duration;
            TimeSpan duration  = TimeSpan.Zero;

            if (sDuration != null)
            {
                duration = TimeSpan.FromSeconds(double.TryParse(sDuration, NumberStyles.Any, CultureInfo.InvariantCulture, out var output) ? output : 0);
            }
            else
            {
                sDuration = (video ?? audio).Tags.Duration;
                if (sDuration != null)
                {
                    TimeSpan.TryParse(sDuration.Remove(sDuration.LastIndexOf('.') + 8), CultureInfo.InvariantCulture, out duration); // TimeSpan fractions only allow up to 7 digits
                }
            }
            info.Duration = duration;

            if (video != null)
            {
                var bitRate           = Convert.ToDouble(video.BitRate, CultureInfo.InvariantCulture);
                var fr                = video.FrameRate.Split('/');
                var commonDenominator = FFProbeHelper.Gcd(video.Width, video.Height);

                videoSize = bitRate * duration.TotalSeconds / BITS_TO_MB;

                info.VideoFormat = video.CodecName;
                info.Width       = video.Width;
                info.Height      = video.Height;
                info.FrameRate   = Math.Round(
                    Convert.ToDouble(fr[0], CultureInfo.InvariantCulture) /
                    Convert.ToDouble(fr[1], CultureInfo.InvariantCulture),
                    3);
                info.Ratio = video.Width / commonDenominator + ":" + video.Height / commonDenominator;
            }
            else
            {
                info.VideoFormat = "none";
            }

            if (audio != null)
            {
                var bitRate = Convert.ToDouble(audio.BitRate, CultureInfo.InvariantCulture);
                info.AudioFormat = audio.CodecName;
                audioSize        = bitRate * duration.TotalSeconds / BITS_TO_MB;
            }
            else
            {
                info.AudioFormat = "none";
            }

            info.Size = Math.Round(videoSize + audioSize, 2);

            return(info);
        }
Beispiel #35
0
        /// <summary>
        ///     Probes the targeted video file asynchronously and retrieves all available details.
        /// </summary>
        /// <param name="info">Source video file.</param>
        /// <returns>A video info object containing all details necessary.</returns>
        public async Task <VideoInfo> ParseVideoInfoAsync(VideoInfo info)
        {
            var output = await RunProcessAsync(_ffprobePath, BuildFFProbeArguments(info));

            return(ParseVideoInfoInternal(info, output));
        }
 public void Play(VideoInfo info)
 {
     video.PlayVideoInfo(info);
 }
Beispiel #37
0
        private void button1_Click(object sender, EventArgs e)
        {
            if ((!String.IsNullOrEmpty(textBox1.Text)) || (textBox1.Text != "Example: qbagLrDTzGY"))
            {
                try
                {
                    int tempvidsdled = RipLeech.Properties.Settings.Default.videosdownloaded;
                    RipLeech.Properties.Settings.Default.videosdownloaded = tempvidsdled + 1;
                    RipLeech.Properties.Settings.Default.Save();
                    // Our youtube link
                    string link = "http://www.youtube.com/watch?v=" + textBox1.Text;

                    /*
                     * Get the available video formats.
                     * We'll work with them in the video and audio download examples.
                     */
                    IEnumerable <VideoInfo> videoInfos = DownloadUrlResolver.GetDownloadUrls(link);
                    #region get vid max quality
                    if (radioButton2.Checked == true)
                    {
                        #region get audio quality
                        if (RipLeech.Properties.Settings.Default.ffmpeg == false)
                        {
                            try
                            {
                                VideoInfo video = videoInfos.Where(info => info.CanExtractAudio).OrderByDescending(info => info.AudioBitrate).First();
                                label11.Text = video.Title;
                                label17.Text = "HQ Mp3";
                                WebClient client = new WebClient();
                                string    saveto = root + video.Title + video.VideoExtension;
                                vidout          = root + video.Title + ".mp3";
                                viddling        = saveto;
                                vidname         = video.Title + ".mp3";
                                client.Encoding = System.Text.Encoding.UTF8;
                                Uri update = new Uri(video.DownloadUrl);
                                client.DownloadFileAsync(update, saveto);
                                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                client.DownloadFileCompleted   += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                        else
                        {
                            try
                            {
                                VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 1080);
                                if (!String.IsNullOrEmpty(RipLeech.Properties.Settings.Default.videosavepath))
                                {
                                    mp4out = RipLeech.Properties.Settings.Default.videosavepath;
                                }
                                else
                                {
                                    mp4out = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + @"\" + video.Title + ".mp4";
                                }
                                label11.Text = video.Title;
                                label17.Text = "1080p";
                                WebClient client = new WebClient();
                                string    saveto = root + video.Title + video.VideoExtension;
                                vidout          = root + video.Title + ".mp3";
                                viddling        = saveto;
                                vidname         = video.Title + ".mp3";
                                client.Encoding = System.Text.Encoding.UTF8;
                                Uri update = new Uri(video.DownloadUrl);
                                client.DownloadFileAsync(update, saveto);
                                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                client.DownloadFileCompleted   += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                            }
                            catch
                            {
                                try
                                {
                                    VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 720);
                                    if (!String.IsNullOrEmpty(RipLeech.Properties.Settings.Default.videosavepath))
                                    {
                                        mp4out = RipLeech.Properties.Settings.Default.videosavepath;
                                    }
                                    else
                                    {
                                        mp4out = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + @"\" + video.Title + ".mp4";
                                    }
                                    label11.Text = video.Title;
                                    label17.Text = "720p";
                                    WebClient client = new WebClient();
                                    string    saveto = root + video.Title + video.VideoExtension;
                                    vidout          = root + video.Title + ".mp3";
                                    viddling        = saveto;
                                    vidname         = video.Title + ".mp3";
                                    client.Encoding = System.Text.Encoding.UTF8;
                                    Uri update = new Uri(video.DownloadUrl);
                                    client.DownloadFileAsync(update, saveto);
                                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                    client.DownloadFileCompleted   += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                                }
                                catch
                                {
                                    try
                                    {
                                        VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 480);
                                        if (!String.IsNullOrEmpty(RipLeech.Properties.Settings.Default.videosavepath))
                                        {
                                            mp4out = RipLeech.Properties.Settings.Default.videosavepath;
                                        }
                                        else
                                        {
                                            mp4out = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + @"\" + video.Title + ".mp4";
                                        }
                                        label11.Text = video.Title;
                                        label17.Text = "480p";
                                        WebClient client = new WebClient();
                                        string    saveto = root + video.Title + video.VideoExtension;
                                        vidout          = root + video.Title + ".mp3";
                                        viddling        = saveto;
                                        vidname         = video.Title + ".mp3";
                                        client.Encoding = System.Text.Encoding.UTF8;
                                        Uri update = new Uri(video.DownloadUrl);
                                        client.DownloadFileAsync(update, saveto);
                                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                        client.DownloadFileCompleted   += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                                    }
                                    catch
                                    {
                                        VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
                                        if (!String.IsNullOrEmpty(RipLeech.Properties.Settings.Default.videosavepath))
                                        {
                                            mp4out = RipLeech.Properties.Settings.Default.videosavepath;
                                        }
                                        else
                                        {
                                            mp4out = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + @"\" + video.Title + ".mp4";
                                        }
                                        label11.Text = video.Title;
                                        label17.Text = "360p";
                                        WebClient client = new WebClient();
                                        string    saveto = root + video.Title + video.VideoExtension;
                                        vidout          = root + video.Title + ".mp3";
                                        viddling        = saveto;
                                        vidname         = video.Title + ".mp3";
                                        client.Encoding = System.Text.Encoding.UTF8;
                                        Uri update = new Uri(video.DownloadUrl);
                                        client.DownloadFileAsync(update, saveto);
                                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                        client.DownloadFileCompleted   += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    else
                    {
                        #region get video quality
                        try
                        {
                            VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 1080);
                            if (!String.IsNullOrEmpty(RipLeech.Properties.Settings.Default.videosavepath))
                            {
                                mp4out = RipLeech.Properties.Settings.Default.videosavepath + @"\" + video.Title + ".mp4";
                            }
                            else
                            {
                                mp4out = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + @"\" + video.Title + ".mp4";
                            }
                            label11.Text = video.Title;
                            label17.Text = "1080p";
                            WebClient client = new WebClient();
                            string    saveto = root + video.Title + video.VideoExtension;
                            vidout          = root + video.Title + video.VideoExtension;
                            viddling        = saveto;
                            vidname         = video.Title + video.VideoExtension;
                            client.Encoding = System.Text.Encoding.UTF8;
                            Uri update = new Uri(video.DownloadUrl);
                            client.DownloadFileAsync(update, saveto);
                            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                            client.DownloadFileCompleted   += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                        }
                        catch
                        {
                            try
                            {
                                VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 720);
                                if (!String.IsNullOrEmpty(RipLeech.Properties.Settings.Default.videosavepath))
                                {
                                    mp4out = RipLeech.Properties.Settings.Default.videosavepath + @"\" + video.Title + ".mp4";
                                }
                                else
                                {
                                    mp4out = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + @"\" + video.Title + ".mp4";
                                }
                                label11.Text = video.Title;
                                label17.Text = "720p";
                                WebClient client = new WebClient();
                                string    saveto = root + video.Title + video.VideoExtension;
                                vidout          = root + video.Title + video.VideoExtension;
                                viddling        = saveto;
                                vidname         = video.Title + video.VideoExtension;
                                client.Encoding = System.Text.Encoding.UTF8;
                                Uri update = new Uri(video.DownloadUrl);
                                client.DownloadFileAsync(update, saveto);
                                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                client.DownloadFileCompleted   += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                            }
                            catch
                            {
                                try
                                {
                                    VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 480);
                                    if (!String.IsNullOrEmpty(RipLeech.Properties.Settings.Default.videosavepath))
                                    {
                                        mp4out = RipLeech.Properties.Settings.Default.videosavepath + @"\" + video.Title + ".mp4";
                                    }
                                    else
                                    {
                                        mp4out = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + @"\" + video.Title + ".mp4";
                                    }
                                    label11.Text = video.Title;
                                    label17.Text = "480p";
                                    WebClient client = new WebClient();
                                    string    saveto = root + video.Title + video.VideoExtension;
                                    vidout          = root + video.Title + video.VideoExtension;
                                    viddling        = saveto;
                                    vidname         = video.Title + video.VideoExtension;
                                    client.Encoding = System.Text.Encoding.UTF8;
                                    Uri update = new Uri(video.DownloadUrl);
                                    client.DownloadFileAsync(update, saveto);
                                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                    client.DownloadFileCompleted   += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                                }
                                catch
                                {
                                    VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 360);
                                    if (!String.IsNullOrEmpty(RipLeech.Properties.Settings.Default.videosavepath))
                                    {
                                        mp4out = RipLeech.Properties.Settings.Default.videosavepath + @"\" + video.Title + ".mp4";
                                    }
                                    else
                                    {
                                        mp4out = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos) + @"\" + video.Title + ".mp4";
                                    }
                                    label11.Text = video.Title;
                                    label17.Text = "360p";
                                    WebClient client = new WebClient();
                                    string    saveto = root + video.Title + video.VideoExtension;
                                    vidout          = root + video.Title + video.VideoExtension;
                                    viddling        = saveto;
                                    vidname         = video.Title + video.VideoExtension;
                                    client.Encoding = System.Text.Encoding.UTF8;
                                    Uri update = new Uri(video.DownloadUrl);
                                    client.DownloadFileAsync(update, saveto);
                                    client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
                                    client.DownloadFileCompleted   += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
                                }
                            }
                        }
                        #endregion
                    }
                    #endregion
                }
                catch (Exception ex)
                {
                    MessageBox.Show("It seems that there has been an error trying to get the Video ID. please try re-entering the id. If the problem persists, submit an issue on https://github.com/NiCoding/RipLeech/issues/new");
                }
            }
            else
            {
                MessageBox.Show("Please Enter a valid Video ID before trying to download the video!");
            }
        }
Beispiel #38
0
        public SetPosition(Subtitle subtitle, int[] selectedIndices, string videoFileName, VideoInfo videoInfo)
        {
            UiUtil.PreInitialize(this);
            InitializeComponent();
            UiUtil.FixFonts(this);

            _subtitle      = subtitle;
            _videoFileName = videoFileName;
            _videoInfo     = videoInfo;

            _subtitleWithNewHeader = new Subtitle(_subtitle, false);
            if (_subtitleWithNewHeader.Header == null)
            {
                _subtitleWithNewHeader.Header = AdvancedSubStationAlpha.DefaultHeader;
            }

            _selectedIndices = selectedIndices;
            radioButtonSelectedLines.Checked = true;
            Text = LanguageSettings.Current.AssaSetPosition.SetPosition;
            radioButtonSelectedLines.Text = string.Format(LanguageSettings.Current.AssaOverrideTags.SelectedLinesX, _selectedIndices.Length);
            radioButtonClipboard.Text     = LanguageSettings.Current.AssaSetPosition.Clipboard;
            labelInfo.Text       = LanguageSettings.Current.AssaSetPosition.SetPosInfo;
            groupBoxPreview.Text = LanguageSettings.Current.General.Preview;
            buttonOK.Text        = LanguageSettings.Current.General.Ok;
            buttonCancel.Text    = LanguageSettings.Current.General.Cancel;

            numericUpDownRotateX.Left  = labelRotateX.Left + labelRotateX.Width + 3;
            numericUpDownRotateY.Left  = labelRotateY.Left + labelRotateY.Width + 3;
            numericUpDownRotateZ.Left  = labelRotateZ.Left + labelRotateZ.Width + 3;
            numericUpDownDistortX.Left = labelDistortX.Left + labelDistortX.Width + 3;
            numericUpDownDistortY.Left = labelDistortY.Left + labelDistortY.Width + 3;

            UiUtil.FixLargeFonts(this, buttonOK);

            if (_videoInfo == null)
            {
                _videoInfo = UiUtil.GetVideoInfo(_videoFileName);
            }

            labelVideoResolution.Text = string.Format(LanguageSettings.Current.AssaSetPosition.VideoResolutionX, $"{_videoInfo.Width}x{_videoInfo.Height}");
            SetPosition_ResizeEnd(null, null);

            if (Configuration.Settings.Tools.AssaSetPositionTarget == "Clipboard")
            {
                radioButtonClipboard.Checked = true;
            }
            else
            {
                radioButtonSelectedLines.Checked = true;
            }
        }
        public override List <VideoInfo> GetVideos(Category category)
        {
            if (((RssLink)category).Url.EndsWith("EMISSIONS_accueil.aspx"))
            {
                List <VideoInfo> listVideos = new List <VideoInfo>();
                string           webData    = GetWebData((category as RssLink).Url);

                Regex r = new Regex(@"<div\sclass=""UneEmission"">\s*<a\sid=""[^""]*""\sclass=""LienContourNoir""\shref=""(?<url>[^""]*)""><img\sid=""[^""]*""\ssrc=""[^""]*""\sstyle=""border-width:1px;border-style:Solid;height:120px;width:120px;""\s/><br\s/><br\s/>\s*<span\sid=""[^""]*""\sstyle=""font-weight:bold;"">(?<title>[^<]*)</span><br\s/>\s*",
                                    RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);

                Match m = r.Match(webData);
                while (m.Success)
                {
                    VideoInfo video = new VideoInfo();
                    video.VideoUrl = m.Groups["url"].Value;
                    video.Title    = m.Groups["title"].Value;

                    listVideos.Add(video);
                    m = m.NextMatch();
                }
                return(listVideos);
            }
            if (((RssLink)category).Url.Contains("?date="))
            {
                List <VideoInfo> listVideos = new List <VideoInfo>();
                string           webData    = GetWebData("http://www.mytaratata.com/Pages/" + (category as RssLink).Url);

                Regex r = new Regex(@"<a\sid=""[^""]*""\sclass=""BoutonVoir""\shref=""(?<VideoUrl>[^""]*)""></a>\s*</td>\s*<td>\s*<div\sclass=""LabelEmission"">\s*<span\sid=""[^""]*"">(?<Title>[^<]*)</span>\s*</div>\s*</td>\s*</tr>\s*<tr>\s*<td>\s*<div\sclass=""LabelInvité"">\s*<span\sid=""[^""]*"">(?<Description>[^<]*)</span>\s*",
                                    RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);

                Match m = r.Match(webData);
                while (m.Success)
                {
                    VideoInfo video = new VideoInfo();
                    video.VideoUrl    = m.Groups["VideoUrl"].Value;
                    video.Title       = m.Groups["Title"].Value;
                    video.Description = m.Groups["Description"].Value;

                    listVideos.Add(video);
                    m = m.NextMatch();
                }
                return(listVideos);
            }


            if (((RssLink)category).Url.Contains("VIDEO_all.aspx") || ((RssLink)category).Url.Contains("PLAYLISTS_all.aspx"))
            {
                List <VideoInfo> listVideos = new List <VideoInfo>();
                string           webData    = GetWebData((category as RssLink).Url);

                Regex r = new Regex(@"class=""[^""]*""\shref=""VIDEO_page_video\.aspx\?sig=(?<url>[^""]*)""\sstyle=""display:inline-block;width:200px;"">(?<title>.*?)</a></td><td><a\sclass=""VideoAllLienArtiste""\shref='[^']*'>(?<description>[^<]*)</a>",
                                    RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Multiline | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace | RegexOptions.ExplicitCapture);

                Match m = r.Match(webData);
                while (m.Success)
                {
                    VideoInfo video = new VideoInfo();
                    video.VideoUrl = m.Groups["url"].Value;
                    string title  = m.Groups["title"].Value;
                    string title2 = title + @".  -  ." + m.Groups["description"].Value;
                    video.Title = title2;
                    video.Other = "VIDEO";
                    listVideos.Add(video);
                    m = m.NextMatch();
                }
                return(listVideos);
            }
            return(null);
        }
Beispiel #40
0
        /// <summary>
        ///     Probes the targeted video file and retrieves all available details.
        /// </summary>
        /// <param name="info">Source video file.</param>
        /// <returns>A video info object containing all details necessary.</returns>
        public VideoInfo ParseVideoInfo(VideoInfo info)
        {
            var jsonOutput =
                RunProcess($"-v quiet -print_format json -show_streams \"{info.FullName}\"");

            var metadata   = JsonConvert.DeserializeObject <Dictionary <string, dynamic> >(jsonOutput);
            int videoIndex = metadata["streams"][0]["codec_type"] == "video" ? 0 : 1,
                audioIndex = 1 - videoIndex;

            var bitRate = Convert.ToDouble(metadata["streams"][videoIndex]["bit_rate"], CultureInfo.InvariantCulture);

            try
            {
                var duration = Convert.ToDouble(metadata["streams"][videoIndex]["duration"], CultureInfo.InvariantCulture);
                info.Duration = TimeSpan.FromSeconds(duration);
                info.Duration = info.Duration.Subtract(TimeSpan.FromMilliseconds(info.Duration.Milliseconds));
            }
            catch (Exception)
            {
                info.Duration = TimeSpan.FromSeconds(0);
            }


            // Get video size in megabytes
            double videoSize = 0,
                   audioSize = 0;

            try
            {
                info.VideoFormat = metadata["streams"][videoIndex]["codec_name"];
                videoSize        = bitRate * info.Duration / 8388608;
            }
            catch (Exception)
            {
                info.VideoFormat = "none";
            }

            // Get audio format - wrap for exceptions if the video has no audio
            try
            {
                info.AudioFormat = metadata["streams"][audioIndex]["codec_name"];
                audioSize        = bitRate * info.Duration / 8388608;
            }
            catch (Exception)
            {
                info.AudioFormat = "none";
            }

            // Get video format


            // Get video width
            info.Width = metadata["streams"][videoIndex]["width"];

            // Get video height
            info.Height = metadata["streams"][videoIndex]["height"];

            info.Size = Math.Round(videoSize + audioSize, 2);

            // Get video aspect ratio
            var cd = FFProbeHelper.Gcd(info.Width, info.Height);

            info.Ratio = info.Width / cd + ":" + info.Height / cd;

            // Get video framerate
            var fr = ((string)metadata["streams"][videoIndex]["r_frame_rate"]).Split('/');

            info.FrameRate = Math.Round(
                Convert.ToDouble(fr[0], CultureInfo.InvariantCulture) /
                Convert.ToDouble(fr[1], CultureInfo.InvariantCulture),
                3);

            return(info);
        }
Beispiel #41
0
 public OutputArgument(VideoInfo value) : base(value)
 {
 }
Beispiel #42
0
 /// <summary>
 /// Creates a play video action.
 /// </summary>
 /// <param name="scene">The scene.</param>
 /// <param name="videoInfo">The video info to play</param>
 /// <returns>The action</returns>
 public static IGameAction CreatePlayVideoGameAction(this Scene scene, VideoInfo videoInfo)
 {
     return(new PlayVideoGameAction(videoInfo, scene));
 }
Beispiel #43
0
 public VideoPlay_BuleSky(IntPtr intPtr, VideoInfo vInfo, CameraInfo cInfo)
 {
     VideoPlayHandle   = intPtr;
     CurrentVideoInfo  = vInfo;
     CurrentCameraInfo = cInfo;
 }
Beispiel #44
0
 private bool ContainsFile(VideoInfo result, FileSystemMetadata file)
 {
     return(result.Files.Any(i => ContainsFile(i, file)) ||
            result.AlternateVersions.Any(i => ContainsFile(i, file)) ||
            result.Extras.Any(i => ContainsFile(i, file)));
 }
Beispiel #45
0
 public VideoPlay_BuleSky(IntPtr intPtr, VideoInfo vInfo) : this(intPtr, vInfo, vInfo.Cameras.First().Value)
 {
 }
Beispiel #46
0
        public override string GetVideoUrl(VideoInfo video)
        {
            string   result     = string.Empty;
            string   videoId    = string.Empty;
            AMFArray renditions = null;

            if (RequestType.Equals(BrightCoveType.FindMediaById))
            {
                /*
                 * sample AMF input (expressed as JSON)
                 * ["466faf0229239e70a6df8fe66fc04f25f50e6fa7",48543011001,1401332946001,15364602001]
                 */
                videoId = video.VideoUrl;

                object[] values = new object[4];
                values[0] = hashValue;
                values[1] = Convert.ToDouble(playerId);
                values[2] = Convert.ToDouble(videoId);
                values[3] = Convert.ToDouble(publisherId);

                AMFSerializer serializer = new AMFSerializer();
                AMFObject     response   = AMFObject.GetResponse(brightcoveUrl, serializer.Serialize2("com.brightcove.player.runtime.PlayerMediaFacade.findMediaById", values, AMFVersion.AMF3));
                //Log.Debug("AMF Response: {0}", response.ToString());

                renditions = response.GetArray("renditions");
            }
            else
            {
                /*
                 * sample AMF input for ViewerExperience (expressed in pretty-printed JSON for clarity - captured using Flashbug in Firebug)
                 * [
                 *  {"targetURI":"com.brightcove.experience.ExperienceRuntimeFacade.getDataForExperience",
                 *   "responseURI":"/1",
                 *   "length":"461 B",
                 *   "data":["82c0aa70e540000aa934812f3573fd475d131a63",
                 *      {"contentOverrides":[
                 *          {"contentType":0,
                 *           "target":"videoPlayer",
                 *           "featuredId":null,
                 *           "contentId":1411956407001,
                 *           "featuredRefId":null,
                 *           "contentIds":null,
                 *           "contentRefId":null,
                 *           "contentRefIds":null,
                 *           "__traits":
                 *              {"type":"com.brightcove.experience.ContentOverride",
                 *               "members":["contentType","target","featuredId","contentId","featuredRefId","contentIds","contentRefId","contentRefIds"],
                 *               "count":8,
                 *               "externalizable":false,
                 *               "dynamic":false}}],
                 *        "TTLToken":"",
                 *        "deliveryType":null,
                 *        "playerKey":"AQ~~,AAAABDk7A3E~,xYAUE9lVY9-LlLNVmcdybcRZ8v_nIl00",
                 *        "URL":"http://ww3.tvo.org/video/171480/safe-houses",
                 *        "experienceId":756015080001,
                 *        "__traits":
                 *          {"type":"com.brightcove.experience.ViewerExperienceRequest",
                 *           "members":["contentOverrides","TTLToken","deliveryType","playerKey","URL","experienceId"],
                 *           "count":6,
                 *           "externalizable":false,
                 *           "dynamic":false}}]}]
                 */
                videoId = getBrightCoveVideoIdForViewerExperienceRequest(video.VideoUrl);
                if (!string.IsNullOrEmpty(videoId))
                {
                    // content override
                    AMFObject contentOverride = new AMFObject(@"com.brightcove.experience.ContentOverride");
                    contentOverride.Add("contentId", videoId);
                    contentOverride.Add("contentIds", null);
                    contentOverride.Add("contentRefId", null);
                    contentOverride.Add("contentRefIds", null);
                    contentOverride.Add("contentType", 0);
                    contentOverride.Add("featuredId", double.NaN);
                    contentOverride.Add("featuredRefId", null);
                    contentOverride.Add("target", "videoPlayer");
                    AMFArray contentOverrideArray = new AMFArray();
                    contentOverrideArray.Add(contentOverride);

                    // viewer experience request
                    AMFObject viewerExperenceRequest = new AMFObject(@"com.brightcove.experience.ViewerExperienceRequest");
                    viewerExperenceRequest.Add("contentOverrides", contentOverrideArray);
                    viewerExperenceRequest.Add("experienceId", Convert.ToDouble(playerId));
                    viewerExperenceRequest.Add("deliveryType", null);
                    viewerExperenceRequest.Add("playerKey", string.Empty);
                    viewerExperenceRequest.Add("URL", video.VideoUrl);
                    viewerExperenceRequest.Add("TTLToken", string.Empty);

                    //Log.Debug("About to make AMF call: {0}", viewerExperenceRequest.ToString());
                    AMFSerializer serializer = new AMFSerializer();
                    AMFObject     response   = AMFObject.GetResponse(brightcoveUrl, serializer.Serialize(viewerExperenceRequest, "com.brightcove.experience.ExperienceRuntimeFacade.getDataForExperience", hashValue));
                    //Log.Debug("AMF Response: {0}", response.ToString());

                    renditions = response.GetArray("programmedContent").GetObject("videoPlayer").GetObject("mediaDTO").GetArray("renditions");
                }
            }

            if (renditions == null)
            {
                return(result);
            }

            video.PlaybackOptions = new Dictionary <string, string>();
            // keep track of bitrates and URLs
            Dictionary <string, string> urlsDictionary = new Dictionary <string, string>();

            for (int i = 0; i < renditions.Count; i++)
            {
                AMFObject rendition = renditions.GetObject(i);
                int       bitrate   = rendition.GetIntProperty("encodingRate");
                string    optionKey = String.Format("{0}x{1} {2}K",
                                                    rendition.GetIntProperty("frameWidth"),
                                                    rendition.GetIntProperty("frameHeight"),
                                                    bitrate / 1024);
                string url = HttpUtility.UrlDecode(rendition.GetStringProperty("defaultURL"));
                Log.Debug("Option: {0} URL: {1}", optionKey, url);

                // typical rtmp url from "defaultURL" is:
                // rtmp://brightcove.fcod.llnwd.net/a500/d20/&mp4:media/1351824783/1351824783_1411974095001_109856X-640x360-1500k.mp4&1330020000000&1b163106256f448754aff72969869479
                //
                // following rtmpdump style command works
                // rtmpdump
                // --app 'a500/d20/?videoId=1411956407001&lineUpId=&pubId=18140038001&playerId=756015080001&playerTag=&affiliateId='
                // --auth 'mp4:media/1351824783/1351824783_1411974097001_109856X-400x224-300k.mp4&1330027200000&23498dd8f4659cd07ad1b6c4ee5a013d'
                // --rtmp 'rtmp://brightcove.fcod.llnwd.net/a500/d20/?videoId=1411956407001&lineUpId=&pubId=18140038001&playerId=756015080001&playerTag=&affiliateId='
                // --flv 'TVO_org_-_Safe_as_Houses.flv'
                // --playpath 'mp4:media/1351824783/1351824783_1411974097001_109856X-400x224-300k.mp4'

                Match rtmpUrlMatch = rtmpUrlRegex.Match(url);

                if (rtmpUrlMatch.Success)
                {
                    string leftover = rtmpUrlMatch.Groups["leftover"].Value;
                    string query    = string.Format(@"videoId={0}&lineUpId=&pubId={1}&playerId={2}&playerTag=&affiliateId=",
                                                    videoId, publisherId, playerId);

                    int questionMarkPosition = leftover.IndexOf('?');
                    // use existing query (if present) in the new query string
                    if (questionMarkPosition != -1)
                    {
                        query = string.Format(@"{0}{1}", leftover.Substring(questionMarkPosition + 1, leftover.Length - questionMarkPosition - 1), query);
                    }

                    string app     = String.Format("{0}?{1}", rtmpUrlMatch.Groups["app"], query);
                    string auth    = leftover;
                    string rtmpUrl = String.Format("{0}://{1}/{2}?{3}",
                                                   rtmpUrlMatch.Groups["rtmp"].Value,
                                                   rtmpUrlMatch.Groups["host"].Value,
                                                   rtmpUrlMatch.Groups["app"].Value,
                                                   query);
                    int    ampersandPosition = leftover.IndexOf('&');
                    string playPath          = ampersandPosition == -1 ? leftover : leftover.Substring(0, ampersandPosition);
                    Log.Debug(@"rtmpUrl: {0}, PlayPath: {1}, App: {2}, Auth: {3}", rtmpUrl, playPath, app, auth);
                    urlsDictionary.Add(optionKey, new RtmpUrl(rtmpUrl)
                    {
                        PlayPath = playPath,
                        App      = app,
                        Auth     = auth
                    }.ToString());
                }
            }

            // sort the URLs ascending by bitrate
            foreach (var item in urlsDictionary.OrderBy(u => u.Key, new BitrateComparer()))
            {
                video.PlaybackOptions.Add(item.Key, item.Value);
                // return last URL as the default (will be the highest bitrate)
                result = item.Value;
            }
            return(result);
        }
        public void Setup(VideoInfo liveVideoInfo)
        {
            CommunityName = liveVideoInfo.Community?.Name;
            if (liveVideoInfo.Community?.Thumbnail != null)
            {
                CommunityThumbnail = liveVideoInfo.Community?.Thumbnail;
            }
            else
            {
                CommunityThumbnail = liveVideoInfo.Video.ThumbnailUrl;
            }
            CommunityGlobalId = liveVideoInfo.Community?.GlobalId;
            CommunityType     = liveVideoInfo.Video.ProviderType;

            LiveTitle             = liveVideoInfo.Video.Title;
            ViewCounter           = int.Parse(liveVideoInfo.Video.ViewCounter);
            CommentCount          = int.Parse(liveVideoInfo.Video.CommentCount);
            OpenTime              = new DateTimeOffset(liveVideoInfo.Video.OpenTime, TimeSpan.FromHours(9));
            StartTime             = new DateTimeOffset(liveVideoInfo.Video.StartTime, TimeSpan.FromHours(9));
            EndTime               = new DateTimeOffset(liveVideoInfo.Video.EndTime, TimeSpan.FromHours(9));
            IsTimeshiftEnabled    = liveVideoInfo.Video.TimeshiftEnabled;
            IsCommunityMemberOnly = liveVideoInfo.Video.CommunityOnly;

            Label = liveVideoInfo.Video.Title;
            AddImageUrl(CommunityThumbnail);

            Description = $"来場者:{ViewCounter} コメ:{CommentCount}";

            if (StartTime > DateTimeOffset.Now)
            {
                // 予約
                DurationText = $" 開始予定: {StartTime.LocalDateTime.ToString("g")}";
            }
            else if (EndTime > DateTimeOffset.Now)
            {
                var duration = DateTimeOffset.Now - StartTime;
                // 放送中
                if (duration.Hours > 0)
                {
                    DurationText = $"{duration.Hours}時間 {duration.Minutes}分 経過";
                }
                else
                {
                    DurationText = $"{duration.Minutes}分 経過";
                }
            }
            else
            {
                var duration = EndTime - StartTime;
                // 終了
                if (duration.Hours > 0)
                {
                    DurationText = $"{EndTime.ToString("g")} 終了({duration.Hours}時間 {duration.Minutes}分)";
                }
                else
                {
                    DurationText = $"{EndTime.ToString("g")} 終了({duration.Minutes}分)";
                }
            }

            OptionText = DurationText;
        }
Beispiel #48
0
 public snowConfigurationPanel(MainForm mainForm, VideoInfo info)
     : base(mainForm, info)
 {
     InitializeComponent();
 }
Beispiel #49
0
 private static string BuildFFProbeArguments(VideoInfo info) =>
 $"-v quiet -print_format json -show_streams \"{info.FullName}\"";
Beispiel #50
0
        public async Task <VideoInfo> GetInfo(string id)
        {
            var ret = new VideoInfo {
                Title = "", Actresses = ""
            };
            var num = id.Replace("ZTOD_", string.Empty);
            var url = string.Format("http://www.ztod.com/videos/{0}", num);

            using (var handler = new HttpClientHandler())
                using (var client = new HttpClient(handler))
                {
                    var response = await client.GetByteArrayAsync(url);

                    var responseString = Encoding.UTF8.GetString(response, 0, response.Length - 1);

                    var search = "<title>";
                    var start  = responseString.IndexOf(search, 0, StringComparison.Ordinal);

                    if (start >= 0)
                    {
                        start = start + search.Length;
                        var end = responseString.IndexOf(" Featuring", start, StringComparison.Ordinal);

                        if (end < 0)
                        {
                            response = await client.GetByteArrayAsync(url);

                            responseString = Encoding.UTF8.GetString(response, 0, response.Length - 1);
                            start          = responseString.IndexOf(search, 0, StringComparison.Ordinal);
                            if (start >= 0)
                            {
                                start = start + search.Length;
                                end   = responseString.IndexOf(" Featuring", start, StringComparison.Ordinal);
                            }
                        }

                        if (end >= 0)
                        {
                            ret.Title = end - start <= 0 ? string.Empty : HttpUtility.HtmlDecode(responseString.Substring(start, end - start));
                            search    = "Pornstars:<span class=\"txt-highlight\">";
                            start     = responseString.IndexOf(search, end, StringComparison.Ordinal);
                            start    += search.Length;
                            end       = responseString.IndexOf("</span>", start, StringComparison.Ordinal);

                            var namesStr = responseString.Substring(start, end - start);
                            search = "\">";
                            foreach (var nameStart in namesStr.AllIndexesOf(search))
                            {
                                var aStart  = nameStart + search.Length;
                                var aEnd    = namesStr.IndexOf("</a>", nameStart, StringComparison.Ordinal);
                                var actress = namesStr.Substring(aStart, aEnd - aStart).TrimEnd();
                                ret.Actresses += string.Format("{0}, ", HttpUtility.HtmlDecode(actress));
                            }
                            if (ret.Actresses != null)
                            {
                                ret.Actresses = ret.Actresses.RemoveEnd(", ");
                            }

                            ret.Title = string.Format("[ZTOD] {0}", ret.Title);
                        }
                    }
                }
            return(ret);
        }
Beispiel #51
0
        /// <summary>
        ///     Probes the targeted video file and retrieves all available details.
        /// </summary>
        /// <param name="info">Source video file.</param>
        /// <returns>A video info object containing all details necessary.</returns>
        public VideoInfo ParseVideoInfo(VideoInfo info)
        {
            var output = RunProcess(BuildFFProbeArguments(info));

            return(ParseVideoInfoInternal(info, output));
        }
Beispiel #52
0
 private void Start()
 {
     videoPlayer.frame = 0;
     videoInfo         = VideoInfo.videoInfo;
 }
Beispiel #53
0
        public override int DiscoverSubCategories(Category parentCategory)
        {
            parentCategory.SubCategories = new List <Category>();
            RssLink parentCat = parentCategory as RssLink;

            string[] myString = parentCategory.Other.ToString().Split(',');

            if (myString[0] == "drnulist_az")
            {
                //Add alphabetic A-Å subcategories
                string[] alpha = new string[25] {
                    "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "VW", "XYZ", "ÆØÅ", "0-9"
                };
                foreach (string a in alpha)
                {
                    RssLink subCategory = new RssLink()
                    {
                        Name                    = a,
                        ParentCategory          = parentCategory,
                        HasSubCategories        = true,
                        SubCategoriesDiscovered = false,
                        Other                   = "drnulist_alpha," + a
                    };
                    parentCategory.SubCategories.Add(subCategory);
                }
            }

            if (myString[0] == "drnulist_alpha")
            {
                //Get series with chosen letter
                if (myString[1].Length > 1)
                {
                    myString[1] = myString[1][0] + ".." + myString[1][myString[1].Length - 1];
                }
                string url = baseUrlDrNu + "/search/tv/programcards-latest-episode-with-asset/series-title-starts-with/" + myString[1] + "?limit=50";
                Log.Debug("DR NU url: " + url);
                string  json        = GetWebData(url);
                JObject contentData = JObject.Parse(json);
                if (contentData != null)
                {
                    JArray slugs = (JArray)contentData["Items"];
                    foreach (JObject slug in slugs)
                    {
                        try
                        {
                            string    itemTitle   = slug.Value <string>("SeriesTitle");
                            JObject   assets      = (JObject)slug["PrimaryAsset"];
                            string    itemslug    = slug.Value <string>("SeriesSlug");
                            VideoInfo video       = new VideoInfo();
                            RssLink   subCategory = new RssLink()
                            {
                                Name                    = itemTitle,
                                ParentCategory          = parentCategory,
                                HasSubCategories        = false,
                                SubCategoriesDiscovered = false,
                                Other                   = "drnulist_card," + itemslug
                            };
                            parentCategory.SubCategories.Add(subCategory);
                        }
                        catch
                        {
                        }
                    }
                }
            }


            //DR NU categories
            if (myString[0] == "drnu")
            {
                //Add static category A-Å program series
                RssLink subCategory = new RssLink()
                {
                    Name                    = "Programmer A-Å",
                    ParentCategory          = parentCategory,
                    HasSubCategories        = true,
                    SubCategoriesDiscovered = false,
                    Other                   = "drnulist_az,"
                };
                parentCategory.SubCategories.Add(subCategory);

                //Add static category last chance
                subCategory = new RssLink()
                {
                    Name                    = "Sidste chance",
                    ParentCategory          = parentCategory,
                    HasSubCategories        = false,
                    SubCategoriesDiscovered = false,
                    EstimatedVideoCount     = 10,
                    Other                   = "drnulastchance,"
                };
                parentCategory.SubCategories.Add(subCategory);

                //Add static category most viewed
                subCategory = new RssLink()
                {
                    Name                    = "Mest sete",
                    ParentCategory          = parentCategory,
                    HasSubCategories        = false,
                    SubCategoriesDiscovered = false,
                    EstimatedVideoCount     = 10,
                    Other                   = "drnumostviewed,"
                };
                parentCategory.SubCategories.Add(subCategory);

                //Add static category highlights
                subCategory = new RssLink()
                {
                    Name                    = "Højdepunkter",
                    ParentCategory          = parentCategory,
                    HasSubCategories        = false,
                    SubCategoriesDiscovered = false,
                    EstimatedVideoCount     = 10,
                    Other                   = "drnuspot,"
                };
                parentCategory.SubCategories.Add(subCategory);
            }

            //DR Bonanza
            if (myString[0] == "bonanza")
            {
                string data = GetWebData(parentCat.Url);
                if (!string.IsNullOrEmpty(data))
                {
                    Regex regEx = (regEx_bonanzaKategori as Regex);
                    if (myString[1] != "start")
                    {
                        regEx = regEx_bonanzaSerie;
                    }
                    Match m = regEx.Match(data);
                    while (m.Success)
                    {
                        RssLink cat = new RssLink()
                        {
                            Url              = m.Groups["url"].Value,
                            Name             = HttpUtility.HtmlDecode(m.Groups["title"].Value.Trim()),
                            Description      = m.Groups["description"].Value,
                            Thumb            = m.Groups["thumb"].Value,
                            ParentCategory   = parentCategory,
                            Other            = "bonanza,",
                            HasSubCategories = parentCategory.Name == "Bonanza"
                        };

                        cat.Url = HttpUtility.HtmlDecode(cat.Url);
                        if (!Uri.IsWellFormedUriString(cat.Url, System.UriKind.Absolute))
                        {
                            cat.Url = new Uri(new Uri(parentCat.Url), cat.Url).AbsoluteUri;
                        }
                        parentCategory.SubCategories.Add(cat);
                        m = m.NextMatch();
                    }
                    parentCategory.SubCategoriesDiscovered = true;
                }
            }
            return(parentCategory.SubCategories.Count);
        }
Beispiel #54
0
        private async Task PlaySong(VideoInfo video)
        {
            await MediaService.StartPlayingSong(video.DownloadUrl);

            CreateNotification(video);
        }
Beispiel #55
0
        private List <VideoInfo> getVideos(JObject contentData)
        {
            List <VideoInfo> res = new List <VideoInfo>();

            if (contentData != null)
            {
                JArray slugs = (JArray)contentData["Items"];
                Log.Debug("DR NU slugs count: " + slugs.Count);
                foreach (JObject slug in slugs)
                {
                    try
                    {
                        string   itemslug   = slug.Value <string>("Slug");
                        string   link       = null;
                        TimeSpan duration   = new TimeSpan(0);
                        string   fduration  = null;
                        string   img        = null;
                        string   webDataUrl = baseUrlDrNu + "/programcard/" + itemslug;
                        Log.Debug("DR NU webDataUrl: " + webDataUrl);
                        string   strprogramcard = GetWebData(webDataUrl);
                        JObject  objprogramcard = JObject.Parse(strprogramcard);
                        string   itemTitle      = (string)objprogramcard["Title"];
                        DateTime airDate        = (DateTime)objprogramcard["PrimaryBroadcastStartTime"];
                        img = (string)objprogramcard["PrimaryImageUri"];
                        string itemDescription = (string)objprogramcard["Description"];
                        Log.Debug("DR NU Description: " + itemDescription);
                        JObject assets = (JObject)objprogramcard["PrimaryAsset"];

                        if (assets.Count > 0)
                        {
                            Log.Debug("DR NU asset count: " + assets.Count);
                            string kind = (string)assets["Kind"];
                            string uri  = (string)assets["Uri"];

                            if (kind == "VideoResource")
                            {
                                link      = uri;
                                duration  = TimeSpan.FromMilliseconds((double)assets["DurationInMilliseconds"]);
                                fduration = String.Format("{0:D2}:{1:D2}:{2:D2}", duration.Hours, duration.Minutes, duration.Seconds);
                            }

                            Log.Debug("DR NU Uri: " + uri);
                        }
                        if (link.Length > 0)
                        {
                            VideoInfo video = new VideoInfo();
                            video.Title       = itemTitle;
                            video.Description = itemDescription;
                            video.VideoUrl    = link;
                            video.Length      = fduration;
                            video.Thumb       = img;
                            video.Other       = "drnu";
                            video.Airdate     = airDate.ToString("dd. MMM. yyyy kl. HH:mm");
                            res.Add(video);
                        }
                    }
                    catch
                    {
                    }
                }
            }
            return(res);
        }
Beispiel #56
0
        public override string GetVideoUrl(VideoInfo video)
        {
            string      url          = string.Format(videoPlayUrl, video.VideoUrl);
            XmlDocument xDoc         = GetWebData <XmlDocument>(url);
            XmlNode     errorElement = xDoc.SelectSingleNode("//error");

            if (errorElement != null)
            {
                throw new OnlineVideosException(errorElement.SelectSingleNode("./description/text()").InnerText);
            }
            XmlNode drm = xDoc.SelectSingleNode("//drmProtected");

            if (drm != null && drm.InnerText.Trim().ToLower() == "true")
            {
                throw new OnlineVideosException("DRM protected content, sorry! :/");
            }
            foreach (XmlElement item in xDoc.SelectNodes("//items/item"))
            {
                string mediaformat = item.GetElementsByTagName("mediaFormat")[0].InnerText.ToLower();
                string itemUrl     = item.GetElementsByTagName("url")[0].InnerText.Trim();
                if (mediaformat.StartsWith("mp4") && itemUrl.ToLower().EndsWith(".f4m"))
                {
                    url = string.Concat(itemUrl, "?hdcore=3.5.0&g=", HelperUtils.GetRandomChars(12));
                }
                else if (mediaformat.StartsWith("mp4") && itemUrl.ToLower().Contains(".f4m?"))
                {
                    url = string.Concat(itemUrl, "&hdcore=3.5.0&g=", HelperUtils.GetRandomChars(12));
                }
                else if (mediaformat.StartsWith("webvtt"))
                {
                    try
                    {
                        string srt = GetWebData(itemUrl, encoding: System.Text.Encoding.Default);
                        Regex  rgx;
                        //Remove WEBVTT stuff
                        rgx = new Regex(@"WEBVTT");
                        srt = rgx.Replace(srt, new MatchEvaluator((Match m) =>
                        {
                            return(string.Empty);
                        }));
                        //Add hours
                        rgx = new Regex(@"(\d\d:\d\d\.\d\d\d)\s*-->\s*(\d\d:\d\d\.\d\d\d).*?\n", RegexOptions.Multiline);
                        srt = rgx.Replace(srt, new MatchEvaluator((Match m) =>
                        {
                            return("00:" + m.Groups[1].Value + " --> 00:" + m.Groups[2].Value + "\n");
                        }));
                        // Remove all trailing stuff, ie in 00:45:21.960 --> 00:45:25.400 A:end L:82%
                        rgx = new Regex(@"(\d\d:\d\d:\d\d\.\d\d\d)\s*-->\s*(\d\d:\d\d:\d\d\.\d\d\d).*\n", RegexOptions.Multiline);
                        srt = rgx.Replace(srt, new MatchEvaluator((Match m) =>
                        {
                            return(m.Groups[1].Value + " --> " + m.Groups[2].Value + "\n");
                        }));

                        //Remove all tags
                        rgx = new Regex(@"</{0,1}[^>]+>");
                        srt = rgx.Replace(srt, string.Empty);
                        //Add index
                        rgx = new Regex(@"(?<time>\d\d:\d\d:\d\d\.\d\d\d\s*?-->\s*?\d\d:\d\d:\d\d\.\d\d\d)");
                        int i = 0;
                        foreach (Match m in rgx.Matches(srt))
                        {
                            i++;
                            string time = m.Groups["time"].Value;
                            srt = srt.Replace(time, i + "\n" + time);
                        }
                        srt = HttpUtility.HtmlDecode(srt).Trim();
                        video.SubtitleText = srt;
                    }
                    catch { }
                }
            }
            return(url);
        }
Beispiel #57
0
        internal static void WriteTrack(string fileName, string outputFolder, bool overwrite, StreamWriter stdOutWriter, CommandLineConverter.BatchConvertProgress progressCallback, Point?resolution, ProgramMapTableParser programMapTableParser, int pid, TransportStreamParser tsParser)
        {
            var overrideScreenSize = Configuration.Settings.Tools.BatchConvertTsOverrideScreenSize &&
                                     Configuration.Settings.Tools.BatchConvertTsScreenHeight > 0 &&
                                     Configuration.Settings.Tools.BatchConvertTsScreenWidth > 0 ||
                                     resolution.HasValue;

            using (var form = new ExportPngXml())
            {
                var language  = TsToBluRaySup.GetFileNameEnding(programMapTableParser, pid);
                var nameNoExt = Utilities.GetFileNameWithoutExtension(fileName) + "." + language;
                var folder    = Path.Combine(outputFolder, nameNoExt);
                if (!Directory.Exists(folder))
                {
                    Directory.CreateDirectory(folder);
                }

                var outputFileName = CommandLineConverter.FormatOutputFileNameForBatchConvert(nameNoExt + Path.GetExtension(fileName), ".xml", folder, overwrite);
                stdOutWriter?.WriteLine($"Saving PID {pid} to {outputFileName}...");
                progressCallback?.Invoke($"Save PID {pid}");
                var sub      = tsParser.GetDvbSubtitles(pid);
                var subtitle = new Subtitle();
                foreach (var p in sub)
                {
                    subtitle.Paragraphs.Add(new Paragraph(string.Empty, p.StartMilliseconds, p.EndMilliseconds));
                }

                var res       = TsToBluRaySup.GetSubtitleScreenSize(sub, overrideScreenSize, resolution);
                var videoInfo = new VideoInfo {
                    Success = true, Width = res.X, Height = res.Y
                };
                form.Initialize(subtitle, new SubRip(), BatchConvert.BdnXmlSubtitle, fileName, videoInfo, fileName);
                var sb = new StringBuilder();
                var imagesSavedCount = 0;
                for (int index = 0; index < sub.Count; index++)
                {
                    var p        = sub[index];
                    var pos      = p.GetPosition();
                    var bmp      = sub[index].GetBitmap();
                    var tsWidth  = bmp.Width;
                    var tsHeight = bmp.Height;
                    var nBmp     = new NikseBitmap(bmp);
                    pos.Top  += nBmp.CropTopTransparent(0);
                    pos.Left += nBmp.CropSidesAndBottom(0, Color.FromArgb(0, 0, 0, 0), true);
                    bmp.Dispose();
                    bmp = nBmp.GetBitmap();
                    var mp = form.MakeMakeBitmapParameter(index, videoInfo.Width, videoInfo.Height);

                    if (overrideScreenSize)
                    {
                        var widthFactor  = (double)videoInfo.Width / tsWidth;
                        var heightFactor = (double)videoInfo.Height / tsHeight;
                        var resizeBmp    = ResizeBitmap(bmp, (int)Math.Round(bmp.Width * widthFactor), (int)Math.Round(bmp.Height * heightFactor));
                        bmp.Dispose();
                        bmp      = resizeBmp;
                        pos.Left = (int)Math.Round(pos.Left * widthFactor);
                        pos.Top  = (int)Math.Round(pos.Top * heightFactor);
                        progressCallback?.Invoke($"Save PID {pid}: {(index + 1) * 100 / sub.Count}%");
                    }

                    mp.Bitmap       = bmp;
                    mp.P            = new Paragraph(string.Empty, p.StartMilliseconds, p.EndMilliseconds);
                    mp.ScreenWidth  = videoInfo.Width;
                    mp.ScreenHeight = videoInfo.Height;
                    int bottomMarginInPixels;
                    if (Configuration.Settings.Tools.BatchConvertTsOverrideXPosition || Configuration.Settings.Tools.BatchConvertTsOverrideYPosition)
                    {
                        if (Configuration.Settings.Tools.BatchConvertTsOverrideXPosition && Configuration.Settings.Tools.BatchConvertTsOverrideYPosition)
                        {
                            var x = (int)Math.Round(videoInfo.Width / 2.0 - mp.Bitmap.Width / 2.0);
                            if (Configuration.Settings.Tools.BatchConvertTsOverrideHAlign.Equals("left", StringComparison.OrdinalIgnoreCase))
                            {
                                x = Configuration.Settings.Tools.BatchConvertTsOverrideHMargin;
                            }
                            else if (Configuration.Settings.Tools.BatchConvertTsOverrideHAlign.Equals("right", StringComparison.OrdinalIgnoreCase))
                            {
                                x = videoInfo.Width - Configuration.Settings.Tools.BatchConvertTsOverrideHMargin - mp.Bitmap.Width;
                            }

                            var y = videoInfo.Height - Configuration.Settings.Tools.BatchConvertTsOverrideBottomMargin - mp.Bitmap.Height;
                            mp.OverridePosition = new Point(x, y);
                        }
                        else if (Configuration.Settings.Tools.BatchConvertTsOverrideXPosition)
                        {
                            var x = (int)Math.Round(videoInfo.Width / 2.0 - mp.Bitmap.Width / 2.0);
                            if (Configuration.Settings.Tools.BatchConvertTsOverrideHAlign.Equals("left", StringComparison.OrdinalIgnoreCase))
                            {
                                x = Configuration.Settings.Tools.BatchConvertTsOverrideHMargin;
                            }
                            else if (Configuration.Settings.Tools.BatchConvertTsOverrideHAlign.Equals("right", StringComparison.OrdinalIgnoreCase))
                            {
                                x = videoInfo.Width - Configuration.Settings.Tools.BatchConvertTsOverrideHMargin - mp.Bitmap.Width;
                            }

                            mp.OverridePosition = new Point(x, pos.Top);
                        }
                        else
                        {
                            var y = videoInfo.Height - Configuration.Settings.Tools.BatchConvertTsOverrideBottomMargin - mp.Bitmap.Height;
                            mp.OverridePosition = new Point(pos.Left, y);
                        }

                        bottomMarginInPixels = Configuration.Settings.Tools.BatchConvertTsScreenHeight - pos.Top - mp.Bitmap.Height;
                    }
                    else
                    {
                        mp.OverridePosition  = new Point(pos.Left, pos.Top); // use original position
                        bottomMarginInPixels = Configuration.Settings.Tools.BatchConvertTsScreenHeight - pos.Top - mp.Bitmap.Height;
                    }

                    imagesSavedCount = form.WriteBdnXmlParagraph(videoInfo.Width, sb, bottomMarginInPixels, videoInfo.Height, imagesSavedCount, mp, index, Path.GetDirectoryName(outputFileName));
                }

                form.WriteBdnXmlFile(imagesSavedCount, sb, outputFileName);
            }
        }
Beispiel #58
0
        /// <summary>
        /// Invoked when BtnExtract is clicked
        /// Starts the extraction process of a video or playlist
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void BtnExtract_Click(object sender, RoutedEventArgs e)
        {
            //The list of videos available for download
            IEnumerable <VideoInfo> videoList = null;

            //Prevent another video being downloaded
            DisableExtractionButton(WAIT_TEXT);

            //Get the video info
            videoList = await Task.Run(() => ResolveURL(ExtractionUrl));

            //Check that the return was not null
            if (videoList == null)
            {
                MessageBox.Show("The URL entered is not a valid YouTube video URL!");
                EnableExtractionButton(DOWNLOAD_TEXT_QUERY);
                return;
            }

            //The user download preferences selector
            WndwInfoSelector infoSelector = null;
            //The video to download
            VideoInfo video = null;

            while (true)
            {
                //Get the user preferences
                infoSelector = GetUserDownloadPreferences(videoList);

                //If we are to download video, else download audio
                if (infoSelector.SelectedDownloadType == DownloadType.Video)
                {
                    //Try to find the first element
                    try
                    {
                        //Get the first video with the selected resolution and format and highest bitrate
                        video = videoList.Where(info => info.Resolution == infoSelector.SelectedVideoResolution &&
                                                info.VideoExtension == infoSelector.SelectedVideoExtension && info.AudioBitrate == infoSelector.SelectedAudioBitrate)
                                .First();
                        break;
                    }
                    catch
                    {
                        MessageBox.Show("We couldn't find a video with the stats that you selected!");
                        continue;
                    }
                }
                else
                {
                    try
                    {
                        //Get the first video with the selected resolution and format and highest bitrate
                        video = videoList.Where(info => info.AudioBitrate == infoSelector.SelectedAudioBitrate &&
                                                info.AudioExtension == infoSelector.SelectedAudioExtension && info.CanExtractAudio)
                                .First();
                        break;
                    } catch
                    {
                        MessageBox.Show("We couldn't find an audio track with the stats that you selected!");
                        continue;
                    }
                }
            }

            //If the video has an encrypted signature, decode it
            if (video.RequiresDecryption)
            {
                DownloadUrlResolver.DecryptDownloadUrl(video);
            }

            //Get the download folder location
            string downloadLocation = ShowFolderSelectionDialog();

            if (infoSelector.SelectedDownloadType == DownloadType.Video)
            {
                //Create the downloader
                VideoDownloader downloader = new VideoDownloader(video, Path.Combine(downloadLocation, DownloadItem.PathCleaner(video.Title) + video.VideoExtension));

                //Create a new DownloadVideo item
                DownloadVideoItem item = new DownloadVideoItem(DownloadType.Video, video.Title, downloader);

                //Add a new DownloadVideoItem
                DownloadingItems.Add(item);

                EnableExtractionButton(DOWNLOAD_TEXT_QUERY);
            }
            else
            {
                //Create the audio downloader
                AudioDownloader downloader = new AudioDownloader(video, Path.Combine(downloadLocation, DownloadItem.PathCleaner(video.Title) + video.AudioExtension));

                //Create a new DownloadAudio item
                DownloadAudioItem item = new DownloadAudioItem(DownloadType.Audio, video.Title, downloader);

                //Add the new DownloadAudioItem
                DownloadingItems.Add(item);

                EnableExtractionButton(DOWNLOAD_TEXT_QUERY);
            }
        }
Beispiel #59
0
 /// <summary>
 /// And play a video action.
 /// </summary>
 /// <param name="parent">The parent.</param>
 /// <param name="videoInfo">The video info to play</param>
 /// <returns>The action</returns>
 public static IGameAction AndPlayVideo(this IGameAction parent, VideoInfo videoInfo)
 {
     return(new PlayVideoGameAction(parent, videoInfo));
 }
Beispiel #60
0
    private void parseData(string jsonStr)
    {
        JsonData jsdArray = JsonMapper.ToObject(jsonStr);//转换成json格式;需要引入LitJson
        JsonData jsdList  = jsdArray["data"];

        for (int i = 0; i < list.Count; i++)
        {
            Destroy(GameObject.Find("ID" + list[i].ID));
        }
        list.Clear();
        int id = 0;

        if (jsdList.IsArray)
        {
            for (int i = 0; i < jsdList.Count; i++)
            {
                //直接data部分
                JsonData jsd = jsdList[i]["data"];
                if (jsd.Keys.Contains("data"))
                {
                    JsonData j_data_data = jsd["data"];
                    if (j_data_data.IsArray)
                    {
                        for (int j = 0; j < j_data_data.Count; j++)
                        {
                            JsonData  jsd_data = j_data_data[j];
                            VideoInfo vi       = createVideoInfo(jsd_data, id);

                            list.Add(vi);
                            id = id + 1;
                        }
                    }
                }

                //children中data部分
                if (jsd.Keys.Contains("children"))
                {
                    JsonData j_data_children = jsd["children"];
                    if (j_data_children.IsArray)
                    {
                        for (int j = 0; j < j_data_children.Count; j++)
                        {
                            JsonData jsd_children         = j_data_children[j];
                            JsonData j_data_children_data = jsd_children["data"];
                            if (j_data_children_data.IsArray)
                            {
                                for (int k = 0; k < j_data_children_data.Count; k++)
                                {
                                    JsonData  jsd_data = j_data_children_data[k];
                                    VideoInfo vi       = createVideoInfo(jsd_data, id);

                                    list.Add(vi);
                                    id = id + 1;
                                }
                            }
                        }
                    }
                }
            }
        }

        //选中状态
        currentType = toBeType;
        upateTypeMaterial();

        //总页数
        totalPage = list.Count % onePageNumber == 0 ? list.Count / onePageNumber : list.Count / onePageNumber + 1;

        showUI(true, 0);

        isLoading                 = false;
        m_WarningText.text        = string.Empty;
        m_BackgroundImage.enabled = false;
        m_DisplayingWarning       = false;
    }