Esempio n. 1
0
        public int GetNumOfFrames(Guid typeId)
        {
            int numFrames = 0;

            try
            {
                using (KStudioClient client = KStudio.CreateClient(KStudioClientFlags.ProcessNotifications))
                {
                    ManualResetEvent mr = new ManualResetEvent(false);
                    KStudioEventStreamSelectorCollection selEvents = new KStudioEventStreamSelectorCollection();
                    selEvents.Add(typeId);
                    //This is where you will intercept steps in the XEF file
                    using (var reader = client.CreateEventReader(_path, selEvents))
                    {
                        KStudioEvent ev;
                        reader.GetNextEvent();
                        while ((ev = reader.GetNextEvent()) != null)
                        {
                            numFrames++;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (e.Message == "Operation is not valid due to the current state of the object.")
                {
                    throw new Exception($"No events of type {typeId} in this XEF file!");
                }
            }
            return(numFrames);
        }
        private void PlayClip(string filePath, bool startpaused)
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();

                KStudioPlaybackFlags flags = KStudioPlaybackFlags.IgnoreOptionalStreams;
                try
                {
                    playback = client.CreatePlayback(filePath, flags);
                }
                catch (Exception ex)
                {
                    FLogger.Log(LogType.Debug, ex.ToString());
                }
                using (playback)
                {
                    playback.PropertyChanged += Playback_PropertyChanged;
                    playback.StateChanged    += Playback_StateChanged;

                    playback.LoopCount              = 0;
                    playback.InPointByRelativeTime  = TimeSpan.FromSeconds(FInputInPoint[0]);
                    playback.OutPointByRelativeTime = TimeSpan.FromSeconds(Math.Min(FInputOutPoint[0], playback.Duration.TotalSeconds));
                    var kStudioMetadata = playback.GetMetadata(KStudioMetadataType.Public);

                    if (startpaused)
                    {
                        playback.StartPaused();
                    }
                    else
                    {
                        playback.Start();
                    };

                    FRecordTotalDuration[0] = playback.Duration.TotalSeconds;

                    while ((playback.State == KStudioPlaybackState.Playing) || (playback.State == KStudioPlaybackState.Paused) && (doPlay))
                    {
                        if (doStep)
                        {
                            if ((playback.State == KStudioPlaybackState.Playing))
                            {
                                playback.Pause();
                            }
                            if (playback.State == KStudioPlaybackState.Paused)
                            {
                                playback.StepOnce();
                                Thread.Sleep(20);
                            }
                            doStep = false;
                        }
                        Thread.Sleep(20);
                    }
                    playback.Stop();
                }

                playback = null;
                client.DisconnectFromService();
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Records a new .xef file
        /// </summary>
        /// <param name="filePath">Full path to where the file should be saved to</param>
        private void RecordClip(string filePath)
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();

                // Specify which streams should be recorded
                KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();
                streamCollection.Add(KStudioEventStreamDataTypeIds.Ir);
                streamCollection.Add(KStudioEventStreamDataTypeIds.Depth);
                streamCollection.Add(KStudioEventStreamDataTypeIds.Body);
                streamCollection.Add(KStudioEventStreamDataTypeIds.BodyIndex);

                // Create the recording object
                using (KStudioRecording recording = client.CreateRecording(filePath, streamCollection))
                {
                    recording.StartTimed(this.duration);
                    while (recording.State == KStudioRecordingState.Recording)
                    {
                        Thread.Sleep(500);
                    }
                }

                client.DisconnectFromService();
            }

            // Update UI after the background recording task has completed
            this.isRecording = false;
            this.Dispatcher.BeginInvoke(new NoArgDelegate(UpdateState));
        }
Esempio n. 4
0
        public void PlaybackClip()
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();

                using (KStudioPlayback playback = client.CreatePlayback(filePath))
                {
                    playback.LoopCount = loopCount;
                    playback.Start();

                    while (done == false && playback.State == KStudioPlaybackState.Playing)
                    {
                        Thread.Sleep(30);
                    }

                    if (playback.State == KStudioPlaybackState.Error)
                    {
                        throw new InvalidOperationException("Error: Playback failed!");
                    }

                    playback.Stop();
                    // Reset the value of done
                    done = false;
                }

                client.DisconnectFromService();
            }
        }
        public void GetDepthArrayTest()
        {
            string[] files = Directory.GetFiles("C:\\KStudioRepo", "*.xef");
            using (KStudioClient client = KStudio.CreateClient()) {
                client.ConnectToService();
                using (KStudioPlayback playback = client.CreatePlayback(files[0])) {
                    playback.Start();
                    DepthStream stream = DepthStream.Instance;
                    Assert.IsNotNull(stream);

                    while (playback.State == KStudioPlaybackState.Playing)
                    {
                        System.Threading.Thread.Sleep(500);
                        DFrame frame = (DFrame)stream.GetFrame();
                        if (frame != null)
                        {
                            //ushort[] testArr = frame.GetDepthArray();
                            //System.Diagnostics.////Debug.WriteLine("Test Arr length : " + testArr.Length);
                            //Assert.IsNotNull(testArr);
                        }
                    }

                    Assert.AreNotEqual(playback.State, KStudioPlaybackState.Error);
                }
                client.DisconnectFromService();
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Plays back a .xef file to the Kinect sensor
        /// </summary>
        /// <param name="filePath">Full path to the .xef file that should be played back to the sensor</param>
        private void PlaybackClip(string filePath)
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();

                // Create the playback object
                using (KStudioPlayback playback = client.CreatePlayback(filePath))
                {
                    playback.LoopCount = this.loopCount;
                    playback.Start();

                    while (playback.State == KStudioPlaybackState.Playing)
                    {
                        Thread.Sleep(500);
                    }
                }

                client.DisconnectFromService();
            }

            // Update the UI after the background playback task has completed
            this.isPlaying = false;
            this.Dispatcher.BeginInvoke(new NoArgDelegate(UpdateState));
        }
