示例#1
0
        private void SetupProperties(MediaInfo mediaInfo)
        {
            BestVideoStream = VideoStreams.OrderByDescending(
                x => (long)x.Width * x.Height * x.BitDepth * (x.Stereoscopic == StereoMode.Mono ? 1L : 2L) * x.FrameRate)
                              .FirstOrDefault();
            VideoCodec      = BestVideoStream?.CodecName ?? string.Empty;
            VideoResolution = BestVideoStream?.Resolution ?? string.Empty;
            Width           = BestVideoStream?.Width ?? 0;
            Height          = BestVideoStream?.Height ?? 0;
            IsInterlaced    = BestVideoStream?.Interlaced ?? false;
            Framerate       = BestVideoStream?.FrameRate ?? 0;
            ScanType        = BestVideoStream != null
                   ? mediaInfo.Get(StreamKind.Video, BestVideoStream.StreamPosition, "ScanType").ToLower()
                   : string.Empty;

            AspectRatio = BestVideoStream != null
                      ? mediaInfo.Get(StreamKind.Video, BestVideoStream.StreamPosition, "DisplayAspectRatio")
                      : string.Empty;

            AspectRatio = AspectRatio == "4:3" || AspectRatio == "1.333" ? "fullscreen" : "widescreen";

            BestAudioStream       = AudioStreams.OrderByDescending(x => x.Channel * 10000000 + x.Bitrate).FirstOrDefault();
            AudioCodec            = BestAudioStream?.CodecName ?? string.Empty;
            AudioRate             = (int?)BestAudioStream?.Bitrate ?? 0;
            AudioChannels         = BestAudioStream?.Channel ?? 0;
            AudioChannelsFriendly = BestAudioStream?.AudioChannelsFriendly ?? string.Empty;
        }
示例#2
0
 internal MediaAnalysis(string path, FFProbeAnalysis analysis)
 {
     VideoStreams       = analysis.Streams.Where(stream => stream.CodecType == "video").Select(ParseVideoStream).ToList();
     AudioStreams       = analysis.Streams.Where(stream => stream.CodecType == "audio").Select(ParseAudioStream).ToList();
     PrimaryVideoStream = VideoStreams.OrderBy(stream => stream.Index).FirstOrDefault();
     PrimaryAudioStream = AudioStreams.OrderBy(stream => stream.Index).FirstOrDefault();
     Path = path;
 }
示例#3
0
        public override void OnVideoOpened()
        {
            foreach (var stream in Player.decoder.demuxer.streams)
            {
                if (stream.Type == FFmpeg.AutoGen.AVMediaType.AVMEDIA_TYPE_AUDIO)
                {
                    AudioStreams.Add(new AudioStream()
                    {
                        DecoderInput = new DecoderInput()
                        {
                            StreamIndex = stream.StreamIndex
                        },
                        BitRate  = stream.BitRate,
                        Language = Language.Get(stream.Language),

                        SampleFormat = stream.SampleFormatStr,
                        SampleRate   = stream.SampleRate,
                        Channels     = stream.Channels,
                        Bits         = stream.Bits
                    });
                }
                else if (stream.Type == FFmpeg.AutoGen.AVMediaType.AVMEDIA_TYPE_VIDEO)
                {
                    VideoStream videoStream    = new VideoStream();
                    VideoStream ptrVideoStream = stream.StreamIndex == Player.decoder.vDecoder.st->index ? defaultVideo : videoStream;

                    ptrVideoStream.DecoderInput = new DecoderInput()
                    {
                        StreamIndex = stream.StreamIndex
                    };
                    ptrVideoStream.BitRate  = stream.BitRate;
                    ptrVideoStream.Language = Language.Get(stream.Language);

                    ptrVideoStream.PixelFormat = stream.PixelFormatStr;
                    ptrVideoStream.Width       = stream.Width;
                    ptrVideoStream.Height      = stream.Height;
                    ptrVideoStream.FPS         = stream.FPS;
                    VideoStreams.Add(ptrVideoStream);
                }
                else if (stream.Type == FFmpeg.AutoGen.AVMediaType.AVMEDIA_TYPE_SUBTITLE)
                {
                    SubtitleStreams.Add(new SubtitleStream()
                    {
                        DecoderInput = new DecoderInput()
                        {
                            StreamIndex = stream.StreamIndex
                        },
                        BitRate  = stream.BitRate,
                        Language = Language.Get(stream.Language),

                        Downloaded = true,
                        Converted  = true
                    });
                }
            }

            defaultVideo.InUse = true;
        }
示例#4
0
        ////------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Initializes a new instance of the <see cref="AudioInfo" /> class.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <exception cref="System.ArgumentNullException">Thrown if stream is null.</exception>
        private AudioInfo(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            _stream = stream;
            AudioTags = new AudioTags();
            AudioStreams = new AudioStreams();
        }
示例#5
0
        /// <summary>
        /// Formatiert den Wert der aktuellen Instanz unter Verwendung des angegebenen Formats.
        /// </summary>
        /// <returns>
        /// Der Wert der aktuellen Instanz im angegebenen Format.
        /// </returns>
        /// <param name="format">Das zu verwendende Format.– oder – Ein NULL-Verweis (Nothing in Visual Basic),
        ///  wenn das für den Typ der <see cref="T:System.IFormattable"/> -Implementierung definierte Standardformat verwendet werden soll. </param>
        /// <param name="formatProvider">Der zum Formatieren des Werts zu verwendende Anbieter.– oder – Ein NULL-Verweis (Nothing in Visual Basic),
        ///  wenn die Informationen über numerische Formate dem aktuellen Gebietsschema des Betriebssystems entnommen werden sollen. </param>
        /// <filterpriority>2</filterpriority>
        public string ToString(string format, IFormatProvider formatProvider)
        {
            var result = string.Empty;

            result += $"JobName:            {JobName} {Environment.NewLine}";
            result += $"BaseName:           {BaseName} {Environment.NewLine}";
            result += $"InputFile:          {InputFile} {Environment.NewLine}";
            result += $"InputType:          {Input} {Environment.NewLine}";
            result += $"OutputFile:         {OutputFile} {Environment.NewLine}";
            result += Environment.NewLine;

            result += $"AudioStreams:       {Environment.NewLine}";
            result  = AudioStreams.Aggregate(result, (current, item) => current + $"{item} {Environment.NewLine}");
            result += Environment.NewLine;

            result += $"SubtitleStreams:    {Environment.NewLine}";
            result  = SubtitleStreams.Aggregate(result, (current, item) => current + $"{item} {Environment.NewLine}");
            result += Environment.NewLine;

            var list = new List <string>();

            foreach (var item in Chapters)
            {
                var dt = DateTime.MinValue.Add(item);
                list.Add(dt.ToString("H:mm:ss.fff"));
            }
            result += $"Chapters:           {string.Join(",", list.ToArray())} {Environment.NewLine}";

            result += $"NextStep:           {NextStep} {Environment.NewLine}";
            result += $"CompletedStep:      {CompletedStep} {Environment.NewLine}";
            result += Environment.NewLine;

            result += $"VideoStream:        {Environment.NewLine}";
            result += $"{VideoStream} {Environment.NewLine}";
            result += Environment.NewLine;

            result += $"StreamID:           {StreamId:0} {Environment.NewLine}";
            result += $"TrackID:            {TrackId:0} {Environment.NewLine}";

            result += $"TempInput:          {TempInput} {Environment.NewLine}";
            result += $"TempOutput:         {TempOutput} {Environment.NewLine}";
            result += $"DumpOutput:         {DumpOutput} {Environment.NewLine}";
            result += $"SelectedDVDChapters:{SelectedDvdChapters} {Environment.NewLine}";
            result += $"TempFiles:          {string.Join(",", TempFiles.ToArray())} {Environment.NewLine}";
            result += $"ReturnValue:        {ExitCode:0} {Environment.NewLine}";

            return(result);
        }
