// Create SaveLabeledImageButton_Click to handle clicking saveLabeledImageButton.
        // Allow use of "byte[] bytes = pixels.ToArray();".
        //using System.Runtime.InteropServices.WindowsRuntime;
        private async void SaveLabeledImageButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            Windows.UI.Xaml.Media.Imaging.RenderTargetBitmap renderTargetBitmap = new Windows.UI.Xaml.Media.Imaging.RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(this.ImageCanvas);

            Windows.Storage.Pickers.FileSavePicker pickerToSaveLabeledImage = new Windows.Storage.Pickers.FileSavePicker();
            pickerToSaveLabeledImage.FileTypeChoices.Add("PNG Image", new string[] { ".png" });
            pickerToSaveLabeledImage.FileTypeChoices.Add("JPEG Image", new string[] { ".jpg" });
            Windows.Storage.StorageFile fileToWhichToSave = await pickerToSaveLabeledImage.PickSaveFileAsync();

            if (fileToWhichToSave != null)
            {
                Windows.Storage.Streams.IBuffer pixels = await renderTargetBitmap.GetPixelsAsync();

                using (Windows.Storage.Streams.IRandomAccessStream stream = await fileToWhichToSave.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
                {
                    Windows.Graphics.Imaging.BitmapEncoder encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.JpegEncoderId, stream);

                    encoder.SetPixelData(
                        Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8,
                        Windows.Graphics.Imaging.BitmapAlphaMode.Ignore,
                        (uint)renderTargetBitmap.PixelWidth,
                        (uint)renderTargetBitmap.PixelHeight,
                        Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi,
                        Windows.Graphics.Display.DisplayInformation.GetForCurrentView().LogicalDpi,
                        pixels.ToArray());
                    await encoder.FlushAsync();
                }
            }
        }
        public async Task <bool> WriteBitmapToPngMediaLibrary(string filename)
        {
            //Canvas tempCanvas = PocketPaintApplication.GetInstance().PaintingAreaCanvas;
            //Size canvasSize = tempCanvas.RenderSize;
            //Point defaultPoint = tempCanvas.RenderTransformOrigin;

            PocketPaintApplication.GetInstance().PaintingAreaCanvas.Measure(PocketPaintApplication.GetInstance().PaintingAreaCanvas.RenderSize);
            PocketPaintApplication.GetInstance().PaintingAreaCanvas.UpdateLayout();
            PocketPaintApplication.GetInstance().PaintingAreaCanvas.Arrange(new Rect(new Point(0, 0), PocketPaintApplication.GetInstance().PaintingAreaCanvas.RenderSize));

            RenderTargetBitmap retarbi = new RenderTargetBitmap();
            await retarbi.RenderAsync(PocketPaintApplication.GetInstance().PaintingAreaCanvas);

            Windows.Storage.Streams.IBuffer buffer = await(retarbi.GetPixelsAsync());
            var pixels = await retarbi.GetPixelsAsync();

            StorageFile outputFile = await KnownFolders.PicturesLibrary.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, writeStream);

                encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                     BitmapAlphaMode.Straight,
                                     (uint)retarbi.PixelWidth,
                                     (uint)retarbi.PixelHeight,
                                     DisplayInformation.GetForCurrentView().LogicalDpi,
                                     DisplayInformation.GetForCurrentView().LogicalDpi,
                                     pixels.ToArray());
                await encoder.FlushAsync();
            }
            return(true);
        }
Пример #3
0
        public static ulong DecodeUint40(this Windows.Storage.Streams.IBuffer buffer)
        {
            var data    = buffer.ToArray();
            var decoded = data.Aggregate(0ul, (l, r) => (l << 8) | r);

            return(decoded);
        }
            /// <summary>
            /// Writes a specified number of bytes to the serial port using data from a buffer.
            /// </summary>
            /// <param name="buffer">The byte array that contains the data to write to the port.</param>
            /// <param name="offset">The zero-based byte offset in the buffer parameter at which to begin copying bytes to the port.</param>
            /// <param name="count">The number of bytes to write.</param>
            /// <remarks>
            /// ArgumentException: offset plus count is greater than the length of the buffer.
            /// </remarks>
            public Windows.Foundation.IAsyncAction Write(
                Windows.Storage.Streams.IBuffer buffer,
                uint offset,
                uint count
                )
            {
                var outputStream = this.cdcData.BulkOutPipes[0].OutputStream;
                var writer       = new Windows.Storage.Streams.DataWriter(outputStream);

                return(Task.Run(async() =>
                {
                    // Overflow check.
                    if ((int)buffer.Length < (offset + count))
                    {
                        throw new System.ArgumentException("Capacity of buffer is not enough.");
                    }

                    writer.WriteBuffer(buffer, offset, count);

                    var written = await writer.StoreAsync();

                    return;
                }
                                ).AsAsyncAction());
            }
