Esempio n. 1
0
        public void Init(StreamSession settings)
        {
            this.serverSettings = settings;

            var address = serverSettings.NetworkIpAddress;

            ComboBoxItem networkItem = null;

            if (address == "0.0.0.0")
            {
                networkItem = networkItems.FirstOrDefault(i => i.Tag == null);
            }
            else
            {
                networkItem = networkItems.FirstOrDefault(i => (i.Tag != null && ((IPAddressInformation)i.Tag).Address.ToString() == address));
            }


            if (networkItem != null)
            {
                networkComboBox.SelectedItem = networkItem;
            }


            textBoxStreamName.Text         = serverSettings.StreamName;
            communicationPortNumeric.Value = serverSettings.CommunicationPort;
            multicastAddressTextBox.Text   = serverSettings.MutlicastAddress;

            multicastPort1Numeric.Value = serverSettings.MutlicastPort1;
            multicastPort2Numeric.Value = serverSettings.MutlicastPort2;

            multicastRadioButton.Checked = serverSettings.IsMulticast;
            transportComboBox.Enabled    = !serverSettings.IsMulticast;
        }
Esempio n. 2
0
        private void CreateStreamSessions(ScheduledStream stream, DateTimeZone timeZone)
        {
            ZonedClock zonedClock = _clock.InZone(timeZone);

            LocalDate nextOfDay = zonedClock.GetCurrentDate()
                                  .With(DateAdjusters.Next(stream.DayOfWeek));

            for (int i = 0; i < 52; i++)
            {
                LocalDateTime nextLocalStartDateTime = nextOfDay + stream.LocalStartTime;
                LocalDateTime nextLocalEndDateTime   = nextOfDay + stream.LocalEndTime;

                var streamSession = new StreamSession
                {
                    TzdbVersionId = DateTimeZoneProviders.Tzdb.VersionId,
                    UtcStartTime  = nextLocalStartDateTime
                                    .InZoneLeniently(timeZone)
                                    .ToInstant(),
                    UtcEndTime = nextLocalEndDateTime.InZoneLeniently(timeZone).ToInstant(),
                };

                stream.Sessions.Add(streamSession);

                nextOfDay = nextOfDay.PlusWeeks(1);
            }
        }
        public M3U8Playlist Aseemble(
            StreamSession streamSession,
            IEnumerable <ChunkFile> chunks)
        {
            var streamCfg =
                _streamsConfig.StreamSources
                .First(x => x.Name == streamSession.Channel);

            var root = Path.Combine(
                _chunkerConfig.ChunkStorageDir,
                streamCfg.Name);

            return(new M3U8Playlist
            {
                Headers = new[]
                {
                    "#EXTM3U",
                    "#EXT-X-VERSION:3",
                    $"#EXT-X-TARGETDURATION:{streamCfg.ChunkTime}",
                    //$"EXT-X-DISCONTINUITY-S   EQUENCE:{streamSession.DiscontSeq}",
                    $"#EXT-X-MEDIA-SEQUENCE:{streamSession.MediaSeq}",
                },
                Files = chunks.Select(file => new M3U8FileEntry
                {
                    Extinf = streamCfg.ChunkTime,
                    FilePath = file.fullPath.Replace(root, ""),
                    IsDiscont = file.isDiscont
                }).ToArray()
            });
        }
Esempio n. 4
0
        public void Setup(StreamSession session)
        {
            this.streamSession = session;

            UpdateInfo();

            timer.Tick    += Timer_Tick;
            timer.Interval = 300;
            timer.Start();
        }
Esempio n. 5
0
        private void ComboBoxSessions_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            StreamSession session = ComboBoxSessions.SelectedItem as StreamSession;

            if (session != null)
            {
                this.DataContext         = session;
                TabMainControl.IsEnabled = true;
            }
        }
