Ejemplo n.º 1
0
        private async Task <PPError> FlushAsyncCore(MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <PPError> ();
            EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); };

            try {
                Flushed += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    Flush();
                }
                else
                {
                    Action <PPError> action = new Action <PPError> ((e) => {
                        var result = (PPError)PPBGraphics2D.Flush(this, new BlockUntilComplete());
                        tcs.TrySetResult(result);
                    }
                                                                    );
                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
            finally
            {
                Flushed -= handler;
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a video encoder resource asynchronously. This should be called after
 /// GetSupportedProfiles() and before any functions below.
 /// </summary>
 /// <param name="inputFormat">The <code>VideoFrame_Format</code> of the
 /// frames which will be encoded.</param>
 /// <param name="inputVisibleSize">A <code>Size</code> specifying the
 /// dimensions of the visible part of the input frames.</param>
 /// <param name="outputProfile">A <code>VideoProfile</code> specifying the
 /// codec profile of the encoded output stream.</param>
 /// <param name="initialBitrate">The initial bitrate of the encoded output stream</param>
 /// <param name="acceleration">A <code>HardwareAcceleration</code> specifying
 /// whether to use a hardware accelerated or a software implementation.</param>
 /// <param name="messageLoop">Optional MessageLoop instance that can be used to post the command to</param>
 /// <returns>Error code.  Returns NotSupported if video encoding is not available, or the
 /// requested codec profile is not supported.
 /// Returns NoMemory if frame and bitstream buffers can't be created.</returns>
 public Task <PPError> InitializeAsync(VideoFrameFormat inputFormat,
                                       PPSize inputVisibleSize,
                                       VideoProfile outputProfile,
                                       uint initialBitrate,
                                       HardwareAcceleration acceleration,
                                       MessageLoop messageLoop = null)
 => InitializeAsyncCore(inputFormat, inputVisibleSize, outputProfile, initialBitrate, acceleration, messageLoop);
Ejemplo n.º 3
0
        private async Task <PPError> ConnectAsyncCore(Uri uri, string[] protocols, MessageLoop connectLoop = null)
        {
            var tcs = new TaskCompletionSource <PPError>();
            EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                Connection += handler;

                if (MessageLoop == null && connectLoop == null)
                {
                    Connect(uri, protocols);
                }
                else
                {
                    PPVar[] varProtocols = null;

                    if (protocols != null)
                    {
                        varProtocols = new PPVar[protocols.Length];

                        for (int p = 0; p < protocols.Length; p++)
                        {
                            varProtocols[p] = new Var(protocols[p]);
                        }
                    }
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var result = (PPError)PPBWebSocket.Connect(this, new Var(uri.AbsoluteUri),
                                                                   varProtocols, varProtocols == null ? 0 : (uint)varProtocols.Length,
                                                                   new BlockUntilComplete()
                                                                   );
                        tcs.TrySetResult(result);
                    }
                                                                   );
                    InvokeHelper(action, connectLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
            finally
            {
                Connection -= handler;
            }
        }
Ejemplo n.º 4
0
        private async Task <PPError> InitializeAsyncCore(VideoFrameFormat inputFormat,
                                                         PPSize inputVisibleSize,
                                                         VideoProfile outputProfile,
                                                         uint initialBitrate,
                                                         HardwareAcceleration acceleration,
                                                         MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <PPError>();
            EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleInitialize += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    Initialize(inputFormat, inputVisibleSize, outputProfile, initialBitrate, acceleration);
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var result = (PPError)PPBVideoEncoder.Initialize(this,
                                                                         (PPVideoFrameFormat)inputFormat,
                                                                         inputVisibleSize,
                                                                         (PPVideoProfile)outputProfile,
                                                                         initialBitrate,
                                                                         (PPHardwareAcceleration)acceleration,
                                                                         new BlockUntilComplete()
                                                                         );
                        tcs.TrySetResult(result);
                    }
                                                                   );

                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
            finally
            {
                HandleInitialize -= handler;
            }
        }
