Exemple #1
0
        // Compares objects of the type
        public int CompareTo(object obj)
        {
            if (obj == null)
            {
                return(1);
            }

            VsImage p = (VsImage)obj;

            return(this.tStamp.CompareTo(p.tStamp));
        }
Exemple #2
0
		// Process new frame
        public override void process_Frame1(VsImage lastFrame)
        {
            try
            {
                if (cvAlgo == null)
                {
                    width = lastFrame.Image.Width;
                    height = lastFrame.Image.Height;
                    cvAlgo = new VsCvFqiDetection(1, 1, width, height, cvDepth.Depth8U, 3);
                    cvAlgo.VsInit();
                    return;
                }

                cvAlgo.VsConfiguration(int.Parse(AnalyzerConfiguration["Threshold"].ToString()));
                lastFrame.Image = cvAlgo.VsProcess(lastFrame.Image);
                lastFrame.Result = cvAlgo.VsResult();
                lastFrame.IsAnalyzed = true;
                lastFrame.IsDetected = true;
            }
            catch { }
    	}
Exemple #3
0
        // methodes
        public VsImage Clone()
        {
            VsImage vsImg = new VsImage();

            try
            {
                vsImg.Image = (Bitmap)bImage.Clone();
                if (aImage != null)
                {
                    vsImg.AnalyzedImage = (Bitmap)aImage.Clone();
                }
                vsImg.TimeStamp  = TimeStamp;
                vsImg.IsDetected = IsDetected;
                vsImg.IsAnalyzed = IsAnalyzed;
                vsImg.Result     = Result;
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);
            }

            return(vsImg);
        }
Exemple #4
0
 public virtual void process_Frame1(VsImage lastFrame1)
 {
 }
Exemple #5
0
 public override void process_Frame(VsImage lastFrame)
 {
     try
     {
         if (lastFrame.IsDetected)
         {
             StartRecord();
             DoRecord(lastFrame);
         }
         else
         {
             StopRecord();
         }
     }
     catch (Exception err)
     {
         logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);
     }
 }
Exemple #6
0
        // ---------------------------------------------------------------
        // Process new frame
        public override void process_Frame(VsImage lastFrame)
        {
            Monitor.Enter(lockEncoder);

            try
            {
                if (lastFrame.IsDetected)
                {
                    width = lastFrame.Image.Width;
                    height = lastFrame.Image.Height;
                    StartRecord();
                    DoRecord(lastFrame);
                }
                else
                {
                    StopRecord(true);
                }
            }
            finally
            {
                Monitor.Exit(lockEncoder);
            }
        }
