Beispiel #1
0
        public bool SaveStreamStatus(PutStreamStatusRequest putStreamStatusRequest)
        {
            try
            {
                using (var context = _chatbotContextFactory.Create())
                {
                    var currentStatus = context.StreamStatuses.FirstOrDefault(s =>
                                                                              s.BroadcasterUsername == putStreamStatusRequest.BroadcasterUsername);

                    if (currentStatus == null)
                    {
                        currentStatus = new StreamStatus
                        {
                            BroadcasterUsername = putStreamStatusRequest.BroadcasterUsername,
                            IsOnline            = putStreamStatusRequest.IsOnline
                        };

                        context.StreamStatuses.Add(currentStatus);
                        context.SaveChanges();
                        return(true);
                    }

                    currentStatus.IsOnline = putStreamStatusRequest.IsOnline;
                    context.SaveChanges();
                    return(true);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e,
                                 $"Exception caught when saving Stream Status. broadcasterUsername: {putStreamStatusRequest.BroadcasterUsername}, isOnline: {putStreamStatusRequest.IsOnline}");

                return(false);
            }
        }
        /// <summary>
        /// Bumps, or signals creation/completion/status update request, based on the stream's current state.
        /// </summary>
        /// <param name="streamStatus">Stream status with the source data filled in with info on the stream being signaled</param>
        /// <param name="cancellationToken">Used to cancel the operation</param>
        /// <returns>Stream status with target details filled in.</returns>
        /// <remarks>
        /// A returned value with equivalent target and sources hashes and a segment length equal to the full data length,
        /// then a completion signal was sent. In this case, <see cref="OnUploadCompleted( string,string)"/> will have been called.
        /// Otherwise, data uploading may begin/proceed if the caller has enough info, or the caller may bump again with a more
        /// targeted segment length.
        /// </remarks>
        public async Task <StreamStatus> BumpAsync(StreamStatus streamStatus, CancellationToken cancellationToken = default)
        {
            try
            {
                using (var client = new snh.HttpClient())
                {
                    var response = await client.PatchWithAuthenticationAsync(
                        $"{this.Config.BaseControllerPath}{this.DataSinkControllerPath}",
                        streamStatus.ToJson(),
                        this.AuthenticationHeaderGenerator,
                        this.Logger,
                        cancellationToken).ConfigureAwait(false);

                    if (!response.IsSuccessStatusCode)
                    {
                        throw new DataSinkHttpClientException("Unsuccessful service call response")
                              {
                                  ErrorResponse = response
                              };
                    }
                    using (var streamReader = new StreamReader(await response.Content.ReadAsStreamAsync().ConfigureAwait(false)))
                        using (var jsonTextReader = new JsonTextReader(streamReader))
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            return(new JsonSerializer().Deserialize <StreamStatus>(jsonTextReader));
                        }
                }
            }
            catch (Exception ex)
            {
                this.Logger?.LogError(ex, "Failure to BumpAsync");
                throw;
            }
        }
        public void OBSStreamStatus_BuildFromJSON()
        {
            int   bytesPerSec   = 294400;
            int   kbitsPerSec   = 2300;
            float strain        = 0.5f;
            int   streamTime    = 120;
            int   totalFrames   = 2000;
            int   droppedFrames = 12;
            float fps           = 29.97f;

            var data = new JObject();

            data.Add("streaming", true);
            data.Add("recording", true);
            data.Add("bytes-per-sec", bytesPerSec);
            data.Add("kbits-per-sec", kbitsPerSec);
            data.Add("strain", strain);
            data.Add("total-stream-time", streamTime);
            data.Add("num-total-frames", totalFrames);
            data.Add("num-dropped-frames", droppedFrames);
            data.Add("fps", fps);

            var streamStatus = new StreamStatus(data);

            Assert.IsTrue(streamStatus.Streaming);
            Assert.IsTrue(streamStatus.Recording);
            Assert.AreEqual(bytesPerSec, streamStatus.BytesPerSec);
            Assert.AreEqual(kbitsPerSec, streamStatus.KbitsPerSec);
            Assert.AreEqual(strain, streamStatus.Strain);
            Assert.AreEqual(streamTime, streamStatus.TotalStreamTime);
            Assert.AreEqual(totalFrames, streamStatus.TotalFrames);
            Assert.AreEqual(droppedFrames, streamStatus.DroppedFrames);
            Assert.AreEqual(fps, streamStatus.FPS);
        }
