コード例 #1
0
 private void SessionRevoked(object sender, ExtendedExecutionForegroundRevokedEventArgs args)
 {
     if (_session != null)
     {
         _session.Dispose();
         _session = null;
     }
 }
コード例 #2
0
        public MainPage()
        {
            this.InitializeComponent();
            if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.Xaml.Media.AcrylicBrush"))
            {
                Windows.UI.Xaml.Media.AcrylicBrush myBrush = new Windows.UI.Xaml.Media.AcrylicBrush();
                myBrush.BackgroundSource = Windows.UI.Xaml.Media.AcrylicBackgroundSource.HostBackdrop;
                myBrush.TintColor        = Color.FromArgb(47, 54, 64, 100);
                myBrush.FallbackColor    = Color.FromArgb(47, 54, 64, 100);
                myBrush.TintOpacity      = 0.2;
                page.Background          = myBrush;
            }
            else
            {
                SolidColorBrush myBrush = new SolidColorBrush(Color.FromArgb(255, 202, 24, 37));
                page.Background = myBrush;
            }
            ApplicationViewTitleBar formattableTitleBar = ApplicationView.GetForCurrentView().TitleBar;

            formattableTitleBar.ButtonBackgroundColor = Colors.Transparent;
            CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar;

            coreTitleBar.ExtendViewIntoTitleBar = true;
            playButton.Visibility = Visibility.Collapsed;

            newSession             = new ExtendedExecutionForegroundSession();
            newSession.Reason      = ExtendedExecutionForegroundReason.Unconstrained;
            newSession.Description = "Long Running Processing";
            newSession.Revoked    += SessionRevoked;
            newSession.RequestExtensionAsync().Completed = (e, s) =>
            {
                switch (e.GetResults())
                {
                case ExtendedExecutionForegroundResult.Allowed:
                    Debug.WriteLine("Extended session allowed");
                    break;

                default:
                case ExtendedExecutionForegroundResult.Denied:
                    Debug.WriteLine("Extended session denied");
                    break;
                }
            };
            cts      = new CancellationTokenSource();
            bgThread = new Thread(new ParameterizedThreadStart(token =>
            {
                CancellationToken ct = (CancellationToken)token;
                while (!ct.IsCancellationRequested)
                {
                    updateTrackInfo();
                    Thread.Sleep(250);
                }
            }));
            bgThread.Start(cts.Token);
            StartServer();
        }
コード例 #3
0
        private void ClearExtendedExecution()
        {
            m_mutex.WaitOne();
            if (m_session != null)
            {
                m_session.Revoked -= Session_Revoked;
                m_session.Dispose();
                m_session = null;
            }

            m_mutex.ReleaseMutex();
        }
コード例 #4
0
        private async void ExtendExecution()
        {
            var session = new ExtendedExecutionForegroundSession {
                Reason = ExtendedExecutionForegroundReason.Unspecified
            };
            var result = await session.RequestExtensionAsync();

            if (result == ExtendedExecutionForegroundResult.Allowed)
            {
                _extendedSession = session;
            }
            else
            {
                session.Dispose();
            }
        }
コード例 #5
0
        private async Task PreventFromSuspending()
        {
            ExtendedExecutionForegroundSession newSession = new ExtendedExecutionForegroundSession();
            newSession.Reason = ExtendedExecutionForegroundReason.Unconstrained;
            newSession.Revoked += SessionRevoked;

            ExtendedExecutionForegroundResult result = await newSession.RequestExtensionAsync();
            switch (result)
            {
                case ExtendedExecutionForegroundResult.Allowed:
                    _session = newSession;
                    break;
                default:
                case ExtendedExecutionForegroundResult.Denied:
                    newSession.Dispose();
                    break;
            }
        }