示例#6
0
        /// <inheritdoc/>
        public void Dispose()
        {
            if (isDisposed)
            {
                return;
            }

            var video = VideoStreams.Cast <MediaStream>();
            var audio = AudioStreams.Cast <MediaStream>();

            var streams = video.Concat(audio);

            foreach (var stream in streams)
            {
                stream.Dispose();
            }

            container.Dispose();

            isDisposed = true;
        }
示例#7
0
        private void ExtractInfo(string filePath, string pathToDll, NumberFormatInfo providerNumber)
        {
            using (var mediaInfo = new MediaInfo(pathToDll))
            {
                Version = mediaInfo.Option("Info_Version");
                mediaInfo.Open(filePath);

                var streamNumber = 0;

                // Setup videos
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Video); ++i)
                {
                    VideoStreams.Add(new VideoStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                if (VideoDuration == 0)
                {
                    double duration;
                    double.TryParse(
                        mediaInfo.Get(StreamKind.Video, 0, "Duration"),
                        NumberStyles.AllowDecimalPoint,
                        providerNumber,
                        out duration);
                    VideoDuration = (int)duration;
                }

                // Setup audios
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Audio); ++i)
                {
                    AudioStreams.Add(new AudioStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                // Setup subtitles
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Text); ++i)
                {
                    Subtitles.Add(new SubtitleStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                // Setup chapters
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Other); ++i)
                {
                    Chapters.Add(new ChapterStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                // Setup menus
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Menu); ++i)
                {
                    MenuStreams.Add(new MenuStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                MediaInfoNotloaded = VideoStreams.Count == 0 && AudioStreams.Count == 0 && Subtitles.Count == 0;

                // Produce copability properties
                if (MediaInfoNotloaded)
                {
                    SetPropertiesDefault();
                }
                else
                {
                    SetupProperties(mediaInfo);
                }
            }
        }
示例#8
0
 public virtual void OnInitialized()
 {
     AudioStreams.Clear();
     VideoStreams.Clear();
     SubtitleStreams.Clear();
 }
示例#9
0
        public void ReadStreamInfo()
        {
            List <string> output = new List <string>(); //the list that holds the mkvInfo output

            try
            {
                //create the process that will execute mkvinfo.  Hide the cmd window and redirect the output
                Process p = new Process();
                p.StartInfo = new ProcessStartInfo(Path, "\"" + mkvPath + "\""); //assign the argument
                p.StartInfo.UseShellExecute        = false;
                p.StartInfo.CreateNoWindow         = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.Start();
                StreamReader reader = p.StandardOutput;
                Tools.WriteLogLine("Mkv Command: " + Path + " \"" + mkvPath + "\"");

                //add each line of the output to the output list
                while (!reader.EndOfStream)
                {
                    string line = reader.ReadLine();
                    if (line.Length > 0)
                    {
                        output.Add(line);
                        Tools.WriteLogLine(line);
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show("Unable to execute MkvInfo:" + Environment.NewLine + ex.ToString());
            }


            //search the output list for audio and subtitle streams
            for (int i = 0; i < output.Count; i++)
            {
                if (output[i].Contains("Track type: subtitles") || output[i].Contains("Track type: audio") || output[i].Contains("Track type: video"))
                {
                    //instantiate temporary variables
                    int        uid       = -1;
                    string     language  = "Unknown";
                    bool       isDefault = true;
                    StreamType stream    = StreamType.Unknown;
                    string     codec     = "Unknown";

                    if (output[i].Contains("Track type: subtitles"))
                    {
                        stream = StreamType.Subtitles;
                    }

                    if (output[i].Contains("Track type: audio"))
                    {
                        stream = StreamType.Audio;
                    }

                    if (output[i].Contains("Track type: video"))
                    {
                        stream = StreamType.Video;
                    }

                    //parse the id number
                    Match trackNumberMatch = Regex.Match(output[i - 2], @"Track number: \d+ \(track ID for mkvmerge & mkvextract: (?<trackNumber>\d+)\)");
                    if (trackNumberMatch.Success)
                    {
                        uid = Convert.ToInt32(trackNumberMatch.Groups["trackNumber"].Value);
                    }
                    else
                    {
                        Match trackNumberMatch2 = Regex.Match(output[i - 3], @"Track number: \d+ \(track ID for mkvmerge & mkvextract: (?<trackNumber>\d+)\)");
                        if (trackNumberMatch2.Success)
                        {
                            uid = Convert.ToInt32(trackNumberMatch2.Groups["trackNumber"].Value);
                        }
                    }

                    //get other stream info
                    for (int j = i; j < output.Count; j++)
                    {
                        try
                        {
                            if (output[j].Contains("+ Language:"))
                            {
                                Match languageMatch = Regex.Match(output[j], @"^.+: (?<language>.*$)");
                                if (languageMatch.Success)
                                {
                                    language = languageMatch.Groups["language"].Value;
                                }
                            }
                        }
                        catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); }

                        try
                        {
                            if (output[j].Contains("+ Codec ID:"))
                            {
                                codec = output[j].Substring(15);
                            }
                            //System.Windows.Forms.MessageBox.Show(j.ToString());
                        }
                        catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); }

                        try
                        {
                            if (output[j].Contains("+ Default flag: 0"))
                            {
                                isDefault = false;
                            }
                        }
                        catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); }

                        //when the search reaches the next stream, stop
                        if (output[j].Contains("A track"))
                        {
                            i = j;
                            break;
                        }
                    }

                    //add the stream info to the appropriate list
                    if (stream == StreamType.Subtitles)
                    {
                        Subtitles.Add(new MkvInfoStreamInfo(uid, codec, language, isDefault, stream));
                    }

                    if (stream == StreamType.Audio)
                    {
                        AudioStreams.Add(new MkvInfoStreamInfo(uid, codec, language, isDefault, stream));
                    }

                    if (stream == StreamType.Video)
                    {
                        VideoStreams.Add(new MkvInfoStreamInfo(uid, codec, language, isDefault, stream));
                    }
                }
                if (output[i].Contains("+ Chapters"))
                {
                    for (int j = i; j < output.Count; j++)
                    {
                        if (output[j].Contains("+ ChapterAtom"))
                        {
                            Chapters.AddChapter();
                        }
                    }
                }
            }
        }
        private void ExtractInfo(string filePath, NumberFormatInfo providerNumber)
