internal override Bitmap TakePicture()
        {
            if (m_callbackCompleted != null)
            {
                return(null);
            }
            //  m_pictureControl = pictureControl;
            m_takePictureEnd = false;

            DsDevice cameraDevice = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice)[m_cameraDeviceIndex];

            IFilterGraph2  filterGraph = null;
            IBaseFilter    cam = null; IPin camCapture = null;                                  // cam
            ISampleGrabber sg = null; IPin sgIn = null;                                         // samplegrabber

            try
            {
                // setup filterGraph & connect camera
                filterGraph = (IFilterGraph2) new FilterGraph();
                DsError.ThrowExceptionForHR(filterGraph.AddSourceFilterForMoniker(cameraDevice.Mon, null, cameraDevice.Name, out cam));

                // setup smarttee and connect so that cam(PinCategory.Capture)->st(PinDirection.Input)
                camCapture = DsFindPin.ByCategory(cam, PinCategory.Capture, 0);                 // output
                ConfStreamDimensions((IAMStreamConfig)camCapture);

                // connect Camera output to SampleGrabber input
                sg = (ISampleGrabber) new SampleGrabber();

                // configure
                AMMediaType media = new AMMediaType();
                try
                {
                    media.majorType  = MediaType.Video;
                    media.subType    = BPP2MediaSubtype(m_configuration.BPP); // this will ask samplegrabber to do convertions for us
                    media.formatType = FormatType.VideoInfo;
                    DsError.ThrowExceptionForHR(sg.SetMediaType(media));
                }
                finally
                {
                    DsUtils.FreeAMMediaType(media);
                    media = null;
                }

                DsError.ThrowExceptionForHR(sg.SetCallback(this, 1));                           // 1 = BufferCB
                DsError.ThrowExceptionForHR(filterGraph.AddFilter((IBaseFilter)sg, "SG"));
                sgIn = DsFindPin.ByDirection((IBaseFilter)sg, PinDirection.Input, 0);           // input
                DsError.ThrowExceptionForHR(filterGraph.Connect(camCapture, sgIn));
                GetSizeInfo(sg);

                // wait until timeout - or picture has been taken
                if (m_callbackCompleted == null)
                {
                    m_callbackCompleted = new ManualResetEvent(false);

                    // start filter
                    DsError.ThrowExceptionForHR(((IMediaControl)filterGraph).Run());
                    m_callbackState = 5;
                    //if (m_pictureControl != null)
                    //{
                    //    m_callbackCompleted.WaitOne();
                    //}
                    //else
                    //{
                    if (!m_callbackCompleted.WaitOne(15000, false))
                    {
                        throw new Exception();     //"Timeout while waiting for Picture");
                    }
                    //}
                    return(m_capturedBitmap);
                }
                else
                {
                    return(null);
                }
            }
            finally
            {
                // release allocated objects
                if (m_callbackCompleted != null)
                {
                    m_callbackCompleted.Close();
                    m_callbackCompleted = null;
                }
                if (sgIn != null)
                {
                    Marshal.ReleaseComObject(sgIn);
                    sgIn = null;
                }
                if (sg != null)
                {
                    Marshal.ReleaseComObject(sg);
                    sg = null;
                }
                if (camCapture != null)
                {
                    Marshal.ReleaseComObject(camCapture);
                    camCapture = null;
                }
                if (cam != null)
                {
                    Marshal.ReleaseComObject(cam);
                    cam = null;
                }
                if (filterGraph != null)
                {
                    try
                    {
                        ((IMediaControl)filterGraph).Stop();
                    }
                    catch (Exception) { }
                    Marshal.ReleaseComObject(filterGraph);
                    filterGraph = null;
                }
                m_capturedBitmap    = null;
                m_callbackCompleted = null;
            }
        }
Beispiel #2
0
 private static DsDevice[] GetDevices(Guid filterCategory)
 {
     return((from d in DsDevice.GetDevicesOfCat(filterCategory)
             select d).ToArray());
 }
Beispiel #3
0
        public IBaseFilter Create(Guid category, string strName, out string strTitle)
        {
            _class.Debug.Log("[3] Create filter: name>" + strName);
            IBaseFilter filter = null;

            strTitle = "*NF*";
            strName  = strName.ToLower();
            int hr = 0;

            int intID = _class.Var.DeviceId;

            if (strName.IndexOf('(') > -1)
            {
                string strID = strName.Substring(strName.IndexOf('(') + 1);
                if (strID.IndexOf(')') > -1)
                {
                    strID = strID.Substring(0, strID.IndexOf(')'));
                }
                strName = strName.Substring(0, strName.IndexOf('(')).Trim();

                _class.Debug.Log("FilterName: " + strName);
                _class.Debug.Log("DevID: " + strID);
                try
                {
                    intID = Convert.ToInt32(strID);
                }
                catch { }
                _class.Debug.Log("Confirm DevID: " + intID.ToString());
            }

            int intDevID = 0;

            DsDevice[] devices = DsDevice.GetDevicesOfCat(category);
            foreach (DsDevice device in DsDevice.GetDevicesOfCat(category))
            {
                string strDevice = device.Name.ToLower();
                _class.Debug.Log("device>" + strDevice);
                if (strDevice.IndexOf(strName) > -1 || strDevice.ToLower() == "oem crossbar")
                {
                    bool boolCreate = true;
                    _class.Debug.Log("TargetID=" + intID.ToString() + " [] + DevID=" + intDevID.ToString());

                    if (intDevID == intID)
                    {
                        boolCreate          = true;
                        _class.Var.DeviceId = intID;
                    }
                    else
                    {
                        boolCreate = false;
                    }

                    if (boolCreate == true)
                    {
                        _class.Debug.Log("SetDeviceID (" + intDevID.ToString() + ")");
                        strTitle = device.Name;
                        IBindCtx bindCtx = null;
                        try
                        {
                            hr = Variables.CreateBindCtx(0, out bindCtx);
                            DsError.ThrowExceptionForHR(hr);
                            Guid   guid = typeof(IBaseFilter).GUID;
                            object obj;
                            device.Mon.BindToObject(bindCtx, null, ref guid, out obj);
                            filter = (IBaseFilter)obj;
                        }
                        finally
                        {
                            if (bindCtx != null)
                            {
                                Marshal.ReleaseComObject(bindCtx);
                            }
                        }
                    }
                    else
                    {
                        _class.Debug.Log(intDevID.ToString() + " skipped");
                    }
                    intDevID++;
                }
            }
            return(filter);
        }
Beispiel #4
0
        static void Main(string[] args)
        {
            Console.WriteLine("FocusUF " + Assembly.GetEntryAssembly().GetName().Version);
            Console.WriteLine("Get the source at https://github.com/anotherlab/FocusUF");

            var argsLists = SplitArgs(args.ToList());

            // Get the list of connected video cameras
            DsDevice[] devs = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);

            foreach (var argsList in argsLists)
            {
                _whatToDo = ProcessArgs(argsList);
                IAMCameraControl camera;
                switch (_whatToDo)
                {
                case Operation.Usage:
                    Usage();
                    break;

                case Operation.ListCameras:
                    foreach (var cam in devs)
                    {
                        Console.WriteLine($"Camera: {cam.Name}");
                        camera = GetCamera(cam);
                        if (camera != null)
                        {
                            // Focus ranges and Values
                            camera.GetRange(CameraControlProperty.Focus, out int focusMin, out int focusMax, out int focusStep, out int focusDefault, out CameraControlFlags focusPossFlags);
                            camera.Get(CameraControlProperty.Focus, out int focusValue, out CameraControlFlags focusSetting);
                            Console.WriteLine($"    Focus Capability: {focusPossFlags}");
                            Console.WriteLine($"    Focus Range: {focusMin} - {focusMax}");
                            Console.WriteLine($"    Focus Setting: {focusSetting}, {focusValue}");
                            camera.GetRange(CameraControlProperty.Exposure, out int expMin, out int expMax, out int expStep, out int expDefault, out CameraControlFlags expPossFlags);
                            camera.Get(CameraControlProperty.Exposure, out int expValue, out CameraControlFlags expSetting);
                            Console.WriteLine($"    Exposure Capability: {expPossFlags}");
                            Console.WriteLine($"    Exposure Range: {expMin} - {expMax}");
                            Console.WriteLine($"    Exposure Setting: {expSetting}, {expValue}");
                        }
                        else
                        {
                            Console.WriteLine($"    Camera does not expose settings through DirectShowLib");
                        }
                    }
                    break;

                case Operation.ManualFocus:
                    SetCameraFlag(devs, _cameraName, CameraControlProperty.Focus, CameraControlFlags.Manual);
                    break;

                case Operation.AutoFocus:
                    SetCameraFlag(devs, _cameraName, CameraControlProperty.Focus, CameraControlFlags.Auto);
                    break;

                case Operation.SetFocus:
                    SetCameraValue(devs, _cameraName, CameraControlProperty.Focus, _focusSetting);
                    break;

                case Operation.ManualExposure:
                    SetCameraFlag(devs, _cameraName, CameraControlProperty.Exposure, CameraControlFlags.Manual);
                    break;

                case Operation.AutoExposure:
                    SetCameraFlag(devs, _cameraName, CameraControlProperty.Exposure, CameraControlFlags.Auto);
                    break;

                case Operation.SetExposure:
                    SetCameraValue(devs, _cameraName, CameraControlProperty.Exposure, _exposureSetting);
                    break;
                }
            }
        }