Ejemplo n.º 5
0
        protected virtual void Dispose(bool disposing)
        {
            if (!IsEmpty)
            {
                if (disposing)
                {
                    // de-reference the managed resource.
                    MessageLoop = null;
                }

                // Release our managed resources
                NativeInstance.resourceReleaseQueue.Enqueue(Handle);
                handle.ppresource = 0; // set ourselves to empty
            }
        }
Ejemplo n.º 6
0
        private async Task <DirectoryEntries> ReadDirectoryEntriesAsyncCore(MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <DirectoryEntries>();
            EventHandler <DirectoryEntries> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleReadDirectoryEntries += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    ReadDirectoryEntries();
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var output = new ArrayOutputAdapterWithStorage <PPDirectoryEntry[]>();
                        var result = (PPError)PPBFileRef.ReadDirectoryEntries(this, output.PPArrayOutput,
                                                                              new BlockUntilComplete()
                                                                              );

                        var entries = new List <DirectoryEntry>();
                        foreach (var entry in output.Output)
                        {
                            entries.Add(new DirectoryEntry(entry));
                        }
                        tcs.TrySetResult(new DirectoryEntries(result, entries.AsReadOnly()));
                    }
                                                                   );

                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(new DirectoryEntries(PPError.Aborted, new List <DirectoryEntry> ().AsReadOnly()));
            }
            finally
            {
                HandleReadDirectoryEntries -= handler;
            }
        }
Ejemplo n.º 7
0
        private async Task <VideoProfileInfo> GetSupportedProfilesAsyncCore(MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <VideoProfileInfo>();
            EventHandler <VideoProfileInfo> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleEncoderProbed += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    GetSupportedProfiles();
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var output = new ArrayOutputAdapterWithStorage <PPVideoProfileDescription01[]>();
                        var result = (PPError)PPBVideoEncoder.GetSupportedProfiles(this, output.PPArrayOutput,
                                                                                   new BlockUntilComplete()
                                                                                   );

                        var profiles = new List <VideoProfileDescription>();
                        foreach (var entry in output.Output)
                        {
                            profiles.Add(new VideoProfileDescription(entry));
                        }
                        tcs.TrySetResult(new VideoProfileInfo(result, profiles.AsReadOnly()));
                    }
                                                                   );

                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(new VideoProfileInfo(PPError.Aborted, new List <VideoProfileDescription>().AsReadOnly()));
            }
            finally
            {
                HandleEncoderProbed -= handler;
            }
        }
Ejemplo n.º 8
0
 internal void InvokeHelper(Action <PPError> action, MessageLoop messageLoop = null, PPError result = PPError.OkCompletionpending)
 {
     if (messageLoop == null)
     {
         MessageLoop.PostWork(action);
     }
     else
     {
         if (messageLoop is BlockingMessageLoop)
         {
             action(result);
         }
         else
         {
             messageLoop.PostWork(action);
         }
     }
 }
Ejemplo n.º 9
0
        private async Task <PPError> EncodeAsyncCore(PPResource videoFrame,
                                                     bool forceKeyframe, MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <PPError>();
            EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleEncode += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    Encode(videoFrame, forceKeyframe);
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var result = (PPError)PPBVideoEncoder.Encode(this,
                                                                     videoFrame,
                                                                     forceKeyframe ? PPBool.True : PPBool.False,
                                                                     new BlockUntilComplete()
                                                                     );

                        tcs.TrySetResult(result);
                    }
                                                                   );

                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
            finally
            {
                HandleEncode -= handler;
            }
        }
Ejemplo n.º 10
0
        private async Task <BitstreamBufferInfo> GetBitstreamBufferAsyncCore(MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <BitstreamBufferInfo>();
            EventHandler <BitstreamBufferInfo> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleBitstreamBuffer += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    GetBitstreamBuffer();
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var output = new APIArgumentAdapter <PPBitstreamBuffer>();
                        var result = (PPError)PPBVideoEncoder.GetBitstreamBuffer(this, out output.output,
                                                                                 new BlockUntilComplete()
                                                                                 );

                        tcs.TrySetResult(new BitstreamBufferInfo(result, output.Output));
                    }
                                                                   );

                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(new BitstreamBufferInfo(PPError.Aborted, new PPBitstreamBuffer()));
            }
            finally
            {
                HandleBitstreamBuffer -= handler;
            }
        }
