The class provides continues access to XIMEA cameras.

The video source class is aimed to provide continues access to XIMEA camera, when images are continuosly acquired from camera and provided throw the NewFrame event. It just creates a background thread and gets new images from XIMEA camera keeping the specified time interval between image acquisition. Essentially it is a wrapper class around XimeaCamera providing IVideoSource interface.

Sample usage:

// create video source for the XIMEA camera with ID 0 XimeaVideoSource videoSource = new XimeaVideoSource( 0 ); // set event handlers videoSource.NewFrame += new NewFrameEventHandler( video_NewFrame ); // start the video source videoSource.Start( ); // set exposure time to 10 milliseconds videoSource.SetParam( CameraParameter.Exposure, 10 * 1000 ); // ... // New frame event handler, which is invoked on each new available video frame private void video_NewFrame( object sender, NewFrameEventArgs eventArgs ) { // get new frame Bitmap bitmap = eventArgs.Frame; // process the frame }
Inheritance: IVideoSource
Example #1
0
        public void Enable()
        {
            if (IsEnabled)
                return;
            if (InvokeRequired)
            {
                Invoke(new SwitchDelegate(Enable));
                return;
            }

            _processing = true;
            if (Camera != null && Camera.IsRunning)
            {
                Disable();
            }

            IsEnabled = true;
            string ckies;
            switch (Camobject.settings.sourceindex)
            {
                case 0:
                    ckies = Camobject.settings.cookies ?? "";
                    ckies = ckies.Replace("[USERNAME]", Camobject.settings.login);
                    ckies = ckies.Replace("[PASSWORD]", Camobject.settings.password);
                    ckies = ckies.Replace("[CHANNEL]", Camobject.settings.ptzchannel);
                    var jpegSource = new JPEGStream2(Camobject.settings.videosourcestring)
                                         {
                                             Login = Camobject.settings.login,
                                             Password = Camobject.settings.password,
                                             ForceBasicAuthentication = Camobject.settings.forcebasic,
                                             RequestTimeout = MainForm.Conf.IPCameraTimeout,
                                             UseHTTP10 = Camobject.settings.usehttp10,
                                             HttpUserAgent = Camobject.settings.useragent,
                                             Cookies = ckies
                                         };

                    OpenVideoSource(jpegSource, true);

                    if (Camobject.settings.frameinterval != 0)
                        jpegSource.FrameInterval = Camobject.settings.frameinterval;

                    break;
                case 1:
                    ckies = Camobject.settings.cookies ?? "";
                    ckies = ckies.Replace("[USERNAME]", Camobject.settings.login);
                    ckies = ckies.Replace("[PASSWORD]", Camobject.settings.password);
                    ckies = ckies.Replace("[CHANNEL]", Camobject.settings.ptzchannel);

                    var mjpegSource = new MJPEGStream2(Camobject.settings.videosourcestring)
                                            {
                                                Login = Camobject.settings.login,
                                                Password = Camobject.settings.password,
                                                ForceBasicAuthentication = Camobject.settings.forcebasic,
                                                RequestTimeout = MainForm.Conf.IPCameraTimeout,
                                                HttpUserAgent = Camobject.settings.useragent,
                                                DecodeKey = Camobject.decodekey,
                                                Cookies = ckies
                                            };
                    OpenVideoSource(mjpegSource, true);
                    break;
                case 2:
                    string url = Camobject.settings.videosourcestring;
                    var ffmpegSource = new FFMPEGStream(url);
                    OpenVideoSource(ffmpegSource, true);
                    break;
                case 3:
                    string moniker = Camobject.settings.videosourcestring;

                    var videoSource = new VideoCaptureDevice(moniker);
                    string[] wh = Camobject.resolution.Split('x');
                    var sz = new Size(Convert.ToInt32(wh[0]), Convert.ToInt32(wh[1]));
                    var vc = videoSource.VideoCapabilities.Where(p => p.FrameSize == sz).ToList();
                    if (vc.Count>0)
                    {
                        var vc2 = vc.FirstOrDefault(p => p.AverageFrameRate == Camobject.settings.framerate) ??
                                  vc.FirstOrDefault();
                        videoSource.VideoResolution = vc2;
                    }

                    if (Camobject.settings.crossbarindex!=-1 && videoSource.CheckIfCrossbarAvailable())
                    {
                        var cbi =
                            videoSource.AvailableCrossbarVideoInputs.FirstOrDefault(
                                p => p.Index == Camobject.settings.crossbarindex);
                        if (cbi!=null)
                        {
                            videoSource.CrossbarVideoInput = cbi;
                        }
                    }

                    OpenVideoSource(videoSource, true);

                    break;
                case 4:
                    Rectangle area = Rectangle.Empty;
                    if (!String.IsNullOrEmpty(Camobject.settings.desktoparea))
                    {
                        var i = Array.ConvertAll(Camobject.settings.desktoparea.Split(','), int.Parse);
                        area = new Rectangle(i[0],i[1],i[2],i[3]);
                    }
                    var desktopSource = new DesktopStream(Convert.ToInt32(Camobject.settings.videosourcestring), area)
                                            {MousePointer = Camobject.settings.desktopmouse};
                    if (Camobject.settings.frameinterval != 0)
                        desktopSource.FrameInterval = Camobject.settings.frameinterval;
                    OpenVideoSource(desktopSource, true);

                    break;
                case 5:
                    List<String> inargs = Camobject.settings.vlcargs.Split(Environment.NewLine.ToCharArray(),
                                                                           StringSplitOptions.RemoveEmptyEntries).ToList();
                    var vlcSource = new VlcStream(Camobject.settings.videosourcestring, inargs.ToArray());
                    OpenVideoSource(vlcSource, true);
                    break;
                case 6:
                    if (XimeaSource == null || !XimeaSource.IsRunning)
                        XimeaSource = new XimeaVideoSource(Convert.ToInt32(Nv("device")));
                    OpenVideoSource(XimeaSource, true);
                    break;
                case 7:
                    var tw = false;
                    if (!String.IsNullOrEmpty(Nv("TripWires")))
                        tw = Convert.ToBoolean(Nv("TripWires"));
                    var ks = new KinectStream(Nv("UniqueKinectId"), Convert.ToBoolean(Nv("KinectSkeleton")), tw);
                    OpenVideoSource(ks, true);
                    break;
                case 8:
                    switch (Nv("custom"))
                    {
                        case "Network Kinect":
                            OpenVideoSource(new KinectNetworkStream(Camobject.settings.videosourcestring), true);
                            break;
                        default:
                            throw new Exception("No custom provider found for "+Nv("custom"));
                    }
                    break;
            }

            if (Camera != null)
            {
                Camera.LastFrameNull = true;

                IMotionDetector motionDetector = null;
                IMotionProcessing motionProcessor = null;

                switch (Camobject.detector.type)
                {
                    case "Two Frames":
                        motionDetector = new TwoFramesDifferenceDetector(Camobject.settings.suppressnoise);
                        break;
                    case "Custom Frame":
                        motionDetector = new CustomFrameDifferenceDetector(Camobject.settings.suppressnoise,
                                                                            Camobject.detector.keepobjectedges);
                        break;
                    case "Background Modelling":
                        motionDetector = new SimpleBackgroundModelingDetector(Camobject.settings.suppressnoise,
                                                                                Camobject.detector.keepobjectedges);
                        break;
                    case "Two Frames (Color)":
                        motionDetector = new TwoFramesColorDifferenceDetector(Camobject.settings.suppressnoise);
                        break;
                    case "Custom Frame (Color)":
                        motionDetector = new CustomFrameColorDifferenceDetector(Camobject.settings.suppressnoise,
                                                                            Camobject.detector.keepobjectedges);
                        break;
                    case "Background Modelling (Color)":
                        motionDetector = new SimpleColorBackgroundModelingDetector(Camobject.settings.suppressnoise,
                                                                                Camobject.detector.keepobjectedges);
                        break;
                    case "None":
                        break;
                }

                if (motionDetector != null)
                {
                    switch (Camobject.detector.postprocessor)
                    {
                        case "Grid Processing":
                            motionProcessor = new GridMotionAreaProcessing
                                                    {
                                                        HighlightColor =
                                                            ColorTranslator.FromHtml(Camobject.detector.color),
                                                        HighlightMotionGrid = Camobject.detector.highlight
                                                    };
                            break;
                        case "Object Tracking":
                            motionProcessor = new BlobCountingObjectsProcessing
                                                    {
                                                        HighlightColor =
                                                            ColorTranslator.FromHtml(Camobject.detector.color),
                                                        HighlightMotionRegions = Camobject.detector.highlight,
                                                        MinObjectsHeight = Camobject.detector.minheight,
                                                        MinObjectsWidth = Camobject.detector.minwidth
                                                    };

                            break;
                        case "Border Highlighting":
                            motionProcessor = new MotionBorderHighlighting
                                                    {
                                                        HighlightColor =
                                                            ColorTranslator.FromHtml(Camobject.detector.color)
                                                    };
                            break;
                        case "Area Highlighting":
                            motionProcessor = new MotionAreaHighlighting
                                                    {
                                                        HighlightColor =
                                                            ColorTranslator.FromHtml(Camobject.detector.color)
                                                    };
                            break;
                        case "None":
                            break;
                    }

                    if (Camera.MotionDetector != null)
                    {
                        Camera.MotionDetector.Reset();
                        Camera.MotionDetector = null;
                    }

                    Camera.MotionDetector = motionProcessor == null ? new MotionDetector(motionDetector) : new MotionDetector(motionDetector, motionProcessor);

                    Camera.AlarmLevel = Helper.CalculateTrigger(Camobject.detector.minsensitivity);
                    Camera.AlarmLevelMax = Helper.CalculateTrigger(Camobject.detector.maxsensitivity);
                    NeedMotionZones = true;
                }
                else
                {
                    Camera.MotionDetector = null;
                }

                if (!Camera.IsRunning)
                {
                    Calibrating = true;
                    CalibrateCount = 0;
                    _calibrateTarget = Camobject.detector.calibrationdelay;
                    _lastRun = DateTime.Now.Ticks;
                    Camera.Start();
                }
                if (Camera.VideoSource is XimeaVideoSource)
                {
                    //need to set these after the camera starts
                    try
                    {
                        XimeaSource.SetParam(PRM.IMAGE_DATA_FORMAT, IMG_FORMAT.RGB24);
                    }
                    catch (ApplicationException)
                    {
                        XimeaSource.SetParam(PRM.IMAGE_DATA_FORMAT, IMG_FORMAT.MONO8);
                    }
                    XimeaSource.SetParam(CameraParameter.OffsetX, Convert.ToInt32(Nv("x")));
                    XimeaSource.SetParam(CameraParameter.OffsetY, Convert.ToInt32(Nv("y")));
                    float gain;
                    float.TryParse(Nv("gain"), out gain);
                    XimeaSource.SetParam(CameraParameter.Gain, gain);
                    float exp;
                    float.TryParse(Nv("exposure"), out exp);
                    XimeaSource.SetParam(CameraParameter.Exposure, exp*1000);
                    XimeaSource.SetParam(CameraParameter.Downsampling, Convert.ToInt32(Nv("downsampling")));
                    XimeaSource.SetParam(CameraParameter.Width, Convert.ToInt32(Nv("width")));
                    XimeaSource.SetParam(CameraParameter.Height, Convert.ToInt32(Nv("height")));
                    XimeaSource.FrameInterval =
                        (int) (1000.0f/XimeaSource.GetParamFloat(CameraParameter.FramerateMax));
                }

                Camobject.settings.active = true;

                if (File.Exists(Camobject.settings.maskimage))
                {
                    Camera.Mask = Image.FromFile(Camobject.settings.maskimage);
                }

                UpdateFloorplans(false);
            }
            _recordingTime = 0;
            _timeLapseTotal = _timeLapseFrameCount = 0;
            InactiveRecord = 0;
            MovementDetected = false;
            VideoSourceErrorState = false;
            VideoSourceErrorMessage = "";
            Alerted = false;
            PTZNavigate = false;
            Camobject.ftp.ready = true;
            _lastRun = DateTime.Now.Ticks;
            MainForm.NeedsSync = true;
            ReconnectCount = 0;
            _dtPTZLastCheck = DateTime.Now;
            _movementLastDetected = DateTime.MinValue;
            _firstFrame = true;

            if (_videoBuffer != null)
            {
                _videoBuffer.Clear();
            }

            if (Camera != null)
            {
                Camera.ZFactor = 1;
                Camera.ZPoint = Point.Empty;
            }
            Invalidate();

            if (VolumeControl != null)
                VolumeControl.Enable();
            _processing = false;
        }