コード例 #6
0
        private async void ExtendedExecutionRequestAsync()
        {
            var newSession = new ExtendedExecutionForegroundSession();

            newSession.Reason      = ExtendedExecutionForegroundReason.Unconstrained;
            newSession.Description = "Long Running Processing";
            //newSession.Revoked += SessionRevoked;
            ExtendedExecutionForegroundResult result = await newSession.RequestExtensionAsync();

            switch (result)
            {
            case ExtendedExecutionForegroundResult.Allowed:
                break;

            default:
            case ExtendedExecutionForegroundResult.Denied:
                break;
            }
        }
コード例 #7
0
        private async void MediaPlayer_CurrentStateChanged(MediaPlayer sender, object args)
        {
            if (sender.PlaybackSession.PlaybackState == MediaPlaybackState.Playing)
            {
                session        = new ExtendedExecutionForegroundSession();
                session.Reason = ExtendedExecutionForegroundReason.BackgroundAudio;
                var result = await session.RequestExtensionAsync();

                if (result != ExtendedExecutionForegroundResult.Allowed)
                {
                    throw new Exception("EE denied");
                }

                IList <AppDiagnosticInfo> infos = await AppDiagnosticInfo.RequestInfoForAppAsync();

                IList <AppResourceGroupInfo> resourceInfos = infos[0].GetResourceGroups();
                await resourceInfos[0].StartSuspendAsync();
            }
        }
コード例 #8
0
        public async Task StartRecording()
        {
            StopRecording();

            m_session          = new ExtendedExecutionForegroundSession();
            m_session.Reason   = ExtendedExecutionForegroundReason.Unconstrained;
            m_session.Revoked += Session_Revoked;
            var result = await m_session.RequestExtensionAsync();

            if (result != ExtendedExecutionForegroundResult.Allowed)
            {
                Utils.Toasts.ShowToast("StartAudioInTheBackground", "Audio EE denied");
                return;
            }

            m_audioOutput              = new Audio.AudioOutput();
            m_audioInput               = new Audio.AudioInput();
            m_audioInput.OnAudioInput += OnAudioInput;
            await m_audioOutput.Start();

            await m_audioInput.Start();
        }
        /// <summary>
        /// Initialize or clean up the camera and our UI,
        /// depending on the page state.
        /// </summary>
        /// <returns></returns>
        private async Task SetUpBasedOnStateAsync()
        {
            Debug.WriteLine("Entering SetupBasedOnStateAsync(): " + new System.Diagnostics.StackTrace().ToString());
            // Avoid reentrancy: Wait until nobody else is in this function.
            while (!_setupTask.IsCompleted)
            {
                await _setupTask;
            }

            // We want our UI to be active if
            // * We are the current active page.
            // * The window is visible.
            // * The app is not suspending.
            bool show = _isActivePage && Window.Current.Visible && !_isSuspending;

            if (_previewVideoEnabled != show)
            {
                _previewVideoEnabled     = show;
                PreviewToggleSwitch.IsOn = show;
            }

            Func <Task> setupAsync = async() =>
            {
                //if(!show)
                if (_isSuspending)
                {
                    Debug.WriteLine("SetupBasedOnStateAsync - shutting down!");
                    _setupBasedOnState = false;
                    await ShutdownAsync();
                    await StopServer();
                }
                else if (!_setupBasedOnState)
                {
                    Debug.WriteLine("SetupBasedOnStateAsync - setting up!");
                    _setupBasedOnState = true;

                    ExtendedExecutionForegroundSession newSession = new ExtendedExecutionForegroundSession();
                    newSession.Reason      = ExtendedExecutionForegroundReason.Unconstrained;
                    newSession.Description = "Long Running Processing";
                    newSession.Revoked    += SessionRevoked;
                    ExtendedExecutionForegroundResult result = await newSession.RequestExtensionAsync();

                    switch (result)
                    {
                    case ExtendedExecutionForegroundResult.Allowed:
                        Debug.WriteLine("Extended Execution in Foreground ALLOWED.");
                        _extendedExecutionSession = newSession;
                        break;

                    default:
                    case ExtendedExecutionForegroundResult.Denied:
                        Debug.WriteLine("Extended Execution in Foreground DENIED.");
                        break;
                    }


                    await MJPEGStreamerInitAsync();
                    await InitializeCameraAsync();
                    await StartServer();

                    // Prevent the device from sleeping while running
                    _displayRequest.RequestActive();
                }
            };

            Debug.WriteLine("SetupBasedOnStateAsync -calling setup Async!");
            _setupTask = setupAsync();
            Debug.WriteLine("SetupBasedOnStateAsync -setup Async called!");

            await _setupTask;

            Debug.WriteLine("SetupBasedOnStateAsync - awaited setup task!");

            UpdateCaptureControls();
        }