Beispiel #5
0
 public BrCamera()
 {
     this.daCamera       = new DaCamera();
     this.rsCamera       = new RsCamera();
     this.systemCamereas = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
 }
        private void DetectSupportedLegacyAmFilterDevices(ref HashSet <string> previouslyKnownDevices, ref HashSet <string> knownDevices)
        {
            Log.Log.Debug("Detect legacy AM filter devices");
            TvBusinessLayer layer          = new TvBusinessLayer();
            Setting         setting        = layer.GetSetting("iptvCardCount", "1");
            int             iptvTunerCount = Convert.ToInt32(setting.Value);

            DsDevice[] connectedDevices = DsDevice.GetDevicesOfCat(FilterCategory.LegacyAmFilterCategory);
            foreach (DsDevice connectedDevice in connectedDevices)
            {
                string name       = connectedDevice.Name;
                string devicePath = connectedDevice.DevicePath;
                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(devicePath))
                {
                    continue;
                }

                if (name.Equals("B2C2 MPEG-2 Source"))
                {
                    knownDevices.Add(devicePath);
                    if (!previouslyKnownDevices.Contains(devicePath))
                    {
                        Log.Log.Info("Detected new TechniSat *Star 2 tuner root device");
                        TvCardDvbSS2 tuner = new TvCardDvbSS2(connectedDevice);
                        _deviceEventListener.OnDeviceAdded(tuner);
                    }
                }
                else if (name.Equals("Elecard NWSource-Plus"))
                {
                    for (int i = 0; i < iptvTunerCount; i++)
                    {
                        TvCardDVBIP iptvTuner = new TvCardDVBIPElecard(connectedDevice, i);
                        knownDevices.Add(iptvTuner.DevicePath);
                        if (!previouslyKnownDevices.Contains(iptvTuner.DevicePath))
                        {
                            Log.Log.Info("Detected new Elecard IPTV tuner {0} {1}", iptvTuner.Name, iptvTuner.DevicePath);
                            _deviceEventListener.OnDeviceAdded(iptvTuner);
                        }
                        else
                        {
                            iptvTuner.Dispose();
                        }
                    }
                }
                else if (name.Equals("MediaPortal IPTV Source Filter"))
                {
                    for (int i = 0; i < iptvTunerCount; i++)
                    {
                        TvCardDVBIP iptvTuner = new TvCardDVBIPBuiltIn(connectedDevice, i);
                        knownDevices.Add(iptvTuner.DevicePath);
                        if (!previouslyKnownDevices.Contains(iptvTuner.DevicePath))
                        {
                            Log.Log.Info("Detected new MediaPortal IPTV tuner {0} {1}", iptvTuner.Name, iptvTuner.DevicePath);
                            _deviceEventListener.OnDeviceAdded(iptvTuner);
                        }
                        else
                        {
                            iptvTuner.Dispose();
                        }
                    }
                }
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            DsDevice[]         capDev;
            IFilterGraph2      m_FilterGraph = new FilterGraph() as IFilterGraph2;
            IBaseFilter        pDeviceFilter = null;
            IAMCameraControl   pCameraControl;
            IAMVideoProcAmp    pVideoProcAmp;
            CameraControlFlags pCapsFlags;
            VideoProcAmpFlags  pCapsFlags2;
            int pSteppingDelta;
            int pMin;
            int pMax;
            int pDefault;
            int pValue;

            int       yLocation = 40;
            const int yStep     = 113;

            overWindowToggleButton.Appearance = Appearance.Button;

            // TODO
            updateButton.Visible = false;

            // Get the collection of video devices
            capDev = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);

            foreach (DsDevice d in capDev)
            {
                //listBox1.Items.Add(d.Name);


                int    hr;
                object camDevice;
                Guid   iid = typeof(IBaseFilter).GUID;
                d.Mon.BindToObject(null, null, ref iid, out camDevice);
                IBaseFilter camFilter = camDevice as IBaseFilter;
                pCameraControl = camFilter as IAMCameraControl;
                pVideoProcAmp  = camFilter as IAMVideoProcAmp;


                if (pCameraControl != null)
                {
                    GroupBox gb           = new GroupBox();
                    CheckBox cbFocus      = cbFocusHID = new CheckBox();
                    CheckBox cbExposure   = new CheckBox();
                    Button   butForce     = new Button();
                    TrackBar tBarFocus    = tBarFocusHID = new TrackBar();
                    TrackBar tBarExposure = new TrackBar();

                    gb.Text     = d.Name;
                    gb.Width    = 295;
                    gb.Height   = 106;
                    gb.Location = new Point(13, yLocation);


                    pCameraControl.GetRange(CameraControlProperty.Focus, out pMin, out pMax, out pSteppingDelta, out pDefault, out pCapsFlags);

                    cbFocus.Text            = "Auto focus";
                    cbFocus.Width           = 78;
                    cbFocus.Height          = 17;
                    cbFocus.Location        = new Point(6, 23);
                    cbFocus.Tag             = butForce;
                    cbFocus.Checked         = (pCapsFlags == CameraControlFlags.Auto);
                    cbFocus.CheckedChanged += new EventHandler(this.checkBoxFocus_CheckedChanged);

                    butForce.Text     = "Force";
                    butForce.Width    = 75;
                    butForce.Height   = 23;
                    butForce.Location = new Point(90, 19);
                    //butForce.Enabled = false;
                    butForce.Tag    = pCameraControl;
                    butForce.Click += new EventHandler(this.ButtonForce_Click);

                    // TODO
                    //butBind.Visible = false;
                    //butBind.Text = "Bind key";
                    //butBind.Width = 75;
                    //butBind.Height = 23;
                    //butBind.Location = new Point(214, 19);

                    tBarFocus.Minimum       = pMin;
                    tBarFocus.Maximum       = pMax;
                    tBarFocus.Value         = pDefault;
                    tBarFocus.Name          = "TrackBarFocus";
                    tBarFocus.AutoSize      = false;
                    tBarFocus.Width         = 283;
                    tBarFocus.Height        = 23;
                    tBarFocus.TickFrequency = pSteppingDelta;
                    tBarFocus.Location      = new Point(6, 46);
                    tBarFocus.Tag           = pCameraControl;
                    tBarFocus.Enabled       = (pCapsFlags == CameraControlFlags.Manual);
                    pCameraControl.Get(CameraControlProperty.Focus, out pValue, out pCapsFlags);
                    tBarFocus.Value   = pMax - pValue + pMin;
                    tBarFocus.Scroll += new EventHandler(this.TrackBarFocus_Scroll);

                    if (pVideoProcAmp != null)
                    {
                        ggghhh = pVideoProcAmp;
                        //pCameraControl.GetRange(CameraControlProperty.Exposure, out pMin, out pMax, out pSteppingDelta, out pDefault, out pCapsFlags);
                        ggghhh.GetRange(VideoProcAmpProperty.WhiteBalance, out pMin, out pMax, out pSteppingDelta, out pDefault, out pCapsFlags2);

                        cbExposure.Text            = "Auto exposure";
                        cbExposure.Width           = 98;
                        cbExposure.Height          = 17;
                        cbExposure.Location        = new Point(191, 23);
                        cbExposure.Tag             = butForce;
                        cbExposure.Checked         = true;
                        cbExposure.CheckedChanged += new EventHandler(this.checkBoxExposure_CheckedChanged);

                        tBarExposure.Minimum       = pMin;
                        tBarExposure.Maximum       = pMax;
                        tBarExposure.Value         = pDefault;
                        tBarExposure.Name          = "TrackBarExposure";
                        tBarExposure.AutoSize      = false;
                        tBarExposure.Width         = 283;
                        tBarExposure.Height        = 23;
                        tBarExposure.TickFrequency = pSteppingDelta;
                        tBarExposure.Location      = new Point(6, 73);
                        tBarExposure.Tag           = pCameraControl;
                        tBarExposure.Enabled       = false;
                        //pCameraControl.Get(CameraControlProperty.Exposure, out value, out pCapsFlags);
                        //tBarExposure.Value = pMax - value + pMin;
                        tBarExposure.Scroll += new EventHandler(this.TrackBarExposure_Scroll);
                    }
                    gb.Controls.Add(cbFocus);
                    gb.Controls.Add(butForce);
                    gb.Controls.Add(cbExposure);
                    gb.Controls.Add(tBarFocus);
                    gb.Controls.Add(tBarExposure);
                    Controls.Add(gb);

                    yLocation += yStep;
                }
                pVideoProcAmp = pDeviceFilter as IAMVideoProcAmp;
            }
            this.Height          = 13 + yLocation + 39;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;

            foreach (var x in HidDevices.Enumerate(VendorId, ProductId))
            {
                device = x;
                device.OpenDevice();
                byte      data = 0xff;
                HidReport out1 = new HidReport(data);
                x.WriteReport(out1);
                //byte[] str = new byte[x.Capabilities.OutputReportByteLength - 1]; ;
                //x.ReadManufacturer(out str);
                // Debug.WriteLine(System.Text.ASCIIEncoding.ASCII.GetString(str));
                device.ReadReport(OnReport);
            }
        }