Esempio n. 6
0
 public static EventViewModel ToViewModel(this StreamSession src)
 {
     return(new EventViewModel
     {
         Id = src.Id,
         ScheduledStreamId = src.ScheduledStream.Id,
         ChannelId = src.ScheduledStream.Channel.Id,
         ChannelName = src.ScheduledStream.Channel.Name,
         Uri = src.ScheduledStream.Channel.Uri,
         UtcStartTime = src.UtcStartTime.ToDateTimeUtc(),
         UtcEndTime = src.UtcEndTime.ToDateTimeUtc(),
     });
 }
        private void ButtonExportFileTimeRange_Click(object sender, RoutedEventArgs e)
        {
            if (DataGridFlowRates.SelectedItem is FlowRate)
            {
                FlowRate      flowRate = DataGridFlowRates.SelectedItem as FlowRate;
                StreamSession session  = (StreamSession)DataContext;


                OpenFileDialog openFile = new OpenFileDialog();
                openFile.Title           = "Select Target Export File";
                openFile.CheckFileExists = false;
                openFile.CheckPathExists = true;
                openFile.DefaultExt      = ".txt";
                openFile.FileName        = System.IO.Path.GetFileNameWithoutExtension(MainWindow.Analyzer.LastFilePath) + "_part_" + flowRate.Time.ToString("hhmmss") + ".txt";

                var result = openFile.ShowDialog();

                if (result.HasValue && result.Value)
                {
                    string targetPath = openFile.FileName;

                    this.ButtonExportFileTimeRange.IsEnabled = false;
                    MainWindow.Instance.ShowPleaseWait();
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            MainWindow.Analyzer.ExportFlowRateRows(session, flowRate, targetPath);
                        }
                        catch (Exception ex)
                        {
                            MainWindow.Instance.ShowError(ex.ToString());
                        }
                    }).ContinueWith(new Action <Task>((Task t) =>
                    {
                        Dispatcher.BeginInvoke(new Action(() =>
                        {
                            MainWindow.Instance.HidePleaseWait();
                            this.ButtonExportFileTimeRange.IsEnabled = true;
                            MessageBox.Show("File part successfully exported to: " + targetPath, "Info", MessageBoxButton.OK, MessageBoxImage.Information);
                        }));
                    }));
                }
            }
            else
            {
                MessageBox.Show("Please select a flow rate!");
            }
        }
Esempio n. 8
0
        public void StartStreaming()
        {
            logger.Debug("StartStreaming()");

            if (mediaStreamer.State == MediaStreamerState.Shutdown)
            {
                this.ErrorObj  = null;
                this.ErrorCode = 0;

                streamSession = CreateSession();


                streamSession.Validate();

                mediaStreamer.Start(streamSession);
            }
        }
        public string GenerateToken(StreamSession session, string salt)
        {
            var strToHash = string.Join("", new[]
            {
                session.Channel,
                session.IP,
                session.UserAgent,
                DateTime.Now.ToString(),
                salt
            });

            return(String.Join("", new[]
            {
                //session.SessionType.ToString(),
                "_",
                SHA256Encrypt(strToHash)
            }));
        }
