Exemple #1
0
        private void MediaBrowser_Load(object sender, EventArgs e)
        {
            Cursor.Position = new Point(this.Location.X + 10, this.Location.Y + 10);//position the cursor w/ in the bounds of the form

            Match m = Regex.Match(mfOwner.ps.SageWebserver, @"https?://[\w|.]+(?::\d+)/sage");

            if (m.Success)
                baseUrl = m.Value;
            else
                using (EPDialog ed = new EPDialog())
                    ed.ShowDialog("Error", "Could not determin base url", 10, mfOwner);


            tcBrowse.SelectedIndex = 0;
            BuildList(lastMode);
        }
Exemple #2
0
        private bool GetXmlFromSage(BrowseMode mode)
        {
            string Url = string.Empty;
            int cacheFor = 0;

            if (lastMode != mode || data == null || data.HasExpired)
            {
                lastMode = mode;
                switch (mode)
                {
                    case BrowseMode.Recordings:
                        Url = string.Format("{0}{1}", baseUrl, mfOwner.ps.SageRecording);
                        cacheFor = mfOwner.ps.CacheRecording;
                        break;
                    case BrowseMode.Media:
                        Url = string.Format("{0}{1}", baseUrl, mfOwner.ps.SageMedia);
                        cacheFor = mfOwner.ps.CacheMedia;
                        break;
                }

                if (MainForm.DebugMode)
                    Url = "http://microsoft.com";

                using (DownloadForm df = new DownloadForm(Url, this.mfOwner.ps.BrowseAttempts))
                {
                    if (df.ShowDialog(this) == DialogResult.OK || MainForm.DebugMode)
                    {
                        //get xml document
                        if (MainForm.DebugMode)
                        {
                            using (StreamReader sr = new StreamReader(@"C:\temp\recordings.xml"))
                            {
                                data = new CachedData(sr.ReadToEnd(), cacheFor);
                            }
                        }
                        else
                        {
                            data = new CachedData(df.Result, cacheFor);
                        }

                        return true;
                    }
                    else
                    {
                        //display the error
                        using (EPDialog ed = new EPDialog())
                            ed.ShowDialog("Error", df.Result, 10, mfOwner);
                        return false;
                    }
                }
            }
            else
                return true;
        }
Exemple #3
0
        void b_Click(object sender, EventArgs e)
        {
            Button b = sender as Button;
            if (b != null)
            {
                BrowserState tState = b.Tag as BrowserState;
                switch (tState.Level)
                {
                    case 1:
                        tState.Level++;
                        DataView showView = data.Data.DefaultViewManager.CreateDataView(data.Data.Tables["show"]);
                        showView.Sort = tState.Sort;
                        showView.RowFilter = string.Format("{0} = '{1}'", tState.Filter, tState.Value.Replace("'", "''"));
                        DataTable dtDetail = showView.ToTable();//true, tState.SecondLevel);
                        CreateControls(dtDetail, tState);
                        break;
                    case 2:
                        List<string> fPath = GetSegmentValue(tState.Filter, tState.Value, "filePath");
                        StringBuilder sbPls = new StringBuilder();

                        for (int i = 0; i < fPath.Count; i++)
                            sbPls.AppendFormat("File{0}={1}{2}", i, fPath[i], Environment.NewLine);

                        MainForm.ParsePlsText(mfOwner, sbPls.ToString());
                        if (mfOwner.OpenClip(OpenClipMode.None))
                            this.Hide();
                        else
                        {
                            using (EPDialog ed = new EPDialog())
                                ed.ShowDialog("Error", "Could not play file", 20, mfOwner);
                        }
                        break;
                }
            }
        }
