public static void TestTicket(string sourcename, int queuelength, ref bool stopGeneratingFrames)
        {
            // Video recording is now a single thread for all imports, and hence has a queue.
            // This code pauses the imports if the save queue grows beyond a set limit, as the save
            // queue eats ram. It is designed in a circular ticket system so no one source gets
            // undue prominence in the save system.
            //
            if (queuelength > 2)
            {
                DateTime queueEntry = DateTime.Now;

                DebugMessageLogger.LogEvent("ImportingVideoPlayer.GenerateFrames - Wait Requested Source={0}, Current Queue Length={1}",
                                            sourcename, queuelength);

                int ticket = VQueueTicket_getTicket();
                while (!stopGeneratingFrames)
                {
                    Kinesense.Interfaces.Threading.ThreadSleepMonitor.Sleep(1000);
                    if (queuelength < 4 && VQueueTicket_checkTicket(ticket))
                    {
                        break;
                    }
                    DebugMessageLogger.LogEventLevel(1,
                                                     "ImportingVideoPlayer.GenerateFrames - Wait Continues Source={0}, Current Queue Length={1}, Ticket={2}, Been Queuing For {3} seconds",
                                                     sourcename, queuelength, ticket, (DateTime.Now - queueEntry).TotalSeconds);
                }
                if (stopGeneratingFrames)
                {
                    DebugMessageLogger.LogEventLevel(1, "ImportingVideoPlayer.GenerateFrames - Stop generating requested whilst in queue. Ticket={0} to be surrounded", ticket);
                    VQueueTicket_surrenderTicket(ticket);
                }
            }
        }
        public static void LogSleepData()
        {
            //order by most sleep calls
            //List<string> data = new List<string>();
            string data = "";

            List <KeyValuePair <string, double> > myList = _sleepCounts.ToList();

            myList.Sort(
                delegate(KeyValuePair <string, double> pair1,
                         KeyValuePair <string, double> pair2)
            {
                return(pair1.Value.CompareTo(pair2.Value));
            }
                );

            foreach (var kvp in myList)
            {
                double tot = _sleepTotalTimes[kvp.Key];
                string s   = string.Format("SleepCount {0} TotalTime {1} at {2}\n", kvp.Value, tot, kvp.Key);
                data += s;
            }

            foreach (var kvp in _sleephistogram)
            {
                data += string.Format("\n{0} - {1}", kvp.Key, kvp.Value);
            }

            DebugMessageLogger.LogEvent(data);
        }
