示例#1
0
 public PacketInterval(int captureBatchId, int interval, int packetCount, CaptureState packetState)
 {
     this.CaptureBatchId = captureBatchId;
     this.Interval = interval;
     this.PacketCount = packetCount;
     this.PacketState = packetState;
 }
示例#2
0
        public int CreateBatchInterval(string fileName, CaptureState marked)
        {
            //bool success = false;
            int newCaptureBatchId = 0;

            //using (var context = new PacketCaptureContext())
            using (var context = new PacketAnalysisEntity())
            {
                // Check to see if the batch already exists (it shouldn't - but we will use this for testing)
                var captureBatchId = (from c in context.CaptureBatches
                             where c.FileName == fileName
                             select c.CaptureBatchId).FirstOrDefault();

                if (captureBatchId > 0)
                {
                    // CaptureBatch already exists - just use the current CaptureBatchId
                    newCaptureBatchId = captureBatchId;
                }
                else
                {
                    // We need to add a new capture batch and get the CaptureBatchId

                    var newBatch = context.CaptureBatches.Add(new CaptureBatch());
                    newBatch.FileName = fileName;
                    newBatch.Marked = marked == CaptureState.Marked? true : false;
                    //newCaptureBatchId = context.SaveChanges();
                    context.SaveChanges();
                    newCaptureBatchId = context.CaptureBatches.Select(c => c.CaptureBatchId).Max();
                }
            }

            // success;
            return newCaptureBatchId;
        }
示例#3
0
 public RawPacket(int capturePacketId, string fileName, int packetNumber, DateTime timeStamp, CaptureState marked)
 {
     this.CapturePacketId = capturePacketId;
     this.FileName = fileName;
     this.PacketNumber = packetNumber;
     this.TimeStamp = timeStamp;
     this.Marked = marked;
 }
示例#4
0
 public RawPacket(int capturePacketId, int captureBatchId, int packetNumber, DateTime timeStamp, CaptureState marked)
 {
     this.CapturePacketId = capturePacketId;
     this.CaptureBatchId = captureBatchId;
     this.PacketNumber = packetNumber;
     this.TimeStamp = timeStamp;
     this.Marked = marked;
 }
示例#5
0
 //public AnalysisEngine(bool trimZeroPacketIntervals, int histogramBinSize, HypothesisTest hypothesisTest, string captureFileName, CaptureState captureState)
 public AnalysisEngine(bool trimZeroPacketIntervals, int histogramBinSize, HypothesisTestType hypothesisTestType, CurrentCaptureFile file)
 {
     this._HistogramBinSize = histogramBinSize;
     this._TrimZeroPacketIntervals = trimZeroPacketIntervals;
     this._CaptureFileName = file.FileName;
     //this._CaptureState = captureState;
     this._CaptureState = file.CaptureState;
     this._HypothesisTestType = hypothesisTestType;
     this._File = new CurrentCaptureFile();
     this._File = file;
 }
示例#6
0
        //public static void StartMutiCapture()
        //{
        //    _timerMutiCapture.Interval = XCamera.GetInstance().CapturePara.MutiCaptureTimeStep;
        //    _timerMutiCapture.Elapsed += _timerMutiCapture_Tick;
        //    //_timerMutiCapture.AutoReset = false;
        //    _captureState = CaptureState.MULT_CAPTURE_TRIGGER_ON;
        //    //_timerMutiCapture.Enabled = true;
        //    _timerMutiCapture.Start();
        //}

        //public static void StopMutiCapture()
        //{
        //    //_timerMutiCapture.Enabled = false;
        //    _timerMutiCapture.Stop();
        //    _captureState = CaptureState.MULT_CAPTURE_TRIGGER_OFF;
        //}

        public static void StartVideoCapture()
        {
            try
            {
                if (XCamera.GetInstance().StartRecord())
                {
                    _captureState = CaptureState.VIDEO_CAPTURING;
                    PublishVideoCaptureStartedEvent(new EventArgs());
                }
            }
            catch (System.Exception ex)
            {
                _logger.Error(ex.Message);
            }
        }
示例#7
0
 /// <summary>
 /// Start Capturing
 /// </summary>
 public void StartRecording()
 {
     lock (syncLock)
     {
         if (captureState != CaptureState.Stopped)
         {
             throw new InvalidOperationException("Previous recording still in progress");
         }
         captureState = CaptureState.Starting;
         InitializeCaptureDevice();
         ThreadStart start = () => CaptureThread(audioClient);
         captureThread = new Thread(start);
         captureThread.Start();
     }
 }
        public void StopPlaybackWithVideo()
        {
            state = CaptureState.None;

            if (Movie != null)
            {
                Movie.Pause();
                Movie.PositionSeconds = 0;
            }

            if (OnStopPlayback != null)
            {
                OnStopPlayback();
            }
        }
示例#9
0
        /// @endcond

        public static void Initialize()
        {
            if (CurrentState != CaptureState.UnInitialized)
            {
                return;
            }

            NRDebug.Log("[NRRgbCamera] Initialize");
            m_NativeCamera = new NativeCamera();
#if !UNITY_EDITOR
            m_NativeCamera.Create();
            m_NativeCamera.SetCaptureCallback(Capture);
#endif
            CurrentState = CaptureState.Initialized;
        }
示例#10
0
    /// <summary>
    /// Ends a capture group.
    /// </summary>
    public static void End()
    {
        EditorGUILayout.EndVertical();

        if (_isDebugEnabled || _isPreformingCapture > 0)
        {
            EventType currentEvent = Event.current.type;

            if (_isPreformingCapture > 0)
            {
                if ((currentEvent == EventType.Repaint || currentEvent == EventType.Layout) && currentEvent != _lastEvent)
                {
                    _lastEvent = currentEvent;

                    if (currentEvent == EventType.Repaint)
                    {
                        _isPreformingCapture--;
                    }

                    if (_isPreformingCapture == 0)
                    {
                        _onRepaint = null;
                        AssetDatabase.Refresh();
                    }
                    else
                    {
                        _onRepaint.Invoke();
                    }
                }
            }

            switch (currentEvent)
            {
            case EventType.Repaint:
                CaptureState state = _captureStack.Pop();
                if (_isDebugEnabled)
                {
                    _cachedContent.text = state.SavePath;
                    _debugStyle.Draw(state.Bounds, _cachedContent, true, false, false, false);
                }
                if (_isPreformingCapture == 1)
                {
                    Capture(state);
                }
                break;
            }
        }
    }