Пример #5
0
        private void AddTimedMetaDataTrack_Data()
        {
            //<SnippetAddDataTrack>
            TimedMetadataTrack metadataTrack = new TimedMetadataTrack("ID_0", "en-us", TimedMetadataKind.Data);

            metadataTrack.Label       = "Custom data track";
            metadataTrack.CueEntered += MetadataTrack_DataCueEntered;
            metadataTrack.CueExited  += MetadataTrack_CueExited;

            // Example cue data
            string data = "Cue data";

            byte[] bytes = new byte[data.Length * sizeof(char)];
            System.Buffer.BlockCopy(data.ToCharArray(), 0, bytes, 0, bytes.Length);
            Windows.Storage.Streams.IBuffer buffer = bytes.AsBuffer();

            for (int i = 0; i < 10; i++)
            {
                DataCue cue = new DataCue()
                {
                    Id        = "ID_" + i,
                    Data      = buffer,
                    StartTime = TimeSpan.FromSeconds(3 + i * 3),
                    Duration  = TimeSpan.FromSeconds(2)
                };

                metadataTrack.AddCue(cue);
            }

            mediaSource.ExternalTimedMetadataTracks.Add(metadataTrack);
            //</SnippetAddDataTrack>
        }
        /*public static IAsyncOperation<bool> RenderToPngAsync(this UIElement lt, string filename)
         * {
         *  return RenderToPngAsync(lt, filename).AsAsyncOperation();
         * } */

        public static async Task <bool> RenderToPngAsync(this UIElement lt, string filename)
        {
#if __UAP__
            var y = new RenderTargetBitmap();
            await y.RenderAsync(lt);

            Windows.Storage.Streams.IBuffer px = await y.GetPixelsAsync();

            StorageFile file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);

            if (file != null)
            {
                CachedFileManager.DeferUpdates(file);
                using (Windows.Storage.Streams.IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

                    encoder.IsThumbnailGenerated = false;
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, (uint)y.PixelWidth, (uint)y.PixelHeight, displayInfo.RawDpiX, displayInfo.RawDpiY, px.ToArray());
                    await encoder.FlushAsync();
                }
                await CachedFileManager.CompleteUpdatesAsync(file);

                return(true);
            }
#endif
            return(false);
        }
Пример #7
0
        //row-major
        void WriteMatrixToBuffer(Windows.Storage.Streams.IBuffer buffer, Matrix4x4 mat)
        {
            using (var stream = buffer.AsStream())
                using (var writer = new BinaryWriter(stream))
                {
                    writer.Write(mat.M11);
                    writer.Write(mat.M12);
                    writer.Write(mat.M13);
                    writer.Write(mat.M14);

                    writer.Write(mat.M21);
                    writer.Write(mat.M22);
                    writer.Write(mat.M23);
                    writer.Write(mat.M24);

                    writer.Write(mat.M31);
                    writer.Write(mat.M32);
                    writer.Write(mat.M33);
                    writer.Write(mat.M34);

                    writer.Write(mat.M41);
                    writer.Write(mat.M42);
                    writer.Write(mat.M43);
                    writer.Write(mat.M44);
                }
        }
Пример #8
0
        //--------------------------------------------------------Attributes:-----------------------------------------------------------------\\
        #region --Attributes--


        #endregion
        //--------------------------------------------------------Constructor:----------------------------------------------------------------\\
        #region --Constructors--


        #endregion
        //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
        #region --Set-, Get- Methods--


        #endregion
        //--------------------------------------------------------Misc Methods:---------------------------------------------------------------\\
        #region --Misc Methods (Public)--
        public static byte[] NextBytesSecureRandom(uint length)
        {
            Windows.Storage.Streams.IBuffer buf = CryptographicBuffer.GenerateRandom(length);
            byte[] bytes = new byte[length];
            CryptographicBuffer.CopyToByteArray(buf, out bytes);
            return(bytes);
        }