#endif
        {
#if (NET40 || NET45)
            using (var mediaInfo = new MediaInfo(pathToDll))
#else
            using (var mediaInfo = new MediaInfo())
#endif
            {
                if (mediaInfo.Handle == IntPtr.Zero)
                {
                    MediaInfoNotloaded = true;
                    _logger.LogWarning("MediaInfo library was not loaded!");
                    return;
                }
                else
                {
                    Version = mediaInfo.Option("Info_Version");
                    _logger.LogDebug($"MediaInfo library was loaded. Handle={mediaInfo.Handle} Version is {Version}");
                }

                var filePricessingHandle = mediaInfo.Open(filePath);
                if (filePricessingHandle == IntPtr.Zero)
                {
                    MediaInfoNotloaded = true;
                    _logger.LogWarning($"MediaInfo library has not been opened media {filePath}");
                    return;
                }
                else
                {
                    _logger.LogDebug($"MediaInfo library successfully opened {filePath}. Handle={filePricessingHandle}");
                }

                var streamNumber = 0;

                Tags = new AudioTagBuilder(mediaInfo, 0).Build();

                // Setup videos
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Video); ++i)
                {
                    VideoStreams.Add(new VideoStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                if (Duration == 0)
                {
                    double.TryParse(
                        mediaInfo.Get(StreamKind.Video, 0, (int)NativeMethods.Video.Video_Duration),
                        NumberStyles.AllowDecimalPoint,
                        providerNumber,
                        out var duration);
                    Duration = (int)duration;
                }

                // Fix 3D for some containers
                if (VideoStreams.Count == 1 && Tags.GeneralTags.TryGetValue((NativeMethods.General) 1000, out var isStereo))
                {
                    var video = VideoStreams.First();
                    if (Tags.GeneralTags.TryGetValue((NativeMethods.General) 1001, out var stereoMode))
                    {
                        video.Stereoscopic = (StereoMode)stereoMode;
                    }
                    else
                    {
                        video.Stereoscopic = (bool)isStereo ? StereoMode.Stereo : StereoMode.Mono;
                    }
                }

                // Setup audios
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Audio); ++i)
                {
                    AudioStreams.Add(new AudioStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                if (Duration == 0)
                {
                    double.TryParse(
                        mediaInfo.Get(StreamKind.Audio, 0, (int)NativeMethods.Audio.Audio_Duration),
                        NumberStyles.AllowDecimalPoint,
                        providerNumber,
                        out var duration);
                    Duration = (int)duration;
                }

                // Setup subtitles
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Text); ++i)
                {
                    Subtitles.Add(new SubtitleStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                // Setup chapters
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Other); ++i)
                {
                    Chapters.Add(new ChapterStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                // Setup menus
                for (var i = 0; i < mediaInfo.CountGet(StreamKind.Menu); ++i)
                {
                    MenuStreams.Add(new MenuStreamBuilder(mediaInfo, streamNumber++, i).Build());
                }

                MediaInfoNotloaded = VideoStreams.Count == 0 && AudioStreams.Count == 0 && Subtitles.Count == 0;

                // Produce capability properties
                if (MediaInfoNotloaded)
                {
                    SetPropertiesDefault();
                }
                else
                {
                    SetupProperties(mediaInfo);
                }
            }
        }
示例#11
0
        /// <summary>
        /// Formatiert den Wert der aktuellen Instanz unter Verwendung des angegebenen Formats.
        /// </summary>
        /// <returns>
        /// Der Wert der aktuellen Instanz im angegebenen Format.
        /// </returns>
        /// <param name="format">Das zu verwendende Format.– oder – Ein NULL-Verweis (Nothing in Visual Basic),
        ///  wenn das für den Typ der <see cref="T:System.IFormattable"/> -Implementierung definierte Standardformat verwendet werden soll. </param>
        /// <param name="formatProvider">Der zum Formatieren des Werts zu verwendende Anbieter.– oder – Ein NULL-Verweis (Nothing in Visual Basic),
        ///  wenn die Informationen über numerische Formate dem aktuellen Gebietsschema des Betriebssystems entnommen werden sollen. </param>
        /// <filterpriority>2</filterpriority>
        public string ToString(string format, IFormatProvider formatProvider)
        {
            string result = string.Empty;

            result += string.Format(AppSettings.CInfo, "JobName:            {0:s} {1:s}", JobName, Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "BaseName:           {0:s} {1:s}", BaseName, Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "InputFile:          {0:s} {1:s}", InputFile, Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "InputType:          {0:s} {1:s}", Input.ToString(),
                                    Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "OutputFile:         {0:s} {1:s}", OutputFile,
                                    Environment.NewLine);
            result += Environment.NewLine;

            result += string.Format(AppSettings.CInfo, "AudioStreams:       {0:s}", Environment.NewLine);

            result = AudioStreams.Aggregate(result,
                                            (current, item) =>
                                            current +
                                            string.Format(AppSettings.CInfo, "{0:s} {1:s}", item, Environment.NewLine));

            result += Environment.NewLine;

            result += string.Format(AppSettings.CInfo, "SubtitleStreams:    {0:s}", Environment.NewLine);

            result = SubtitleStreams.Aggregate(result,
                                               (current, item) =>
                                               current +
                                               string.Format(AppSettings.CInfo, "{0:s} {1:s}", item, Environment.NewLine));

            result += Environment.NewLine;

            result += string.Format(AppSettings.CInfo, "Chapters:           {0:s} {1:s}",
                                    string.Join(",", (from item in Chapters
                                                      let dt = new DateTime()
                                                               select DateTime.MinValue.Add(item)
                                                               into dt select dt.ToString("H:mm:ss.fff")).ToArray()),
                                    Environment.NewLine);

            result += string.Format(AppSettings.CInfo, "NextStep:           {0:s} {1:s}", NextStep.ToString(),
                                    Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "CompletedStep:      {0:s} {1:s}", CompletedStep.ToString(),
                                    Environment.NewLine);
            result += Environment.NewLine;

            result += string.Format(AppSettings.CInfo, "VideoStream:        {0:s}", Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "{0:s} {1:s}", VideoStream, Environment.NewLine);
            result += Environment.NewLine;

            result += string.Format(AppSettings.CInfo, "StreamID:           {0:g} {1:s}", StreamId, Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "TrackID:            {0:g} {1:s}", TrackId, Environment.NewLine);

            result += string.Format(AppSettings.CInfo, "TempInput:          {0:s} {1:s}", TempInput, Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "TempOutput:         {0:s} {1:s}", TempOutput,
                                    Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "DumpOutput:         {0:s} {1:s}", DumpOutput,
                                    Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "SelectedDVDChapters:{0:s} {1:s}", SelectedDvdChapters,
                                    Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "TempFiles:          {0:s} {1:s}",
                                    string.Join(",", TempFiles.ToArray()), Environment.NewLine);
            result += string.Format(AppSettings.CInfo, "ReturnValue:        {0:g} {1:s}", ExitCode, Environment.NewLine);

            return(result);
        }