Esempio n. 7
0
 /// <summary>
 /// 播放xef视频
 /// </summary>
 /// <param name="filePath">xef视频路径</param>
 public void PlaybackClip(object filePath)
 {
     ///以前的方法,不能加骨骼上去
     #region
     using (KStudioClient PlayClient = KStudio.CreateClient())
     {
         PlayClient.ConnectToService();
         using (KStudioPlayback playback = PlayClient.CreatePlayback((string)filePath))
         {
             playback.LoopCount = 0;
             playback.Start();
             Flag2 = 0;
             while (playback.State == KStudioPlaybackState.Playing)
             {
             }
             if (playback.State == KStudioPlaybackState.Error)
             {
                 Flag2 = 1;
                 throw new InvalidOperationException("Error: Playback failed!");
             }
             Flag2 = 1;
             playback.Stop();
             playback.Dispose();
         }
         PlayClient.DisconnectFromService();
         System.Windows.Forms.MessageBox.Show("回放结束");
     }
     #endregion
 }
Esempio n. 8
0
        public void GetVideoBitmapTest()
        {
            string[] files = Directory.GetFiles("C:\\KStudioRepo", "*.xef");
            using (KStudioClient client = KStudio.CreateClient()) {
                client.ConnectToService();
                using (KStudioPlayback playback = client.CreatePlayback(files[0])) {
                    playback.Start();
                    VideoStream stream = VideoStream.Instance;
                    Assert.IsNotNull(stream);

                    while (playback.State == KStudioPlaybackState.Playing)
                    {
                        System.Threading.Thread.Sleep(500);
                        VFrame frame = (VFrame)stream.GetFrame();
                        if (frame == null)
                        {
                            continue;
                        }
                        WriteableBitmap bmp = frame.GetBitmap();
                        Assert.IsNotNull(bmp);
                    }

                    Assert.AreNotEqual(playback.State, KStudioPlaybackState.Error);
                }
            }
        }
Esempio n. 9
0
        public T[] LoadFrame <T>(int desiredFrameNum, Guid eventType, Func <KStudioEvent, T[]> pixelCopyOperation)
        {
            T[] pixels = null;

            using (KStudioClient client = KStudio.CreateClient(KStudioClientFlags.ProcessNotifications))
            {
                KStudioEventStreamSelectorCollection selEvents = new KStudioEventStreamSelectorCollection();
                selEvents.Add(eventType);

                //This is where you will intercept steps in the XEF file
                using (var reader = client.CreateEventReader(_path, selEvents))
                {
                    KStudioEvent ev;
                    reader.GetNextEvent();
                    int frameNum = 0;
                    while ((ev = reader.GetNextEvent()) != null)
                    {
                        if (frameNum == desiredFrameNum)
                        {
                            pixels = pixelCopyOperation(ev);
                            break;
                        }
                        frameNum++;
                    }
                }
            }
            return(pixels);
        }
Esempio n. 10
0
        private void PlayClip(string filePath)
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();


                KStudioPlaybackFlags flags = KStudioPlaybackFlags.IgnoreOptionalStreams;
                playback = client.CreatePlayback(filePath, flags);
                using (playback)
                {
                    playback.PropertyChanged += Recording_PropertyChanged;
                    playback.StateChanged    += Playback_StateChanged;
                    playback.LoopCount        = 10000;
                    playback.Start();

                    FRecordTotalDuration[0] = playback.Duration.TotalSeconds;

                    while ((playback.State == KStudioPlaybackState.Playing) || (playback.State == KStudioPlaybackState.Paused) && (doPlay))
                    {
                        Thread.Sleep(50);
                    }
                    playback.Stop();
                }
                client.DisconnectFromService();
            }
        }
Esempio n. 11
0
        public static void PlaybackClip(string filePath, uint loopCount)
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();

                using (KStudioPlayback playback = client.CreatePlayback(filePath))
                {
                    playback.LoopCount = loopCount;
                    playback.Start();

                    while (playback.State == KStudioPlaybackState.Playing)
                    {
                        Thread.Sleep(500);
                    }

                    if (playback.State == KStudioPlaybackState.Error)
                    {
                        throw new InvalidOperationException("Error: Playback failed!");
                    }
                }

                client.DisconnectFromService();
            }
        }
Esempio n. 12
0
        public void VFrameTest_LT_1Sec()
        {
            string[] files = Directory.GetFiles("C:\\KStudioRepo", "*.xef");
            Array.Sort(files);
            using (KStudioClient client = KStudio.CreateClient()) {
                client.ConnectToService();
                var broken = false;
                using (KStudioPlayback playback = client.CreatePlayback(files[0])) {
                    //Console.WriteLine("Playing: {0}", files[0]);
                    playback.Start();
                    Stopwatch time = new Stopwatch();

                    VideoStream stream = VideoStream.Instance;

                    while (playback.State == KStudioPlaybackState.Playing)
                    {
                        time.Start();
                        BaseFrame frame = stream.GetFrame();
                        if (time.ElapsedMilliseconds > (1 * 1000))
                        {
                            if (frame == null)
                            {
                                broken = true;
                                System.DateTime now = DateTime.Now;
                                //System.Diagnostics.////Debug.WriteLine("Failed at: {0}:{1}:{2}:{3}", now.Hour, now.Minute, now.Second, now.Millisecond);
                            }
                        }
                        Thread.Sleep(150);
                    }
                }

                client.DisconnectFromService();
                Assert.IsFalse(broken, "The frame should not be null after 1 second");
            }
        }