Beispiel #8
0
        public static void AddBDATunerAndDemodulatorToGraph(IFilterGraph2 graphBuilder, IBaseFilter networkProvider, out IBaseFilter tuner, out IBaseFilter capture)
        {
            int hr = 0;

            DsDevice[]            devices;
            ICaptureGraphBuilder2 capBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();

            capBuilder.SetFiltergraph(graphBuilder);

            try
            {
                tuner   = null;
                capture = null;

                devices = DsDevice.GetDevicesOfCat(FilterCategory.BDASourceFiltersCategory);

                for (int i = 0; i < devices.Length; i++)
                {
                    IBaseFilter tmp;

                    hr = graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                    DsError.ThrowExceptionForHR(hr);

                    hr = capBuilder.RenderStream(null, null, networkProvider, null, tmp);
                    if (hr == 0)
                    {
                        tuner = tmp;
                        break;
                    }
                    else
                    {
                        hr = graphBuilder.RemoveFilter(tmp);
                        Marshal.ReleaseComObject(tmp);
                    }
                }

                devices = DsDevice.GetDevicesOfCat(FilterCategory.BDAReceiverComponentsCategory);

                for (int i = 0; i < devices.Length; i++)
                {
                    IBaseFilter tmp;

                    hr = graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                    DsError.ThrowExceptionForHR(hr);

                    hr = capBuilder.RenderStream(null, null, tuner, null, tmp);
                    if (hr == 0)
                    {
                        capture = tmp;
                        break;
                    }
                    else
                    {
                        hr = graphBuilder.RemoveFilter(tmp);
                        Marshal.ReleaseComObject(tmp);
                    }
                }
            }
            finally
            {
                Marshal.ReleaseComObject(capBuilder);
            }
        }
        private void AddAndConnectBDABoardFilters()
        {
            int hr = 0;

            DsDevice[] devices;

            ICaptureGraphBuilder2 capBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();

            capBuilder.SetFiltergraph(this.graphBuilder);

            try
            {
                // Enumerate BDA Source filters category and found one that can connect to the network provider
                devices = DsDevice.GetDevicesOfCat(FilterCategory.BDASourceFiltersCategory);
                for (int i = 0; i < devices.Length; i++)
                {
                    IBaseFilter tmp;

                    hr = graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                    DsError.ThrowExceptionForHR(hr);

                    hr = capBuilder.RenderStream(null, null, this.networkProvider, null, tmp);
                    if (hr == 0)
                    {
                        // Got it !
                        this.tuner = tmp;
                        break;
                    }
                    else
                    {
                        // Try another...
                        hr = graphBuilder.RemoveFilter(tmp);
                        Marshal.ReleaseComObject(tmp);
                    }
                }

                if (this.tuner == null)
                {
                    throw new ApplicationException("Can't find a valid BDA tuner");
                }

                // trying to connect this filter to the MPEG-2 Demux
                hr = capBuilder.RenderStream(null, null, tuner, null, mpeg2Demux);
                if (hr >= 0)
                {
                    // this is a one filter model
                    this.demodulator = null;
                    this.capture     = null;
                    return;
                }
                else
                {
                    // Then enumerate BDA Receiver Components category to found a filter connecting
                    // to the tuner and the MPEG2 Demux
                    devices = DsDevice.GetDevicesOfCat(FilterCategory.BDAReceiverComponentsCategory);

                    for (int i = 0; i < devices.Length; i++)
                    {
                        IBaseFilter tmp;

                        hr = graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                        DsError.ThrowExceptionForHR(hr);

                        hr = capBuilder.RenderStream(null, null, this.tuner, null, tmp);
                        if (hr == 0)
                        {
                            // Got it !
                            this.capture = tmp;

                            // Connect it to the MPEG-2 Demux
                            hr = capBuilder.RenderStream(null, null, this.capture, null, this.mpeg2Demux);
                            if (hr >= 0)
                            {
                                // This second filter connect both with the tuner and the demux.
                                // This is a capture filter...
                                return;
                            }
                            else
                            {
                                // This second filter connect with the tuner but not with the demux.
                                // This is in fact a demodulator filter. We now must find the true capture filter...

                                this.demodulator = this.capture;
                                this.capture     = null;

                                // saving the Demodulator's DevicePath to avoid creating it twice.
                                string demodulatorDevicePath = devices[i].DevicePath;

                                for (int j = 0; i < devices.Length; j++)
                                {
                                    if (devices[j].DevicePath.Equals(demodulatorDevicePath))
                                    {
                                        continue;
                                    }

                                    hr = graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                                    DsError.ThrowExceptionForHR(hr);

                                    hr = capBuilder.RenderStream(null, null, this.demodulator, null, tmp);
                                    if (hr == 0)
                                    {
                                        // Got it !
                                        this.capture = tmp;

                                        // Connect it to the MPEG-2 Demux
                                        hr = capBuilder.RenderStream(null, null, this.capture, null, this.mpeg2Demux);
                                        if (hr >= 0)
                                        {
                                            // This second filter connect both with the demodulator and the demux.
                                            // This is a true capture filter...
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        // Try another...
                                        hr = graphBuilder.RemoveFilter(tmp);
                                        Marshal.ReleaseComObject(tmp);
                                    }
                                } // for j

                                // We have a tuner and a capture/demodulator that don't connect with the demux
                                // and we found no additionals filters to build a working filters chain.
                                throw new ApplicationException("Can't find a valid BDA filter chain");
                            }
                        }
                        else
                        {
                            // Try another...
                            hr = graphBuilder.RemoveFilter(tmp);
                            Marshal.ReleaseComObject(tmp);
                        }
                    } // for i

                    // We have a tuner that connect to the Network Provider BUT not with the demux
                    // and we found no additionals filters to build a working filters chain.
                    throw new ApplicationException("Can't find a valid BDA filter chain");
                }
            }
            finally
            {
                Marshal.ReleaseComObject(capBuilder);
            }
        }
Beispiel #10
0
        private void SetupDialogForm_Load(object sender, EventArgs e)
        {
            List <DeviceItem> items = new List <DeviceItem>(); bool found = false;

            foreach (DsDevice device in DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice))
            {
                if (string.IsNullOrEmpty(device.Name))
                {
                    continue;
                }

                items.Add(new DeviceItem(device.Name));

                if (device.Name == Camera.webcamName)
                {
                    found = true;
                }
            }

            if (!found)
            {
                items.Add(new DeviceItem(Camera.webcamName, false));
            }

            items.Sort(this);

            this.comboBoxWebcam.Items.Clear();
            this.comboBoxWebcam.Items.AddRange(items.ToArray());

            for (int index = 0; index < items.Count; index++)
            {
                DeviceItem item = items[index];

                if (item.Name == Camera.webcamName)
                {
                    this.comboBoxWebcam.SelectedIndex = index;
                }
            }

            this.textBoxPixelSizeX.Text = Camera.pixelSizeX.ToString();
            this.textBoxPixelSizeY.Text = Camera.pixelSizeY.ToString();

            /////

            items.Clear(); found = false;

            foreach (string name in SerialPort.GetPortNames())
            {
                items.Add(new DeviceItem(name));

                if (name == Camera.comPortName)
                {
                    found = true;
                }
            }

            if (!found)
            {
                items.Add(new DeviceItem(Camera.comPortName, false));
            }

            items.Sort(this);

            this.comboBoxComPort.Items.Clear();
            this.comboBoxComPort.Items.AddRange(items.ToArray());

            for (int index = 0; index < items.Count; index++)
            {
                DeviceItem item = items[index];

                if (item.Name == Camera.comPortName)
                {
                    this.comboBoxComPort.SelectedIndex = index;
                }
            }

            Util util = new Util();

            if (util.ServicePack > 0)
            {
                this.labelPlatformVersion.Text = string.Format(CultureInfo.InvariantCulture, "Platform Version: {0}.{1} SP{2}", util.MajorVersion, util.MinorVersion, util.ServicePack);
            }
            else
            {
                this.labelPlatformVersion.Text = string.Format(CultureInfo.InvariantCulture, "Platform Version: {0}.{1}", util.MajorVersion, util.MinorVersion);
            }

            Version version = Assembly.GetExecutingAssembly().GetName().Version;

            this.labelDriverVersion.Text = string.Format(CultureInfo.InvariantCulture, "Driver Version: {0}.{1}", version.Major, version.Minor);

            this.checkBoxTraceLogger.Checked = Camera.traceLogger.Enabled;
        }
Beispiel #11
0
 /// <summary>
 /// Initializes a new instance of the Capture class.
 /// Use capture device zero, default frame rate and size
 /// </summary>
 public Capture()
 {
     Initialize();
     DsDevice[] capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
     NewCamera(capDevices[0], 0, 0, 0); //force default values
 }
Beispiel #12
0
        /// <summary>
        /// Creates the filter by trying to detect it
        /// </summary>
        /// <param name="tuner">The tuner component</param>
        /// <param name="graph">The stored graph</param>
        /// <param name="graphBuilder">The graphBuilder</param>
        /// <returns>true, if the graph building was successful</returns>
        private bool CreateAutomaticFilterInstance(Graph graph, IFilterGraph2 graphBuilder, Tuner tuner)
        {
            _audioTunerIn = null;
            DsDevice[] devices;
            //get list of all crossbar devices installed on this system
            try
            {
                devices = DsDevice.GetDevicesOfCat(FilterCategory.AMKSCrossbar);
                devices = DeviceSorter.Sort(devices, graph.Tuner.Name);
            }
            catch (Exception)
            {
                Log.Log.WriteFile("analog: AddCrossBarFilter no crossbar devices found");
                return(false);
            }
            if (devices == null || devices.Length == 0)
            {
                Log.Log.WriteFile("analog: AddCrossBarFilter no crossbar devices found");
                return(false);
            }
            //try each crossbar
            for (int i = 0; i < devices.Length; i++)
            {
                IBaseFilter tmp;
                Log.Log.WriteFile("analog: AddCrossBarFilter try:{0} {1}", devices[i].Name, i);
                //if crossbar is already in use then we can skip it
                if (DevicesInUse.Instance.IsUsed(devices[i]))
                {
                    continue;
                }
                int hr;
                try
                {
                    //add the crossbar to the graph
                    hr = graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                }
                catch (Exception)
                {
                    Log.Log.WriteFile("analog: cannot add filter to graph");
                    continue;
                }
                if (hr != 0)
                {
                    //failed. try next crossbar
                    if (tmp != null)
                    {
                        graphBuilder.RemoveFilter(tmp);
                        Release.ComObject("CrossBarFilter", tmp);
                    }
                    continue;
                }
                _crossBarFilter = (IAMCrossbar)tmp;
                CheckCapabilities();
                if (_videoOutPinIndex == -1)
                {
                    Log.Log.WriteFile("analog: AddCrossbarFilter no video output found");
                    graphBuilder.RemoveFilter(tmp);
                    _crossBarFilter = null;
                    Release.ComObject("CrossBarFilter", tmp);
                    continue;
                }

                // Check that the crossbar has a tuner video input pin.
                IPin pinIn = null;
                if (_videoPinMap.ContainsKey(AnalogChannel.VideoInputType.Tuner))
                {
                    pinIn = DsFindPin.ByDirection(tmp, PinDirection.Input, _videoPinMap[AnalogChannel.VideoInputType.Tuner]);
                }
                if (pinIn == null)
                {
                    // no pin found, continue with next crossbar
                    Log.Log.WriteFile("analog: AddCrossBarFilter no video tuner input pin detected");
                    if (tmp != null)
                    {
                        graphBuilder.RemoveFilter(tmp);
                        _crossBarFilter = null;
                        Release.ComObject("CrossBarFilter", tmp);
                    }
                    continue;
                }
                //connect tv tuner->crossbar
                int tempVideoPinIndex;
                if (FilterGraphTools.ConnectFilter(graphBuilder, tuner.Filter, pinIn, out tempVideoPinIndex))
                {
                    // Got it, we're done
                    _filterCrossBar = tmp;
                    _crossBarDevice = devices[i];
                    DevicesInUse.Instance.Add(_crossBarDevice);
                    if (_audioTunerIn == null)
                    {
                        _audioTunerIn = DsFindPin.ByDirection(_filterCrossBar, PinDirection.Input,
                                                              _audioPinMap[AnalogChannel.AudioInputType.Tuner]);
                    }
                    Release.ComObject("crossbar videotuner pin", pinIn);
                    _videoOut = DsFindPin.ByDirection(_filterCrossBar, PinDirection.Output, _videoOutPinIndex);
                    if (_audioOutPinIndex != -1)
                    {
                        _audioOut = DsFindPin.ByDirection(_filterCrossBar, PinDirection.Output, _audioOutPinIndex);
                    }
                    Log.Log.WriteFile("analog: AddCrossBarFilter succeeded");
                    graph.Crossbar.AudioOut                = _audioOutPinIndex;
                    graph.Crossbar.AudioPinMap             = _audioPinMap;
                    graph.Crossbar.Name                    = _crossBarDevice.Name;
                    graph.Crossbar.VideoOut                = _videoOutPinIndex;
                    graph.Crossbar.VideoPinMap             = _videoPinMap;
                    graph.Crossbar.VideoPinRelatedAudioMap = _videoPinRelatedAudioMap;
                    graph.Tuner.VideoPin                   = tempVideoPinIndex;
                    break;
                }
                // cannot connect tv tuner to crossbar, try next crossbar device
                graphBuilder.RemoveFilter(tmp);
                Release.ComObject("crossbar videotuner pin", pinIn);
                Release.ComObject("crossbar filter", tmp);
            }
            return(_filterCrossBar != null);
        }