Exemple #4
0
        internal void PlayMovieInWindow(string filename)
        {
            FileLogger.Log("PlayMovieInWindow: {0}", filename);
            lastJump = 0;

            int hr = 0;

            if (filename == string.Empty)
                return;

            this.graphBuilder = (IGraphBuilder)new FilterGraph();
            FileLogger.Log("PlayMovieInWindow: Create Graph");

            this.evrRenderer = FilterGraphTools.AddFilterFromClsid(this.graphBuilder, new Guid("{FA10746C-9B63-4B6C-BC49-FC300EA5F256}"), "EVR");

            if (evrRenderer != null)
            {
                FileLogger.Log("PlayMovieInWindow: Add EVR");

                SetupEvrDisplay();

                //#if DEBUG
                if (ps.PublishGraph)
                    rot = new DsROTEntry(this.graphBuilder);
                //#endif

                IObjectWithSite grfSite = graphBuilder as IObjectWithSite;
                if (grfSite != null)
                    grfSite.SetSite(new FilterBlocker(filename));

                string fileExt = Path.GetExtension(filename).ToLower();

                if (ps.PreferredDecoders != null)
                {
                    foreach (string pa in ps.PreferredDecoders)
                    {
                        string[] pvA = pa.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                        if (pvA[0].ToLower() == fileExt)
                        {
                            for (int i = 1; i < pvA.Length; i++)
                            {
                                string strFilter = pvA[i].Trim();
                                IBaseFilter filter = null;
                                try
                                {
                                    if (Regex.IsMatch(strFilter, @"{?\w{8}-\w{4}-\w{4}-\w{4}-\w{12}}?"))
                                        filter = FilterGraphTools.AddFilterFromClsid(graphBuilder, new Guid(strFilter), strFilter);
                                    else
                                        filter = FilterGraphTools.AddFilterByName(graphBuilder, FilterCategory.LegacyAmFilterCategory, strFilter);

                                    if (filter != null)
                                    {
                                        FileLogger.Log("Added {0} to the graph", strFilter);
                                    }
                                    else
                                        FileLogger.Log("{0} not added to the graph", strFilter);
                                }
                                finally
                                {
                                    if (filter != null)
                                        Marshal.ReleaseComObject(filter);
                                    filter = null;
                                }
                            }
                        }
                    }
                }
                // Have the graph builder construct its the appropriate graph automatically
                //hr = this.graphBuilder.RenderFile(filename, null);
                IBaseFilter sourceFilter = null;

                try
                {
                    hr = graphBuilder.AddSourceFilter(filename, "Source", out sourceFilter);
                    DsError.ThrowExceptionForHR(hr);

                    IPin outPin = DsFindPin.ByConnectionStatus(sourceFilter, PinConnectedStatus.Unconnected, 0);
                    while (outPin != null)
                    {
                        try
                        {
                            hr = graphBuilder.Render(outPin);
                            DsError.ThrowExceptionForHR(hr);
                        }
                        finally
                        {
                            if (outPin != null)
                                Marshal.ReleaseComObject(outPin);
                            outPin = null;
                        }
                        outPin = DsFindPin.ByConnectionStatus(sourceFilter, PinConnectedStatus.Unconnected, 0);
                    }
                }
                finally
                {
                    if (sourceFilter != null)
                        Marshal.ReleaseComObject(sourceFilter);
                }

                SetEvrVideoMode();

                // QueryInterface for DirectShow interfaces
                this.mediaControl = (IMediaControl)this.graphBuilder;
                this.mediaEventEx = (IMediaEventEx)this.graphBuilder;
                this.mediaSeeking = (IMediaSeeking)this.graphBuilder;
                this.mediaPosition = (IMediaPosition)this.graphBuilder;

                // Query for video interfaces, which may not be relevant for audio files
                //this.videoWindow = this.graphBuilder as IVideoWindow;
                //this.basicVideo = this.graphBuilder as IBasicVideo;

                // Query for audio interfaces, which may not be relevant for video-only files
                this.basicAudio = this.graphBuilder as IBasicAudio;

                // Is this an audio-only file (no video component)?
                CheckVisibility();

                // Have the graph signal event via window callbacks for performance
                hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WM.GRAPH_NOTIFY, IntPtr.Zero);
                DsError.ThrowExceptionForHR(hr);


                // Setup the video window
                //hr = this.videoWindow.put_Owner(this.Handle);
                //DsError.ThrowExceptionForHR(hr);
                this.evrDisplay.SetVideoWindow(container.Handle);

                //hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
                //DsError.ThrowExceptionForHR(hr);

                hr = InitVideoWindow(1, 1);
                DsError.ThrowExceptionForHR(hr);

                GetFrameStepInterface();


                // Complete window initialization
                //CheckSizeMenu(menuFileSizeNormal);
                //this.isFullScreen = false;
                this.currentPlaybackRate = 1.0;
                //UpdateMainTitle();

                container.Focus();

                //pre-roll the graph
                hr = this.mediaControl.Pause();
                DsError.ThrowExceptionForHR(hr);

                // Run the graph to play the media file
                hr = this.mediaControl.Run();
                DsError.ThrowExceptionForHR(hr);

                if (commWatcher != null)
                    commWatcher.Dispose();

                string commPath = Path.Combine(Path.GetDirectoryName(filename), Commercials.GetEdlFilename(filename));

                ReadComm(commPath);

                commWatcher = new FileSystemWatcher(Path.GetDirectoryName(filename), Commercials.GetEdlFilename(filename));
                commWatcher.Changed += new FileSystemEventHandler(commWatcher_Changed);
                commWatcher.Created += new FileSystemEventHandler(commWatcher_Changed);
                //commWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
                commWatcher.EnableRaisingEvents = true;

                MoveToBookmark();

                this.currentState = PlayState.Running;
                //if (isFullScreen)
                //    tmMouseMove.Enabled = true;
            }
            else
            {
                //MessageBox.Show("EVR cannot be loaded on this PC");
                using (EPDialog ed = new EPDialog())
                    ed.ShowDialog("EVR Error", "The Enhanced Video Renderer cannot be loaded on this PC", 30);
            }
        }