示例#12
0
        /// <summary>
        /// Opens the media by initializing the DirectShow graph
        //
        //                                          +----------------+          +----------------+       +-----------------------+
        //     +---------------------+              | LavVideo       |          | VobSub         |       | EVR+CustomPresenter   |
        //     | LavSplitterSource   |              |----------------|          |----------------|       |-----------------------|
        //     +---------------------+              |                |          |                |       |                       |
        //     |                     |              |                |          |                |       |    VIDEO              |
        //     |             video  +|->+---------+<-+ IN       OUT +->+------+<-+ VID_IN   OUT +-> +-+ <-+   RENDERER           |
        //     |                     |              +----------------+          |                |       |                       |
        //     |             audio  +|->+------+                                |                |       +-----------------------+
        //     |                     |         |    +----------------+      +-+<-+ TXT_IN        |
        //     |          subtitle  +|->+--+   |    | LavAudio       |      |   |                |
        //     +---------------------+    |   |    |----------------|      |   +----------------+       +-----------------------+
        //                                 |   |    |                |      |                            | DShow output device   |
        //                                 |   |    |                |     xxx                           |-----------------------|
        //                                 |   +--+<-+ IN       OUT +->+--x | x-----------------------+  |                       |
        //                                 |        +----------------+      |                            |    AUDIO              |
        //                                 |                                |                           <-+   RENDERER           |
        //                                 |                                |                            |                       |
        //                                 +--------------------------------+                            +-----------------------+
        //
        /// </summary>
//        protected virtual void OpenSource()
//        {
//            /* Make sure we clean up any remaining mess */
//            //if (m_graph != null) RemoveAllFilters(m_graph);
//            FreeResources();

//            if (m_sourceUri == null)
//                return;

//            string fileSource = m_sourceUri.OriginalString;

//            if (string.IsNullOrEmpty(fileSource))
//                return;

//            try
//            {
//                if (m_graph != null) Marshal.ReleaseComObject(m_graph);

//                /* Creates the GraphBuilder COM object */
//                m_graph = new FilterGraphNoThread() as IGraphBuilder;

//                if (m_graph == null)
//                    throw new Exception("Could not create a graph");

//                /* Add our prefered audio renderer */
//                var audioRenderer = InsertAudioRenderer(AudioRenderer);
//                if (_audioRenderer != null) Marshal.ReleaseComObject(_audioRenderer);
//                _audioRenderer = audioRenderer;

//                if ((System.Environment.OSVersion.Platform == PlatformID.Win32NT &&
//                (System.Environment.OSVersion.Version.Major == 5)))
//                    VideoRenderer = VideoRendererType.VideoMixingRenderer9;

//                IBaseFilter renderer = CreateVideoRenderer(VideoRenderer, m_graph, 2);
//                if (_renderer != null) Marshal.ReleaseComObject(_renderer);
//                _renderer = renderer;
//                //if (_renderer != null)
//                //    m_graph.AddFilter((IBaseFilter)_renderer, "Renderer");

//                var filterGraph = m_graph as IFilterGraph2;

//                if (filterGraph == null)
//                    throw new Exception("Could not QueryInterface for the IFilterGraph2");

//                ILAVAudioSettings lavAudioSettings;
//                ILAVAudioStatus lavStatus;
//                IBaseFilter audioDecoder = FilterProvider.GetAudioFilter(out lavAudioSettings, out lavStatus);
//                if (audioDecoder != null)
//                {
//                    if (_audio != null) Marshal.ReleaseComObject(_audio);
//                    _audio = audioDecoder;
//                    lavAudioSettings.SetRuntimeConfig(true);
//                    m_graph.AddFilter((IBaseFilter)_audio, "LavAudio");
//                }

//                ILAVSplitterSettings splitterSettings;
//                IFileSourceFilter splitter = FilterProvider.GetSplitterSource(out splitterSettings);
//                //IBaseFilter splitter = FilterProvider.GetSplitter(out splitterSettings);

//                if (splitter != null)
//                {
//                    splitter.Load(fileSource, null);
//                    if (_splitter != null) Marshal.ReleaseComObject(_splitter);
//                    _splitter = splitter;
//                    splitterSettings.SetRuntimeConfig(true);
//                    m_graph.AddFilter((IBaseFilter)splitter, "LavSplitter");
//                }

//                int hr = 0;


//                /* We will want to enum all the pins on the source filter */
//                IEnumPins pinEnum;

//                hr = ((IBaseFilter)splitter).EnumPins(out pinEnum);
//                DsError.ThrowExceptionForHR(hr);

//                IntPtr fetched = IntPtr.Zero;
//                IPin[] pins = { null };

//                /* Counter for how many pins successfully rendered */


//                if (VideoRenderer == VideoRendererType.VideoMixingRenderer9)
//                {
//                    var mixer = renderer as IVMRMixerControl9;

//                    if (mixer != null)
//                    {
//                        VMR9MixerPrefs dwPrefs;
//                        mixer.GetMixingPrefs(out dwPrefs);
//                        dwPrefs &= ~VMR9MixerPrefs.RenderTargetMask;
//                        dwPrefs |= VMR9MixerPrefs.RenderTargetRGB;
//                        //mixer.SetMixingPrefs(dwPrefs);
//                    }
//                }

//                // Test using FFDShow Video Decoder Filter
//                ILAVVideoSettings lavVideoSettings;
//                IBaseFilter lavVideo = FilterProvider.GetVideoFilter(out lavVideoSettings);
//                if (_video != null) Marshal.ReleaseComObject(_video);
//                _video = lavVideo;

//                IBaseFilter vobSub = FilterProvider.GetVobSubFilter();

//                if (vobSub != null)
//                {
//                    m_graph.AddFilter(vobSub, "VobSub");
//                    IDirectVobSub vss = vobSub as IDirectVobSub;
//                    if (_vobsub != null) Marshal.ReleaseComObject(_vobsub);
//                    _vobsub = vss;
//                    InitSubSettings();
//                }

//                if (lavVideo != null)
//                {
//                    lavVideoSettings.SetRuntimeConfig(true);
//                    m_graph.AddFilter(lavVideo, "LavVideo");
//                }

//                int ret;