コード例 #10
0
        public MainPage()
        {
            ActionSchedule = new Dictionary <int, OwlCommand.Commands>();
            this.InitializeComponent();

            //don't let the app go idle
            _displayRequest = new Windows.System.Display.DisplayRequest();
            _displayRequest.RequestActive();

            //===================================
            //Get values from config

            Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            Windows.Storage.StorageFolder            localFolder   = Windows.Storage.ApplicationData.Current.LocalFolder;

            enableWingsCheckbox.IsChecked    = GetConfig_Bool(localSettings, "EnableWings");
            enableHeadCheckbox.IsChecked     = GetConfig_Bool(localSettings, "EnableHead");
            enableLeftEyeCheckbox.IsChecked  = GetConfig_Bool(localSettings, "EnableLeftEye");
            enableRightEyeCheckbox.IsChecked = GetConfig_Bool(localSettings, "EnableRightEye");

            //===================================

            _owl = new OwlMasterController.Owl(
                enableHeadCheckbox.IsChecked.GetValueOrDefault(),
                enableWingsCheckbox.IsChecked.GetValueOrDefault(),
                enableRightEyeCheckbox.IsChecked.GetValueOrDefault(),
                enableLeftEyeCheckbox.IsChecked.GetValueOrDefault());

            _owl.DeviceError   += _component_DeviceError;
            _owl.MoveCompleted += _component_MoveCompleted;

            _owl.DeviceInfoMessage += _owl_DeviceInfoMessage;

            _owl.Initialize();

            this.PointerPressed += ScreensaverBG_PointerPressed;
            //Return the initializer call ASAP

            Task.Factory.StartNew(() =>
            {
                ActionSchedule.Add(0, OwlCommand.Commands.RandomFull);
                ActionSchedule.Add(5, OwlCommand.Commands.Wink);
                ActionSchedule.Add(10, OwlCommand.Commands.HeadLeft);
                ActionSchedule.Add(15, OwlCommand.Commands.Wink);
                ActionSchedule.Add(20, OwlCommand.Commands.HeadRight);
                ActionSchedule.Add(25, OwlCommand.Commands.Wink);
                ActionSchedule.Add(30, OwlCommand.Commands.RandomShort);
                ActionSchedule.Add(35, OwlCommand.Commands.Wink);
                ActionSchedule.Add(40, OwlCommand.Commands.Surprise);
                ActionSchedule.Add(45, OwlCommand.Commands.Wink);
                ActionSchedule.Add(50, OwlCommand.Commands.SmallWiggle);
                ActionSchedule.Add(55, OwlCommand.Commands.Wink);

                StringBuilder sbList = new StringBuilder();
                sbList.AppendLine("SCHEDULE");
                sbList.AppendLine("=======================================");
                ActionSchedule.ToList().ForEach(v =>
                {
                    String line = String.Format(":{0} - {1}", v.Key.ToString("00"), v.Value.ToString());
                    sbList.AppendLine(line);
                });
                this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    _lastTouchDetected = DateTime.Now;
                    startupDateTime    = DateTime.Now;
                    _startupDelayTimer = ThreadPoolTimer.CreatePeriodicTimer(__startupDelayTimer_Tick, TimeSpan.FromMilliseconds(500));
                    _autoClockTimer    = ThreadPoolTimer.CreatePeriodicTimer(_clockTimer_Tick, TimeSpan.FromMilliseconds(5000));
                    _screensaverTimer  = ThreadPoolTimer.CreatePeriodicTimer(_screensaver_Tick, TimeSpan.FromMilliseconds(5000));

                    SetStatusLight(Colors.Green);
                    scheduleTextBlock.Text = sbList.ToString();
                });

                var newSession         = new ExtendedExecutionForegroundSession();
                newSession.Reason      = ExtendedExecutionForegroundReason.Unconstrained;
                newSession.Description = "Long Running Processing";
                newSession.Revoked    += OnSessionRevoked;
                //ExtendedExecutionResult result = newSession.RequestExtensionAsync().GetAwaiter().GetResult();

                newSession.RequestExtensionAsync().GetAwaiter().GetResult();

                //switch (result)
                //{
                //    case ExtendedExecutionResult.Allowed:
                //        DoLongRunningWork();
                //        break;

                //    default:
                //    case ExtendedExecutionResult.Denied:
                //        DoShortRunningWork();
                //        break;
                //}
            });
        }