Пример #9
0
        private X509Certificate2 ConvertPublicKeyCertificate(RTCertificate cert)
        {
            // Convert Windows X509v2 cert to .NET X509v2 cert.
            RTIBuffer blob = cert.GetCertificateBlob();

            return(new X509Certificate2(blob.ToArray()));
        }
        public async Task <string> SavePhotoAsync(Windows.Storage.Streams.IBuffer buffer, string username)
        {
            var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(username + ".jpg", CreationCollisionOption.ReplaceExisting);

            await FileIO.WriteBufferAsync(file, buffer);

            return(file.Path);
        }
Пример #11
0
        public static string ToString(Windows.Storage.Streams.IBuffer buffer, ToStringOptions options = ToStringOptions.None)
        {
            var dr = Windows.Storage.Streams.DataReader.FromBuffer(buffer);

            byte[] bytes = new byte[dr.UnconsumedBufferLength];
            dr.ReadBytes(bytes);
            return(ToString(bytes, options));
        }
Пример #12
0
        public static string GetMD5(string inputString)
        {
            CryptographicHash objHash = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5).CreateHash();

            objHash.Append(CryptographicBuffer.ConvertStringToBinary(inputString, BinaryStringEncoding.Utf8));
            Windows.Storage.Streams.IBuffer buffHash1 = objHash.GetValueAndReset();
            return(CryptographicBuffer.EncodeToHexString(buffHash1));
        }
 // Summary:
 //     Instantiates a new instance of the System.Windows.Media.MediaStreamSample
 //     class.
 //
 // Parameters:
 //   mediaStreamDescription:
 //     A description of the stream this sample was pulled from.
 //
 //   stream:
 //     A stream containing the desired media sample. Set to null to report the end
 //     of a stream.
 //
 //   offset:
 //     The offset into the stream where the actual sample data begins.
 //
 //   count:
 //     The number of bytes that comprises the sample data.
 //
 //   timestamp:
 //     The time from the beginning of the media file at which this sample should
 //     be rendered as expressed using 100 nanosecond increments.
 //
 //   attributes:
 //     A collection of pairs describing other attributes of the media sample.
 //
 // Exceptions:
 //   System.InvalidOperationException:
 //     One or more parameters are invalid.
 public MediaStreamSample(MediaStreamDescription mediaStreamDescription,
                          Windows.Storage.Streams.IBuffer buffer,// Stream stream,
                          long offset,
                          long count,
                          long timestamp,
                          IDictionary <MediaSampleAttributeKeys, string> attributes)
 {
     _innerSample = new MSSWinRTExtension.MediaStreamSample(buffer, (int)offset, (int)count, timestamp, 0);
 }
Пример #14
0
        static async Task <byte[]> ReadAllBytes(string filename)
        {
            var uri  = new Uri("ms-appx:///" + filename);
            var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

            Windows.Storage.Streams.IBuffer buffer = await FileIO.ReadBufferAsync(file);

            return(buffer.ToArray());
        }
            /// <summary>
            /// This is an internal method called from Read method.
            /// </summary>
            /// <param name="buffer">The byte array, passed to Read method.</param>
            /// <param name="offset">The offset in the buffer array to begin writing.</param>
            /// <param name="count">The number of bytes to read.</param>
            /// <param name="timeout">Milliseconds before a time-out occurs.</param>
            /// <param name="ct">A cancellation_token will be used by ReadPartial method.</param>
            /// <returns>
            /// The result of Task contains the length of bytes read.
            /// </returns>
            private Task <int> ReadInternal(
                Windows.Storage.Streams.IBuffer buffer,
                int offset,
                int count,
                int timeout,
                System.Threading.CancellationToken ct
                )
            {
                // ConfigureAwait(false) means that we'd try to execute the task in non UI thread.
                Task <int> task;

                (task = Task.Run(async() =>
                {
                    int totalReadcount = 0;

                    while (timeout == Constants.InfiniteTimeout || timeout >= 0)
                    {
                        var start = System.DateTime.Now.Ticks; // 100 nano-sec.

                        var readcount = 0;
                        try
                        {
                            readcount = await this.ReadPartial(buffer, offset, count, timeout, ct);
                        }
                        catch (TimeoutException)
                        {
                            break; // timeout
                        }
                        catch (OperationCanceledException)
                        {
                            // Cancel the task.
                            throw new OperationCanceledException("ReadInternal was canceled.");
                        }

                        totalReadcount += readcount;

                        if (readcount >= count)
                        {
                            break; // completed;
                        }

                        // Prepare for the next ReadPartial.
                        if (timeout >= 0)
                        {
                            timeout = (int)(timeout - (System.DateTime.Now.Ticks - start) / 10000);
                        }
                        offset += readcount;
                        count -= readcount;
                    }

                    return(totalReadcount);
                }
                                 )).ConfigureAwait(false);

                return(task);
            }