示例#11
0
 // Lock the focus as the first step for a still image capture.
 private void LockFocus()
 {
     try
     {
         // This is how to tell the camera to lock focus.
         _previewRequestBuilder.Set(CaptureRequest.ControlAfTrigger, (int)ControlAFTrigger.Start);
         // Tell #mCaptureCallback to wait for the lock.
         State = CaptureState.WaitingLock;
         _captureSession.Capture(_previewRequestBuilder.Build(), _captureListener,
                                 _backgroundThread.Handler);
     }
     catch (CameraAccessException e)
     {
         e.PrintStackTrace();
     }
 }
示例#12
0
        internal bool SetControlIfCapturing(System.Windows.Input.Key key)
        {
            if (!IsCapturing || _captureState != CaptureState.CaptureKeyboard)
            {
                return(false);
            }

            LoadedConfiguration.SetKeyboardInput(_controlToCapture, key);

            UpdateAllButtonText();

            IsCapturing       = false;
            HasUnsavedChanges = true;
            _captureState     = CaptureState.NotCapturing;
            return(true);
        }
示例#13
0
 // Run the precapture sequence for capturing a still image. This method should be called when
 // we get a response in {@link #mCaptureCallback} from {@link #lockFocus()}.
 private void RunPrecaptureSequence()
 {
     try
     {
         // This is how to tell the camera to trigger.
         _previewRequestBuilder.Set(CaptureRequest.ControlAePrecaptureTrigger,
                                    (int)ControlAEPrecaptureTrigger.Start);
         // Tell #mCaptureCallback to wait for the precapture sequence to be set.
         State = CaptureState.WaitingPrecapture;
         _captureSession.Capture(_previewRequestBuilder.Build(), _captureListener, _backgroundThread.Handler);
     }
     catch (CameraAccessException e)
     {
         e.PrintStackTrace();
     }
 }
        public void DeleteCumulativeProbabilityDistribution(CaptureState captureState)
        {
            using (var context = new PacketAnalysisEntity())
            {
                var distribution = from d in context.CumulativeProbabilityDistributions
                                   where d.CaptureState == (int)captureState
                                   select d;

                foreach (CumulativeProbabilityDistribution cpd in distribution)
                {
                    context.CumulativeProbabilityDistributions.Remove(cpd);
                }

                context.SaveChanges();
            }
        }
        public void StartPlaybackWithVideo()
        {
            state = CaptureState.PlayingWithVideo;

            if (Movie == null)
            {
                return;
            }

            Movie.Play();
            Movie.PositionSeconds = 0;

            if (OnStartPlayback != null)
            {
                OnStartPlayback();
            }
        }
示例#16
0
        internal bool SetControlIfCapturing(GamePadButton pressedButton)
        {
            if (!IsCapturing || _captureState != CaptureState.CaptureController)
            {
                return(false);
            }

            LoadedConfiguration.SetControllerInput(_controlToCapture, pressedButton);

            UpdateAllButtonText();
            UpdateAllButtonIcons();

            IsCapturing       = false;
            _captureState     = CaptureState.NotCapturing;
            HasUnsavedChanges = true;
            return(true);
        }
        IEnumerator Bake(Action callback)
        {
            state = CaptureState.BakingAnimation;
            yield return(StartCoroutine(currentTake.Bake()));

            Logger.Info("Finished recording of length: " + (currentTake.BakeTime - currentTake.CreationTime));
            Logger.Info("Number of channels: " + currentTake.ChannelCount);
            Logger.Info("Number of frames: " + currentTake.GetChannel(currentTake.ChannelNames.First()).keyframes.Count);
            if (callback != null)
            {
                callback();
            }
            if (OnStopRecording != null)
            {
                OnStopRecording();
            }
        }
示例#18
0
        /**
         * @brief Start to play rgb camera.
         */
        public static void Play()
        {
            if (CurrentState == CaptureState.UnInitialized)
            {
                Initialize();
            }
            if (CurrentState == CaptureState.UnInitialized || CurrentState == CaptureState.Running)
            {
                StateError(string.Format("Can not start in state:{0}", CurrentState));
                return;
            }
            NRDebug.Log("[NRRgbCamera] Start to play");
#if !UNITY_EDITOR
            m_NativeCamera.StartCapture();
#endif
            CurrentState = CaptureState.Running;
        }
        // need to create insert and delete functions
        public BindingList<CumulativeProbabilityDistribution> GetCumulativeProbabilityDistribution(CaptureState captureState)
        {
            BindingList<CumulativeProbabilityDistribution> probabilities = new BindingList<CumulativeProbabilityDistribution>();

               using (var context = new PacketAnalysisEntity())
               {
               var cpd = from c in context.CumulativeProbabilityDistributions
                         where c.CaptureState == (int)captureState
                         select c;

               foreach (CumulativeProbabilityDistribution dist in cpd)
               {
                   probabilities.Add(dist);
               }
               }
               return probabilities;
        }
示例#20
0
        public void CaptureFrame(IGameContext gameContext, Action<byte[]> onCapture)
        {
            if (this.m_CaptureState != null)
            {
                return;
            }

            this.m_CaptureState = new CaptureState
            {
                Mode = CaptureStateMode.Requested,
                RenderTarget = new RenderTarget2D(
                    gameContext.Graphics.GraphicsDevice,
                    gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferWidth,
                    gameContext.Graphics.GraphicsDevice.PresentationParameters.BackBufferHeight),
                Action = onCapture
            };
        }