Ejemplo n.º 11
0
        private async Task <FileInfo> QueryAsyncCore(MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <FileInfo>();
            EventHandler <FileInfo> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleQuery += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    Query();
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var fileInfo = new PPFileInfo();
                        var result   = (PPError)PPBFileRef.Query(this, out fileInfo,
                                                                 new BlockUntilComplete()
                                                                 );
                        tcs.TrySetResult(new FileInfo(result, fileInfo));
                    }
                                                                   );

                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(new FileInfo(PPError.Aborted, new PPFileInfo()));
            }
            finally
            {
                HandleQuery -= handler;
            }
        }
Ejemplo n.º 12
0
        private async Task <PPError> ReadResponseBodyAsyncCore(byte[] buffer,
                                                               int bytes_to_read,
                                                               MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <PPError>();
            EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleReadResponseBody += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    ReadResponseBody(buffer, bytes_to_read);
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var result = (PPError)PPBURLLoader.ReadResponseBody(this,
                                                                            buffer, bytes_to_read,
                                                                            new BlockUntilComplete());
                        tcs.TrySetResult(result);
                    }
                                                                   );
                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
            finally
            {
                HandleReadResponseBody -= handler;
            }
        }
Ejemplo n.º 13
0
        private async Task <NetworkListInfo> UpdateNetworkListAsyncCore(MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <NetworkListInfo>();
            EventHandler <NetworkListInfo> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleUpdateNetworkList += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    UpdateNetworkList();
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var output = new APIArgumentAdapter <PPResource>();
                        var result = (PPError)PPBNetworkMonitor.UpdateNetworkList(this,
                                                                                  out output.output,
                                                                                  new BlockUntilComplete());

                        tcs.TrySetResult(new NetworkListInfo(result, new NetworkList(output.Output)));
                    }
                                                                   );
                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(new NetworkListInfo(PPError.Aborted, null));
            }
            finally
            {
                HandleUpdateNetworkList -= handler;
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Connects asynchronously to the specified WebSocket server
        /// </summary>
        /// <param name="url">The URI of the WebSocket server to connect to.</param>
        /// <param name="protocols"></param>
        ///
        public Task <PPError> ConnectAsync(Uri url, MessageLoop messageLoop, string[] protocols = null, MessageLoop connectLoop = null)
        {
            if (PPBWebSocket.IsWebSocket(this) != PPBool.True)
            {
                throw new PlatformNotSupportedException("Websocket not supported");
            }

            if (url == null)
            {
                throw new ArgumentNullException(nameof(url));
            }
            if (!url.IsAbsoluteUri)
            {
                throw new ArgumentException("Not Absolute URI", nameof(url));
            }
            if (url.Scheme.ToLower() != UriSchemeWs && url.Scheme.ToLower() != UriSchemeWss)
            {
                throw new ArgumentException("Scheme invalid", nameof(url));
            }

            return(ConnectAsyncCore(url, protocols, connectLoop));
        }
Ejemplo n.º 15
0
        private async Task <PPError> OpenAsyncCore(URLRequestInfo requestInfo, MessageLoop openLoop = null)
        {
            var tcs = new TaskCompletionSource <PPError>();
            EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleOpen += handler;

                if (MessageLoop == null && openLoop == null)
                {
                    Open(requestInfo);
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var result = (PPError)PPBURLLoader.Open(this, requestInfo,
                                                                new BlockUntilComplete()
                                                                );
                        tcs.TrySetResult(result);
                    }
                                                                   );
                    InvokeHelper(action, openLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
            finally
            {
                HandleOpen -= handler;
            }
        }
Ejemplo n.º 16
0
        private async Task <VideoFrameInfo> GetEmptyFrameAsyncCore(MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <VideoFrameInfo>();
            EventHandler <VideoFrameInfo> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleEmptyFrame += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    GetFrame();
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var output = new APIArgumentAdapter <PPResource>();
                        var result = (PPError)PPBMediaStreamVideoTrack.GetEmptyFrame(this, out output.output,
                                                                                     new BlockUntilComplete());
                        tcs.TrySetResult(new VideoFrameInfo(result, output.Output));
                    }
                                                                   );
                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(new VideoFrameInfo(PPError.Aborted, PPResource.Empty));
            }
            finally
            {
                HandleEmptyFrame -= handler;
            }
        }