Esempio n. 13
0
        ///// <summary>
        ///// Function used to store raw data from kinect
        ///// </summary>
        ///// <param name="filePath">path of the recording file</param>
        ///// <param name="duration">duration of the recording in seconds</param>
        //public void RecordData(string filePath, TimeSpan duration)
        //{

        //    using (KStudioClient client = KStudio.CreateClient())
        //    {
        //        client.ConnectToService();

        //        KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();
        //        streamCollection.Add(KStudioEventStreamDataTypeIds.Ir);
        //        streamCollection.Add(KStudioEventStreamDataTypeIds.Depth);
        //        streamCollection.Add(KStudioEventStreamDataTypeIds.Body);

        //        using (KStudioRecording recording = client.CreateRecording(filePath, streamCollection))
        //        {

        //            recording.StartTimed(duration);
        //            while (recording.State == KStudioRecordingState.Recording)
        //            {
        //                Thread.Sleep(500);
        //            }

        //            if (recording.State == KStudioRecordingState.Error)
        //            {
        //                throw new InvalidOperationException("Error: Recording failed!");
        //            }
        //        }

        //        client.DisconnectFromService();
        //    }
        //}

        /// <summary>
        /// Function used to store raw data from kinect
        /// </summary>
        /// <param name="filePath">path of the recording file</param>
        public void RecordData(string filePath)
        {
            _keepRecording = true;
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();

                KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();
                streamCollection.Add(KStudioEventStreamDataTypeIds.Ir);
                streamCollection.Add(KStudioEventStreamDataTypeIds.Depth);
                streamCollection.Add(KStudioEventStreamDataTypeIds.Body);
                //streamCollection.Add(KStudioEventStreamDataTypeIds.CompressedColor);

                using (KStudioRecording recording = client.CreateRecording(filePath, streamCollection))
                {
                    recording.Start();


                    //stopRecording.WaitOne();
                    while (_keepRecording)
                    {
                        Thread.Sleep(500);
                    }
                    recording.Stop();

                    if (recording.State == KStudioRecordingState.Error)
                    {
                        throw new InvalidOperationException("Error: Recording failed!");
                    }
                }

                client.DisconnectFromService();
            }
        }
        /// <summary>
        /// Function used to store raw data from kinect
        /// </summary>
        /// <param name="filePath">path of the recording file</param>
        /// <param name="duration">duration of the recording in seconds</param>
        public void RecordData(string filePath, TimeSpan duration)
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();

                KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();
                streamCollection.Add(KStudioEventStreamDataTypeIds.Ir);
                streamCollection.Add(KStudioEventStreamDataTypeIds.Depth);
                streamCollection.Add(KStudioEventStreamDataTypeIds.Body);

                using (KStudioRecording recording = client.CreateRecording(filePath, streamCollection))
                {
                    recording.StartTimed(duration);
                    while (recording.State == KStudioRecordingState.Recording)
                    {
                        Thread.Sleep(500);
                    }

                    if (recording.State == KStudioRecordingState.Error)
                    {
                        throw new InvalidOperationException("Error: Recording failed!");
                    }
                }

                client.DisconnectFromService();
            }
        }
Esempio n. 15
0
 /// <summary>
 /// Constructor
 /// </summary>
 public KinectStudio()
 {
     client  = KStudio.CreateClient();
     thread  = null;
     path    = "";
     loop    = 0;
     isPause = false;
 }
