protected virtual void OnLapPacketReceived(PacketReceivedEventArgs <PacketLapData> e) { if (CanSend) { LapPacketReceived?.Invoke(this, e); } }
/// <summary> /// Handle responses from the simulator that tell us a texture we have requested is unable to be located /// or no longer exists. This will remove the request from the pipeline and free up a slot if one is in use /// </summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void ImageNotInDatabaseHandler(object sender, PacketReceivedEventArgs e) { ImageNotInDatabasePacket imageNotFoundData = (ImageNotInDatabasePacket)e.Packet; TaskInfo task; if (TryGetTransferValue(imageNotFoundData.ImageID.ID, out task)) { // cancel acive request and free up the threadpool slot if (task.State == TextureRequestState.Progress) { resetEvents[task.RequestSlot].Set(); } // fire callback to inform the caller foreach (TextureDownloadCallback callback in task.Callbacks) { callback(TextureRequestState.NotFound, new AssetTexture(imageNotFoundData.ImageID.ID, Utils.EmptyBytes)); } resetEvents[task.RequestSlot].Set(); RemoveTransfer(imageNotFoundData.ImageID.ID); } else { Logger.Log("Received an ImageNotFound packet for an image we did not request: " + imageNotFoundData.ImageID.ID, Helpers.LogLevel.Warning); } }
private void Handle_UseItem(PacketReceivedEventArgs args) { int slotNum = args.Message.ReadInt32(); // Sanity check: is there actually an item in this slot? if (_player.Inventory.GetSlot(slotNum) == null) { // Log it! Logger.LogEvent($"Player attempted to equip bad item! User: {_player.Name} SlotNum: {slotNum}.", LogTypes.GAME, Environment.StackTrace); return; } Item item = _player.Inventory.GetSlot(slotNum).Item; if (item.ItemType == ItemTypes.Equipment) { _player.Equipment.Equip(item); item.OnEquip(_player); _player.Inventory.RemoveItem(slotNum, 1); } else if (item.ItemType == ItemTypes.Usable) { item.OnUse(_player); } }
private void Handle_PlayerInteract(PacketReceivedEventArgs args) { foreach (var mapObject in _player.Layer.GetCollidingMapObjects(_player.Position, _player.CollisionBounds)) { mapObject.OnInteract(_player); } }
private void Handle_MapData(PacketReceivedEventArgs args) { _mapLoaded = false; this.LoadingMap?.Invoke(this, new EventArgs()); // Make sure the player is no longer moving if (_player != null) { _player.State = ActorStates.Idle; } var name = args.Message.ReadString(); var dimensions = args.Message.ReadVector(); _map?.Unload(); // unload the previous map if it existed. _map = new Map(dimensions, name); _map.Unpack(args.Message); _mapLoaded = true; _camera.Bounds = new Rectangle(_map.Bounds.X * EngineConstants.TILE_SIZE, _map.Bounds.Y * EngineConstants.TILE_SIZE, _map.Bounds.Width * EngineConstants.TILE_SIZE, _map.Bounds.Height * EngineConstants.TILE_SIZE); this.LoadedMap?.Invoke(this, new EventArgs()); }
private void HandlePacket(object sender, PacketReceivedEventArgs e) { //_packetLogger.Log<ERelayPacket>(e.Packet); switch (e.Packet.PacketID) { case (byte)ERelayPacket.CLoginReq: HandleLoginRequest(e.Session, e.Packet); break; case (byte)ERelayPacket.CJoinTunnelReq: HandleJoinTunnelRequest(e.Session, e.Packet); break; case (byte)ERelayPacket.CLeaveTunnelReq: HandleLeaveTunnelRequest(e.Session, e.Packet); break; case (byte)ERelayPacket.CUseTunnelReq: HandleUseTunnelRequest(e.Session, e.Packet); break; case (byte)ERelayPacket.CDetourPacketReq: HandleDetourPacketRequest(e.Session, e.Packet); break; case (byte)ERelayPacket.CKeepAliveReq: break; default: _logger.Warning("Unkown packet {0}", e.Packet.PacketID.ToString("x2")); break; } }
private void Handle_UnequipItem(PacketReceivedEventArgs args) { int slotNum = args.Message.ReadInt32(); // Sanity check: is there actually an item in this slot? if (_player.Equipment.GetSlot(slotNum) == null) { // Log it! Logger.LogEvent($"Player attempted to unequip bad item! User: {_player.Name} SlotNum: {slotNum}.", LogTypes.GAME, Environment.StackTrace); return; } var item = _player.Equipment.GetSlot(slotNum); if (item.ItemType != ItemTypes.Equipment || item.SlotType == EquipmentSlots.NE) { // Log it! Logger.LogEvent($"Player attempted to unequip unequippable item! User: {_player.Name} SlotNum: {slotNum}.", LogTypes.GAME, Environment.StackTrace); return; } _player.Equipment.SetSlot(slotNum, null); _player.Inventory.Add(item, 1); _player.SendEquipmentUpdate(); _player.CalculateBoostedStats(); }
private void Handle_PlayerJoined(PacketReceivedEventArgs args) { var uniqueID = args.Message.ReadInt64(); Player player; if (uniqueID == Client.ServiceLocator.GetService <NetHandler>().UniqueID) { if (_player == null) { player = new Player(_camera, uniqueID); player.Unpack(args.Message, _contentManager); _player = player; } player = _player; player.EventOccured += (sender, eventArgs) => this.EventOccured?.Invoke(this, new SubjectEventArgs(eventArgs.EventName, player)); } else { player = new Player(uniqueID); player.Unpack(args.Message, _contentManager); } _map?.AddEntity(uniqueID, player); this.EventOccured?.Invoke(this, new SubjectEventArgs("playerJoined", new object[] { player })); this.EventOccured?.Invoke(this, new SubjectEventArgs("playerUpdated", new object[] { player })); }
private static void DataReceived(object sender, PacketReceivedEventArgs e) { Console.WriteLine($"#Conduit:\tReceived { e.Packet.Data?.Length } bytes."); switch (e.Packet.PacketType) { case ConduitPacketType.Print: Console.WriteLine("#Component:\n->\t" + Encoding.Default.GetString(e.Packet.Data)); break; case ConduitPacketType.Execute: Console.WriteLine($"#Component:\tExecuting assembly."); var path = Encoding.Default.GetString(e.Packet.Data); ScriptDomain = AppDomain.CreateDomain("ScriptDomain"); ScriptDomain.ExecuteAssembly(path); break; case ConduitPacketType.Terminate: Console.WriteLine($"#Component:\tAborting running assembly."); AppDomain.Unload(ScriptDomain); break; } }
/// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void OnlineNotificationHandler(object sender, PacketReceivedEventArgs e) { Packet packet = e.Packet; if (packet.Type == PacketType.OnlineNotification) { OnlineNotificationPacket notification = ((OnlineNotificationPacket)packet); foreach (OnlineNotificationPacket.AgentBlockBlock block in notification.AgentBlock) { FriendInfo friend; lock (FriendList.Dictionary) { if (!FriendList.ContainsKey(block.AgentID)) { friend = new FriendInfo(block.AgentID, FriendRights.CanSeeOnline, FriendRights.CanSeeOnline); FriendList.Add(block.AgentID, friend); } else { friend = FriendList[block.AgentID]; } } bool doNotify = !friend.IsOnline; friend.IsOnline = true; if (m_FriendOnline != null && doNotify) { OnFriendOnline(new FriendInfoEventArgs(friend)); } } } }
private void Handle_InventoryUpdate(PacketReceivedEventArgs args) { var inventoryWidget = this.GuiManager.GetWidget <WidgetContainer>("inventoryWidget"); inventoryWidget.ClearWidgets(); for (int i = 0; i < Constants.MAX_INVENTORY; i++) { bool slotOccupied = args.Message.ReadBoolean(); if (slotOccupied) { var itemName = args.Message.ReadString(); var textureName = args.Message.ReadString(); var slotType = args.Message.ReadInt32(); var amount = args.Message.ReadInt32(); Texture2D texture2D = this.ContentManager.LoadTexture2D(Constants.FILEPATH_GFX + "/Items/" + textureName); var invSlot = new Picture(texture2D); invSlot.Position = new Vector2(((i % 5) * Constants.INV_SLOT_OFFSET) + Constants.INVENTORY_OFFSET_X, ((i / 5) * Constants.INV_SLOT_OFFSET) + Constants.INVENTORY_OFFSET_Y) + inventoryWidget.Position; invSlot.Visible = true; invSlot.Clicked += InvSlot_Clicked; inventoryWidget.AddWidget(invSlot, "slot" + i); } } }
private void Handle_PlayerMessage(PacketReceivedEventArgs args) { Color color; ChatMessageType messageType = (ChatMessageType)args.Message.ReadByte(); switch (messageType) { case ChatMessageType.Regular: color = Color.White; break; case ChatMessageType.Announcement: color = new Color(0, 255, 255); break; case ChatMessageType.Alert: color = Color.Red; break; default: color = Color.White; break; } this.GuiManager.GetWidget <Chatbox>("chatbox").AddEntry("[" + DateTime.Now.ToString("h:mm tt") + "] " + args.Message.ReadString(), color); }
private void Handle_PlayerJoined(PacketReceivedEventArgs args) { var uniqueID = args.Message.ReadString(); Player player; if (uniqueID == Engine.Services.Get <NetHandler>().UniqueID) { if (_player == null) { player = new Player(_camera, uniqueID); _player = player; this.PlayerJoined?.Invoke(this, new PlayerJoinedEventArgs(player)); } player = _player; } else { player = new Player(uniqueID); this.PlayerJoined?.Invoke(this, new PlayerJoinedEventArgs(player)); } player.Unpack(args.Message, _contentManager); _map?.AddEntity(uniqueID, player); }
private void _networkClient_PacketReceived(object sender, PacketReceivedEventArgs e) { var type = (MessageType)e.Packet.ProtocolHeader.Type; if (type == MessageType.DeviceStateService) { HandleDeviceStateService(e.Packet, e.RemoteAddress); } else { __logger.Info($"Packet Event: {type} -- {e.Packet.Frame.Source}"); if (_tcsDictionary.ContainsKey(e.Packet.Frame.Source)) { TaskCompletionSource <LIFXProtocolPacket> v = null; var success = _tcsDictionary.TryGetValue(e.Packet.Frame.Source, out v); if (!success) { throw new Exception($"Failed to get key {e.Packet.Frame.Source} from dictionary"); } v.SetResult(e.Packet); } //switch (type) //{ // case MessageType.DeviceStateVersion: // HandleDeviceStateService(e.Packet, e.RemoteAddress); // break; // default: // __logger.Warn($"Unknown Packet: Type: {e.Packet.ProtocolHeader.Type} - Remote Address: {e.RemoteAddress}"); // // Todo: Log detail of this packet for futher investigation // break; //} } }
/// <summary> /// Logs the packet received for this client. /// </summary> /// <remarks> /// This handler assumes that packets are processed one at a time. /// </remarks> /// <param name="sender">Sender.</param> /// <param name="args">Arguments.</param> private void HandlePacket(object sender, PacketReceivedEventArgs args) { // Console.WriteLine( // "Received packet {0} from {1} for {2}", args.Packet.Type, args.Simulator.Name, m_client.Self.Name); lock (this) { if (!m_isLogging) { return; } m_logStreamWriter.WriteLine("Received: {0}", DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss.fff")); try { m_logStreamWriter.WriteLine(PacketDecoder.PacketToString(args.Packet)); } catch (Exception e) { m_logStreamWriter.WriteLine("Failed to write decode of {0}, exception {1}", args.Packet.Type, e); } if (--m_packetsToLogRemaining <= 0) { m_client.Network.UnregisterCallback(PacketType.Default, HandlePacket); m_logStreamWriter.Close(); Console.WriteLine("Finished logging packets for {0}", m_client.Self.Name); m_isLogging = false; } } }
/// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void MapBlockReplyHandler(object sender, PacketReceivedEventArgs e) { MapBlockReplyPacket map = (MapBlockReplyPacket)e.Packet; foreach (MapBlockReplyPacket.DataBlock block in map.Data) { if (block.X != 0 || block.Y != 0) { GridRegion region; region.X = block.X; region.Y = block.Y; region.Name = Utils.BytesToString(block.Name); // RegionFlags seems to always be zero here? region.RegionFlags = (RegionFlags)block.RegionFlags; region.WaterHeight = block.WaterHeight; region.Agents = block.Agents; region.Access = (SimAccess)block.Access; region.MapImageID = block.MapImageID; region.RegionHandle = Utils.UIntsToLong((uint)(region.X * 256), (uint)(region.Y * 256)); lock (Regions) { Regions[region.Name] = region; RegionsByHandle[region.RegionHandle] = region; } if (m_GridRegion != null) { OnGridRegion(new GridRegionEventArgs(region)); } } } }
private void OnPacketReceived(object sender, PacketReceivedEventArgs args) { if (args.Response != Enums.Response.OK) { return; } switch (args.Type) { case Enums.Type.BLamp: { LampUpdate?.Invoke(this, new BLampEventArgs((BLamp)args.Packet)); break; } case Enums.Type.SKRegData: { SkIntensityChanged?.Invoke(this, new SkIntensityChangedEventArgs((SKRegData)args.Packet)); break; } case Enums.Type.SkAttr: { SkAttrChanged?.Invoke(this, new SkAttrChangedEventArgs((SKRegAttr)args.Packet)); break; } } }
/// <summary> /// Saving the decoded Packets to our active Buffer, if the Buffer is full queue it into the OutputQueue /// and wait until another buffer gets freed up /// </summary> private void AudioPacketDecoded(object sender, PacketReceivedEventArgs args) { if (BitRate == 0) { BitRate = ((AudioFileStream)sender).BitRate; } foreach (var p in args.PacketDescriptions) { _currentByteCount += p.DataByteSize; AudioStreamPacketDescription packetDescription = p; int left = BufferSize - _currentBuffer.CurrentOffset; if (left < packetDescription.DataByteSize) { EnqueueBuffer(); WaitForBuffer(); } AudioQueue.FillAudioData(_currentBuffer.Buffer, _currentBuffer.CurrentOffset, args.InputData, (int)packetDescription.StartOffset, packetDescription.DataByteSize); // Set new offset for this packet packetDescription.StartOffset = _currentBuffer.CurrentOffset; // Add the packet to our Buffer _currentBuffer.PacketDescriptions.Add(packetDescription); // Add the Size so that we know how much is in the buffer _currentBuffer.CurrentOffset += packetDescription.DataByteSize; } if ((_audioFileStream != null && _currentByteCount == _audioFileStream.DataByteCount) || _lastPacket) { _lastPacket = false; Console.WriteLine($"{nameof(AudioPacketDecoded)} This is the lastpacket"); EnqueueBuffer(); } }
private void ObjectUpdateHandler(object sender, PacketReceivedEventArgs e) { //ObjectUpdatePacket update = (ObjectUpdatePacket)packet; DetectedObject = true; //CurrentRegionHandle = update.RegionData.RegionHandle; }
private void Handle_ReqTarget(PacketReceivedEventArgs args) { var targetUniqueID = args.Message.ReadString(); // Make sure we don't target ourselves if (targetUniqueID == _player.UniqueID) { return; } var target = _player.Map.GetActor(targetUniqueID); if (target != null) { _player.Target = target; var packet = new Packet(PacketType.TARGET_ACQ, ChannelType.UNASSIGNED); packet.Message.Write(target.UniqueID); _player.NetworkComponent.SendPacket(packet, NetDeliveryMethod.ReliableOrdered); } else { _player.NetworkComponent.SendChatMessage("Invalid target!", ChatMessageType.Alert); } }
private void Handle_MapData(PacketReceivedEventArgs args) { _mapLoaded = false; this.EventOccured?.Invoke(this, new SubjectEventArgs("loadingMap", new object[] { _map })); // Make sure the player is no longer moving if (_player != null) { _player.State = ActorStates.Idle; } var name = args.Message.ReadString(); var dimensions = args.Message.ReadVector2(); _map?.Unload(); // unload the previous map if it existed. _map = new Map(dimensions, name); _map.Unpack(args.Message); _mapLoaded = true; _camera.Bounds = new Rectangle(_map.Bounds.X * Constants.TILE_WIDTH, _map.Bounds.Y * Constants.TILE_HEIGHT, _map.Bounds.Width * Constants.TILE_WIDTH, _map.Bounds.Height * Constants.TILE_HEIGHT); this.EventOccured?.Invoke(this, new SubjectEventArgs("finishedLoadingMap", new object[] { _map })); }
public void Packet_MapBlockReply(object sender, PacketReceivedEventArgs e) { MapBlockReplyPacket reply = (MapBlockReplyPacket)e.Packet; Hashtable hash = new Hashtable(); hash.Add("MessageType", "MapBlocks"); Hashtable[] blocks = new Hashtable[reply.Data.Length]; float temp1, temp2; // Neither of these do anything, really. Just to make Helpers.GlobalPosToRegionHandle happy. int i = 0; foreach (MapBlockReplyPacket.DataBlock data in reply.Data) { string name = Utils.BytesToString(data.Name); Hashtable simhash = new Hashtable(); simhash.Add("Name", name); simhash.Add("Access", data.Access); simhash.Add("X", data.X); simhash.Add("Y", data.Y); simhash.Add("Flags", data.RegionFlags); // Convert the regionhandle to a string - JavaScript is likely to get upset over long integers. simhash.Add("RegionHandle", Helpers.GlobalPosToRegionHandle(data.X * 256, data.Y * 256, out temp1, out temp2).ToString()); blocks[i++] = simhash; } hash.Add("Blocks", blocks); enqueue(hash); }
protected void BalanceHandler(object sender, PacketReceivedEventArgs e) { Packet packet = e.Packet; string value = ((MoneyBalanceReplyPacket)packet).MoneyData.MoneyBalance.ToString(); this.BeginInvoke(new StringParamInvoker(UpdateBalance), new object[] { value }); }
private void Handle_PlayerMoving(PacketReceivedEventArgs args) { if (!_player.MapLoaded) { return; } _player.Direction = (Direction)args.Message.ReadByte(); var wantsToMove = args.Message.ReadBoolean(); if (wantsToMove) { _player.State = ActorStates.Moving; // Can the player actually move based on the minimum update time from the tick rate if (_player.CanMove(_player.Direction, _player.Descriptor.Speed * (1000f / Settings.TickRate))) { _player.NetworkComponent.SendMovementPacket(); } else { _player.State = ActorStates.Idle; _player.NetworkComponent.SendMovementPacket(); } } else // The player wishes to cease moving. { _player.State = ActorStates.Idle; _player.NetworkComponent.SendMovementPacket(); } }
private async void PacketReceivedEventHandler(object sender, PacketReceivedEventArgs e) { if (!Message.IsMessageContentType(e.Packet.ContentType)) { await ErrorAsync("Packet content is not a message!").ConfigureAwait(false); return; } // TODO: exceptions here? Logger.Debug("Attempting to parse a message..."); Message message = await Message.DeSerializeAsync(e.Packet.ContentType, e.Packet.Encoding, e.Packet.Content, 0, e.Packet.ContentLength, MessageFactory).ConfigureAwait(false); if (null == message) { await ErrorAsync("Failed to parse a message!").ConfigureAwait(false); return; } Logger.Debug($"{message.Type} message parsed!"); MessageReceivedEvent?.Invoke(this, new MessageReceivedEventArgs { Message = message } ); }
/// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> private void ChangeUserRightsHandler(object sender, PacketReceivedEventArgs e) { Packet packet = e.Packet; if (packet.Type == PacketType.ChangeUserRights) { FriendInfo friend; ChangeUserRightsPacket rights = (ChangeUserRightsPacket)packet; foreach (ChangeUserRightsPacket.RightsBlock block in rights.Rights) { FriendRights newRights = (FriendRights)block.RelatedRights; if (FriendList.TryGetValue(block.AgentRelated, out friend)) { friend.TheirFriendRights = newRights; if (m_FriendRights != null) { OnFriendRights(new FriendInfoEventArgs(friend)); } } else if (block.AgentRelated == Client.Self.AgentID) { if (FriendList.TryGetValue(rights.AgentData.AgentID, out friend)) { friend.MyFriendRights = newRights; if (m_FriendRights != null) { OnFriendRights(new FriendInfoEventArgs(friend)); } } } } } }
/// <summary>Process an incoming packet and raise the appropriate events</summary> /// <param name="sender">The sender</param> /// <param name="e">The EventArgs object containing the packet data</param> protected void OfflineNotificationHandler(object sender, PacketReceivedEventArgs e) { Packet packet = e.Packet; if (packet.Type == PacketType.OfflineNotification) { OfflineNotificationPacket notification = (OfflineNotificationPacket)packet; foreach (OfflineNotificationPacket.AgentBlockBlock block in notification.AgentBlock) { FriendInfo friend = new FriendInfo(block.AgentID, FriendRights.CanSeeOnline, FriendRights.CanSeeOnline); lock (FriendList.Dictionary) { if (!FriendList.Dictionary.ContainsKey(block.AgentID)) { FriendList.Dictionary[block.AgentID] = friend; } friend = FriendList.Dictionary[block.AgentID]; } friend.IsOnline = false; if (m_FriendOffline != null) { OnFriendOffline(new FriendInfoEventArgs(friend)); } } } }
void StreamPacketsProc(object sender, PacketReceivedEventArgs args) { //Debug.WriteLine ("{0} packets", args.PacketDescriptions.Length); unsafe { AudioQueueBuffer *buffer; if (audioQueue.AllocateBuffer(args.Bytes, out buffer) != AudioQueueStatus.Ok) { throw new ApplicationException(); } buffer->AudioDataByteSize = (uint)args.Bytes; buffer->CopyToAudioData(args.InputData, args.Bytes); if (audioQueue.EnqueueBuffer(buffer, args.PacketDescriptions) != AudioQueueStatus.Ok) { throw new ApplicationException(); } } totalPacketsReceived += args.PacketDescriptions.Length; if (!audioQueue.IsRunning && totalPacketsReceived > 100) { var res = audioQueue.Start(); if (res != AudioQueueStatus.Ok) { throw new ApplicationException(res.ToString()); } } }
/// <summary> /// Saving the decoded Packets to our active Buffer, if the Buffer is full queue it into the OutputQueue /// and wait until another buffer gets freed up /// </summary> private void AudioPacketDecoded(object sender, PacketReceivedEventArgs args) { foreach (var p in args.PacketDescriptions) { currentByteCount += p.DataByteSize; AudioStreamPacketDescription pd = p; int left = bufferSize - currentBuffer.CurrentOffset; if (left < pd.DataByteSize) { EnqueueBuffer(); WaitForBuffer(); } AudioQueue.FillAudioData(currentBuffer.Buffer, currentBuffer.CurrentOffset, args.InputData, (int)pd.StartOffset, pd.DataByteSize); // Set new offset for this packet pd.StartOffset = currentBuffer.CurrentOffset; // Add the packet to our Buffer currentBuffer.PacketDescriptions.Add(pd); // Add the Size so that we know how much is in the buffer currentBuffer.CurrentOffset += pd.DataByteSize; } if ((fileStream != null && currentByteCount == fileStream.DataByteCount) || lastPacket) { EnqueueBuffer(); } }
private void Handle_ClientCommand(PacketReceivedEventArgs args) { string command = args.Message.ReadString(); int cArgsLength = args.Message.ReadInt32(); string[] cArgs = new string[cArgsLength]; for (int i = 0; i < cArgsLength; i++) { cArgs[i] = args.Message.ReadString(); } if (_scriptedCommandHandlers.ContainsKey(command)) { // Get the player var player = Engine.Services.Get <PlayerManager>().GetPlayer(args.Connection.UniqueIdentifier.ToString()); _scriptedCommandHandlers[command].ForEach(a => { try { a(new CommandArgs(this, player, cArgs)); } catch (Exception ex) { Engine.Services.Get <ScriptManager>().HandleException(ex); } } ); } }
void OnPacketDecoded(object sender, PacketReceivedEventArgs e) { IntPtr outBuffer; outputQueue.AllocateBuffer (e.Bytes, out outBuffer); AudioQueue.FillAudioData (outBuffer, 0, e.InputData, 0, e.Bytes); outputQueue.EnqueueBuffer (outBuffer, e.Bytes, e.PacketDescriptions); if (!outputQueueStarted) { var status = outputQueue.Start (); if (status != AudioQueueStatus.Ok) { Console.WriteLine ("could not start audio queue"); } outputQueueStarted = true; } }
void StreamPacketsProc(object sender, PacketReceivedEventArgs args) { //Debug.WriteLine ("{0} packets", args.PacketDescriptions.Length); unsafe { AudioQueueBuffer* buffer; if (audioQueue.AllocateBuffer (args.Bytes, out buffer) != AudioQueueStatus.Ok) throw new ApplicationException (); buffer->AudioDataByteSize = (uint)args.Bytes; buffer->CopyToAudioData (args.InputData, args.Bytes); if (audioQueue.EnqueueBuffer (buffer, args.PacketDescriptions) != AudioQueueStatus.Ok) throw new ApplicationException (); } totalPacketsReceived += args.PacketDescriptions.Length; if (!audioQueue.IsRunning && totalPacketsReceived > 25) { var res = audioQueue.Start (); if (res != AudioQueueStatus.Ok) throw new ApplicationException (res.ToString ()); } }
/// <summary> /// Saving the decoded Packets to our active Buffer, if the Buffer is full queue it into the OutputQueue /// and wait until another buffer gets freed up /// </summary> void AudioPacketDecoded (object sender, PacketReceivedEventArgs args) { lock (locker) { foreach (var p in args.PacketDescriptions) { AudioStreamPacketDescription pd = p; var currentBuffer = GetOrCreateAudioBuffer (); int left = BufferSize - currentBuffer.CurrentOffset; if (left < pd.DataByteSize) { EnqueueBuffer (); currentBuffer = GetOrCreateAudioBuffer (); } AudioQueue.FillAudioData (currentBuffer.Buffer, currentBuffer.CurrentOffset, args.InputData, (int)pd.StartOffset, pd.DataByteSize); // Set new offset for this packet pd.StartOffset = currentBuffer.CurrentOffset; // Add the packet to our Buffer currentBuffer.PacketDescriptions.Add (pd); // Add the Size so that we know how much is in the buffer currentBuffer.CurrentOffset += pd.DataByteSize; } } }
unsafe void AudioPacketDecoded(object sender, PacketReceivedEventArgs args) { Console.Write ('.'); foreach (var pd in args.PacketDescriptions){ var packetSize = pd.DataByteSize; int left = bufferSize - bytesFilled; if (left < packetSize){ EnqueueBuffer (); WaitForBuffer (); } // Fill the buffer var buf = outputBuffers [fillBufferIndex]; AudioQueue.FillAudioData (buf, bytesFilled, args.InputData, (int) pd.StartOffset, packetSize); // Fill out the packet description pdesc [packetsFilled] = pd; pdesc [packetsFilled].StartOffset = bytesFilled; bytesFilled += packetSize; packetsFilled++; // If we filled out all of our packet descriptions, enqueue the buffer if (pdesc.Length == packetsFilled){ EnqueueBuffer (); WaitForBuffer (); } } }
/////////////////////////////////////////////////////////////////////////////// // Eventhandler // /////////////////////////////////////////////////////////////////////////////// #region EVENTS /// <summary> /// Packet received handler to check for good tracking count. /// </summary> /// <param name="sender">The sender.</param> /// <param name="packetReceivedEventArgs">The event arguments.</param> private void BaseClientOnPacketReceived(object sender, PacketReceivedEventArgs packetReceivedEventArgs) { var packet = packetReceivedEventArgs.Packet; NetworkData data; if (!packet.TryGetValue(TrackerDataId.GazeDirectionQ, out data)) { return; } var q = data.GetValue<double>(); if (q > 0.2) { this.goodTrackingCount++; } else if (this.goodTrackingCount > 0) { this.goodTrackingCount--; } }
/// <summary> /// Raised when new gaze data packet is received /// </summary> /// <param name="sender"><see cref="object"/> The sender</param>. /// <param name="e"><see cref="PacketReceivedEventArgs"/> event arguments</param>. private void OnGazePacketReceived(object sender, PacketReceivedEventArgs e) { this.UdpIsConnected = true; if (this.GazeDataAvailable != null) { SmartEyeGazeData gazeData; if (this.ParseGazeData(e.Packet, out gazeData)) { this.GazeDataAvailable(this, new GazeDataReceivedEventArgs(gazeData)); } } }
/// <summary> /// Saving the decoded Packets to our active Buffer, if the Buffer is full queue it into the OutputQueue /// and wait until another buffer gets freed up /// </summary> void AudioPacketDecoded (object sender, PacketReceivedEventArgs args) { foreach (var p in args.PacketDescriptions) { currentByteCount += p.DataByteSize; AudioStreamPacketDescription pd = p; int left = bufferSize - currentBuffer.CurrentOffset; if (left < pd.DataByteSize) { EnqueueBuffer (); WaitForBuffer (); } AudioQueue.FillAudioData (currentBuffer.Buffer, currentBuffer.CurrentOffset, args.InputData, (int)pd.StartOffset, pd.DataByteSize); #if true // Set new offset for this packet pd.StartOffset = currentBuffer.CurrentOffset; // Add the packet to our Buffer currentBuffer.PacketDescriptions.Add (pd); // Add the Size so that we know how much is in the buffer currentBuffer.CurrentOffset += pd.DataByteSize; #else // Fill out the packet description pdesc [packetsFilled] = pd; pdesc [packetsFilled].StartOffset = bytesFilled; bytesFilled += packetSize; packetsFilled++; var t = OutputQueue.CurrentTime; Console.WriteLine ("Time: {0}", t); // If we filled out all of our packet descriptions, enqueue the buffer if (pdesc.Length == packetsFilled){ EnqueueBuffer (); WaitForBuffer (); } #endif } if ((fileStream != null && currentByteCount == fileStream.DataByteCount) || lastPacket) EnqueueBuffer (); }
void HandlePacketDecoded (object sender, PacketReceivedEventArgs e) { AudioFileStream afs = (AudioFileStream)sender; byte[] audioData = new byte[e.Bytes]; Marshal.Copy (e.InputData, audioData, 0, e.Bytes); //Console.WriteLine ("Packet decoded "); AudioStreamBasicDescription asbd = afs.StreamBasicDescription; Rate = (float)asbd.SampleRate; Size = e.Bytes; if (asbd.ChannelsPerFrame == 1) { if (asbd.BitsPerChannel == 8) { Format = ALFormat.Mono8; } else { Format = ALFormat.Mono16; } } else { if (asbd.BitsPerChannel == 8) { Format = ALFormat.Stereo8; } else { Format = ALFormat.Stereo16; } } _data = audioData; var _dblDuration = (e.Bytes / ((asbd.BitsPerChannel / 8) * asbd.ChannelsPerFrame)) / asbd.SampleRate; _duration = TimeSpan.FromSeconds (_dblDuration); // Console.WriteLine ("From Data: " + _name + " - " + Format + " = " + Rate + " / " + Size + " -- " + Duration); // Console.WriteLine("Duration: " + _dblDuration // + " / size: " + e.Bytes // + " bits: " + asbd.BitsPerChannel // + " channels: " + asbd.ChannelsPerFrame // + " rate: " + asbd.SampleRate); }
/// <summary> /// Saving the decoded Packets to our active Buffer, if the Buffer is full queue it into the OutputQueue /// and wait until another buffer gets freed up /// </summary> private void AudioPacketDecoded(object sender, PacketReceivedEventArgs args) { foreach (var p in args.PacketDescriptions) { currentByteCount += p.DataByteSize; AudioStreamPacketDescription pd = p; int left = bufferSize - currentBuffer.CurrentOffset; if (left < pd.DataByteSize) { EnqueueBuffer (); WaitForBuffer (); } AudioQueue.FillAudioData (currentBuffer.Buffer, currentBuffer.CurrentOffset, args.InputData, (int)pd.StartOffset, pd.DataByteSize); // Set new offset for this packet pd.StartOffset = currentBuffer.CurrentOffset; // Add the packet to our Buffer currentBuffer.PacketDescriptions.Add (pd); // Add the Size so that we know how much is in the buffer currentBuffer.CurrentOffset += pd.DataByteSize; } if ((fileStream != null && currentByteCount == fileStream.DataByteCount) || lastPacket) EnqueueBuffer (); }
void HandlePacketDecoded (object sender, PacketReceivedEventArgs e) { AudioFileStream afs = (AudioFileStream)sender; byte[] audioData = new byte[e.Bytes]; Marshal.Copy (e.InputData, audioData, 0, e.Bytes); //Console.WriteLine ("Packet decoded "); AudioStreamBasicDescription asbd = afs.StreamBasicDescription; Rate = (float)asbd.SampleRate; Size = e.Bytes; if (asbd.ChannelsPerFrame == 1) { if (asbd.BitsPerChannel == 8) { Format = ALFormat.Mono8; } else if (asbd.BitsPerChannel == 0) // This shouldn't happen. hackking around bad data for now. { //TODO: Remove this when sound's been fixed on iOS and other devices. Format = ALFormat.Mono16; Debug.WriteLine("Warning, bad decoded audio packet in SoundEffect.HandlePacketDecoded. Squelching sound."); _duration = TimeSpan.Zero; _data = audioData; return; } else { Format = ALFormat.Mono16; } } else { if (asbd.BitsPerChannel == 8) { Format = ALFormat.Stereo8; } else { Format = ALFormat.Stereo16; } } _data = audioData; var _dblDuration = (e.Bytes / ((asbd.BitsPerChannel / 8) * asbd.ChannelsPerFrame)) / asbd.SampleRate; _duration = TimeSpan.FromSeconds (_dblDuration); // Console.WriteLine ("From Data: " + _name + " - " + Format + " = " + Rate + " / " + Size + " -- " + Duration); // Console.WriteLine("Duration: " + _dblDuration // + " / size: " + e.Bytes // + " bits: " + asbd.BitsPerChannel // + " channels: " + asbd.ChannelsPerFrame // + " rate: " + asbd.SampleRate); }
void HandlePacket(object sender, PacketReceivedEventArgs e) { if (e.Packet is SetSymbols) { SetSymbols setSymbols = (SetSymbols)e.Packet; SymbolLookup.SymbolsPath = setSymbols.SymbolsPath; } else if (e.Packet is SetArchitecture) { SetArchitecture setArchitecture = (SetArchitecture)e.Packet; Transport.TargetSystemInfo.Architecture = setArchitecture.Architecture; Transport.TargetSystemInfo.Endianness = setArchitecture.Endianness; } else { History.Add(e.Packet, e.TimeStamp); } }