Exemple #7
0
        // Process new frame
        public override void process_Frame1(VsImage lastFrame)
        {
            try
            {
                // frame sampling for background estimation
                // ----------------------------------------------------------------
                counter++; if (counter > 65000) counter = 0;
                if (threshold2 > 0 && counter % threshold2 != 0)
                {
                    lastFrame.Result = "";
                    lastFrame.IsAnalyzed = true;
                    lastFrame.IsDetected = bLastDetected;
                    return;
                }

                // image scaling
                using (Graphics gp = Graphics.FromImage(curImage)) gp.DrawImage(lastFrame.Image, 0, 0, width, height);

                // first frame checking for memory allocation
                // ----------------------------------------------------------------
                if (bkgFrame == null)
                {
                    threshold1 = double.Parse(AnalyzerConfiguration["ThresholdAlpha"].ToString()) / 100.0;
                    if (threshold1 < 0.1) threshold1 = 0.005;
                    threshold2 = double.Parse(AnalyzerConfiguration["ThresholdSigma"].ToString());
                    if (threshold2 < 0) threshold2 = 1;

                    // alloc memory for a backgound image and for current image
                    bkgFrame = new byte[len];
                    curFrame = new byte[len];
                    dilatatedFrame = new byte[len];

                    // lock image
                    BitmapData imgData = curImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                    // create initial backgroung image
                    preprocess_Frame(imgData, width, height, bkgFrame);

                    // unlock the image
                    curImage.UnlockBits(imgData);
                }

                // background estimation
                // ----------------------------------------------------------------
                // lock image
                BitmapData dataImage = curImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                // preprocess input image
                preprocess_Frame(dataImage, width, height, curFrame);

                // unlock the image
                curImage.UnlockBits(dataImage);

                // update background by running average
                float alpha = 0.30F;
                for (int i = 0; i < len; i++) bkgFrame[i] = (byte)(alpha * curFrame[i] + (1 - alpha) * bkgFrame[i]);

                // motion detection
                // ----------------------------------------------------------------
                // by difference and thresholding
                for (int i = 0; i < len; i++)
                {
                    int t = curFrame[i] - bkgFrame[i];
                    if (t < 0) t = -t;

                    if (t >= 5) curFrame[i] = (byte)255;
                    else curFrame[i] = (byte)0;
                }

                // erosion analogue
                // it can be skipped
                blockChanged = 0;
                for (int i = 1; i < fH - 1; i++)
                {
                    for (int j = 1; j < fW - 1; j++)
                    {
                        int k = i * fW + j;
                        if (curFrame[k] == 255)
                        {
                            if ((curFrame[i * fW + (j + 1)] == 255) ||
                                (curFrame[i * fW + (j - 1)] == 255) ||
                                (curFrame[(i - 1) * fW + j] == 255) ||
                                (curFrame[(i + 1) * fW + j] == 255))
                            {
                                blockChanged += (block * block);
                                curFrame[k] = (byte)255;
                            }
                            else curFrame[k] = (byte)0;
                        }
                    }
                }

                // postprocess the input image
                // lock image
                /*
                lastFrame.AnalyzedImage = (Bitmap)curImage.Clone();
                BitmapData adata = lastFrame.AnalyzedImage.LockBits(
                    new Rectangle(0, 0, width, height),
                    ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                 * 
                postprocess_Frame(adata, width, height, curFrame);

                lastFrame.AnalyzedImage.UnlockBits(adata);
                */

                // set motion index
                // ----------------------------------------------------------------
                lastFrame.Result = ""; lastFrame.IsAnalyzed = true;

                double ch = (double)blockChanged / (width * height);
                if (ch > threshold1 && ch < 0.8)
                {
                    lastFrame.IsDetected = true;
                    bLastDetected = true;
                }
                else
                {
                    lastFrame.IsDetected = false;
                    bLastDetected = false;
                }
            }
            catch { }
        }
Exemple #8
0
        private void framedOut(object sender, VsImageEventArgs e)
        {

            //if (BQueue != null)
            //{
            img = (VsImage)e.Image.Clone();
            //Monitor.PulseAll(this);
            //    BQueue.Enqueue(img);
            //}

            //  bmp = img.Image;

            //MessageBox.Show("grameout");
            //((MultimodeVideoSource)coreProvider).FrameOut -= new VsImageEventHandler(framedOut);
            //  coreProvider.Stop();
        }
Exemple #9
0
 // Constructor
 public VsImageEventArgs(VsImage vsImg)
 {
     vsImage = vsImg;
 }