예제 #3
0
        public static string GetPublicIP()
        {
            String direction = "?";

            DebugMessageLogger.LogEvent("Requesting External IP Address from http://checkip.dyndns.org/");
            try
            {
                WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
                using (WebResponse response = request.GetResponse())
                    using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                    {
                        direction = stream.ReadToEnd();
                    }

                //Search for the ip in the html
                int first = direction.IndexOf("Address: ") + 9;
                int last  = direction.LastIndexOf("</body>");
                direction = direction.Substring(first, last - first);

                DebugMessageLogger.LogEvent("My IP is " + direction);
            }
            catch (Exception e)
            {
                DebugMessageLogger.LogError(e, "Failed to get IP address. Perhaps Computer is not online");
            }
            return(direction);
        }
        public byte[] TakeBuffer(int timeout_ms)
        {
            byte[] bf = null;

            int ticket = -1;


            int waitcount = 0;

            while (!_buffers.TryDequeue(out bf))
            {
                System.Diagnostics.Debug.WriteLine("Waiting for Buffer {0}, wait count {1}", BufferSize, waitcount);

                if (ticket == -1)
                {
                    lock (_countlock)
                    {
                        ticket = _ticketCount++;
                    }
                }

                _waiting++;
                waitcount++;

                _event.WaitOne(timeout_ms);

                _waiting--;

                int diff = ticket - _usedTickets;
                if (diff > 0)
                {
                    Kinesense.Interfaces.Threading.ThreadSleepMonitor.Sleep(diff);
                }

                if ((waitcount > 3 && BufferCount < MaxBuffers) ||
                    (waitcount > 10))
                {
                    BufferCount++;
                    DebugMessageLogger.LogEvent("Waiting too long for buffer - making a new one of size {0} ({1}/{2})", this.BufferSize, this.BufferCount, this.MaxBuffers);
                    bf = new byte[this.BufferSize];
                    break;
                }
            }
            if (ticket != -1)
            {
                lock (_countlock)
                {
                    if (_usedTickets < ticket)
                    {
                        _usedTickets = ticket;
                    }
                }
            }

            MostRecentUse = DateTime.Now;

            Array.Clear(bf, 0, bf.Length);
            return(bf);
        }
 public void DropBuffers()
 {
     DebugMessageLogger.LogEvent("DropBuffers on {0} Dropping {1} Buffers", this.BufferSize, this.BufferCount);
     while (_buffers.Count > 0)
     {
         byte[] buf = null;
         _buffers.TryDequeue(out buf);
         buf = null;
     }
     GC.Collect();
 }
        public byte[] GetFrameData(DateTime time)
        {
            byte[] jpgBuffer = null;

            try
            {
                //parse header
                int pos = -1;
                if (!_timePosDictionary.TryGetValue(time, out pos))
                {
                    return(null);
                }

                //Read Frame Header:
                int linelimit = 0;
                //content Length
                string contentLengthString = ByteArrayUtils.GetPrefixedLine(
                    _buffer, ContentLengthPrefix, pos, 400, Encoding.ASCII, out linelimit);
                //Hash code
                //string hashString = ByteArrayUtils.GetPrefixedLine(
                //    _buffer, ContentHashPrefix, linelimit, 400, Encoding.ASCII, out linelimit);

                //string privatehashString = ByteArrayUtils.GetPrefixedLine(
                //    _buffer, ContentPrivateHashPrefix, linelimit, 400, Encoding.ASCII, out linelimit);

                //use linelimit as start point to copy the jpeg data
                int contentLength = int.Parse(contentLengthString);

                //This should work always, but its possible that the bytes 0x00 and 0x10 could be different sometimes.
                //keep an eye out for weird behaviour. See http://www.garykessler.net/library/file_sigs.html
                //
                // Gerrr Mark
                //
                //byte[] jpegHeaderpattern = new byte[] { 0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10, 0x4A, 0x46, 0x49, 0x46 };
                byte?[] jpegHeaderpattern = new byte?[] { 0xFF, null, 0xFF, null };
                int     datastart         = ByteArrayUtils.IndexOf(_buffer, jpegHeaderpattern, linelimit, 400);
                if (datastart == -1)
                {
                    DebugMessageLogger.LogEvent("Search for jpeg header failed; MultipartVideoDecoder.GetAllFrames()");
                }

                //return bytes
                jpgBuffer = new byte[contentLength];
                Array.Copy(_buffer, datastart, jpgBuffer, 0, contentLength);
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return(jpgBuffer);
        }
        public byte[] ComputeEncodedDataHash(IHashAlgorithmFactory hashAlgorithmFactory, byte[] encodedData)
        {
            if (string.IsNullOrEmpty(this.HashAlgorithmName))
            {
                this.HashAlgorithmName = "MD5";
                DebugMessageLogger.LogEvent("Frame HashAlgorithmName not set!");
            }
            HashAlgorithm hashAlgorithm = hashAlgorithmFactory.GetHashAlgorithm(this.HashAlgorithmName);

            return(hashAlgorithm != null?hashAlgorithm.ComputeHash(encodedData) : new byte[]
            {
            });
        }
예제 #8
0
        public byte[] GetBuffer(long length)
        {
            if (!BufferManagerOn)
            {
                return(new byte[length]);
            }

            byte[] buffer = null;

            if (Sizes.Count == 0)
            {
                PopulateSizes();
            }

            try
            {
                if (length > _bufferSizeTestThreshold)
                {
                    _countAllocations++;
                    if (_countAllocations % _testMemoryFrequency == 0)
                    {
                        double d = this.ProcessMemoryLoad();
                        if (d > 50)
                        {
                            DebugMessageLogger.LogEvent("BufferManager. Process Memory Load is {0}%, introducing a short sleep", d);
                            Kinesense.Interfaces.Threading.ThreadSleepMonitor.Sleep((int)d);
                        }
                    }
                }

                long size = GetClosestBuffer(length, BufferNeededFor.Allocation);

                buffer = _bufferManagers[size].TakeBuffer(50);

                //foreach(byte b in buffer)
                //    if (b != 0)
                //    {
                //    }
            }
            catch (Exception ee)
            {
                DebugMessageLogger.LogError(ee);
            }

            return(buffer);
        }
예제 #9
0
        public static bool TryDo <T>(Func <T> fun, int millisecondsTimeout, out T result)
        {
            var tResult           = default(T);
            var exceptionHappened = false;

            var thread = new Thread(() =>
            {
                try
                {
                    tResult = fun();
                }
                catch (ThreadAbortException ex)
                {
                    exceptionHappened = true;
                    DebugMessageLogger.LogEvent("SaveActionHelper TryDo Timeout");
                    DebugMessageLogger.LogError(ex);
                }
                catch (Exception ex)
                {
                    exceptionHappened = true;
                    DebugMessageLogger.LogError(ex);
                }
            });

            thread.Start();

            var completed = thread.Join(millisecondsTimeout);

            result = tResult;

            if (!completed || exceptionHappened)
            {
                thread.Abort();
                return(false);
            }

            return(true);
        }