//                IBaseFilter dcDsp = FilterProvider.GetDCDSPFilter();
//                if (dcDsp != null)
//                {
//                    _dspFilter = (IDCDSPFilterInterface)dcDsp;

//                    //hr = i.set_PCMDataBeforeMainDSP(true);
//                    hr = m_graph.AddFilter((IBaseFilter)dcDsp, "VobSub");

//                    ret = m_graph.Connect(DsFindPin.ByName((IBaseFilter)splitter, "Audio"), DsFindPin.ByDirection(audioDecoder, PinDirection.Input, 0));
//                    ret = m_graph.Connect(DsFindPin.ByDirection((IBaseFilter)audioDecoder, PinDirection.Output, 0), DsFindPin.ByDirection(_dspFilter, PinDirection.Input, 0));
//                    ret = m_graph.Connect(DsFindPin.ByDirection((IBaseFilter)_dspFilter, PinDirection.Output, 0), DsFindPin.ByDirection(audioRenderer, PinDirection.Input, 0));

//                    //bool d = false;
//                    //int delay = 0;
//                    //hr = i.get_EnableDelay(ref d);
//                    int cnt = 0;
//                    object intf = null;
//                    //hr = i.set_EnableDelay(true);
//                    //hr = i.set_Delay(0);
//                    hr = _dspFilter.set_AddFilter(0, TDCFilterType.ftEqualizer);
//                    hr = _dspFilter.get_FilterCount(ref cnt);
//                    hr = _dspFilter.get_FilterInterface(0, out intf);
//                    _equalizer = (IDCEqualizer)intf;
//                    hr = _dspFilter.set_AddFilter(0, TDCFilterType.ftDownMix);
//                    hr = _dspFilter.get_FilterInterface(0, out intf);
//                    _downmix = (IDCDownMix)intf;
//                    hr = _dspFilter.set_AddFilter(0, TDCFilterType.ftAmplify);
//                    hr = _dspFilter.get_FilterInterface(0, out intf);
//                    _amplify = (IDCAmplify)intf;

//                    _equalizer.set_Seperate(false);
//                }

//                bool subconnected = false;
//                ret = m_graph.Connect(DsFindPin.ByName((IBaseFilter)splitter, "Video"), DsFindPin.ByDirection(lavVideo, PinDirection.Input, 0));
//                ret = m_graph.Connect(DsFindPin.ByDirection((IBaseFilter)lavVideo, PinDirection.Output, 0), DsFindPin.ByDirection(vobSub, PinDirection.Input, 0));
//                if (ret == 0)
//                {
//                    int lc;
//                    ((IDirectVobSub)vobSub).get_LanguageCount(out lc);
//                    subconnected = (lc != 0);
//                    IPin pn = DsFindPin.ByName((IBaseFilter)splitter, "Subtitle");
//                    if (pn != null)
//                    {
//                        ret = m_graph.Connect(pn, DsFindPin.ByDirection(vobSub, PinDirection.Input, 1));
//                        ((IDirectVobSub)vobSub).get_LanguageCount(out lc);
//                        subconnected = (lc != 0);
//                    }
//                    ret = m_graph.Connect(DsFindPin.ByDirection(vobSub, PinDirection.Output, 0),
//                                          DsFindPin.ByDirection(renderer, PinDirection.Input, 0));
//                }
//                else
//                {
//                    ret = m_graph.Connect(DsFindPin.ByDirection(lavVideo, PinDirection.Output, 0),
//                                      DsFindPin.ByDirection(renderer, PinDirection.Input, 0));
//                }

//                /* Loop over each pin of the source filter */
//                while (pinEnum.Next(pins.Length, pins, fetched) == 0)
//                {
//                    IPin cTo;
//                    pins[0].ConnectedTo(out cTo);
//                    if (cTo == null)
//                    {
//                        // this should not happen if the filtegraph is manually connected in a good manner
//                        ret = filterGraph.RenderEx(pins[0], AMRenderExFlags.RenderToExistingRenderers, IntPtr.Zero);
//                    }
//                    else
//                    {
//                        Marshal.ReleaseComObject(cTo);
//                    }
//                    Marshal.ReleaseComObject(pins[0]);
//                }

//                if (lavVideoSettings != null)
//                {
//                    if (lavVideoSettings.CheckHWAccelSupport(LAVHWAccel.HWAccel_CUDA) != 0)
//                    {
//                        ret = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_CUDA);
//                    }
//                    else if (lavVideoSettings.CheckHWAccelSupport(LAVHWAccel.HWAccel_QuickSync) != 0)
//                    {
//                        ret = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_QuickSync);
//                    }
//                    else if (lavVideoSettings.CheckHWAccelSupport(LAVHWAccel.HWAccel_DXVA2Native) != 0)
//                    {
//                        ret = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_DXVA2Native);
//                    }
//                    else if (lavVideoSettings.CheckHWAccelSupport(LAVHWAccel.HWAccel_DXVA2) != 0)
//                    {
//                        ret = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_DXVA2);
//                    }
//                    else if (lavVideoSettings.CheckHWAccelSupport(LAVHWAccel.HWAccel_DXVA2CopyBack) != 0)
//                    {
//                        ret = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_DXVA2CopyBack);
//                    }
//                }

//                //hr = m_graph.RenderFile(fileSource, null);

//                Marshal.ReleaseComObject(pinEnum);

//                IAMStreamSelect selector = splitter as IAMStreamSelect;
//                int numstreams;
//                selector.Count(out numstreams);
//                AMMediaType mt;
//                AMStreamSelectInfoFlags fl;
//                SubtitleStreams.Clear();
//                VideoStreams.Clear();
//                AudioStreams.Clear();
//                for (int i = 0; i < numstreams; i++)
//                {
//                    int lcid;
//                    int group;
//                    string name;
//                    object o, o2;
//                    selector.Info(i, out mt, out fl, out lcid, out group, out name, out o, out o2);
//                    switch (group)
//                    {
//                        case 0:
//                            VideoStreams.Add(name);
//                            break;
//                        case 1:
//                            AudioStreams.Add(name);
//                            break;
//                        case 2:
//                            SubtitleStreams.Add(name);
//                            break;
//                    }

//                    if (o != null) Marshal.ReleaseComObject(o);
//                    if (o2 != null) Marshal.ReleaseComObject(o2);
//                }

//                OnPropertyChanged("SubtitleStreams");
//                OnPropertyChanged("VideoStreams");
//                OnPropertyChanged("AudioStreams");

//                //Marshal.ReleaseComObject(splitter);


//                /* Configure the graph in the base class */
//                SetupFilterGraph(m_graph);

//#if DEBUG
//                /* Adds the GB to the ROT so we can view
//* it in graphedit */
//                m_dsRotEntry = new DsROTEntry(m_graph);
//#endif