Exemple #10
0
		// Thread entry point
		public void WorkerThread()
		{
            byte[] buffer = new byte[bufSize];	// buffer to read stream

            while (true)
            {
                // reset reload event
                reloadEvent.Reset();

                HttpWebRequest req = null;
                WebResponse resp = null;
                Stream stream = null;
                byte[] delimiter = null;
                byte[] delimiter2 = null;
                byte[] boundary = null;
                int boundaryLen, delimiterLen = 0, delimiter2Len = 0;
                int read, todo = 0, total = 0, pos = 0, align = 1;
                int start = 0, stop = 0;

                // align
                //  1 = searching for image start
                //  2 = searching for image end
                try
                {
                    // create request
                    req = (HttpWebRequest)WebRequest.Create(source);
                    // set login and password
                    if ((login != null) && (password != null) && (login != ""))
                        req.Credentials = new NetworkCredential(login, password);
                    // set connection group name
                    if (useSeparateConnectionGroup)
                        req.ConnectionGroupName = GetHashCode().ToString();
                    // get response
                    resp = req.GetResponse();

                    // check content type
                    string ct = resp.ContentType;
                    if (ct.IndexOf("multipart/x-mixed-replace") == -1)
                        throw new ApplicationException("Invalid URL");

                    // get boundary
                    ASCIIEncoding encoding = new ASCIIEncoding();
                    boundary = encoding.GetBytes(ct.Substring(ct.IndexOf("boundary=", 0) + 9));
                    boundaryLen = boundary.Length;

                    // get response stream
                    stream = resp.GetResponseStream();

                    // loop
                    while ((!stopEvent.WaitOne(0, true)) && (!reloadEvent.WaitOne(0, true)))
                    {
                        // check total read
                        if (total > bufSize - readSize)
                        {
                            total = pos = todo = 0;
                        }

                        // read next portion from stream
                        if ((read = stream.Read(buffer, total, readSize)) == 0)
                            throw new ApplicationException();

                        total += read;
                        todo += read;

                        // increment received bytes counter
                        bytesReceived += read;

                        // does we know the delimiter ?
                        if (delimiter == null)
                        {
                            // find boundary
                            pos = ByteArrayUtils.Find(buffer, boundary, pos, todo);

                            if (pos == -1)
                            {
                                // was not found
                                todo = boundaryLen - 1;
                                pos = total - todo;
                                continue;
                            }

                            todo = total - pos;

                            if (todo < 2)
                                continue;

                            // check new line delimiter type
                            if (buffer[pos + boundaryLen] == 10)
                            {
                                delimiterLen = 2;
                                delimiter = new byte[2] { 10, 10 };
                                delimiter2Len = 1;
                                delimiter2 = new byte[1] { 10 };
                            }
                            else
                            {
                                delimiterLen = 4;
                                delimiter = new byte[4] { 13, 10, 13, 10 };
                                delimiter2Len = 2;
                                delimiter2 = new byte[2] { 13, 10 };
                            }

                            pos += boundaryLen + delimiter2Len;
                            todo = total - pos;
                        }

                        // search for image
                        if (align == 1)
                        {
                            start = ByteArrayUtils.Find(buffer, delimiter, pos, todo);
                            if (start != -1)
                            {
                                // found delimiter
                                start += delimiterLen;
                                pos = start;
                                todo = total - pos;
                                align = 2;
                            }
                            else
                            {
                                // delimiter not found
                                todo = delimiterLen - 1;
                                pos = total - todo;
                            }
                        }

                        // search for image end
                        while ((align == 2) && (todo >= boundaryLen))
                        {
                            stop = ByteArrayUtils.Find(buffer, boundary, pos, todo);
                            if (stop != -1)
                            {
                                pos = stop;
                                todo = total - pos;

                                // increment frames counter
                                framesReceived++;

                                // image at stop
                                if (FrameOut != null)
                                {
                                    Bitmap bmp = (Bitmap)Bitmap.FromStream(new MemoryStream(buffer, start, stop - start));
                                    VsImage img = new VsImage(bmp);
                                    
                                    // notify client
                                    FrameOut(this, new VsImageEventArgs(img));
                                    // release the image
                                    img.Dispose();
                                    img = null;
                                }

                                // shift array
                                pos = stop + boundaryLen;
                                todo = total - pos;
                                Array.Copy(buffer, pos, buffer, 0, todo);

                                total = todo;
                                pos = 0;
                                align = 1;
                            }
                            else
                            {
                                // delimiter not found
                                todo = boundaryLen - 1;
                                pos = total - todo;
                            }
                        }
                    }
                }
                catch (WebException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // wait for a while before the next try
                    Thread.Sleep(250);
                }
                catch (ApplicationException ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                    // wait for a while before the next try
                    Thread.Sleep(250);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
                }
                finally
                {
                    // abort request
                    if (req != null)
                    {
                        req.Abort();
                        req = null;
                    }
                    // close response stream
                    if (stream != null)
                    {
                        stream.Close();
                        stream = null;
                    }
                    // close response
                    if (resp != null)
                    {
                        resp.Close();
                        resp = null;
                    }
                }

                // need to stop ?
                if (stopEvent.WaitOne(0, true))
                    break;
            }
        }
Exemple #11
0
		// new frame
		protected void OnNewFrame(Bitmap image)
		{
			framesReceived++;
            if (FrameOut != null)
            {
                VsImage img = new VsImage(image);

                FrameOut(this, new VsImageEventArgs(img));

                img.Dispose();
                img = null;
            }
		}
Exemple #12
0
        public override void DoRecord(VsImage lastFrame)
        {
            if (vsEncoder == null) return;

            try
            {
                // record frame
                vsEncoder.DoRecord(lastFrame.Image);
            }
            catch (Exception err)
            {
                // error log
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);

                // if error stop record
                StopRecord();
            }
        }