Пример #16
0
        public async Task <string> GetData(Windows.Storage.Streams.IBuffer data, uint scanDataType)
        {
            try
            {
                string result = null;
                if (data == null)
                {
                    result = "No data";
                }
                else
                {
                    switch (Windows.Devices.PointOfService.BarcodeSymbologies.GetName(scanDataType))
                    {
                    case "Ean13":
                    case "Ean8":
                    case "Code128":
                    case "Qr":
                    case "Code93":
                    case "Code39":
                    case "Gs1128":
                    case "DataMatrix":
                    case "Gs1128Coupon":
                    case "Gs1DatabarType1":
                    case "Gs1DatabarType2":
                    case "Gs1DatabarType3":
                    case "Upca":
                    case "Upce":
                    case "TfInd":
                    case "TfInt":
                    case "TfStd":
                    case "UccEan128":
                    case "Ean13Add2":
                    case "Ean13Add5":
                        Windows.Storage.Streams.DataReader reader = Windows.Storage.Streams.DataReader.FromBuffer(data);
                        result = reader.ReadString(data.Length).ToString();
                        byte[] bytes = Encoding.ASCII.GetBytes(result);
                        result = Encoding.UTF8.GetString(bytes);

                        break;

                    default:
                        result = string.Format("Decoded data unavailable. Raw label data: {0}", GetData(data));
                        break;
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                //await DisplayAlert("Error", "GetData failed, Code:" + " Message:" + ex.Message, "OK");
            }
            return("");
        }
Пример #17
0
Файл: Util.cs Проект: ckc/WinApp
        internal static String BinaryBufferToBinaryString(Windows.Storage.Streams.IBuffer buffer)
        {
            var str    = "";
            var reader = Windows.Storage.Streams.DataReader.FromBuffer(buffer);

            for (uint i = 0; i < buffer.Length; i++)
            {
                str += reader.ReadByte().ToString("X2") + " ";
            }
            return(str);
        }
        public void MapDepthFrameToCameraSpace(Windows.Storage.Streams.IBuffer depthFrameData, Windows.Kinect.CameraSpacePoint[] cameraSpacePoints)
        {
            if (_pNative == RootSystem.IntPtr.Zero)
            {
                throw new RootSystem.ObjectDisposedException("CoordinateMapper");
            }

            uint length = depthFrameData.Length / sizeof(UInt16);

            Windows_Kinect_CoordinateMapper_MapDepthFrameToCameraSpace(_pNative, depthFrameData.UnderlyingBuffer, length, cameraSpacePoints, cameraSpacePoints.Length);
        }
Пример #19
0
        public static string FormatToString(Windows.Storage.Streams.IBuffer value)
        {
            string formattedResult = string.Empty;

            Windows.Security.Cryptography.CryptographicBuffer.CopyToByteArray(value, out byte[] data);
            if (data != null)
            {
                formattedResult = Encoding.UTF8.GetString(data);
            }
            return(formattedResult);
        }
Пример #20
0
        public void Send(Windows.Storage.Streams.IBuffer data)
        {
            m_audioDataMutex.WaitOne();
            if (m_isRunning)
            {
                byte[] buffer;
                CryptographicBuffer.CopyToByteArray(data, out buffer);
                m_audioData.Add(buffer);
            }

            m_audioDataMutex.ReleaseMutex();
        }
Пример #21
0
        /// <summary>
        /// This is the click handler for the 'scenario3BtnBuffer' button.  You would replace this with your own handler
        /// if you have a button or buttons on this page.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Scenario3BtnBuffer_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Get load settings
                var loadSettings = new Windows.Data.Xml.Dom.XmlLoadSettings();
                if (true == scenario3RB1.IsChecked)
                {
                    loadSettings.ProhibitDtd      = true;   // DTD is prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB2.IsChecked)
                {
                    loadSettings.ProhibitDtd      = false;  // DTD is not prohibited
                    loadSettings.ResolveExternals = false;  // Disable the resolve to external definitions such as external DTD
                }
                else if (true == scenario3RB3.IsChecked)
                {
                    loadSettings.ProhibitDtd      = false;  // DTD is not prohibited
                    loadSettings.ResolveExternals = true;   // Enable the resolve to external definitions such as external DTD
                }

                String xml;

                scenario3OriginalData.Document.GetText(Windows.UI.Text.TextGetOptions.None, out xml);

                // Set external dtd file path
                if (loadSettings.ResolveExternals == true && loadSettings.ProhibitDtd == false)
                {
                    Windows.Storage.StorageFolder storageFolder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("loadExternaldtd");

                    String dtdPath = storageFolder.Path + "\\dtd.txt";
                    xml = xml.Replace("dtd.txt", dtdPath);
                }

                var dataWriter = new Windows.Storage.Streams.DataWriter();

                dataWriter.WriteString(xml);

                Windows.Storage.Streams.IBuffer ibuffer = dataWriter.DetachBuffer();

                var doc = new Windows.Data.Xml.Dom.XmlDocument();

                doc.LoadXmlFromBuffer(ibuffer, loadSettings);

                Scenario.RichEditBoxSetMsg(scenario3Result, doc.GetXml(), true);
            }
            catch (Exception)
            {
                // After loadSettings.ProhibitDtd is set to true, the exception is expected as the sample XML contains DTD
                Scenario.RichEditBoxSetError(scenario3Result, "Error: DTD is prohibited");
            }
        }
Пример #22
0
 /// <summary>
 /// Retrieve a unique ID that is stable across application instances, similar to what
 /// Unity does with SystemInfo.deviceUniqueIdentifier.
 /// </summary>
 /// <param name="variant">Optional variation quantity to modify the unique ID,
 /// to allow multiple instances of the application to run in parallel with different IDs.</param>
 /// <returns>A unique string ID stable across multiple runs of the application</returns>
 /// <remarks>
 /// This is a debugging utility useful to generate deterministic WebRTC peers for node-dss
 /// signaling, to avoid manual input during testing. This is not a production-level solution.
 /// </remarks>
 private string GetDeviceUniqueIdLikeUnity(byte variant = 0)
 {
     // More or less like Unity, which can use HardwareIdentification.GetPackageSpecificToken() in some cases,
     // although it's unclear how they convert that to a string.
     Windows.Storage.Streams.IBuffer buffer = HardwareIdentification.GetPackageSpecificToken(null).Id;
     using (var dataReader = Windows.Storage.Streams.DataReader.FromBuffer(buffer))
     {
         byte[] bytes = new byte[buffer.Length];
         dataReader.ReadBytes(bytes);
         bytes[0] += variant;
         return(BitConverter.ToString(bytes).Replace("-", string.Empty).Remove(32));
     }
 }
        // Send one packet of BLE frame
        private async Task <bool> send_one_TX_Packet(int num)
        {
            int len    = 0;
            int offset = 0;

            if (SPPOverLECharacteristic == null)
            {
                setUpSPP();
                await SPPOverLECharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
                    GattClientCharacteristicConfigurationDescriptorValue.Notify);
            }
            if (SPPOverLECharacteristic == null)
            {
                throw new InvalidOperationException("Invalid BLE Characteristics");
            }


            // Check if last packet
            if (num > 0)
            {
                offset = m_TX_Buffer_rest + ((num - 1) * LEN_PACKET);
                len    = LEN_PACKET;
            }
            else
            {
                offset = 0;
                len    = m_TX_Buffer_rest;
            }

            // Extract frame from buffer
            byte[] packet = new byte[len + 1];
            packet[0] = (byte)offset;

            for (int i = 0; i < len; i++)
            {
                packet[i + 1] = m_TX_buffer[offset + i];
            }

            Log.WriteLine("~~~ send: " + CurrentRequest.index + " data=[" + BitConverter.ToString(packet, 0, packet.Length) + "]");

            Windows.Storage.Streams.IBuffer packetBuffer = GattConvert.ToIBufferFromArray(packet);

            if (SPPOverLECharacteristic != null)
            {
                GattCommunicationStatus status = await SPPOverLECharacteristic.WriteValueAsync(packetBuffer, GattWriteOption.WriteWithoutResponse);

                return(status == GattCommunicationStatus.Success);
            }

            return(false);
        }
 /// <summary>
 /// Sends a raw CDC request.
 /// </summary>
 /// <param name="request">CDC request code.</param>
 /// <param name="value">value, corresponded with the request code.</param>
 /// <param name="buffer">data, corresponded with the request code.</param>
 /// <returns>
 /// The result of IAsyncOperation contains a length of bytes actually sent.
 /// </returns>
 public Windows.Foundation.IAsyncOperation <uint> SetControlRequest(
     byte request,
     ushort value,
     Windows.Storage.Streams.IBuffer buffer
     )
 {
     return(Task.Run(async() =>
     {
         var requestType = new UsbControlRequestType();
         requestType.AsByte = RequestType.Set;
         return await UsbControlRequestForSet(this.cdcControl.InterfaceNumber, requestType, request, value, buffer);
     }
                     ).AsAsyncOperation <uint>());
 }