Esempio n. 16
0
        public TargetFolderBrowserData(KStudioClient client, string targetAlias, string defaultPath)
        {
            DebugHelper.AssertUIThread();

            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (String.IsNullOrWhiteSpace(targetAlias))
            {
                throw new ArgumentNullException("targetAlias");
            }

            if (String.IsNullOrWhiteSpace(defaultPath))
            {
                throw new ArgumentNullException("defaultPath");
            }

            string currentPath = null;
            string fileSpec    = null;

            if (fileSpec != null)
            {
                fileSpec = fileSpec.ToUpperInvariant();
            }

            if (String.IsNullOrWhiteSpace(currentPath))
            {
                currentPath = defaultPath;
            }

            int i = currentPath.IndexOf(Path.VolumeSeparatorChar);

            if (i >= 0)
            {
                this.drive  = currentPath.Substring(0, i + 1);
                currentPath = currentPath.Substring(i + 1);
            }
            else
            {
                this.drive = String.Empty;
            }

            if (!currentPath.StartsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                currentPath = Path.DirectorySeparatorChar.ToString() + currentPath;
            }

            this.client      = client;
            this.targetAlias = targetAlias;
            this.currentPath = currentPath;
            this.fileSpec    = fileSpec;

            Reload();
        }
        public TargetFolderBrowserData(KStudioClient client, string targetAlias, string defaultPath)
        {
            DebugHelper.AssertUIThread();

            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (String.IsNullOrWhiteSpace(targetAlias))
            {
                throw new ArgumentNullException("targetAlias");
            }

            if (String.IsNullOrWhiteSpace(defaultPath))
            {
                throw new ArgumentNullException("defaultPath");
            }

            string currentPath = null; 
            string fileSpec = null;

            if (fileSpec != null)
            {
                fileSpec = fileSpec.ToUpperInvariant();
            }

            if (String.IsNullOrWhiteSpace(currentPath))
            {
                currentPath = defaultPath;
            }

            int i = currentPath.IndexOf(Path.VolumeSeparatorChar);
            if (i >= 0)
            {
                this.drive = currentPath.Substring(0, i + 1);
                currentPath = currentPath.Substring(i + 1);
            }
            else
            {
                this.drive = String.Empty;
            }

            if (!currentPath.StartsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                currentPath = Path.DirectorySeparatorChar.ToString() + currentPath;
            }

            this.client = client;
            this.targetAlias = targetAlias;
            this.currentPath = currentPath;
            this.fileSpec = fileSpec;

            Reload();
        }
        private void RecordClip(string filePath)
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();

                KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();

                if (FInputIRStream[0])
                {
                    streamCollection.Add(KStudioEventStreamDataTypeIds.Ir);
                }
                if (FInputDepthStream[0])
                {
                    streamCollection.Add(KStudioEventStreamDataTypeIds.Depth);
                }
                streamCollection.Add(KStudioEventStreamDataTypeIds.Body);
                streamCollection.Add(KStudioEventStreamDataTypeIds.BodyIndex);
                if (FInputRGBStream[0])
                {
                    streamCollection.Add(KStudioEventStreamDataTypeIds.UncompressedColor);
                }

                recordingBufferSizeMB = (uint)FInputRecordingBufferSizeMB[0];

                recording = client.CreateRecording(filePath, streamCollection, recordingBufferSizeMB, KStudioRecordingFlags.IgnoreOptionalStreams);
                using (recording)
                {
                    recording.PropertyChanged += Recording_PropertyChanged;
                    recording.Start();

                    FRecordBufferSizeMegabytes[0] = (uint)recording.BufferSizeMegabytes;

                    while ((recording.State == KStudioRecordingState.Recording) && (doRecord))
                    {
                        Thread.Sleep(100);
                        //recording reports no values :(
                        FRecordBufferInUseSizeMegabytes[0] = recording.BufferInUseSizeMegabytes;
                    }
                    recording.Stop();

                    //wait until the recording buffer is empty
                    while (recording.BufferInUseSizeMegabytes > 0)
                    {
                        Thread.Sleep(50);
                        FRecordBufferInUseSizeMegabytes[0] = recording.BufferInUseSizeMegabytes;
                    }

                    recording.PropertyChanged -= Recording_PropertyChanged;
                }
                client.DisconnectFromService();
            }
        }
        public Task RecordClip(string filePath, TimeSpan duration)
        {
            if (IsRecording || IsPlaying)
            {
                return(null);
            }

            if (duration == TimeSpan.Zero)
            {
                duration = _maxRecordingDuration;
            }

            _stopRequested = false;
            Task t = Task.Run(() =>
            {
                _recording = true;
                using (KStudioClient client = KStudio.CreateClient())
                {
                    client.ConnectToService();

                    KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();
                    //streamCollection.Add(KStudioEventStreamDataTypeIds.Ir);
                    streamCollection.Add(KStudioEventStreamDataTypeIds.Depth);
                    streamCollection.Add(KStudioEventStreamDataTypeIds.Body);
                    streamCollection.Add(KStudioEventStreamDataTypeIds.BodyIndex);
                    streamCollection.Add(KStudioEventStreamDataTypeIds.UncompressedColor);

                    using (KStudioRecording recording = client.CreateRecording(filePath, streamCollection))
                    {
                        recording.StartTimed(duration);
                        while (recording.State == KStudioRecordingState.Recording)
                        {
                            if (_stopRequested)
                            {
                                recording.Stop();
                            }
                            Thread.Sleep(50);
                        }

                        if (recording.State == KStudioRecordingState.Error)
                        {
                            throw new InvalidOperationException("Error: Recording failed!");
                        }
                    }

                    client.DisconnectFromService();
                }
                Thread.Sleep(500);
                _recording = false;
            });

            return(t);
        }
Esempio n. 20
0
        /// <summary>
        /// Constructor with Settings
        /// </summary>
        /// <param name="path">Absolute path to clip.</param>
        /// <param name="loop">Number of times to loop.</param>
        public KinectStudio(string path, uint loop = 0)
        {
            if (!Path.IsPathRooted(path))
            {
                throw new ArgumentException("Need Enter Absolute Path to Clip", "path");
            }

            client    = KStudio.CreateClient();
            thread    = null;
            this.path = path;
            this.loop = loop;
            isPause   = false;
        }
Esempio n. 21
0
        /// <summary>
        /// Playback a list of clips
        /// </summary>
        /// <param name="filename">ObservableCollection of VideoModel objects that contains Filename of the clip to be played.</param>
        private void PlaybackClip(ObservableCollection <VideoModel> videos)
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();
                KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();
                VideoModel video;
                int        i = 0;

                while (i < videos.Count)
                {
                    video = videos[i];

                    if (!string.IsNullOrEmpty(video.Filename))
                    {
                        _status = "Playing " + video.Filename + " - " + (i + 1) + "/" + videos.Count;

                        using (KStudioPlayback playback = client.CreatePlayback(video.Filename))
                        {
                            _isPlaying = true;
                            _stop      = false;

                            // We can use playback.StartPaused() and SeekRelativeTime to start the clip at
                            // a specific time.
                            playback.Start();


                            while (playback.State == KStudioPlaybackState.Playing)
                            {
                                Thread.Sleep(150);

                                if (_stop)
                                {
                                    playback.Stop();
                                    break;
                                }
                            }

                            _isPlaying = false;

                            if (_stop)
                            {
                                return;
                            }
                        }
                    }
                    i++;
                }
                client.DisconnectFromService();
            }
        }
Esempio n. 22
0
        private void Play()
        {
            using (KStudioClient client = KStudio.CreateClient())
            {
                client.ConnectToService();


                for (int f = 0; f < fileNames.Length; f++)
                {
                    string[] nameAndLoop = fileNames[f].Split(',');
                    Dispatcher.InvokeAsync(new Action(() => this.statusBox.Text = "Playing" + nameAndLoop[0]));

                    double loopCount = 0, timeSleept = 0;

                    try
                    {
                        playback = client.CreatePlayback(nameAndLoop[0]);
                        if (nameAndLoop.Length > 1)
                        {
                            loopCount = Double.Parse(nameAndLoop[1]);
                        }
                        else
                        {
                            loopCount = 1;
                        }

                        lock (playback)
                        {
                            playback.LoopCount   = (uint)loopCount;
                            playback.EndBehavior = KStudioPlaybackEndBehavior.Stop;
                            playback.Start();
                        }

                        while (playback != null && playback.State == KStudioPlaybackState.Playing)
                        {
                            Thread.Sleep(100);
                            timeSleept += 100;
                        }
                        if (playback != null && timeSleept < playback.Duration.TotalMilliseconds)
                        {
                            MessageBox.Show("Due to an unknown failure the playback has stopped.");
                            break;
                        }
                    }
                    catch (ThreadAbortException t) {
                        Console.WriteLine(t.ToString());
                    }
                }
            }
        }