Ejemplo n.º 17
0
        private async Task <PPError> CloseAsyncCore(MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <PPError>();
            EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleClose += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    Close();
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        PPBMediaStreamAudioTrack.Close(this);
                        tcs.TrySetResult(PPError.Ok);
                    }
                                                                   );
                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
            finally
            {
                HandleClose -= handler;
            }
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Closes the MediaStream video track asynchronously, and disconnects it from video source.
 /// After calling <code>Close()</code>, no new frames will be received.
 /// </summary>
 /// <param name="messageLoop">Optional MessageLoop instance that can be used to post the command to</param>
 public Task <PPError> CloseAsync(MessageLoop messageLoop = null)
 => CloseAsyncCore(messageLoop);
Ejemplo n.º 19
0
 /// <summary>
 /// Flush() flushes changes to disk asynchronously.  This call can be very expensive!
 /// </summary>
 /// <param name="messageLoop">Optional MessageLoop instance used to run the command on.</param>
 /// <returns>Error code</returns>
 public Task <PPError> FlushAsync(MessageLoop messageLoop = null)
 => FlushAsyncCore(messageLoop);
Ejemplo n.º 20
0
        private async Task <PPError> ConfigureAsyncCore(MediaStreamAudioTrackAttributes attributes, MessageLoop messageLoop = null)
        {
            var tcs = new TaskCompletionSource <PPError>();
            EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                HandleConfigure += handler;

                if (MessageLoop == null && messageLoop == null)
                {
                    Configure(attributes);
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var result = (PPError)PPBMediaStreamAudioTrack.Configure(this, attributes.ToAttributes(),
                                                                                 new BlockUntilComplete()
                                                                                 );
                        tcs.TrySetResult(result);
                    }
                                                                   );

                    InvokeHelper(action, messageLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
            finally
            {
                HandleConfigure -= handler;
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Gets the next audio buffer from the MediaStream track.
 /// If internal processing is slower than the incoming buffer rate,
 /// new buffers will be dropped from the incoming stream. Once all buffers
 /// are full, audio samples will be dropped until <code>RecycleBuffer()</code>
 /// is called to free a spot for another buffer.
 /// </summary>
 /// <param name="messageLoop">Optional MessageLoop instance that can be used to post the command to</param>
 /// <returns>AudioBufferInfo instance</returns>
 public Task <AudioBufferInfo> GetBufferAsync(MessageLoop messageLoop = null)
 => GetBufferAsyncCore(messageLoop);
Ejemplo n.º 22
0
        private async Task <WebSocketReceiveResult> ReceiveAsyncCore(ArraySegment <byte> buffer, MessageLoop receiveLoop = null)
        {
            var tcs = new TaskCompletionSource <WebSocketReceiveResult>();
            EventHandler <WebSocketReceiveResult> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                ReceiveData += handler;

                if (MessageLoop == null)
                {
                    //Console.WriteLine("Receive no message loop");
                    var receiveResult = Receive(buffer);
                    if (receiveResult != PPError.Ok && !tcs.Task.IsCompleted)
                    {
                        tcs.TrySetResult(new WebSocketReceiveResult(0, WebSocketMessageType.Close, true));
                    }
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var rcvMsgResult = (PPError)PPBWebSocket.ReceiveMessage(this, out receiveVar, new BlockUntilComplete());
                        WebSocketReceiveResult receiveResult = null;
                        var recVar = (Var)receiveVar;
                        if (State == WebSocketState.Open)
                        {
                            if (recVar.IsArrayBuffer)
                            {
                                var arrayBuffer = new VarArrayBuffer(receiveVar);
                                var size        = (uint)Math.Min(buffer.Count, arrayBuffer.ByteLength);

                                int offs = 0;
                                var data = arrayBuffer.Map();
                                for (offs = 0; offs < size; offs++)
                                {
                                    buffer.Array[offs] = data[offs];
                                }
                                arrayBuffer.Unmap();
                                receiveResult = new WebSocketReceiveResult(size, WebSocketMessageType.Binary, true);
                            }
                            else
                            {
                                var msg  = Encoding.UTF8.GetBytes(recVar.AsString());
                                var size = (uint)Math.Min(buffer.Count, msg.Length);

                                int offs = 0;
                                for (offs = 0; offs < size; offs++)
                                {
                                    buffer.Array[offs] = msg[offs];
                                }
                                receiveResult = new WebSocketReceiveResult(size, WebSocketMessageType.Text, true);
                            }
                        }
                        else
                        {
                            receiveResult = new WebSocketReceiveResult(0, WebSocketMessageType.Close, true, CloseStatus, CloseStatusDescription);
                        }

                        tcs.TrySetResult(receiveResult);
                    }
                                                                   );
                    InvokeHelper(action, receiveLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(new WebSocketReceiveResult(0, WebSocketMessageType.Close, true));
            }
            finally
            {
                ReceiveData -= handler;
            }
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Configures underlying buffer buffers for incoming audio samples asynchronously.
 /// If the application doesn't want to drop samples, then the
 /// <code>Buffers</code> should be
 /// chosen such that inter-buffer processing time variability won't overrun
 /// all input buffers. If all buffers are filled, then samples will be
 /// dropped. The application can detect this by examining the timestamp on
 /// returned buffers. If <code>Configure()</code> is not called, default
 /// settings will be used. Calls to Configure while the plugin holds
 /// buffers will fail.
 /// Example usage from plugin code:
 /// <code>
 /// var attribs = new MediaStreamAudioTrackAttributes() {
 ///     Buffers = 4,
 ///     Duration, 10
 ///     };
 /// track.Configure(attribs);
 /// </code>
 /// </summary>
 /// <param name="attributes">A MediaStreamAudioTrackAttributes instance</param>
 /// <param name="messageLoop">Optional MessageLoop instance that can be used to post the command to</param>
 /// <returns>Error code</returns>
 public Task <PPError> ConfigureAsync(MediaStreamAudioTrackAttributes attributes, MessageLoop messageLoop = null)
 => ConfigureAsyncCore(attributes, messageLoop);
Ejemplo n.º 24
0
        private async Task <PPError> SendAsyncCore(ArraySegment <byte> buffer, WebSocketMessageType messageType, MessageLoop sendLoop)
        {
            var tcs = new TaskCompletionSource <PPError>();

            try
            {
                if (messageType == WebSocketMessageType.Text)
                {
                    if (MessageLoop == null)
                    {
                        tcs.TrySetResult(Send(buffer, messageType));
                    }
                    else
                    {
                        Action <PPError> action = new Action <PPError>((e) =>
                        {
                            var varBuffer = new Var(Encoding.UTF8.GetString(buffer.Array));
                            var result    = (PPError)PPBWebSocket.SendMessage(this, varBuffer);
                            tcs.TrySetResult(result);
                        }
                                                                       );
                        InvokeHelper(action, sendLoop);
                    }
                }
                else
                {
                    if (MessageLoop == null)
                    {
                        tcs.TrySetResult(Send(buffer, messageType));
                    }
                    else
                    {
                        Action <PPError> action = new Action <PPError>((e) =>
                        {
                            var size        = (uint)buffer.Count;
                            var arrayBuffer = new VarArrayBuffer(size);

                            var data = arrayBuffer.Map();
                            for (int i = 0; i < size; ++i)
                            {
                                data[i] = buffer.Array[i];
                            }
                            arrayBuffer.Flush();
                            arrayBuffer.Unmap();

                            var result = (PPError)PPBWebSocket.SendMessage(this, arrayBuffer);
                            tcs.TrySetResult(result);
                        });
                        InvokeHelper(action, sendLoop);
                    }
                }

                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Receive a message from the WebSocket server asynchronously.
 /// </summary>
 /// <param name="buffer">An ArraySegment of byte that was returned</param>
 /// <returns></returns>
 public Task <WebSocketReceiveResult> ReceiveAsync(ArraySegment <byte> buffer, MessageLoop receiveLoop = null)
 {
     ThrowIfNotConnected();
     return(ReceiveAsyncCore(buffer, receiveLoop));
 }
Ejemplo n.º 26
0
        /// <summary>
        /// Sends a message to the WebSocket server asynchronously
        /// </summary>
        /// <param name="buffer">An ArraySegment of bytes that will be sent to the WebSocket server.</param>
        /// <param name="messageType">This is the message type to send Binary or Text</param>
        /// <returns>Ok or an error</returns>
        public Task <PPError> SendAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType, MessageLoop sendLoop = null)
        {
            ThrowIfNotConnected();

            if (messageType != WebSocketMessageType.Binary &&
                messageType != WebSocketMessageType.Text)
            {
                throw new ArgumentException($"Invalid Message Type {messageType} in method Send - Valid values are {WebSocketMessageType.Binary}, {WebSocketMessageType.Text}",
                                            "messageType");
            }

            ValidateArraySegment <byte>(buffer, "buffer");

            return(SendAsyncCore(buffer, messageType, sendLoop));
        }
Ejemplo n.º 27
0
        private async Task <PPError> CloseAsyncCore(WebSocketCloseStatus closeCode, string reason = null, MessageLoop closeLoop = null)
        {
            var tcs = new TaskCompletionSource <PPError>();
            EventHandler <PPError> handler = (s, e) => { tcs.TrySetResult(e); };

            try
            {
                Closed += handler;

                if (MessageLoop == null && closeLoop == null)
                {
                    Close(closeCode, reason);
                }
                else
                {
                    Action <PPError> action = new Action <PPError>((e) =>
                    {
                        var result = (PPError)PPBWebSocket.Close(this, (ushort)closeCode,
                                                                 string.IsNullOrEmpty(reason) ? null : new Var(reason),
                                                                 new BlockUntilComplete()
                                                                 );
                        tcs.TrySetResult(result);
                    }
                                                                   );
                    InvokeHelper(action, closeLoop);
                }
                return(await tcs.Task);
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                tcs.SetException(exc);
                return(PPError.Aborted);
            }
            finally
            {
                Closed -= handler;
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// Closes the connection to the WebSocket server asynchronously
 /// </summary>
 /// <param name="closeCode">The WebSocket close status</param>
 /// <param name="reason">A description of the close status.</param>
 /// <returns></returns>
 public Task <PPError> CloseAsync(WebSocketCloseStatus closeCode, string reason = null, MessageLoop closeLoop = null)
 {
     return(CloseAsyncCore(closeCode, reason, closeLoop));
 }
Ejemplo n.º 29
0
 /// <summary>
 /// SetLength() sets the length of the file asynchronously.  If the file size is extended,
 /// then the extended area of the file is zero-filled.  The FileIO object must
 /// have been opened with write access.
 /// </summary>
 /// <param name="length"></param>
 /// <param name="messageLoop">Optional MessageLoop instance used to run the command on.</param>
 /// <returns>Error code</returns>
 public Task <PPError> SetLengthAsync(long length, MessageLoop messageLoop = null)
 => SetLengthAsyncCore(length, messageLoop);
Ejemplo n.º 30
0
 /// <summary>
 /// Open() opens the specified regular file for I/O according to the given
 /// open flags, which is a bit-mask of the FileOpenFlags values.  Upon
 /// success, the corresponding file is classified as "in use" by this FileIO
 /// object until such time as the FileIO object is closed or destroyed.
 /// </summary>
 /// <param name="fileRef">A FileRef instance</param>
 /// <param name="openFlags">A bit-mask of <code>FileOpenFlags</code> values.</param>
 /// <param name="openLoop">Optional MessageLoop instance that can be used to post the command to</param>
 /// <returns>Error code</returns>
 public Task <PPError> OpenAsync(FileRef fileRef, FileOpenFlags openFlags, MessageLoop openLoop = null)
 => OpenAsyncCore(fileRef, openFlags, openLoop);