Beispiel #13
0
        /// <summary>
        /// Creates the filter based on the configuration file
        /// </summary>
        /// <param name="tuner">The tuner component</param>
        /// <param name="graph">The stored graph</param>
        /// <param name="graphBuilder">The graphBuilder</param>
        /// <returns>true, if the graph building was successful</returns>
        private bool CreateConfigurationBasedFilterInstance(Graph graph, IFilterGraph2 graphBuilder, Tuner tuner)
        {
            string deviceName = graph.Crossbar.Name;

            _audioTunerIn = null;
            DsDevice[] devices;
            //get list of all crossbar devices installed on this system
            try
            {
                devices = DsDevice.GetDevicesOfCat(FilterCategory.AMKSCrossbar);
                devices = DeviceSorter.Sort(devices, graph.Tuner.Name);
            }
            catch (Exception)
            {
                Log.Log.WriteFile("analog: AddCrossBarFilter no crossbar devices found");
                return(false);
            }
            if (devices == null || devices.Length == 0)
            {
                Log.Log.WriteFile("analog: AddCrossBarFilter no crossbar devices found");
                return(false);
            }
            //try each crossbar
            for (int i = 0; i < devices.Length; i++)
            {
                IBaseFilter tmp;
                //if crossbar is already in use then we can skip it
                if (DevicesInUse.Instance.IsUsed(devices[i]))
                {
                    continue;
                }
                if (!deviceName.Equals(devices[i].Name))
                {
                    continue;
                }
                Log.Log.WriteFile("analog: AddCrossBarFilter use:{0} {1}", devices[i].Name, i);
                int hr;
                try
                {
                    //add the crossbar to the graph
                    hr = graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                }
                catch (Exception)
                {
                    Log.Log.WriteFile("analog: cannot add filter to graph");
                    continue;
                }
                if (hr != 0)
                {
                    //failed. try next crossbar
                    if (tmp != null)
                    {
                        graphBuilder.RemoveFilter(tmp);
                        Release.ComObject("CrossBarFilter", tmp);
                    }
                    continue;
                }
                _crossBarFilter          = (IAMCrossbar)tmp;
                _videoPinMap             = graph.Crossbar.VideoPinMap;
                _audioPinMap             = graph.Crossbar.AudioPinMap;
                _videoPinRelatedAudioMap = graph.Crossbar.VideoPinRelatedAudioMap;
                _videoOutPinIndex        = graph.Crossbar.VideoOut;
                _audioOutPinIndex        = graph.Crossbar.AudioOut;
                if (_videoOutPinIndex == -1)
                {
                    Log.Log.WriteFile("analog: AddCrossbarFilter no video output found");
                    graphBuilder.RemoveFilter(tmp);
                    _crossBarFilter = null;
                    Release.ComObject("CrossBarFilter", tmp);
                    continue;
                }
                //connect tv tuner->crossbar
                IPin tunerOut = DsFindPin.ByDirection(tuner.Filter, PinDirection.Output,
                                                      graph.Tuner.VideoPin);
                if (tunerOut != null && _videoPinMap.ContainsKey(AnalogChannel.VideoInputType.Tuner) &&
                    FilterGraphTools.ConnectPin(graphBuilder, tunerOut, tmp, _videoPinMap[AnalogChannel.VideoInputType.Tuner]))
                {
                    // Got it, we're done
                    _filterCrossBar = tmp;
                    _crossBarDevice = devices[i];
                    DevicesInUse.Instance.Add(_crossBarDevice);
                    if (_audioTunerIn == null)
                    {
                        _audioTunerIn = DsFindPin.ByDirection(_filterCrossBar, PinDirection.Input,
                                                              _audioPinMap[AnalogChannel.AudioInputType.Tuner]);
                    }
                    Release.ComObject("tuner video out", tunerOut);
                    _videoOut = DsFindPin.ByDirection(_filterCrossBar, PinDirection.Output, _videoOutPinIndex);
                    if (_audioOutPinIndex != -1)
                    {
                        _audioOut = DsFindPin.ByDirection(_filterCrossBar, PinDirection.Output, _audioOutPinIndex);
                    }
                    Log.Log.WriteFile("analog: AddCrossBarFilter succeeded");
                    break;
                }
                // cannot connect tv tuner to crossbar, try next crossbar device
                if (tmp != null)
                {
                    graphBuilder.RemoveFilter(tmp);
                    Release.ComObject("crossbarFilter filter", tmp);
                }
                if (tunerOut != null)
                {
                    Release.ComObject("tuner video out", tunerOut);
                }
            }
            return(_filterCrossBar != null);
        }
Beispiel #14
0
        public static List <string> GetDevices()
        {
            var devices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);

            return(devices.Select(t => t.Name).ToList());
        }
Beispiel #15
0
        protected DsDevice FindDeviceByName(string name)
        {
            var devices = DsDevice.GetDevicesOfCat(FilterCategory.LegacyAmFilterCategory);

            return(devices.FirstOrDefault(device => device.GetPropBagValue("FriendlyName") == name));
        }
 public CameraActivity()
 {
     ListCamerasData = new List <KeyValuePair <int, string> >();
     _SystemCamereas = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
     _DeviceIndex    = 0;
 }
Beispiel #17
0
        /// <summary>
        /// Configures the DirectShow graph to play the selected video capture
        /// device with the selected parameters
        /// </summary>
        private void SetupGraph()
        {
            /* Clean up any messes left behind */
            FreeResources();

            try
            {
                /* Create a new graph */
                m_graph = (IGraphBuilder) new FilterGraphNoThread();

#if DEBUG
                m_rotEntry = new DsROTEntry(m_graph);
#endif

                /* Create a capture graph builder to help
                 * with rendering a capture graph */
                var graphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();

                /* Set our filter graph to the capture graph */
                int hr = graphBuilder.SetFiltergraph(m_graph);
                DsError.ThrowExceptionForHR(hr);

                /* Add our capture device source to the graph */
                if (m_videoCaptureSourceChanged)
                {
                    m_captureDevice = AddFilterByName(m_graph,
                                                      FilterCategory.VideoInputDevice,
                                                      VideoCaptureSource);

                    m_videoCaptureSourceChanged = false;
                }
                else if (m_videoCaptureDeviceChanged)
                {
                    m_captureDevice = AddFilterByDevicePath(m_graph,
                                                            FilterCategory.VideoInputDevice,
                                                            VideoCaptureDevice.DevicePath);

                    m_videoCaptureDeviceChanged = false;
                }

                /* If we have a null capture device, we have an issue */
                if (m_captureDevice == null)
                {
                    throw new Exception(string.Format("Capture device {0} not found or could not be created", VideoCaptureSource));
                }

                if (UseYuv && !EnableSampleGrabbing)
                {
                    /* Configure the video output pin with our parameters and if it fails
                     * then just use the default media subtype*/
                    if (!SetVideoCaptureParameters(graphBuilder, m_captureDevice, MediaSubType.YUY2))
                    {
                        SetVideoCaptureParameters(graphBuilder, m_captureDevice, Guid.Empty);
                    }
                }
                else
                {
                    /* Configure the video output pin with our parameters */
                    SetVideoCaptureParameters(graphBuilder, m_captureDevice, Guid.Empty);
                }

                var rendererType = VideoRendererType.VideoMixingRenderer9;

                /* Creates a video renderer and register the allocator with the base class */
                m_renderer = CreateVideoRenderer(rendererType, m_graph, 1);

                if (rendererType == VideoRendererType.VideoMixingRenderer9)
                {
                    var mixer = m_renderer as IVMRMixerControl9;

                    if (mixer != null && !EnableSampleGrabbing && UseYuv)
                    {
                        VMR9MixerPrefs dwPrefs;
                        mixer.GetMixingPrefs(out dwPrefs);
                        dwPrefs &= ~VMR9MixerPrefs.RenderTargetMask;
                        dwPrefs |= VMR9MixerPrefs.RenderTargetYUV;
                        /* Prefer YUV */
                        mixer.SetMixingPrefs(dwPrefs);
                    }
                }

                if (EnableSampleGrabbing)
                {
                    m_sampleGrabber = (ISampleGrabber) new SampleGrabber();
                    SetupSampleGrabber(m_sampleGrabber);
                    hr = m_graph.AddFilter(m_sampleGrabber as IBaseFilter, "SampleGrabber");
                    DsError.ThrowExceptionForHR(hr);
                }

                IBaseFilter     mux  = null;
                IFileSinkFilter sink = null;
                if (!string.IsNullOrEmpty(this.m_fileName))
                {
                    hr = graphBuilder.SetOutputFileName(MediaSubType.Asf, this.m_fileName, out mux, out sink);
                    DsError.ThrowExceptionForHR(hr);

                    hr = graphBuilder.RenderStream(PinCategory.Capture, MediaType.Video, m_captureDevice, null, mux);
                    DsError.ThrowExceptionForHR(hr);

                    // use the first audio device
                    var audioDevices = DsDevice.GetDevicesOfCat(FilterCategory.AudioInputDevice);

                    if (audioDevices.Length > 0)
                    {
                        var audioDevice = AddFilterByDevicePath(m_graph,
                                                                FilterCategory.AudioInputDevice,
                                                                audioDevices[0].DevicePath);

                        hr = graphBuilder.RenderStream(PinCategory.Capture, MediaType.Audio, audioDevice, null, mux);
                        DsError.ThrowExceptionForHR(hr);
                    }
                }

                hr = graphBuilder.RenderStream(PinCategory.Preview,
                                               MediaType.Video,
                                               m_captureDevice,
                                               null,
                                               m_renderer);

                DsError.ThrowExceptionForHR(hr);

                /* Register the filter graph
                 * with the base classes */
                SetupFilterGraph(m_graph);

                /* Sets the NaturalVideoWidth/Height */
                SetNativePixelSizes(m_renderer);

                HasVideo = true;

                /* Make sure we Release() this COM reference */
                if (mux != null)
                {
                    Marshal.ReleaseComObject(mux);
                }
                if (sink != null)
                {
                    Marshal.ReleaseComObject(sink);
                }

                Marshal.ReleaseComObject(graphBuilder);
            }
            catch (Exception ex)
            {
                /* Something got fuct up */
                FreeResources();
                InvokeMediaFailed(new MediaFailedEventArgs(ex.Message, ex));
            }

            /* Success */
            InvokeMediaOpened();
        }