Exemple #13
0
 public virtual void process_Frame5(VsImage lastFrame1, VsImage lastFrame2, VsImage lastFrame3, VsImage lastFrame4, VsImage lastFrame5)
 {
 }
Exemple #14
0
 public virtual void process_Frame3(VsImage lastFrame1, VsImage lastFrame2, VsImage lastFrame3)
 {
 }
Exemple #15
0
        private void FrameReceived(object sender, RtpStream.FrameReceivedEventArgs ea)
        {
            try
            {    
                if (firstFrame)
                {
                    Bitmap DrawImage = new Bitmap(video_width, video_height);

                    EncoderParameter epQuality = new EncoderParameter(Encoder.Quality, video_quality);
                    // Store the quality parameter in the list of encoder parameters
                    EncoderParameters epParameters = new EncoderParameters(1);
                    epParameters.Param[0] = epQuality;

                    MemoryStream ms = new MemoryStream();
                    DrawImage.Save(ms, GetImageCodecInfo(ImageFormat.Jpeg), epParameters);

                    Array.Copy(ms.GetBuffer(), 0, JpegHeader, 0, offset);
                    firstFrame = false;
                }

                byte[] data = new byte[ea.Frame.Buffer.Length + offset];
                Array.Copy(JpegHeader, data, JpegHeader.Length);
                Array.Copy(ea.Frame.Buffer, 0, data, offset, ea.Frame.Buffer.Length);
                System.IO.MemoryStream msImage = new MemoryStream(data);

                VsImage img = new VsImage((Bitmap)Image.FromStream(msImage));
                int index =  GetIndex(ea.RtpStream.IPAddress);

                if (index!= -1 && vsRtpStream[index] != null && vsRtpStream[index].FrameOut != null)
                {
                    vsRtpStream[index].FrameOut(this, new VsImageEventArgs(img));
                }
                img.Dispose();
                img = null;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemple #16
0
 // Process new frame
 public override void process_Frame1(VsImage lastFrame)
 {
     lastFrame.Result = "";
     lastFrame.IsAnalyzed = true;
     lastFrame.IsDetected = true;
 }
        // Process new frame
        public override void process_Frame1(VsImage lastFrame)
        {
            try
            {
                counter++; if (counter > 65000) counter = 0;
                if (threshold2 > 0 && counter % threshold2 != 0)
                {
                    lastFrame.Result = "";
                    lastFrame.IsAnalyzed = true;
                    lastFrame.IsDetected = bLastDetected;
                    return;
                }

                width = lastFrame.Image.Width;
                height = lastFrame.Image.Height;

                int fW = (((width - 1) / block) + 1);
                int fH = (((height - 1) / block) + 1);
                int len = fW * fH;

                if (bkgFrame == null)
                {
                    threshold1 = double.Parse(AnalyzerConfiguration["ThresholdAlpha"].ToString()) / 100.0;
                    threshold2 = double.Parse(AnalyzerConfiguration["ThresholdSigma"].ToString());

                    // alloc memory for a backgound image and for current image
                    bkgFrame = new byte[len];
                    curFrame = new byte[len];
                    dilatatedFrame = new byte[len];

                    // lock image
                    BitmapData imgData = lastFrame.Image.LockBits(
                        new Rectangle(0, 0, width, height),
                        ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                    // create initial backgroung image
                    preprocess_Frame(imgData, width, height, bkgFrame);

                    // unlock the image
                    lastFrame.Image.UnlockBits(imgData);
                }

                // lock image
                BitmapData data = lastFrame.Image.LockBits(
                    new Rectangle(0, 0, width, height),
                    ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);

                // preprocess input image
                preprocess_Frame(data, width, height, curFrame);

                float alpha = 0.30F;
                for (int i = 0; i < len; i++)
                {
                    bkgFrame[i] = (byte)(alpha * curFrame[i] + (1 - alpha) * bkgFrame[i]);
                }

                // difference and thresholding
                for (int i = 0; i < len; i++)
                {
                    int t = curFrame[i] - bkgFrame[i];
                    if (t < 0) t = -t;

                    if (t >= 10)
                    {
                        curFrame[i] = (byte)255;
                    }
                    else
                    {
                        curFrame[i] = (byte)0;
                    }
                }

                // erosion analogue
                // it can be skipped
                pixelsChanged = 0;
                for (int i = 1; i < fH - 1; i++)
                {
                    for (int j = 1; j < fW - 1; j++)
                    {
                        int k = i * fW + j;
                        if (curFrame[k] == 255)
                        {
                            if ((curFrame[i * fW + (j + 1)] == 255) ||
                                (curFrame[i * fW + (j - 1)] == 255) ||
                                (curFrame[(i - 1) * fW + j] == 255) ||
                                (curFrame[(i + 1) * fW + j] == 255))
                            {
                                pixelsChanged += (block * block);
                                curFrame[k] = (byte)255;
                            }
                            else curFrame[k] = (byte)0;
                        }
                    }
                }

                // unlock the image
                lastFrame.Image.UnlockBits(data);

                // postprocess the input image
                // lock image
                /*
                lastFrame.AnalyzedImage = (Bitmap)lastFrame.Image.Clone();
                BitmapData adata = lastFrame.AnalyzedImage.LockBits(
                    new Rectangle(0, 0, width, height),
                    ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
                 * 
                postprocess_Frame(adata, width, height, curFrame);

                lastFrame.AnalyzedImage.UnlockBits(adata);
                */

                lastFrame.Result = "";
                lastFrame.IsAnalyzed = true;

                if (CalPixelChange() > threshold1)
                {
                    lastFrame.IsDetected = true;
                    bLastDetected = true;
                }
                else
                {
                    lastFrame.IsDetected = false;
                    bLastDetected = false;
                }
            }
            catch { }
        }
Exemple #18
0
 public void StopProvider()
 {
     lock (this)
     {
         coreProvider.Stop();
         coreProvider.WaitForStop();
         img = null;
         provicerRuningState = false;
     }
 }
Exemple #19
0
		// new frame
		protected void OnNewFrame(Bitmap image)
		{
			framesReceived++;
            if ((!stopEvent.WaitOne(0, true)) && (FrameOut != null))
            {
                VsImage img = new VsImage(image);

                // notify client
                FrameOut(this, new VsImageEventArgs(img));
                // release the image
                img.Dispose();
                img = null;
            }
		}
Exemple #20
0
 [MethodImpl(MethodImplOptions.Synchronized)] // lock/unlock all thread from current instance object
 public virtual void process_Frame(VsImage lastFrame)
 {
     // TODO
 }
Exemple #21
0
 [MethodImpl(MethodImplOptions.Synchronized)] // lock/unlock all thread from current instance object
 public virtual void DoRecord(VsImage lastFrame)
 {
     // TODO
 }
Exemple #22
0
        // ---------------------------------------------------------------
        // add image's files to video
        public override void DoRecord(VsImage lastFrame)
        {
            if (vsEncoder != null &&  vsEncoder.Recording)
            {
                try
                {
                    // record frame
                    vsEncoder.DoRecord(lastFrame.Image);
                }
                catch (Exception err)
                {
                    // error log
                    logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace); ;

                    // stop encoder
                    StopRecord(false);
                }
            }
        }
Exemple #23
0
        private void process_NewFrame(object stateInfo)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            try
            {
                // get new one
                if (imgBuffer.Count > 0)
                {
                    lastFrame = (VsImage)imgBuffer.Dequeue();
                }

                if (lastFrame != null)
                {
                    using (Graphics gb = Graphics.FromImage(lastFrame.Image))
                    {
                        SolidBrush drawRec = new SolidBrush(Color.Black);
                        gb.FillRectangle(drawRec, 0, 0, lastFrame.Image.Width, 16);
                        //gb.DrawImage(isysLogo, 3, 3, 15, 15);

                        DateTime date = DateTime.Now;

                        // Create font and brush
                        Font drawFont = new Font("Tahoma", 10, FontStyle.Bold);
                        SolidBrush drawBrush = new SolidBrush(Color.White);

                        gb.DrawString(date.ToString(), drawFont, drawBrush, new PointF(18, 0));
                        
                        drawBrush.Dispose();
                        drawFont.Dispose();
                        drawRec.Dispose();
                    }

                    // output
                    if (FrameOut != null) FrameOut(this, new VsImageEventArgs(lastFrame));
                }
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);;
            }
            finally
            {
                if(lastFrame != null) 
                    lastFrame.Dispose();
                lastFrame = null;
            }
        }