//                //if (_splitterSettings != null)
//                //{
//                // Marshal.ReleaseComObject(_splitterSettings);
//                // _splitterSettings = null;
//                //}
//                if (_splitterSettings != null) Marshal.ReleaseComObject(_splitterSettings);
//                _splitterSettings = (ILAVSplitterSettings)splitter;
//                //ret = _splitterSettings.SetRuntimeConfig(true);
//                //if (ret != 0)
//                // throw new Exception("Could not set SetRuntimeConfig to true");

//                //string sss = "*:*";

//                //LAVSubtitleMode mode = LAVSubtitleMode.LAVSubtitleMode_NoSubs;
//                //mode = _splitterSettings.GetSubtitleMode();
//                //if (mode != LAVSubtitleMode.LAVSubtitleMode_Default)
//                // throw new Exception("Could not set GetAdvancedSubtitleConfige");

//                //ret = _splitterSettings.SetSubtitleMode(LAVSubtitleMode.LAVSubtitleMode_Advanced);
//                //if (ret != 1)
//                // throw new Exception("Could not set SetAdvancedSubtitleConfige");

//                //ret = _splitterSettings.SetAdvancedSubtitleConfig(sss);
//                //if (ret != 1)
//                // throw new Exception("Could not set SetAdvancedSubtitleConfige");

//                //sss = "";
//                //ret = _splitterSettings.GetAdvancedSubtitleConfig(out sss);
//                //if (ret != 0)
//                // throw new Exception("Could not set GetAdvancedSubtitleConfige");

//                //IPin sub = DsFindPin.ByDirection((IBaseFilter)splitter, PinDirection.Output, 2);
//                //PinInfo pi;
//                //sub.QueryPinInfo(out pi);
//                SIZE a, b;
//                if ((_displayControl).GetNativeVideoSize(out a, out b) == 0)
//                {
//                    if (a.cx > 0 && a.cy > 0)
//                    {
//                        HasVideo = true;
//                        SetNativePixelSizes(a);
//                    }
//                }

//                if (!subconnected)
//                {
//                    InvokeNoSubtitleLoaded(new EventArgs());
//                }
//                else
//                {
//                    InitSubSettings();
//                }
//                /* Sets the NaturalVideoWidth/Height */
//                //SetNativePixelSizes(renderer);

//                //InvokeMediaFailed(new MediaFailedEventArgs(sss, null));
//            }
//            catch (Exception ex)
//            {
//                /* This exection will happen usually if the media does
//                * not exist or could not open due to not having the
//                * proper filters installed */
//                FreeResources();