Beispiel #18
0
        public void Initialize(ContentManager content, GraphicsDevice graphics)
        {
            //WebCamDevices
            webCamDevices               = new System.Windows.Forms.ComboBox();
            webCamDevices.Location      = new System.Drawing.Point(635, 320);
            webCamDevices.Size          = new System.Drawing.Size(200, 40);
            webCamDevices.FlatStyle     = System.Windows.Forms.FlatStyle.Flat;
            webCamDevices.Name          = "WebCamDevices";
            webCamDevices.AllowDrop     = false;
            webCamDevices.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            cameraDevices               = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);

            //
            //WebCamera
            //
            cameraFeedBox = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(cameraFeedBox)).BeginInit();
            stillImageBox = new System.Windows.Forms.PictureBox();
            ((System.ComponentModel.ISupportInitialize)(stillImageBox)).BeginInit();
            //CameraFeed
            cameraFeedBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            cameraFeedBox.Location    = new System.Drawing.Point(635, 165);
            cameraFeedBox.Name        = "CameraFeed";
            cameraFeedBox.Size        = new System.Drawing.Size(200, 150);
            cameraFeedBox.TabIndex    = 0;
            cameraFeedBox.TabStop     = false;
            //StillImage
            stillImageBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            stillImageBox.Location    = new System.Drawing.Point(630, 400);
            stillImageBox.Name        = "StillImage";
            stillImageBox.Size        = new System.Drawing.Size(200, 150);
            stillImageBox.TabIndex    = 1;
            stillImageBox.TabStop     = false;
            //Cameraboxes
            cameraBoxes             = new System.Windows.Forms.PictureBox();
            cameraBoxes.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            cameraBoxes.Location    = new System.Drawing.Point(0, 0);
            cameraBoxes.Name        = "CameraBox";
            cameraBoxes.Size        = new System.Drawing.Size(VIDEOWIDTH, VIDEOHEIGHT);
            cameraBoxes.TabIndex    = 0;
            cameraBoxes.BackColor   = System.Drawing.Color.Transparent;
            System.Drawing.Bitmap pic = new System.Drawing.Bitmap(VIDEOWIDTH, VIDEOHEIGHT);
            using (System.Drawing.Graphics graph = System.Drawing.Graphics.FromImage(pic))
            {
                System.Drawing.Pen   pen = new System.Drawing.Pen(System.Drawing.Color.Purple, 1);
                System.Drawing.Brush b   = System.Drawing.Brushes.Transparent;
                graph.FillRectangle(b, 0, 0, 200, 150);
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        graph.DrawRectangle(pen, 25 + 25 - 10 + 50 * j, 25 - 10 + 50 * i, 20, 20);
                    }
                }
                pen.Dispose();
            }
            cameraBoxes.Image = pic;


            cameraFeedBox.Controls.Add(cameraBoxes);
            System.Windows.Forms.Control.FromHandle(GameEngine.WindowPtr).Controls.Add(stillImageBox);
            System.Windows.Forms.Control.FromHandle(GameEngine.WindowPtr).Controls.Add(cameraFeedBox);
            System.Windows.Forms.Control.FromHandle(GameEngine.WindowPtr).Controls.Add(webCamDevices);


            webCamDevices.SelectedIndexChanged += On_WebDeviceChanged;

            //CameraButton
            takeImageButton = new Button(new Sprite2D(content.Load <Texture2D>("Sprites/Button"), new Rectangle(635 + 50, 345, 100, 50)));
            cameraIcon      = new Sprite2D(content.Load <Texture2D>("Sprites/Camera"), new Rectangle(0, 0, 50, 50));
            cameraIcon.Center(takeImageButton.Bounds);
            takeImageButton.Click += On_TakeImageButtonClick;
            //Background
            background = new Sprite2D(content.Load <Texture2D>("Sprites/ColorChooserBackground"), new Rectangle(585, 100, 300, 525));

            //Extra
            exitBtn        = new Button(new Sprite2D(content.Load <Texture2D>("Sprites/XMark"), new Rectangle(865, 100, 20, 20)));
            exitBtn.Click += new EventHandler((sender, e) => { OnExitButtonClick(); });

            UpdateCameraDevices();
        }
        private void DetectSupportedBdaSourceDevices(ref HashSet <string> previouslyKnownDevices, ref HashSet <string> knownDevices)
        {
            Log.Log.Debug("Detect BDA source devices");

            // MS generic, MCE 2005 roll-up 2 or better
            bool isMsGenericNpAvailable = FilterGraphTools.IsThisComObjectInstalled(typeof(NetworkProvider).GUID);

            DsDevice[] connectedDevices = DsDevice.GetDevicesOfCat(FilterCategory.BDASourceFiltersCategory);
            foreach (DsDevice connectedDevice in connectedDevices)
            {
                string name       = connectedDevice.Name;
                string devicePath = connectedDevice.DevicePath;
                if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(devicePath))
                {
                    continue;
                }
                if (previouslyKnownDevices.Contains(devicePath))
                {
                    knownDevices.Add(devicePath);
                    continue;
                }

                // North American CableCARD tuners [PBDA].
                if (name.StartsWith("HDHomeRun Prime") || name.StartsWith("Ceton InfiniTV"))
                {
                    Log.Log.Info("Detected new PBDA CableCARD tuner device {0} {1}", name, devicePath);
                    TunerPbdaCableCard cableCardTuner = new TunerPbdaCableCard(connectedDevice);
                    knownDevices.Add(devicePath);
                    _deviceEventListener.OnDeviceAdded(cableCardTuner);
                    continue;
                }

                IBaseFilter tmpDeviceFilter;
                try
                {
                    _graphBuilder.AddSourceFilterForMoniker(connectedDevice.Mon, null, name, out tmpDeviceFilter);
                }
                catch (Exception ex)
                {
                    Log.Log.Error("Failed to add filter to detect device type for {0}!\r\n{1}", name, ex);
                    continue;
                }

                try
                {
                    // Silicondust regular (non-CableCARD) HDHomeRun. Workaround for tuner type
                    // detection issue. The MS generic provider would always detect DVB-T.
                    bool isCablePreferred = false;
                    if (name.StartsWith("Silicondust HDHomeRun Tuner"))
                    {
                        isCablePreferred = GetHdHomeRunSourceType(name).Equals("Digital Cable");
                    }

                    Log.Log.Info("Detected new digital BDA tuner device {0} {1}", name, devicePath);

                    // Try the MediaPortal network provider first.
                    ITVCard deviceToAdd = null;
                    if (_mpNp != null)
                    {
                        Log.Log.Debug("  check type with MP NP");
                        IDvbNetworkProvider interfaceNetworkProvider = (IDvbNetworkProvider)_mpNp;
                        string hash = GetHash(devicePath);
                        interfaceNetworkProvider.ConfigureLogging(GetFileName(devicePath), hash, LogLevelOption.Debug);
                        if (ConnectFilter(_graphBuilder, _mpNp, tmpDeviceFilter))
                        {
                            TuningType tuningTypes;
                            interfaceNetworkProvider.GetAvailableTuningTypes(out tuningTypes);
                            Log.Log.Debug("  tuning types = {0}, hash = {1}", tuningTypes, hash);
                            if ((tuningTypes & TuningType.DvbT) != 0 && !isCablePreferred)
                            {
                                deviceToAdd = new TvCardDVBT(connectedDevice);
                            }
                            else if ((tuningTypes & TuningType.DvbS) != 0 && !isCablePreferred)
                            {
                                deviceToAdd = new TvCardDVBS(connectedDevice);
                            }
                            else if ((tuningTypes & TuningType.DvbC) != 0)
                            {
                                deviceToAdd = new TvCardDVBC(connectedDevice);
                            }
                            else if ((tuningTypes & TuningType.Atsc) != 0)
                            {
                                deviceToAdd = new TvCardATSC(connectedDevice);
                            }
                            else
                            {
                                Log.Log.Debug("  connected to MP NP but type not recognised");
                            }
                        }
                        else
                        {
                            Log.Log.Debug("  failed to connect to MP NP");
                        }
                    }
                    // Try the Microsoft network provider next if the MP NP
                    // failed and the MS generic NP is available.
                    if (deviceToAdd == null && isMsGenericNpAvailable)
                    {
                        // Note: the MS NP must be added/removed to/from the graph for each
                        // device that is checked. If you don't do this, the networkTypes
                        // list gets longer and longer and longer.
                        Log.Log.Debug("  check type with MS NP");
                        IBaseFilter genericNp = null;
                        try
                        {
                            genericNp = FilterGraphTools.AddFilterFromClsid(_graphBuilder, typeof(NetworkProvider).GUID, "Microsoft Network Provider");
                        }
                        catch
                        {
                            genericNp = null;
                        }
                        if (genericNp == null)
                        {
                            Log.Log.Error(" failed to add MS NP to graph");
                        }
                        else
                        {
                            if (ConnectFilter(_graphBuilder, genericNp, tmpDeviceFilter))
                            {
                                int    networkTypesMax = 5;
                                int    networkTypeCount;
                                Guid[] networkTypes = new Guid[networkTypesMax];
                                int    hr           = (genericNp as ITunerCap).get_SupportedNetworkTypes(networkTypesMax, out networkTypeCount, networkTypes);
                                Log.Log.Debug("  network type count = {0}", networkTypeCount);
                                for (int n = 0; n < networkTypeCount; n++)
                                {
                                    Log.Log.Debug("  network type {0} = {1}", n, networkTypes[n]);
                                }
                                for (int n = 0; n < networkTypeCount; n++)
                                {
                                    if (networkTypes[n] == typeof(DVBTNetworkProvider).GUID && !isCablePreferred)
                                    {
                                        deviceToAdd = new TvCardDVBT(connectedDevice);
                                    }
                                    else if (networkTypes[n] == typeof(DVBSNetworkProvider).GUID && !isCablePreferred)
                                    {
                                        deviceToAdd = new TvCardDVBS(connectedDevice);
                                    }
                                    else if (networkTypes[n] == typeof(DVBCNetworkProvider).GUID)
                                    {
                                        deviceToAdd = new TvCardDVBC(connectedDevice);
                                    }
                                    else if (networkTypes[n] == typeof(ATSCNetworkProvider).GUID)
                                    {
                                        deviceToAdd = new TvCardATSC(connectedDevice);
                                    }
                                    if (deviceToAdd != null)
                                    {
                                        break;
                                    }
                                    else if (n == (networkTypeCount - 1))
                                    {
                                        Log.Log.Debug(" connected to MS NP but type not recognised");
                                    }
                                }
                            }
                            else
                            {
                                Log.Log.Debug("  failed to connect to MS NP");
                            }

                            _graphBuilder.RemoveFilter(genericNp);
                            Release.ComObject("device detection generic network provider", genericNp);
                            genericNp = null;
                        }
                    }
                    // Last shot is the old style Microsoft network providers.
                    if (deviceToAdd == null)
                    {
                        Log.Log.Debug("  check type with specific NPs");
                        if (ConnectFilter(_graphBuilder, _dvbtNp, tmpDeviceFilter))
                        {
                            deviceToAdd = new TvCardDVBT(connectedDevice);
                        }
                        else if (ConnectFilter(_graphBuilder, _dvbcNp, tmpDeviceFilter))
                        {
                            deviceToAdd = new TvCardDVBC(connectedDevice);
                        }
                        else if (ConnectFilter(_graphBuilder, _dvbsNp, tmpDeviceFilter))
                        {
                            deviceToAdd = new TvCardDVBS(connectedDevice);
                        }
                        else if (ConnectFilter(_graphBuilder, _atscNp, tmpDeviceFilter))
                        {
                            deviceToAdd = new TvCardATSC(connectedDevice);
                        }
                        else
                        {
                            Log.Log.Debug("  failed to connect to specific NP");
                        }
                    }

                    if (deviceToAdd != null)
                    {
                        Log.Log.Info("  tuner type = {0}", deviceToAdd.CardType);
                        knownDevices.Add(devicePath);
                        _deviceEventListener.OnDeviceAdded(deviceToAdd);
                    }
                }
                finally
                {
                    _graphBuilder.RemoveFilter(tmpDeviceFilter);
                    Release.ComObject("device detection device filter", tmpDeviceFilter);
                }
            }
        }
        /// <summary>
        /// Creates the filter based on the configuration file
        /// </summary>
        /// <param name="tvAudio">The tvaudio component</param>
        /// <param name="crossbar">The crossbar componen</param>
        /// <param name="tuner">The tuner component</param>
        /// <param name="graph">The stored graph</param>
        /// <param name="graphBuilder">The graphBuilder</param>
        /// <param name="capBuilder">The Capture graph builder</param>
        /// <returns>true, if the graph building was successful</returns>
        private bool CreateConfigurationBasedFilterInstance(Graph graph, ICaptureGraphBuilder2 capBuilder,
                                                            IFilterGraph2 graphBuilder, Tuner tuner, Crossbar crossbar,
                                                            TvAudio tvAudio)
        {
            string audioDeviceName = graph.Capture.AudioCaptureName;
            string videoDeviceName = graph.Capture.Name;

            DsDevice[] devices;
            bool       videoConnected = false;
            bool       audioConnected = false;

            //get a list of all video capture devices
            try
            {
                if (tuner.TunerName == "Adaptec USB TvTuner")
                {
                    Log.Log.WriteFile("analog: Adaptec USB device detected!");
                    devices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
                }
                else
                {
                    devices = DsDevice.GetDevicesOfCat(FilterCategory.AMKSCapture); //shouldn't be VideoInputDevice
                    devices = DeviceSorter.Sort(devices, tuner.TunerName, tvAudio.TvAudioName, crossbar.CrossBarName);
                }
            }
            catch (Exception)
            {
                Log.Log.WriteFile("analog: AddTvCaptureFiler error in allocating devices collection");
                return(false);
            }
            if (devices.Length == 0)
            {
                Log.Log.WriteFile("analog: AddTvCaptureFilter no tvcapture devices found");
                return(false);
            }
            //try each video capture filter
            for (int i = 0; i < devices.Length; i++)
            {
                bool        filterUsed = false;
                IBaseFilter tmp;
                if (_badCaptureDevices.Contains(devices[i].Name))
                {
                    Log.Log.WriteFile("analog: AddTvCaptureFilter bypassing: {0}", devices[i].Name);
                    continue;
                }
                Log.Log.WriteFile("analog: AddTvCaptureFilter try:{0} {1}", devices[i].Name, i);
                // if video capture filter is in use, then we can skip it
                if (DevicesInUse.Instance.IsUsed(devices[i]))
                {
                    Log.Log.WriteFile("analog: Device: {0} in use?", devices[i].Name);
                    continue;
                }
                if (!videoDeviceName.Equals(devices[i].Name) &&
                    (audioDeviceName == null || !audioDeviceName.Equals(devices[i].Name)))
                {
                    continue;
                }
                int hr;
                try
                {
                    // add video capture filter to graph
                    hr = graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                }
                catch (Exception)
                {
                    Log.Log.WriteFile("analog: cannot add filter to graph");
                    continue;
                }
                if (hr != 0)
                {
                    //cannot add video capture filter to graph, try next one
                    if (tmp != null)
                    {
                        Log.Log.WriteFile("analog: cannot add filter: {0} to graph", devices[i].Name);
                        graphBuilder.RemoveFilter(tmp);
                        Release.ComObject("TvCaptureFilter", tmp);
                    }
                    continue;
                }
                // connect crossbar->video capture filter
                if (videoDeviceName.Equals(devices[i].Name) &&
                    FilterGraphTools.ConnectPin(graphBuilder, crossbar.VideoOut, tmp, graph.Capture.VideoIn))
                {
                    _filterVideoCapture = tmp;
                    _videoCaptureDevice = devices[i];
                    if (_audioCaptureDevice != _videoCaptureDevice)
                    {
                        DevicesInUse.Instance.Add(_videoCaptureDevice);
                    }
                    Log.Log.WriteFile("analog: AddTvCaptureFilter connected video to crossbar successfully");
                    videoConnected = true;
                    filterUsed     = true;
                }
                // crossbar->audio capture filter
                // Many video capture are also the audio capture filter, so we can always try it again
                if (audioDeviceName.Equals(devices[i].Name) &&
                    FilterGraphTools.ConnectPin(graphBuilder, crossbar.AudioOut, tmp, graph.Capture.AudioIn))
                {
                    _filterAudioCapture = tmp;
                    _audioCaptureDevice = devices[i];
                    if (_audioCaptureDevice != _videoCaptureDevice)
                    {
                        DevicesInUse.Instance.Add(_audioCaptureDevice);
                    }
                    Log.Log.WriteFile("analog: AddTvCaptureFilter connected audio to crossbar successfully");
                    audioConnected = true;
                    filterUsed     = true;
                }
                // _audioCaptureDevice should never be null - avoids null exception crashes with Encoder.cs
                else
                {
                    _audioCaptureDevice = devices[i];
                }

                if (!filterUsed)
                {
                    // cannot connect crossbar->video capture filter, remove filter from graph
                    // cand continue with the next vieo capture filter
                    Log.Log.WriteFile("analog: AddTvCaptureFilter failed to connect to crossbar");
                    graphBuilder.RemoveFilter(tmp);
                    Release.ComObject("capture filter", tmp);
                }
                else
                {
                    i = -1; // Go through the devices again from the start...
                }
                if (videoConnected && audioConnected)
                {
                    break;
                }
            }
            if (_filterVideoCapture != null)
            {
                if (graph.Capture.TeletextPin != -1)
                {
                    _pinVBI = DsFindPin.ByDirection(_filterVideoCapture, PinDirection.Output,
                                                    graph.Capture.TeletextPin);
                }
                _videoProcAmp              = _filterVideoCapture as IAMVideoProcAmp;
                _analogVideoDecoder        = _filterVideoCapture as IAMAnalogVideoDecoder;
                _streamConfig              = _filterVideoCapture as IAMStreamConfig;
                _videoFormats              = graph.Capture.AvailableVideoStandard;
                _defaultVideoProcAmpValues = graph.Capture.VideoProcAmpValues;
                _frameRate   = graph.Capture.FrameRate;
                _imageWidth  = graph.Capture.ImageWidth;
                _imageHeight = graph.Capture.ImageHeight;
                CheckCapabilitiesStreamConfig(graph, capBuilder);
                SetCaptureConfiguration(graph);
            }
            return(_filterVideoCapture != null);
        }