Esempio n. 23
0
        /// <summary>
        /// Verifies that the streams selected for playback exist in the file and are capable of being played on the service
        /// </summary>
        /// <param name="client">KStudioClient which is connected to the Kinect service</param>
        /// <param name="filePath">Path to file that will be played back</param>
        /// <param name="playbackStreams">Collection of streams which have been selected for playback</param>
        private static void VerifyStreamsForPlayback(KStudioClient client, string filePath, IEnumerable <Guid> playbackStreams)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (!client.IsServiceConnected)
            {
                throw new InvalidOperationException(Strings.ErrorNotConnected);
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filePath");
            }

            if (playbackStreams == null)
            {
                throw new ArgumentNullException("playbackStreams");
            }

            // verify stream exists in the file
            using (KStudioEventFile file = client.OpenEventFile(filePath))
            {
                HashSet <Guid> fileStreams = new HashSet <Guid>();
                foreach (KStudioEventStream stream in file.EventStreams)
                {
                    fileStreams.Add(stream.DataTypeId);
                }

                if (!fileStreams.IsSupersetOf(playbackStreams))
                {
                    Guid invalidStream = playbackStreams.First(x => !fileStreams.Contains(x));
                    throw new InvalidOperationException(string.Format(Strings.ErrorPlaybackStreamNotInFile, StreamSupport.ConvertStreamGuidToString(invalidStream)));
                }
            }

            // verify stream is supported for playback by the Kinect sensor
            foreach (Guid stream in playbackStreams)
            {
                KStudioEventStream eventStream = client.GetEventStream(stream, KStudioEventStreamSemanticIds.KinectDefaultSensorConsumer);
                if (!eventStream.IsPlaybackable)
                {
                    throw new InvalidOperationException(string.Format(Strings.ErrorPlaybackStreamNotSupported, StreamSupport.ConvertStreamGuidToString(stream)));
                }
            }
        }
Esempio n. 24
0
        public void StopRecording()
        {
            if (recording != null)
            {
                recording.Stop();
                recording.Dispose();
                recording = null;
            }
            if (client != null)
            {
                client.DisconnectFromService();
                client.Dispose();
                client = null;
            }

            LogConsole.WriteLine("Recording stopped");
        }
Esempio n. 25
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("ERROR: Missing filename");
                return;
            }
            if (args.Length < 2)
            {
                Console.WriteLine("ERROR: Missing output directory");
                return;
            }
            string fileName  = args[0];
            string outputDir = args[1];

            var outputDirPath = Environment.CurrentDirectory + "/" + outputDir;

            if (Directory.Exists(outputDirPath))
            {
                Directory.Delete(outputDirPath, true);
            }
            Directory.CreateDirectory(outputDirPath);
            Console.WriteLine(fileName);
            KStudioClient    client = KStudio.CreateClient();
            KStudioEventFile file   = client.OpenEventFile(fileName);

            foreach (KStudioSeekableEventStream stream in file.EventStreams)
            {
                if (stream.DataTypeName.Equals("Nui Uncompressed Color"))
                {
                    int    width     = 1920;
                    int    height    = 1080;
                    byte[] bufferYuv = new byte[width * height * 2];
                    uint   length    = stream.EventCount;
                    for (uint i = 0; i < length; i++)
                    {
                        var currentEvent = stream.ReadEvent(i);
                        currentEvent.CopyEventDataToArray(bufferYuv, 0);
                        string filePath = outputDirPath + "/" + i.ToString("D4");
                        File.WriteAllBytes(filePath, bufferYuv);
                    }
                }
            }
        }
Esempio n. 26
0
 /// <summary>
 /// 开始录制xef文件
 /// </summary>
 /// <param name="filePath">xef文件路径</param>
 public void StartRecordClip(object filePath)
 {
     try
     {
         using (KStudioClient client = KStudio.CreateClient())
         {
             client.ConnectToService();
             KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();
             //streamCollection.Add(KStudioEventStreamDataTypeIds.Ir);
             streamCollection.Add(KStudioEventStreamDataTypeIds.Depth);
             streamCollection.Add(KStudioEventStreamDataTypeIds.Body);
             streamCollection.Add(KStudioEventStreamDataTypeIds.BodyIndex);
             //streamCollection.Add(KStudioEventStreamDataTypeIds.UncompressedColor);
             using (KStudioRecording recording = client.CreateRecording((string)filePath, streamCollection))
             {
                 recording.Start();
                 SharpAvi.IsCreateRecord = true;
                 SharpAvi.IsRecording    = true;
                 while (recording.State == KStudioRecordingState.Recording)
                 {
                     //Flag为1时调出循环,结束录像
                     if (_flag == 1)
                     {
                         break;
                     }
                 }
                 SharpAvi.IsStopRecord = true;
                 recording.Stop();
                 recording.Dispose();
             }
             client.DisconnectFromService();
             client.Dispose();
             _flag = 0;
         }
     }
     catch
     {
         _flag  = 0;
         _flag1 = 1;
         SharpAvi.IsStopRecord = true;
         MessageBox.Show("视频录制出现异常");
     }
 }
Esempio n. 27
0
        public void CloseRecording()
        {
            OnRecordingStopped();

            if (playback != null)
            {
                playback.Stop();
                playback.Dispose();
                playback = null;
            }
            if (client != null)
            {
                client.DisconnectFromService();
                client.Dispose();
                client = null;
            }

            LogConsole.WriteLine("Recording stopped");
        }