Пример #25
0
            public void OnSampleReceived(Windows.Storage.Streams.IBuffer pBuffer, UInt64 hnsPresentationTime)
            {
                lock (lockObj)
                {
                    if (this.sampleQueue.Count >= VideoStreamSource.maxSampleQueueSize)
                    {
                        // The sample queue is full, discard the older sample
                        this.sampleQueue.Dequeue();
                    }

                    this.sampleQueue.Enqueue(new Sample(pBuffer, hnsPresentationTime));
                    FeedSamples();
                }
            }
        void TransportController_VideoMessageReceived(Windows.Storage.Streams.IBuffer ibuffer, UInt64 hnsPresenationTime, UInt64 hnsSampleDuration)
        {
            lock (lockObj)
            {
                if (_sampleQueue.Count >= VideoMediaStreamSource.maxQueueSize)
                {
                    // Dequeue and discard oldest
                    _sampleQueue.Dequeue();
                }

                _sampleQueue.Enqueue(new VideoSample(ibuffer, hnsPresenationTime, hnsSampleDuration));
                SendSamples();
            }
        }
Пример #27
0
        void Instance_VideoFrameReceived(Windows.Storage.Streams.IBuffer ibuffer, ulong hnsPresenationTime, ulong hnsSampleDuration)
        {
            lock (lockObj)
            {
                if (_sampleQueue.Count >= VideoMediaStreamSource.maxQueueSize)
                {
                    // Dequeue and discard oldest
                    _sampleQueue.Dequeue();
                }

                _sampleQueue.Enqueue(new VideoSample(ibuffer, hnsPresenationTime, hnsSampleDuration));
                SendSamples();
            }
        }