示例#21
0
        public string EndCapture()
        {
            if (_capture == null)
            {
                throw new InvalidOperationException("Capture has not started.");
            }

            StringBuilder text = new StringBuilder();

            lock (_lines)
            {
                for (int y = _capture.Y; y <= _y; y++)
                {
                    char[] line = _lines[y].ToArray();

                    if (text.Length > 0)
                    {
                        text.AppendLine();
                    }

                    if (y == _capture.Y)
                    {
                        if (_capture.X < line.Length)
                        {
                            text.Append(line.Skip(_capture.X).ToArray());
                        }
                    }
                    else if (y == _y)
                    {
                        if (_x > 0)
                        {
                            text.Append(line.Take(_x).ToArray());
                        }
                    }
                    else
                    {
                        text.Append(line);
                    }
                }
            }

            _capture = null;

            return(text.ToString());
        }
示例#22
0
        private void DoRecording(AudioClient client)
        {
            //Debug.WriteLine(String.Format("Client buffer frame count: {0}", client.BufferSize));
            int bufferFrameCount = client.BufferSize;

            // Calculate the actual duration of the allocated buffer.
            long actualDuration = (long)((double)ReftimesPerSec *
                                         bufferFrameCount / waveFormat.SampleRate);
            int sleepMilliseconds = (int)(actualDuration / ReftimesPerMillisec / 2);
            int waitMilliseconds  = (int)(3 * actualDuration / ReftimesPerMillisec);

            var capture = client.AudioCaptureClient;

            lock (syncLock)
            {
                if (captureState != CaptureState.Starting)
                {
                    return; // Client probably requested stop (or some other state change happened) before we actually started capturing.
                }
                client.Start();
                captureState = CaptureState.Capturing;
            }
            while (captureState == CaptureState.Capturing)
            {
                bool readBuffer = true;
                if (isUsingEventSync)
                {
                    readBuffer = frameEventWaitHandle.WaitOne(waitMilliseconds, false);
                }
                else
                {
                    Thread.Sleep(sleepMilliseconds);
                }
                if (captureState != CaptureState.Capturing)
                {
                    break;
                }

                // If still recording and notification is ok
                if (readBuffer)
                {
                    ReadNextPacket(capture);
                }
            }
        }
示例#23
0
        internal bool SetNumpadEnterControlIfCapturing()
        {
            if (!IsCapturing)
            {
                return(false);
            }

            ControlInputSetting numpadEnterSetting = ControlMapper.ControlInputs.Where(c => c.DisplayText == "NUMPADENTER").FirstOrDefault();

            LoadedConfiguration.SetKeyboardInput(_controlToCapture, numpadEnterSetting);

            UpdateAllButtonText();

            IsCapturing       = false;
            HasUnsavedChanges = true;
            _captureState     = CaptureState.NotCapturing;
            return(true);
        }
示例#24
0
        public bool Start(IntPtr handle, int fps = 25, Rectangle?subrect = null, bool showCursor = true)
        {
            if (FCaptureState != CaptureState.Idle)
            {
                return(false);
            }

            FHandle              = handle;
            FShowCursor          = showCursor;
            FSubrect             = subrect;
            FCaptureState        = CaptureState.Capturing;
            FDelayInMilliseconds = 1000 / fps;

            FTimer.Interval = FDelayInMilliseconds;
            FTimer.Start();

            return(true);
        }
示例#25
0
        private void RecordThread()
        {
            Exception e = (Exception)null;

            try
            {
                this.DoRecording();
            }
            catch (Exception ex)
            {
                e = ex;
            }
            finally
            {
                this.captureState = CaptureState.Stopped;
                this.RaiseRecordingStoppedEvent(e);
            }
        }
示例#26
0
        private void RecordThread()
        {
            Exception exception = null;

            try
            {
                DoRecording();
            }
            catch (Exception e)
            {
                exception = e;
            }
            finally
            {
                captureState = CaptureState.Stopped;
                RaiseRecordingStoppedEvent(exception);
            }
        }
示例#27
0
    // Use this for initialization
    void Start()
    {
        // Suppose this could be set with a public enum variable
        teamTag_ = gameObject.tag;

        // Gain Access to the world manager script
        worldManager_ = worldManager_.GetComponent <WorldManager>();

        teamFlagCaptured_   = false;
        enemeyFlagCaptured_ = false;

        rend = GetComponent <Renderer>();

        if (teamTag_ == "BlueTeam")
        {
            team_ = Team.Blue;
            rend.material.color = Color.blue;
        }
        else
        {
            team_ = Team.Red;
            rend.material.color = Color.red;
        }

        moveSpeed        = 7.5f;
        isAlive          = true;
        didRespawn       = false;
        respawnPos       = gameObject.transform.position;
        isCapturing      = false;
        enemyUnitTarget_ = null;

        bulletLine = GetComponent <LineRenderer>();

        captureState_ = this.GetComponent <CaptureState>();
        defendState_  = this.GetComponent <DefendState>();

        captureState_.enabled = false;
        defendState_.enabled  = false;

        startNode = getClosestNode();

        IDXcounter_ = 0;
        hasFlag     = false;
    }
        private void PointDown(System.Windows.Point pointDown)
        {
            switch (_state)
            {
            case CaptureState.SelectingWindow:
                break;

            case CaptureState.SelectedWindow:
                startDrawing(pointDown);
                _state = CaptureState.SelectingCaptureArea;
                break;

            case CaptureState.SelectingCaptureArea:
                break;

            default:
                throw new NotSupportedException();
            }
        }