Esempio n. 10
0
        public static void RegisterDataStreamHandler <T>(StreamSession <T> .DataHandler handler) where T : IHeartbeat
        {
            if (typeof(T) != typeof(Event) && typeof(T) != typeof(RateStreamResponse))
            {
                throw new ArgumentException(string.Format("Unrecognized stream data handler type: ", typeof(T)));
            }

            if (_eventsStreamStarted && typeof(T) == typeof(Event))
            {
                _eventsSession.DataReceived += handler as StreamSession <Event> .DataHandler;
            }
            else if (_rateStreamStarted && typeof(T) == typeof(RateStreamResponse))
            {
                _ratesSession.DataReceived += handler as StreamSession <RateStreamResponse> .DataHandler;
            }
            else
            {
                throw new InvalidOperationException(string.Format("Stream not started for handler type: ", typeof(T)));
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Starts a new stream session. Call ExtendSession to extend the session.
        /// </summary>
        public async Task <StreamSession> OpenStreamAsync(
            int streamId,
            CancellationToken cancel)
        {
            var streamConfig = (await GetStreamConfigsAsync(cancel)).FirstOrDefault(s => s.Id == streamId);

            if (streamConfig == null)
            {
                throw new NotFoundException("No stream found by Id");
            }

            var token    = Rando.GetReallyRandomString(30);
            var dirToken = Rando.GetReallyRandomString(30);
            var session  = new StreamSession()
            {
                Id         = Guid.NewGuid(),
                StreamId   = streamConfig.Id,
                StreamName = streamConfig.Name,
                Token      = token,
                Expirers   = DateTime.UtcNow.AddSeconds(_Config.ClientSessionTTLSeconds),
                TTLSeconds = _Config.ClientSessionTTLSeconds,
                Uri        = $"Stream/{dirToken}/{StreamName}"
            };

            lock (_Sync){
                _Sessions.Add(session);
            }

            var ready = new TaskCompletionSource <bool>();

            RunStreamAsync(session, streamConfig, dirToken, ready, cancel, _Cancel.Token).LogErrors();

            using (cancel.Register(() => {
                ready.TrySetCanceled();
            }))
            {
                await ready.Task;
            }

            return(session);
        }
Esempio n. 12
0
        public async Task<IActionResult> OnPostAsync(int channelId)
        {
            ScheduledStream stream = StreamTime.ToModel();

            var channel = await _context.Channels
                .Include(x => x.ScheduledStreams)
                .SingleAsync(x => x.Id == channelId);

            channel.ScheduledStreams.Add(stream);

            var zone = DateTimeZoneProviders.Tzdb[channel.TimeZoneId];
            var version = DateTimeZoneProviders.Tzdb.VersionId;
            ZonedClock zonedClock = _clock.InZone(zone);

            LocalDate today = zonedClock.GetCurrentDate();
            LocalDate next = today.With(DateAdjusters.Next(stream.DayOfWeek));

            
            for (int i = 0; i < 52; i++)
            {
                LocalDateTime nextLocalStartDateTime = next + stream.LocalStartTime;
                LocalDateTime nextLocalEndDateTime = next + stream.LocalEndTime;

                var streamSession = new StreamSession
                {
                    TzdbVersionId = version,
                    UtcStartTime = nextLocalStartDateTime.InZoneLeniently(zone).ToInstant(),
                    UtcEndTime = nextLocalEndDateTime.InZoneLeniently(zone).ToInstant(),
                };

                stream.Sessions.Add(streamSession);

                next = next.PlusWeeks(1);
            }

            await _context.SaveChangesAsync();

            return RedirectToPage("./Index");

        }
Esempio n. 13
0
        public static Config Default()
        {
            var config = new Config();


            var screenCaptureProperties = new ScreenCaptureProperties
            {
                CaptureMouse  = true,
                AspectRatio   = true,
                CaptureType   = VideoCaptureType.DXGIDeskDupl,
                UseHardware   = true,
                Fps           = 60,//30,
                ShowDebugInfo = false,
            };

            config.SelectAreaRectangle     = new Rectangle(0, 0, 640, 480);
            config.ScreenCaptureProperties = screenCaptureProperties;


            config.Session = StreamSession.Default();

            return(config);
        }
Esempio n. 14
0
 public static async Task StartRatesStreamAsync(List <string> instruments, StreamSession <RateStreamResponse> .DataHandler onRateDataReceived)
 {
     await StartRatesStreamAsync(EEnvironment.Practice, Security.Token.PracticeToken, Security.Account.PracticeAccount, instruments, onRateDataReceived);
 }
Esempio n. 15
0
        public static async Task StartEventsStreamAsync(EEnvironment environment, string token, int account, StreamSession <Event> .DataHandler dataHandler, EventsSession.SessionStatusHandler faultHandler)
        {
            if (Credentials.GetDefaultCredentials() == null)
            {
                Credentials.SetCredentials(environment, token, account);
            }

            if (!_eventsStreamStarted)
            {
                _eventsSession = new MarketMinerEventsSession(account);

                if (dataHandler != null)
                {
                    _eventsSession.DataReceived += dataHandler;
                }

                // register fault handlers .. yes, the order matters
                _eventsSession.SessionStatusChanged += (s, e) => _eventsStreamStarted = false;
                if (faultHandler != null)
                {
                    _eventsSession.SessionStatusChanged += faultHandler;
                }

                _eventReceived = new Semaphore(0, 100);
                _eventsSession.StartSession();

                if (!_eventsSession.Stopped())
                {
                    // good start
                    _eventReceived.WaitOne(10000);
                    _eventsStreamStarted = true;
                }
            }
            else
            {
                _eventsSession.DataReceived += dataHandler;
            }
        }
Esempio n. 16
0
        /// <summary>
        ///
        /// </summary>
        private async Task RunStreamAsync(
            StreamSession session,
            StreamConfig streamConfig,
            string dirToken,
            TaskCompletionSource <bool> ready,
            CancellationToken clientCancel,
            CancellationToken cancel)
        {
            Process proc = null;
            var     root = _Config.HlsRoot;

            if (string.IsNullOrWhiteSpace(root))
            {
                throw new InvalidConfigException("HlsRoot not set");
            }

            var cmd = _Config.HlsCommand;

            if (string.IsNullOrWhiteSpace(cmd))
            {
                throw new InvalidConfigException("HlsCommand not set");
            }

            var streamDir = Path.Combine(root, dirToken);

            if (Directory.Exists(streamDir))
            {
                throw new InvalidOperationException("streamDir already exists");
            }

            try{
                lock (_Sync){
                    if (_FirstStream)
                    {
                        _FirstStream = false;

                        var files = Directory.GetFiles(root);
                        var dirs  = Directory.GetDirectories(root);
                        foreach (var file in files)
                        {
                            try{
                                File.Delete(file);
                            }catch (Exception ex) {
                                _Logger.LogWarning(ex, "Unable to delete old hls file " + file);
                            }
                        }
                        foreach (var dir in dirs)
                        {
                            try{
                                Directory.Delete(dir, true);
                            }catch (Exception ex) {
                                _Logger.LogWarning(ex, "Unable to delete old hls directory " + dir);
                            }
                        }

                        _Logger.LogInformation("HLS cleanup complete");
                    }
                }

                Directory.CreateDirectory(streamDir);


                cmd = cmd
                      .Replace("{INPUT}", streamConfig.Uri)
                      .Replace("{STREAM_NAME}", StreamName);
                var args = cmd.Split(' ', 2);

                proc = new Process()
                {
                    StartInfo = new ProcessStartInfo()
                    {
                        WorkingDirectory = streamDir,
                        FileName         = args[0],
                        Arguments        = args.Length == 1?null:args[1]
                    }
                };

                proc.Start();

                var timeout = DateTime.UtcNow.AddSeconds(_Config.StreamStartTimeoutSeconds);
                while (true)
                {
                    if (DateTime.UtcNow > timeout)
                    {
                        throw new RequestException(408, "Start start timeout");
                    }
                    await Task.Delay(20);

                    var files  = Directory.GetFiles(streamDir, "*.m3u8");
                    var exists = files.Any(f => f.EndsWith(StreamName));
                    cancel.ThrowIfCancellationRequested();
                    clientCancel.ThrowIfCancellationRequested();
                    if (exists)
                    {
                        break;
                    }
                }

                ready.TrySetResult(true);

                var n = DateTime.UtcNow;

                while (!cancel.IsCancellationRequested)
                {
                    await Task.Delay(5000);

                    if (session.Expirers < DateTime.UtcNow)
                    {
                        _Logger.LogInformation("Client Stream expired");
                        break;
                    }

                    proc.Refresh();
                    if (proc.HasExited)
                    {
                        throw new Exception("stream commanded existed with exit code " + proc.ExitCode);
                    }
                }
            }catch (Exception ex) {
                if (!cancel.IsCancellationRequested && !(!ready.Task.IsCompleted && cancel.IsCancellationRequested))
                {
                    _Logger.LogError(ex, "RunStreamAsync");
                }
            }finally{
                if (proc != null)
                {
                    try{ proc.Kill(); }catch {}
                    proc.SafeDispose();
                }
                try{
                    if (Directory.Exists(streamDir))
                    {
                        Directory.Delete(streamDir, true);
                    }
                }catch {}
                lock (_Sync){
                    _Sessions.Remove(session);
                }
            }
        }
Esempio n. 17
0
        public static async Task StartRatesStreamAsync(EEnvironment environment, string token, int account, List <string> instruments, StreamSession <RateStreamResponse> .DataHandler dataHandler, RatesSession.SessionStatusHandler statusHandler)
        {
            if (Credentials.GetDefaultCredentials() == null)
            {
                Credentials.SetCredentials(environment, token, account);
            }

            if (!_rateStreamStarted)
            {
                var oandaInstruments = await Rest.GetInstrumentsAsync(account, null, instruments);

                _ratesSession = new MarketMinerRatesSession(account, oandaInstruments);

                if (dataHandler != null)
                {
                    _ratesSession.DataReceived += dataHandler;
                }

                // register fault handlers .. yes, the order matters
                _ratesSession.SessionStatusChanged += (s, e) => _rateStreamStarted = false;
                if (statusHandler != null)
                {
                    _ratesSession.SessionStatusChanged += statusHandler;
                }

                _tickReceived = new Semaphore(0, 100);
                _ratesSession.StartSession();

                if (!_ratesSession.Stopped())
                {
                    // good start
                    _tickReceived.WaitOne(10000);
                    _rateStreamStarted = true;
                }
            }
            else
            {
                _ratesSession.DataReceived += dataHandler;
            }
        }
 public TokenParseResult(StreamSession session, IActionResult ac)
 {
     this.session      = session;
     this.actionResult = ac;
 }
Esempio n. 19
0
        public static async Task StartEventsStreamAsync(StreamSession <Event> .DataHandler onEventDataReceived)
        {
            Credentials credentials = Credentials.GetDefaultCredentials();

            await StartEventsStreamAsync(credentials.Environment, credentials.AccessToken, credentials.DefaultAccountId, onEventDataReceived);
        }
Esempio n. 20
0
        public static string RegisterDataStreamHandler <T>(StreamSession <T> .DataHandler handler) where T : IHeartbeat
        {
            MAOE.Utilities.RegisterDataStreamHandler <T>(handler);

            return(string.Format("OANDA {0} stream handler registered.", typeof(T).Name.ToString()));
        }
Esempio n. 21
0
 public static async Task StartEventsStreamAsync(EEnvironment environment, string token, int account, StreamSession <Event> .DataHandler handler)
 {
     await MAOE.Utilities.StartEventsStreamAsync(environment, token, account, handler, OnEventsSessionStatusChanged);
 }
Esempio n. 22
0
        private StreamSession CreateSession()
        {
            var session = StreamSession.Default();

            var transport = TransportMode.Udp;

            if (PropertyNetwork.UnicastProtocol == ProtocolKind.TCP)
            {
                transport = TransportMode.Tcp;
            }


            session.StreamName       = Name;
            session.NetworkIpAddress = PropertyNetwork.Network ?? "0.0.0.0";

            session.CommunicationPort = PropertyNetwork.Port;

            if (PropertyNetwork.Port > 0)
            {
                session.CommunicationPort = PropertyNetwork.Port;
            }
            else if (PropertyNetwork.CommunicationPort > 0)
            {
                session.CommunicationPort = PropertyNetwork.CommunicationPort;
            }
            else
            {
                session.CommunicationPort = Helpers.NetworkHelper.FindAvailableTcpPort();
            }

            //if(PropertyNetwork.CommunicationPort <=0)
            //{
            //    session.CommunicationPort = PropertyNetwork.Port;
            //}
            //else
            //{
            //    session.CommunicationPort = PropertyNetwork.CommunicationPort;
            //}


            //int communicationPort = PropertyNetwork.Port;
            //if (communicationPort <= 0)
            //{// если порт не задан - ищем свободный начиная с 808

            //    //communicationPort = GetRandomTcpPort();

            //    var freeTcpPorts = MediaToolkit.Utils.NetTools.GetFreePortRange(System.Net.Sockets.ProtocolType.Tcp, 1, 808);
            //    if (freeTcpPorts != null && freeTcpPorts.Count() > 0)
            //    {
            //        communicationPort = freeTcpPorts.FirstOrDefault();
            //    }
            //}

            ////PropertyNetwork.CommunicationPort = communicationPort;

            //session.CommunicationPort = communicationPort;


            session.TransportMode = transport;

            bool isMulticast = !PropertyNetwork.IsUnicast;

            session.IsMulticast = isMulticast;

            if (isMulticast)
            {
                //VAlidate....
                session.MutlicastAddress = PropertyNetwork.MulticastIp;

                session.MutlicastPort1 = PropertyNetwork.MulticasVideoPort;
                session.MutlicastPort2 = PropertyNetwork.MulticasAudioPort;
            }

            var videoSettings = session.VideoSettings;

            var encoderResolution = new Size(PropertyVideo.ResolutionWidth, PropertyVideo.ResolutionHeight);

            videoSettings.StreamFlags &= ~VideoStreamFlags.UseEncoderResoulutionFromSource;
            if (AdvancedSettings.UseResolutionFromCaptureSource)
            {
                videoSettings.StreamFlags |= VideoStreamFlags.UseEncoderResoulutionFromSource;
            }
            else
            {
                encoderResolution = new Size(AdvancedSettings.Width, AdvancedSettings.Height);
            }


            var videoEncoderSettings = videoSettings.EncoderSettings;

            videoEncoderSettings.EncoderId  = AdvancedSettings.EncoderId;
            videoEncoderSettings.Bitrate    = AdvancedSettings.Bitrate;
            videoEncoderSettings.MaxBitrate = AdvancedSettings.MaxBitrate;
            videoEncoderSettings.Width      = encoderResolution.Width;
            videoEncoderSettings.Height     = encoderResolution.Height;


            videoEncoderSettings.FrameRate  = new MediaRatio(AdvancedSettings.Fps, 1);
            videoEncoderSettings.Profile    = AdvancedSettings.H264Profile;
            videoEncoderSettings.LowLatency = AdvancedSettings.LowLatency;

            var captureRegion = PropertyVideo.VideoRect;
            var captureType   = PropertyVideo.CaptType;
            //var captureFps = PropertyVideo.CaptFps;
            var captureFps  = AdvancedSettings.Fps;
            var useHardware = PropertyVideo.CaptUseHardware;

            var screenCaptureProperties = new ScreenCaptureProperties
            {
                CaptureMouse = PropertyVideo.CaptureMouse,

                CaptureType     = captureType, // VideoCaptureType.DXGIDeskDupl,
                UseHardware     = useHardware,
                Fps             = captureFps,
                ShowDebugInfo   = false,
                ShowDebugBorder = PropertyVideo.ShowCaptureBorder,
                AspectRatio     = AdvancedSettings.KeepAspectRatio,
            };

            VideoCaptureDevice captureDevice = null;

            //var videoSourceItem = PropertyVideo.Display;
            if (PropertyVideo.IsUvcDevice)
            {
                captureDevice = new UvcDevice
                {
                    Name       = PropertyVideo.DeviceName,
                    Resolution = captureRegion.Size,
                    DeviceId   = PropertyVideo.DeviceId,
                };
            }
            else
            {
                captureDevice = new ScreenCaptureDevice
                {
                    CaptureRegion = captureRegion,
                    DisplayRegion = captureRegion,
                    Name          = PropertyVideo.DeviceName,

                    Resolution = captureRegion.Size,
                    Properties = screenCaptureProperties,
                    DeviceId   = PropertyVideo.DeviceId,
                };
            }

            if (PropertyAudio.IsEnabled)
            {
                var deviceId = PropertyAudio.DeviceId;

                var audioDevice = MediaToolkit.AudioTool.GetAudioCaptureDevices().FirstOrDefault(d => d.DeviceId == deviceId);
                if (audioDevice != null)
                {
                    session.AudioSettings.Enabled = true;
                    audioDevice.Properties        = new WasapiCaptureProperties();

                    session.AudioSettings.CaptureDevice = audioDevice;
                }
            }
            else
            {
                session.AudioSettings.Enabled = false;
            }

            logger.Info("CaptureDevice: " + captureRegion);

            session.VideoSettings.CaptureDevice = captureDevice;

            return(session);
        }
Esempio n. 23
0
 public static async Task StartRatesStreamAsync(EEnvironment environment, string token, int account, List <string> instruments, StreamSession <RateStreamResponse> .DataHandler handler)
 {
     await MAOE.Utilities.StartRatesStreamAsync(environment, token, account, instruments, handler, OnRatesSessionStatusChanged);
 }