//                /* Fire our failed event */
//                InvokeMediaFailed(new MediaFailedEventArgs(ex.Message, ex));
//            }
//            finally
//            {
//                string filters = string.Join(Environment.NewLine, EnumAllFilters(m_graph).ToArray());
//                System.Diagnostics.Debug.WriteLine(filters);
//            }
//            InvokeMediaOpened();
//        }
        protected virtual void OpenSource()
        {
            _eqEnabled = false;
            //if (m_graph != null)
            //{
            //    //RemoveAllFilters(m_graph);
            //    Marshal.ReleaseComObject(m_graph);
            //}

            /* Make sure we clean up any remaining mess */
            FreeResources();

            if (m_sourceUri == null)
            {
                return;
            }

            string fileSource = m_sourceUri.OriginalString;

            if (string.IsNullOrEmpty(fileSource))
            {
                return;
            }

            try
            {
                int hr = 0;

                /* Creates the GraphBuilder COM object */
                m_graph = new FilterGraphNoThread() as IGraphBuilder;

                if (_displayControl != null)
                {
                    Marshal.ReleaseComObject(_displayControl);
                    _displayControl = null;
                }

                if (_displayControlVMR != null)
                {
                    Marshal.ReleaseComObject(_displayControlVMR);
                    _displayControlVMR = null;
                }

                if (m_graph == null)
                {
                    throw new Exception("Could not create a graph");
                }

                var filterGraph = m_graph as IFilterGraph2;

                var flt = EnumAllFilters(m_graph).ToList();

                if (filterGraph == null)
                {
                    throw new Exception("Could not QueryInterface for the IFilterGraph2");
                }

                /* Add our prefered audio renderer */
                var audioRenderer = InsertAudioRenderer(AudioRenderer);
                if (audioRenderer != null)
                {
                    if (_audioRenderer != null)
                    {
                        Marshal.ReleaseComObject(_audioRenderer);
                    }
                    _audioRenderer = audioRenderer;
                }

                if ((System.Environment.OSVersion.Platform == PlatformID.Win32NT &&
                     (System.Environment.OSVersion.Version.Major == 5)))
                {
                    VideoRenderer = VideoRendererType.VideoMixingRenderer9;
                }

                if (_presenterSettings != null)
                {
                    Marshal.ReleaseComObject(_presenterSettings);
                }
                if (_renderer != null)
                {
                    Marshal.ReleaseComObject(_renderer);
                }

                IBaseFilter renderer = InsertVideoRenderer(VideoRenderer, m_graph, 1);
                _renderer = renderer;

                ILAVAudioSettings lavAudioSettings;
                ILAVAudioStatus   lavStatus;
                IBaseFilter       audioDecoder = FilterProvider.GetAudioFilter(out lavAudioSettings, out lavStatus);
                if (audioDecoder != null)
                {
                    if (_audio != null)
                    {
                        Marshal.ReleaseComObject(_audio);
                    }
                    _audio         = audioDecoder;
                    _audioStatus   = lavStatus;
                    _audioSettings = lavAudioSettings;

                    hr = (int)lavAudioSettings.SetRuntimeConfig(true);
                    hr = m_graph.AddFilter((IBaseFilter)audioDecoder, "LavAudio");
                    DsError.ThrowExceptionForHR(hr);
#if DEBUG
                    hr = (int)lavAudioSettings.SetTrayIcon(true);
#endif
                }

                ILAVSplitterSettings splitterSettings;
                IFileSourceFilter    splitter = FilterProvider.GetSplitterSource(out splitterSettings);

                if (splitter != null)
                {
                    if (_splitter != null)
                    {
                        Marshal.ReleaseComObject(_splitter);
                    }
                    _splitter = splitter;

                    _splitterSettings = (ILAVSplitterSettings)splitterSettings;

                    hr = splitterSettings.SetRuntimeConfig(true);
                    hr = splitter.Load(fileSource, null);
                    if (hr != 0)
                    {
                        throw new Exception("Playback of this file is not supported!");
                    }
                    hr = m_graph.AddFilter((IBaseFilter)splitter, "LavSplitter");
                    DsError.ThrowExceptionForHR(hr);
                }

                IEnumPins pinEnum;
                hr = ((IBaseFilter)splitter).EnumPins(out pinEnum);
                DsError.ThrowExceptionForHR(hr);

                IntPtr fetched = IntPtr.Zero;
                IPin[] pins    = { null };

                if (VideoRenderer == VideoRendererType.VideoMixingRenderer9)
                {
                    var mixer = _renderer as IVMRMixerControl9;

                    if (mixer != null)
                    {
                        VMR9MixerPrefs dwPrefs;
                        mixer.GetMixingPrefs(out dwPrefs);
                        dwPrefs &= ~VMR9MixerPrefs.RenderTargetMask;
                        dwPrefs |= VMR9MixerPrefs.RenderTargetRGB;
                        mixer.SetMixingPrefs(dwPrefs);
                    }
                }

                ILAVVideoSettings lavVideoSettings;
                IBaseFilter       lavVideo = FilterProvider.GetVideoFilter(out lavVideoSettings);

                if (lavVideo != null)
                {
                    if (_video != null)
                    {
                        Marshal.ReleaseComObject(_video);
                    }
                    _video = lavVideo;

                    if (lavVideoSettings != null)
                    {
                        _videoSettings = lavVideoSettings;

                        lavVideoSettings.SetRuntimeConfig(true);
                        hr = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_None);

                        // check for best acceleration available
                        //if (lavVideoSettings.CheckHWAccelSupport(LAVHWAccel.HWAccel_CUDA) != 0)
                        //{
                        //    hr = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_CUDA);
                        //    hr = lavVideoSettings.SetHWAccelResolutionFlags(LAVHWResFlag.SD | LAVHWResFlag.HD | LAVHWResFlag.UHD);
                        //}
                        //else if (lavVideoSettings.CheckHWAccelSupport(LAVHWAccel.HWAccel_QuickSync) != 0)
                        //{
                        //    hr = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_QuickSync);
                        //    hr = lavVideoSettings.SetHWAccelResolutionFlags(LAVHWResFlag.SD | LAVHWResFlag.HD | LAVHWResFlag.UHD);
                        //}
                        //else
                        if (lavVideoSettings.CheckHWAccelSupport(LAVHWAccel.HWAccel_DXVA2Native) != 0)
                        {
                            hr = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_DXVA2Native);
                            hr = lavVideoSettings.SetHWAccelResolutionFlags(LAVHWResFlag.SD | LAVHWResFlag.HD | LAVHWResFlag.UHD);
                        }
                        //else
                        //if (lavVideoSettings.CheckHWAccelSupport(LAVHWAccel.HWAccel_DXVA2CopyBack) != 0)
                        //{
                        //    hr = lavVideoSettings.SetHWAccel(LAVHWAccel.HWAccel_DXVA2CopyBack);
                        //    hr = lavVideoSettings.SetHWAccelResolutionFlags(LAVHWResFlag.SD | LAVHWResFlag.HD | LAVHWResFlag.UHD);
                        //}

#if DEBUG
                        hr = lavVideoSettings.SetTrayIcon(true);
#endif
                    }

                    hr = m_graph.AddFilter(_video, "LavVideo");
                    DsError.ThrowExceptionForHR(hr);
                }

                IBaseFilter vobSub = FilterProvider.GetVobSubFilter();

                if (vobSub != null)
                {
                    try
                    {
                        hr = m_graph.AddFilter(vobSub, "VobSub");
                        DsError.ThrowExceptionForHR(hr);
                        IDirectVobSub vss = vobSub as IDirectVobSub;
                        if (_vobsub != null)
                        {
                            Marshal.ReleaseComObject(_vobsub);
                        }
                        _vobsub = vss;
                        InitSubSettings();
                    }
                    catch { }
                }

                hr = m_graph.Connect(DsFindPin.ByName((IBaseFilter)splitter, "Audio"), DsFindPin.ByDirection(_audio, PinDirection.Input, 0));
                if (hr == 0)
                {
                    HasAudio = true;
                }
                else
                {
                    HasAudio = false;
                }


                IBaseFilter dcDsp = FilterProvider.GetDCDSPFilter();
                if (dcDsp != null)
                {
                    if (_dspFilter != null)
                    {
                        Marshal.ReleaseComObject(_dspFilter);
                    }
                    _dspFilter = (IDCDSPFilterInterface)dcDsp;

                    if (HasAudio)
                    {
                        hr = m_graph.AddFilter((IBaseFilter)_dspFilter, "AudioProcessor");
                        hr = _dspFilter.set_EnableBitrateConversionBeforeDSP(true);
                        hr = ((IDCDSPFilterVisualInterface)_dspFilter).set_VISafterDSP(true);
                        hr = m_graph.Connect(DsFindPin.ByDirection((IBaseFilter)_audio, PinDirection.Output, 0), DsFindPin.ByDirection(_dspFilter, PinDirection.Input, 0));
                        DsError.ThrowExceptionForHR(hr);
                        hr = m_graph.Connect(DsFindPin.ByDirection((IBaseFilter)_dspFilter, PinDirection.Output, 0), DsFindPin.ByDirection(_audioRenderer, PinDirection.Input, 0));

                        var cb = new AudioCallback(this);
                        hr = _dspFilter.set_CallBackPCM(cb);

                        object intf = null;
                        hr         = _dspFilter.set_AddFilter(0, TDCFilterType.ftEqualizer);
                        hr         = _dspFilter.get_FilterInterface(0, out intf);
                        _equalizer = (IDCEqualizer)intf;
                        _equalizer.set_Seperate(false);
                    }
                }
                else
                {
                    if (HasAudio)
                    {
                        hr = m_graph.Connect(DsFindPin.ByDirection((IBaseFilter)_audio, PinDirection.Output, 0), DsFindPin.ByDirection(_audioRenderer, PinDirection.Input, 0));
                    }
                }

                bool subconnected = false;

                hr = m_graph.Connect(DsFindPin.ByName((IBaseFilter)_splitter, "Video"), DsFindPin.ByDirection(_video, PinDirection.Input, 0));
                if (hr == 0)
                {
                    HasVideo = true;
                }
                else
                {
                    HasVideo = false;
                }

                if (HasVideo)
                {
                    hr = m_graph.Connect(DsFindPin.ByDirection((IBaseFilter)_video, PinDirection.Output, 0), DsFindPin.ByDirection(vobSub, PinDirection.Input, 0));
                    DsError.ThrowExceptionForHR(hr);
                    if (hr == 0)
                    {
                        int lc;
                        ((IDirectVobSub)vobSub).get_LanguageCount(out lc);
                        subconnected = (lc != 0);
                        IPin pn = DsFindPin.ByName((IBaseFilter)splitter, "Subtitle");
                        if (pn != null)
                        {
                            hr = m_graph.Connect(pn, DsFindPin.ByDirection(vobSub, PinDirection.Input, 1));
                            ((IDirectVobSub)vobSub).get_LanguageCount(out lc);
                            subconnected = (lc != 0);
                        }
                        hr = m_graph.Connect(DsFindPin.ByDirection(vobSub, PinDirection.Output, 0),
                                             DsFindPin.ByDirection(_renderer, PinDirection.Input, 0));
                    }
                    else
                    {
                        if (_vobsub != null)
                        {
                            Marshal.ReleaseComObject(_vobsub);
                        }
                        _vobsub = null;
                        hr      = m_graph.Connect(DsFindPin.ByDirection(_video, PinDirection.Output, 0),
                                                  DsFindPin.ByDirection(_renderer, PinDirection.Input, 0));
                    }
                }

                /* Loop over each pin of the source filter */
                while (pinEnum.Next(pins.Length, pins, fetched) == 0)
                {
                    IPin cTo;
                    pins[0].ConnectedTo(out cTo);
                    if (cTo == null)
                    {
                        // this should not happen if the filtegraph is manually connected in a good manner
                        hr = filterGraph.RenderEx(pins[0], AMRenderExFlags.RenderToExistingRenderers, IntPtr.Zero);
                    }
                    else
                    {
                        Marshal.ReleaseComObject(cTo);
                    }
                    Marshal.ReleaseComObject(pins[0]);
                }

                Marshal.ReleaseComObject(pinEnum);

                var selector = splitter as IAMStreamSelect;
                int numstreams;
                selector.Count(out numstreams);
                AMMediaType             mt;
                AMStreamSelectInfoFlags fl;
                SubtitleStreams.Clear();
                VideoStreams.Clear();
                AudioStreams.Clear();
                for (int i = 0; i < numstreams; i++)
                {
                    int    lcid;
                    int    group;
                    string name;
                    object o, o2;
                    selector.Info(i, out mt, out fl, out lcid, out group, out name, out o, out o2);
                    switch (group)
                    {
                    case 0:
                        VideoStreams.Add(name);
                        break;

                    case 1:
                        AudioStreams.Add(name);
                        break;

                    case 2:
                        SubtitleStreams.Add(name);
                        break;
                    }

                    if (o != null)
                    {
                        Marshal.ReleaseComObject(o);
                    }
                    if (o2 != null)
                    {
                        Marshal.ReleaseComObject(o2);
                    }
                }

                OnPropertyChanged("SubtitleStreams");
                OnPropertyChanged("VideoStreams");
                OnPropertyChanged("AudioStreams");

                /* Configure the graph in the base class */
                SetupFilterGraph(m_graph);