Esempio n. 28
0
        public void StartRecording(string filePath)
        {
            client = KStudio.CreateClient();

            client.ConnectToService();

            KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();

            streamCollection.Add(KStudioEventStreamDataTypeIds.UncompressedColor);
            streamCollection.Add(KStudioEventStreamDataTypeIds.Depth);
            // The enum value for Audio is missing. The GUID below was taken from Kinect Studio.
            var Audio = new Guid(0x787c7abd, 0x9f6e, 0x4a85, 0x8d, 0x67, 0x63, 0x65, 0xff, 0x80, 0xcc, 0x69);

            streamCollection.Add(Audio);

            recording = client.CreateRecording(filePath, streamCollection, KStudioRecordingFlags.IgnoreOptionalStreams);
            recording.Start();

            LogConsole.WriteLine("File opened and recording ...");
        }
Esempio n. 29
0
        public void startPlayback(string filePath)
        {
            uint loopCount = 100;

            new System.Threading.Thread(() =>
            {
                using (_client = KStudio.CreateClient())
                {
                    _client.ConnectToService();

                    try
                    {
                        using (_playback = _client.CreatePlayback(filePath))
                        {
                            _playback.LoopCount = loopCount;
                            _playback.Start();

                            while (_playback.State == KStudioPlaybackState.Playing || _playback.State == KStudioPlaybackState.Paused)
                            {
                                System.Threading.Thread.Sleep(500);
                            }
                            _playback.Dispose();
                            _playback = null;
                        }
                        _client.DisconnectFromService();
                    }
                    catch (NullReferenceException)
                    {
                        Debug.WriteLine("Don't know why");
                    }
                    catch (ArgumentException)
                    {
                        Debug.WriteLine("Don't know why");
                    }
                    catch (InvalidOperationException)
                    {
                        Debug.WriteLine("Same video can't be loaded at the same time");
                    }
                }
            }).Start();
        }
Esempio n. 30
0
        /// <summary>
        /// Updates (add/edits) stream-level metadata in an event file
        /// </summary>
        /// <param name="client">KStudioClient to use for accessing the event file</param>
        /// <param name="fileName">Path to event file</param>
        /// <param name="streamName">Name of stream which should contain the metadata</param>
        /// <param name="type">Type of metadata to update (Public or Personal)</param>
        /// <param name="key">Key of metadata object to add/edit</param>
        /// <param name="value">Value of metadata object to add/edit</param>
        /// <returns>String which contains the updated contents of the target metadata object</returns>
        public static string UpdateStreamMetadata(KStudioClient client, string fileName, string streamName, KStudioMetadataType type, string key, object value)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            if (string.IsNullOrEmpty(streamName))
            {
                throw new ArgumentNullException("streamName");
            }

            string metadataText = string.Empty;

            using (KStudioEventFile file = client.OpenEventFileForEdit(fileName))
            {
                // find the stream in the file and alter its metadata
                Guid dataTypeId = StreamSupport.ConvertStreamStringToGuid(streamName);
                if (dataTypeId == KStudioEventStreamDataTypeIds.Null)
                {
                    throw new InvalidOperationException(Strings.ErrorNullStream);
                }

                KStudioEventStream stream = file.EventStreams.FirstOrDefault(s => s.DataTypeId == dataTypeId);
                if (stream != null)
                {
                    KStudioMetadata metadata = stream.GetMetadata(type);
                    Metadata.AlterMetadata(metadata, key, value);
                    metadataText = Metadata.GetMetadataAsText(metadata, type, stream.DataTypeName);
                }
            }

            return(metadataText);
        }
Esempio n. 31
0
        /// <summary>
        /// Edits file or stream-level metadata
        /// </summary>
        /// <param name="filePath">Path of file which contains metadata to edit</param>
        /// <param name="key">Key of metadata item to alter</param>
        /// <param name="value">New value to set for the metadata item</param>
        /// <param name="streamName">String which represents the stream to alter metadata for</param>
        /// <param name="updatePersonalMetadata">Value which indicates if personal metadata should be altered (default is public)</param>
        /// <param name="updateStreamMetadata">Value which indicates if stream metadata should be altered (default is file)</param>
        /// <returns>String containing updated contents of the target metadata object</returns>
        private string EditMetadata(string filePath, string key, object value, string streamName, bool updatePersonalMetadata, bool updateStreamMetadata)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filePath");
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key");
            }

            string metadataText = string.Empty;

            using (KStudioClient client = KStudio.CreateClient())
            {
                if (filePath.ToUpperInvariant().StartsWith(Strings.ConsoleClipRepository.ToUpperInvariant()))
                {
                    client.ConnectToService();
                }

                KStudioMetadataType type = KStudioMetadataType.Public;
                if (updatePersonalMetadata)
                {
                    type = KStudioMetadataType.PersonallyIdentifiableInformation;
                }

                if (updateStreamMetadata)
                {
                    metadataText = Metadata.UpdateStreamMetadata(client, filePath, streamName, type, key, value);
                }
                else
                {
                    metadataText = Metadata.UpdateFileMetadata(client, filePath, type, key, value);
                }
            }

            return(metadataText);
        }
Esempio n. 32
0
        /// <summary>
        /// Updates (adds/edits) file-level metadata in an event file
        /// </summary>
        /// <param name="client">KStudioClient to use for accessing the event file</param>
        /// <param name="fileName">Path to event file</param>
        /// <param name="type">Type of metadata (Public or Personal)</param>
        /// <param name="key">Key of metadata object to add/edit</param>
        /// <param name="value">Value of metadata object to add/edit</param>
        /// <returns>String which contains the updated contents of the target metadata object</returns>
        public static string UpdateFileMetadata(KStudioClient client, string fileName, KStudioMetadataType type, string key, object value)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            string metadataText = string.Empty;

            using (KStudioEventFile file = client.OpenEventFileForEdit(fileName))
            {
                KStudioMetadata metadata = file.GetMetadata(type);
                Metadata.AlterMetadata(metadata, key, value);
                metadataText = Metadata.GetMetadataAsText(metadata, type, string.Empty);
            }

            return metadataText;
        }