コード例 #11
0
        private async void ToggleButton_Checked(object sender, RoutedEventArgs e)
        {
            var button = (ToggleButton)sender;

            // get storage folder
            if (storageFolder == null)
            {
                var msg = new MessageDialog("Please choose a folder first...");
                await msg.ShowAsync();

                button.IsChecked = false;
                return;
            }

            // check storage folder permissions
            try
            {
                var files = await storageFolder.GetFilesAsync();
            }
            catch
            {
                var dialog = new MessageDialog(
                    "The selected storage directory does not exist anymore or is not accessable. Please select a new directory.",
                    "Directory not found or not enough permissions");

                await dialog.ShowAsync();

                button.IsChecked = false;
                return;
            }

            var requestSuspensionExtension = new ExtendedExecutionForegroundSession();

            requestSuspensionExtension.Reason = ExtendedExecutionForegroundReason.Unspecified;
            var requestExtensionResult = await requestSuspensionExtension.RequestExtensionAsync();

            // get storage files
            var time = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss_");

            var screenFile = await storageFolder.CreateFileAsync(time + "slides.mp4");

            var webcamFile = await storageFolder.CreateFileAsync(time + "talkinghead.mp4");

            var jsonFile = await storageFolder.CreateFileAsync(time + "meta.json");

            // get encoder properties
            var frameRate     = uint.Parse(((string)FrameRateComboBox.SelectedItem).Replace("fps", ""));
            var quality       = (VideoEncodingQuality)Enum.Parse(typeof(VideoEncodingQuality), (string)QualityComboBox.SelectedItem, false);
            var useSourceSize = UseCaptureItemSizeCheckBox.IsChecked.Value;

            var  temp    = MediaEncodingProfile.CreateMp4(quality);
            uint bitrate = 2500000;
            var  width   = temp.Video.Width;
            var  height  = temp.Video.Height;

            // get capture item
            var picker = new GraphicsCapturePicker();

            captureItem = await picker.PickSingleItemAsync();

            if (captureItem == null)
            {
                button.IsChecked = false;
                return;
            }

            // use the capture item's size for the encoding if desired
            if (useSourceSize)
            {
                width  = (uint)captureItem.Size.Width;
                height = (uint)captureItem.Size.Height;
            }

            // we have a screen resolution of more than 4K?
            if (width > 1920)
            {
                var v = width / 1920;
                width   = 1920;
                height /= v;
            }

            // even if we're using the capture item's real size,
            // we still want to make sure the numbers are even.
            width  = EnsureEven(width);
            height = EnsureEven(height);

            // tell the user we've started recording
            var originalBrush = MainTextBlock.Foreground;

            MainTextBlock.Foreground        = new SolidColorBrush(Colors.Red);
            MainProgressBar.IsIndeterminate = true;

            button.IsEnabled = false;

            MainTextBlock.Text = "3";
            await Task.Delay(1000);

            MainTextBlock.Text = "2";
            await Task.Delay(1000);

            MainTextBlock.Text = "1";
            await Task.Delay(1000);

            button.IsEnabled = true;

            MainTextBlock.Text = "● rec";

            _timerCount = 0;
            _timer.Start();

            try
            {
                // start webcam recording
                MediaEncodingProfile webcamEncodingProfile = null;

                if (AdaptBitrateCheckBox.IsChecked.Value)
                {
                    var selectedItem       = WebcamComboBox.SelectedItem as ComboBoxItem;
                    var encodingProperties = (selectedItem.Tag as StreamPropertiesHelper);

                    if (encodingProperties.Height > 720)
                    {
                        webcamEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD1080p);
                        webcamEncodingProfile.Video.Bitrate = 8000000;
                    }
                    else if (encodingProperties.Height > 480)
                    {
                        webcamEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);
                        webcamEncodingProfile.Video.Bitrate = 5000000;
                    }
                    else
                    {
                        webcamEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
                    }
                }
                else
                {
                    webcamEncodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
                }

                mediaRecording = await mediaCapture.PrepareLowLagRecordToStorageFileAsync(webcamEncodingProfile, webcamFile);

                // kick off the screen encoding parallel
                using (var stream = await screenFile.OpenAsync(FileAccessMode.ReadWrite))
                    using (screenCapture = new Encoder(screenDevice, captureItem))
                    {
                        // webcam recording
                        if (mediaCapture != null)
                        {
                            await mediaRecording.StartAsync();
                        }

                        // screen recording
                        await screenCapture.EncodeAsync(
                            stream,
                            width, height, bitrate,
                            frameRate);
                    }

                MainTextBlock.Foreground = originalBrush;

                // user has finished recording, so stop webcam recording
                await mediaRecording.StopAsync();

                await mediaRecording.FinishAsync();

                _timer.Stop();
            }
            catch (Exception ex)
            {
                _timer.Stop();

                var dialog = new MessageDialog(
                    $"Uh-oh! Something went wrong!\n0x{ex.HResult:X8} - {ex.Message}",
                    "Recording failed");

                await dialog.ShowAsync();

                button.IsChecked                = false;
                MainTextBlock.Text              = "failure";
                MainTextBlock.Foreground        = originalBrush;
                MainProgressBar.IsIndeterminate = false;

                captureItem = null;
                if (mediaRecording != null)
                {
                    await mediaRecording.StopAsync();

                    await mediaRecording.FinishAsync();
                }

                return;
            }

            // at this point the encoding has finished
            MainTextBlock.Text = "saving...";

            // save slide markers
            var recording = new Recording()
            {
                Slides = screenCapture.GetTimestamps()
            };

            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            var json = JsonConvert.SerializeObject(recording, Formatting.Indented, settings);
            await FileIO.WriteTextAsync(jsonFile, json);

            // add metadata
            var recordingMetadataDialog       = new RecordingMetadataDialog();
            var recordingMetadataDialogResult = await recordingMetadataDialog.ShowAsync();

            if (recordingMetadataDialogResult == ContentDialogResult.Primary)
            {
                recording.Description = recordingMetadataDialog.LectureTitle;

                if (recordingMetadataDialog.LectureDate.HasValue)
                {
                    recording.LectureDate = recordingMetadataDialog.LectureDate.Value.DateTime;
                }
            }
            else
            {
                recording.Description = null;
                recording.LectureDate = DateTime.Now;
            }

            json = JsonConvert.SerializeObject(recording, Formatting.Indented, settings);
            await FileIO.WriteTextAsync(jsonFile, json);

            // tell the user we're done
            button.IsChecked   = false;
            MainTextBlock.Text = "done";
            MainProgressBar.IsIndeterminate = false;

            requestSuspensionExtension.Dispose();
        }
コード例 #12
0
 public ExtendedExecutionForegroundSessionEvents(ExtendedExecutionForegroundSession This)
 {
     this.This = This;
 }