Exemple #5
0
        private void ChangePosition(long changeBy, AMSeekingSeekingFlags seekType)
        {
            long cPos, cDuration;
            int hr;

            try
            {
                hr = this.mediaSeeking.GetCurrentPosition(out cPos);
                DsError.ThrowExceptionForHR(hr);

                hr = this.mediaSeeking.GetDuration(out cDuration);
                DsError.ThrowExceptionForHR(hr);

                long nPos = 0;

                if (seekType == AMSeekingSeekingFlags.RelativePositioning)
                    nPos = cPos + (changeBy * TICK_MULT);
                else if (seekType == AMSeekingSeekingFlags.AbsolutePositioning)
                    nPos = changeBy;

                if (nPos < cDuration && nPos >= 0)
                {
                    DsLong ndspos = new DsLong(nPos);
                    hr = this.mediaSeeking.SetPositions(nPos, AMSeekingSeekingFlags.AbsolutePositioning, 0, AMSeekingSeekingFlags.NoPositioning);//mediaPosition.put_CurrentPosition(nPos);
                    DsError.ThrowExceptionForHR(hr);
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Error skipping: {0}", ex.Message);
                using (EPDialog ed = new EPDialog())
                    ed.ShowDialog("Error", string.Format("Error skipping: {0}", ex.Message), 10);
            }
        }
Exemple #6
0
        internal bool OpenClip(object objShowFileDialog)
        {
            if (this.InvokeRequired)
            {
                return (bool)this.Invoke(new BoolInvoke(OpenClip), new object[] { objShowFileDialog });
            }
            else
            {
                OpenClipMode showFileDialog = (OpenClipMode)objShowFileDialog;
                //CommonOpenFileDialog cfd = new CommonOpenFileDialog();
                //cfd.EnsureReadOnly = true;

                //if (showFileDialog == OpenClipMode.Folder)
                //{
                //    cfd.IsFolderPicker = true;
                //}
                //else
                //{
                //    cfd.IsFolderPicker = false;
                //}
                try
                {
                    //// If no filename specified by command line, show file open dialog
                    if (this.filename.Count == 0)
                    {
                        UpdateMainTitle();
                        this.filename.Clear();
                        
                        switch (showFileDialog)
                        {
                            case OpenClipMode.File:
                            case OpenClipMode.Url:
                                Durrant.Common.ApartmentStateSwitcher.Execute(new GetClipDelgate(GetClipFileName), new object[] {showFileDialog}, ApartmentState.STA);
                                break;
                            case OpenClipMode.Folder:
                                GetDvdPath();
                                break;
                        }
                    
                        if (this.filename.Count == 0)
                            return false;
                    }

                    // Reset status variables
                    this.currentState = PlayState.Stopped;
                    this.currentVolume = VolumeFull;

                    BuildHistoryMenu(this.filename[currentIndex]);

                    // Start playing the media file
                    if (Regex.IsMatch(this.filename[currentIndex], @"VIDEO_TS\\?$") || Path.GetExtension(this.filename[currentIndex]).ToLower() == ".ifo")
                        PlayDVDInWindow(this.filename[currentIndex]);
                    else
                        PlayMovieInWindow(this.filename[currentIndex]);

                    disabledScreenSaver = NativeMethods2.SystemParametersInfo(SPI.SPI_SETSCREENSAVEACTIVE,
                              Convert.ToUInt32(false),      // TRUE to enable
                              IntPtr.Zero,
                              SPIF.SPIF_SENDWININICHANGE
                             );

                    tmStatus.Enabled = true;
                    //if (isFullScreen)
                    ToogleControls(!isFullScreen);
                    this.Activate();
                    return true;
                }
                catch (Exception ex)
                {
                    FileLogger.Log("Error opening file: {0}", ex.ToString());
                    CloseClip();
                    //MessageBox.Show(string.Format("Error: {0}", ex.Message));
                    using (EPDialog ed = new EPDialog())
                        ed.ShowDialog("Error", string.Format("Error Opening: {0}", ex.Message), 20, this);
                }
                return false;
            }
        }
Exemple #7
0
        private void GetDvdPath()
        {
            //if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            //{
            //    if (folderBrowserDialog1.SelectedPath.ToLower().IndexOf("video_ts") < 0)
            //    {
            //        //MessageBox.Show("Please select a valid VIDEO_TS folder");
            //        using (EPDialog ed = new EPDialog())
            //            ed.ShowDialog("Error", "Please select a valid VIDEO_TS folder", 10, this);
            //    }
            //    else
            //        filename.Add(folderBrowserDialog1.SelectedPath);
            //}

            CommonOpenFileDialog cfd = new CommonOpenFileDialog();
            cfd.EnsureReadOnly = true;

            cfd.IsFolderPicker = true;
            if (cfd.ShowDialog() == CommonFileDialogResult.Ok)
            {
                if (cfd.FileName.ToLower().IndexOf("video_ts") < 0)
                {
                    //MessageBox.Show("Please select a valid VIDEO_TS folder");
                    using (EPDialog ed = new EPDialog())
                        ed.ShowDialog("Error", "Please select a valid VIDEO_TS folder", 10, this);
                }
                else
                    filename.Add(cfd.FileName);
            }
              
        }
Exemple #8
0
        internal bool ShowDvdMenu(DvdMenuId menu)
        {
            IDvdCmd icmd;

            if ((this.currentState != PlayState.Running) || (dvdCtrl == null))
            {
                return false;
            }
            else
            {
                try
                {
                    int hr = dvdCtrl.ShowMenu(menu, DvdCmdFlags.Block | DvdCmdFlags.Flush, out icmd);
                    DsError.ThrowExceptionForHR(hr);
                }
                catch (Exception ex)
                {
                    using (EPDialog ed = new EPDialog())
                        ed.ShowDialog("Error", ex.Message, 10, this);
                }
                return true;
            }
        }
Exemple #9
0
        private void miFileHistoryClick(object sender, EventArgs e)
        {
            MenuItem mi = (MenuItem)sender;
            string nfPath = (string)mi.Tag;
                
            try
            {
                Uri fUri = new Uri(nfPath);

                if ((fUri.IsFile && File.Exists(nfPath)) || !fUri.IsFile)
                {
                    if (this.currentState != PlayState.Init)
                        CloseClip();

                    filename.Clear();
                    currentIndex = 0;
                    filename.Add(nfPath);

                    // Open the new clip
                    OpenClip(OpenClipMode.None);
                }
                else if (Directory.Exists(nfPath) && nfPath.ToLower().IndexOf("video_ts") > 0)
                {
                    if (this.currentState != PlayState.Init)
                        CloseClip();

                    filename.Clear();
                    currentIndex = 0;
                    filename.Add(nfPath);

                    // Open the new clip
                    OpenClip(OpenClipMode.Folder);
                }
                else
                {
                    //MessageBox.Show(string.Format("{0} could not be found", nfPath));
                    using (EPDialog ed = new EPDialog())
                        ed.ShowDialog("Error", string.Format("{0} could not be found", nfPath), 10, this);
                }
            }
            catch (Exception ex)
            {
                using (EPDialog ed = new EPDialog())
                    ed.ShowDialog("Error", string.Format("Could not open {0}: {1}", nfPath, ex.Message), 10, this);
            }
        }
Exemple #10
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            //if (Environment.OSVersion.Version.Major < 6)
            //{
            //    //MessageBox.Show("This application will only run on Windows Vista or greater");
            //    using (EPDialog ed = new EPDialog())
            //        ed.ShowDialog("Error", "This application requires the Enhanced Video Renderer (EVR)", 10);
            //    this.Close();
            //}

            try
            {
                if (!FilterGraphTools.IsThisComObjectInstalled(new Guid("{FA10746C-9B63-4B6C-BC49-FC300EA5F256}")))
                {
                    using (EPDialog ed = new EPDialog())
                        ed.ShowDialog("Error", "This application requires the Enhanced Video Renderer (EVR).", 10, this);
                    this.Close();
                    return;
                }
            }
            catch (Exception ex)
            {
                using (EPDialog ed = new EPDialog())
                    ed.ShowDialog("Error", string.Format("Error Testing EVR: {0}", ex.Message), 10, this);
                this.Close();
                return;
            }

            RegistryKey runFrom = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\babgvant\EVRPlay", true);
            try
            {
                if (runFrom == null)
                    runFrom = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\babgvant\EVRPlay");

                runFrom.SetValue("LastRunFrom", Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
            }
            finally
            {
                if (runFrom != null)
                    runFrom.Close();
            }


            RawDevice.RegisterRawDevices(0xFFBC, 0x88, InputMode.BackgroundMode);
            RawDevice.RegisterRawDevices(0x0C, 0x01, InputMode.BackgroundMode);
            RawDevice.RegisterRawDevices(0x0C, 0x80, InputMode.BackgroundMode);
            
            RawDevice.RawInput += new EventHandler<RawInputEventArgs>(RawDevice_RawInput);

            //messageWindow = new SageMessageListener(this);
            try
            {
                messageWindow = new EVRPlayListener(this);
            }
            catch (Exception ex)
            {
                FileLogger.Log(ex.ToString());
            }

            if (ps.NeedsUpgrade)
            {
                ps.Upgrade();
                ps.NeedsUpgrade = false;
                ps.Save();
            }

            if (fHist.NeedsUpgrade)
            {
                fHist.Upgrade();
                fHist.NeedsUpgrade = false;
                fHist.Save();
            }

            miSkip1.Text = string.Format("Forward {0} Seconds", ps.SkipForward1);
            miSkipForward2.Text = string.Format("Forward {0} Seconds", ps.SkipForward2);
            miSkipBack1.Text = string.Format("Back {0} Seconds", ps.SkipBack1);
            miSkipBack2.Text = string.Format("Back {0} Seconds", ps.SkipBack2);
            BuildHistoryMenu(string.Empty);

            if (fHist.LastWidth == 0 || fHist.LastHeight == 0)
                ToggleFullScreen("Load");
            else
            {
                this.Width = fHist.LastWidth;
                this.Height = fHist.LastHeight;
            }

            pf = new ProgressForm();
            this.AddOwnedForm(pf);
            //pf.Owner = this;
            //pf.Show();

            //wbSageServer.Navigate(ABOUT_BLANK);
            //SHDocVw.WebBrowser axBrowser = (SHDocVw.WebBrowser)this.wbSageServer.ActiveXInstance;

            //axBrowser.NavigateError +=  new SHDocVw.DWebBrowserEvents2_NavigateErrorEventHandler(axBrowser_NavigateError);
            //axBrowser.BeforeNavigate2 += new SHDocVw.DWebBrowserEvents2_BeforeNavigate2EventHandler(axBrowser_BeforeNavigate2);

            if (ps.OpenMediaBrowser)
            {
                ShowMediaBrowser(BrowseMode.Recordings);
            }
            else if (ps.BrowseOnLoad)
            {
                CreateBrowserForm();
                bf.BrowseWebserver();
            }
        }
Exemple #11
0
        void MoveToBookmark()
        {
            try
            {
                if (File.Exists(BookmarkFile) && ps.UseBookmarks)
                {
                    if (dvdGraph == null)
                    {
                        using (StreamReader sr = File.OpenText(BookmarkFile))
                        {
                            string strPos = sr.ReadLine();
                            try
                            {
                                FileLogger.Log("MoveToBookmark: {0} - {1}", BookmarkFile, strPos);

                                currentPosition = Convert.ToInt64(strPos);
                                ChangePosition(currentPosition, AMSeekingSeekingFlags.AbsolutePositioning);
                            }
                            catch (Exception ex)
                            {
                                FileLogger.Log("MoveToBookmark error: {0}", ex.Message);
                            }
                        }
                    }
                    else
                    {
                        if (dvdCtrl != null)
                        {
                            IStorage storage = null;
                            IStream stream = null;
                            int hr = 0;
                            IDvdState pStateData = null;
                            IDvdCmd dCmd = null;

                            try
                            {
                                if (NativeMethods.StgIsStorageFile(BookmarkFile) != 0)
                                    throw new ArgumentException();

                                hr = NativeMethods.StgOpenStorage(
                                    BookmarkFile,
                                    null,
                                    STGM.Read | STGM.ShareExclusive,
                                    IntPtr.Zero,
                                    0,
                                    out storage
                                    );

                                Marshal.ThrowExceptionForHR(hr);

                                storage.OpenStream(
                                    @"EVRPlayDvdBookmark",
                                    IntPtr.Zero,
                                    (STGM.Read | STGM.ShareExclusive),
                                    0,
                                out stream
                                    );

                                Marshal.ThrowExceptionForHR(hr);
                                Guid stateGuid = new Guid("86303d6d-1c4a-4087-ab42-f711167048ef");
                                object state;

                                hr = NativeMethods2.OleLoadFromStream(stream, ref stateGuid, out state);
                                Marshal.ThrowExceptionForHR(hr);

                                pStateData = (IDvdState)state;

                                hr = dvdCtrl.SetState(pStateData, DvdCmdFlags.Block, out dCmd);
                                DsError.ThrowExceptionForHR(hr);
                            }
                            finally
                            {
                                if (stream != null)
                                    Marshal.ReleaseComObject(stream);
                                if (storage != null)
                                    Marshal.ReleaseComObject(storage);
                                if (pStateData != null)
                                    Marshal.ReleaseComObject(pStateData);
                                if (dCmd != null)
                                    Marshal.ReleaseComObject(dCmd);
                            }
                        }
                        //hr = (pStateData as IPersistStream).Load(stream);
                        //Marshal.ThrowExceptionForHR(hr);
                    }
                }
            }
            catch (Exception ex)
            {
                using (EPDialog ed = new EPDialog())
                    ed.ShowDialog("Bookmark Error", ex.Message, 10, this);
            }
        }
Exemple #12
0
        private void PlayMovieInWindow(string filename)
        {
            WindowsMediaLib.IWMReaderAdvanced2 wmReader = null;
            IBaseFilter sourceFilter = null;

            try
            {

                FileLogger.Log("PlayMovieInWindow: {0}", filename);
                lastJump = 0;

                int hr = 0;

                if (filename == string.Empty)
                    return;

                this.graphBuilder = (IGraphBuilder)new FilterGraph();
                FileLogger.Log("PlayMovieInWindow: Create Graph");

                this.evrRenderer = FilterGraphTools.AddFilterFromClsid(this.graphBuilder, new Guid("{FA10746C-9B63-4B6C-BC49-FC300EA5F256}"), "EVR");

                if (evrRenderer != null)
                {
                    FileLogger.Log("PlayMovieInWindow: Add EVR");

                    SetupEvrDisplay();

                    //#if DEBUG
                    if (ps.PublishGraph)
                        rot = new DsROTEntry(this.graphBuilder);
                    //#endif

                    IObjectWithSite grfSite = graphBuilder as IObjectWithSite;
                    if (grfSite != null)
                        grfSite.SetSite(new FilterBlocker(filename));

                    string fileExt = Path.GetExtension(filename).ToLower();

                    if (ps.PreferredDecoders != null)
                    {
                        foreach (string pa in ps.PreferredDecoders)
                        {
                            string[] pvA = pa.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                            if (pvA[0].ToLower() == fileExt)
                            {
                                for (int i = 1; i < pvA.Length; i++)
                                {
                                    string strFilter = pvA[i].Trim();
                                    IBaseFilter filter = null;
                                    try
                                    {
                                        if (Regex.IsMatch(strFilter, @"{?\w{8}-\w{4}-\w{4}-\w{4}-\w{12}}?"))
                                            filter = FilterGraphTools.AddFilterFromClsid(graphBuilder, new Guid(strFilter), strFilter);
                                        else
                                            filter = FilterGraphTools.AddFilterByName(graphBuilder, FilterCategory.LegacyAmFilterCategory, strFilter);

                                        if (filter != null)
                                        {
                                            FileLogger.Log("Added {0} to the graph", strFilter);
                                        }
                                        else
                                            FileLogger.Log("{0} not added to the graph", strFilter);
                                    }
                                    finally
                                    {
                                        if (filter != null)
                                            Marshal.ReleaseComObject(filter);
                                        filter = null;
                                    }
                                }
                            }
                        }
                    }
                    // Have the graph builder construct its the appropriate graph automatically
                    //hr = this.graphBuilder.RenderFile(filename, null);
                    if (ps.UseCustomAudioRenderer)
                    {
                        m_audioRendererClsid = new Guid(ps.CustomAudioRender);
                    }

                    audioRenderer = FilterGraphTools.AddFilterFromClsid(graphBuilder, m_audioRendererClsid, "Audio Renderer");
                    //IAVSyncClock wtf = audioRenderer as IAVSyncClock;
                    //double cap;
                    //hr = wtf.GetBias(out cap);
                    //IMPAudioSettings arSett = audioRenderer as IMPAudioSettings;
                    //if (arSett != null)
                    //{
                    //    AC3Encoding ac3Mode;
                    //    hr = arSett.GetAC3EncodingMode(out ac3Mode);
                    //    SpeakerConfig sc;
                    //    hr = arSett.GetSpeakerConfig(out sc);
                    //    AUDCLNT_SHAREMODE sm;
                    //    hr = arSett.GetWASAPIMode(out sm);
                    //    bool em;
                    //    hr = arSett.GetUseWASAPIEventMode(out em);
                    //    /*DeviceDefinition[] */IntPtr dc;
                    //    //int count;
                    //    //hr = arSett.GetAvailableAudioDevices(out dc, out count);
                    //    //DsError.ThrowExceptionForHR(hr);

                    //    ////DeviceDefinition[] dd = new DeviceDefinition[count];
                    //    //AudioDeviceDefinition dd = (AudioDeviceDefinition)Marshal.PtrToStructure(dc, typeof(AudioDeviceDefinition));
                    //    //if (dc != null)
                    //    //    Marshal.ReleaseComObject(dc);
                    //    hr = arSett.SetAudioDeviceById(null);
                    //    //arSett.SetSpeakerMatchOutput(true);

                    //    arSett.SetUseWASAPIEventMode(true);
                    //    arSett.SetUseFilters((int)MPARUseFilters.ALL);
                    //    arSett.SetAllowBitStreaming(true);
                    //    arSett.SetAC3EncodingMode(AC3Encoding.DISABLED);
                    //    arSett.SetUseTimeStretching(false);
                    //}

                    IMPAudioRendererConfig arSett = audioRenderer as IMPAudioRendererConfig;
                    if (arSett != null)
                    {
                        int ac3Mode;
                        hr = arSett.GetInt(MPARSetting.AC3_ENCODING, out ac3Mode);
                        int sc;
                        hr = arSett.GetInt(MPARSetting.SPEAKER_CONFIG, out sc);
                        int sm;
                        hr = arSett.GetInt(MPARSetting.WASAPI_MODE, out sm);
                        bool em;
                        hr = arSett.GetBool(MPARSetting.WASAPI_EVENT_DRIVEN, out em);
                        /*DeviceDefinition[] */
                        IntPtr dc;
                        //int count;
                        //hr = arSett.GetAvailableAudioDevices(out dc, out count);
                        //DsError.ThrowExceptionForHR(hr);

                        ////DeviceDefinition[] dd = new DeviceDefinition[count];
                        //AudioDeviceDefinition dd = (AudioDeviceDefinition)Marshal.PtrToStructure(dc, typeof(AudioDeviceDefinition));
                        //if (dc != null)
                        //    Marshal.ReleaseComObject(dc);
                        hr = arSett.SetString(MPARSetting.SETTING_AUDIO_DEVICE, ps.AudioPlaybackDevice);
                        //arSett.SetSpeakerMatchOutput(true);

                        arSett.SetBool(MPARSetting.WASAPI_EVENT_DRIVEN, true);
                        arSett.SetInt(MPARSetting.USE_FILTERS, (int)MPARUseFilters.ALL);
                        arSett.SetBool(MPARSetting.ALLOW_BITSTREAMING, true);
                        arSett.SetInt(MPARSetting.AC3_ENCODING, (int)AC3Encoding.DISABLED);
                        arSett.SetBool(MPARSetting.ENABLE_TIME_STRETCHING, false);
                    }
                    
                    //try
                    //{
                        hr = graphBuilder.AddSourceFilter(filename, "Source", out sourceFilter);
                        if (hr < 0)
                        {
                            //if it doesn't work before failing try to load it with the WMV reader
                            sourceFilter = (IBaseFilter)new WMAsfReader();
                            hr = graphBuilder.AddFilter(sourceFilter, "WM/ASF Reader");
                            DsError.ThrowExceptionForHR(hr);

                            hr = ((IFileSourceFilter)sourceFilter).Load(filename, null);
                            DsError.ThrowExceptionForHR(hr);

                            wmReader = sourceFilter as WindowsMediaLib.IWMReaderAdvanced2;
                        }

                        IPin outPin = DsFindPin.ByConnectionStatus(sourceFilter, PinConnectedStatus.Unconnected, 0);
                        while (outPin != null)
                        {
                            try
                            {
                                hr = graphBuilder.Render(outPin);
                                DsError.ThrowExceptionForHR(hr);
                            }
                            finally
                            {
                                if (outPin != null)
                                    Marshal.ReleaseComObject(outPin);
                                outPin = null;
                            }
                            outPin = DsFindPin.ByConnectionStatus(sourceFilter, PinConnectedStatus.Unconnected, 0);
                        }

                        if (ps.MultiChannelWMA)
                        {
                            FileLogger.Log("Set multichannel mode for WMA");

                            IBaseFilter wmaDec = FilterGraphTools.FindFilterByName(graphBuilder, "WMAudio Decoder DMO");
                            if (wmaDec != null)
                            {
                                try
                                {
                                    //http://msdn.microsoft.com/en-us/library/aa390550(VS.85).aspx
                                    IPropertyBag bag = wmaDec as IPropertyBag;
                                    if (bag != null)
                                    {
                                        object pVar;
                                        hr = bag.Read("_HIRESOUTPUT", out pVar, null);
                                        DsError.ThrowExceptionForHR(hr);
                                        bool bVar = (bool)pVar;
                                        FileLogger.Log("_HIRESOUTPUT = {0}", bVar);
                                        if (!bVar)
                                        {
                                            IPin wmaOut = DsFindPin.ByDirection(wmaDec, PinDirection.Output, 0);
                                            IPin cPin = null;

                                            try
                                            {
                                                hr = wmaOut.ConnectedTo(out cPin);
                                                DsError.ThrowExceptionForHR(hr);

                                                if (cPin != null) //cpin should never be null at this point, but lets be safe
                                                {
                                                    hr = wmaOut.Disconnect();
                                                    DsError.ThrowExceptionForHR(hr);
                                                
                                                    List<Guid> oldFilters = new List<Guid>();
                                                    IBaseFilter oFilt = FilterGraphTools.GetFilterFromPin(cPin);
                                                    try
                                                    {
                                                        while (oFilt != null)
                                                        {
                                                            IBaseFilter cFilter = null;

                                                            try
                                                            {
                                                                Guid clsid;
                                                                hr = oFilt.GetClassID(out clsid);
                                                                DsError.ThrowExceptionForHR(hr);

                                                                if (clsid != DSOUND_RENDERER)
                                                                {
                                                                    oldFilters.Add(clsid);
                                                                    cFilter = FilterGraphTools.GetConnectedFilter(oFilt, PinDirection.Output, 0);
                                                                }
                                                                hr = graphBuilder.RemoveFilter(oFilt);
                                                                DsError.ThrowExceptionForHR(hr);
                                                            }
                                                            finally
                                                            {
                                                                if (oFilt != null)
                                                                    Marshal.ReleaseComObject(oFilt);
                                                                oFilt = null;
                                                            }
                                                            oFilt = cFilter;
                                                        }
                                                    }
                                                    finally
                                                    {
                                                        if (oFilt != null)
                                                            Marshal.ReleaseComObject(oFilt);
                                                        oFilt = null;
                                                    }

                                                    foreach (Guid addFilt in oldFilters)
                                                    {
                                                        IBaseFilter addMe = FilterGraphTools.AddFilterFromClsid(graphBuilder, addFilt, addFilt.ToString());
                                                        if (addMe != null)
                                                            Marshal.ReleaseComObject(addMe);
                                                    }
                                                }

                                                pVar = true;
                                                hr = bag.Write("_HIRESOUTPUT", ref pVar);
                                                DsError.ThrowExceptionForHR(hr);

                                                hr = graphBuilder.Render(wmaOut);
                                                DsError.ThrowExceptionForHR(hr);

                                            }
                                            finally
                                            {
                                                if (wmaOut != null)
                                                    Marshal.ReleaseComObject(wmaOut);
                                                if (cPin != null)
                                                    Marshal.ReleaseComObject(cPin);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    FileLogger.Log("Error setting multichannel mode for WMA: {0}", ex.Message);
                                }
                                finally
                                {
                                    while(Marshal.ReleaseComObject(wmaDec) > 0);
                                }
                            }
                        }
                    //}
                    //finally
                    //{
                    //    if (sourceFilter != null)
                    //        Marshal.ReleaseComObject(sourceFilter);
                    //}
                        if (ps.DXVAWMV)
                        {
                            FileLogger.Log("Set DXVA for WMV");
                            IBaseFilter wmvDec = FilterGraphTools.FindFilterByName(graphBuilder, "WMVideo Decoder DMO");
                            if (wmvDec != null)
                            {
                                try
                                {
                                    MediaFoundation.Misc.IPropertyStore config = wmvDec as MediaFoundation.Misc.IPropertyStore;

                                    if (config != null)
                                    {
                                        MediaFoundation.Misc.PropVariant pv = new MediaFoundation.Misc.PropVariant();
                                        //config.GetValue(MediaFoundation.Misc.WMVConst.MFPKEY_DXVA_ENABLED, pv);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    FileLogger.Log("Error setting DXVA mode for WMV: {0}", ex.Message);
                                }
                                finally
                                {
                                    while (Marshal.ReleaseComObject(wmvDec) > 0) ;
                                }
                            }
                        }

                    SetEvrVideoMode();

                    // QueryInterface for DirectShow interfaces
                    this.mediaControl = (IMediaControl)this.graphBuilder;
                    this.mediaEventEx = (IMediaEventEx)this.graphBuilder;
                    this.mediaSeeking = (IMediaSeeking)this.graphBuilder;
                    this.mediaPosition = (IMediaPosition)this.graphBuilder;

                    // Query for video interfaces, which may not be relevant for audio files
                    //this.videoWindow = this.graphBuilder as IVideoWindow;
                    //this.basicVideo = this.graphBuilder as IBasicVideo;

                    // Query for audio interfaces, which may not be relevant for video-only files
                    this.basicAudio = this.graphBuilder as IBasicAudio;

                    // Is this an audio-only file (no video component)?
                    CheckVisibility();

                    // Have the graph signal event via window callbacks for performance
                    hr = this.mediaEventEx.SetNotifyWindow(this.Handle, WM.GRAPH_NOTIFY, IntPtr.Zero);
                    DsError.ThrowExceptionForHR(hr);

                    if (!this.isAudioOnly)
                    {
                        // Setup the video window
                        //hr = this.videoWindow.put_Owner(this.Handle);
                        //DsError.ThrowExceptionForHR(hr);
                        //this.evrDisplay.SetVideoWindow(this.Handle);

                        //hr = this.videoWindow.put_WindowStyle(WindowStyle.Child | WindowStyle.ClipSiblings | WindowStyle.ClipChildren);
                        //DsError.ThrowExceptionForHR(hr);

                        hr = InitVideoWindow();//1, 1);
                        DsError.ThrowExceptionForHR(hr);

                        GetFrameStepInterface();
                    }
                    else
                    {
                        // Initialize the default player size and enable playback menu items
                        hr = InitPlayerWindow();
                        DsError.ThrowExceptionForHR(hr);

                        EnablePlaybackMenu(true, MediaType.Audio);
                    }

                    // Complete window initialization
                    //CheckSizeMenu(menuFileSizeNormal);
                    //this.isFullScreen = false;
                    this.currentPlaybackRate = 1.0;
                    UpdateMainTitle();

                    this.Activate();

                    //pre-roll the graph
                    hr = this.mediaControl.Pause();
                    DsError.ThrowExceptionForHR(hr);

                    if (wmReader != null)
                    {
                        WindowsMediaLib.PlayMode pMode;

                        hr = wmReader.GetPlayMode(out pMode);
                        DsError.ThrowExceptionForHR(hr);
                        
                        if (pMode == WindowsMediaLib.PlayMode.Streaming)
                        {
                            int pdwPercent = 0;
                            long pcnsBuffering;

                            while (pdwPercent < 100)
                            {
                                hr = wmReader.GetBufferProgress(out pdwPercent, out pcnsBuffering);
                                DsError.ThrowExceptionForHR(hr);

                                if (pdwPercent >= 100)
                                    break;

                                int sleepFor = Convert.ToInt32(pcnsBuffering / 1000);
                                Thread.Sleep(100);
                            }
                        }
                    }

                    // Run the graph to play the media file
                    hr = this.mediaControl.Run();
                    DsError.ThrowExceptionForHR(hr);

                    if (commWatcher != null)
                        commWatcher.Dispose();

                    string commPath = string.Empty;

                    if (ps.UseDtbXml)
                    {
                        commWatcher = new FileSystemWatcher(Commercials.XmlDirectory, Commercials.GetXmlFilename(filename));
                        commPath = Path.Combine(Commercials.XmlDirectory, Commercials.GetXmlFilename(filename));
                    }
                    else
                    {
                        commWatcher = new FileSystemWatcher(Path.GetDirectoryName(filename), Commercials.GetEdlFilename(filename));
                        commPath = Path.Combine(Path.GetDirectoryName(filename), Commercials.GetEdlFilename(filename));
                    }

                    ReadComm(commPath);

                    commWatcher.Changed += new FileSystemEventHandler(commWatcher_Changed);
                    commWatcher.Created += new FileSystemEventHandler(commWatcher_Changed);
                    //commWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
                    commWatcher.EnableRaisingEvents = true;

                    MoveToBookmark();

                    this.currentState = PlayState.Running;
                    if (isFullScreen)
                        tmMouseMove.Enabled = true;
                }
                else
                {
                    //MessageBox.Show("EVR cannot be loaded on this PC");
                    using (EPDialog ed = new EPDialog())
                        ed.ShowDialog("Error", "The Enhanced Video Renderer cannot be loaded", 20, this);
                }
            }
            finally
            {
                //if (wmReader != null)
                //    Marshal.ReleaseComObject(wmReader);
                if (sourceFilter != null)
                    while(Marshal.ReleaseComObject(sourceFilter)>0);
            }
        }