示例#29
0
 // Unlock the focus. This method should be called when still image capture sequence is
 // finished.
 private void UnlockFocus()
 {
     try
     {
         // Reset the auto-focus trigger
         _previewRequestBuilder.Set(CaptureRequest.ControlAfTrigger, (int)ControlAFTrigger.Cancel);
         Utils.SetAutoFlash(_previewRequestBuilder, _manager, _cameraId);
         _captureSession.Capture(_previewRequestBuilder.Build(), _captureListener,
                                 _backgroundThread.Handler);
         // After this, the camera will go back to the normal state of preview.
         State = CaptureState.WaitingLock;
         _captureSession.SetRepeatingRequest(_previewRequest, _captureListener,
                                             _backgroundThread.Handler);
     }
     catch (CameraAccessException e)
     {
         e.PrintStackTrace();
     }
 }
示例#30
0
        private void DoRecording(AudioClient client)
        {
            //Debug.WriteLine(String.Format("Client buffer frame count: {0}", client.BufferSize));
            int bufferFrameCount = client.BufferSize;

            // Calculate the actual duration of the allocated buffer.
            long actualDuration = (long)((double)ReftimesPerSec *
                                         bufferFrameCount / waveFormat.SampleRate);
            int sleepMilliseconds = (int)(actualDuration / ReftimesPerMillisec / 2);
            int waitMilliseconds  = (int)(3 * actualDuration / ReftimesPerMillisec);

            var capture = client.AudioCaptureClient;

            client.Start();
            // avoid race condition where we stop immediately after starting
            if (captureState == CaptureState.Starting)
            {
                captureState = CaptureState.Capturing;
            }
            while (captureState == CaptureState.Capturing)
            {
                bool readBuffer = true;
                if (isUsingEventSync)
                {
                    readBuffer = frameEventWaitHandle.WaitOne(waitMilliseconds, false);
                }
                else
                {
                    Thread.Sleep(sleepMilliseconds);
                }
                if (captureState != CaptureState.Capturing)
                {
                    break;
                }

                // If still recording and notification is ok
                if (readBuffer)
                {
                    ReadNextPacket(capture);
                }
            }
        }
        private void btnStartDrawing_Click_1(object sender, RoutedEventArgs e)
        {
            if (_state == CaptureState.SelectingWindow)
            {
                _state           = CaptureState.SelectedWindow;
                this.Background  = new SolidColorBrush(System.Windows.Media.Color.FromArgb(0xFF, 0x5D, 0x5D, 0x5D));
                MaxHeight        = System.Windows.SystemParameters.PrimaryScreenHeight;
                this.WindowState = WindowState.Maximized;

                this.Opacity = 0.6;

                lblHelp.Visibility         = Visibility.Visible;
                btnStartDrawing.Visibility = Visibility.Hidden;
                btnCancel.Visibility       = Visibility.Collapsed;

                this.Hide();
                this.Show();
                this.Topmost = true;
            }
        }
        private void SnagImg_OnStateChange(CaptureState newState)
        {
            if (newState == CaptureState.scsCaptureSucceeded)
            {
                IsDone = true;
            }

            if (newState != CaptureState.scsBusy && newState != CaptureState.scsIdle)
            {
                IsDone = true;
            }

            if (newState == CaptureState.scsCaptureFailed)
            {
                HasError = true;
            }


            Debug.WriteLine(newState.ToString() + " - IsDone " + IsDone);
        }
示例#33
0
        private void DoRecording2(List <AudioClient> clientList)
        {
            //Debug.WriteLine(String.Format("Client buffer frame count: {0}", client.BufferSize));
            int bufferFrameCount1 = clientList[0].BufferSize;
            int bufferFrameCount2 = clientList[1].BufferSize;

            // Calculate the actual duration of the allocated buffer.
            long actualDuration1 = (long)((double)ReftimesPerSec *
                                          bufferFrameCount1 / waveFormatList[0].SampleRate);
            int sleepMilliseconds1 = (int)(actualDuration1 / ReftimesPerMillisec);
            int waitMilliseconds1  = (int)(3 * actualDuration1 / ReftimesPerMillisec);

            long actualDuration2 = (long)((double)ReftimesPerSec *
                                          bufferFrameCount2 / waveFormatList[1].SampleRate);
            int sleepMilliseconds2 = (int)(actualDuration1 / ReftimesPerMillisec);
            int waitMilliseconds2  = (int)(3 * actualDuration1 / ReftimesPerMillisec);

            var capture1 = clientList[0].AudioCaptureClient;

            clientList[0].Start();
            var capture2 = clientList[1].AudioCaptureClient;

            clientList[1].Start();

            captureState = CaptureState.Capturing;
            while (captureState == CaptureState.Capturing)
            {
                bool readBuffer = true;
                Thread.Sleep(Math.Max(sleepMilliseconds1, sleepMilliseconds2) / 2);
                if (captureState != CaptureState.Capturing)
                {
                    break;
                }

                // If still recording and notification is ok
                if (readBuffer)
                {
                    ReadNextPacket2(capture1, capture2);
                }
            }
        }