Beispiel #21
0
        private void AddAndConnectWDMBoardFilters()
        {
            int hr = 0;

            DsDevice[] devices;
            Guid       iid = typeof(IBaseFilter).GUID;

            this.captureGraphBuilder = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();
            captureGraphBuilder.SetFiltergraph(this.graphBuilder);

            try
            {
                if (this.VideoCaptureDevice != null)
                {
                    IBaseFilter tmp;

                    object o;
                    this.VideoCaptureDevice.Mon.BindToObject(null, null, ref iid, out o);
                    tmp = o as IBaseFilter;
                    //MessageBox.Show(this.VideoInputDevice.DevicePath);
                    //Add the Video input device to the graph
                    hr = graphBuilder.AddFilter(tmp, this.VideoCaptureDevice.Name);

                    this.videoCaptureFilter = tmp;
                    SetCaptureResolution(this.captureFormat);                     // this.captureResolution);
                    this.videoCaptureFilter = null;

                    //Render any preview pin of the device
                    //int hr1 = captureGraphBuilder.RenderStream(PinCategory.Preview, MediaType.Video, tmp, null, this.videoRenderer);
                    int hr1 = captureGraphBuilder.RenderStream(PinCategory.Capture, MediaType.Video, tmp, null, this.videoRenderer);

                    if (hr >= 0 && hr1 >= 0)
                    {
                        // Got it !
                        this.videoCaptureFilter = tmp;
                    }
                    else
                    {
                        // Try another...
                        int hr2 = graphBuilder.RemoveFilter(tmp);
                        Marshal.ReleaseComObject(tmp);
                        if (hr >= 0 && hr1 < 0)
                        {
                            DsError.ThrowExceptionForHR(hr1);
                        }
                        DsError.ThrowExceptionForHR(hr);
                        return;
                    }
                }
                else
                {
                    // Enumerate WDM Source filters category and found one that can connect to the network provider
                    devices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
                    for (int i = 0; i < devices.Length; i++)
                    {
                        IBaseFilter tmp;

                        object o;
                        devices[i].Mon.BindToObject(null, null, ref iid, out o);
                        tmp = o as IBaseFilter;

                        //Add the Video input device to the graph
                        hr = graphBuilder.AddFilter(tmp, devices[i].Name);

                        //Render any preview pin of the device
                        //int hr1 = captureGraphBuilder.RenderStream(PinCategory.Preview, MediaType.Video, tmp, null, this.videoRenderer);
                        int hr1 = captureGraphBuilder.RenderStream(PinCategory.Capture, MediaType.Video, tmp, null, this.videoRenderer);

                        if (hr >= 0 && hr1 >= 0)
                        {
                            // Got it !
                            this.videoCaptureFilter = tmp;
                            break;
                        }
                        else
                        {
                            // Try another...
                            hr = graphBuilder.RemoveFilter(tmp);
                            Marshal.ReleaseComObject(tmp);
                        }
                    }
                }
                // Assume we found a video filter...

                AddAndConnectNullRendererForWPF();
                //if (useWPF)
                //{
                //    IPin pinOutFromFilterOut = DsFindPin.ByDirection(this.videoRenderer, PinDirection.Output, 0);
                //    if (pinOutFromFilterOut != null)
                //    {
                //        hr = this.graphBuilder.Render(pinOutFromFilterOut);
                //        Marshal.ReleaseComObject(pinOutFromFilterOut);
                //    }
                //}

                if (this.AudioCaptureDevice != null)
                {
                    if (this.VideoCaptureDevice != null && this.videoCaptureFilter != null && this.AudioCaptureDevice.DevicePath == this.VideoCaptureDevice.DevicePath)
                    {
                        //Render any preview pin of the device
                        int hr1 = captureGraphBuilder.RenderStream(null, MediaType.Audio, this.videoCaptureFilter, null, this.audioRenderer);
                        DsError.ThrowExceptionForHR(hr);

                        if (hr1 >= 0)
                        {
                            // Got it !
                            this.audioCaptureFilter = null;                             // this.videoCaptureFilter;
                        }
                        else
                        {
                            // No audio?
                        }
                    }
                    else
                    {
                        IBaseFilter tmp;

                        object o;
                        this.AudioCaptureDevice.Mon.BindToObject(null, null, ref iid, out o);
                        tmp = o as IBaseFilter;

                        //Add the audio input device to the graph
                        hr = graphBuilder.AddFilter(tmp, this.AudioCaptureDevice.Name);
                        DsError.ThrowExceptionForHR(hr);

                        //Render any preview pin of the device
                        int hr1 = captureGraphBuilder.RenderStream(null, MediaType.Audio, tmp, null, this.audioRenderer);
                        DsError.ThrowExceptionForHR(hr);

                        if (hr >= 0 && hr1 >= 0)
                        {
                            // Got it !
                            this.audioCaptureFilter = tmp;
                        }
                        else
                        {
                            // Try another...
                            int hr2 = graphBuilder.RemoveFilter(tmp);
                            Marshal.ReleaseComObject(tmp);
                            DsError.ThrowExceptionForHR(hr);
                            return;
                        }
                    }
                }
                else
                {
                    // Then enumerate WDM AudioInputDevice category
                    //devices = DsDevice.GetDevicesOfCat(FilterCategory.AudioInputDevice);
                    devices = DsDevice.GetDevicesOfCat(FilterCategory.AMKSCapture);

                    for (int i = 0; i < devices.Length; i++)
                    {
                        IBaseFilter tmp;

                        object o;
                        devices[i].Mon.BindToObject(null, null, ref iid, out o);
                        tmp = o as IBaseFilter;

                        //Add the audio input device to the graph
                        hr = graphBuilder.AddFilter(tmp, devices[i].Name);
                        DsError.ThrowExceptionForHR(hr);

                        //Render any preview pin of the device
                        int hr1 = captureGraphBuilder.RenderStream(null, MediaType.Audio, tmp, null, this.audioRenderer);

                        if (hr >= 0 && hr1 >= 0)
                        {
                            // Got it !
                            this.audioCaptureFilter = tmp;

                            break;
                        }
                        else
                        {
                            // Try another...
                            hr = graphBuilder.RemoveFilter(tmp);
                            Marshal.ReleaseComObject(tmp);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLineIf(trace.TraceError, ex.ToString());
            }
            finally
            {
            }
        }
        /// <summary>
        /// Creates the filter by trying to detect it
        /// </summary>
        /// <param name="tvAudio">The tvaudio component</param>
        /// <param name="crossbar">The crossbar componen</param>
        /// <param name="tuner">The tuner component</param>
        /// <param name="graph">The stored graph</param>
        /// <param name="graphBuilder">The graphBuilder</param>
        /// <param name="capBuilder">The Capture graph builder</param>
        /// <returns>true, if the graph building was successful</returns>
        private bool CreateAutomaticFilterInstance(Graph graph, ICaptureGraphBuilder2 capBuilder, IFilterGraph2 graphBuilder,
                                                   Tuner tuner, Crossbar crossbar, TvAudio tvAudio)
        {
            DsDevice[] devices;
            bool       videoConnected = false;
            bool       audioConnected = false;

            //get a list of all video capture devices
            try
            {
                if (tuner.TunerName == "Adaptec USB TvTuner")
                {
                    Log.Log.WriteFile("analog: Adaptec USB device detected!");
                    devices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
                }
                else
                {
                    devices = DsDevice.GetDevicesOfCat(FilterCategory.AMKSCapture);
                    devices = DeviceSorter.Sort(devices, tuner.TunerName, tvAudio.TvAudioName, crossbar.CrossBarName);
                }
            }
            catch (Exception)
            {
                Log.Log.WriteFile("analog: AddTvCaptureFiler error in allocating devices collection");
                return(false);
            }
            if (devices.Length == 0)
            {
                Log.Log.WriteFile("analog: AddTvCaptureFilter no tvcapture devices found");
                return(false);
            }
            //try each video capture filter
            for (int i = 0; i < devices.Length; i++)
            {
                bool        filterUsed = false;
                IBaseFilter tmp;
                if (_badCaptureDevices.Contains(devices[i].Name))
                {
                    Log.Log.WriteFile("analog: AddTvCaptureFilter bypassing: {0}", devices[i].Name);
                    continue;
                }
                Log.Log.WriteFile("analog: AddTvCaptureFilter try:{0} {1}", devices[i].Name, i);
                // if video capture filter is in use, then we can skip it
                if (DevicesInUse.Instance.IsUsed(devices[i]))
                {
                    continue;
                }
                int hr;
                try
                {
                    // add video capture filter to graph
                    hr = graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                }
                catch (Exception)
                {
                    Log.Log.WriteFile("analog: cannot add filter to graph");
                    continue;
                }
                if (hr != 0)
                {
                    //cannot add video capture filter to graph, try next one
                    if (tmp != null)
                    {
                        graphBuilder.RemoveFilter(tmp);
                        Release.ComObject("TvCaptureFilter", tmp);
                    }
                    continue;
                }

                int destinationIndex;
                // connect crossbar->video capture filter
                if (!videoConnected &&
                    FilterGraphTools.ConnectFilter(graphBuilder, crossbar.VideoOut, tmp, out destinationIndex))
                {
                    _filterVideoCapture = tmp;
                    _videoCaptureDevice = devices[i];
                    if (_audioCaptureDevice != _videoCaptureDevice)
                    {
                        DevicesInUse.Instance.Add(_videoCaptureDevice);
                    }
                    Log.Log.WriteFile("analog: AddTvCaptureFilter connected video to crossbar successfully");
                    graph.Capture.Name    = _videoCaptureDevice.Name;
                    graph.Capture.VideoIn = destinationIndex;
                    videoConnected        = true;
                    filterUsed            = true;
                }
                // crossbar->audio capture filter
                // Many video capture are also the audio capture filter, so we can always try it again
                if (videoConnected && FilterGraphTools.ConnectFilter(graphBuilder, crossbar.AudioOut, tmp, out destinationIndex))
                {
                    _filterAudioCapture = tmp;
                    _audioCaptureDevice = devices[i];
                    if (_audioCaptureDevice != _videoCaptureDevice)
                    {
                        DevicesInUse.Instance.Add(_audioCaptureDevice);
                    }
                    Log.Log.WriteFile("analog: AddTvCaptureFilter connected audio to crossbar successfully");
                    graph.Capture.AudioCaptureName = devices[i].Name;
                    graph.Capture.AudioIn          = destinationIndex;
                    audioConnected = true;
                    filterUsed     = true;
                }
                // _audioCaptureDevice should never be null - avoids null exception crashes with Encoder.cs
                else
                {
                    _audioCaptureDevice = devices[i];
                }

                if (!filterUsed)
                {
                    // cannot connect crossbar->video capture filter, remove filter from graph
                    // cand continue with the next vieo capture filter
                    Log.Log.WriteFile("analog: AddTvCaptureFilter failed to connect to crossbar");
                    graphBuilder.RemoveFilter(tmp);
                    Release.ComObject("capture filter", tmp);
                }
                else
                {
                    i = -1; // Go through the devices again from the start...
                }
                if (videoConnected && audioConnected)
                {
                    break;
                }
            }
            if (_filterVideoCapture != null)
            {
                FindVBIPin(graph);
                CheckCapabilities(graph, capBuilder);
            }
            return(_filterVideoCapture != null);
        }
Beispiel #23
0
 public static string[] GetDevicesName()
 {
     return(DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice).Select(x => x.Name).ToArray());
 }
 /// <summary>
 /// Updates list of devices (cameras) of CameraChoice.
 /// </summary>
 public void UpdateDeviceList()
 {
     m_pCapDevices = new List <DsDevice>(DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice));
 }
        private void CMB_videosources_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (MainV2.MONO)
            {
                return;
            }

            int                   hr;
            int                   count;
            int                   size;
            object                o;
            IBaseFilter           capFilter = null;
            ICaptureGraphBuilder2 capGraph  = null;
            AMMediaType           media     = null;
            VideoInfoHeader       v;
            VideoStreamConfigCaps c;
            var                   modes = new List <GCSBitmapInfo>();

            // Get the ICaptureGraphBuilder2
            capGraph = (ICaptureGraphBuilder2) new CaptureGraphBuilder2();
            var m_FilterGraph = (IFilterGraph2) new FilterGraph();

            DsDevice[] capDevices;
            capDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);

            // Add the video device
            hr = m_FilterGraph.AddSourceFilterForMoniker(capDevices[CMB_videosources.SelectedIndex].Mon, null,
                                                         "Video input", out capFilter);
            try
            {
                DsError.ThrowExceptionForHR(hr);
            }
            catch (Exception ex)
            {
                CustomMessageBox.Show("Can not add video source\n" + ex);
                return;
            }

            // Find the stream config interface
            hr = capGraph.FindInterface(PinCategory.Capture, MediaType.Video, capFilter, typeof(IAMStreamConfig).GUID,
                                        out o);
            DsError.ThrowExceptionForHR(hr);

            var videoStreamConfig = o as IAMStreamConfig;

            if (videoStreamConfig == null)
            {
                CustomMessageBox.Show("Failed to get IAMStreamConfig");
                return;
            }

            hr = videoStreamConfig.GetNumberOfCapabilities(out count, out size);
            DsError.ThrowExceptionForHR(hr);
            var TaskMemPointer = Marshal.AllocCoTaskMem(size);

            for (var i = 0; i < count; i++)
            {
                var ptr = IntPtr.Zero;

                hr = videoStreamConfig.GetStreamCaps(i, out media, TaskMemPointer);
                v  = (VideoInfoHeader)Marshal.PtrToStructure(media.formatPtr, typeof(VideoInfoHeader));
                c  = (VideoStreamConfigCaps)Marshal.PtrToStructure(TaskMemPointer, typeof(VideoStreamConfigCaps));
                modes.Add(new GCSBitmapInfo(v.BmiHeader.Width, v.BmiHeader.Height, c.MaxFrameInterval,
                                            c.VideoStandard.ToString(), media));
            }
            Marshal.FreeCoTaskMem(TaskMemPointer);
            DsUtils.FreeAMMediaType(media);

            CMB_videoresolutions.DataSource = modes;

            if (Settings.Instance["video_options"] != "" && CMB_videosources.Text != "")
            {
                try
                {
                    CMB_videoresolutions.SelectedIndex = Settings.Instance.GetInt32("video_options");
                }
                catch
                {
                } // ignore bad entries
            }
        }
 private void AddCaptureFilter()
 {
     DsDevice[] devices;
     Log.Log.WriteFile("HDPVR: Add Capture Filter");
     //get a list of all video capture devices
     try
     {
         devices = DsDevice.GetDevicesOfCat(FilterCategory.AMKSCapture);
         devices = DeviceSorter.Sort(devices, _tunerDevice, _filterCrossBar, _captureDevice, _filterEncoder);
     }
     catch (Exception)
     {
         Log.Log.WriteFile("HDPVR: AddTvCaptureFilter no tvcapture devices found");
         return;
     }
     if (devices.Length == 0)
     {
         Log.Log.WriteFile("HDPVR: AddTvCaptureFilter no tvcapture devices found");
         return;
     }
     //try each video capture filter
     for (int i = 0; i < devices.Length; i++)
     {
         if (devices[i].Name != _captureDeviceName)
         {
             continue;
         }
         Log.Log.WriteFile("HDPVR: AddTvCaptureFilter try:{0} {1}", devices[i].Name, i);
         // if video capture filter is in use, then we can skip it
         if (DevicesInUse.Instance.IsUsed(devices[i]))
         {
             continue;
         }
         IBaseFilter tmp;
         int         hr;
         try
         {
             // add video capture filter to graph
             hr = _graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
         }
         catch (Exception)
         {
             Log.Log.WriteFile("HDPVR: cannot add filter to graph");
             continue;
         }
         if (hr != 0)
         {
             //cannot add video capture filter to graph, try next one
             if (tmp != null)
             {
                 _graphBuilder.RemoveFilter(tmp);
                 Release.ComObject("TvCaptureFilter", tmp);
             }
             continue;
         }
         // connect crossbar->video capture filter
         hr = _capBuilder.RenderStream(null, null, _filterCrossBar, null, tmp);
         if (hr == 0)
         {
             // That worked. Since most crossbar devices require 2 connections from
             // crossbar->video capture filter, we do it again to connect the 2nd pin
             _capBuilder.RenderStream(null, null, _filterCrossBar, null, tmp);
             _filterCapture = tmp;
             _captureDevice = devices[i];
             DevicesInUse.Instance.Add(_captureDevice);
             Log.Log.WriteFile("HDPVR: AddTvCaptureFilter connected to crossbar successfully");
             break;
         }
         // cannot connect crossbar->video capture filter, remove filter from graph
         // cand continue with the next vieo capture filter
         Log.Log.WriteFile("HDPVR: AddTvCaptureFilter failed to connect to crossbar");
         _graphBuilder.RemoveFilter(tmp);
         Release.ComObject("capture filter", tmp);
     }
     if (_filterCapture == null)
     {
         Log.Log.Error("HDPVR: unable to add TvCaptureFilter to graph");
         //throw new TvException("Unable to add TvCaptureFilter to graph");
     }
 }