Example #2
0
        public void Disable()
        {
            if (!IsEnabled)
                return;

            if (InvokeRequired)
            {
                Invoke(new SwitchDelegate(Disable));
                return;
            }

            IsEnabled = false;
            _processing = true;

            if (_recordingThread != null)
                RecordSwitch(false);

            if (VolumeControl != null && VolumeControl.IsEnabled)
                VolumeControl.Disable();

            if (TopLevelControl != null)
            {
                if (((MainForm) TopLevelControl).TalkCamera == this)
                    ((MainForm) TopLevelControl).TalkTo(this, false);
            }

            Application.DoEvents();

            if (SavingTimeLapse)
            {
                CloseTimeLapseWriter();
            }
            if (_camera != null)
            {
                _camera.ClearMotionZones();
                Calibrating = false;
                if (Camera.MotionDetector != null)
                {
                    try
                    {
                        Camera.MotionDetector.Reset();
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Camera " + Camobject.id, ex);
                    }
                    Camera.MotionDetector = null;
                }
                if (_camera.VideoSource != null)
                {
                    _camera.VideoSource.PlayingFinished -= SourcePlayingFinished;
                    _camera.VideoSource.VideoSourceError -= SourceVideoSourceError;
                    _camera.NewFrame -= CameraNewFrame;
                    _camera.Alarm -= CameraAlarm;

                    if (_camera.VideoSource is KinectStream)
                    {
                        ((KinectStream)_camera.VideoSource).TripWire -= CameraAlarm;
                    }
                    try
                    {
                        _camera.SignalToStop();
                        if (_camera.VideoSource is VideoCaptureDevice)
                        {
                            _camera.VideoSource.WaitForStop();
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Error("Camera " + Camobject.id, ex);
                    }

                    if (_camera.VideoSource is XimeaVideoSource)
                    {
                        XimeaSource = null;
                        _camera.VideoSource = null;
                    }
                    _camera.Plugin = null;
                }
                try
                {
                    if (_camera.LastFrameUnmanaged != null)
                    {
                        _camera.LastFrameUnmanaged.Dispose();
                        _camera.LastFrameUnmanaged = null;
                    }
                }
                catch
                {
                }

                if (_camera.Mask != null)
                {
                    _camera.Mask.Dispose();
                    _camera.Mask = null;
                }
                _camera = null;
                BackgroundColor = MainForm.BackgroundColor;
            }
            Camobject.settings.active = false;
            _recordingTime = 0;
            InactiveRecord = 0;
            _timeLapseTotal = _timeLapseFrameCount = 0;
            ForcedRecording = false;

            MovementDetected = false;
            Alerted = false;
            FlashCounter = 0;
            ReconnectCount = 0;
            PTZNavigate = false;
            UpdateFloorplans(false);
            MainForm.NeedsSync = true;
            _errorTime = _reconnectTime = DateTime.MinValue;

            if (!ShuttingDown)
                Invalidate();

            if (_videoBuffer != null)
            {
                _videoBuffer.Clear();
            }

            _processing = false;
        }
Example #3
0
        // On "Connect" button click
        private void connectButton_Click( object sender, EventArgs e )
        {
            // set busy cursor
            this.Cursor = Cursors.WaitCursor;

            // close whatever is open now
            CloseCamera( );

            if ( videoSource == null )
            {
                try
                {
                    videoSource = new XimeaVideoSource( deviceCombo.SelectedIndex );
                    
                    // start the camera
                    videoSource.Start( );

                    // get some parameters
                    nameBox.Text = videoSource.GetParamString( CameraParameter.DeviceName );
                    snBox.Text   = videoSource.GetParamString( CameraParameter.DeviceSerialNumber );
                    typeBox.Text = videoSource.GetParamString( CameraParameter.DeviceType);

                    // width
                    widthUpDown.Minimum = videoSource.GetParamInt( CameraParameter.WidthMin );
                    widthUpDown.Maximum = videoSource.GetParamInt( CameraParameter.WidthMax );
                    widthUpDown.Value = videoSource.GetParamInt( CameraParameter.WidthMax );

                    // height
                    heightUpDown.Minimum = videoSource.GetParamInt( CameraParameter.HeightMin );
                    heightUpDown.Maximum = videoSource.GetParamInt( CameraParameter.HeightMax );
                    heightUpDown.Value = videoSource.GetParamInt( CameraParameter.HeightMax );

                    // exposure
                    exposureUpDown.Minimum = videoSource.GetParamInt( CameraParameter.ExposureMin ) / 1000;
                    exposureUpDown.Maximum = videoSource.GetParamInt( CameraParameter.ExposureMax ) / 1000;
                    exposureUpDown.Value = 0;
                    exposureUpDown.Value = 10;

                    // gain
                    gainUpDown.Minimum = new Decimal( videoSource.GetParamFloat( CameraParameter.GainMin ) );
                    gainUpDown.Maximum = new Decimal( videoSource.GetParamFloat( CameraParameter.GainMax ) );
                    gainUpDown.Value = new Decimal( videoSource.GetParamFloat( CameraParameter.Gain ) );
                    
                    videoSourcePlayer.VideoSource = videoSource;

                    EnableConnectionControls( false );

                    // reset stop watch
                    stopWatch = null;

                    // start timer
                    timer.Start( );
                }
                catch ( Exception ex )
                {
                    MessageBox.Show( "Failed openning XIMEA camera:\n\n" + ex.Message, "Error",
                        MessageBoxButtons.OK, MessageBoxIcon.Error );
                    CloseCamera( );
                }
            }

            this.Cursor = Cursors.Default;
        }
Example #4
0
        // Close currently open camera if any
        private void CloseCamera( )
        {
            timer.Stop( );

            if ( videoSource != null )
            {
                videoSourcePlayer.VideoSource = null;

                videoSource.SignalToStop( );
                videoSource.WaitForStop( );
                videoSource = null;
            }
        }
Example #5
0
        public void Disable(bool stopSource = true)
        {
            if (_disabling)
                return;

            if (InvokeRequired)
            {
                Invoke(new Delegates.DisableDelegate(Disable), stopSource);
                return;
            }

            lock (_lockobject)
            {
                if (!IsEnabled)
                    return;
                IsEnabled = false;
            }

            _disabling = true;
            IsReconnect = false;

            try
            {
                RecordSwitch(false);

                if (VolumeControl != null && VolumeControl.IsEnabled)
                    VolumeControl.Disable();

                    if (MainForm.InstanceReference.TalkCamera == this)
                        MainForm.InstanceReference.TalkTo(this, false);

                Application.DoEvents();

                if (SavingTimeLapse)
                {
                    CloseTimeLapseWriter();
                }

                StopSaving();
                if (Camera != null)
                {

                    Calibrating = false;

                    Camera.NewFrame -= CameraNewFrame;
                    Camera.Alarm -= CameraAlarm;
                    Camera.PlayingFinished -= VideoDeviceVideoFinished;
                    Camera.ErrorHandler -= CameraWindow_ErrorHandler;

                    if (Camera != null && Camera.VideoSource != null)
                    {

                        if (Camera.Plugin != null)
                        {
                            //wait for plugin to exit
                            int i = 0;
                            while (Camera.PluginRunning && i < 10)
                            {
                                Thread.Sleep(100);
                                i++;
                            }
                        }

                        var source = Camera.VideoSource as KinectStream;
                        if (source != null)
                        {
                            source.TripWire -= CameraAlarm;
                        }

                        var source1 = Camera.VideoSource as KinectNetworkStream;
                        if (source1 != null)
                        {
                            //remove the alert handler from the source stream
                            source1.AlertHandler -= CameraWindow_AlertHandler;
                        }

                        var audiostream = Camera.VideoSource as ISupportsAudio;
                        if (audiostream != null)
                        {
                            audiostream.HasAudioStream -= VideoSourceHasAudioStream;
                        }

                        if (!IsClone)
                        {
                            Application.DoEvents();

                            if (stopSource)
                            {
                                lock (_lockobject)
                                {
                                    try
                                    {
                                        Camera.SignalToStop();
                                        if (Camera.VideoSource is VideoCaptureDevice && !ShuttingDown)
                                        {
                                            Camera.VideoSource.WaitForStop();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        if (ErrorHandler != null)
                                            ErrorHandler(ex.Message);
                                    }
                                }
                            }

                            if (Camera.VideoSource is XimeaVideoSource)
                            {
                                XimeaSource = null;
                            }
                        }
                    }

                    var vl = VolumeControl;
                    if (vl != null && vl.AudioSource != null && vl.IsEnabled)
                    {
                        if ((Camera != null && vl.AudioSource == Camera.VideoSource) || vl.IsClone)
                        {
                            vl.AudioSource.LevelChanged -= vl.AudioDeviceLevelChanged;
                            vl.AudioSource.DataAvailable -= vl.AudioDeviceDataAvailable;
                            vl.AudioSource.AudioFinished -= vl.AudioDeviceAudioFinished;
                        }
                    }

                    LastFrame = null;
                    Camera = null; //setter calls dispose
                }
                BackgroundColor = MainForm.BackgroundColor;
                Camobject.settings.active = false;
                InactiveRecord = 0;
                _timeLapseTotal = _timeLapseFrameCount = 0;
                ForcedRecording = false;

                MovementDetected = false;
                Alerted = false;
                FlashCounter = DateTime.MinValue;
                ReconnectCount = 0;
                PTZNavigate = false;
                UpdateFloorplans(false);
                MainForm.NeedsSync = true;
                _errorTime = _reconnectTime = DateTime.MinValue;
                _autoofftimer = 0;

                ClearBuffer();

                if (!ShuttingDown)
                    _requestRefresh = true;

                LastFrame = null;

                if (CameraDisabled != null)
                    CameraDisabled(this, EventArgs.Empty);

                //GC.Collect();
            }
            catch (Exception ex)
            {
                if (ErrorHandler != null)
                    ErrorHandler(ex.Message);
            }
            _disabling = false;
        }
Example #6
0
        public void Enable()
        {
            if (_enabling)
                return;

            if (InvokeRequired)
            {
                Invoke(new Delegates.EnableDelegate(Enable));
                return;
            }

            lock (_lockobject)
            {
                if (IsEnabled)
                    return;
                IsEnabled = true;
            }
            _enabling = true;

            try
            {
            IsReconnect = false;
            Seekable = false;
            IsClone = Camobject.settings.sourceindex == 10;
            VideoSourceErrorState = false;
            VideoSourceErrorMessage = "";

            string ckies, hdrs;
            switch (Camobject.settings.sourceindex)
            {
                case 0:
                    ckies = Camobject.settings.cookies ?? "";
                    ckies = ckies.Replace("[USERNAME]", Camobject.settings.login);
                    ckies = ckies.Replace("[PASSWORD]", Camobject.settings.password);
                    ckies = ckies.Replace("[CHANNEL]", Camobject.settings.ptzchannel);

                    hdrs = Camobject.settings.headers ?? "";
                    hdrs = hdrs.Replace("[USERNAME]", Camobject.settings.login);
                    hdrs = hdrs.Replace("[PASSWORD]", Camobject.settings.password);
                    hdrs = hdrs.Replace("[CHANNEL]", Camobject.settings.ptzchannel);

                    var jpegSource = new JPEGStream2(Camobject.settings.videosourcestring)
                                        {
                                            Login = Camobject.settings.login,
                                            Password = Camobject.settings.password,
                                            ForceBasicAuthentication = Camobject.settings.forcebasic,
                                            RequestTimeout = Camobject.settings.timeout,
                                            UseHTTP10 = Camobject.settings.usehttp10,
                                            HttpUserAgent = Camobject.settings.useragent,
                                            Cookies = ckies,
                                            Headers = hdrs
                                        };

                    OpenVideoSource(jpegSource, true);

                    if (Camobject.settings.frameinterval != 0)
                        jpegSource.FrameInterval = Camobject.settings.frameinterval;

                    break;
                case 1:
                    ckies = Camobject.settings.cookies ?? "";
                    ckies = ckies.Replace("[USERNAME]", Camobject.settings.login);
                    ckies = ckies.Replace("[PASSWORD]", Camobject.settings.password);
                    ckies = ckies.Replace("[CHANNEL]", Camobject.settings.ptzchannel);

                    hdrs = Camobject.settings.headers ?? "";
                    hdrs = hdrs.Replace("[USERNAME]", Camobject.settings.login);
                    hdrs = hdrs.Replace("[PASSWORD]", Camobject.settings.password);
                    hdrs = hdrs.Replace("[CHANNEL]", Camobject.settings.ptzchannel);

                    var mjpegSource = new MJPEGStream2(Camobject.settings.videosourcestring)
                                        {
                                            Login = Camobject.settings.login,
                                            Password = Camobject.settings.password,
                                            ForceBasicAuthentication = Camobject.settings.forcebasic,
                                            RequestTimeout = Camobject.settings.timeout,
                                            HttpUserAgent = Camobject.settings.useragent,
                                            DecodeKey = Camobject.decodekey,
                                            Cookies = ckies,
                                            Headers = hdrs
                                        };
                    OpenVideoSource(mjpegSource, true);
                    break;
                case 2:
                    string url = Camobject.settings.videosourcestring;
                    var ffmpegSource = new FFMPEGStream(url)
                                        {
                                            Cookies = Camobject.settings.cookies,
                                            AnalyzeDuration = Camobject.settings.analyseduration,
                                            Timeout = Camobject.settings.timeout,
                                            UserAgent = Camobject.settings.useragent,
                                            Headers = Camobject.settings.headers,
                                            RTSPMode = Camobject.settings.rtspmode
                                        };
                    OpenVideoSource(ffmpegSource, true);
                    break;
                case 3:
                    string moniker = Camobject.settings.videosourcestring;

                    var videoSource = new VideoCaptureDevice(moniker);
                    string[] wh = Camobject.resolution.Split('x');
                    var sz = new Size(Convert.ToInt32(wh[0]), Convert.ToInt32(wh[1]));

                    string precfg = Nv("video");
                    bool found = false;

                    if (Nv("capturemode") != "snapshots")
                    {
                        VideoCapabilities[] videoCapabilities = videoSource.VideoCapabilities;
                        videoSource.ProvideSnapshots = false;
                        foreach (VideoCapabilities capabilty in videoCapabilities)
                        {

                            string item = string.Format(VideoSource.VideoFormatString, capabilty.FrameSize.Width,
                                Math.Abs(capabilty.FrameSize.Height), capabilty.AverageFrameRate, capabilty.BitCount);
                            if (precfg == item)
                            {
                                videoSource.VideoResolution = capabilty;
                                found = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        precfg = Nv("snapshots");
                        videoSource.ProvideSnapshots = true;
                        VideoCapabilities[] videoCapabilities = videoSource.SnapshotCapabilities;
                        foreach (VideoCapabilities capabilty in videoCapabilities)
                        {

                            string item = string.Format(VideoSource.SnapshotFormatString, capabilty.FrameSize.Width,
                                Math.Abs(capabilty.FrameSize.Height), capabilty.AverageFrameRate, capabilty.BitCount);
                            if (precfg == item)
                            {
                                videoSource.VideoResolution = capabilty;
                                found = true;
                                break;
                            }
                        }
                    }
                    if (!found)
                    {
                        var vc = videoSource.VideoCapabilities.Where(p => p.FrameSize == sz).ToList();
                        if (vc.Count > 0)
                        {
                            var vc2 = vc.FirstOrDefault(p => p.AverageFrameRate == Camobject.settings.framerate) ??
                                        vc.FirstOrDefault();
                            videoSource.VideoResolution = vc2;
                            found = true;
                        }
                        if (!found)
                        {
                            //first available
                            var vcf = videoSource.VideoCapabilities.FirstOrDefault();
                            if (vcf != null)
                                videoSource.VideoResolution = vcf;
                            //else
                            //{
                            //    dont do this, not having an entry is ok for some video providers
                            //    throw new Exception("Unable to find a video format for the capture device");
                            //}
                        }
                    }

                    if (Camobject.settings.crossbarindex != -1 && videoSource.CheckIfCrossbarAvailable())
                    {
                        var cbi =
                            videoSource.AvailableCrossbarVideoInputs.FirstOrDefault(
                                p => p.Index == Camobject.settings.crossbarindex);
                        if (cbi != null)
                        {
                            videoSource.CrossbarVideoInput = cbi;
                        }
                    }

                    OpenVideoSource(videoSource, true);

                    break;
                case 4:
                    Rectangle area = Rectangle.Empty;
                    if (!String.IsNullOrEmpty(Camobject.settings.desktoparea))
                    {
                        var i = System.Array.ConvertAll(Camobject.settings.desktoparea.Split(','), int.Parse);
                        area = new Rectangle(i[0], i[1], i[2], i[3]);
                    }
                    var desktopSource = new DesktopStream(Convert.ToInt32(Camobject.settings.videosourcestring),
                        area) {MousePointer = Camobject.settings.desktopmouse};
                    if (Camobject.settings.frameinterval != 0)
                        desktopSource.FrameInterval = Camobject.settings.frameinterval;
                    OpenVideoSource(desktopSource, true);

                    break;
                case 5:
                    List<String> inargs = Camobject.settings.vlcargs.Split(Environment.NewLine.ToCharArray(),
                        StringSplitOptions.RemoveEmptyEntries)
                        .
                        ToList();
                    var vlcSource = new VlcStream(Camobject.settings.videosourcestring, inargs.ToArray())
                                    {
                                        TimeOut
                                            =
                                            Camobject
                                            .settings
                                            .timeout
                                    };

                    OpenVideoSource(vlcSource, true);
                    break;
                case 6:
                    if (XimeaSource == null || !XimeaSource.IsRunning)
                        XimeaSource =
                            new XimeaVideoSource(Convert.ToInt32(Nv(Camobject.settings.namevaluesettings, "device")));
                    OpenVideoSource(XimeaSource, true);
                    break;
                case 7:
                    var tw = false;
                    try
                    {
                        if (!String.IsNullOrEmpty(Nv(Camobject.settings.namevaluesettings, "TripWires")))
                            tw = Convert.ToBoolean(Nv(Camobject.settings.namevaluesettings, "TripWires"));
                        var ks = new KinectStream(Nv(Camobject.settings.namevaluesettings, "UniqueKinectId"),
                            Convert.ToBoolean(Nv(Camobject.settings.namevaluesettings, "KinectSkeleton")), tw);
                        if (Nv(Camobject.settings.namevaluesettings, "StreamMode") != "")
                            ks.StreamMode = Convert.ToInt32(Nv(Camobject.settings.namevaluesettings, "StreamMode"));
                        OpenVideoSource(ks, true);
                    }
                    catch (Exception ex)
                    {
                        if (ErrorHandler != null)
                            ErrorHandler(ex.Message);
                    }
                    break;
                case 8:
                    switch (Nv(Camobject.settings.namevaluesettings, "custom"))
                    {
                        case "Network Kinect":
                            // open the network kinect video stream
                            OpenVideoSource(new KinectNetworkStream(Camobject.settings.videosourcestring), true);
                            break;
                        default:
                            lock (_lockobject)
                            {
                                IsEnabled = false;
                            }
                            throw new Exception("No custom provider found for " +
                                                Nv(Camobject.settings.namevaluesettings, "custom"));
                    }
                    break;
                case 9:
                    //there is no 9, spooky hey?
                    break;
                case 10:
                    int icam;
                    if (Int32.TryParse(Camobject.settings.videosourcestring, out icam))
                    {
                        var cw = MainForm.InstanceReference.GetCameraWindow(icam);
                        if (cw != null)
                        {
                            OpenVideoSource(cw);
                        }

                    }
                    break;
            }

            if (Camera != null)
            {
                IMotionDetector motionDetector = null;
                IMotionProcessing motionProcessor = null;

                switch (Camobject.detector.type)
                {
                    default:
                        motionDetector = new TwoFramesDifferenceDetector(Camobject.settings.suppressnoise);
                        break;
                    case "Custom Frame":
                        motionDetector = new CustomFrameDifferenceDetector(Camobject.settings.suppressnoise,
                            Camobject.detector.keepobjectedges);
                        break;
                    case "Background Modeling":
                        motionDetector = new SimpleBackgroundModelingDetector(Camobject.settings.suppressnoise,
                            Camobject.detector.keepobjectedges);
                        break;
                    case "Two Frames (Color)":
                        motionDetector = new TwoFramesColorDifferenceDetector(Camobject.settings.suppressnoise);
                        break;
                    case "Custom Frame (Color)":
                        motionDetector = new CustomFrameColorDifferenceDetector(
                            Camobject.settings.suppressnoise,
                            Camobject.detector.keepobjectedges);
                        break;
                    case "Background Modeling (Color)":
                        motionDetector =
                            new SimpleColorBackgroundModelingDetector(Camobject.settings.suppressnoise,
                                Camobject.detector.
                                    keepobjectedges);
                        break;
                    case "None":
                        break;
                }

                if (motionDetector != null)
                {
                    switch (Camobject.detector.postprocessor)
                    {
                        case "Grid Processing":
                            motionProcessor = new GridMotionAreaProcessing
                                                {
                                                    HighlightColor =
                                                        ColorTranslator.FromHtml(Camobject.detector.color),
                                                    HighlightMotionGrid = Camobject.detector.highlight
                                                };
                            break;
                        case "Object Tracking":
                            motionProcessor = new BlobCountingObjectsProcessing
                                                {
                                                    HighlightColor =
                                                        ColorTranslator.FromHtml(Camobject.detector.color),
                                                    HighlightMotionRegions = Camobject.detector.highlight,
                                                    MinObjectsHeight = Camobject.detector.minheight,
                                                    MinObjectsWidth = Camobject.detector.minwidth
                                                };

                            break;
                        case "Border Highlighting":
                            motionProcessor = new MotionBorderHighlighting
                                                {
                                                    HighlightColor =
                                                        ColorTranslator.FromHtml(Camobject.detector.color)
                                                };
                            break;
                        case "Area Highlighting":
                            motionProcessor = new MotionAreaHighlighting
                                                {
                                                    HighlightColor =
                                                        ColorTranslator.FromHtml(Camobject.detector.color)
                                                };
                            break;
                        case "None":
                            break;
                    }

                    if (Camera.MotionDetector != null)
                    {
                        Camera.MotionDetector.Reset();
                        Camera.MotionDetector = null;
                    }

                    Camera.MotionDetector = motionProcessor == null
                        ? new MotionDetector(motionDetector)
                        : new MotionDetector(motionDetector, motionProcessor);

                    Camera.AlarmLevel = Helper.CalculateTrigger(Camobject.detector.minsensitivity);
                    Camera.AlarmLevelMax = Helper.CalculateTrigger(Camobject.detector.maxsensitivity);
                    NeedMotionZones = true;
                }
                else
                {
                    Camera.MotionDetector = null;
                }

                LastMovementDetected = Helper.Now;

                ClearBuffer();

                if (!Camera.IsRunning)
                {
                    Calibrating = true;
                    _lastRun = Helper.Now.Ticks;
                    Camera.Start();
                }
                if (Camera.VideoSource is XimeaVideoSource)
                {
                    //need to set these after the camera starts
                    try
                    {
                        XimeaSource.SetParam(PRM.IMAGE_DATA_FORMAT, IMG_FORMAT.RGB24);
                    }
                    catch (ApplicationException)
                    {
                        XimeaSource.SetParam(PRM.IMAGE_DATA_FORMAT, IMG_FORMAT.MONO8);
                    }
                    XimeaSource.SetParam(CameraParameter.OffsetX,
                        Convert.ToInt32(Nv(Camobject.settings.namevaluesettings, "x")));
                    XimeaSource.SetParam(CameraParameter.OffsetY,
                        Convert.ToInt32(Nv(Camobject.settings.namevaluesettings, "y")));
                    float gain;
                    float.TryParse(Nv(Camobject.settings.namevaluesettings, "gain"), out gain);
                    XimeaSource.SetParam(CameraParameter.Gain, gain);
                    float exp;
                    float.TryParse(Nv(Camobject.settings.namevaluesettings, "exposure"), out exp);
                    XimeaSource.SetParam(CameraParameter.Exposure, exp*1000);
                    XimeaSource.SetParam(CameraParameter.Downsampling,
                        Convert.ToInt32(Nv(Camobject.settings.namevaluesettings, "downsampling")));
                    XimeaSource.SetParam(CameraParameter.Width,
                        Convert.ToInt32(Nv(Camobject.settings.namevaluesettings, "width")));
                    XimeaSource.SetParam(CameraParameter.Height,
                        Convert.ToInt32(Nv(Camobject.settings.namevaluesettings, "height")));
                    XimeaSource.FrameInterval =
                        (int) (1000.0f/XimeaSource.GetParamFloat(CameraParameter.FramerateMax));
                }

                if (File.Exists(Camobject.settings.maskimage))
                {
                    Camera.Mask = (Bitmap) Image.FromFile(Camobject.settings.maskimage);
                }

            }

            Camobject.settings.active = true;
            UpdateFloorplans(false);

            _timeLapseTotal = _timeLapseFrameCount = 0;
            InactiveRecord = 0;
            MovementDetected = false;

            Alerted = false;
            PTZNavigate = false;
            Camobject.ftp.ready = true;
            _lastRun = Helper.Now.Ticks;
            MainForm.NeedsSync = true;
            ReconnectCount = 0;
            _dtPTZLastCheck = DateTime.Now;

            _firstFrame = true;
            _autoofftimer = 0;

            if (Camera != null)
            {
                Camera.ZFactor = 1;
            }
            _requestRefresh = true;

            SetVolumeLevel(Camobject.settings.micpair);
            if (VolumeControl != null)
            {
                VolumeControl.Micobject.settings.buffer = Camobject.recorder.bufferseconds;
                VolumeControl.Enable();
            }

            SetVideoSize();

            //cloned initialisation goes here
            if (CameraEnabled != null)
                CameraEnabled(this, EventArgs.Empty);
            }
            catch (Exception ex)
            {
                if (ErrorHandler != null)
                    ErrorHandler(ex.Message);
            }
            _enabling = false;
        }