Пример #28
0
        public static byte[] GenerateKeyBytes(int keySize)
        {
#if WINDOWS_UWP
            Windows.Storage.Streams.IBuffer keyBytesBuffer = CryptographicBuffer.GenerateRandom((uint)keySize);
            byte[] keyBytes;
            CryptographicBuffer.CopyToByteArray(keyBytesBuffer, out keyBytes);
#else
            var keyBytes = new byte[keySize];
            using (var cyptoProvider = new RNGCryptoServiceProvider())
            {
                cyptoProvider.GetNonZeroBytes(keyBytes);
            }
#endif
            return(keyBytes);
        }
 /// <summary>
 /// Reads a number of bytes from the SerialPort input buffer and writes those bytes into a byte array at the specified offset.
 /// </summary>
 /// <param name="buffer">The byte array to write the input to.</param>
 /// <param name="offset">The offset in the buffer array to begin writing.</param>
 /// <param name="count">The number of bytes to read.</param>
 /// <param name="ct">A CancellationToken in order to notify of cancellation from user.</param>
 /// <returns>
 /// The result of IAsyncOperation contains the number of bytes read.
 /// A less length than count means timeout occurred.
 /// </returns>
 /// <remarks>
 /// ArgumentException: offset plus count is greater than the length of the buffer.
 /// OperationCanceledException: The IAsyncOperation was canceled.
 /// </remarks>
 public Windows.Foundation.IAsyncOperation <int> Read(
     Windows.Storage.Streams.IBuffer buffer,
     uint offset,
     uint count,
     System.Threading.CancellationToken ct
     )
 {
     return(Task.Run(async() =>
     {
         var readcount = await ReadInternal(buffer, Convert.ToInt32(offset), Convert.ToInt32(count), this.ReadTimeout, ct);
         buffer.Length = (uint)readcount;
         return readcount;
     },
                     ct).AsAsyncOperation <int>());
 }