示例#34
0
	// Use this for initialization
	void Start ()
	{
		// initialise the shrine
		captureProgress = 76.0f;
		conversionSpeed = 40.0f;

		// Set initial state to unowned
		ownerState = CaptureState.UNCAPTURED;

		// Find objects
		PlayerOne = GameObject.FindGameObjectWithTag("Player1");
		PlayerTwo = GameObject.FindGameObjectWithTag("Player2");

		// Access material and set initial colour
		material = GetComponent<Renderer>().material;
		material.SetColor("_IconColour", captureColor);
		material.SetTexture("_IconTex", uncapturedTexture);

		// Access audio source
		audioSource = GetComponent<AudioSource> ();
	}
        private void btnStartDrawing_Click_1(object sender, RoutedEventArgs e)
        {
            if (_state == CaptureState.SelectingWindow)
            {
                _state            = CaptureState.SelectedWindow;
                helpBg.Background = null;
                // helpBg.VerticalAlignment = VerticalAlignment.Top;
                lblHelp.Content = "Draw Screenshot Capture Area/スクリーンショットを撮る領域を指定して下さい";

                this.Background  = new SolidColorBrush(System.Windows.Media.Color.FromArgb(78, 0, 0, 0));
                MaxHeight        = System.Windows.SystemParameters.PrimaryScreenHeight;
                this.WindowState = WindowState.Maximized;

                btnStartDrawing.Visibility = Visibility.Hidden;
                btnCancel.Visibility       = Visibility.Collapsed;

                this.Hide();
                this.Show();
                this.Topmost = true;
            }
        }
    private void CaptureTarget()
    {
        var plane = GetComponent <PassengerPlane>();

        if (plane.CanAddPassenger == false)
        {
            return;
        }

        PersonGenerator.instance.PlaySound(m_captureSound);

        plane.AddPassenger(m_targetPerson.Data);
        Destroy(m_targetPerson.gameObject);
        Console.instance.WriteMessage($"Picked up {m_targetPerson.Data}");

        m_cooldownTimeElapsed = 0f;
        m_state = CaptureState.Cooldown;
        GetComponent <PlaneController>().CheckWin();

        m_targetPerson = null;
    }
        private void CaptureThread(AudioClient client)
        {
            Exception exception = null;

            try
            {
                DoRecording(client);
            }
            catch (Exception e)
            {
                exception = e;
            }
            finally
            {
                client.Stop();
                // don't dispose - the AudioClient only gets disposed when WasapiCapture is disposed
            }
            captureThread = null;
            captureState  = CaptureState.Stopped;
            RaiseRecordingStopped(exception);
        }
示例#38
0
        private void DoRecording()
        {
            _captureState = CaptureState.Capturing;

            while (_captureState == CaptureState.Capturing)
            {
                int bufferSize = BufferMilliseconds * WaveFormat.AverageBytesPerSecond / 1000;
                if (bufferSize % WaveFormat.BlockAlign != 0)
                {
                    bufferSize -= bufferSize % WaveFormat.BlockAlign;
                }

                var buffer = new byte[bufferSize];
                if (_api.pa_simple_read(_connectionHandle, buffer, (UIntPtr)bufferSize, out var error) < 0)
                {
                    throw new Exception("PulseAudio read error");
                }

                DataAvailable?.Invoke(this, new WaveInEventArgs(buffer, bufferSize));
            }
        }
        public void StopRecording(Action callback)
        {
            Logger.Debug("Channel mapping: " + (channelMapping == null));
            if (channelMapping == null)
            {
                return;
            }

            foreach (var target in channelMapping.Values)
            {
                currentTake.SetMetadata(target.Name, target);
            }
#if UNITY_EDITOR
            StartCoroutine(Bake(() => {
                if (callback != null)
                {
                    callback();
                }
                state = CaptureState.Live;
            }));
#endif
        }
        public bool DeleteCumulativeIntervals(CaptureState marked)
        {
            bool success = false;

            bool Marked = marked == CaptureState.Marked ? true : false;

            // Delete the cumulative interval counts for a marked type
            using(var context = new PacketAnalysisEntity())
            {
                var rowCount = (from c in context.CumulativeIntervals
                                where c.Marked == Marked
                                select c.CumulativeIntervalNumber).Count();

                if (rowCount > 0)
                {
                    var deleteParameter = new SqlParameter("@Marked", Marked);
                    var retval = new SqlParameter("@RowsDeleted", SqlDbType.Int);
                    retval.Value = 0;
                    retval.Direction = ParameterDirection.Output;

                    var result = context.Database
                        .SqlQuery<CumulativeInterval>("[COWE].[CumulativeIntervalDelete] @Marked, @RowsDeleted out", deleteParameter, retval);
                    //context.Database.ExecuteSqlCommand("exec @retval = [COWE].[CumulativeIntervalDelete] @Marked", retval, deleteParameter);

                    //var rows = result.Single();

                    ////if (result.Count() == rowCount)
                    //if ((int)retval.Value == (int)rowCount)
                    //{
                    //    success = true;
                    //}
                }
            }

            return success;
        }
示例#41
0
        public void StopPlaybackWithVideo()
        {
            state = CaptureState.None;

            if(Movie != null){
            Movie.Pause();
            Movie.PositionSeconds = 0;
            }

            if (OnStopPlayback != null) OnStopPlayback();
        }
示例#42
0
        public void StopPlayback()
        {
            state = CaptureState.Live;

            if (OnStopPlayback != null) OnStopPlayback();
        }
示例#43
0
        public void StartRecordingFromVideo()
        {
            state = CaptureState.RecordingFromVideo;
            currentTake = new Recording();

            StartCoroutine(RecordFromVideo());

            if (OnStartRecording != null) OnStartRecording();
        }
示例#44
0
        public void StartRecording()
        {
            Logger.Debug ("Channel mapping is null: " + (channelMapping == null));
            state = CaptureState.Recording;
            currentTake = new Recording();
            t = 0f;

            if (OnStartRecording != null) OnStartRecording();
        }
