use alloc::collections::{BTreeMap, VecDeque};
use alloc::vec::Vec;
use core::time::Duration;
use avb_mrp::msrp;
use avb_net::MacAddress;
use crate::acmp::{AcmpFlags, AcmpMessageType, AcmpStatus, Acmpdu};
use crate::adp::{AdpMessageType, Adpdu, ControllerCapabilities, EntityCapabilities};
use crate::aecp::{
AaMode, AaStatus, AaTlv, AddressAccessPdu, AecpHeader, AecpMessageType, AemCommandType, AemPdu,
AemStatus, VendorUniquePdu,
};
use crate::aem::{
self, Addressing, AsPath, AudioMap, AudioMapping, AudioMappings, AvbInfo, Counters,
DynamicQuery, MappingChange, MaxTransitTime, ReadDescriptorResponse, SetClockSource, SetName,
SetSamplingRate, SetStreamFormat, StreamInfo, StreamInfoFlags,
};
use crate::cache::{CachedModel, ModelKey};
use crate::descriptor::{
AudioUnitDescriptor, ConfigurationDescriptor, DescriptorType, EntityDescriptor,
LocaleDescriptor, MemoryObjectDescriptor, MemoryObjectType, SamplingRate, StreamPortDescriptor,
};
use crate::error::{DecodeError, EncodeError};
use crate::id::{EntityId, EntityModelId};
use crate::lite::{self, CvuMessage, LiteCommandType, LiteMessage, LiteStatus};
use crate::model::{Binding, EntityModel, EnumerationFailure, EnumerationState, TxState, Wireless};
use crate::mvu::{self, MediaClockReference, MilanInfo, MvuCommandType, MvuMessage};
use crate::pdu::{self, Pdu};
use crate::stream_format::StreamFormat;
use crate::time::Instant;
use crate::wireless::{self, WirelessCommandType, WirelessMessage, WirelessStatus};
pub const COMMAND_TIMEOUT: Duration = Duration::from_millis(250);
const CVU_LIFETIME: Duration = Duration::from_secs(30);
const MAX_DESCRIPTORS: usize = 4096;
const READ_TYPES: [DescriptorType; 11] = [
DescriptorType::AUDIO_UNIT,
DescriptorType::STREAM_INPUT,
DescriptorType::STREAM_OUTPUT,
DescriptorType::JACK_INPUT,
DescriptorType::JACK_OUTPUT,
DescriptorType::AVB_INTERFACE,
DescriptorType::CLOCK_SOURCE,
DescriptorType::MEMORY_OBJECT,
DescriptorType::LOCALE,
DescriptorType::CONTROL,
DescriptorType::CLOCK_DOMAIN,
];
const STATIC_TYPES: [DescriptorType; 5] = [
DescriptorType::STRINGS,
DescriptorType::LOCALE,
DescriptorType::AUDIO_MAP,
DescriptorType::STREAM_PORT_INPUT,
DescriptorType::STREAM_PORT_OUTPUT,
];
const OWN_TYPES: [DescriptorType; 4] = [
DescriptorType::ENTITY,
DescriptorType::CONFIGURATION,
DescriptorType::AVB_INTERFACE,
DescriptorType::CLOCK_SOURCE,
];
const WIRELESS_MISSES: u8 = 3;
const MAX_DYNAMIC_QUERIES: usize = 16;
const MAX_LOGO: u64 = 1 << 20;
const MEMORY_SEGMENT: u64 = (AddressAccessPdu::MAX_TLVS_LEN - AaTlv::HEADER_LEN) as u64;
const MAX_MAP_PARTS: u16 = 256;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Config {
pub entity_id: EntityId,
pub enumerate: bool,
pub register_unsolicited: bool,
pub network_info: bool,
pub read_mappings: bool,
pub media_clock_info: bool,
pub read_counters: bool,
pub read_transit_times: bool,
pub read_configurations: bool,
pub read_talker_state: bool,
pub lite_status: bool,
pub lite_poll: Duration,
pub wireless_status: bool,
pub wireless_poll: Duration,
pub read_logos: bool,
pub own_mac: Option<MacAddress>,
pub advertise: Option<Advertise>,
pub first_sequence_id: u16,
pub random_seed: u64,
}
impl Config {
pub fn new(entity_id: EntityId) -> Self {
Self {
entity_id,
enumerate: true,
register_unsolicited: true,
network_info: true,
read_mappings: true,
media_clock_info: true,
read_counters: true,
read_transit_times: true,
read_configurations: true,
read_talker_state: true,
lite_status: true,
lite_poll: Duration::from_secs(5),
wireless_status: true,
wireless_poll: Duration::from_secs(5),
read_logos: true,
own_mac: None,
advertise: None,
first_sequence_id: 0,
random_seed: entity_id.0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Advertise {
pub entity_model_id: EntityModelId,
pub valid_time: u8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiscoveredEntity {
pub adp: Adpdu,
pub mac: MacAddress,
pub first_seen: Instant,
pub last_seen: Instant,
pub expires: Instant,
}
impl DiscoveredEntity {
pub fn entity_id(&self) -> EntityId {
self.adp.entity_id
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OfflineReason {
Departed,
TimedOut,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Event {
EntityOnline(EntityId),
EntityChanged(EntityId),
EntityRestarted(EntityId),
EntityOffline(EntityId, OfflineReason),
EnumerationStarted(EntityId),
EntityEnumerated(EntityId),
EnumerationFailed(EntityId, EnumerationFailure),
EntityModelChanged(EntityId),
CommandFinished(CommandId, Outcome),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct CommandId(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Outcome {
Done,
Refused(Refusal),
NoResponse,
NotPossible,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Refusal {
Acmp(AcmpStatus),
Aem(AemStatus),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Transmit {
pub destination: MacAddress,
pub length: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Request {
ReadDescriptor {
descriptor_type: DescriptorType,
index: u16,
refresh: bool,
},
GetMilanInfo,
GetMediaClockReference {
domain: u16,
},
RegisterUnsolicited,
GetRxState {
input: u16,
},
GetStreamInfo {
descriptor_type: DescriptorType,
index: u16,
},
GetAvbInfo {
index: u16,
},
GetAsPath {
index: u16,
},
GetCounters {
descriptor_type: DescriptorType,
index: u16,
},
Bind {
talker: EntityId,
talker_unique_id: u16,
input: u16,
class_b: bool,
command: CommandId,
},
Unbind {
talker: EntityId,
talker_unique_id: u16,
input: u16,
command: CommandId,
},
Identify {
control: u16,
on: bool,
command: Option<CommandId>,
},
SetName {
set: SetName,
command: CommandId,
},
SetStreamFormat {
set: SetStreamFormat,
command: CommandId,
},
Streaming {
descriptor_type: DescriptorType,
index: u16,
start: bool,
command: CommandId,
},
SetSamplingRate {
set: SetSamplingRate,
command: CommandId,
},
SetClockSource {
set: SetClockSource,
command: CommandId,
},
SetConfiguration {
configuration: u16,
command: CommandId,
},
ReadOther {
configuration: u16,
descriptor_type: DescriptorType,
index: u16,
},
GetAudioMap {
descriptor_type: DescriptorType,
index: u16,
map_index: u16,
},
ChangeMappings {
change: MappingChange,
descriptor_type: DescriptorType,
index: u16,
command: CommandId,
},
SetControl {
index: u16,
command: CommandId,
},
GetTxState {
output: u16,
command: Option<CommandId>,
},
GetTxConnection {
output: u16,
index: u16,
command: Option<CommandId>,
},
DisconnectTx {
output: u16,
listener: EntityId,
listener_unique_id: u16,
command: CommandId,
},
GetMaxTransitTime {
output: u16,
command: Option<CommandId>,
},
SetMaxTransitTime {
set: MaxTransitTime,
command: CommandId,
},
GetLiteStatus {
interface: u16,
},
SetLiteConfig {
interface: u16,
flags: u8,
command: CommandId,
},
GetWirelessStatus {
interface: u16,
},
SetWirelessConfig {
interface: u16,
flags: u8,
command: CommandId,
},
ReadForCaller {
descriptor_type: DescriptorType,
index: u16,
command: CommandId,
},
GetDynamicInfo {
queries: [DynamicQuery; MAX_DYNAMIC_QUERIES],
count: u8,
},
ReadMemory {
index: u16,
offset: u32,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Channel {
Aem,
Mvu,
Acmp,
AddressAccess,
}
impl Request {
fn channel(self) -> Channel {
match self {
Request::GetMilanInfo
| Request::GetMediaClockReference { .. }
| Request::GetLiteStatus { .. }
| Request::SetLiteConfig { .. }
| Request::GetWirelessStatus { .. }
| Request::SetWirelessConfig { .. } => Channel::Mvu,
Request::GetRxState { .. }
| Request::Bind { .. }
| Request::Unbind { .. }
| Request::GetTxState { .. }
| Request::GetTxConnection { .. }
| Request::DisconnectTx { .. } => Channel::Acmp,
Request::ReadMemory { .. } => Channel::AddressAccess,
_ => Channel::Aem,
}
}
fn acmp_message(self) -> Option<AcmpMessageType> {
match self {
Request::GetRxState { .. } => Some(AcmpMessageType::GET_RX_STATE_COMMAND),
Request::Bind { .. } => Some(AcmpMessageType::CONNECT_RX_COMMAND),
Request::GetTxState { .. } => Some(AcmpMessageType::GET_TX_STATE_COMMAND),
Request::GetTxConnection { .. } => Some(AcmpMessageType::GET_TX_CONNECTION_COMMAND),
Request::DisconnectTx { .. } => Some(AcmpMessageType::DISCONNECT_TX_COMMAND),
Request::Unbind { .. } => Some(AcmpMessageType::DISCONNECT_RX_COMMAND),
_ => None,
}
}
fn command(self) -> Option<CommandId> {
match self {
Request::Bind { command, .. }
| Request::Unbind { command, .. }
| Request::SetName { command, .. }
| Request::SetStreamFormat { command, .. }
| Request::Streaming { command, .. }
| Request::SetSamplingRate { command, .. }
| Request::SetClockSource { command, .. }
| Request::SetConfiguration { command, .. }
| Request::SetControl { command, .. }
| Request::DisconnectTx { command, .. }
| Request::SetMaxTransitTime { command, .. }
| Request::ReadForCaller { command, .. }
| Request::SetLiteConfig { command, .. }
| Request::SetWirelessConfig { command, .. }
| Request::ChangeMappings { command, .. } => Some(command),
Request::Identify { command, .. }
| Request::GetTxState { command, .. }
| Request::GetTxConnection { command, .. }
| Request::GetMaxTransitTime { command, .. } => command,
_ => None,
}
}
}
#[derive(Debug, Clone, Copy)]
struct Inflight {
entity_id: EntityId,
request: Request,
deadline: Instant,
retried: bool,
}
#[derive(Debug, Default)]
struct Session {
queue: VecDeque<Request>,
inflight: Option<(Channel, u16)>,
requested: usize,
}
#[derive(Debug, Clone, Copy)]
struct Random(u64);
impl Random {
fn new(seed: u64) -> Self {
Self(seed | 1)
}
fn up_to(&mut self, limit: Duration) -> Duration {
self.0 ^= self.0 << 13;
self.0 ^= self.0 >> 7;
self.0 ^= self.0 << 17;
let millis = limit.as_millis() as u64;
Duration::from_millis(if millis == 0 {
0
} else {
self.0 % (millis + 1)
})
}
}
#[derive(Debug)]
struct Advertiser {
config: Advertise,
available_index: u32,
next: Option<Instant>,
started: bool,
}
impl Advertiser {
fn valid(&self) -> Duration {
Duration::from_secs(2 * u64::from(self.config.valid_time.clamp(1, 31)))
}
fn delay_limit(&self) -> Duration {
(self.valid() / 5).min(Duration::from_secs(1))
}
}
pub struct Controller {
config: Config,
entities: BTreeMap<EntityId, DiscoveredEntity>,
models: BTreeMap<EntityId, EntityModel>,
sessions: BTreeMap<EntityId, Session>,
inflight: BTreeMap<(Channel, u16), Inflight>,
next_aem_sequence: u16,
next_mvu_sequence: u16,
next_acmp_sequence: u16,
next_address_access_sequence: u16,
next_command: u32,
identify_off: BTreeMap<EntityId, (Instant, u16)>,
next_lite_poll: Option<Instant>,
next_wireless_poll: Option<Instant>,
cache: BTreeMap<ModelKey, CachedModel>,
mapping_changes: BTreeMap<CommandId, Vec<AudioMapping>>,
control_values: BTreeMap<CommandId, Vec<u8>>,
memory_reads: BTreeMap<(EntityId, u16), Vec<u8>>,
advertiser: Option<Advertiser>,
random: Random,
outgoing: VecDeque<(MacAddress, Vec<u8>)>,
events: VecDeque<Event>,
malformed: u64,
}
impl Controller {
pub fn new(config: Config) -> Self {
Self {
config,
entities: BTreeMap::new(),
models: BTreeMap::new(),
sessions: BTreeMap::new(),
inflight: BTreeMap::new(),
next_aem_sequence: config.first_sequence_id,
next_mvu_sequence: config.first_sequence_id,
next_acmp_sequence: config.first_sequence_id,
next_address_access_sequence: config.first_sequence_id,
next_command: 0,
identify_off: BTreeMap::new(),
next_lite_poll: None,
next_wireless_poll: None,
cache: BTreeMap::new(),
mapping_changes: BTreeMap::new(),
control_values: BTreeMap::new(),
memory_reads: BTreeMap::new(),
advertiser: config.advertise.map(|advertise| Advertiser {
config: advertise,
available_index: 0,
next: None,
started: false,
}),
random: Random::new(config.random_seed),
outgoing: VecDeque::new(),
events: VecDeque::new(),
malformed: 0,
}
}
pub fn entity_id(&self) -> EntityId {
self.config.entity_id
}
pub fn discover(&mut self, entity: Option<EntityId>) {
let adpdu = Adpdu::discover(entity.unwrap_or_default());
self.queue_adp(&adpdu);
}
pub fn enumerate(&mut self, now: Instant, entity_id: EntityId) {
if self.entities.contains_key(&entity_id) {
self.start_enumeration(now, entity_id);
}
}
pub fn depart(&mut self) {
let Some(advertiser) = &mut self.advertiser else {
return;
};
advertiser.next = None;
advertiser.available_index = 0;
let adpdu = self.own_adpdu(AdpMessageType::ENTITY_DEPARTING, 0);
self.queue_adp(&adpdu);
}
pub fn handle_frame(
&mut self,
now: Instant,
source: MacAddress,
bytes: &[u8],
) -> Result<(), DecodeError> {
self.start_advertising(now);
let result = match pdu::decode(bytes) {
Ok(Pdu::Adp(adpdu)) => {
self.handle_adpdu(now, source, &adpdu);
Ok(())
}
Ok(Pdu::Aem(aem)) => {
self.handle_aem(now, source, &aem);
Ok(())
}
Ok(Pdu::Acmp(acmpdu)) => {
self.handle_acmp(&acmpdu);
Ok(())
}
Ok(Pdu::VendorUnique(vendor_unique)) => {
self.handle_vendor_unique(now, &vendor_unique);
Ok(())
}
Ok(Pdu::Aecp(header, _))
if header.message_type == AecpMessageType::ADDRESS_ACCESS_RESPONSE =>
{
if let Ok(response) = AddressAccessPdu::decode(bytes) {
self.handle_address_access(&response);
}
Ok(())
}
Ok(_) => Ok(()),
Err(error) => {
self.malformed += 1;
Err(error)
}
};
self.pump(now);
result
}
pub fn handle_adpdu(&mut self, now: Instant, source: MacAddress, adpdu: &Adpdu) {
let entity_id = adpdu.entity_id;
if entity_id == self.config.entity_id {
return;
}
match adpdu.message_type {
AdpMessageType::ENTITY_AVAILABLE if entity_id.is_valid() => {
self.entity_available(now, source, adpdu);
}
AdpMessageType::ENTITY_DEPARTING => {
let known = self.entities.remove(&entity_id).is_some();
if known {
self.forget(entity_id);
self.events
.push_back(Event::EntityOffline(entity_id, OfflineReason::Departed));
}
}
AdpMessageType::ENTITY_DISCOVER => {
let asked = !entity_id.is_valid() || entity_id == self.config.entity_id;
if let Some(advertiser) = self.advertiser.as_mut().filter(|_| asked) {
let soon = now + self.random.up_to(advertiser.delay_limit());
advertiser.next = Some(advertiser.next.map_or(soon, |next| next.min(soon)));
}
}
_ => {}
}
}
fn entity_available(&mut self, now: Instant, source: MacAddress, adpdu: &Adpdu) {
let entity_id = adpdu.entity_id;
let expires = now + Duration::from_secs(2 * u64::from(adpdu.valid_time.max(1)));
let Some(known) = self.entities.get_mut(&entity_id) else {
self.entities.insert(
entity_id,
DiscoveredEntity {
adp: *adpdu,
mac: source,
first_seen: now,
last_seen: now,
expires,
},
);
self.events.push_back(Event::EntityOnline(entity_id));
if self.wants_model(adpdu) {
self.start_enumeration(now, entity_id);
}
return;
};
let restarted = adpdu.available_index < known.adp.available_index;
let changed = !same_advertisement(&known.adp, adpdu) || known.mac != source;
let moved = adpdu.gptp_grandmaster_id != known.adp.gptp_grandmaster_id
|| adpdu.gptp_domain_number != known.adp.gptp_domain_number;
let reconfigured = adpdu.current_configuration_index
!= known.adp.current_configuration_index
&& adpdu
.entity_capabilities
.contains(EntityCapabilities::AEM_CONFIGURATION_INDEX_VALID);
let remodeled = adpdu.entity_model_id != known.adp.entity_model_id;
known.adp = *adpdu;
known.mac = source;
known.last_seen = now;
known.expires = expires;
if restarted {
self.events.push_back(Event::EntityRestarted(entity_id));
}
if changed {
self.events.push_back(Event::EntityChanged(entity_id));
}
if (restarted || reconfigured || remodeled) && self.wants_model(adpdu) {
self.start_enumeration(now, entity_id);
} else if moved {
self.read_network_info(now, entity_id);
}
}
fn read_network_info(&mut self, now: Instant, entity_id: EntityId) {
if !self.config.network_info {
return;
}
let Some(model) = self.models.get(&entity_id) else {
return;
};
let interfaces: Vec<u16> = model
.descriptors(DescriptorType::AVB_INTERFACE)
.map(|(index, _)| index)
.collect();
for index in interfaces {
self.queue_query(entity_id, Request::GetAvbInfo { index });
self.queue_query(entity_id, Request::GetAsPath { index });
}
self.pump(now);
}
fn wants_model(&self, adpdu: &Adpdu) -> bool {
self.config.enumerate
&& adpdu
.entity_capabilities
.contains(EntityCapabilities::AEM_SUPPORTED)
}
fn forget(&mut self, entity_id: EntityId) {
self.models.remove(&entity_id);
self.identify_off.remove(&entity_id);
self.memory_reads.retain(|&(read, _), _| read != entity_id);
let mut abandoned: Vec<CommandId> = Vec::new();
if let Some(session) = self.sessions.remove(&entity_id) {
abandoned.extend(session.queue.iter().filter_map(|request| request.command()));
}
self.inflight.retain(|_, inflight| {
let keep = inflight.entity_id != entity_id;
if !keep {
abandoned.extend(inflight.request.command());
}
keep
});
for command in abandoned {
self.drop_command_data(command);
self.events
.push_back(Event::CommandFinished(command, Outcome::NotPossible));
}
}
fn start_enumeration(&mut self, now: Instant, entity_id: EntityId) {
self.forget(entity_id);
let Some(entity) = self.entities.get(&entity_id) else {
return;
};
if self.config.own_mac == Some(entity.mac) {
let mut model = EntityModel::reading();
model.state = EnumerationState::Failed(EnumerationFailure::OnThisComputer);
self.models.insert(entity_id, model);
self.events.push_back(Event::EnumerationFailed(
entity_id,
EnumerationFailure::OnThisComputer,
));
return;
}
let mut session = Session::default();
if entity
.adp
.entity_capabilities
.contains(EntityCapabilities::VENDOR_UNIQUE_SUPPORTED)
{
session.queue.push_back(Request::GetMilanInfo);
}
session.queue.push_back(Request::ReadDescriptor {
descriptor_type: DescriptorType::ENTITY,
index: 0,
refresh: false,
});
self.sessions.insert(entity_id, session);
self.models.insert(entity_id, EntityModel::reading());
self.events.push_back(Event::EnumerationStarted(entity_id));
self.pump(now);
}
fn handle_aem(&mut self, now: Instant, source: MacAddress, aem: &AemPdu<'_>) {
let header = &aem.header;
match header.message_type {
AecpMessageType::AEM_COMMAND if header.target_entity_id == self.config.entity_id => {
let status = match aem.command_type {
AemCommandType::CONTROLLER_AVAILABLE => AemStatus::SUCCESS,
_ => AemStatus::NOT_IMPLEMENTED,
};
let mut out = [0; 600];
if let Ok(length) = aem::encode_response(aem, status, &mut out) {
self.outgoing.push_back((source, out[..length].to_vec()));
}
}
AecpMessageType::AEM_RESPONSE
if header.controller_entity_id == self.config.entity_id =>
{
if aem.unsolicited {
if aem.command_type == AemCommandType::SET_CONFIGURATION {
self.reconfigured(now, header.target_entity_id, aem.payload);
return;
}
self.handle_notification(header.target_entity_id, aem);
return;
}
let key = (Channel::Aem, header.sequence_id);
let Some(inflight) = self.inflight.get_mut(&key) else {
return;
};
if inflight.entity_id != header.target_entity_id
|| aem.command_type != command_type_of(inflight.request)
{
return;
}
if aem.status() == AemStatus::IN_PROGRESS {
inflight.deadline = now + COMMAND_TIMEOUT;
return;
}
let inflight = *inflight;
self.complete(key, inflight);
if let Request::SetConfiguration { command, .. } = inflight.request {
self.events
.push_back(Event::CommandFinished(command, aem_outcome(aem)));
if aem.status().is_success() {
self.reconfigured(now, inflight.entity_id, aem.payload);
}
return;
}
self.handle_response(inflight, aem);
}
AecpMessageType::AEM_RESPONSE
if !aem.unsolicited && aem.status().is_success() && overheard(aem.command_type) =>
{
if aem.command_type == AemCommandType::SET_CONFIGURATION {
self.reconfigured(now, header.target_entity_id, aem.payload);
return;
}
self.handle_notification(header.target_entity_id, aem);
}
_ => {}
}
}
fn reconfigured(&mut self, now: Instant, entity_id: EntityId, payload: &[u8]) {
if let (Some(configuration), Some(entity)) = (
aem::configuration_of(payload),
self.entities.get_mut(&entity_id),
) {
entity.adp.current_configuration_index = configuration;
}
if self.entities.contains_key(&entity_id) && self.config.enumerate {
self.start_enumeration(now, entity_id);
}
}
fn handle_vendor_unique(&mut self, now: Instant, pdu: &VendorUniquePdu<'_>) {
if pdu.header.message_type == AecpMessageType::VENDOR_UNIQUE_COMMAND {
if let Ok(cvu) = CvuMessage::from_pdu(pdu) {
self.store_cvu(now, &cvu);
}
return;
}
if pdu.header.message_type != AecpMessageType::VENDOR_UNIQUE_RESPONSE
|| pdu.header.controller_entity_id != self.config.entity_id
{
return;
}
if let Ok(message) = LiteMessage::from_pdu(pdu) {
self.handle_lite(now, pdu, &message);
return;
}
if let Ok(message) = WirelessMessage::from_pdu(pdu) {
self.handle_wireless(now, pdu, &message);
return;
}
let Ok(message) = MvuMessage::from_pdu(pdu) else {
return;
};
let entity_id = pdu.header.target_entity_id;
if message.unsolicited {
if pdu.header.status == 0
&& message.command_type == MvuCommandType::SET_MEDIA_CLOCK_REFERENCE_INFO
&& let Ok(reference) = MediaClockReference::decode(message.data)
{
self.store_media_clock_reference(entity_id, reference);
}
return;
}
let key = (Channel::Mvu, pdu.header.sequence_id);
let Some(inflight) = self.inflight.get(&key).copied() else {
return;
};
if inflight.entity_id != entity_id {
return;
}
match (inflight.request, message.command_type) {
(Request::GetMilanInfo, MvuCommandType::GET_MILAN_INFO) => {
self.complete(key, inflight);
let info = (pdu.header.status == 0)
.then(|| MilanInfo::decode(message.data).ok())
.flatten();
if let Some(model) = self.models.get_mut(&entity_id) {
model.milan = info;
}
}
(
Request::GetMediaClockReference { domain },
MvuCommandType::GET_MEDIA_CLOCK_REFERENCE_INFO,
) => {
self.complete(key, inflight);
if pdu.header.status == 0
&& let Ok(reference) = MediaClockReference::decode(message.data)
&& reference.domain == domain
{
self.store_media_clock_reference(entity_id, reference);
}
}
_ => return,
}
self.check_complete(entity_id);
}
fn handle_lite(&mut self, now: Instant, pdu: &VendorUniquePdu<'_>, message: &LiteMessage<'_>) {
let entity_id = pdu.header.target_entity_id;
let status = (pdu.header.status == 0
&& message.command_type == LiteCommandType::GET_LITE_STATUS)
.then(|| LiteStatus::decode(message.data).ok())
.flatten();
if message.unsolicited {
if let Some(status) = status {
self.store_lite_status(entity_id, status);
}
return;
}
let key = (Channel::Mvu, pdu.header.sequence_id);
let Some(inflight) = self.inflight.get(&key).copied() else {
return;
};
if let Request::SetLiteConfig {
interface, command, ..
} = inflight.request
{
if inflight.entity_id != entity_id {
return;
}
self.complete(key, inflight);
let status = AemStatus(pdu.header.status);
self.events.push_back(Event::CommandFinished(
command,
if status.is_success() {
Outcome::Done
} else {
Outcome::Refused(Refusal::Aem(status))
},
));
self.queue_query(entity_id, Request::GetLiteStatus { interface });
return;
}
let Request::GetLiteStatus { interface } = inflight.request else {
return;
};
if inflight.entity_id != entity_id {
return;
}
self.complete(key, inflight);
match status {
Some(status) if status.interface == interface => {
if let Some(model) = self.models.get_mut(&entity_id) {
model.lite_supported = Some(true);
}
if !self.config.lite_poll.is_zero() {
self.next_lite_poll
.get_or_insert(now + self.config.lite_poll);
}
self.store_lite_status(entity_id, status);
}
_ if pdu.header.status == AemStatus::NOT_IMPLEMENTED.0 => {
if let Some(model) = self.models.get_mut(&entity_id) {
model.lite_supported = Some(false);
}
}
_ => {}
}
self.check_complete(entity_id);
}
fn store_lite_status(&mut self, entity_id: EntityId, status: LiteStatus) {
if let Some(model) = self.models.get_mut(&entity_id)
&& model.has(DescriptorType::AVB_INTERFACE, status.interface)
&& model.set_lite_status(status)
&& model.state == EnumerationState::Complete
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn handle_wireless(
&mut self,
now: Instant,
pdu: &VendorUniquePdu<'_>,
message: &WirelessMessage<'_>,
) {
let entity_id = pdu.header.target_entity_id;
let wireless = (pdu.header.status == 0
&& message.command_type == WirelessCommandType::GET_WIRELESS_STATUS)
.then(|| WirelessStatus::decode(message.data).ok())
.flatten()
.map(|status| Wireless {
status,
stations: status.stations(message.data).collect(),
});
if message.unsolicited {
if let Some(wireless) = wireless {
self.store_wireless(entity_id, wireless);
}
return;
}
let key = (Channel::Mvu, pdu.header.sequence_id);
let Some(inflight) = self.inflight.get(&key).copied() else {
return;
};
if inflight.entity_id != entity_id {
return;
}
if let Request::SetWirelessConfig {
interface, command, ..
} = inflight.request
{
self.complete(key, inflight);
let status = AemStatus(pdu.header.status);
self.events.push_back(Event::CommandFinished(
command,
if status.is_success() {
Outcome::Done
} else {
Outcome::Refused(Refusal::Aem(status))
},
));
self.queue_query(entity_id, Request::GetWirelessStatus { interface });
return;
}
let Request::GetWirelessStatus { interface } = inflight.request else {
return;
};
self.complete(key, inflight);
let status = AemStatus(pdu.header.status);
match wireless {
Some(wireless) if wireless.status.interface == interface => {
if let Some(model) = self.models.get_mut(&entity_id) {
model.wireless_supported = Some(true);
}
if !self.config.wireless_poll.is_zero() {
self.next_wireless_poll
.get_or_insert(now + self.config.wireless_poll);
}
self.store_wireless(entity_id, wireless);
}
_ if status == AemStatus::NOT_SUPPORTED => {
if let Some(model) = self.models.get_mut(&entity_id) {
model.wireless_supported = Some(true);
}
}
_ if status == AemStatus::NOT_IMPLEMENTED => {
if let Some(model) = self.models.get_mut(&entity_id) {
model.wireless_supported = Some(false);
}
}
_ => {}
}
self.check_complete(entity_id);
}
fn store_wireless(&mut self, entity_id: EntityId, wireless: Wireless) {
if let Some(model) = self.models.get_mut(&entity_id)
&& model.has(DescriptorType::AVB_INTERFACE, wireless.status.interface)
&& model.set_wireless(wireless)
&& model.state == EnumerationState::Complete
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn store_cvu(&mut self, now: Instant, cvu: &CvuMessage<'_>) {
let Some(model) = self.models.get_mut(&cvu.sender) else {
return;
};
let mut changed = false;
for declaration in msrp::talker_declarations(cvu.msrp) {
changed |= if declaration.event.declares() {
model.set_cvu_talker(declaration, now)
} else {
model.remove_cvu_talker(declaration.stream_id)
};
}
if changed {
self.events.push_back(Event::EntityModelChanged(cvu.sender));
}
}
fn store_media_clock_reference(&mut self, entity_id: EntityId, reference: MediaClockReference) {
if let Some(model) = self.models.get_mut(&entity_id)
&& model.has(DescriptorType::CLOCK_DOMAIN, reference.domain)
&& model.set_media_clock_reference(reference)
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn complete(&mut self, key: (Channel, u16), inflight: Inflight) {
self.inflight.remove(&key);
if let Some(session) = self.sessions.get_mut(&inflight.entity_id)
&& session.inflight == Some(key)
{
session.inflight = None;
}
}
fn handle_address_access(&mut self, response: &AddressAccessPdu<'_>) {
let header = &response.header;
if header.controller_entity_id != self.config.entity_id {
return;
}
let key = (Channel::AddressAccess, header.sequence_id);
let Some(&inflight) = self.inflight.get(&key) else {
return;
};
let Request::ReadMemory { index, offset } = inflight.request else {
return;
};
if inflight.entity_id != header.target_entity_id {
return;
}
self.complete(key, inflight);
let read = (response.status() == AaStatus::SUCCESS)
.then(|| response.tlvs().next())
.flatten()
.and_then(Result::ok)
.filter(|tlv| tlv.mode == AaMode::READ && !tlv.data.is_empty());
self.memory_read(inflight.entity_id, index, offset, read.map(|tlv| tlv.data));
}
fn memory_read(&mut self, entity_id: EntityId, index: u16, offset: u32, data: Option<&[u8]>) {
let key = (entity_id, index);
let Some(data) = data else {
self.memory_reads.remove(&key);
return;
};
let read = self.memory_reads.entry(key).or_default();
if offset == 0 {
read.clear();
}
if read.len() != offset as usize {
self.memory_reads.remove(&key);
return;
}
read.extend_from_slice(data);
let have = read.len() as u64;
let Some(model) = self.models.get_mut(&entity_id) else {
self.memory_reads.remove(&key);
return;
};
let length = model
.memory_objects()
.find(|object| object.index == index)
.map(|object| object.length);
match length {
Some(length) if have < length => {
if let Some(session) = self.sessions.get_mut(&entity_id) {
session.queue.push_front(Request::ReadMemory {
index,
offset: have as u32,
});
}
}
Some(length) if have == length => {
let octets = self.memory_reads.remove(&key).unwrap_or_default();
if model.store_memory(index, octets) {
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
_ => {
self.memory_reads.remove(&key);
}
}
}
fn handle_response(&mut self, inflight: Inflight, aem: &AemPdu<'_>) {
let entity_id = inflight.entity_id;
match inflight.request {
Request::ReadDescriptor {
descriptor_type,
index,
refresh,
} => {
if !aem.status().is_success() {
self.read_failed(
entity_id,
descriptor_type,
refresh,
EnumerationFailure::Refused(aem.status()),
);
return;
}
let response = ReadDescriptorResponse::decode(aem.payload);
let Some(response) = matching(response, descriptor_type, index) else {
self.read_failed(
entity_id,
descriptor_type,
refresh,
EnumerationFailure::Malformed,
);
return;
};
self.descriptor_read(entity_id, response, refresh);
}
Request::RegisterUnsolicited => {
if let Some(model) = self.models.get_mut(&entity_id) {
model.registered = aem.status().is_success();
}
}
Request::GetStreamInfo {
descriptor_type,
index,
} => {
if let Ok(info) = StreamInfo::decode(aem.payload)
&& aem.status().is_success()
&& info.descriptor_type == descriptor_type
&& info.index == index
{
self.store_stream_info(entity_id, info);
}
}
Request::GetAvbInfo { index } => {
if let Ok(info) = AvbInfo::decode(aem.payload)
&& aem.status().is_success()
&& info.index == index
{
self.store_avb_info(entity_id, info);
}
}
Request::GetAsPath { index } => {
if let Ok(path) = AsPath::decode(aem.payload)
&& aem.status().is_success()
&& path.index == index
{
self.store_as_path(entity_id, &path);
}
}
Request::GetCounters {
descriptor_type,
index,
} => {
if let Ok(counters) = Counters::decode(aem.payload)
&& aem.status().is_success()
&& counters.descriptor_type == descriptor_type
&& counters.index == index
{
self.store_counters(entity_id, counters);
}
}
Request::Identify { command, .. } => {
if let Some(command) = command {
self.events
.push_back(Event::CommandFinished(command, aem_outcome(aem)));
}
}
Request::Streaming {
descriptor_type,
index,
command,
..
} => {
if aem.status().is_success() {
self.queue_query(
entity_id,
Request::GetStreamInfo {
descriptor_type,
index,
},
);
}
self.events
.push_back(Event::CommandFinished(command, aem_outcome(aem)));
}
Request::SetControl { index, command } => {
self.control_values.remove(&command);
if let Some(values) = control_values(aem.payload, index) {
self.store_control(entity_id, index, values);
}
self.events
.push_back(Event::CommandFinished(command, aem_outcome(aem)));
}
Request::GetDynamicInfo { queries, count } => {
self.dynamic_info_answered(entity_id, &queries[..usize::from(count)], Some(aem));
}
Request::GetMaxTransitTime { output, command } => {
if aem.status().is_success() {
self.store_max_transit_time(entity_id, output, aem.payload);
self.read_other_transit_times(entity_id, output);
}
if let Some(command) = command {
self.events
.push_back(Event::CommandFinished(command, aem_outcome(aem)));
}
}
Request::SetMaxTransitTime { set, command } => {
if aem.status().is_success() {
self.store_max_transit_time(entity_id, set.output, aem.payload);
}
self.events
.push_back(Event::CommandFinished(command, aem_outcome(aem)));
}
Request::ReadForCaller {
descriptor_type,
index,
command,
} => {
let response = ReadDescriptorResponse::decode(aem.payload);
if aem.status().is_success()
&& let Some(response) = matching(response, descriptor_type, index)
&& let Some(model) = self.models.get_mut(&entity_id)
&& model.store(descriptor_type, index, response.descriptor)
&& model.state == EnumerationState::Complete
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
self.events
.push_back(Event::CommandFinished(command, aem_outcome(aem)));
}
Request::GetAudioMap {
descriptor_type,
index,
map_index,
} => {
if let Ok(map) = AudioMap::decode(aem.payload)
&& aem.status().is_success()
&& (map.descriptor_type, map.index, map.map_index)
== (descriptor_type, index, map_index)
{
self.store_audio_map(entity_id, &map);
}
}
Request::ChangeMappings {
change,
descriptor_type,
index,
command,
} => {
self.mapping_changes.remove(&command);
if aem.status().is_success() {
if let Ok(changed) = AudioMappings::decode(aem.payload) {
self.store_mapping_change(entity_id, change, &changed);
}
self.queue_query(
entity_id,
Request::GetAudioMap {
descriptor_type,
index,
map_index: 0,
},
);
}
self.events
.push_back(Event::CommandFinished(command, aem_outcome(aem)));
}
Request::ReadOther {
configuration,
descriptor_type,
index,
} => {
let response = ReadDescriptorResponse::decode(aem.payload);
let read = aem
.status()
.is_success()
.then(|| matching(response, descriptor_type, index))
.flatten()
.map(|response| response.descriptor);
self.other_read(entity_id, configuration, descriptor_type, index, read);
}
Request::SetName { command, .. }
| Request::SetStreamFormat { command, .. }
| Request::SetSamplingRate { command, .. }
| Request::SetClockSource { command, .. } => {
if aem.status().is_success() {
self.applied(entity_id, inflight.request, aem.payload);
}
self.events
.push_back(Event::CommandFinished(command, aem_outcome(aem)));
}
Request::SetConfiguration { .. }
| Request::GetMilanInfo
| Request::GetMediaClockReference { .. }
| Request::GetLiteStatus { .. }
| Request::SetLiteConfig { .. }
| Request::GetWirelessStatus { .. }
| Request::SetWirelessConfig { .. }
| Request::GetRxState { .. }
| Request::Bind { .. }
| Request::Unbind { .. }
| Request::GetTxState { .. }
| Request::GetTxConnection { .. }
| Request::DisconnectTx { .. }
| Request::ReadMemory { .. } => {}
}
self.check_complete(entity_id);
}
fn other_read(
&mut self,
entity_id: EntityId,
configuration: u16,
descriptor_type: DescriptorType,
index: u16,
bytes: Option<&[u8]>,
) {
let Some(model) = self.models.get_mut(&entity_id) else {
return;
};
if let Some(bytes) = bytes {
model.store_other(configuration, descriptor_type, index, bytes);
}
if descriptor_type == DescriptorType::CONFIGURATION
&& let Some(Ok(descriptor)) = bytes.map(ConfigurationDescriptor::decode)
{
if descriptor.object_name.is_empty()
&& let Some(strings) = self
.models
.get(&entity_id)
.and_then(|model| model.strings_of(descriptor.localized_description))
{
self.queue_query(
entity_id,
Request::ReadOther {
configuration,
descriptor_type: DescriptorType::STRINGS,
index: strings,
},
);
}
for (stream_type, count) in descriptor.descriptor_counts().filter(|(found, _)| {
matches!(
*found,
DescriptorType::STREAM_INPUT | DescriptorType::STREAM_OUTPUT
)
}) {
for stream in 0..count {
self.queue_query(
entity_id,
Request::ReadOther {
configuration,
descriptor_type: stream_type,
index: stream,
},
);
}
}
}
let pending = self.sessions.get(&entity_id).is_some_and(|session| {
session
.queue
.iter()
.any(|request| matches!(request, Request::ReadOther { .. }))
});
if !pending {
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn applied(&mut self, entity_id: EntityId, request: Request, payload: &[u8]) {
let Some(model) = self.models.get_mut(&entity_id) else {
return;
};
let (changed, target) = match request {
Request::SetName { set, .. } => (
SetName::decode(payload).is_ok_and(|set| model.apply_name(&set)),
(set.descriptor_type, set.index),
),
Request::SetStreamFormat { set, .. } => (
SetStreamFormat::decode(payload).is_ok_and(|set| model.apply_stream_format(&set)),
(set.descriptor_type, set.index),
),
Request::SetSamplingRate { set, .. } => (
SetSamplingRate::decode(payload).is_ok_and(|set| model.apply_sampling_rate(&set)),
(set.descriptor_type, set.index),
),
Request::SetClockSource { set, .. } => (
SetClockSource::decode(payload).is_ok_and(|set| model.apply_clock_source(&set)),
(DescriptorType::CLOCK_DOMAIN, set.domain),
),
_ => return,
};
let streams: Vec<(DescriptorType, u16)> = match request {
Request::SetSamplingRate { .. } => {
[DescriptorType::STREAM_INPUT, DescriptorType::STREAM_OUTPUT]
.into_iter()
.flat_map(|descriptor_type| {
model
.descriptors(descriptor_type)
.map(move |(index, _)| (descriptor_type, index))
})
.collect()
}
_ => Vec::new(),
};
if changed {
self.events.push_back(Event::EntityModelChanged(entity_id));
} else {
self.queue_read(entity_id, target.0, target.1, true);
}
for (descriptor_type, index) in streams {
self.queue_read(entity_id, descriptor_type, index, true);
}
if let Request::SetStreamFormat { set, .. } = request {
self.queue_query(
entity_id,
Request::GetStreamInfo {
descriptor_type: set.descriptor_type,
index: set.index,
},
);
}
if matches!(
request,
Request::SetStreamFormat { .. } | Request::SetSamplingRate { .. }
) {
self.queue_audio_map_reads(entity_id);
}
}
fn queue_audio_map_reads(&mut self, entity_id: EntityId) {
if !self.config.read_mappings {
return;
}
let Some(model) = self.models.get(&entity_id) else {
return;
};
for request in audio_map_reads(model) {
self.queue_query(entity_id, request);
}
}
fn store_audio_map(&mut self, entity_id: EntityId, map: &AudioMap<'_>) {
let Some(model) = self.models.get_mut(&entity_id) else {
return;
};
if !model.has(map.descriptor_type, map.index) {
return;
}
if model.set_audio_map(map) {
self.events.push_back(Event::EntityModelChanged(entity_id));
}
let next = map.map_index.saturating_add(1);
if next < map.number_of_maps.min(MAX_MAP_PARTS)
&& let Some(session) = self.sessions.get_mut(&entity_id)
{
let request = Request::GetAudioMap {
descriptor_type: map.descriptor_type,
index: map.index,
map_index: next,
};
if !session.queue.contains(&request) {
let place = session
.queue
.iter()
.position(|queued| queued.command().is_none())
.unwrap_or(session.queue.len());
session.queue.insert(place, request);
}
}
}
fn store_mapping_change(
&mut self,
entity_id: EntityId,
change: MappingChange,
changed: &AudioMappings<'_>,
) {
if let Some(model) = self.models.get_mut(&entity_id)
&& model.apply_mappings(change, changed)
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn store_stream_info(&mut self, entity_id: EntityId, info: StreamInfo) {
if let Some(model) = self.models.get_mut(&entity_id)
&& model.has(info.descriptor_type, info.index)
&& model.set_stream_info(info)
{
self.events.push_back(Event::EntityModelChanged(entity_id));
if self.config.read_talker_state
&& info.descriptor_type == DescriptorType::STREAM_OUTPUT
{
self.queue_query(
entity_id,
Request::GetTxState {
output: info.index,
command: None,
},
);
}
}
}
fn store_avb_info(&mut self, entity_id: EntityId, info: AvbInfo) {
if let Some(model) = self.models.get_mut(&entity_id)
&& model.has(DescriptorType::AVB_INTERFACE, info.index)
&& model.set_avb_info(info)
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn store_as_path(&mut self, entity_id: EntityId, path: &AsPath<'_>) {
if let Some(model) = self.models.get_mut(&entity_id)
&& model.has(DescriptorType::AVB_INTERFACE, path.index)
&& model.set_as_path(path)
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn store_counters(&mut self, entity_id: EntityId, counters: Counters) {
if let Some(model) = self.models.get_mut(&entity_id)
&& model.has(counters.descriptor_type, counters.index)
&& model.set_counters(counters)
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn handle_acmp(&mut self, acmpdu: &Acmpdu) {
if !acmpdu.message_type.is_response() {
return;
}
let key = (Channel::Acmp, acmpdu.sequence_id);
let addressed = if to_talker(acmpdu.message_type) {
acmpdu.talker_entity_id
} else {
acmpdu.listener_entity_id
};
if acmpdu.controller_entity_id == self.config.entity_id
&& let Some(inflight) = self.inflight.get(&key).copied()
&& inflight.entity_id == addressed
&& inflight
.request
.acmp_message()
.map(AcmpMessageType::response)
== Some(acmpdu.message_type)
{
self.complete(key, inflight);
if let Request::Bind { input, .. } | Request::Unbind { input, .. } = inflight.request
&& !acmpdu.status.is_success()
{
self.queue_query(addressed, Request::GetRxState { input });
}
if let Request::GetTxState { output, .. } = inflight.request
&& acmpdu.status.is_success()
&& acmpdu.talker_unique_id == output
{
let state = TxState {
stream_id: acmpdu.stream_id,
destination: acmpdu.stream_dest_mac,
connection_count: acmpdu.connection_count,
vlan_id: acmpdu.stream_vlan_id,
};
if let Some(model) = self.models.get_mut(&addressed) {
let mut changed = model.set_tx_state(output, state);
changed |= model.trim_tx_connections(output, state.connection_count);
if changed {
self.events.push_back(Event::EntityModelChanged(addressed));
}
if self.config.read_talker_state
&& model.tx_connections_supported != Some(false)
{
for index in 0..state.connection_count {
self.queue_query(
addressed,
Request::GetTxConnection {
output,
index,
command: None,
},
);
}
}
}
}
if let Request::GetTxConnection { .. } = inflight.request
&& acmpdu.status == AcmpStatus::NOT_SUPPORTED
&& let Some(model) = self.models.get_mut(&addressed)
{
model.tx_connections_supported = Some(false);
}
if let Request::GetTxConnection { output, index, .. } = inflight.request
&& acmpdu.status.is_success()
&& acmpdu.talker_unique_id == output
&& let Some(model) = self.models.get_mut(&addressed)
&& model.set_tx_connection(
output,
index,
(acmpdu.listener_entity_id, acmpdu.listener_unique_id),
)
{
self.events.push_back(Event::EntityModelChanged(addressed));
}
if let Some(command) = inflight.request.command() {
let outcome = if acmpdu.status.is_success() {
Outcome::Done
} else {
Outcome::Refused(Refusal::Acmp(acmpdu.status))
};
self.events
.push_back(Event::CommandFinished(command, outcome));
}
}
if acmpdu.status.is_success() {
self.observe_binding(acmpdu);
self.observe_talker(acmpdu);
}
}
fn observe_talker(&mut self, acmpdu: &Acmpdu) {
if !self.config.read_talker_state
|| !matches!(
acmpdu.message_type,
AcmpMessageType::CONNECT_TX_RESPONSE | AcmpMessageType::DISCONNECT_TX_RESPONSE
)
{
return;
}
let (talker, output) = (acmpdu.talker_entity_id, acmpdu.talker_unique_id);
if !self
.models
.get(&talker)
.is_some_and(|model| model.has(DescriptorType::STREAM_OUTPUT, output))
{
return;
}
self.queue_query(
talker,
Request::GetTxState {
output,
command: None,
},
);
self.queue_query(
talker,
Request::GetStreamInfo {
descriptor_type: DescriptorType::STREAM_OUTPUT,
index: output,
},
);
}
fn observe_binding(&mut self, acmpdu: &Acmpdu) {
let binding = match acmpdu.message_type {
AcmpMessageType::CONNECT_RX_RESPONSE => Binding {
talker: acmpdu.talker_entity_id,
talker_unique_id: acmpdu.talker_unique_id,
connection_count: acmpdu.connection_count.max(1),
flags: acmpdu.flags,
},
AcmpMessageType::DISCONNECT_RX_RESPONSE => Binding::default(),
AcmpMessageType::GET_RX_STATE_RESPONSE => Binding {
talker: acmpdu.talker_entity_id,
talker_unique_id: acmpdu.talker_unique_id,
connection_count: acmpdu.connection_count,
flags: acmpdu.flags,
},
_ => return,
};
let entity_id = acmpdu.listener_entity_id;
let input = acmpdu.listener_unique_id;
let Some(model) = self.models.get_mut(&entity_id) else {
return;
};
if !model.has(DescriptorType::STREAM_INPUT, input) {
return;
}
if model.set_binding(input, binding) {
self.events.push_back(Event::EntityModelChanged(entity_id));
}
if acmpdu.message_type != AcmpMessageType::GET_RX_STATE_RESPONSE {
self.queue_query(
entity_id,
Request::GetStreamInfo {
descriptor_type: DescriptorType::STREAM_INPUT,
index: input,
},
);
}
}
fn queue_query(&mut self, entity_id: EntityId, request: Request) {
if let Some(session) = self.sessions.get_mut(&entity_id)
&& !session.queue.contains(&request)
{
session.queue.push_back(request);
}
}
fn read_failed(
&mut self,
entity_id: EntityId,
descriptor_type: DescriptorType,
refresh: bool,
failure: EnumerationFailure,
) {
let Some(model) = self.models.get_mut(&entity_id) else {
return;
};
let essential = matches!(
descriptor_type,
DescriptorType::ENTITY | DescriptorType::CONFIGURATION
);
if essential && !refresh {
model.state = EnumerationState::Failed(failure);
if let Some(session) = self.sessions.get_mut(&entity_id) {
session.queue.clear();
}
self.events
.push_back(Event::EnumerationFailed(entity_id, failure));
} else {
model.failed_reads = model.failed_reads.saturating_add(1);
}
}
fn descriptor_read(
&mut self,
entity_id: EntityId,
response: ReadDescriptorResponse<'_>,
refresh: bool,
) {
let descriptor = response.descriptor;
let mut follow_ups: Vec<(DescriptorType, u16, u16)> = Vec::new();
let Some(model) = self.models.get_mut(&entity_id) else {
return;
};
if !refresh {
match response.descriptor_type {
DescriptorType::ENTITY => match EntityDescriptor::decode(descriptor) {
Ok(entity) => {
model.configuration = entity.current_configuration;
follow_ups.push((
DescriptorType::CONFIGURATION,
entity.current_configuration,
1,
));
}
Err(_) => {
self.read_failed(
entity_id,
DescriptorType::ENTITY,
false,
EnumerationFailure::Malformed,
);
return;
}
},
DescriptorType::CONFIGURATION => {
match ConfigurationDescriptor::decode(descriptor) {
Ok(configuration) => {
let key = model.entity().map(|entity| ModelKey {
entity_model_id: entity.entity_model_id,
firmware: entity.firmware_version.into(),
configuration: response.index,
});
let cached =
key.and_then(|key| self.cache.get(&key)).filter(|cached| {
cached
.descriptor(DescriptorType::CONFIGURATION, response.index)
.and_then(|bytes| {
ConfigurationDescriptor::decode(bytes).ok()
})
.is_some_and(|known| {
known
.descriptor_counts()
.eq(configuration.descriptor_counts())
})
});
if let Some(cached) = cached {
let cached = cached.clone();
model.store(response.descriptor_type, response.index, descriptor);
self.use_cached(entity_id, &cached);
return;
}
for (descriptor_type, count) in configuration.descriptor_counts() {
if READ_TYPES.contains(&descriptor_type) {
follow_ups.push((descriptor_type, 0, count));
}
}
}
Err(_) => {
self.read_failed(
entity_id,
DescriptorType::CONFIGURATION,
false,
EnumerationFailure::Malformed,
);
return;
}
}
}
DescriptorType::AUDIO_UNIT => {
if let Ok(unit) = AudioUnitDescriptor::decode(descriptor) {
follow_ups.push((
DescriptorType::STREAM_PORT_INPUT,
unit.base_stream_input_port,
unit.number_of_stream_input_ports,
));
follow_ups.push((
DescriptorType::STREAM_PORT_OUTPUT,
unit.base_stream_output_port,
unit.number_of_stream_output_ports,
));
}
}
DescriptorType::STREAM_PORT_INPUT | DescriptorType::STREAM_PORT_OUTPUT => {
if let Ok(port) = StreamPortDescriptor::decode(descriptor) {
follow_ups.push((
DescriptorType::AUDIO_CLUSTER,
port.base_cluster,
port.number_of_clusters,
));
follow_ups.push((
DescriptorType::AUDIO_MAP,
port.base_map,
port.number_of_maps,
));
}
}
DescriptorType::LOCALE => {
if let Ok(locale) = LocaleDescriptor::decode(descriptor) {
follow_ups.push((
DescriptorType::STRINGS,
locale.base_strings,
locale.number_of_strings,
));
}
}
_ => {}
}
}
let changed = model.store(response.descriptor_type, response.index, descriptor);
if refresh && changed {
self.events.push_back(Event::EntityModelChanged(entity_id));
}
for (descriptor_type, first, count) in follow_ups {
for index in first..first.saturating_add(count) {
self.queue_read(entity_id, descriptor_type, index, false);
}
}
}
fn use_cached(&mut self, entity_id: EntityId, cached: &CachedModel) {
let Some(model) = self.models.get_mut(&entity_id) else {
return;
};
model.from_cache = true;
let milan = model.milan.is_some();
let mut own = Vec::new();
let mut queries = Vec::new();
for (descriptor_type, index, bytes) in &cached.descriptors {
let (descriptor_type, index) = (*descriptor_type, *index);
if OWN_TYPES.contains(&descriptor_type) {
if !matches!(
descriptor_type,
DescriptorType::ENTITY | DescriptorType::CONFIGURATION
) {
own.push((descriptor_type, index));
}
continue;
}
model.store(descriptor_type, index, bytes);
if STATIC_TYPES.contains(&descriptor_type) {
continue;
}
queries.extend(dynamic_queries(descriptor_type, index));
}
for (descriptor_type, index) in own {
self.queue_read(entity_id, descriptor_type, index, false);
}
if milan {
self.queue_dynamic_info(entity_id, &queries);
} else {
self.read_instead(entity_id, &queries);
}
}
fn queue_dynamic_info(&mut self, entity_id: EntityId, queries: &[DynamicQuery]) {
let Some(session) = self.sessions.get_mut(&entity_id) else {
return;
};
let mut batch = [DynamicQuery::ClockSource { domain: 0 }; MAX_DYNAMIC_QUERIES];
let (mut count, mut room) = (0, 0);
for &query in queries {
if count == MAX_DYNAMIC_QUERIES || room + query.answer_len() > aem::MAX_AEM_PAYLOAD {
session.queue.push_back(Request::GetDynamicInfo {
queries: batch,
count: count as u8,
});
(count, room) = (0, 0);
}
batch[count] = query;
count += 1;
room += query.answer_len();
}
if count > 0 {
session.queue.push_back(Request::GetDynamicInfo {
queries: batch,
count: count as u8,
});
}
}
fn read_instead(&mut self, entity_id: EntityId, queries: &[DynamicQuery]) {
let mut targets: Vec<(DescriptorType, u16)> =
queries.iter().map(|query| query.target()).collect();
targets.dedup();
for (descriptor_type, index) in targets {
self.queue_read(entity_id, descriptor_type, index, true);
}
}
fn dynamic_info_answered(
&mut self,
entity_id: EntityId,
asked: &[DynamicQuery],
aem: Option<&AemPdu<'_>>,
) {
let Some(aem) = aem.filter(|aem| aem.status().is_success()) else {
let mut queries = asked.to_vec();
if let Some(session) = self.sessions.get_mut(&entity_id) {
session.queue.retain(|request| match request {
Request::GetDynamicInfo {
queries: more,
count,
} => {
queries.extend_from_slice(&more[..usize::from(*count)]);
false
}
_ => true,
});
}
self.read_instead(entity_id, &queries);
return;
};
let Some(model) = self.models.get_mut(&entity_id) else {
return;
};
let mut unanswered: Vec<DynamicQuery> = asked.to_vec();
let mut changed = false;
for info in aem::dynamic_infos(aem.payload) {
if !info.status.is_success() {
continue;
}
let applied = match info.command_type {
AemCommandType::GET_NAME => SetName::decode(info.data).ok().map(|got| {
let query = DynamicQuery::Name {
descriptor_type: got.descriptor_type,
index: got.index,
name_index: got.name_index,
};
(query, model.apply_name(&got))
}),
AemCommandType::GET_STREAM_FORMAT => {
SetStreamFormat::decode(info.data).ok().map(|got| {
let query = DynamicQuery::StreamFormat {
descriptor_type: got.descriptor_type,
index: got.index,
};
(query, model.apply_stream_format(&got))
})
}
AemCommandType::GET_SAMPLING_RATE => {
SetSamplingRate::decode(info.data).ok().map(|got| {
let query = DynamicQuery::SamplingRate {
descriptor_type: got.descriptor_type,
index: got.index,
};
(query, model.apply_sampling_rate(&got))
})
}
AemCommandType::GET_CLOCK_SOURCE => {
SetClockSource::decode(info.data).ok().map(|got| {
(
DynamicQuery::ClockSource { domain: got.domain },
model.apply_clock_source(&got),
)
})
}
_ => None,
};
if let Some((query, applied)) = applied {
unanswered.retain(|asked| *asked != query);
changed |= applied;
}
}
if changed && model.state == EnumerationState::Complete {
self.events.push_back(Event::EntityModelChanged(entity_id));
}
self.read_instead(entity_id, &unanswered);
}
pub fn remember_model(&mut self, model: CachedModel) {
self.cache.insert(model.key.clone(), model);
}
pub fn static_model(&self, entity_id: EntityId) -> Option<CachedModel> {
let model = self.models.get(&entity_id)?;
if model.state != EnumerationState::Complete || model.failed_reads > 0 || model.from_cache {
return None;
}
let entity = model.entity()?;
Some(CachedModel {
key: ModelKey {
entity_model_id: entity.entity_model_id,
firmware: entity.firmware_version.into(),
configuration: model.configuration,
},
descriptors: model
.all_descriptors()
.filter(|(descriptor_type, _, _)| *descriptor_type != DescriptorType::ENTITY)
.map(|(descriptor_type, index, bytes)| (descriptor_type, index, bytes.to_vec()))
.collect(),
})
}
fn queue_read(
&mut self,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
refresh: bool,
) {
let (Some(session), Some(model)) = (
self.sessions.get_mut(&entity_id),
self.models.get(&entity_id),
) else {
return;
};
let request = Request::ReadDescriptor {
descriptor_type,
index,
refresh,
};
if session.queue.contains(&request) {
return;
}
if !refresh {
if model.has(descriptor_type, index) || session.requested >= MAX_DESCRIPTORS {
return;
}
session.requested += 1;
}
session.queue.push_back(request);
}
fn check_complete(&mut self, entity_id: EntityId) {
let (Some(session), Some(model)) = (
self.sessions.get_mut(&entity_id),
self.models.get_mut(&entity_id),
) else {
return;
};
if model.state != EnumerationState::Reading
|| !session.queue.is_empty()
|| session.inflight.is_some()
{
return;
}
model.state = EnumerationState::Complete;
for (index, _) in model.descriptors(DescriptorType::STREAM_INPUT) {
session
.queue
.push_back(Request::GetRxState { input: index });
session.queue.push_back(Request::GetStreamInfo {
descriptor_type: DescriptorType::STREAM_INPUT,
index,
});
}
for (index, _) in model.descriptors(DescriptorType::STREAM_OUTPUT) {
session.queue.push_back(Request::GetStreamInfo {
descriptor_type: DescriptorType::STREAM_OUTPUT,
index,
});
}
if self.config.read_mappings {
session.queue.extend(audio_map_reads(model));
}
if self.config.read_counters {
for descriptor_type in [
DescriptorType::CLOCK_DOMAIN,
DescriptorType::STREAM_INPUT,
DescriptorType::STREAM_OUTPUT,
] {
for (index, _) in model.descriptors(descriptor_type) {
session.queue.push_back(Request::GetCounters {
descriptor_type,
index,
});
}
}
}
if self.config.read_transit_times {
let asked = if model.milan.is_some() { usize::MAX } else { 1 };
for (output, _) in model.descriptors(DescriptorType::STREAM_OUTPUT).take(asked) {
session.queue.push_back(Request::GetMaxTransitTime {
output,
command: None,
});
}
}
if self.config.read_configurations
&& let Some(entity) = model.entity()
{
for configuration in
(0..entity.configurations_count).filter(|&other| other != model.configuration)
{
session.queue.push_back(Request::ReadOther {
configuration,
descriptor_type: DescriptorType::CONFIGURATION,
index: configuration,
});
}
}
if self.config.lite_status && model.lite_supported != Some(false) {
for (interface, _) in model.descriptors(DescriptorType::AVB_INTERFACE) {
session
.queue
.push_back(Request::GetLiteStatus { interface });
}
}
if self.config.wireless_status && model.wireless_supported != Some(false) {
for (interface, _) in model.descriptors(DescriptorType::AVB_INTERFACE) {
session
.queue
.push_back(Request::GetWirelessStatus { interface });
}
}
if self.config.media_clock_info && model.milan.is_some() {
for (domain, _) in model.descriptors(DescriptorType::CLOCK_DOMAIN) {
session
.queue
.push_back(Request::GetMediaClockReference { domain });
}
}
if self.config.network_info {
for (index, _) in model.descriptors(DescriptorType::AVB_INTERFACE) {
session.queue.push_back(Request::GetAvbInfo { index });
session.queue.push_back(Request::GetAsPath { index });
session.queue.push_back(Request::GetCounters {
descriptor_type: DescriptorType::AVB_INTERFACE,
index,
});
}
}
if self.config.register_unsolicited && !model.registered {
session.queue.push_back(Request::RegisterUnsolicited);
}
let address_access = self.entities.get(&entity_id).is_some_and(|entity| {
entity
.adp
.entity_capabilities
.contains(EntityCapabilities::ADDRESS_ACCESS_SUPPORTED)
});
if self.config.read_logos && address_access {
for object in model.memory_objects().filter(is_logo) {
session.queue.push_back(Request::ReadMemory {
index: object.index,
offset: 0,
});
}
}
self.events.push_back(Event::EntityEnumerated(entity_id));
}
fn handle_notification(&mut self, entity_id: EntityId, aem: &AemPdu<'_>) {
let Some(model) = self.models.get_mut(&entity_id) else {
return;
};
if aem.command_type == AemCommandType::DEREGISTER_UNSOLICITED_NOTIFICATION {
model.registered = false;
if self.config.register_unsolicited
&& model.state == EnumerationState::Complete
&& let Some(session) = self.sessions.get_mut(&entity_id)
{
session.queue.push_back(Request::RegisterUnsolicited);
}
return;
}
match aem.command_type {
AemCommandType::GET_STREAM_INFO | AemCommandType::SET_STREAM_INFO => {
if let Ok(info) = StreamInfo::decode(aem.payload) {
self.store_stream_info(entity_id, info);
}
return;
}
AemCommandType::GET_AVB_INFO => {
if let Ok(info) = AvbInfo::decode(aem.payload) {
self.store_avb_info(entity_id, info);
}
return;
}
AemCommandType::GET_AS_PATH => {
if let Ok(path) = AsPath::decode(aem.payload) {
self.store_as_path(entity_id, &path);
}
return;
}
AemCommandType::GET_COUNTERS => {
if let Ok(counters) = Counters::decode(aem.payload) {
self.store_counters(entity_id, counters);
}
return;
}
AemCommandType::ADD_AUDIO_MAPPINGS | AemCommandType::REMOVE_AUDIO_MAPPINGS => {
let change = if aem.command_type == AemCommandType::ADD_AUDIO_MAPPINGS {
MappingChange::Add
} else {
MappingChange::Remove
};
if let Ok(changed) = AudioMappings::decode(aem.payload) {
self.store_mapping_change(entity_id, change, &changed);
}
return;
}
AemCommandType::GET_AUDIO_MAP => return,
AemCommandType::SET_MAX_TRANSIT_TIME | AemCommandType::GET_MAX_TRANSIT_TIME => {
if let Ok(time) = MaxTransitTime::decode(aem.payload) {
self.store_max_transit_time(entity_id, time.output, aem.payload);
}
return;
}
AemCommandType::SET_CONTROL | AemCommandType::GET_CONTROL => {
if let Some((DescriptorType::CONTROL, index)) = aem::target_descriptor(aem.payload)
&& let Some(values) = control_values(aem.payload, index)
{
self.store_control(entity_id, index, values);
}
return;
}
_ => {}
}
if let Some((descriptor_type, index)) = aem::target_descriptor(aem.payload)
&& model.has(descriptor_type, index)
{
self.queue_read(entity_id, descriptor_type, index, true);
}
}
fn pump(&mut self, now: Instant) {
let ready: Vec<EntityId> = self
.sessions
.iter()
.filter(|(_, session)| session.inflight.is_none() && !session.queue.is_empty())
.map(|(&entity_id, _)| entity_id)
.collect();
for entity_id in ready {
let Some(request) = self
.sessions
.get_mut(&entity_id)
.and_then(|session| session.queue.pop_front())
else {
continue;
};
let counter = match request.channel() {
Channel::Aem => &mut self.next_aem_sequence,
Channel::Mvu => &mut self.next_mvu_sequence,
Channel::Acmp => &mut self.next_acmp_sequence,
Channel::AddressAccess => &mut self.next_address_access_sequence,
};
let sequence = *counter;
*counter = sequence.wrapping_add(1);
let key = (request.channel(), sequence);
let inflight = Inflight {
entity_id,
request,
deadline: now + self.timeout(entity_id, request),
retried: false,
};
if !self.send(key, inflight) {
continue;
}
self.inflight.insert(key, inflight);
if let Some(session) = self.sessions.get_mut(&entity_id) {
session.inflight = Some(key);
}
}
}
fn send(&mut self, (_, sequence_id): (Channel, u16), inflight: Inflight) -> bool {
let Some(entity) = self.entities.get(&inflight.entity_id) else {
return false;
};
let addressing = Addressing {
target: inflight.entity_id,
controller: self.config.entity_id,
sequence_id,
};
let mut out = [0; 600];
let acmp = |message_type, talker: (EntityId, u16), input: u16, out: &mut [u8]| {
Acmpdu::command(
message_type,
addressing.controller,
talker,
(addressing.target, input),
sequence_id,
)
.encode(out)
};
let destination = match inflight.request.channel() {
Channel::Acmp => crate::ADP_ACMP_MULTICAST,
Channel::Aem | Channel::Mvu | Channel::AddressAccess => entity.mac,
};
let length = match inflight.request {
Request::ReadDescriptor {
descriptor_type,
index,
..
} => {
let configuration = self
.models
.get(&inflight.entity_id)
.map_or(0, |model| model.configuration);
aem::encode_read_descriptor(
addressing,
configuration,
descriptor_type,
index,
&mut out,
)
}
Request::RegisterUnsolicited => aem::encode_register_unsolicited(addressing, &mut out),
Request::GetLiteStatus { interface } => lite::encode_get_lite_status(
addressing.target,
addressing.controller,
sequence_id,
interface,
&mut out,
),
Request::SetLiteConfig {
interface, flags, ..
} => lite::encode_set_lite_config(
addressing.target,
addressing.controller,
sequence_id,
interface,
lite::LiteConfigFlags(flags),
&mut out,
),
Request::GetWirelessStatus { interface } => wireless::encode_get_wireless_status(
addressing.target,
addressing.controller,
sequence_id,
interface,
&mut out,
),
Request::SetWirelessConfig {
interface, flags, ..
} => wireless::encode_set_wireless_config(
addressing.target,
addressing.controller,
sequence_id,
interface,
wireless::WirelessConfigFlags(flags),
&mut out,
),
Request::GetMilanInfo => mvu::encode_get_milan_info(
addressing.target,
addressing.controller,
sequence_id,
&mut out,
),
Request::GetMediaClockReference { domain } => mvu::encode_get_media_clock_reference(
addressing.target,
addressing.controller,
sequence_id,
domain,
&mut out,
),
Request::GetStreamInfo {
descriptor_type,
index,
} => aem::encode_get_stream_info(addressing, descriptor_type, index, &mut out),
Request::GetAvbInfo { index } => aem::encode_get_avb_info(addressing, index, &mut out),
Request::GetAsPath { index } => aem::encode_get_as_path(addressing, index, &mut out),
Request::GetCounters {
descriptor_type,
index,
} => aem::encode_get_counters(addressing, descriptor_type, index, &mut out),
Request::Identify { control, on, .. } => {
aem::encode_set_control(addressing, control, &[if on { 255 } else { 0 }], &mut out)
}
Request::SetName { set, .. } => {
let configuration = match set.descriptor_type {
DescriptorType::ENTITY | DescriptorType::CONFIGURATION => 0,
_ => self
.models
.get(&inflight.entity_id)
.map_or(0, |model| model.configuration),
};
SetName {
configuration,
..set
}
.encode(addressing, &mut out)
}
Request::SetStreamFormat { set, .. } => set.encode(addressing, &mut out),
Request::Streaming {
descriptor_type,
index,
start,
..
} => aem::encode_streaming(addressing, start, descriptor_type, index, &mut out),
Request::SetSamplingRate { set, .. } => set.encode(addressing, &mut out),
Request::SetClockSource { set, .. } => set.encode(addressing, &mut out),
Request::SetConfiguration { configuration, .. } => {
aem::encode_set_configuration(addressing, configuration, &mut out)
}
Request::ReadOther {
configuration,
descriptor_type,
index,
} => aem::encode_read_descriptor(
addressing,
configuration,
descriptor_type,
index,
&mut out,
),
Request::GetMaxTransitTime { output, .. } => {
aem::encode_get_max_transit_time(addressing, output, &mut out)
}
Request::SetMaxTransitTime { set, .. } => set.encode(addressing, &mut out),
Request::ReadForCaller {
descriptor_type,
index,
..
} => {
let configuration = self
.models
.get(&inflight.entity_id)
.map_or(0, |model| model.configuration);
aem::encode_read_descriptor(
addressing,
configuration,
descriptor_type,
index,
&mut out,
)
}
Request::GetTxState { output, .. } => Acmpdu::command(
AcmpMessageType::GET_TX_STATE_COMMAND,
addressing.controller,
(addressing.target, output),
(EntityId(0), 0),
sequence_id,
)
.encode(&mut out),
Request::GetTxConnection { output, index, .. } => Acmpdu {
connection_count: index,
..Acmpdu::command(
AcmpMessageType::GET_TX_CONNECTION_COMMAND,
addressing.controller,
(addressing.target, output),
(EntityId(0), 0),
sequence_id,
)
}
.encode(&mut out),
Request::DisconnectTx {
output,
listener,
listener_unique_id,
..
} => Acmpdu::command(
AcmpMessageType::DISCONNECT_TX_COMMAND,
addressing.controller,
(addressing.target, output),
(listener, listener_unique_id),
sequence_id,
)
.encode(&mut out),
Request::SetControl { index, command } => aem::encode_set_control(
addressing,
index,
self.control_values
.get(&command)
.map_or(&[][..], Vec::as_slice),
&mut out,
),
Request::GetAudioMap {
descriptor_type,
index,
map_index,
} => aem::encode_get_audio_map(addressing, descriptor_type, index, map_index, &mut out),
Request::ChangeMappings {
change,
descriptor_type,
index,
command,
} => aem::encode_audio_mappings(
addressing,
change,
descriptor_type,
index,
self.mapping_changes
.get(&command)
.map_or(&[][..], Vec::as_slice),
&mut out,
),
Request::GetDynamicInfo { queries, count } => {
let configuration = self
.models
.get(&inflight.entity_id)
.map_or(0, |model| model.configuration);
aem::encode_get_dynamic_info(
addressing,
configuration,
&queries[..usize::from(count)],
&mut out,
)
}
Request::ReadMemory { index, offset } => {
let Some((address, length)) = self
.models
.get(&inflight.entity_id)
.and_then(|model| memory_part(model, index, offset))
else {
return false;
};
let zeros = [0; MEMORY_SEGMENT as usize];
let mut tlv = [0; AaTlv::HEADER_LEN + MEMORY_SEGMENT as usize];
let read = AaTlv {
mode: AaMode::READ,
length,
address,
data: &zeros[..usize::from(length)],
};
read.encode(&mut tlv).and_then(|_| {
AddressAccessPdu {
header: AecpHeader {
message_type: AecpMessageType::ADDRESS_ACCESS_COMMAND,
status: 0,
target_entity_id: addressing.target,
controller_entity_id: addressing.controller,
sequence_id,
},
tlv_count: 1,
tlvs: &tlv[..AaTlv::HEADER_LEN + usize::from(length)],
}
.encode(&mut out)
})
}
Request::GetRxState { input } => acmp(
AcmpMessageType::GET_RX_STATE_COMMAND,
(EntityId(0), 0),
input,
&mut out,
),
Request::Bind {
talker,
talker_unique_id,
input,
class_b,
..
} => {
let mut connect = Acmpdu::command(
AcmpMessageType::CONNECT_RX_COMMAND,
addressing.controller,
(talker, talker_unique_id),
(addressing.target, input),
sequence_id,
);
if class_b {
connect.flags |= AcmpFlags::CLASS_B;
}
connect.encode(&mut out)
}
Request::Unbind {
talker,
talker_unique_id,
input,
..
} => acmp(
AcmpMessageType::DISCONNECT_RX_COMMAND,
(talker, talker_unique_id),
input,
&mut out,
),
};
match length {
Ok(length) => {
self.outgoing
.push_back((destination, out[..length].to_vec()));
true
}
Err(_) => false,
}
}
fn timeout(&self, entity_id: EntityId, request: Request) -> Duration {
let Some(message_type) = request.acmp_message() else {
return COMMAND_TIMEOUT;
};
let milan = self
.models
.get(&entity_id)
.is_some_and(|model| model.milan.is_some());
let millis = if milan {
message_type.milan_timeout_ms()
} else {
message_type.timeout_ms()
};
Duration::from_millis(u64::from(millis.unwrap_or(250)))
}
fn next_command(&mut self) -> CommandId {
self.next_command = self.next_command.wrapping_add(1);
CommandId(self.next_command)
}
fn queue_command(
&mut self,
now: Instant,
entity_id: EntityId,
command: CommandId,
request: Request,
) {
if !self.entities.contains_key(&entity_id) {
self.events
.push_back(Event::CommandFinished(command, Outcome::NotPossible));
return;
}
let queue = &mut self.sessions.entry(entity_id).or_default().queue;
let place = queue
.iter()
.position(|queued| queued.command().is_none())
.unwrap_or(queue.len());
queue.insert(place, request);
self.pump(now);
}
pub fn set_name(
&mut self,
now: Instant,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
name_index: u16,
name: &str,
) -> CommandId {
let command = self.next_command();
let Some(name) = aem::aem_name(name) else {
self.events
.push_back(Event::CommandFinished(command, Outcome::NotPossible));
return command;
};
let set = SetName {
descriptor_type,
index,
name_index,
configuration: 0,
name,
};
self.queue_command(now, entity_id, command, Request::SetName { set, command });
command
}
pub fn set_stream_format(
&mut self,
now: Instant,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
format: StreamFormat,
) -> CommandId {
let command = self.next_command();
let set = SetStreamFormat {
descriptor_type,
index,
format,
};
let request = Request::SetStreamFormat { set, command };
self.queue_command(now, entity_id, command, request);
command
}
pub fn start_streaming(
&mut self,
now: Instant,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
) -> CommandId {
self.streaming(now, entity_id, descriptor_type, index, true)
}
pub fn stop_streaming(
&mut self,
now: Instant,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
) -> CommandId {
self.streaming(now, entity_id, descriptor_type, index, false)
}
fn streaming(
&mut self,
now: Instant,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
start: bool,
) -> CommandId {
let command = self.next_command();
let request = Request::Streaming {
descriptor_type,
index,
start,
command,
};
self.queue_command(now, entity_id, command, request);
command
}
pub fn set_sampling_rate(
&mut self,
now: Instant,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
rate: SamplingRate,
) -> CommandId {
let command = self.next_command();
let set = SetSamplingRate {
descriptor_type,
index,
rate,
};
let request = Request::SetSamplingRate { set, command };
self.queue_command(now, entity_id, command, request);
command
}
pub fn set_lite_config(
&mut self,
now: Instant,
entity_id: EntityId,
interface: u16,
escalation_allowed: bool,
) -> CommandId {
let command = self.next_command();
let flags = if escalation_allowed {
lite::LiteConfigFlags::ESCALATION_ALLOWED.0
} else {
0
};
let request = Request::SetLiteConfig {
interface,
flags,
command,
};
self.queue_command(now, entity_id, command, request);
command
}
pub fn set_wireless_config(
&mut self,
now: Instant,
entity_id: EntityId,
interface: u16,
class_a_allowed: bool,
) -> CommandId {
let command = self.next_command();
let flags = if class_a_allowed {
wireless::WirelessConfigFlags::CLASS_A_ALLOWED.0
} else {
0
};
let request = Request::SetWirelessConfig {
interface,
flags,
command,
};
self.queue_command(now, entity_id, command, request);
command
}
pub fn set_clock_source(
&mut self,
now: Instant,
entity_id: EntityId,
domain: u16,
source: u16,
) -> CommandId {
let command = self.next_command();
let request = Request::SetClockSource {
set: SetClockSource { domain, source },
command,
};
self.queue_command(now, entity_id, command, request);
command
}
pub fn set_configuration(
&mut self,
now: Instant,
entity_id: EntityId,
configuration: u16,
) -> CommandId {
let command = self.next_command();
let request = Request::SetConfiguration {
configuration,
command,
};
self.queue_command(now, entity_id, command, request);
command
}
pub fn set_control(
&mut self,
now: Instant,
entity_id: EntityId,
index: u16,
values: &[u8],
) -> CommandId {
let command = self.next_command();
if values.is_empty() || values.len() > aem::MAX_CONTROL_VALUES {
self.events
.push_back(Event::CommandFinished(command, Outcome::NotPossible));
return command;
}
self.control_values.insert(command, values.to_vec());
self.queue_command(
now,
entity_id,
command,
Request::SetControl { index, command },
);
if !self.entities.contains_key(&entity_id) {
self.control_values.remove(&command);
}
command
}
pub fn refresh_descriptor(
&mut self,
now: Instant,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
) {
if self.read(entity_id, descriptor_type, index) {
self.queue_read(entity_id, descriptor_type, index, true);
self.pump(now);
}
}
pub fn refresh_stream(
&mut self,
now: Instant,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
) {
if !self.read(entity_id, descriptor_type, index) {
return;
}
self.queue_query(
entity_id,
Request::GetStreamInfo {
descriptor_type,
index,
},
);
if self.config.read_counters {
self.queue_query(
entity_id,
Request::GetCounters {
descriptor_type,
index,
},
);
}
self.pump(now);
}
fn read(&self, entity_id: EntityId, descriptor_type: DescriptorType, index: u16) -> bool {
self.models.get(&entity_id).is_some_and(|model| {
model.state == EnumerationState::Complete && model.has(descriptor_type, index)
})
}
pub fn tx_state(&mut self, now: Instant, talker: (EntityId, u16)) -> CommandId {
let command = self.next_command();
let request = Request::GetTxState {
output: talker.1,
command: Some(command),
};
self.queue_command(now, talker.0, command, request);
command
}
pub fn tx_connection(
&mut self,
now: Instant,
talker: (EntityId, u16),
index: u16,
) -> CommandId {
let command = self.next_command();
let request = Request::GetTxConnection {
output: talker.1,
index,
command: Some(command),
};
self.queue_command(now, talker.0, command, request);
command
}
pub fn disconnect_talker(
&mut self,
now: Instant,
talker: (EntityId, u16),
listener: (EntityId, u16),
) -> CommandId {
let command = self.next_command();
let request = Request::DisconnectTx {
output: talker.1,
listener: listener.0,
listener_unique_id: listener.1,
command,
};
self.queue_command(now, talker.0, command, request);
command
}
pub fn max_transit_time(
&mut self,
now: Instant,
entity_id: EntityId,
output: u16,
) -> CommandId {
let command = self.next_command();
let request = Request::GetMaxTransitTime {
output,
command: Some(command),
};
self.queue_command(now, entity_id, command, request);
command
}
pub fn set_max_transit_time(
&mut self,
now: Instant,
entity_id: EntityId,
output: u16,
nanoseconds: u64,
) -> CommandId {
let command = self.next_command();
let request = Request::SetMaxTransitTime {
set: MaxTransitTime {
output,
nanoseconds,
},
command,
};
self.queue_command(now, entity_id, command, request);
command
}
pub fn read_descriptor(
&mut self,
now: Instant,
entity_id: EntityId,
descriptor_type: DescriptorType,
index: u16,
) -> CommandId {
let command = self.next_command();
let request = Request::ReadForCaller {
descriptor_type,
index,
command,
};
self.queue_command(now, entity_id, command, request);
command
}
fn store_max_transit_time(&mut self, entity_id: EntityId, output: u16, payload: &[u8]) {
if let Ok(time) = MaxTransitTime::decode(payload)
&& time.output == output
&& let Some(model) = self.models.get_mut(&entity_id)
&& model.has(DescriptorType::STREAM_OUTPUT, output)
&& model.set_max_transit_time(output, time.nanoseconds)
&& model.state == EnumerationState::Complete
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn read_other_transit_times(&mut self, entity_id: EntityId, answered: u16) {
let Some(model) = self.models.get(&entity_id) else {
return;
};
if model.milan.is_some() {
return;
}
let mut outputs = model
.descriptors(DescriptorType::STREAM_OUTPUT)
.map(|(output, _)| output);
if outputs.next() != Some(answered) {
return;
}
let others: Vec<u16> = outputs
.filter(|&output| model.max_transit_time(output).is_none())
.collect();
let queue = &mut self.sessions.entry(entity_id).or_default().queue;
for output in others {
queue.push_back(Request::GetMaxTransitTime {
output,
command: None,
});
}
}
fn drop_command_data(&mut self, command: CommandId) {
self.mapping_changes.remove(&command);
self.control_values.remove(&command);
}
fn store_control(&mut self, entity_id: EntityId, index: u16, values: &[u8]) {
if let Some(model) = self.models.get_mut(&entity_id)
&& model.apply_control(index, values)
&& model.state == EnumerationState::Complete
{
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
pub fn add_audio_mappings(
&mut self,
now: Instant,
entity_id: EntityId,
port: (DescriptorType, u16),
mappings: &[AudioMapping],
) -> CommandId {
self.change_mappings(now, entity_id, MappingChange::Add, port, mappings)
}
pub fn remove_audio_mappings(
&mut self,
now: Instant,
entity_id: EntityId,
port: (DescriptorType, u16),
mappings: &[AudioMapping],
) -> CommandId {
self.change_mappings(now, entity_id, MappingChange::Remove, port, mappings)
}
fn change_mappings(
&mut self,
now: Instant,
entity_id: EntityId,
change: MappingChange,
(descriptor_type, index): (DescriptorType, u16),
mappings: &[AudioMapping],
) -> CommandId {
let command = self.next_command();
if mappings.is_empty() || mappings.len() > aem::MAX_MAPPINGS_PER_CHANGE {
self.events
.push_back(Event::CommandFinished(command, Outcome::NotPossible));
return command;
}
self.mapping_changes.insert(command, mappings.to_vec());
let request = Request::ChangeMappings {
change,
descriptor_type,
index,
command,
};
self.queue_command(now, entity_id, command, request);
command
}
pub fn connect(
&mut self,
now: Instant,
talker: (EntityId, u16),
listener: (EntityId, u16),
) -> CommandId {
let command = self.next_command();
let class_b = self
.models
.get(&talker.0)
.and_then(|model| model.stream_info(DescriptorType::STREAM_OUTPUT, talker.1))
.is_some_and(|info| info.flags.contains(StreamInfoFlags::CLASS_B));
let request = Request::Bind {
talker: talker.0,
talker_unique_id: talker.1,
input: listener.1,
class_b,
command,
};
self.queue_command(now, listener.0, command, request);
command
}
pub fn disconnect(&mut self, now: Instant, listener: (EntityId, u16)) -> CommandId {
let command = self.next_command();
let talker = self
.models
.get(&listener.0)
.and_then(|model| model.binding(listener.1))
.map_or((EntityId(0), 0), |binding| {
(binding.talker, binding.talker_unique_id)
});
let request = Request::Unbind {
talker: talker.0,
talker_unique_id: talker.1,
input: listener.1,
command,
};
self.queue_command(now, listener.0, command, request);
command
}
pub fn identify(&mut self, now: Instant, entity_id: EntityId, duration: Duration) -> CommandId {
let command = self.next_command();
let control = self.entities.get(&entity_id).and_then(|entity| {
entity
.adp
.entity_capabilities
.contains(EntityCapabilities::AEM_IDENTIFY_CONTROL_INDEX_VALID)
.then_some(entity.adp.identify_control_index)
});
let Some(control) = control else {
self.events
.push_back(Event::CommandFinished(command, Outcome::NotPossible));
return command;
};
self.identify_off
.insert(entity_id, (now + duration, control));
let request = Request::Identify {
control,
on: true,
command: Some(command),
};
self.queue_command(now, entity_id, command, request);
command
}
pub fn handle_timeout(&mut self, now: Instant) {
self.start_advertising(now);
let mut expired = Vec::new();
self.entities.retain(|&entity_id, entity| {
let keep = entity.expires > now;
if !keep {
expired.push(entity_id);
}
keep
});
for entity_id in expired {
self.forget(entity_id);
self.events
.push_back(Event::EntityOffline(entity_id, OfflineReason::TimedOut));
}
let late: Vec<((Channel, u16), Inflight)> = self
.inflight
.iter()
.filter(|(_, inflight)| inflight.deadline <= now)
.map(|(&key, &inflight)| (key, inflight))
.collect();
for (key, inflight) in late {
if !inflight.retried {
let retry = Inflight {
deadline: now + self.timeout(inflight.entity_id, inflight.request),
retried: true,
..inflight
};
self.inflight.insert(key, retry);
self.send(key, retry);
continue;
}
self.complete(key, inflight);
if let Request::ReadDescriptor {
descriptor_type,
refresh,
..
} = inflight.request
{
self.read_failed(
inflight.entity_id,
descriptor_type,
refresh,
EnumerationFailure::NoResponse,
);
}
if let Request::GetLiteStatus { .. } = inflight.request
&& let Some(model) = self.models.get_mut(&inflight.entity_id)
&& model.lite_supported.is_none()
{
model.lite_supported = Some(false);
}
if let Request::GetWirelessStatus { .. } = inflight.request
&& let Some(model) = self.models.get_mut(&inflight.entity_id)
&& model.wireless_supported.is_none()
{
model.wireless_misses += 1;
if model.wireless_misses >= WIRELESS_MISSES {
model.wireless_supported = Some(false);
} else if !self.config.wireless_poll.is_zero() {
self.next_wireless_poll
.get_or_insert(now + self.config.wireless_poll);
}
}
if let Request::ReadMemory { index, .. } = inflight.request {
self.memory_reads.remove(&(inflight.entity_id, index));
}
if let Request::GetDynamicInfo { queries, count } = inflight.request {
self.dynamic_info_answered(
inflight.entity_id,
&queries[..usize::from(count)],
None,
);
}
if let Some(command) = inflight.request.command() {
self.drop_command_data(command);
self.events
.push_back(Event::CommandFinished(command, Outcome::NoResponse));
}
self.check_complete(inflight.entity_id);
}
let due: Vec<(EntityId, u16)> = self
.identify_off
.iter()
.filter(|(_, (when, _))| *when <= now)
.map(|(&entity_id, &(_, control))| (entity_id, control))
.collect();
for (entity_id, control) in due {
self.identify_off.remove(&entity_id);
self.queue_query(
entity_id,
Request::Identify {
control,
on: false,
command: None,
},
);
}
self.poll_lite(now);
self.poll_wireless(now);
self.age_cvu_talkers(now);
if let Some(advertiser) = &mut self.advertiser
&& advertiser.next.is_some_and(|next| next <= now)
{
let index = advertiser.available_index;
advertiser.available_index = index.wrapping_add(1);
advertiser.next = Some(now + advertiser.valid() / 4);
let adpdu = self.own_adpdu(AdpMessageType::ENTITY_AVAILABLE, index);
self.queue_adp(&adpdu);
}
self.pump(now);
}
fn poll_lite(&mut self, now: Instant) {
if self.next_lite_poll.is_none_or(|next| next > now) {
return;
}
let asked: Vec<(EntityId, u16)> = self
.models
.iter()
.filter(|(_, model)| model.lite_supported == Some(true))
.flat_map(|(&entity_id, model)| {
model
.descriptors(DescriptorType::AVB_INTERFACE)
.map(move |(interface, _)| (entity_id, interface))
})
.collect();
self.next_lite_poll = (!asked.is_empty()).then(|| now + self.config.lite_poll);
for (entity_id, interface) in asked {
self.queue_query(entity_id, Request::GetLiteStatus { interface });
}
}
fn poll_wireless(&mut self, now: Instant) {
if self.next_wireless_poll.is_none_or(|next| next > now) {
return;
}
let mut asked: Vec<(EntityId, u16)> = self
.models
.iter()
.flat_map(|(&entity_id, model)| {
model
.wireless_interfaces()
.map(move |(interface, _)| (entity_id, interface))
})
.collect();
asked.extend(
self.models
.iter()
.filter(|(_, model)| {
model.wireless_supported.is_none() && model.wireless_misses > 0
})
.flat_map(|(&entity_id, model)| {
model
.descriptors(DescriptorType::AVB_INTERFACE)
.map(move |(interface, _)| (entity_id, interface))
}),
);
self.next_wireless_poll = (!asked.is_empty()).then(|| now + self.config.wireless_poll);
for (entity_id, interface) in asked {
self.queue_query(entity_id, Request::GetWirelessStatus { interface });
}
}
fn age_cvu_talkers(&mut self, now: Instant) {
let Some(before) = now.checked_sub(CVU_LIFETIME) else {
return;
};
let mut aged = Vec::new();
for (&entity_id, model) in &mut self.models {
if model.age_cvu_talkers(before) {
aged.push(entity_id);
}
}
for entity_id in aged {
self.events.push_back(Event::EntityModelChanged(entity_id));
}
}
fn start_advertising(&mut self, now: Instant) {
if let Some(advertiser) = &mut self.advertiser
&& !advertiser.started
{
advertiser.started = true;
advertiser.next = Some(now + self.random.up_to(advertiser.delay_limit()));
}
}
fn own_adpdu(&self, message_type: AdpMessageType, available_index: u32) -> Adpdu {
let advertise = self.advertiser.as_ref().map(|advertiser| advertiser.config);
Adpdu {
message_type,
valid_time: if message_type == AdpMessageType::ENTITY_AVAILABLE {
advertise.map_or(31, |advertise| advertise.valid_time.clamp(1, 31))
} else {
0
},
entity_id: self.config.entity_id,
entity_model_id: advertise
.map_or_else(Default::default, |advertise| advertise.entity_model_id),
controller_capabilities: ControllerCapabilities::IMPLEMENTED,
available_index,
..Adpdu::default()
}
}
fn queue_adp(&mut self, adpdu: &Adpdu) {
if let Ok(bytes) = adpdu.to_bytes() {
self.outgoing
.push_back((crate::ADP_ACMP_MULTICAST, bytes.to_vec()));
}
}
pub fn poll_timeout(&self) -> Option<Instant> {
let expiries = self.entities.values().map(|entity| entity.expires);
let deadlines = self.inflight.values().map(|inflight| inflight.deadline);
let advertise = self
.advertiser
.as_ref()
.and_then(|advertiser| advertiser.next);
let identify = self.identify_off.values().map(|(when, _)| *when);
let lite = self.next_lite_poll;
let wireless = self.next_wireless_poll;
let declarations = self
.models
.values()
.filter_map(EntityModel::oldest_cvu_talker)
.map(|heard| heard + CVU_LIFETIME);
expiries
.chain(deadlines)
.chain(advertise)
.chain(identify)
.chain(lite)
.chain(wireless)
.chain(declarations)
.min()
}
pub fn poll_transmit(&mut self, out: &mut [u8]) -> Result<Option<Transmit>, EncodeError> {
let Some((destination, bytes)) = self.outgoing.front() else {
return Ok(None);
};
let length = bytes.len();
let Some(target) = out.get_mut(..length) else {
return Err(EncodeError::BufferTooSmall {
needed: length,
available: out.len(),
});
};
target.copy_from_slice(bytes);
let destination = *destination;
self.outgoing.pop_front();
Ok(Some(Transmit {
destination,
length,
}))
}
pub fn poll_event(&mut self) -> Option<Event> {
self.events.pop_front()
}
pub fn entity(&self, entity_id: EntityId) -> Option<&DiscoveredEntity> {
self.entities.get(&entity_id)
}
pub fn entities(&self) -> impl Iterator<Item = &DiscoveredEntity> {
self.entities.values()
}
pub fn model(&self, entity_id: EntityId) -> Option<&EntityModel> {
self.models.get(&entity_id)
}
pub fn busy(&self, entity_id: EntityId) -> bool {
self.sessions
.get(&entity_id)
.is_some_and(|session| session.inflight.is_some() || !session.queue.is_empty())
}
pub fn malformed_frames(&self) -> u64 {
self.malformed
}
}
fn to_talker(message: AcmpMessageType) -> bool {
matches!(
message.0 & !1,
0 | 2 | 4 | 12 )
}
fn control_values(payload: &[u8], index: u16) -> Option<&[u8]> {
let (descriptor_type, named) = aem::target_descriptor(payload)?;
(descriptor_type == DescriptorType::CONTROL && named == index)
.then(|| payload.get(4..))
.flatten()
.filter(|values| !values.is_empty())
}
fn overheard(command_type: AemCommandType) -> bool {
matches!(
command_type,
AemCommandType::SET_CONFIGURATION
| AemCommandType::SET_STREAM_FORMAT
| AemCommandType::SET_STREAM_INFO
| AemCommandType::GET_STREAM_INFO
| AemCommandType::SET_NAME
| AemCommandType::SET_SAMPLING_RATE
| AemCommandType::SET_CLOCK_SOURCE
| AemCommandType::SET_CONTROL
| AemCommandType::GET_AVB_INFO
| AemCommandType::GET_AS_PATH
| AemCommandType::GET_COUNTERS
| AemCommandType::ADD_AUDIO_MAPPINGS
| AemCommandType::REMOVE_AUDIO_MAPPINGS
| AemCommandType::SET_MAX_TRANSIT_TIME
)
}
fn is_logo(object: &MemoryObjectDescriptor<'_>) -> bool {
matches!(
object.memory_object_type,
MemoryObjectType::PNG_ENTITY | MemoryObjectType::PNG_MANUFACTURER
) && (1..=MAX_LOGO).contains(&object.length)
}
fn memory_part(model: &EntityModel, index: u16, offset: u32) -> Option<(u64, u16)> {
let object = model
.memory_objects()
.find(|object| object.index == index)
.filter(is_logo)?;
let left = object.length.checked_sub(u64::from(offset))?;
let segment = object
.maximum_segment_length
.filter(|&segment| segment > 0)
.map_or(MEMORY_SEGMENT, |segment| segment.min(MEMORY_SEGMENT));
let length = u16::try_from(left.min(segment))
.ok()
.filter(|&length| length > 0)?;
Some((object.start_address.checked_add(u64::from(offset))?, length))
}
fn command_type_of(request: Request) -> AemCommandType {
match request {
Request::ReadDescriptor { .. } => AemCommandType::READ_DESCRIPTOR,
Request::RegisterUnsolicited => AemCommandType::REGISTER_UNSOLICITED_NOTIFICATION,
Request::GetStreamInfo { .. } => AemCommandType::GET_STREAM_INFO,
Request::GetAvbInfo { .. } => AemCommandType::GET_AVB_INFO,
Request::GetAsPath { .. } => AemCommandType::GET_AS_PATH,
Request::GetCounters { .. } => AemCommandType::GET_COUNTERS,
Request::Identify { .. } => AemCommandType::SET_CONTROL,
Request::SetName { .. } => AemCommandType::SET_NAME,
Request::SetStreamFormat { .. } => AemCommandType::SET_STREAM_FORMAT,
Request::Streaming { start: true, .. } => AemCommandType::START_STREAMING,
Request::Streaming { start: false, .. } => AemCommandType::STOP_STREAMING,
Request::SetSamplingRate { .. } => AemCommandType::SET_SAMPLING_RATE,
Request::SetClockSource { .. } => AemCommandType::SET_CLOCK_SOURCE,
Request::SetConfiguration { .. } => AemCommandType::SET_CONFIGURATION,
Request::SetControl { .. } => AemCommandType::SET_CONTROL,
Request::GetMaxTransitTime { .. } => AemCommandType::GET_MAX_TRANSIT_TIME,
Request::SetMaxTransitTime { .. } => AemCommandType::SET_MAX_TRANSIT_TIME,
Request::ReadForCaller { .. } | Request::ReadOther { .. } => {
AemCommandType::READ_DESCRIPTOR
}
Request::GetDynamicInfo { .. } => AemCommandType::GET_DYNAMIC_INFO,
Request::GetAudioMap { .. } => AemCommandType::GET_AUDIO_MAP,
Request::ChangeMappings { change, .. } => change.command_type(),
Request::GetMilanInfo
| Request::GetMediaClockReference { .. }
| Request::GetLiteStatus { .. }
| Request::SetLiteConfig { .. }
| Request::GetWirelessStatus { .. }
| Request::SetWirelessConfig { .. }
| Request::GetRxState { .. }
| Request::Bind { .. }
| Request::Unbind { .. }
| Request::GetTxState { .. }
| Request::GetTxConnection { .. }
| Request::DisconnectTx { .. }
| Request::ReadMemory { .. } => AemCommandType(0xffff),
}
}
fn dynamic_queries(descriptor_type: DescriptorType, index: u16) -> Vec<DynamicQuery> {
let mut queries = Vec::new();
if descriptor_type.has_object_name() {
queries.push(DynamicQuery::Name {
descriptor_type,
index,
name_index: 0,
});
}
match descriptor_type {
DescriptorType::STREAM_INPUT | DescriptorType::STREAM_OUTPUT => {
queries.push(DynamicQuery::StreamFormat {
descriptor_type,
index,
});
}
DescriptorType::AUDIO_UNIT => queries.push(DynamicQuery::SamplingRate {
descriptor_type,
index,
}),
DescriptorType::CLOCK_DOMAIN => queries.push(DynamicQuery::ClockSource { domain: index }),
_ => {}
}
queries
}
fn audio_map_reads(model: &EntityModel) -> Vec<Request> {
[true, false]
.into_iter()
.flat_map(|input| model.stream_ports(input))
.filter(|port| port.has_dynamic_mappings())
.map(|port| Request::GetAudioMap {
descriptor_type: port.descriptor_type,
index: port.index,
map_index: 0,
})
.collect()
}
fn aem_outcome(aem: &AemPdu<'_>) -> Outcome {
if aem.status().is_success() {
Outcome::Done
} else {
Outcome::Refused(Refusal::Aem(aem.status()))
}
}
fn matching<'a>(
response: Result<ReadDescriptorResponse<'a>, DecodeError>,
descriptor_type: DescriptorType,
index: u16,
) -> Option<ReadDescriptorResponse<'a>> {
response
.ok()
.filter(|response| response.descriptor_type == descriptor_type && response.index == index)
}
fn same_advertisement(left: &Adpdu, right: &Adpdu) -> bool {
let normalized = |adpdu: &Adpdu| Adpdu {
available_index: 0,
valid_time: 0,
..*adpdu
};
normalized(left) == normalized(right)
}
#[cfg(test)]
mod tests;