Пример #30
0
        public static async System.Threading.Tasks.Task <int> SynSpeechWriteToFileAsync(string text, string fileName)
        {
            using (Windows.Media.SpeechSynthesis.SpeechSynthesizer synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer())
            {
                try
                {
                    using (Windows.Media.SpeechSynthesis.SpeechSynthesisStream synthStream = await synth.SynthesizeTextToStreamAsyncServiceAsync(text, apiArgs)) // doesn't handle special characters such as quotes
                    {
                        // TODO: obsolete to use DataReader? use await Windows.Storage.FileIO.Read...(file);
                        using (Windows.Storage.Streams.DataReader reader = new Windows.Storage.Streams.DataReader(synthStream))
                        {
                            await reader.LoadAsync((uint)synthStream.Size);

                            Windows.Storage.Streams.IBuffer buffer     = reader.ReadBuffer((uint)synthStream.Size);
                            Windows.Storage.StorageFolder   tempFolder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(Options.options.tempFolderPath);

                            Windows.Storage.StorageFile srcFile = await tempFolder.CreateFileAsync(Options.options.audio.speechSynthesisFileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                            await Windows.Storage.FileIO.WriteBufferAsync(srcFile, buffer);

                            Windows.Storage.FileProperties.MusicProperties musicProperties = await srcFile.Properties.GetMusicPropertiesAsync();

                            Log.WriteLine("Bitrate:" + musicProperties.Bitrate);

                            Windows.Media.MediaProperties.MediaEncodingProfile profile    = Windows.Media.MediaProperties.MediaEncodingProfile.CreateWav(Windows.Media.MediaProperties.AudioEncodingQuality.Low);
                            Windows.Media.Transcoding.MediaTranscoder          transcoder = new Windows.Media.Transcoding.MediaTranscoder();
                            Windows.Storage.StorageFile destFile = await tempFolder.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);

                            Windows.Media.Transcoding.PrepareTranscodeResult result = await transcoder.PrepareFileTranscodeAsync(srcFile, destFile, profile);

                            if (result.CanTranscode)
                            {
                                await result.TranscodeAsync();
                            }
                            else
                            {
                                Log.WriteLine("can't transcode file:" + result.FailureReason.ToString());
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            return(0);
        }
Пример #31
0
        public Windows.Storage.Streams.IBuffer LockImageBuffer()
        {
            if (_pNative == RootSystem.IntPtr.Zero)
            {
                throw new RootSystem.ObjectDisposedException("LongExposureInfraredFrame");
            }

            RootSystem.IntPtr objectPointer = Windows_Kinect_LongExposureInfraredFrame_LockImageBuffer(_pNative);
            if (objectPointer == RootSystem.IntPtr.Zero)
            {
                return null;
            }

            objectPointer = Helper.NativeObjectCache.MapToIUnknown(objectPointer);
            var obj = Helper.NativeObjectCache.GetObject<Windows.Storage.Streams.IBuffer>(objectPointer);
            if (obj == null)
            {
                obj = new Windows.Storage.Streams.IBuffer(objectPointer);
                Helper.NativeObjectCache.AddObject<Windows.Storage.Streams.IBuffer>(objectPointer, obj);
            }

            return obj;
        }
Пример #32
0
 public VideoSample(Windows.Storage.Streams.IBuffer _buffer, UInt64 _hnsPresentationTime, UInt64 _hnsSampleDuration)
 {
     buffer = _buffer;
     hnsPresentationTime = _hnsPresentationTime;
     hnsSampleDuration = _hnsSampleDuration;
 }