use alloc::string::String;
use alloc::vec::Vec;
use avb_net::MacAddress;
use crate::aecp::{AaStatus, AaTlv, AddressAccessPdu};
use crate::aem::NAME_LENGTH;
use crate::descriptor::{
ClockSourceType, DescriptorType, InterfaceFlags, MemoryObjectType, StreamFlags,
};
use crate::id::{ClockIdentity, EntityId, EntityModelId};
use crate::stream_format::StreamFormat;
const NO_STRING: u16 = 0xffff;
const MBLA: u8 = 0x40;
pub const IDENTIFY_CONTROL_TYPE: u64 = 0x90e0_f000_0000_0001;
const LINEAR_UINT8: u16 = 0x0001;
const LOCATION_ENTITY: u16 = 0x0000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StreamModel {
pub name: String,
pub formats: Vec<StreamFormat>,
pub current_format: StreamFormat,
pub channels: u16,
}
impl StreamModel {
pub fn class_b(&self) -> bool {
self.current_format.is_class_b()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClockQuality {
pub priority1: u8,
pub clock_class: u8,
pub clock_accuracy: u8,
pub offset_scaled_log_variance: u16,
pub priority2: u8,
}
impl ClockQuality {
pub const NOT_GRANDMASTER_CAPABLE: Self = Self {
priority1: 255,
clock_class: 255,
clock_accuracy: 0xfe,
offset_scaled_log_variance: 0x436a,
priority2: 248,
};
pub const fn grandmaster_capable(priority1: u8) -> Self {
Self {
priority1,
clock_class: 248,
clock_accuracy: 0xfe,
offset_scaled_log_variance: 0x436a,
priority2: 248,
}
}
pub const fn of_priority1(priority1: u8) -> Self {
if priority1 == 255 {
Self::NOT_GRANDMASTER_CAPABLE
} else {
Self::grandmaster_capable(priority1)
}
}
pub const fn is_grandmaster_capable(&self) -> bool {
self.priority1 < 255
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EndpointModel {
pub entity_id: EntityId,
pub entity_model_id: EntityModelId,
pub entity_name: String,
pub group_name: String,
pub vendor_name: String,
pub model_name: String,
pub firmware_version: String,
pub serial_number: String,
pub mac: MacAddress,
pub interface_name: String,
pub clock_identity: ClockIdentity,
pub clock_quality: ClockQuality,
pub sampling_rates: Vec<u32>,
pub current_sampling_rate: u32,
pub outputs: Vec<StreamModel>,
pub inputs: Vec<StreamModel>,
pub clock_source: u16,
pub clock_source_inputs: Vec<u16>,
pub logo: Option<Vec<u8>>,
pub vendor_logo: Option<Vec<u8>>,
}
pub const LOGO_ADDRESS: u64 = 0x1000_0000;
pub const VENDOR_LOGO_ADDRESS: u64 = 0x2000_0000;
struct MemoryObject<'a> {
memory_object_type: MemoryObjectType,
name: &'static str,
address: u64,
data: &'a [u8],
}
pub const MEMORY_SEGMENT: u16 = (AddressAccessPdu::MAX_TLVS_LEN - AaTlv::HEADER_LEN) as u16;
pub(crate) fn name_field(text: &str) -> [u8; NAME_LENGTH] {
let mut field = [0; NAME_LENGTH];
let mut end = text.len().min(NAME_LENGTH);
while !text.is_char_boundary(end) {
end -= 1;
}
field[..end].copy_from_slice(&text.as_bytes()[..end]);
field
}
struct Writer(Vec<u8>);
impl Writer {
fn new(descriptor_type: DescriptorType, index: u16) -> Self {
let mut bytes = Vec::with_capacity(320);
bytes.extend_from_slice(&descriptor_type.0.to_be_bytes());
bytes.extend_from_slice(&index.to_be_bytes());
Writer(bytes)
}
fn u8(&mut self, value: u8) -> &mut Self {
self.0.push(value);
self
}
fn u16(&mut self, value: u16) -> &mut Self {
self.0.extend_from_slice(&value.to_be_bytes());
self
}
fn u32(&mut self, value: u32) -> &mut Self {
self.0.extend_from_slice(&value.to_be_bytes());
self
}
fn u64(&mut self, value: u64) -> &mut Self {
self.0.extend_from_slice(&value.to_be_bytes());
self
}
fn bytes(&mut self, value: &[u8]) -> &mut Self {
self.0.extend_from_slice(value);
self
}
fn name(&mut self, text: &str) -> &mut Self {
self.bytes(&name_field(text))
}
fn pad_to(&mut self, length: usize) -> &mut Self {
if self.0.len() < length {
self.0.resize(length, 0);
}
self
}
fn done(&mut self) -> Vec<u8> {
core::mem::take(&mut self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Port {
pub(crate) input: bool,
pub(crate) index: u16,
pub(crate) stream: u16,
base_cluster: u16,
pub(crate) channels: u16,
map: Option<u16>,
}
impl EndpointModel {
pub(crate) fn ports(&self) -> Vec<Port> {
let mut ports = Vec::new();
let mut cluster = 0;
let mut map = 0;
for (input, streams) in [(true, &self.inputs), (false, &self.outputs)] {
let audio = streams
.iter()
.enumerate()
.filter(|(_, stream)| !stream.current_format.is_clock() && stream.channels > 0);
for (index, (stream, model)) in audio.enumerate() {
ports.push(Port {
input,
index: index as u16,
stream: stream as u16,
base_cluster: cluster,
channels: model.channels,
map: (!input).then_some(map),
});
cluster += model.channels;
if !input {
map += 1;
}
}
}
ports
}
pub(crate) fn clock_sources(&self) -> u16 {
1 + self.clock_source_inputs.len() as u16
}
pub fn clock_source_input(&self, source: u16) -> Option<u16> {
let at = usize::from(source.checked_sub(1)?);
self.clock_source_inputs.get(at).copied()
}
pub fn descriptor_counts(&self) -> Vec<(DescriptorType, u16)> {
let mut counts = Vec::from([(DescriptorType::AUDIO_UNIT, 1)]);
if !self.inputs.is_empty() {
counts.push((DescriptorType::STREAM_INPUT, self.inputs.len() as u16));
}
if !self.outputs.is_empty() {
counts.push((DescriptorType::STREAM_OUTPUT, self.outputs.len() as u16));
}
counts.extend([
(DescriptorType::AVB_INTERFACE, 1),
(DescriptorType::CLOCK_SOURCE, self.clock_sources()),
(DescriptorType::LOCALE, 1),
(DescriptorType::CONTROL, 1),
(DescriptorType::CLOCK_DOMAIN, 1),
]);
let memory_objects = self.memory_objects().count() as u16;
if memory_objects > 0 {
counts.push((DescriptorType::MEMORY_OBJECT, memory_objects));
}
counts
}
fn memory_objects(&self) -> impl Iterator<Item = MemoryObject<'_>> {
[
(
MemoryObjectType::PNG_ENTITY,
"Logo",
LOGO_ADDRESS,
&self.logo,
),
(
MemoryObjectType::PNG_MANUFACTURER,
"Vendor logo",
VENDOR_LOGO_ADDRESS,
&self.vendor_logo,
),
]
.into_iter()
.filter_map(|(memory_object_type, name, address, data)| {
Some(MemoryObject {
memory_object_type,
name,
address,
data: data.as_deref()?,
})
})
}
pub(crate) fn has_memory(&self) -> bool {
self.memory_objects().next().is_some()
}
pub(crate) fn memory_length(&self, index: u16) -> Option<u64> {
let object = self.memory_objects().nth(usize::from(index))?;
Some(object.data.len() as u64)
}
pub(crate) fn memory(&self, address: u64, length: u16) -> Result<&[u8], AaStatus> {
let object = self
.memory_objects()
.filter(|object| object.address <= address)
.max_by_key(|object| object.address)
.ok_or(AaStatus::ADDRESS_TOO_LOW)?;
let start =
usize::try_from(address - object.address).map_err(|_| AaStatus::ADDRESS_TOO_HIGH)?;
let end = start
.checked_add(usize::from(length))
.filter(|end| *end <= object.data.len())
.ok_or(AaStatus::ADDRESS_TOO_HIGH)?;
Ok(&object.data[start..end])
}
fn strings(&self) -> [&str; 7] {
[&self.vendor_name, &self.model_name, "", "", "", "", ""]
}
pub fn descriptor(
&self,
descriptor_type: DescriptorType,
index: u16,
entity: &EntityState,
) -> Option<Vec<u8>> {
let ports = self.ports();
let mut writer = Writer::new(descriptor_type, index);
let bytes = match descriptor_type {
DescriptorType::ENTITY if index == 0 => writer
.u64(self.entity_id.0)
.u64(self.entity_model_id.0)
.u32(entity.capabilities)
.u16(self.outputs.len() as u16)
.u16(entity.talker_capabilities)
.u16(self.inputs.len() as u16)
.u16(entity.listener_capabilities)
.u32(0)
.u32(entity.available_index)
.u64(0)
.name(&self.entity_name)
.u16(0) .u16(1) .name(&self.firmware_version)
.name(&self.group_name)
.name(&self.serial_number)
.u16(1) .u16(0) .done(),
DescriptorType::CONFIGURATION if index == 0 => {
let counts = self.descriptor_counts();
writer
.name("Configuration")
.u16(NO_STRING)
.u16(counts.len() as u16)
.u16(74);
for (kind, count) in counts {
writer.u16(kind.0).u16(count);
}
writer.done()
}
DescriptorType::AUDIO_UNIT if index == 0 => {
let inputs = ports.iter().filter(|port| port.input).count() as u16;
let outputs = ports.iter().filter(|port| !port.input).count() as u16;
writer
.name("Audio")
.u16(NO_STRING)
.u16(0) .u16(inputs)
.u16(0)
.u16(outputs)
.u16(0)
.pad_to(136)
.u32(self.current_sampling_rate)
.u16(144)
.u16(self.sampling_rates.len() as u16);
for rate in &self.sampling_rates {
writer.u32(*rate);
}
writer.done()
}
DescriptorType::STREAM_INPUT | DescriptorType::STREAM_OUTPUT => {
let input = descriptor_type == DescriptorType::STREAM_INPUT;
let streams = if input { &self.inputs } else { &self.outputs };
let stream = streams.get(usize::from(index))?;
let mut flags = StreamFlags::empty();
if stream.formats.iter().any(|format| !format.is_class_b()) {
flags |= StreamFlags::CLASS_A;
}
if stream.formats.iter().any(|format| format.is_class_b()) {
flags |= StreamFlags::CLASS_B;
}
if input && self.clock_source_inputs.contains(&index) {
flags |= StreamFlags::CLOCK_SYNC_SOURCE;
}
writer
.name(&stream.name)
.u16(NO_STRING)
.u16(0) .u16(flags.0)
.u64(stream.current_format.0)
.u16(138)
.u16(stream.formats.len() as u16)
.pad_to(126) .u16(0) .u32(0) .u16(138 + 8 * stream.formats.len() as u16)
.u16(0) .u16(0); for format in &stream.formats {
writer.u64(format.0);
}
writer.done()
}
DescriptorType::AVB_INTERFACE if index == 0 => {
let quality = self.clock_quality;
let mut flags = InterfaceFlags::GPTP_SUPPORTED | InterfaceFlags::SRP_SUPPORTED;
if quality.is_grandmaster_capable() {
flags |= InterfaceFlags::GPTP_GRANDMASTER_SUPPORTED;
}
writer
.name(&self.interface_name)
.u16(NO_STRING)
.bytes(&self.mac.0)
.u16(flags.0)
.u64(self.clock_identity.0)
.u8(quality.priority1)
.u8(quality.clock_class)
.u16(quality.offset_scaled_log_variance)
.u8(quality.clock_accuracy)
.u8(quality.priority2)
.u8(0) .u8(0xfd) .u8(0) .u8(0) .u16(1) .pad_to(110)
.done()
}
DescriptorType::CLOCK_SOURCE if index < self.clock_sources() => {
if index == 0 {
writer
.name("Internal")
.u16(NO_STRING)
.u16(0)
.u16(ClockSourceType::INTERNAL.0)
.u64(0)
.u16(LOCATION_ENTITY)
.u16(0)
} else {
let input = self.clock_source_input(index)?;
let name = self.inputs.get(usize::from(input))?.name.as_str();
writer
.name(name)
.u16(NO_STRING)
.u16(0)
.u16(ClockSourceType::INPUT_STREAM.0)
.u64(0)
.u16(DescriptorType::STREAM_INPUT.0)
.u16(input)
};
writer.pad_to(94).done()
}
DescriptorType::CLOCK_DOMAIN if index == 0 => {
writer
.name("Clock Domain")
.u16(NO_STRING)
.u16(self.clock_source)
.u16(76)
.u16(self.clock_sources());
for source in 0..self.clock_sources() {
writer.u16(source);
}
writer.pad_to(88).done()
}
DescriptorType::LOCALE if index == 0 => writer
.name("en")
.u16(1) .u16(0) .pad_to(80)
.done(),
DescriptorType::STRINGS if index == 0 => {
for text in self.strings() {
writer.name(text);
}
writer.pad_to(460).done()
}
DescriptorType::STREAM_PORT_INPUT | DescriptorType::STREAM_PORT_OUTPUT => {
let input = descriptor_type == DescriptorType::STREAM_PORT_INPUT;
let port = ports
.iter()
.find(|port| port.input == input && port.index == index)?;
writer
.u16(0) .u16(0) .u16(0) .u16(0) .u16(port.channels)
.u16(port.base_cluster)
.u16(u16::from(port.map.is_some())) .u16(port.map.unwrap_or(0))
.pad_to(28)
.done()
}
DescriptorType::AUDIO_CLUSTER => {
let port = ports.iter().find(|port| {
(port.base_cluster..port.base_cluster + port.channels).contains(&index)
})?;
let channel = index - port.base_cluster + 1;
let mut name = String::from("Channel ");
push_number(&mut name, channel);
writer
.name(&name)
.u16(NO_STRING)
.u16(0xffff) .u16(0) .u16(0) .u32(0) .u32(0) .u16(1) .u8(MBLA)
.pad_to(100)
.done()
}
DescriptorType::AUDIO_MAP => {
let port = ports.iter().find(|port| port.map == Some(index))?;
writer.u16(8).u16(port.channels);
for channel in 0..port.channels {
writer.u16(port.stream).u16(channel).u16(channel).u16(0);
}
writer.pad_to(24).done()
}
DescriptorType::CONTROL if index == 0 => writer
.name("Identify")
.u16(NO_STRING)
.u32(0) .u32(0) .u16(0) .u16(LINEAR_UINT8)
.u64(IDENTIFY_CONTROL_TYPE)
.u32(0) .u16(104) .u16(1) .u16(DescriptorType::ENTITY.0) .u16(0) .u16(0) .u8(0) .u8(255) .u8(255) .u8(0) .u8(if entity.identifying { 255 } else { 0 })
.u16(0) .u16(NO_STRING)
.pad_to(212)
.done(),
DescriptorType::MEMORY_OBJECT => {
let object = self.memory_objects().nth(usize::from(index))?;
let length = object.data.len() as u64;
writer
.name(object.name)
.u16(NO_STRING)
.u16(object.memory_object_type.0)
.u16(DescriptorType::ENTITY.0) .u16(0) .u64(object.address) .u64(length) .u64(length)
.u64(u64::from(MEMORY_SEGMENT)) .done()
}
_ => return None,
};
Some(bytes)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct EntityState {
pub capabilities: u32,
pub talker_capabilities: u16,
pub listener_capabilities: u16,
pub available_index: u32,
pub identifying: bool,
}
fn push_number(text: &mut String, number: u16) {
let mut digits = [0u8; 5];
let mut place = digits.len();
let mut rest = number;
loop {
place -= 1;
digits[place] = b'0' + (rest % 10) as u8;
rest /= 10;
if rest == 0 {
break;
}
}
for digit in &digits[place..] {
text.push(char::from(*digit));
}
}