Beispiel #27
0
 public static DsDevice[] GetVideoDevices()
 {
     return(DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice));
 }
        private void AddEncoderFilter()
        {
            DsDevice[] devices;
            Log.Log.WriteFile("HDPVR: AddEncoderFilter");
            // first get all encoder filters available on this system
            try
            {
                devices = DsDevice.GetDevicesOfCat(FilterCategory.WDMStreamingEncoderDevices);
                devices = DeviceSorter.Sort(devices, _tunerDevice, _filterCrossBar, _captureDevice, _filterEncoder);
            }
            catch (Exception)
            {
                Log.Log.WriteFile("HDPVR: AddTvEncoderFilter no encoder devices found (Exception)");
                return;
            }

            if (devices == null)
            {
                Log.Log.WriteFile("HDPVR: AddTvEncoderFilter no encoder devices found (devices == null)");
                return;
            }

            if (devices.Length == 0)
            {
                Log.Log.WriteFile("HDPVR: AddTvEncoderFilter no encoder devices found");
                return;
            }

            //for each encoder
            Log.Log.WriteFile("HDPVR: AddTvEncoderFilter found:{0} encoders", devices.Length);
            for (int i = 0; i < devices.Length; i++)
            {
                if (devices[i].Name != _encoderDeviceName)
                {
                    continue;
                }

                //if encoder is in use, we can skip it
                if (DevicesInUse.Instance.IsUsed(devices[i]))
                {
                    Log.Log.WriteFile("HDPVR:  skip :{0} (inuse)", devices[i].Name);
                    continue;
                }

                Log.Log.WriteFile("HDPVR:  try encoder:{0} {1}", devices[i].Name, i);
                IBaseFilter tmp;
                int         hr;
                try
                {
                    //add encoder filter to graph
                    hr = _graphBuilder.AddSourceFilterForMoniker(devices[i].Mon, null, devices[i].Name, out tmp);
                }
                catch (Exception)
                {
                    Log.Log.WriteFile("HDPVR: cannot add filter {0} to graph", devices[i].Name);
                    continue;
                }
                if (hr != 0)
                {
                    //failed to add filter to graph, continue with the next one
                    if (tmp != null)
                    {
                        _graphBuilder.RemoveFilter(tmp);
                        Release.ComObject("TvEncoderFilter", tmp);
                    }
                    continue;
                }
                if (tmp == null)
                {
                    continue;
                }
                hr = _capBuilder.RenderStream(null, null, _filterCapture, null, tmp);
                if (hr == 0)
                {
                    // That worked. Since most crossbar devices require 2 connections from
                    // crossbar->video capture filter, we do it again to connect the 2nd pin
                    _capBuilder.RenderStream(null, null, _filterCapture, null, tmp);
                    _filterEncoder = tmp;
                    _encoderDevice = devices[i];
                    DevicesInUse.Instance.Add(_encoderDevice);
                    Log.Log.WriteFile("HDPVR: AddTvEncoderFilter connected to catpure successfully");
                    //and we're done
                    return;
                }
                // cannot connect crossbar->video capture filter, remove filter from graph
                // cand continue with the next vieo capture filter
                Log.Log.WriteFile("HDPVR: AddTvEncoderFilter failed to connect to capture");
                _graphBuilder.RemoveFilter(tmp);
                Release.ComObject("capture filter", tmp);
            }
            Log.Log.WriteFile("HDPVR: AddTvEncoderFilter no encoder found");
        }
        /// <summary>
        /// Program initialization
        /// </summary>
        /// <param name="sender">Sender</param>
        /// <param name="e">Event arguments</param>
        private void OnLoad(object sender, EventArgs e)
        {
            // program title
            Text = "QRCodeVideoDecoder " + QRDecoder.VersionNumber + " \u00a9 2018-2019 Uzi Granot. All rights reserved.";

                #if DEBUG
            // current directory
            string CurDir  = Environment.CurrentDirectory;
            string WorkDir = CurDir.Replace("bin\\Debug", "Work");
            if (WorkDir != CurDir && Directory.Exists(WorkDir))
            {
                Environment.CurrentDirectory = WorkDir;
            }

            // open trace file
            QRCodeTrace.Open("QRCodeVideoDecoderTrace.txt");
            QRCodeTrace.Write(Text);
                #endif

            // disable reset button
            ResetButton.Enabled   = false;
            GoToUriButton.Enabled = false;

            // get an array of web camera devices
            DsDevice[] CameraDevices = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);

            // make sure at least one is available
            if (CameraDevices == null || CameraDevices.Length == 0)
            {
                MessageBox.Show("No video cameras in this computer");
                Close();
                return;
            }

            // select the first camera
            DsDevice CameraDevice = CameraDevices[0];

            // Device moniker
            IMoniker CameraMoniker = CameraDevice.Moniker;

            // get a list of frame sizes available
            FrameSize[] FrameSizes = Camera.GetFrameSizeList(CameraMoniker);

            // make sure there is at least one frame size
            if (FrameSizes == null || FrameSizes.Length == 0)
            {
                MessageBox.Show("No video cameras in this computer");
                Close();
                return;
            }

            // test if our frame size is available
            int Index;
            for (Index = 0; Index < FrameSizes.Length &&
                 (FrameSizes[Index].Width != FrameSize.Width || FrameSizes[Index].Height != FrameSize.Height); Index++)
            {
                ;
            }

            // select first frame size
            if (Index == FrameSizes.Length)
            {
                FrameSize = FrameSizes[0];
            }

            // Set selected camera to camera control with default frame size
            // Create camera object
            VideoCamera = new Camera(PreviewPanel, CameraMoniker, FrameSize);

            // create QR code decoder
            Decoder = new QRDecoder();

            // resize window
            OnResize(sender, e);

            // create timer
            QRCodeTimer          = new Timer();
            QRCodeTimer.Interval = 200;
            QRCodeTimer.Tick    += QRCodeTimer_Tick;
            QRCodeTimer.Enabled  = true;
            return;
        }
        internal override WebcamConfiguration[] QueryFormats()
        {
            List <WebcamConfiguration> result = new List <WebcamConfiguration>();

            DsDevice      cameraDevice = cameraDevice = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice)[m_cameraDeviceIndex];
            IFilterGraph2 filterGraph = null; IBaseFilter cam = null; IPin camOutPin = null;

            try
            {
                filterGraph = (IFilterGraph2) new FilterGraph();
                DsError.ThrowExceptionForHR(filterGraph.AddSourceFilterForMoniker(cameraDevice.Mon, null, cameraDevice.Name, out cam));
                camOutPin = DsFindPin.ByCategory(cam, PinCategory.Capture, 0);

                if (camOutPin != null)
                {
                    IAMStreamConfig config = (IAMStreamConfig)camOutPin;

                    int piCount, piSize;
                    config.GetNumberOfCapabilities(out piCount, out piSize);

                    byte[]   temp       = new byte[piSize];
                    GCHandle tempHandle = GCHandle.Alloc(temp, GCHandleType.Pinned);
                    try
                    {
                        for (int x = 0; x < piCount; x++)
                        {
                            AMMediaType mediaType = null;
                            try
                            {
                                DsError.ThrowExceptionForHR(config.GetStreamCaps(x, out mediaType, tempHandle.AddrOfPinnedObject()));
                                VideoInfoHeader v = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader));

                                if (BPPIsValid(v.BmiHeader.BitCount))
                                {
                                    result.Add(new WebcamConfiguration(new Size(v.BmiHeader.Width, v.BmiHeader.Height), v.BmiHeader.BitCount, mediaType.subType));
                                }
                                else
                                {
                                    //System.Diagnostics.Debug.WriteLine("BPP " + v.BmiHeader.BitCount + " was not accepted!");
                                }
                            }
                            finally
                            {
                                if (mediaType != null)
                                {
                                    DsUtils.FreeAMMediaType(mediaType);
                                    mediaType = null;
                                }
                            }
                        }
                    }
                    finally
                    {
                        tempHandle.Free();
                    }
                }
            }
            finally
            {
                if (camOutPin != null)
                {
                    Marshal.ReleaseComObject(camOutPin);
                    camOutPin = null;
                }
                if (filterGraph != null)
                {
                    Marshal.ReleaseComObject(filterGraph);
                    filterGraph = null;
                }
            }

            result.Sort();
            return(result.ToArray());
        }