Esempio n. 33
0
        /// <summary>
        /// Records streams from the Kinect sensor to an event file
        /// </summary>
        /// <param name="client">KStudioClient which is connected to the Kinect service</param>
        /// <param name="filePath">Path to new event file which will be created for recording</param>
        /// <param name="duration">How long the recording should last before being stopped</param>
        /// <param name="streamNames">Collection of streams to include in the recording</param>
        public static void RecordClip(KStudioClient client, string filePath, TimeSpan duration, IEnumerable<string> streamNames)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (!client.IsServiceConnected)
            {
                throw new InvalidOperationException(Strings.ErrorNotConnected);
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filePath");
            }

            HashSet<Guid> streamDataTypeIds = new HashSet<Guid>();
            KStudioEventStreamSelectorCollection streamCollection = new KStudioEventStreamSelectorCollection();
            KStudioRecording recording = null;

            // decide which streams to record
            if (streamNames != null && streamNames.Count<string>() > 0)
            {
                streamDataTypeIds = StreamSupport.ConvertStreamsToGuids(streamNames);
                StreamSupport.VerifyStreamsForRecordAndPlayback(streamDataTypeIds);
            }
            else
            {
                if (Path.GetExtension(filePath).ToLower().Equals(Strings.XrfExtension))
                {
                    streamDataTypeIds.Add(KStudioEventStreamDataTypeIds.RawIr);
                }
                else
                {
                    streamDataTypeIds.Add(KStudioEventStreamDataTypeIds.Ir);
                    streamDataTypeIds.Add(KStudioEventStreamDataTypeIds.Depth);
                    streamDataTypeIds.Add(KStudioEventStreamDataTypeIds.Body);
                    streamDataTypeIds.Add(KStudioEventStreamDataTypeIds.BodyIndex);
                }
            }

            // verify streams are recordable by the Kinect sensor
            foreach (Guid stream in streamDataTypeIds)
            {
                KStudioEventStream eventStream = client.GetEventStream(stream, KStudioEventStreamSemanticIds.KinectDefaultSensorProducer);
                if (!eventStream.IsRecordable)
                {
                    throw new InvalidOperationException(string.Format(Strings.ErrorRecordingStreamNotSupported, StreamSupport.ConvertStreamGuidToString(stream)));
                }

                streamCollection.Add(stream);
            }

            // fix file extension, if necessary
            if (streamDataTypeIds.Contains(KStudioEventStreamDataTypeIds.RawIr) && Path.GetExtension(filePath).ToUpperInvariant().Equals(Strings.XefExtension.ToUpperInvariant()))
            {
                Path.ChangeExtension(filePath, Strings.XrfExtension);
            }

            // attempt to record streams for the specified duration
            try
            {
                recording = client.CreateRecording(filePath, streamCollection);
            }
            catch (Exception)
            {
                //K4W supports uncompressed and compressed color, so if we get an error, try recording the other type
                streamCollection = StreamSupport.CreateStreamCollection(streamDataTypeIds, true);
                recording = client.CreateRecording(filePath, streamCollection);
            }

            using (recording)
            {
                recording.StartTimed(duration);
                while (recording.State == KStudioRecordingState.Recording)
                {
                    Thread.Sleep(500);
                }

                if (recording.State == KStudioRecordingState.Error)
                {
                    throw new InvalidOperationException(Strings.ErrorRecordingFailed);
                }
            }
        }
Esempio n. 34
0
        /// <summary>
        /// Verifies that the streams selected for playback exist in the file and are capable of being played on the service
        /// </summary>
        /// <param name="client">KStudioClient which is connected to the Kinect service</param>
        /// <param name="filePath">Path to file that will be played back</param>
        /// <param name="playbackStreams">Collection of streams which have been selected for playback</param>
        private static void VerifyStreamsForPlayback(KStudioClient client, string filePath, IEnumerable<Guid> playbackStreams)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (!client.IsServiceConnected)
            {
                throw new InvalidOperationException(Strings.ErrorNotConnected);
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filePath");
            }

            if (playbackStreams == null)
            {
                throw new ArgumentNullException("playbackStreams");
            }

            // verify stream exists in the file
            using (KStudioEventFile file = client.OpenEventFile(filePath))
            {
                HashSet<Guid> fileStreams = new HashSet<Guid>();
                foreach (KStudioEventStream stream in file.EventStreams)
                {
                    fileStreams.Add(stream.DataTypeId);
                }

                if (!fileStreams.IsSupersetOf(playbackStreams))
                {
                    Guid invalidStream = playbackStreams.First(x => !fileStreams.Contains(x));
                    throw new InvalidOperationException(string.Format(Strings.ErrorPlaybackStreamNotInFile, StreamSupport.ConvertStreamGuidToString(invalidStream)));
                }
            }

            // verify stream is supported for playback by the Kinect sensor
            foreach (Guid stream in playbackStreams)
            {
                KStudioEventStream eventStream = client.GetEventStream(stream, KStudioEventStreamSemanticIds.KinectDefaultSensorConsumer);
                if (!eventStream.IsPlaybackable)
                {
                    throw new InvalidOperationException(string.Format(Strings.ErrorPlaybackStreamNotSupported, StreamSupport.ConvertStreamGuidToString(stream)));
                }
            }
        }