示例#45
0
        public void CalculateCumulativeProbabilityDistribution(CaptureState captureState)
        {
            // Note: cumulative histogram intervals must have previously been calculated in order to calculate cumulative probabilities

            //SortedDictionary<int, decimal> _CumulativeMarkedProbabilities = new SortedDictionary<int, decimal>();
            //SortedDictionary<int, decimal> _CumulativeUnmarkedProbabilities = new SortedDictionary<int, decimal>();

            //_CumulativeMarkedProbabilities = new CalculateProbability(batchIntervals).GetProbabilityByPacketRange(_TrimZeroPacketIntervals, histogramBinSize);

            // Get the batch intervals
            BindingList<BatchIntervalMarked> unmarkedBatchIntervals = new BindingList<BatchIntervalMarked>();
            BindingList<BatchIntervalMarked> markedBatchIntervals = new BindingList<BatchIntervalMarked>();
            BindingList<CumulativeProbabilityDistribution> distribution = new BindingList<CumulativeProbabilityDistribution>();
            //CumulativeProbabilityDistributionData cumProbDistData = new CumulativeProbabilityDistributionData();

            using (var uow = new UnitOfWorkCumulativeProbability())
            {
                //using (var cpdRepository = new CumulativeProbabilityDistributionRepository(new UnitOfWorkCumulativeProbability()))
                using (var cpdRepository = new CumulativeProbabilityDistributionRepository(uow))
                {
                    //// Delete any existing cumulative probability distribution data for the captureState
                    //cumProbDistData.DeleteCumulativeProbabilityDistribution(captureState);

                    cpdRepository.DeleteBatch(captureState);

                    // Add the newly calculated cumulative probability distribution
                    switch (captureState)
                    {
                        case CaptureState.Marked:
                            if (_CumulativeMarkedProbabilities != null)
                            {
                                SortedDictionary<int, decimal> markedProbabilities = new CalculateProbability(markedBatchIntervals).GetCumulativeProbabilityDistribution(_CumulativeMarkedProbabilities);

                                // Convert to CumulativeProbabilityDistribution type
                                foreach (KeyValuePair<int, decimal> item in markedProbabilities)
                                {
                                    CumulativeProbabilityDistribution cpd = new CumulativeProbabilityDistribution();
                                    cpd.CaptureState = (int)CaptureState.Marked;
                                    cpd.Interval = item.Key;
                                    cpd.Probability = Math.Round(item.Value, 10);
                                    //distribution.Add(cpd);
                                    cpdRepository.InsertOrUpdate(cpd);
                                    uow.Save();
                                }
                            }
                            //// Save to database
                            //cumProbDistData.InsertCumulativeProbabilityDistribution(distribution);
                            break;

                        case CaptureState.Unmarked:
                            if (_CumulativeUnmarkedProbabilities != null)
                            {
                                SortedDictionary<int, decimal> unmarkedProbabilities = new CalculateProbability(unmarkedBatchIntervals).GetCumulativeProbabilityDistribution(_CumulativeUnmarkedProbabilities);

                                // Convert to CumulativeProbabilityDistribution type
                                foreach (KeyValuePair<int, decimal> item in unmarkedProbabilities)
                                {
                                    CumulativeProbabilityDistribution cpd = new CumulativeProbabilityDistribution();
                                    cpd.CaptureState = (int)CaptureState.Unmarked;
                                    cpd.Interval = item.Key;
                                    //cpd.Probability = Convert.ToDecimal(String.Format("{0,10}", item.Value.ToString("D")));
                                    cpd.Probability = Math.Round(item.Value, 10);
                                    //distribution.Add(cpd);
                                    cpdRepository.InsertOrUpdate(cpd);
                                    uow.Save();
                                }

                            }
                            //// Save to database
                            //cumProbDistData.InsertCumulativeProbabilityDistribution(distribution);
                            break;
                    }
                }
            }
        }
示例#46
0
 IEnumerator Bake(Action callback)
 {
     state = CaptureState.BakingAnimation;
     yield return StartCoroutine(currentTake.Bake ());
     Logger.Info ("Finished recording of length: " + (currentTake.BakeTime - currentTake.CreationTime));
     Logger.Info ("Number of channels: " + currentTake.ChannelCount);
     Logger.Info ("Number of frames: " + currentTake.GetChannel(currentTake.ChannelNames.First()).keyframes.Count);
     if (callback != null) callback();
     if (OnStopRecording != null) OnStopRecording();
 }
示例#47
0
 private void CaptureThread(AudioClient client)
 {
     Exception exception = null;
     try
     {
         DoRecording(client);
     }
     catch (Exception e)
     {
         exception = e;
     }
     finally
     {
         client.Stop();
         // don't dispose - the AudioClient only gets disposed when WasapiCapture is disposed
     }
     captureThread = null;
     captureState = CaptureState.Stopped;
     RaiseRecordingStopped(exception);
 }
示例#48
0
        public void StopRecording(Action callback)
        {
            Logger.Debug ("Channel mapping: " + (channelMapping == null));
            if (channelMapping == null) return;

            foreach(var target in channelMapping.Values) {
            currentTake.SetMetadata(target.Name, target);
            }
            #if UNITY_EDITOR
            StartCoroutine(Bake (()=>{
            if (callback != null) callback();
            state = CaptureState.Live;
            }));
            #endif
        }
示例#49
0
        public bool CalculateSingleBatchStatistics()
        {
            bool result = false;

            // Calculate single batch statistics
            //// Get the last marked and unmarked batches and add them to the graph
            //int lastBatchId = 0;
            ProcessCapturePackets pcp = new ProcessCapturePackets();
            //lastBatchId = pcp.GetLastCaptureBatchId();
            CurrentCaptureFile captureFile = new CurrentCaptureFile();
            CaptureFileData cfd = new CaptureFileData();
            //captureFile = cfd.GetLastCaptureBatchRecord();
            captureFile = cfd.GetCurrentCaptureFile(_CaptureFileName);

            // Set the global variable
            _CaptureState = captureFile.CaptureState;

            BindingList<BatchIntervalMarked> batchIntervals = new BindingList<BatchIntervalMarked>();

            // Calculate probabilities
            batchIntervals = pcp.GetMarkedBatchIntervals(captureFile.CaptureBatchId);
            int histogramBinSize = Convert.ToInt32(_HistogramBinSize);
            SortedDictionary<int, decimal> probabilities = new CalculateProbability(batchIntervals).GetProbabilityByPacketRange(_TrimZeroPacketIntervals, histogramBinSize);

            BatchStatistics markedSingleStats = new BatchStatistics();
            BatchStatistics unmarkedSingleStats = new BatchStatistics();

            // Add the results to the DisplayStatistics table
            DisplayStatisticsData dsd = new DisplayStatisticsData();
            if(captureFile.CaptureState == CaptureState.Marked)
            {
                markedSingleStats = CalculateBatchStatistics(batchIntervals, CaptureState.Marked, BatchType.Single);
            }
            else
            {
                unmarkedSingleStats = CalculateBatchStatistics(batchIntervals, CaptureState.Unmarked, BatchType.Single);
            }
            return result;
        }