#if DEBUG
                /* Adds the GB to the ROT so we can view
                 * it in graphedit */
                m_dsRotEntry = new DsROTEntry(m_graph);
#endif

                SIZE a, b;
                if (HasVideo && _displayControl != null && (_displayControl).GetNativeVideoSize(out a, out b) == 0)
                {
                    var sz = MediaPlayerBase.GetVideoSize(_renderer, PinDirection.Input, 0);
                    if (a.cx > 0 && a.cy > 0)
                    {
                        SetNativePixelSizes(a);
                    }
                }

                if (!subconnected)
                {
                    InvokeNoSubtitleLoaded(new EventArgs());
                }
                else
                {
                    InitSubSettings();
                }
            }
            catch (Exception ex)
            {
                /* This exection will happen usually if the media does
                 * not exist or could not open due to not having the
                 * proper filters installed */
                FreeResources();

                /* Fire our failed event */
                InvokeMediaFailed(new MediaFailedEventArgs(ex.Message, ex));
            }

            InvokeMediaOpened();
        }
示例#13
0
        public OpenVideoResults OpenVideo()
        {
            Uri uri;

            try
            {
                uri = new Uri(Session.InitialUrl);
                if ((uri.Scheme.ToLower() != "http" && uri.Scheme.ToLower() != "https") || Utils.GetUrlExtention(Session.InitialUrl).ToLower() == "m3u8")
                {
                    return(null);
                }
            } catch (Exception) { return(null); }

            try
            {
                string url = Session.InitialUrl;
                Session.SingleMovie.UrlType = UrlType.Web;
                if (Regex.IsMatch(uri.DnsSafeHost, @"\.youtube\.", RegexOptions.IgnoreCase))
                {
                    var query = HttpUtility.ParseQueryString(uri.Query);
                    url = uri.Scheme + "://" + uri.Host + uri.AbsolutePath + "?v=" + query["v"];
                }

                string tmpFile = Path.GetTempPath() + Guid.NewGuid().ToString();

                Process proc = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName        = plugin_path,
                        Arguments       = $"--no-check-certificate --skip-download --write-info-json -o \"{tmpFile}\" \"{url}\"",
                        CreateNoWindow  = true,
                        UseShellExecute = false,
                        WindowStyle     = ProcessWindowStyle.Hidden
                    }
                };
                proc.Start();
                while (!proc.HasExited && Player.decoder.interrupt == 0)
                {
                    Thread.Sleep(35);
                }
                if (Player.decoder.interrupt == 1)
                {
                    if (!proc.HasExited)
                    {
                        proc.Kill();
                    }
                    return(null);
                }
                if (!File.Exists($"{tmpFile}.info.json"))
                {
                    return(null);
                }

                // Parse Json Object
                string json = File.ReadAllText($"{tmpFile}.info.json");
                ytdl = JsonConvert.DeserializeObject <YoutubeDLJson>(json, settings);
                if (ytdl == null || ytdl.formats == null || ytdl.formats.Count == 0)
                {
                    return(null);
                }

                Format fmt;
                // Fix Nulls (we are not sure if they have audio/video)
                for (int i = 0; i < ytdl.formats.Count; i++)
                {
                    fmt = ytdl.formats[i];
                    if (ytdl.formats[i].vcodec == null)
                    {
                        ytdl.formats[i].vcodec = "";
                    }
                    if (ytdl.formats[i].acodec == null)
                    {
                        ytdl.formats[i].acodec = "";
                    }

                    //Dump(ytdl.formats[i]);

                    if (HasVideo(fmt))
                    {
                        VideoStreams.Add(new VideoStream()
                        {
                            DecoderInput = new DecoderInput()
                            {
                                Url = fmt.url
                            },
                            BitRate   = (long)fmt.vbr,
                            CodecName = fmt.vcodec,
                            Language  = Language.Get(fmt.language),
                            Width     = (int)fmt.width,
                            Height    = (int)fmt.height,
                            FPS       = fmt.fps
                        });
                    }

                    if (HasAudio(fmt))
                    {
                        AudioStreams.Add(new AudioStream()
                        {
                            DecoderInput = new DecoderInput()
                            {
                                Url = fmt.url
                            },
                            BitRate   = (long)fmt.abr,
                            CodecName = fmt.acodec,
                            Language  = Language.Get(fmt.language)
                        });
                    }
                }

                fmt = GetBestMatch();

                Player.Session.SingleMovie.Title = ytdl.title;

                foreach (var t1 in VideoStreams)
                {
                    if (fmt.url == t1.DecoderInput.Url)
                    {
                        return(new OpenVideoResults(t1));
                    }
                }
            }
            catch (Exception e) { Console.WriteLine($"[Youtube-DL] Error ... {e.Message}"); }

            return(new OpenVideoResults());
            //return formats[formats.Count - 1];
        }