Esempio n. 35
0
        /// <summary>
        /// Plays an event file to the Kinect service
        /// </summary>
        /// <param name="client">KStudioClient which is connected to the Kinect service</param>
        /// <param name="filePath">Path to event file which is targeted for playback</param>
        /// <param name="streamNames">Collection of streams to include in the playback session</param>
        /// <param name="loopCount">Number of times the playback should be repeated before stopping</param>
        public static void PlaybackClip(KStudioClient client, string filePath, IEnumerable<string> streamNames, uint loopCount)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (!client.IsServiceConnected)
            {
                throw new InvalidOperationException(Strings.ErrorNotConnected);
            }

            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filePath");
            }

            KStudioPlayback playback = null;

            // determine if all specified streams are valid for playback
            if (streamNames.Count<string>() > 0)
            {
                HashSet<Guid> playbackDataTypeIds = StreamSupport.ConvertStreamsToPlaybackGuids(streamNames);
                StreamSupport.VerifyStreamsForRecordAndPlayback(playbackDataTypeIds);
                Playback.VerifyStreamsForPlayback(client, filePath, playbackDataTypeIds);

                try
                {
                    KStudioEventStreamSelectorCollection streams = StreamSupport.CreateStreamCollection(playbackDataTypeIds, false);
                    playback = client.CreatePlayback(filePath, streams);
                }
                catch (Exception)
                {
                    //K4W supports uncompressed and compressed color, so if we get an error, try playing the other type
                    KStudioEventStreamSelectorCollection streams = StreamSupport.CreateStreamCollection(playbackDataTypeIds, true);
                    playback = client.CreatePlayback(filePath, streams);
                }
            }
            else
            {
                playback = client.CreatePlayback(filePath);
            }

            // begin playback
            using (playback)
            {
                playback.EndBehavior = KStudioPlaybackEndBehavior.Stop; // this is the default behavior
                playback.Mode = KStudioPlaybackMode.TimingEnabled; // this is the default behavior
                playback.LoopCount = loopCount;
                playback.Start();

                while (playback.State == KStudioPlaybackState.Playing)
                {
                    Thread.Sleep(500);
                }

                if (playback.State == KStudioPlaybackState.Error)
                {
                    throw new InvalidOperationException(Strings.ErrorPlaybackFailed);
                }
            }
        }
        public TargetOpenSaveFileData(bool save, KStudioClient client, string targetAlias, string defaultPath, string fileName, bool showReadOnly)
        {
            DebugHelper.AssertUIThread();

            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (String.IsNullOrWhiteSpace(targetAlias))
            {
                throw new ArgumentNullException("targetAlias");
            }

            if (String.IsNullOrWhiteSpace(defaultPath))
            {
                throw new ArgumentNullException("defaultPath");
            }

            this.save = save;
            this.fileName = fileName;
            this.showReadOnly = showReadOnly;

            string currentPath = null; 
            string fileSpec = null;

            IMostRecentlyUsedService mruService = ToolsUIApplication.Instance.RootServiceProvider.GetService(typeof(IMostRecentlyUsedService)) as IMostRecentlyUsedService;
            if (mruService != null)
            {
                mruService.GetTargetFileDialogSettings(targetAlias, ref currentPath, ref fileSpec, ref this.left, ref this.top, ref this.width, ref this.height, ref this.nameWidth, ref this.dateWidth, ref this.sizeWidth);
            }

            if (fileSpec != null)
            {
                fileSpec = fileSpec.ToUpperInvariant();
            }

            if (String.IsNullOrWhiteSpace(currentPath))
            {
                currentPath = defaultPath;
            }

            if (String.IsNullOrEmpty(fileSpec) || (TargetOpenSaveFileData.fileTypes.FirstOrDefault((ft) => ft.Item1 == fileSpec) == null))
            {
                fileSpec = defaultFileSpec;
            }

            int i = currentPath.IndexOf(Path.VolumeSeparatorChar);
            if (i >= 0)
            {
                this.drive = currentPath.Substring(0, i + 1);
                currentPath = currentPath.Substring(i + 1);
            }
            else
            {
                this.drive = String.Empty;
            }

            if (!currentPath.StartsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal))
            {
                currentPath = Path.DirectorySeparatorChar.ToString() + currentPath;
            }

            this.client = client;
            this.targetAlias = targetAlias;
            this.currentPath = currentPath;
            this.fileSpec = fileSpec;

            Reload();
        }
Esempio n. 37
0
 /// <summary>
 /// Initializes a new instance of the MainWindow class
 /// </summary>
 public MainWindow()
 {
     this.InitializeComponent();
     this.client = KStudio.CreateClient();
     this.DataContext = this;
 }
 public TargetOpenSaveFileData(bool save, KStudioClient client, string targetAlias, string defaultPath, bool showReadOnly)
     :this(save, client, targetAlias, defaultPath, null, showReadOnly)
 {
 }
Esempio n. 39
0
        /// <summary>
        /// Updates (add/edits) stream-level metadata in an event file
        /// </summary>
        /// <param name="client">KStudioClient to use for accessing the event file</param>
        /// <param name="fileName">Path to event file</param>
        /// <param name="streamName">Name of stream which should contain the metadata</param>
        /// <param name="type">Type of metadata to update (Public or Personal)</param>
        /// <param name="key">Key of metadata object to add/edit</param>
        /// <param name="value">Value of metadata object to add/edit</param>
        /// <returns>String which contains the updated contents of the target metadata object</returns>
        public static string UpdateStreamMetadata(KStudioClient client, string fileName, string streamName, KStudioMetadataType type, string key, object value)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName");
            }

            if (string.IsNullOrEmpty(streamName))
            {
                throw new ArgumentNullException("streamName");
            }

            string metadataText = string.Empty;

            using (KStudioEventFile file = client.OpenEventFileForEdit(fileName))
            {
                // find the stream in the file and alter its metadata
                Guid dataTypeId = StreamSupport.ConvertStreamStringToGuid(streamName);
                if (dataTypeId == KStudioEventStreamDataTypeIds.Null)
                {
                    throw new InvalidOperationException(Strings.ErrorNullStream);
                }

                KStudioEventStream stream = file.EventStreams.FirstOrDefault(s => s.DataTypeId == dataTypeId);
                if (stream != null)
                {
                    KStudioMetadata metadata = stream.GetMetadata(type);
                    Metadata.AlterMetadata(metadata, key, value);
                    metadataText = Metadata.GetMetadataAsText(metadata, type, stream.DataTypeName);
                }
            }

            return metadataText;
        }