Beispiel #4
0
        private StreamDescription WaitForStreamToExitPhase(StreamStatus phaseToExit, bool useMostRecentStreamDescription = false)
        {
            int remainingTime = WaitForPhaseExitTimeout;

            if (useMostRecentStreamDescription && MostRecentStreamDescription != null && MostRecentStreamDescription.StreamStatus != phaseToExit)
            {
                return(MostRecentStreamDescription);
            }
            while (true)
            {
                StreamDescription streamDescription = DescribeStream();
                if (streamDescription == null)
                {
                    Assert.Fail();
                }
                if (streamDescription.StreamStatus != phaseToExit)
                {
                    return(streamDescription);
                }
                if (remainingTime < 0)
                {
                    Assert.Fail();
                }
                Thread.Sleep(SleepTime * 1000);
                remainingTime -= SleepTime;
            }
        }
 private void Obs_StreamStatus(OBSWebsocket sender, StreamStatus status)
 {
     lastStreamStatus = DateTime.Now;
     IsStreaming      = status.Streaming;
     IsRecording      = status.Recording;
     StreamStatusChanged?.Invoke(this, new StreamStatusEventArgs(status));
 }
Beispiel #6
0
        public bool LoadStream(string FileName, bool b3D = false)
        {
            FMOD.RESULT result;
            FMOD.System sys = m_system.System;

            is3d = b3D;

            if (sys != null)
            {
                result = sys.createStream(FileName, (b3D) ? FMOD.MODE._3D : FMOD.MODE._2D, ref m_sound);
                if (!m_system.ERRCHECK(result, "LoadStream"))
                {
                    return(false);
                }

                m_status = StreamStatus.Loaded;

                Console.WriteLine("[FMOD] SoundStream file: " + FileName + " file loaded");
            }
            else
            {
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Opens channel.
        /// </summary>
        /// <param name="connection">SSH connection object</param>
        /// <param name="command">Remote command</param>
        /// <param name="millisecondsTimeout">timeout in milliseconds</param>
        /// <exception cref="SCPClientInvalidStatusException">Channel has been already opened or already closed.</exception>
        /// <exception cref="SCPClientTimeoutException">Timeout has occurred while waiting for READY status.</exception>
        public void Open(ISSHConnection connection, string command, int millisecondsTimeout)
        {
            if (_status != StreamStatus.NotOpened)
            {
                throw new SCPClientInvalidStatusException();
            }

            ISSHChannel channel = null;
            SCPClientChannelEventHandler eventHandler =
                connection.ExecCommand(
                    (ch) => {
                channel = ch;
                return(new SCPClientChannelEventHandler(
                           new DataReceivedDelegate(OnDataReceived),
                           new ChannelStatusChangedDelegate(OnChannelStatusChanged)
                           ));
            },
                    command
                    );

            _eventHandler = eventHandler;
            _channel      = channel;

            if (!_eventHandler.WaitStatus(SCPChannelStatus.READY, millisecondsTimeout))
            {
                throw new SCPClientTimeoutException();
            }

            lock (_statusSync) {
                if (_status == StreamStatus.NotOpened)
                {
                    _status = StreamStatus.Opened;
                }
            }
        }
 private void onStreamData(OBSWebsocket sender, StreamStatus data)
 {
     if (txtStreamTime)
     {
         txtStreamTime.text = data.TotalStreamTime.ToString() + " sec";
     }
     if (txtKbitsSec)
     {
         txtKbitsSec.text = data.KbitsPerSec.ToString() + " kbit/s";
     }
     if (txtBytesSec)
     {
         txtBytesSec.text = data.BytesPerSec.ToString() + " bytes/s";
     }
     if (txtFramerate)
     {
         txtFramerate.text = data.FPS.ToString() + " FPS";
     }
     if (txtStrain)
     {
         txtStrain.text = (data.Strain * 100).ToString() + " %";
     }
     if (txtDroppedFrames)
     {
         txtDroppedFrames.text = data.DroppedFrames.ToString();
     }
     if (txtTotalFrames)
     {
         txtTotalFrames.text = data.TotalFrames.ToString();
     }
 }
        /// <summary>
        /// Close channel.
        /// </summary>
        public void Close()
        {
            lock (_statusSync) {
                if (_status != StreamStatus.Opened && _status != StreamStatus.Error)
                {
                    return;
                }

                _status = StreamStatus.Closing;
            }

            _channel.SendEOF();

            if (_status != StreamStatus.Closing)
            {
                return;
            }

            _channel.Close();

            lock (_statusSync) {
                if (_status == StreamStatus.Closing)
                {
                    _status = StreamStatus.Closed;
                }
            }
        }
        /// <summary>
        /// Send data which read from audio file
        /// </summary>
        /// <param name="ws">websocket handle</param>
        /// <param name="appId">app_id</param>
        /// <param name="audioPath">audio file path</param>
        private void SendData(WebSocket ws, string appId, string audioPath)
        {
            BinaryReader br = new BinaryReader(new FileStream(audioPath, FileMode.Open));

            byte[] currentFrame = br.ReadBytes(FRAME_SIZE);
            bool   moreData     = true;

            // send first frame
            ws.Send(GenerateData(appId, STREAM_STATUS, currentFrame));
            while (moreData)
            {
                currentFrame = br.ReadBytes(FRAME_SIZE);
                if (currentFrame.Length != 0)
                {
                    STREAM_STATUS = StreamStatus.STATUS_CONTINUE_FRAME;
                }
                else
                {
                    STREAM_STATUS = StreamStatus.STATUS_LAST_FRAME;
                    moreData      = false;
                }

                ws.Send(GenerateData(appId, STREAM_STATUS, currentFrame));
            }

            br.Close();
        }
 public LiveUrl()
 {
     Url          = "";
     StreamStatus = StreamStatus.GeneralError;
     TranscoderStreamResolution = string.Empty;
     VideoProfileResolution     = string.Empty;
     VideoSourceResolution      = string.Empty;
 }
Beispiel #12
0
 private void Obs_StreamStatus(OBSWebsocket sender, StreamStatus status)
 {
     Logger.log?.Info($"Stream Time: {status.TotalStreamTime.ToString()} sec");
     Logger.log?.Info($"Bitrate: {(status.KbitsPerSec / 1024f).ToString("N2")} Mbps");
     Logger.log?.Info($"FPS: {status.FPS.ToString()} FPS");
     Logger.log?.Info($"Strain: {(status.Strain * 100).ToString()} %");
     Logger.log?.Info($"DroppedFrames: {status.DroppedFrames.ToString()} frames");
     Logger.log?.Info($"TotalFrames: {status.TotalFrames.ToString()} frames");
 }
Beispiel #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="Stream"/> class.
 /// </summary>
 /// <param name="client">The client for which the stream belongs.</param>
 /// <param name="id">The unique identifier of the stream within the tor session.</param>
 /// <param name="target">The target of the stream.</param>
 internal Stream(Client client, int id, Host target)
 {
     this.circuitID = 0;
     this.client    = client;
     this.id        = id;
     this.purpose   = StreamPurpose.None;
     this.reason    = StreamReason.None;
     this.status    = StreamStatus.None;
     this.target    = target;
 }
Beispiel #14
0
 private void onStreamData(OBSWebsocket sender, StreamStatus status)
 {
     TotalStreamTime = status.TotalStreamTime;
     KbitsPerSecond  = status.KbitsPerSec;
     BytesPerSec     = status.BytesPerSec;
     Framerate       = status.FPS;
     Strain          = status.Strain * 100;
     DroppedFrames   = status.DroppedFrames;
     TotalFrames     = status.TotalFrames;
 }
Beispiel #15
0
 private void onStreamData(ObsWebSocket sender, StreamStatus data)
 {
     BeginInvoke((MethodInvoker)delegate {
         txtStreamTime.Text = data.TotalStreamTime.ToString() + " sec";
         txtKbitsSec.Text = data.KbitsPerSec.ToString() + " kbit/s";
         txtBytesSec.Text = data.BytesPerSec.ToString() + " bytes/s";
         txtFramerate.Text = data.FPS.ToString() + " FPS";
         txtDroppedFrames.Text = data.DroppedFrames.ToString();
         txtTotalFrames.Text = data.TotalFrames.ToString();
     });
 }
 private static void OnStreamData(ObsWebSocket sender, StreamStatus data)
 {
     App.Current.Dispatcher.Invoke(() =>
     {
         MainWindow.Form.ObsState_TotalStream.Content = data.TotalStreamTime.ToString() + " sec";
         MainWindow.Form.ObsState_FPS.Content         = data.FPS.ToString() + " FPS";
         MainWindow.Form.ObsState_Strain.Content      = (data.Strain * 100).ToString() + " %";
         MainWindow.Form.ObsState_DropFrames.Content  = data.DroppedFrames.ToString();
         MainWindow.Form.ObsState_TotalFrames.Content = data.TotalFrames.ToString();
     });
 }
Beispiel #17
0
        public void Close()
        {
            client.Dispose();
            client   = null;
            hlsQueue = null;

            Status = StreamStatus.Closed;

            buffer.Close();
            buffer = null;
        }
Beispiel #18
0
 public StreamState(StreamStatus streamStatus, DateTime latestStreamOnTime, DateTime latestStreamOffTime, TwitchStreamStatus.RootObject rawStatus)
 {
     StreamStatus        = streamStatus;
     LatestStreamOnTime  = latestStreamOnTime;
     LatestStreamOffTime = latestStreamOffTime;
     Viewers             = rawStatus.stream?.viewers ?? 0;
     Title      = rawStatus.stream?.channel.status;
     Game       = rawStatus.stream?.game;
     Delay      = rawStatus.stream?.delay ?? 0;
     AverageFps = rawStatus.stream?.average_fps ?? 0;
     CreatedAt  = rawStatus.stream?.Parsed_created_at ?? DateTime.MaxValue;
 }
 public async Task UpdateStreamAcrossServers(List <TwitchUser> userList, StreamStatus streamStatus = null)
 {
     if (streamStatus == null)
     {
         //offline
         await StreamOffline(userList);
     }
     else
     {
         await StreamOnline(userList, streamStatus);
     }
 }
 public void SetStreamInfoInCache(string username, StreamStatus streamStatus)
 {
     if (streamStatus != null)
     {
         var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(new TimeSpan(TimeSpan.TicksPerDay));
         _cache.Set(CacheKeys.TwitchUsername + username, streamStatus, cacheEntryOptions);
     }
     else
     {
         _cache.Remove(CacheKeys.TwitchUsername + username);
     }
 }
Beispiel #21
0
        /// <summary>
        /// Raises an appropriate event when the status of the stream changes.
        /// </summary>
        /// <param name="status">Task status.</param>
        /// <param name="message">Error message.</param>
        protected override void OnStatusChanged(TaskStatus status, string?message)
        {
            _status = status switch
            {
                TaskStatus.RanToCompletion => StreamStatus.Finished,
                TaskStatus.Canceled => StreamStatus.Canceled,
                TaskStatus.Faulted => StreamStatus.Faulted,
                _ => StreamStatus.Active
            };

            StatusChanged?.Invoke(this, _status, message);
        }
Beispiel #22
0
        public bool StopStream()
        {
            if (m_channel != null)
            {
                m_channel.stop();

                m_status = StreamStatus.Stopped;

                Console.WriteLine("[FMOD] SoundStream stopped");
            }
            return(true);
        }
Beispiel #23
0
        /// <summary>
        /// Opens channel.
        /// </summary>
        /// <param name="connection">SSH connection object</param>
        /// <param name="command">Remote command</param>
        /// <param name="millisecondsTimeout">timeout in milliseconds</param>
        /// <exception cref="SCPClientInvalidStatusException">Channel has been already opened or already closed.</exception>
        /// <exception cref="SCPClientTimeoutException">Timeout has occurred while waiting for READY status.</exception>
        public void Open(SSHConnection connection, string command, int millisecondsTimeout)
        {
            if (_status != StreamStatus.NotOpened)
            {
                throw new SCPClientInvalidStatusException();
            }

            SCPClientChannelEventReceiver channelReceiver =
                new SCPClientChannelEventReceiver(
                    new DataReceivedDelegate(OnDataReceived),
                    new ChannelStatusChangedDelegate(OnChannelStatusChanged)
                    );

            SSHChannel channel;

            /* FIXME: SSH1's executing command is not implemented !!
             * if (connection is SSH1Connection) {
             *  channel = ((SSH1Connection)connection).DoExecCommand(channelReceiver, command);
             * }
             * else
             */
            if (connection is SSH2Connection)
            {
                channel = ((SSH2Connection)connection).DoExecCommand(channelReceiver, command);
            }
            else
            {
                // FIXME:
                //throw new ArgumentException("connection must be SSH1Connection or SSH2Connection.");
                throw new ArgumentException("connection must be SSH2Connection.");
            }

            _channelReceiver = channelReceiver;
            _channel         = channel;

            lock (_channelReceiver.StatusChangeNotifier) {
                while (_channelReceiver.ChannelStatus != SCPChannelStatus.READY)
                {
                    bool signaled = Monitor.Wait(_channelReceiver.StatusChangeNotifier, millisecondsTimeout);
                    if (!signaled)
                    {
                        throw new SCPClientTimeoutException();
                    }
                }
            }

            lock (_statusSync) {
                if (_status == StreamStatus.NotOpened)
                {
                    _status = StreamStatus.Opened;
                }
            }
        }
 private void OnStreamStatusReceived(OBSWebsocket sender, StreamStatus status)
 {
     ConsecutiveStrains.Enqueue(status.Strain);
     Console.WriteLine($"Received strain: {status.Strain}");
     if (ConsecutiveStrains.IsFull)
     {
         float averageStrain = GetFloatAverage(ConsecutiveStrains);
         if (!ServiceIsRestarting && averageStrain >= Configuration.StrainRestartLimit)
         {
             Task.Run(() => RestartStream());
         }
     }
 }
        public void EmitStreamStatus(StreamStatus streamStatus)
        {
            _serializationDelegate.Instance = streamStatus;

            try
            {
                _recordWriter.BroadcastEmit(_serializationDelegate);
            }
            catch (Exception e)
            {
                throw new RuntimeException(e.Message, e);
            }
        }
Beispiel #26
0
        private void CheckLiveStatus(OBSWebsocket sender, StreamStatus status)
        {
            if (status.Streaming == IsStreaming)
            {
                return;
            }

            if (status.Streaming)
            {
                StreamStarted = DateTime.Now - status.TotalStreamTime;
                _streamStatusTimer.Start();
            }
        }
Beispiel #27
0
        public void ToggleStreamStatus(StreamStatus status)
        {
            if (status.Equals(StreamStatus))
            {
                return;
            }

            StreamStatus = status;

            // try and forward the stream status change to all outgoing connections.
            foreach (var streamOutput in StreamOutputs)
            {
                streamOutput.EmitStreamStatus(status);
            }
        }
Beispiel #28
0
 private void OnStreamData(OBSWebsocket sender, StreamStatus data)
 {
     BeginInvoke((MethodInvoker) delegate
     {
         // ReSharper disable LocalizableElement
         txtStreamTime.Text    = $"{data.TotalStreamTime} sec";
         txtKbitsSec.Text      = $"{data.KbitsPerSec} kb/s";
         txtBytesSec.Text      = $"{data.BytesPerSec} bytes/s";
         txtFramerate.Text     = $"{data.FPS} FPS";
         txtStrain.Text        = $"{(data.Strain * 100)} %";
         txtDroppedFrames.Text = data.DroppedFrames.ToString();
         txtTotalFrames.Text   = data.TotalFrames.ToString();
         // ReSharper restore LocalizableElement
     });
 }
        public async Task <ActionResult> StreamChange(string username, [FromBody] StreamStatusJson request)
        {
            Task <List <TwitchUser> > twitchUsersTask = _context.TwitchUsers
                                                        .AsQueryable()
                                                        .Where(t => (t.ChannelName == username))
                                                        .ToListAsync();
            StreamStatus previousStatus = GetStreamStatusFromCache(username);
            //await SendMessage(username + "'s stream was updated.");
            bool previousStatusOk = true;

            if (previousStatus == null)
            {
                previousStatusOk = false;
            }
            if (request.data.Any())
            {
                await SendMessage(request.data[0].ToString());

                //Stream Changed
                if (previousStatusOk && (request.data[0].id == previousStatus.id))
                {
                    //Duplicate Request. This might happen sometimes. No need to add to cache.
                    return(Ok());
                }
                else
                {
                    //Going Online
                    //TODO: Don't post messages if the stream was online before.
                    if (previousStatusOk)
                    {
                        //Stream was updated. Handle game changes here
                    }
                    else
                    {
                        //await SendMessage("It went online");
                        await StreamOnline(await twitchUsersTask, request.data[0]);
                    }
                }
            }
            else
            {
                //Stream Offline
                //await SendMessage("It went offline");
                await StreamOffline(await twitchUsersTask);
            }
            SetStreamInfoInCache(username, request);
            return(Ok());
        }
Beispiel #30
0
        public void Open()
        {
            client   = new HttpClient();
            hlsQueue = new Queue <HLSSegment>();

            Status = StreamStatus.Opened;

            // 32 MB buffer
            buffer = new MemoryStream(32 * 1024 * 1024);

            workerTask = new Task(Worker);
            workerTask.Start();

            writerTask = new Task(Writer);
            writerTask.Start();
        }
Beispiel #31
0
        internal void OpenForTest(SSHChannel dummyChannel)
        {
            if (_status != StreamStatus.NotOpened)
                throw new SCPClientInvalidStatusException();

            SCPClientChannelEventReceiver channelReceiver =
                new SCPClientChannelEventReceiver(
                    new DataReceivedDelegate(OnDataReceived),
                    new ChannelStatusChangedDelegate(OnChannelStatusChanged)
                );

            _channelReceiver = channelReceiver;
            _channel = dummyChannel;

            lock (_statusSync) {
                if (_status == StreamStatus.NotOpened) {
                    _status = StreamStatus.Opened;
                }
            }
        }
Beispiel #32
0
 private void OnChannelStatusChanged(SCPChannelStatus newStatus)
 {
     if (newStatus == SCPChannelStatus.CLOSED) {
         lock (_statusSync) {
             _status = StreamStatus.Closed;
         }
         lock (_bufferSync) {
             Monitor.PulseAll(_bufferSync);
         }
     }
     else if (newStatus == SCPChannelStatus.ERROR) {
         lock (_statusSync) {
             _status = StreamStatus.Error;
         }
         lock (_bufferSync) {
             Monitor.PulseAll(_bufferSync);
         }
     }
 }
Beispiel #33
0
        /// <summary>
        /// Opens channel.
        /// </summary>
        /// <param name="connection">SSH connection object</param>
        /// <param name="command">Remote command</param>
        /// <param name="millisecondsTimeout">timeout in milliseconds</param>
        /// <exception cref="SCPClientInvalidStatusException">Channel has been already opened or already closed.</exception>
        /// <exception cref="SCPClientTimeoutException">Timeout has occurred while waiting for READY status.</exception>
        public void Open(SSHConnection connection, string command, int millisecondsTimeout)
        {
            if (_status != StreamStatus.NotOpened)
                throw new SCPClientInvalidStatusException();

            SCPClientChannelEventReceiver channelReceiver =
                new SCPClientChannelEventReceiver(
                    new DataReceivedDelegate(OnDataReceived),
                    new ChannelStatusChangedDelegate(OnChannelStatusChanged)
                );

            SSHChannel channel;
            /* FIXME: SSH1's executing command is not implemented !!
            if (connection is SSH1Connection) {
                channel = ((SSH1Connection)connection).DoExecCommand(channelReceiver, command);
            }
            else
            */
            if (connection is SSH2Connection) {
                channel = ((SSH2Connection)connection).DoExecCommand(channelReceiver, command);
            }
            else {
                // FIXME:
                //throw new ArgumentException("connection must be SSH1Connection or SSH2Connection.");
                throw new ArgumentException("connection must be SSH2Connection.");
            }

            _channelReceiver = channelReceiver;
            _channel = channel;

            lock (_channelReceiver.StatusChangeNotifier) {
                while (_channelReceiver.ChannelStatus != SCPChannelStatus.READY) {
                    bool signaled = Monitor.Wait(_channelReceiver.StatusChangeNotifier, millisecondsTimeout);
                    if (!signaled) {
                        throw new SCPClientTimeoutException();
                    }
                }
            }

            lock(_statusSync) {
                if (_status == StreamStatus.NotOpened) {
                    _status = StreamStatus.Opened;
                }
            }
        }
Beispiel #34
0
        /// <summary>
        /// Close channel.
        /// </summary>
        public void Close()
        {
            lock (_statusSync) {
                if (_status != StreamStatus.Opened && _status != StreamStatus.Error)
                    return;

                _status = StreamStatus.Closing;
            }

            _channel.SendEOF();

            if (_status != StreamStatus.Closing)
                return;

            _channel.Close();

            lock (_statusSync) {
                if (_status == StreamStatus.Closing) {
                    _status = StreamStatus.Closed;
                }
            }
        }
 private async Task<StreamStatus> GetStreamStatus(FollowedStream stream, bool checkCache = true)
 {
     bool isLive;
     string response;
     JObject data;
     StreamStatus result;
     switch (stream.Type)
     {
         case FollowedStream.FollowedStreamType.Hitbox:
             var hitboxUrl = $"https://api.hitbox.tv/media/status/{stream.Username}";
             if (checkCache && cachedStatuses.TryGetValue(hitboxUrl, out result))
                 return result;
             using (var http = new HttpClient())
             {
                 response = await http.GetStringAsync(hitboxUrl).ConfigureAwait(false);
             }
             data = JObject.Parse(response);
             isLive = data["media_is_live"].ToString() == "1";
             result = new StreamStatus(hitboxUrl, isLive, data["media_views"].ToString());
             cachedStatuses.TryAdd(hitboxUrl, result);
             return result;
         case FollowedStream.FollowedStreamType.Twitch:
             var twitchUrl = $"https://api.twitch.tv/kraken/streams/{Uri.EscapeUriString(stream.Username)}?client_id=67w6z9i09xv2uoojdm9l0wsyph4hxo6";
             if (checkCache && cachedStatuses.TryGetValue(twitchUrl, out result))
                 return result;
             using (var http = new HttpClient())
             {
                 response = await http.GetStringAsync(twitchUrl).ConfigureAwait(false);
             }
             data = JObject.Parse(response);
             isLive = !string.IsNullOrWhiteSpace(data["stream"].ToString());
             result = new StreamStatus(twitchUrl, isLive, isLive ? data["stream"]["viewers"].ToString() : "0");
             cachedStatuses.TryAdd(twitchUrl, result);
             return result;
         case FollowedStream.FollowedStreamType.Beam:
             var beamUrl = $"https://beam.pro/api/v1/channels/{stream.Username}";
             if (checkCache && cachedStatuses.TryGetValue(beamUrl, out result))
                 return result;
             using (var http = new HttpClient())
             {
                 response = await http.GetStringAsync(beamUrl).ConfigureAwait(false);
             }
             data = JObject.Parse(response);
             isLive = data["online"].ToObject<bool>() == true;
             result = new StreamStatus(beamUrl, isLive, data["viewersCurrent"].ToString());
             cachedStatuses.TryAdd(beamUrl, result);
             return result;
         default:
             break;
     }
     return null;
 }
Beispiel #36
0
        /// <summary>
        /// Инициализация потока
        /// </summary>
        public void p_Init_NewPlayStream(string fileName, bool? SoundDevice)
        {
            if (SoundDevice.Value)
            {
                // останавливаем старый поток
                // не подходит для кросфейдера
                if (v_stream != 0 && v_streem_need_free) v_stream_status = StreamStatus.FREE;

                // новый поток
                //v_stream = Bass.BASS_StreamCreateFile( fileName, 0, 0, BASSFlag.BASS_DEFAULT);
                v_stream = Bass.BASS_StreamCreateFile(fileName, 0, 0, BASSFlag.BASS_STREAM_DECODE); // BASSFlag.BASS_DEFAULT
                v_stream = BassFx.BASS_FX_TempoCreate(v_stream, BASSFlag.BASS_FX_FREESOURCE);
                //BASS_StreamCreateFile(FALSE, file, 0, 0, BASS_STREAM_DECODE);
                _v_stream_status = StreamStatus.STOP; // фактическое состояние потока - остановлен
            }
        }
        /// <summary>
        /// Opens channel.
        /// </summary>
        /// <param name="connection">SSH connection object</param>
        /// <param name="command">Remote command</param>
        /// <param name="millisecondsTimeout">timeout in milliseconds</param>
        /// <exception cref="SCPClientInvalidStatusException">Channel has been already opened or already closed.</exception>
        /// <exception cref="SCPClientTimeoutException">Timeout has occurred while waiting for READY status.</exception>
        public void Open(ISSHConnection connection, string command, int millisecondsTimeout)
        {
            if (_status != StreamStatus.NotOpened)
                throw new SCPClientInvalidStatusException();

            ISSHChannel channel = null;
            SCPClientChannelEventHandler eventHandler =
             connection.ExecCommand(
                (ch) => {
                    channel = ch;
                    return new SCPClientChannelEventHandler(
                                new DataReceivedDelegate(OnDataReceived),
                                new ChannelStatusChangedDelegate(OnChannelStatusChanged)
                            );
                },
                command
            );

            _eventHandler = eventHandler;
            _channel = channel;

            if (!_eventHandler.WaitStatus(SCPChannelStatus.READY, millisecondsTimeout)) {
                throw new SCPClientTimeoutException();
            }

            lock(_statusSync) {
                if (_status == StreamStatus.NotOpened) {
                    _status = StreamStatus.Opened;
                }
            }
        }
Beispiel #38
0
        public TweetStream(TweetStreamParameters streamParameters)
        {
            this.streamParameters = streamParameters;

            status = new StreamStatus();
        }
Beispiel #39
0
 private static Color GetStatusColor(StreamStatus status)
 {
     return status.Equals(StreamStatus.STREAMING) ? Color.Green : Color.Red;
 }