Exemple #24
0
 // Constructor
 public VsImageEventArgs(VsImage vsImg)
 {
     vsImage = vsImg;
 }
Exemple #25
0
        // methodes
        public VsImage Clone()
        {
            VsImage vsImg = new VsImage();

            try
            {
                vsImg.Image = (Bitmap)bImage.Clone();
                if (aImage != null) vsImg.AnalyzedImage = (Bitmap)aImage.Clone();
                vsImg.TimeStamp = TimeStamp;
                vsImg.IsDetected = IsDetected;
                vsImg.IsAnalyzed = IsAnalyzed;
                vsImg.Result = Result;
            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);
            }
            
            return vsImg;
        }
Exemple #26
0
        public override void DoRecord(VsImage lastFrame)
        {
            // check if not recording
            if (!bRecord) return;
            if (vsEncoder == null) { bRecord = false; return; }

            try
            {
                // record frame
                vsEncoder.DoRecord(lastFrame.Image);
            }
            catch (Exception err)
            {
                // error log
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);

                // dispose encoder
                DisposeEncoder();
            }
        }
Exemple #27
0
		// Thread entry point
		public void WorkerThread()
		{
			byte[]			buffer = new byte[bufSize];	// buffer to read stream
			HttpWebRequest	req = null;
			WebResponse		resp = null;
			Stream			stream = null;
			Random			rnd = new Random((int) DateTime.Now.Ticks);
			DateTime		start;
			TimeSpan		span;

			while (true)
			{
				int	read, total = 0;

				try
				{
					start = DateTime.Now;

					// create request
					if (!preventCaching)
					{
						req = (HttpWebRequest) WebRequest.Create(source);
					}
					else
					{
						req = (HttpWebRequest) WebRequest.Create(source + ((source.IndexOf('?') == -1) ? '?' : '&') + "fake=" + rnd.Next().ToString());
					}
                    
					// set login and password
					if ((login != null) && (password != null) && (login != ""))
						req.Credentials = new NetworkCredential(login, password);
					// set connection group name
					if (useSeparateConnectionGroup)
						req.ConnectionGroupName = GetHashCode().ToString();
					// get response
					resp = req.GetResponse();

					// get response stream
					stream = resp.GetResponseStream();

					// loop
					while (!stopEvent.WaitOne(0, true))
					{
						// check total read
						if (total > bufSize - readSize)
						{
							total = 0;
						}

						// read next portion from stream
						if ((read = stream.Read(buffer, total, readSize)) == 0)
							break;

						total += read;

						// increment received bytes counter
						bytesReceived += read;
					}

					if (!stopEvent.WaitOne(0, true))
					{
						// increment frames counter
						framesReceived++;

						// image at stop
                        if (FrameOut != null)
						{
							Bitmap	bmp = (Bitmap) Bitmap.FromStream(new MemoryStream(buffer, 0, total));
							// notify client
                            VsImage img = new VsImage(bmp);
                            FrameOut(this, new VsImageEventArgs(img));
							// release the image
                            img.Dispose();
                            img = null;
						}
					}

					// wait for a while ?
					if (frameInterval > 0)
					{
						// times span
						span = DateTime.Now.Subtract(start);
						// miliseconds to sleep
						int msec = frameInterval - (int) span.TotalMilliseconds;

						while ((msec > 0) && (stopEvent.WaitOne(0, true) == false))
						{
							// sleeping ...
							Thread.Sleep((msec < 100) ? msec : 100);
							msec -= 100;
						}
					}
				}
				catch (WebException ex)
				{
					System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
					// wait for a while before the next try
					Thread.Sleep(250);
				}
				catch (Exception ex)
				{
					System.Diagnostics.Debug.WriteLine("=============: " + ex.Message);
				}
				finally
				{
					// abort request
					if (req != null)
					{
						req.Abort();
						req = null;
					}
					// close response stream
					if (stream != null)
					{
						stream.Close();
						stream = null;
					}
					// close response
					if (resp != null)
					{
						resp.Close();
						resp = null;
					}
				}

				// need to stop ?
				if (stopEvent.WaitOne(0, true))
					break;
			}
		}