示例#50
0
        public BatchStatistics CalculateBatchStatistics(BindingList<BatchIntervalMarked> batchIntervals, CaptureState captureState, BatchType batchType)
        {
            decimal batchIntervalsMean = 0;
            decimal batchIntervalsTrimmedMean = 0;

            // Trim zero packets from the batch interval
            BindingList<BatchIntervalMarked> batchIntervalsTrimmed = new BindingList<BatchIntervalMarked>();
            foreach (BatchIntervalMarked bim in batchIntervals)
            {
                if (bim.PacketCount > AnalysisConfiguration.HistogramBinSize)
                {
                    batchIntervalsTrimmed.Add(bim);
                }
            }

            // Calculate statistics for the batch
            BatchStatistics bs = new BatchStatistics();

            if (AnalysisConfiguration.TrimSmallPackets)
            {
                BaseStatistics stats = new BaseStatistics(batchIntervalsTrimmed);
                bs.IntervalCountTrimmed = stats.Count;
                bs.PacketCountMaximum = stats.Maximum;
                bs.PacketCountMinimum = stats.Minimum;
                bs.PacketCountMean = stats.Mean;
                bs.PacketCountStandardDeviation = stats.StdDev;

                // Calculate both means for updating the capture batch intervals
                batchIntervalsTrimmedMean = stats.Mean;
                batchIntervalsMean = Convert.ToDecimal((from t in batchIntervals select t.PacketCount).Average());

                // Get both counts for the batch
                bs.IntervalCountTrimmed = stats.Count < 0 ? 0 : stats.Count;
                bs.IntervalCount = batchIntervals.Count < 0 ? 0 : batchIntervals.Count;
            }
            else
            {
                BaseStatistics stats = new BaseStatistics(batchIntervals);
                bs.IntervalCount = stats.Count;
                bs.PacketCountMaximum = stats.Maximum;
                bs.PacketCountMinimum = stats.Minimum;
                bs.PacketCountMean = stats.Mean;
                bs.PacketCountStandardDeviation = stats.StdDev;

                // Calculate both means for updating the capture batch intervals
                batchIntervalsMean = bs.PacketCountMean;
                batchIntervalsTrimmedMean = Convert.ToDecimal((from t in batchIntervalsTrimmed select t.PacketCount).Average());

                // Get both counts for the batch
                bs.IntervalCount = stats.Count < 0 ? 0 : stats.Count;
                bs.IntervalCountTrimmed = batchIntervalsTrimmed.Count < 0 ? 0 : batchIntervalsTrimmed.Count;
            }

            // Update the batch mean - only for single batches, not cumulative batches
            CurrentCaptureFile captureFile = new CurrentCaptureFile();
            ProcessCapturePackets pcp = new ProcessCapturePackets();
            captureFile = pcp.GetCurrentCaptureFile(_CaptureFileName);
            int captureBatchId = captureFile.CaptureBatchId;

            if (batchType == BatchType.Single && captureBatchId != 0)
            {
                try
                {
                    //ProcessCapturePackets pcp = new ProcessCapturePackets();
                    //if (!pcp.UpdateBatchMean(Convert.ToInt32(captureBatchId), bs.PacketCountMean))
                    if (!pcp.UpdateBatchMean(Convert.ToInt32(captureBatchId), batchIntervalsMean, batchIntervalsTrimmedMean))
                    {
                        throw new Exception("Error updating batch mean for CaptureBatchId " + captureBatchId);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Error updating batch mean for CaptureBatchId " + captureBatchId + ": " + ex.Message);
                }
            }

            // Save the statistics to the database for display on the Analysis tab (save to DisplayStatistics table)
            SaveDisplayStatistics(bs, captureBatchId, captureState, batchType, true);

            return bs;
        }
示例#51
0
        private void CalculateCumulativeHistogramProbability(BindingList<BatchIntervalMarked> batchIntervalsCollection, BatchType batchType, CaptureState captureState)
        {
            BindingList<BatchIntervalMarked> batchIntervals = new BindingList<BatchIntervalMarked>();
            batchIntervals = batchIntervalsCollection;

            SortedDictionary<int, decimal> histogramProbabilities = new SortedDictionary<int, decimal>();

            int histogramBinSize = AnalysisConfiguration.HistogramBinSize;
            histogramProbabilities = new CalculateProbability(batchIntervals).GetProbabilityByPacketRange(_TrimZeroPacketIntervals, histogramBinSize);

            // Update the cumulative intervals for calculating cumulative probability distributions
            switch(captureState)
            {
                case CaptureState.Marked:
                    _CumulativeMarkedProbabilities = histogramProbabilities;
                    break;

                case CaptureState.Unmarked:
                    _CumulativeUnmarkedProbabilities = histogramProbabilities;
                    break;
            }

            // Convert histogram probabilities to Histogram type collection
            BindingList<CumulativeHistogram> cumulativeHistogramProbabilityData = new BindingList<CumulativeHistogram>();
            foreach (KeyValuePair<int, decimal> data in histogramProbabilities)
            {
                CumulativeHistogram h = new CumulativeHistogram();
                h.Interval = data.Key;
                h.Probability = data.Value;
                h.BatchType = Convert.ToInt32(batchType);
                h.CaptureState = Convert.ToInt32(captureState);
                cumulativeHistogramProbabilityData.Add(h);
            }

            // Save histogram data
            CumulativeHistogramData chd = new CumulativeHistogramData(cumulativeHistogramProbabilityData);
            chd.InsertCumulativeHistogramData();
        }
示例#52
0
 public void SaveDisplayStatistics(BatchStatistics batchStatistics, int captureBatchId, CaptureState captureState, BatchType batchType, bool saveData)
 {
     // Save the statistics to the database for display on the Analysis tab (save to DisplayStatistics table)
     // Replace cumulative data with new data
     DisplayStatisticsData dsd = new DisplayStatisticsData();
     switch (captureState)
     {
         case CaptureState.Marked:
             switch (batchType)
             {
                 case BatchType.Single:
                     //dsd.DeleteSingleMarkedDisplayStatitics();
                     dsd.InsertSingleMarkedDisplayStatitics(batchStatistics);
                     dsd.UpdateDisplayStatsSavedFlag(captureBatchId, BatchType.Single, true);
                     break;
                 case BatchType.Cumulative:
                     dsd.DeleteCumulativeMarkedDisplayStatitics();
                     dsd.InsertCumulativeMarkedDisplayStatitics(batchStatistics);
                     dsd.UpdateDisplayStatsSavedFlag(captureBatchId, BatchType.Cumulative, true);
                     break;
             }
             break;
         case CaptureState.Unmarked:
             switch (batchType)
             {
                 case BatchType.Single:
                     //dsd.DeleteSingleUnmarkedDisplayStatitics();
                     dsd.InsertSingleUnarkedDisplayStatitics(batchStatistics);
                     dsd.UpdateDisplayStatsSavedFlag(captureBatchId, BatchType.Single, true);
                     break;
                 case BatchType.Cumulative:
                     dsd.DeleteCumulativeUnmarkedDisplayStatitics();
                     dsd.InsertCumulativeUnarkedDisplayStatitics(batchStatistics);
                     dsd.UpdateDisplayStatsSavedFlag(captureBatchId, BatchType.Cumulative, true);
                     break;
             }
             break;
     }
 }
示例#53
0
        public void StopRecordingFromVideo(Action callback)
        {
            if (channelMapping == null) {
            Debug.LogError ("Channel Mapping is null.");
            return;
            }

            foreach(var target in channelMapping.Values) {
            currentTake.SetMetadata(target.Name, target);
            }

            Movie.Pause ();
            #if UNITY_EDITOR
            StartCoroutine(Bake(() => {
            if (callback != null) callback();
            state = CaptureState.None;
            Movie.Rewind ();
            }));
            #endif
        }
示例#54
0
 /// <summary>
 /// Stop Capturing (requests a stop, wait for RecordingStopped event to know it has finished)
 /// </summary>
 public void StopRecording()
 {
     if (captureState != CaptureState.Stopped)
         captureState = CaptureState.Stopping;
 }
示例#55
0
 /// <summary>
 /// Start Capturing
 /// </summary>
 public void StartRecording()
 {
     if (captureState != CaptureState.Stopped)
     {
         throw new InvalidOperationException("Previous recording still in progress");
     }
     captureState = CaptureState.Starting;
     InitializeCaptureDevice();
     ThreadStart start = () => CaptureThread(audioClient);
     captureThread = new Thread(start);
     captureThread.Start();
 }
示例#56
0
        public void StartLiveTracking()
        {
            //Debug.Log ("Start Live Tracking");
            Logger.Log ("FacePlus connectivity: " + (FacePlus.Echo (123) == 123 ? "Pass" : "FAIL"));
            Logger.Log ("FacePlus initializing...");
            //Logger.Log ("Initializing with: " + "VGA@CAM" + FacePlus.DeviceID.ToString ());

            FacePlus.Init ("VGA@CAM"+FacePlus.DeviceID.ToString());
            Live = true;

            float startTime = Time.time;
            StartCoroutine (FacePlus.AfterInit((bool success) => {
            float timePassed = Time.time - startTime;
            Logger.Info ("FacePlus completed initialization.");
            Logger.Log ("FacePlus initialized (success: "+success+") in " + timePassed + "s");

            if (success) {
                Live = true;
                state = CaptureState.Live;
                Logger.Debug ("starting tracking thread");
                FacePlus.TrackForeverThreaded();
                Logger.Debug ("done starting tracking thread");

            } else {
                Live = false;
            }
            }));
        }
 public CumulativeHistogramData(CaptureState captureState)
 {
     this._CaptureState = captureState;
 }
示例#58
0
        public void StartPlayback()
        {
            t = 0f;
            state = CaptureState.Playing;

            if (OnStartPlayback != null) OnStartPlayback();
        }
示例#59
0
        public void StartPlaybackWithVideo()
        {
            state = CaptureState.PlayingWithVideo;

            if(Movie == null) return;

            Movie.Play();
            Movie.PositionSeconds = 0;

            if (OnStartPlayback != null) OnStartPlayback();
        }
示例#60
0
        private void DoRecording(AudioClient client)
        {
            //Debug.WriteLine(String.Format("Client buffer frame count: {0}", client.BufferSize));
            int bufferFrameCount = client.BufferSize;

            // Calculate the actual duration of the allocated buffer.
            long actualDuration = (long)((double)ReftimesPerSec *
                             bufferFrameCount / waveFormat.SampleRate);
            int sleepMilliseconds = (int)(actualDuration / ReftimesPerMillisec / 2);
            int waitMilliseconds = (int)(3 * actualDuration / ReftimesPerMillisec);

            var capture = client.AudioCaptureClient;
            client.Start();
            captureState = CaptureState.Capturing;
            while (captureState == CaptureState.Capturing)
            {
                bool readBuffer = true;
                if (isUsingEventSync)
                {
                    readBuffer = frameEventWaitHandle.WaitOne(waitMilliseconds, false);
                }
                else
                {
                    Thread.Sleep(sleepMilliseconds);
                }
                if (captureState != CaptureState.Capturing)
                    break;

                // If still recording and notification is ok
                if (readBuffer)
                {
                    ReadNextPacket(capture);
                }
            }
        }