Exemple #28
0
 private void process_NewFrame(object stateInfo)
 {            
     try
     {
         Bitmap imgBuffer = GenerateBitmap();
         if (imgBuffer != null)
         {
             // 
             VsImage lastFrame = new VsImage(imgBuffer);
             // output
             if (FrameOut != null) FrameOut(this, new VsImageEventArgs(lastFrame));
         }
     }
     catch (Exception err)
     {
         logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);;
     }
 } 
Exemple #29
0
        private void process_NewFrame(object sender, System.Timers.ElapsedEventArgs e)
        {
            Thread.CurrentThread.Priority = ThreadPriority.Highest;

            // Stop analyzer
            StopAnalyzer();

            try
            {
                // input frame
                if (numInput >= 5)
                {
                    if (lastFrame5 == null && imgBuffer5.Count > 0) lastFrame5 = (VsImage)imgBuffer5.Dequeue();
                    if (lastFrame5 == null) return;
                }

                if (numInput >= 4)
                {
                    if (lastFrame4 == null && imgBuffer4.Count > 0) lastFrame4 = (VsImage)imgBuffer4.Dequeue();
                    if (lastFrame4 == null) return;
                }

                if (numInput >= 3)
                {
                    if (lastFrame3 == null && imgBuffer3.Count > 0) lastFrame3 = (VsImage)imgBuffer3.Dequeue();
                    if (lastFrame3 == null) return;
                }

                if (numInput >= 2)
                {
                    if (lastFrame2 == null && imgBuffer2.Count > 0) lastFrame2 = (VsImage)imgBuffer2.Dequeue();
                    if (lastFrame2 == null) return;
                }

                if (numInput >= 1)
                {
                    if (lastFrame1 == null && imgBuffer1.Count > 0) lastFrame1 = (VsImage)imgBuffer1.Dequeue();
                    if (lastFrame1 == null) return;
                }

                // process
                if (numInput == 5) process_Frame5(lastFrame1, lastFrame2, lastFrame3, lastFrame4, lastFrame5);
                if (numInput == 4) process_Frame4(lastFrame1, lastFrame2, lastFrame3, lastFrame4);
                if (numInput == 3) process_Frame3(lastFrame1, lastFrame2, lastFrame3);
                if (numInput == 2) process_Frame2(lastFrame1, lastFrame2);
                if (numInput == 1) process_Frame1(lastFrame1);
 
                if (lastFrame1 != null)
                {
                    if (lastFrame1.IsDetected)
                    {
                        if (!lastMotion)
                        {
                            // new motion occurs
                            // alert motion
                            EventAlert();
                        }
                        // still moving
                        timeSave = interLength;
                        lastMotion = true;
                        lastResult = lastFrame1.Result;
                    }
                    else
                    {
                        if (timeSave > 0)
                        {
                            // motion smoothing
                            lastFrame1.IsDetected = true;
                            lastFrame1.Result = lastResult;
                            lastMotion = true;
                        }
                        else
                        {
                            // motion disappear
                            lastMotion = false;
                            lastResult = "";
                        }
                    }

                    // draw image
                    DrawMotion(lastFrame1.Image, lastFrame1.IsDetected);
                }

                // send out
                if (numOutput >= 5) if (FrameOut5 != null) FrameOut5(this, new VsImageEventArgs(lastFrame5));
                if (numOutput >= 4) if (FrameOut4 != null) FrameOut4(this, new VsImageEventArgs(lastFrame4));
                if (numOutput >= 3) if (FrameOut3 != null) FrameOut3(this, new VsImageEventArgs(lastFrame3));
                if (numOutput >= 2) if (FrameOut2 != null) FrameOut2(this, new VsImageEventArgs(lastFrame2));
                if (numOutput >= 1) if (FrameOut1 != null) FrameOut1(this, new VsImageEventArgs(lastFrame1));

            }
            catch (Exception err)
            {
                logger.Log(LogLevel.Error, err.Message + " " + err.Source + " " + err.StackTrace);;
            }
            finally
            {
                // free buffer
                if (numInput >= 5 && lastFrame5 != null) { lastFrame5.Dispose(); lastFrame5 = null; }
                if (numInput >= 4 && lastFrame4 != null) { lastFrame4.Dispose(); lastFrame4 = null; }
                if (numInput >= 3 && lastFrame3 != null) { lastFrame3.Dispose(); lastFrame3 = null; }
                if (numInput >= 2 && lastFrame2 != null) { lastFrame2.Dispose(); lastFrame2 = null; }
                if (numInput >= 1 && lastFrame1 != null) { lastFrame1.Dispose(); lastFrame1 = null; }

                // Start analyzer
                StartAnalyzer();
            }
        }