mirror of
https://github.com/nestriness/nestri.git
synced 2026-11-27 17:46:13 +02:00
feat: pyrowave support (#354)
At this point, why not.. Calling it `nespyro` since it's slightly modified, uses slang shader language instead, along other things.. --------- Co-authored-by: DatCaptainHorse <DatCaptainHorse@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
DatCaptainHorse
Claude Opus 5.5
parent
ca7115dba8
commit
cf46bf4d12
@@ -39,3 +39,6 @@ libc = "0.2"
|
||||
|
||||
# Shared IPC protocol
|
||||
nesprotocol = { path = "../../crates/nesprotocol" }
|
||||
|
||||
# PyroWave, the LAN codec, on the same device as pixelforge.
|
||||
nespyro = { path = "../../crates/nespyro" }
|
||||
|
||||
+1235
-303
File diff suppressed because it is too large
Load Diff
@@ -41,10 +41,9 @@ pub unsafe extern "system" fn vkCreateInstance(
|
||||
let next_create: PFN_vkCreateInstance =
|
||||
unsafe { load_instance_fn(next_gipa, vk::Instance::null(), b"vkCreateInstance\0") };
|
||||
|
||||
// The encoder needs Vulkan 1.1 on the game's instance to run on the game's
|
||||
// device. An application asking for 1.0 is raised to 1.1 where the loader
|
||||
// has it: 1.1 only adds to 1.0, so nothing the application can do behaves
|
||||
// any differently, and without it the encoder needs a device of its own.
|
||||
// The encoders run on the game's device, so the game's instance has to be
|
||||
// new enough for them: 1.1 for pixelforge, 1.3 for nespyro. See
|
||||
// `raised_version`.
|
||||
let asked = unsafe {
|
||||
let app = (*p_create_info).p_application_info;
|
||||
if app.is_null() {
|
||||
@@ -57,7 +56,7 @@ pub unsafe extern "system" fn vkCreateInstance(
|
||||
let mut raised_ci;
|
||||
let mut create_info = p_create_info;
|
||||
let mut api_version = asked;
|
||||
if asked < vk::API_VERSION_1_1 && unsafe { loader_version(next_gipa) } >= vk::API_VERSION_1_1 {
|
||||
if let Some(raised) = raised_version(asked, unsafe { loader_version(next_gipa) }) {
|
||||
raised_app = unsafe {
|
||||
let app = (*p_create_info).p_application_info;
|
||||
if app.is_null() {
|
||||
@@ -66,13 +65,17 @@ pub unsafe extern "system" fn vkCreateInstance(
|
||||
*app
|
||||
}
|
||||
};
|
||||
raised_app.api_version = vk::API_VERSION_1_1;
|
||||
raised_app.api_version = raised;
|
||||
raised_ci = unsafe { *p_create_info };
|
||||
raised_ci.p_application_info = &raised_app;
|
||||
create_info = &raised_ci;
|
||||
api_version = vk::API_VERSION_1_1;
|
||||
api_version = raised;
|
||||
log::info!(
|
||||
"instance asked for Vulkan 1.0; created as 1.1 so the encoder can share its devices"
|
||||
"instance asked for Vulkan {}.{}; created as {}.{} so the encoders can share its devices",
|
||||
vk::api_version_major(asked),
|
||||
vk::api_version_minor(asked),
|
||||
vk::api_version_major(raised),
|
||||
vk::api_version_minor(raised),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -115,6 +118,27 @@ pub unsafe extern "system" fn vkCreateInstance(
|
||||
vk::Result::SUCCESS
|
||||
}
|
||||
|
||||
/// The version to create the game's instance at instead of the one it asked
|
||||
/// for, or `None` to leave it alone.
|
||||
///
|
||||
/// As high as 1.3, which nespyro needs, and as the loader allows. A newer
|
||||
/// version only adds to an older one: a game cannot depend on behaviour it
|
||||
/// never asked for, and the only side of a session that has to care about old
|
||||
/// Vulkan is the client, which this layer is not. A loader below 1.1 is left
|
||||
/// alone, since then neither encoder can share the device anyway. The patch is
|
||||
/// dropped, as the version names a major.minor and its patch level is the
|
||||
/// loader's business.
|
||||
fn raised_version(asked: u32, loader: u32) -> Option<u32> {
|
||||
let target = vk::API_VERSION_1_3.min(loader);
|
||||
let target = vk::make_api_version(
|
||||
0,
|
||||
vk::api_version_major(target),
|
||||
vk::api_version_minor(target),
|
||||
0,
|
||||
);
|
||||
(target >= vk::API_VERSION_1_1 && asked < target).then_some(target)
|
||||
}
|
||||
|
||||
/// The highest instance version the loader below supports; 1.0 when it cannot
|
||||
/// say, since vkEnumerateInstanceVersion is itself a 1.1 addition.
|
||||
unsafe fn loader_version(next_gipa: crate::dispatch::PFN_vkGetInstanceProcAddr) -> u32 {
|
||||
@@ -145,3 +169,44 @@ pub unsafe extern "system" fn vkDestroyInstance(
|
||||
unsafe { (state.destroy_instance)(instance, p_allocator) };
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::raised_version;
|
||||
use ash::vk;
|
||||
|
||||
const LOADER_1_4: u32 = vk::make_api_version(0, 1, 4, 321);
|
||||
|
||||
#[test]
|
||||
fn an_old_instance_is_raised_to_1_3() {
|
||||
for asked in [
|
||||
0,
|
||||
vk::API_VERSION_1_0,
|
||||
vk::API_VERSION_1_1,
|
||||
vk::API_VERSION_1_2,
|
||||
] {
|
||||
assert_eq!(raised_version(asked, LOADER_1_4), Some(vk::API_VERSION_1_3));
|
||||
}
|
||||
}
|
||||
|
||||
/// Raising is only ever upward: a game asking for more keeps it.
|
||||
#[test]
|
||||
fn a_new_enough_instance_is_left_alone() {
|
||||
assert_eq!(raised_version(vk::API_VERSION_1_3, LOADER_1_4), None);
|
||||
assert_eq!(raised_version(LOADER_1_4, LOADER_1_4), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_older_loader_gets_what_it_has() {
|
||||
let loader = vk::make_api_version(0, 1, 2, 198);
|
||||
assert_eq!(
|
||||
raised_version(vk::API_VERSION_1_0, loader),
|
||||
Some(vk::API_VERSION_1_2)
|
||||
);
|
||||
assert_eq!(raised_version(vk::API_VERSION_1_2, loader), None);
|
||||
assert_eq!(
|
||||
raised_version(vk::API_VERSION_1_0, vk::API_VERSION_1_0),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -326,14 +326,24 @@ fn encoder_ready(ds: &crate::state::DeviceState, ds_key: usize, width: u32, heig
|
||||
// On the game's own device where it was created for that, and
|
||||
// on a device of the encoder's own where it was not, or where
|
||||
// adopting it fails.
|
||||
let shared = ds.shared.as_ref().and_then(|s| match s.video_context() {
|
||||
Ok(ctx) => Some(ctx),
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"could not encode on the game's device ({e}); using a device of its own"
|
||||
);
|
||||
None
|
||||
// Each encoder the device was set up for is adopted on its own; a
|
||||
// failure in one costs only that one. Only when neither is left
|
||||
// does the encoder move to a device of its own, which can then
|
||||
// host Vulkan Video and nothing else.
|
||||
let shared = ds.shared.as_ref().and_then(|s| {
|
||||
let video = s.video_context().and_then(|r| {
|
||||
r.map_err(|e| log::warn!("Vulkan Video on the game's device failed ({e})"))
|
||||
.ok()
|
||||
});
|
||||
let pyro = s.pyro_context().and_then(|r| {
|
||||
r.map_err(|e| log::warn!("PyroWave on the game's device failed ({e})"))
|
||||
.ok()
|
||||
});
|
||||
if video.is_none() && pyro.is_none() {
|
||||
log::warn!("no encoder on the game's device; using a device of its own");
|
||||
return None;
|
||||
}
|
||||
Some(crate::encode::SharedEncoders { video, pyro })
|
||||
});
|
||||
let on_shared = shared.is_some();
|
||||
match PipelineHandle::new(cfg, shared) {
|
||||
|
||||
+621
-81
@@ -6,6 +6,10 @@
|
||||
// because two devices share no timeline. Here the game's device is created
|
||||
// with what the encoder needs, and the encoder is handed that device instead.
|
||||
//
|
||||
// Two encoders can live there: pixelforge's Vulkan Video encoder and
|
||||
// nespyro's PyroWave. Each is checked on its own, and the device gets the
|
||||
// additions of whichever it can host — one, both, or, if neither, none.
|
||||
//
|
||||
// Three things are added to the game's vkCreateDevice, and none of them
|
||||
// changes what the game gets:
|
||||
//
|
||||
@@ -33,9 +37,13 @@ use std::collections::BTreeMap;
|
||||
/// the device's queue create infos.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct QueuePlan {
|
||||
pub encode: DeviceQueue,
|
||||
/// Vulkan Video encode, when pixelforge is hosted.
|
||||
pub encode: Option<DeviceQueue>,
|
||||
/// pixelforge's converter and all of nespyro. Both encoders submit from the
|
||||
/// one encoder thread, so they share it freely.
|
||||
pub compute: DeviceQueue,
|
||||
pub transfer: DeviceQueue,
|
||||
/// pixelforge's copies, when pixelforge is hosted.
|
||||
pub transfer: Option<DeviceQueue>,
|
||||
/// How many queues to create in each family, where that is more than the
|
||||
/// game asked for.
|
||||
pub counts: BTreeMap<u32, u32>,
|
||||
@@ -71,7 +79,32 @@ fn rank(flags: vk::QueueFlags) -> u32 {
|
||||
r
|
||||
}
|
||||
|
||||
/// Pick a queue for every role.
|
||||
/// Which roles a plan has to fill.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Wants {
|
||||
/// An encode queue, and the family the encoder would like it from.
|
||||
pub encode: Option<Option<u32>>,
|
||||
/// A transfer queue.
|
||||
pub transfer: bool,
|
||||
}
|
||||
|
||||
impl Wants {
|
||||
/// What pixelforge needs: encode, compute and transfer.
|
||||
pub fn video(preferred_encode: Option<u32>) -> Self {
|
||||
Self {
|
||||
encode: Some(preferred_encode),
|
||||
transfer: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// What nespyro alone needs: compute, which every plan has.
|
||||
pub const PYRO_ONLY: Self = Self {
|
||||
encode: None,
|
||||
transfer: false,
|
||||
};
|
||||
}
|
||||
|
||||
/// Pick a queue for every role `wants` names, and a compute queue always.
|
||||
///
|
||||
/// `families` is the device's queue families, `game` how many queues the game
|
||||
/// asked for in each (and with which flags). The encoder takes at most one
|
||||
@@ -83,7 +116,7 @@ fn rank(flags: vk::QueueFlags) -> u32 {
|
||||
pub fn plan_queues(
|
||||
families: &[vk::QueueFamilyProperties],
|
||||
game: &BTreeMap<u32, (u32, vk::DeviceQueueCreateFlags)>,
|
||||
preferred_encode: Option<u32>,
|
||||
wants: Wants,
|
||||
internally_synchronized_queues: bool,
|
||||
) -> Option<QueuePlan> {
|
||||
let mut counts: BTreeMap<u32, u32> = BTreeMap::new();
|
||||
@@ -146,13 +179,16 @@ pub fn plan_queues(
|
||||
None
|
||||
};
|
||||
|
||||
let encode = pick(
|
||||
vk::QueueFlags::VIDEO_ENCODE_KHR,
|
||||
preferred_encode,
|
||||
&mut counts,
|
||||
&mut ours,
|
||||
&mut shared,
|
||||
)?;
|
||||
let encode = match wants.encode {
|
||||
Some(preferred) => Some(pick(
|
||||
vk::QueueFlags::VIDEO_ENCODE_KHR,
|
||||
preferred,
|
||||
&mut counts,
|
||||
&mut ours,
|
||||
&mut shared,
|
||||
)?),
|
||||
None => None,
|
||||
};
|
||||
let compute = pick(
|
||||
vk::QueueFlags::COMPUTE,
|
||||
None,
|
||||
@@ -160,13 +196,17 @@ pub fn plan_queues(
|
||||
&mut ours,
|
||||
&mut shared,
|
||||
)?;
|
||||
let transfer = pick(
|
||||
vk::QueueFlags::TRANSFER,
|
||||
Some(compute.family),
|
||||
&mut counts,
|
||||
&mut ours,
|
||||
&mut shared,
|
||||
)?;
|
||||
let transfer = if wants.transfer {
|
||||
Some(pick(
|
||||
vk::QueueFlags::TRANSFER,
|
||||
Some(compute.family),
|
||||
&mut counts,
|
||||
&mut ours,
|
||||
&mut shared,
|
||||
)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Some(QueuePlan {
|
||||
encode,
|
||||
@@ -191,6 +231,52 @@ pub enum Feature {
|
||||
VideoEncodeIntraRefresh,
|
||||
VideoEncodeQuantizationMap,
|
||||
InternallySynchronizedQueues,
|
||||
// nespyro's. The first two are Vulkan 1.0 core features, which live in
|
||||
// `VkPhysicalDeviceFeatures` rather than in a struct of their own.
|
||||
ShaderInt16,
|
||||
ShaderStorageImageWriteWithoutFormat,
|
||||
StorageBuffer16BitAccess,
|
||||
StorageBuffer8BitAccess,
|
||||
ShaderInt8,
|
||||
ShaderFloat16,
|
||||
BufferDeviceAddress,
|
||||
SubgroupSizeControl,
|
||||
ComputeFullSubgroups,
|
||||
}
|
||||
|
||||
impl Feature {
|
||||
/// Whether this is a Vulkan 1.0 feature, set in `VkPhysicalDeviceFeatures`
|
||||
/// rather than in a pNext struct of its own.
|
||||
fn is_core(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::ShaderInt16 | Self::ShaderStorageImageWriteWithoutFormat
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// The features nespyro asks for.
|
||||
pub fn pyro_features(f: &nespyro::DeviceFeatures) -> Vec<Feature> {
|
||||
use Feature as F;
|
||||
[
|
||||
(f.shader_int16, F::ShaderInt16),
|
||||
(
|
||||
f.shader_storage_image_write_without_format,
|
||||
F::ShaderStorageImageWriteWithoutFormat,
|
||||
),
|
||||
(f.storage_buffer_16bit_access, F::StorageBuffer16BitAccess),
|
||||
(f.storage_buffer_8bit_access, F::StorageBuffer8BitAccess),
|
||||
(f.shader_int8, F::ShaderInt8),
|
||||
(f.shader_float16, F::ShaderFloat16),
|
||||
(f.timeline_semaphore, F::TimelineSemaphore),
|
||||
(f.buffer_device_address, F::BufferDeviceAddress),
|
||||
(f.synchronization2, F::Synchronization2),
|
||||
(f.subgroup_size_control, F::SubgroupSizeControl),
|
||||
(f.compute_full_subgroups, F::ComputeFullSubgroups),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(on, feature)| on.then_some(feature))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The features `f` asks for, plus the one queue sharing needs.
|
||||
@@ -307,6 +393,79 @@ unsafe fn field(
|
||||
vk::PhysicalDeviceInternallySynchronizedQueuesFeaturesKHR,
|
||||
internally_synchronized_queues
|
||||
),
|
||||
(S::PHYSICAL_DEVICE_FEATURES_2, F::ShaderInt16) => Some(unsafe {
|
||||
&raw mut (*(p as *mut vk::PhysicalDeviceFeatures2))
|
||||
.features
|
||||
.shader_int16
|
||||
}),
|
||||
(S::PHYSICAL_DEVICE_FEATURES_2, F::ShaderStorageImageWriteWithoutFormat) => Some(unsafe {
|
||||
&raw mut (*(p as *mut vk::PhysicalDeviceFeatures2))
|
||||
.features
|
||||
.shader_storage_image_write_without_format
|
||||
}),
|
||||
(S::PHYSICAL_DEVICE_VULKAN_1_1_FEATURES, F::StorageBuffer16BitAccess) => {
|
||||
at!(
|
||||
vk::PhysicalDeviceVulkan11Features,
|
||||
storage_buffer16_bit_access
|
||||
)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES, F::StorageBuffer16BitAccess) => {
|
||||
at!(
|
||||
vk::PhysicalDevice16BitStorageFeatures,
|
||||
storage_buffer16_bit_access
|
||||
)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, F::StorageBuffer8BitAccess) => {
|
||||
at!(
|
||||
vk::PhysicalDeviceVulkan12Features,
|
||||
storage_buffer8_bit_access
|
||||
)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES, F::StorageBuffer8BitAccess) => {
|
||||
at!(
|
||||
vk::PhysicalDevice8BitStorageFeatures,
|
||||
storage_buffer8_bit_access
|
||||
)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, F::ShaderInt8) => {
|
||||
at!(vk::PhysicalDeviceVulkan12Features, shader_int8)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES, F::ShaderInt8) => {
|
||||
at!(vk::PhysicalDeviceShaderFloat16Int8Features, shader_int8)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, F::ShaderFloat16) => {
|
||||
at!(vk::PhysicalDeviceVulkan12Features, shader_float16)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES, F::ShaderFloat16) => {
|
||||
at!(vk::PhysicalDeviceShaderFloat16Int8Features, shader_float16)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, F::BufferDeviceAddress) => {
|
||||
at!(vk::PhysicalDeviceVulkan12Features, buffer_device_address)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES, F::BufferDeviceAddress) => {
|
||||
at!(
|
||||
vk::PhysicalDeviceBufferDeviceAddressFeatures,
|
||||
buffer_device_address
|
||||
)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, F::SubgroupSizeControl) => {
|
||||
at!(vk::PhysicalDeviceVulkan13Features, subgroup_size_control)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES, F::SubgroupSizeControl) => {
|
||||
at!(
|
||||
vk::PhysicalDeviceSubgroupSizeControlFeatures,
|
||||
subgroup_size_control
|
||||
)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, F::ComputeFullSubgroups) => {
|
||||
at!(vk::PhysicalDeviceVulkan13Features, compute_full_subgroups)
|
||||
}
|
||||
(S::PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES, F::ComputeFullSubgroups) => {
|
||||
at!(
|
||||
vk::PhysicalDeviceSubgroupSizeControlFeatures,
|
||||
compute_full_subgroups
|
||||
)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -338,6 +497,11 @@ enum OwnedFeature {
|
||||
IntraRefresh(vk::PhysicalDeviceVideoEncodeIntraRefreshFeaturesKHR<'static>),
|
||||
QpMap(vk::PhysicalDeviceVideoEncodeQuantizationMapFeaturesKHR<'static>),
|
||||
SharedQueues(vk::PhysicalDeviceInternallySynchronizedQueuesFeaturesKHR<'static>),
|
||||
Storage16(vk::PhysicalDevice16BitStorageFeatures<'static>),
|
||||
Storage8(vk::PhysicalDevice8BitStorageFeatures<'static>),
|
||||
Float16Int8(vk::PhysicalDeviceShaderFloat16Int8Features<'static>),
|
||||
Bda(vk::PhysicalDeviceBufferDeviceAddressFeatures<'static>),
|
||||
SubgroupSize(vk::PhysicalDeviceSubgroupSizeControlFeatures<'static>),
|
||||
}
|
||||
|
||||
impl OwnedFeature {
|
||||
@@ -377,6 +541,33 @@ impl OwnedFeature {
|
||||
vk::PhysicalDeviceInternallySynchronizedQueuesFeaturesKHR::default()
|
||||
.internally_synchronized_queues(true),
|
||||
),
|
||||
F::StorageBuffer16BitAccess => Self::Storage16(
|
||||
vk::PhysicalDevice16BitStorageFeatures::default().storage_buffer16_bit_access(true),
|
||||
),
|
||||
F::StorageBuffer8BitAccess => Self::Storage8(
|
||||
vk::PhysicalDevice8BitStorageFeatures::default().storage_buffer8_bit_access(true),
|
||||
),
|
||||
F::ShaderInt8 => Self::Float16Int8(
|
||||
vk::PhysicalDeviceShaderFloat16Int8Features::default().shader_int8(true),
|
||||
),
|
||||
F::ShaderFloat16 => Self::Float16Int8(
|
||||
vk::PhysicalDeviceShaderFloat16Int8Features::default().shader_float16(true),
|
||||
),
|
||||
F::BufferDeviceAddress => Self::Bda(
|
||||
vk::PhysicalDeviceBufferDeviceAddressFeatures::default()
|
||||
.buffer_device_address(true),
|
||||
),
|
||||
F::SubgroupSizeControl => Self::SubgroupSize(
|
||||
vk::PhysicalDeviceSubgroupSizeControlFeatures::default()
|
||||
.subgroup_size_control(true),
|
||||
),
|
||||
F::ComputeFullSubgroups => Self::SubgroupSize(
|
||||
vk::PhysicalDeviceSubgroupSizeControlFeatures::default()
|
||||
.compute_full_subgroups(true),
|
||||
),
|
||||
F::ShaderInt16 | F::ShaderStorageImageWriteWithoutFormat => {
|
||||
unreachable!("core features have no struct of their own")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -391,6 +582,11 @@ impl OwnedFeature {
|
||||
Self::IntraRefresh(s) => std::ptr::from_mut(s).cast(),
|
||||
Self::QpMap(s) => std::ptr::from_mut(s).cast(),
|
||||
Self::SharedQueues(s) => std::ptr::from_mut(s).cast(),
|
||||
Self::Storage16(s) => std::ptr::from_mut(s).cast(),
|
||||
Self::Storage8(s) => std::ptr::from_mut(s).cast(),
|
||||
Self::Float16Int8(s) => std::ptr::from_mut(s).cast(),
|
||||
Self::Bda(s) => std::ptr::from_mut(s).cast(),
|
||||
Self::SubgroupSize(s) => std::ptr::from_mut(s).cast(),
|
||||
};
|
||||
p.cast()
|
||||
}
|
||||
@@ -398,8 +594,13 @@ impl OwnedFeature {
|
||||
|
||||
impl FeaturePatch {
|
||||
/// Turn on every feature in `wanted` for a device whose create info has
|
||||
/// `chain` as its pNext. Returns the patch and the pNext the create info
|
||||
/// should carry instead.
|
||||
/// `chain` as its pNext. Returns the patch, the pNext the create info
|
||||
/// should carry instead, and the Vulkan 1.0 features the chain had no
|
||||
/// `VkPhysicalDeviceFeatures2` to hold — those belong in
|
||||
/// `pEnabledFeatures`, see [`core_features`].
|
||||
///
|
||||
/// Structs of ours are searched like the game's, so two features sharing
|
||||
/// one struct type land in one struct: a chain may hold each type once.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
@@ -408,16 +609,18 @@ impl FeaturePatch {
|
||||
pub unsafe fn apply(
|
||||
chain: *const std::ffi::c_void,
|
||||
wanted: &[Feature],
|
||||
) -> (Self, *const std::ffi::c_void) {
|
||||
) -> (Self, *const std::ffi::c_void, Vec<Feature>) {
|
||||
let mut patch = Self {
|
||||
restores: Vec::new(),
|
||||
owned: Vec::new(),
|
||||
};
|
||||
let mut missing: Vec<Feature> = Vec::new();
|
||||
let mut core_missing: Vec<Feature> = Vec::new();
|
||||
// Ours sit in front of the game's chain, in the order they were added.
|
||||
let mut head = chain;
|
||||
|
||||
for &feature in wanted {
|
||||
let mut found = false;
|
||||
let mut p = chain as *mut vk::BaseOutStructure<'_>;
|
||||
let mut p = head as *mut vk::BaseOutStructure<'_>;
|
||||
while !p.is_null() {
|
||||
let s_type = unsafe { (*p).s_type };
|
||||
if let Some(bit) = unsafe { field(s_type, p, feature) } {
|
||||
@@ -427,20 +630,23 @@ impl FeaturePatch {
|
||||
}
|
||||
p = unsafe { (*p).p_next };
|
||||
}
|
||||
if !found {
|
||||
missing.push(feature);
|
||||
if found {
|
||||
continue;
|
||||
}
|
||||
if feature.is_core() {
|
||||
core_missing.push(feature);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
let mut head = chain;
|
||||
for feature in missing.into_iter().rev() {
|
||||
let mut owned = Box::new(OwnedFeature::new(feature));
|
||||
let base = owned.base();
|
||||
unsafe { (*base).p_next = head as *mut _ };
|
||||
head = base as *const _;
|
||||
unsafe { (*base).p_next = chain as *mut _ };
|
||||
match patch.owned.last_mut() {
|
||||
Some(last) => unsafe { (*last.base()).p_next = base },
|
||||
None => head = base as *const _,
|
||||
}
|
||||
patch.owned.push(owned);
|
||||
}
|
||||
(patch, head)
|
||||
(patch, head, core_missing)
|
||||
}
|
||||
|
||||
/// Put the application's chain back as it was.
|
||||
@@ -455,6 +661,28 @@ impl FeaturePatch {
|
||||
}
|
||||
}
|
||||
|
||||
/// `pEnabledFeatures` with `missing` turned on: the game's own, copied, or a
|
||||
/// fresh set when it gave none.
|
||||
///
|
||||
/// Only used when the chain holds no `VkPhysicalDeviceFeatures2`, since the
|
||||
/// two may not be given together, and with one the bits went there instead.
|
||||
pub fn core_features(
|
||||
game: Option<&vk::PhysicalDeviceFeatures>,
|
||||
missing: &[Feature],
|
||||
) -> vk::PhysicalDeviceFeatures {
|
||||
let mut out = game.copied().unwrap_or_default();
|
||||
for feature in missing {
|
||||
match feature {
|
||||
Feature::ShaderInt16 => out.shader_int16 = vk::TRUE,
|
||||
Feature::ShaderStorageImageWriteWithoutFormat => {
|
||||
out.shader_storage_image_write_without_format = vk::TRUE
|
||||
}
|
||||
other => debug_assert!(!other.is_core(), "{other:?} has no place here"),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ── Extensions ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// `game` with every name in `add` it does not already have, as pointers
|
||||
@@ -475,28 +703,51 @@ pub fn merged_extensions(
|
||||
out
|
||||
}
|
||||
|
||||
/// Everything the device needs beyond what the game asked for: the pixelforge
|
||||
/// requirements, and the queue plan that satisfies them.
|
||||
/// Everything the device needs beyond what the game asked for: each hosted
|
||||
/// encoder's requirements, and the queue plan that satisfies them.
|
||||
pub struct Additions {
|
||||
pub requirements: DeviceRequirements,
|
||||
/// pixelforge's, when the device can encode Vulkan Video.
|
||||
pub video: Option<DeviceRequirements>,
|
||||
/// nespyro's, when the device can run PyroWave.
|
||||
pub pyro: Option<nespyro::DeviceRequirements>,
|
||||
pub queues: QueuePlan,
|
||||
}
|
||||
|
||||
impl Additions {
|
||||
/// The extensions to add, including the one queue sharing needs.
|
||||
/// The extensions to add, including the one queue sharing needs. Each
|
||||
/// named once, however many encoders want it.
|
||||
pub fn extensions(&self) -> Vec<&'static std::ffi::CStr> {
|
||||
let mut names = self.requirements.extensions.clone();
|
||||
let mut names: Vec<&'static std::ffi::CStr> = Vec::new();
|
||||
let mut add = |name: &'static std::ffi::CStr| {
|
||||
if !names.contains(&name) {
|
||||
names.push(name);
|
||||
}
|
||||
};
|
||||
for name in self.video.iter().flat_map(|r| r.extensions.iter()) {
|
||||
add(name);
|
||||
}
|
||||
for name in self.pyro.iter().flat_map(|r| r.extensions.iter()) {
|
||||
add(name);
|
||||
}
|
||||
if !self.queues.internally_synchronized.is_empty() {
|
||||
names.push(ash::khr::internally_synchronized_queues::NAME);
|
||||
add(ash::khr::internally_synchronized_queues::NAME);
|
||||
}
|
||||
names
|
||||
}
|
||||
|
||||
/// Each named once, however many encoders want it.
|
||||
pub fn features(&self) -> Vec<Feature> {
|
||||
wanted_features(
|
||||
&self.requirements.features,
|
||||
!self.queues.internally_synchronized.is_empty(),
|
||||
)
|
||||
let share = !self.queues.internally_synchronized.is_empty();
|
||||
let mut out = match &self.video {
|
||||
Some(r) => wanted_features(&r.features, share),
|
||||
None => wanted_features(&DeviceFeatures::default(), share),
|
||||
};
|
||||
for f in self.pyro.iter().flat_map(|r| pyro_features(&r.features)) {
|
||||
if !out.contains(&f) {
|
||||
out.push(f);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
@@ -630,6 +881,8 @@ pub struct PreparedDevice {
|
||||
extensions: Vec<*const std::ffi::c_char>,
|
||||
patch: FeaturePatch,
|
||||
p_next: *const std::ffi::c_void,
|
||||
/// The 1.0 features, when they had to go in `pEnabledFeatures`.
|
||||
enabled_features: Option<Box<vk::PhysicalDeviceFeatures>>,
|
||||
}
|
||||
|
||||
/// Work out what to add to the game's device so the encoder can run on it.
|
||||
@@ -664,17 +917,44 @@ pub unsafe fn prepare(
|
||||
return None;
|
||||
}
|
||||
let (entry, instance) = instance_view(istate, next_gdpa);
|
||||
let requirements = match pixelforge::VideoContextBuilder::new().encode_device_requirements(
|
||||
let video = match pixelforge::VideoContextBuilder::new().encode_device_requirements(
|
||||
&entry,
|
||||
&instance,
|
||||
physical_device,
|
||||
) {
|
||||
Ok(r) => r,
|
||||
Ok(r) => Some(r),
|
||||
Err(e) => {
|
||||
log::info!("the game's device cannot host the encoder ({e})");
|
||||
return None;
|
||||
log::info!("the game's device cannot host Vulkan Video encode ({e})");
|
||||
None
|
||||
}
|
||||
};
|
||||
// nespyro uses Vulkan 1.3 commands, which a device only has when its
|
||||
// instance asked for 1.3 as well as the GPU having it.
|
||||
let pyro = if istate.api_version < vk::API_VERSION_1_3 {
|
||||
log::info!("instance is below Vulkan 1.3; no PyroWave on the game's device");
|
||||
None
|
||||
} else {
|
||||
match nespyro::DeviceRequirements::query(&instance, physical_device, nespyro::Roles::ENCODE)
|
||||
{
|
||||
Ok(r) => Some(r),
|
||||
Err(e) => {
|
||||
log::info!("the game's device cannot host PyroWave ({e})");
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
if video.is_none() && pyro.is_none() {
|
||||
log::info!("neither encoder fits the game's device; encoding on a device of its own");
|
||||
return None;
|
||||
}
|
||||
let internally_synchronized_queues = match &video {
|
||||
Some(r) => r.internally_synchronized_queues,
|
||||
None => supports_internally_synchronized_queues(&instance, physical_device),
|
||||
};
|
||||
let wants = match &video {
|
||||
Some(r) => Wants::video(r.queues.encode),
|
||||
None => Wants::PYRO_ONLY,
|
||||
};
|
||||
|
||||
let families = unsafe { instance.get_physical_device_queue_family_properties(physical_device) };
|
||||
let game_infos: &[vk::DeviceQueueCreateInfo<'_>] = if ci.queue_create_info_count == 0
|
||||
@@ -691,12 +971,7 @@ pub unsafe fn prepare(
|
||||
.map(|q| (q.queue_family_index, (q.queue_count, q.flags)))
|
||||
.collect();
|
||||
|
||||
let Some(queues) = plan_queues(
|
||||
&families,
|
||||
&game,
|
||||
requirements.queues.encode,
|
||||
requirements.internally_synchronized_queues,
|
||||
) else {
|
||||
let Some(queues) = plan_queues(&families, &game, wants, internally_synchronized_queues) else {
|
||||
log::info!(
|
||||
"no queue for the encoder that the game does not submit to; \
|
||||
encoding on a device of its own"
|
||||
@@ -704,7 +979,12 @@ pub unsafe fn prepare(
|
||||
return None;
|
||||
};
|
||||
log::info!(
|
||||
"encoder on the game's device: encode queue {:?}, compute queue {:?}, transfer queue {:?}{}",
|
||||
"encoders on the game's device ({}): encode queue {:?}, compute queue {:?}, transfer queue {:?}{}",
|
||||
match (video.is_some(), pyro.is_some()) {
|
||||
(true, true) => "Vulkan Video and PyroWave",
|
||||
(true, false) => "Vulkan Video",
|
||||
_ => "PyroWave",
|
||||
},
|
||||
queues.encode,
|
||||
queues.compute,
|
||||
queues.transfer,
|
||||
@@ -759,11 +1039,17 @@ pub unsafe fn prepare(
|
||||
}
|
||||
|
||||
let additions = Additions {
|
||||
requirements,
|
||||
video,
|
||||
pyro,
|
||||
queues,
|
||||
};
|
||||
let extensions = merged_extensions(extensions, &additions.extensions());
|
||||
let (patch, p_next) = unsafe { FeaturePatch::apply(ci.p_next, &additions.features()) };
|
||||
let (patch, p_next, core_missing) =
|
||||
unsafe { FeaturePatch::apply(ci.p_next, &additions.features()) };
|
||||
let enabled_features = (!core_missing.is_empty()).then(|| {
|
||||
let game = unsafe { ci.p_enabled_features.as_ref() };
|
||||
Box::new(core_features(game, &core_missing))
|
||||
});
|
||||
|
||||
Some(PreparedDevice {
|
||||
additions,
|
||||
@@ -774,9 +1060,33 @@ pub unsafe fn prepare(
|
||||
extensions,
|
||||
patch,
|
||||
p_next,
|
||||
enabled_features,
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `physical_device` supports `VK_KHR_internally_synchronized_queues`,
|
||||
/// extension and feature both. pixelforge answers this when it is hosted; this
|
||||
/// is the same question for a device hosting only nespyro.
|
||||
fn supports_internally_synchronized_queues(
|
||||
instance: &ash::Instance,
|
||||
physical_device: vk::PhysicalDevice,
|
||||
) -> bool {
|
||||
let Ok(exts) = (unsafe { instance.enumerate_device_extension_properties(physical_device) })
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if !exts.iter().any(|e| {
|
||||
e.extension_name_as_c_str()
|
||||
.is_ok_and(|n| n == ash::khr::internally_synchronized_queues::NAME)
|
||||
}) {
|
||||
return false;
|
||||
}
|
||||
let mut features = vk::PhysicalDeviceInternallySynchronizedQueuesFeaturesKHR::default();
|
||||
let mut query = vk::PhysicalDeviceFeatures2::default().push(&mut features);
|
||||
unsafe { instance.get_physical_device_features2(physical_device, &mut query) };
|
||||
features.internally_synchronized_queues != 0
|
||||
}
|
||||
|
||||
impl PreparedDevice {
|
||||
/// `ci` with the additions in. Valid while `self` is.
|
||||
pub fn create_info<'a>(&'a self, ci: &vk::DeviceCreateInfo<'a>) -> vk::DeviceCreateInfo<'a> {
|
||||
@@ -786,6 +1096,9 @@ impl PreparedDevice {
|
||||
out.p_queue_create_infos = self.queue_infos.as_ptr().cast();
|
||||
out.enabled_extension_count = self.extensions.len() as u32;
|
||||
out.pp_enabled_extension_names = self.extensions.as_ptr();
|
||||
if let Some(features) = &self.enabled_features {
|
||||
out.p_enabled_features = &raw const **features;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -811,6 +1124,9 @@ pub struct SharedDevice {
|
||||
/// created below Vulkan 1.2 still has: the encoder enabled the extension.
|
||||
timeline: ash::khr::timeline_semaphore::Device,
|
||||
pub queues: QueuePlan,
|
||||
/// Which encoders the device was created for.
|
||||
video: bool,
|
||||
pyro: bool,
|
||||
}
|
||||
|
||||
impl SharedDevice {
|
||||
@@ -860,6 +1176,8 @@ impl SharedDevice {
|
||||
device,
|
||||
timeline,
|
||||
queues: additions.queues,
|
||||
video: additions.video.is_some(),
|
||||
pyro: additions.pyro.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -902,26 +1220,56 @@ impl SharedDevice {
|
||||
}
|
||||
|
||||
/// A pixelforge context on the game's device, submitting to the queues
|
||||
/// the plan set aside.
|
||||
pub fn video_context(&self) -> Result<pixelforge::VideoContext, pixelforge::PixelForgeError> {
|
||||
pixelforge::VideoContextBuilder::new()
|
||||
.app_name("nescapture")
|
||||
.with_encode_queue(self.queues.encode)
|
||||
.with_compute_queue(self.queues.compute)
|
||||
.with_transfer_queue(self.queues.transfer)
|
||||
.build_from_existing_encode(
|
||||
self.entry.clone(),
|
||||
/// the plan set aside. `None` when the device was not created for it.
|
||||
pub fn video_context(
|
||||
&self,
|
||||
) -> Option<Result<pixelforge::VideoContext, pixelforge::PixelForgeError>> {
|
||||
if !self.video {
|
||||
return None;
|
||||
}
|
||||
let (Some(encode), Some(transfer)) = (self.queues.encode, self.queues.transfer) else {
|
||||
return None;
|
||||
};
|
||||
Some(
|
||||
pixelforge::VideoContextBuilder::new()
|
||||
.app_name("nescapture")
|
||||
.with_encode_queue(encode)
|
||||
.with_compute_queue(self.queues.compute)
|
||||
.with_transfer_queue(transfer)
|
||||
.build_from_existing_encode(
|
||||
self.entry.clone(),
|
||||
self.instance.clone(),
|
||||
self.physical_device,
|
||||
self.device.clone(),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
/// A nespyro context on the game's device, on the plan's compute queue.
|
||||
/// `None` when the device was not created for it.
|
||||
///
|
||||
/// No queue lock: the encoder thread is the only submitter to that queue
|
||||
/// apart from a game sharing it, and a queue shared with the game was
|
||||
/// created internally synchronized.
|
||||
pub fn pyro_context(&self) -> Option<Result<nespyro::Context, nespyro::Error>> {
|
||||
self.pyro.then(|| {
|
||||
nespyro::Context::from_existing(
|
||||
self.instance.clone(),
|
||||
self.physical_device,
|
||||
self.device.clone(),
|
||||
nespyro::DeviceQueue::new(self.queues.compute.family, self.queues.compute.index),
|
||||
nespyro::QueueLock::none(),
|
||||
nespyro::Roles::ENCODE,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// The queue families that touch a capture image: the one the game
|
||||
/// presents on, where the blit runs, and the encoder's.
|
||||
pub fn image_families(&self, present_family: u32) -> Vec<u32> {
|
||||
let mut out = vec![present_family];
|
||||
for f in [self.queues.compute.family, self.queues.transfer.family] {
|
||||
let transfer = self.queues.transfer.map(|q| q.family);
|
||||
for f in std::iter::once(self.queues.compute.family).chain(transfer) {
|
||||
if !out.contains(&f) {
|
||||
out.push(f);
|
||||
}
|
||||
@@ -966,19 +1314,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn spare_queues_keep_the_encoder_off_the_games_queue() {
|
||||
let plan = plan_queues(&amd(), &game(&[(0, 1)]), Some(2), false).unwrap();
|
||||
assert_eq!(plan.encode, DeviceQueue::new(2, 0));
|
||||
let plan = plan_queues(&amd(), &game(&[(0, 1)]), Wants::video(Some(2)), false).unwrap();
|
||||
assert_eq!(plan.encode, Some(DeviceQueue::new(2, 0)));
|
||||
// Compute on the compute family, not on the game's graphics queue.
|
||||
assert_eq!(plan.compute, DeviceQueue::new(1, 0));
|
||||
// And copies share it: one thread submits both.
|
||||
assert_eq!(plan.transfer, plan.compute);
|
||||
assert_eq!(plan.transfer, Some(plan.compute));
|
||||
assert!(plan.internally_synchronized.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_family_the_game_already_uses_gets_one_more_queue() {
|
||||
// The game took two of the four compute queues for itself.
|
||||
let plan = plan_queues(&amd(), &game(&[(0, 1), (1, 2)]), Some(2), false).unwrap();
|
||||
let plan = plan_queues(
|
||||
&amd(),
|
||||
&game(&[(0, 1), (1, 2)]),
|
||||
Wants::video(Some(2)),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(plan.compute, DeviceQueue::new(1, 2));
|
||||
assert_eq!(plan.counts.get(&1), Some(&3));
|
||||
}
|
||||
@@ -987,11 +1341,14 @@ mod tests {
|
||||
fn with_every_capable_family_full_nothing_is_planned_unless_sharing_is_safe() {
|
||||
// The game took all four compute queues and its one graphics queue.
|
||||
let full = game(&[(0, 1), (1, 4)]);
|
||||
assert_eq!(plan_queues(&amd(), &full, Some(2), false), None);
|
||||
assert_eq!(
|
||||
plan_queues(&amd(), &full, Wants::video(Some(2)), false),
|
||||
None
|
||||
);
|
||||
|
||||
// Sharing picks the compute family over the graphics one, since the
|
||||
// game renders on the latter.
|
||||
let plan = plan_queues(&amd(), &full, Some(2), true).unwrap();
|
||||
let plan = plan_queues(&amd(), &full, Wants::video(Some(2)), true).unwrap();
|
||||
assert_eq!(plan.compute, DeviceQueue::new(1, 0));
|
||||
assert_eq!(plan.internally_synchronized, vec![1]);
|
||||
}
|
||||
@@ -1009,17 +1366,17 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn without_a_spare_the_games_queue_is_shared_where_that_is_safe() {
|
||||
let plan = plan_queues(&intel(), &game(&[(0, 1)]), Some(1), true).unwrap();
|
||||
assert_eq!(plan.encode, DeviceQueue::new(1, 0));
|
||||
let plan = plan_queues(&intel(), &game(&[(0, 1)]), Wants::video(Some(1)), true).unwrap();
|
||||
assert_eq!(plan.encode, Some(DeviceQueue::new(1, 0)));
|
||||
assert_eq!(plan.compute, DeviceQueue::new(0, 0));
|
||||
assert_eq!(plan.transfer, DeviceQueue::new(0, 0));
|
||||
assert_eq!(plan.transfer, Some(DeviceQueue::new(0, 0)));
|
||||
assert_eq!(plan.internally_synchronized, vec![0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_spare_or_a_safe_share_there_is_no_plan() {
|
||||
assert_eq!(
|
||||
plan_queues(&intel(), &game(&[(0, 1)]), Some(1), false),
|
||||
plan_queues(&intel(), &game(&[(0, 1)]), Wants::video(Some(1)), false),
|
||||
None
|
||||
);
|
||||
}
|
||||
@@ -1028,15 +1385,21 @@ mod tests {
|
||||
fn a_protected_queue_is_never_shared() {
|
||||
let mut g = game(&[(0, 1)]);
|
||||
g.insert(0, (1, vk::DeviceQueueCreateFlags::PROTECTED));
|
||||
assert_eq!(plan_queues(&intel(), &g, Some(1), true), None);
|
||||
assert_eq!(plan_queues(&intel(), &g, Wants::video(Some(1)), true), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_game_that_already_encodes_keeps_its_encode_queue() {
|
||||
let mut families = amd();
|
||||
families[2].queue_count = 2;
|
||||
let plan = plan_queues(&families, &game(&[(0, 1), (2, 1)]), Some(2), false).unwrap();
|
||||
assert_eq!(plan.encode, DeviceQueue::new(2, 1));
|
||||
let plan = plan_queues(
|
||||
&families,
|
||||
&game(&[(0, 1), (2, 1)]),
|
||||
Wants::video(Some(2)),
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(plan.encode, Some(DeviceQueue::new(2, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1046,7 +1409,7 @@ mod tests {
|
||||
v13.p_next = (&raw mut v12).cast();
|
||||
let chain = (&raw const v13).cast();
|
||||
|
||||
let (patch, head) = unsafe {
|
||||
let (patch, head, _) = unsafe {
|
||||
FeaturePatch::apply(
|
||||
chain,
|
||||
&[Feature::Synchronization2, Feature::TimelineSemaphore],
|
||||
@@ -1067,7 +1430,7 @@ mod tests {
|
||||
fn a_feature_with_no_home_gets_a_struct_in_front_of_the_chain() {
|
||||
let v12 = vk::PhysicalDeviceVulkan12Features::default();
|
||||
let chain = (&raw const v12).cast();
|
||||
let (patch, head) = unsafe { FeaturePatch::apply(chain, &[Feature::Synchronization2]) };
|
||||
let (patch, head, _) = unsafe { FeaturePatch::apply(chain, &[Feature::Synchronization2]) };
|
||||
assert_ne!(head, chain);
|
||||
let first = head as *const vk::BaseInStructure<'_>;
|
||||
unsafe {
|
||||
@@ -1087,7 +1450,7 @@ mod tests {
|
||||
Feature::TimelineSemaphore,
|
||||
Feature::VideoEncodeAv1,
|
||||
];
|
||||
let (patch, head) = unsafe { FeaturePatch::apply(std::ptr::null(), &wanted) };
|
||||
let (patch, head, _) = unsafe { FeaturePatch::apply(std::ptr::null(), &wanted) };
|
||||
let mut seen = Vec::new();
|
||||
let mut p = head as *const vk::BaseInStructure<'_>;
|
||||
while !p.is_null() {
|
||||
@@ -1118,6 +1481,183 @@ mod tests {
|
||||
assert_eq!(merged.len(), 2);
|
||||
}
|
||||
|
||||
// ── PyroWave beside, or instead of, Vulkan Video ─────────────────────────
|
||||
|
||||
/// A GPU with no video encode family still gets a compute queue of its
|
||||
/// own for nespyro, and no encode or transfer queue it would not use.
|
||||
#[test]
|
||||
fn pyrowave_alone_plans_only_compute() {
|
||||
let families = vec![family(GFX, 1), family(COMPUTE, 2)];
|
||||
let plan = plan_queues(&families, &game(&[(0, 1)]), Wants::PYRO_ONLY, false).unwrap();
|
||||
assert_eq!(plan.compute, DeviceQueue::new(1, 0));
|
||||
assert_eq!(plan.encode, None);
|
||||
assert_eq!(plan.transfer, None);
|
||||
assert!(plan.internally_synchronized.is_empty());
|
||||
}
|
||||
|
||||
/// Without the video family there is nothing to plan an encode queue on,
|
||||
/// and asking for one must fail rather than quietly skip it.
|
||||
#[test]
|
||||
fn vulkan_video_without_an_encode_family_has_no_plan() {
|
||||
let families = vec![family(GFX, 1), family(COMPUTE, 2)];
|
||||
assert_eq!(
|
||||
plan_queues(&families, &game(&[(0, 1)]), Wants::video(None), true),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
/// Two features of one struct type must land in one struct: a pNext chain
|
||||
/// may hold each type once, and int8 and float16 share
|
||||
/// `VkPhysicalDeviceShaderFloat16Int8Features`.
|
||||
#[test]
|
||||
fn features_sharing_a_struct_share_one_of_ours() {
|
||||
let wanted = [
|
||||
Feature::ShaderInt8,
|
||||
Feature::ShaderFloat16,
|
||||
Feature::SubgroupSizeControl,
|
||||
Feature::ComputeFullSubgroups,
|
||||
];
|
||||
let (patch, head, core) = unsafe { FeaturePatch::apply(std::ptr::null(), &wanted) };
|
||||
assert!(core.is_empty());
|
||||
let mut seen = Vec::new();
|
||||
let mut p = head as *const vk::BaseInStructure<'_>;
|
||||
while !p.is_null() {
|
||||
seen.push(unsafe { (*p).s_type });
|
||||
p = unsafe { (*p).p_next };
|
||||
}
|
||||
assert_eq!(
|
||||
seen,
|
||||
vec![
|
||||
vk::StructureType::PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES,
|
||||
vk::StructureType::PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES,
|
||||
]
|
||||
);
|
||||
let f = unsafe { &*(head as *const vk::PhysicalDeviceShaderFloat16Int8Features<'_>) };
|
||||
assert_eq!((f.shader_int8, f.shader_float16), (vk::TRUE, vk::TRUE));
|
||||
unsafe { patch.restore() };
|
||||
}
|
||||
|
||||
/// Ours go in front of the game's chain, which is then still reachable
|
||||
/// from the head and left as it was.
|
||||
#[test]
|
||||
fn our_structs_lead_into_the_games_chain() {
|
||||
let v11 = vk::PhysicalDeviceVulkan11Features::default();
|
||||
let chain = (&raw const v11).cast();
|
||||
let (patch, head, _) = unsafe {
|
||||
FeaturePatch::apply(
|
||||
chain,
|
||||
&[
|
||||
Feature::BufferDeviceAddress,
|
||||
Feature::StorageBuffer16BitAccess,
|
||||
],
|
||||
)
|
||||
};
|
||||
let first = head as *const vk::BaseInStructure<'_>;
|
||||
unsafe {
|
||||
assert_eq!(
|
||||
(*first).s_type,
|
||||
vk::StructureType::PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES
|
||||
);
|
||||
assert_eq!((*first).p_next.cast(), chain, "the game's chain was lost");
|
||||
}
|
||||
// 16-bit storage had a home in the game's Vulkan 1.1 struct.
|
||||
assert_eq!(v11.storage_buffer16_bit_access, vk::TRUE);
|
||||
unsafe { patch.restore() };
|
||||
assert_eq!(v11.storage_buffer16_bit_access, vk::FALSE);
|
||||
}
|
||||
|
||||
/// The 1.0 features live in `VkPhysicalDeviceFeatures`. Inside a chained
|
||||
/// `VkPhysicalDeviceFeatures2` they are set there and put back after.
|
||||
#[test]
|
||||
fn core_features_go_in_a_chained_features2() {
|
||||
let mut f2 = vk::PhysicalDeviceFeatures2::default();
|
||||
f2.features.shader_int16 = vk::FALSE;
|
||||
let chain = (&raw const f2).cast();
|
||||
let (patch, head, core) = unsafe {
|
||||
FeaturePatch::apply(
|
||||
chain,
|
||||
&[
|
||||
Feature::ShaderInt16,
|
||||
Feature::ShaderStorageImageWriteWithoutFormat,
|
||||
],
|
||||
)
|
||||
};
|
||||
assert!(core.is_empty(), "Features2 was there to hold them");
|
||||
assert_eq!(head, chain);
|
||||
assert_eq!(f2.features.shader_int16, vk::TRUE);
|
||||
assert_eq!(
|
||||
f2.features.shader_storage_image_write_without_format,
|
||||
vk::TRUE
|
||||
);
|
||||
unsafe { patch.restore() };
|
||||
assert_eq!(f2.features.shader_int16, vk::FALSE);
|
||||
}
|
||||
|
||||
/// Without one they are reported, never chained as a struct of their own:
|
||||
/// a Features2 of ours beside the game's `pEnabledFeatures` is invalid.
|
||||
#[test]
|
||||
fn core_features_without_features2_are_handed_back() {
|
||||
let (patch, head, core) = unsafe {
|
||||
FeaturePatch::apply(
|
||||
std::ptr::null(),
|
||||
&[Feature::ShaderInt16, Feature::ShaderInt8],
|
||||
)
|
||||
};
|
||||
assert_eq!(core, vec![Feature::ShaderInt16]);
|
||||
let first = head as *const vk::BaseInStructure<'_>;
|
||||
unsafe {
|
||||
assert_eq!(
|
||||
(*first).s_type,
|
||||
vk::StructureType::PHYSICAL_DEVICE_SHADER_FLOAT16_INT8_FEATURES
|
||||
);
|
||||
assert!((*first).p_next.is_null());
|
||||
}
|
||||
unsafe { patch.restore() };
|
||||
}
|
||||
|
||||
/// The game's own `pEnabledFeatures` is copied, never written: it is the
|
||||
/// game's memory, and the copy keeps every bit it asked for.
|
||||
#[test]
|
||||
fn enabled_features_are_a_copy_with_ours_added() {
|
||||
let game = vk::PhysicalDeviceFeatures {
|
||||
geometry_shader: vk::TRUE,
|
||||
..Default::default()
|
||||
};
|
||||
let ours = core_features(
|
||||
Some(&game),
|
||||
&[
|
||||
Feature::ShaderInt16,
|
||||
Feature::ShaderStorageImageWriteWithoutFormat,
|
||||
],
|
||||
);
|
||||
assert_eq!(ours.geometry_shader, vk::TRUE);
|
||||
assert_eq!(ours.shader_int16, vk::TRUE);
|
||||
assert_eq!(ours.shader_storage_image_write_without_format, vk::TRUE);
|
||||
assert_eq!(game.shader_int16, vk::FALSE);
|
||||
|
||||
let fresh = core_features(None, &[Feature::ShaderInt16]);
|
||||
assert_eq!(fresh.shader_int16, vk::TRUE);
|
||||
assert_eq!(fresh.geometry_shader, vk::FALSE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nespyro_features_map_to_ours() {
|
||||
let f = nespyro::DeviceFeatures {
|
||||
shader_int16: true,
|
||||
shader_float16: true,
|
||||
subgroup_size_control: true,
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
pyro_features(&f),
|
||||
vec![
|
||||
Feature::ShaderInt16,
|
||||
Feature::ShaderFloat16,
|
||||
Feature::SubgroupSizeControl
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
// ── The null instance a layer below need not survive ─────────────────────
|
||||
|
||||
/// On construction `ash::Entry` asks for the instance-global commands with
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
//! How much PyroWave an iroh connection carries.
|
||||
//!
|
||||
//! Sends PyroWave-shaped frames at a set rate through the same packing and the
|
||||
//! same skip rule the hub uses, and collects them with the same collector the
|
||||
//! client uses, then says what got through. Run it before trusting a rate:
|
||||
//!
|
||||
//! ```text
|
||||
//! # CPU cost of the transport alone, both ends in this process:
|
||||
//! cargo run --release -p neshub --example pyro_bench -- loopback --mbps 300
|
||||
//!
|
||||
//! # The real thing, across a LAN. On the sending machine:
|
||||
//! cargo run --release -p neshub --example pyro_bench -- serve --mbps 300
|
||||
//! # and on the receiving one, with what `serve` printed:
|
||||
//! cargo run --release -p neshub --example pyro_bench -- connect <addr>
|
||||
//! ```
|
||||
//!
|
||||
//! Options: `--mbps`, `--fps` (60), `--secs` (10).
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use base64::Engine as _;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use bytes::Bytes;
|
||||
use iroh::endpoint::{Connection, QuicTransportConfig, presets};
|
||||
|
||||
use nesprotocol::ALPN_VIDEO;
|
||||
use nesprotocol::datagram::DGRAM_BUFFER_BYTES;
|
||||
use nesprotocol::pyrowave::{
|
||||
FrameMeta, PYRO_DGRAM_HDR_LEN, PyroCollector, PyroFrame, decode_pyro_datagram, pack_datagrams,
|
||||
should_skip,
|
||||
};
|
||||
|
||||
struct Opts {
|
||||
mbps: u64,
|
||||
fps: u64,
|
||||
secs: u64,
|
||||
}
|
||||
|
||||
fn transport() -> QuicTransportConfig {
|
||||
QuicTransportConfig::builder()
|
||||
.datagram_send_buffer_size(DGRAM_BUFFER_BYTES)
|
||||
.datagram_receive_buffer_size(Some(DGRAM_BUFFER_BYTES))
|
||||
.build()
|
||||
}
|
||||
|
||||
async fn endpoint(alpn: bool) -> Result<iroh::Endpoint> {
|
||||
let mut b = iroh::Endpoint::builder(presets::N0)
|
||||
.relay_mode(iroh::endpoint::RelayMode::Disabled)
|
||||
.transport_config(transport());
|
||||
if alpn {
|
||||
b = b.alpns(vec![ALPN_VIDEO.to_vec()]);
|
||||
}
|
||||
Ok(b.bind().await?)
|
||||
}
|
||||
|
||||
/// A frame of whole packets at `packet` bytes, behind an 8-byte stand-in for
|
||||
/// the sequence header.
|
||||
fn frame(bytes: usize, packet: usize) -> PyroFrame {
|
||||
let mut data = Vec::with_capacity(bytes + packet);
|
||||
let mut packets = Vec::with_capacity(bytes / packet + 2);
|
||||
packets.push(0..8);
|
||||
data.extend_from_slice(&[0; 8]);
|
||||
while data.len() < bytes {
|
||||
let start = data.len();
|
||||
data.extend((0..packet).map(|k| k as u8));
|
||||
packets.push(start..data.len());
|
||||
}
|
||||
PyroFrame {
|
||||
frame: 0,
|
||||
meta: FrameMeta::default(),
|
||||
critical: 3.min(packets.len()),
|
||||
data,
|
||||
packets,
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(conn: Connection, o: &Opts) -> Result<()> {
|
||||
let max = conn
|
||||
.max_datagram_size()
|
||||
.context("peer does not take datagrams")?;
|
||||
let packet = max - PYRO_DGRAM_HDR_LEN;
|
||||
let frame_bytes = (o.mbps * 1_000_000 / 8 / o.fps) as usize;
|
||||
let mut f = frame(frame_bytes, packet);
|
||||
println!(
|
||||
"send: {} Mbit/s at {} fps, {} KB frames of {} packets, {packet} B each",
|
||||
o.mbps,
|
||||
o.fps,
|
||||
frame_bytes / 1000,
|
||||
f.packets.len()
|
||||
);
|
||||
|
||||
let mut tick = tokio::time::interval(Duration::from_micros(1_000_000 / o.fps));
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
let end = Instant::now() + Duration::from_secs(o.secs);
|
||||
let (mut seq, mut sent, mut skipped) = (0u16, 0u64, 0u64);
|
||||
let mut busy = Duration::ZERO;
|
||||
let mut second = Instant::now();
|
||||
while Instant::now() < end {
|
||||
tick.tick().await;
|
||||
let t0 = Instant::now();
|
||||
f.meta.ts_ms = seq as u32;
|
||||
// Read per frame, as the hub does: with several paths up, the limit
|
||||
// is the smallest of their MTUs and moves as paths come and go.
|
||||
let now_max = conn.max_datagram_size().context("datagrams went away")?;
|
||||
let d = pack_datagrams(seq, &f, now_max)?;
|
||||
let backlog = DGRAM_BUFFER_BYTES.saturating_sub(conn.datagram_send_buffer_space());
|
||||
if should_skip(backlog, d.buf.len(), DGRAM_BUFFER_BYTES).is_some() {
|
||||
skipped += 1;
|
||||
} else {
|
||||
let buf = Bytes::from(d.buf);
|
||||
let mut at = 0;
|
||||
for len in d.lens {
|
||||
conn.send_datagram(buf.slice(at..at + len))?;
|
||||
at += len;
|
||||
}
|
||||
seq = seq.wrapping_add(1);
|
||||
sent += 1;
|
||||
}
|
||||
busy += t0.elapsed();
|
||||
|
||||
if second.elapsed() >= Duration::from_secs(1) {
|
||||
let path = conn.paths().iter().find(|p| p.is_selected()).map(|p| {
|
||||
let s = p.stats();
|
||||
(p.rtt(), s.cwnd)
|
||||
});
|
||||
println!(
|
||||
"send: {sent} frames, {skipped} skipped, {:.1} ms of work per frame, path {path:?}",
|
||||
busy.as_secs_f64() * 1000.0 / (sent + skipped).max(1) as f64
|
||||
);
|
||||
(sent, skipped, busy, second) = (0, 0, Duration::ZERO, Instant::now());
|
||||
}
|
||||
}
|
||||
// Let the queue drain before closing, or its tail reads as loss.
|
||||
while conn.datagram_send_buffer_space() < DGRAM_BUFFER_BYTES {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
conn.close(0u32.into(), b"done");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn receive(conn: Connection) -> Result<()> {
|
||||
let start = Instant::now();
|
||||
let mut c = PyroCollector::<Bytes>::new();
|
||||
let (mut bytes, mut datagrams) = (0u64, 0u64);
|
||||
let (mut all_bytes, mut whole, mut partial, mut lost) = (0u64, 0u64, 0u64, 0u64);
|
||||
let mut second = Instant::now();
|
||||
let mut busy = Duration::ZERO;
|
||||
loop {
|
||||
let d = match conn.read_datagram().await {
|
||||
Ok(d) => d,
|
||||
Err(_) => break,
|
||||
};
|
||||
let t0 = Instant::now();
|
||||
datagrams += 1;
|
||||
bytes += d.len() as u64;
|
||||
if let Some((h, p)) = decode_pyro_datagram(&d) {
|
||||
let at = d.len() - p.len();
|
||||
c.push(h, d.slice(at..), start.elapsed().as_micros() as u64);
|
||||
}
|
||||
busy += t0.elapsed();
|
||||
if second.elapsed() >= Duration::from_secs(1) {
|
||||
c.poll(start.elapsed().as_micros() as u64);
|
||||
let s = c.take_stats();
|
||||
println!(
|
||||
"recv: {:.0} Mbit/s, {datagrams} datagrams, {} whole, {} partial, {} lost, \
|
||||
{} recovered, {:.2} µs of work per datagram",
|
||||
bytes as f64 * 8.0 / second.elapsed().as_secs_f64() / 1e6,
|
||||
s.whole,
|
||||
s.partial,
|
||||
s.lost,
|
||||
s.recovered,
|
||||
busy.as_secs_f64() * 1e6 / datagrams.max(1) as f64
|
||||
);
|
||||
all_bytes += bytes;
|
||||
(whole, partial, lost) = (whole + s.whole, partial + s.partial, lost + s.lost);
|
||||
(bytes, datagrams, busy, second) = (0, 0, Duration::ZERO, Instant::now());
|
||||
}
|
||||
}
|
||||
c.poll(u64::MAX);
|
||||
let s = c.take_stats();
|
||||
(whole, partial, lost) = (whole + s.whole, partial + s.partial, lost + s.lost);
|
||||
all_bytes += bytes;
|
||||
println!(
|
||||
"recv total: {:.0} Mbit/s average, {whole} whole, {partial} partial, {lost} datagrams lost",
|
||||
all_bytes as f64 * 8.0 / start.elapsed().as_secs_f64() / 1e6
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse() -> Result<(String, Option<String>, Opts)> {
|
||||
let mut args = std::env::args().skip(1);
|
||||
let mode = args.next().context("mode: loopback, serve or connect")?;
|
||||
let mut target = None;
|
||||
let mut o = Opts {
|
||||
mbps: 300,
|
||||
fps: 60,
|
||||
secs: 10,
|
||||
};
|
||||
while let Some(a) = args.next() {
|
||||
let mut num = |name: &str| -> Result<u64> {
|
||||
args.next()
|
||||
.with_context(|| format!("{name} needs a value"))?
|
||||
.parse()
|
||||
.with_context(|| format!("{name} is a number"))
|
||||
};
|
||||
match a.as_str() {
|
||||
"--mbps" => o.mbps = num("--mbps")?,
|
||||
"--fps" => o.fps = num("--fps")?,
|
||||
"--secs" => o.secs = num("--secs")?,
|
||||
other if target.is_none() && !other.starts_with("--") => target = Some(a),
|
||||
other => bail!("unknown argument {other}"),
|
||||
}
|
||||
}
|
||||
Ok((mode, target, o))
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let (mode, target, o) = parse()?;
|
||||
match mode.as_str() {
|
||||
"loopback" => {
|
||||
let (hub, client) = (endpoint(true).await?, endpoint(false).await?);
|
||||
let addr = hub.addr();
|
||||
let accept = tokio::spawn(async move {
|
||||
let conn = hub.accept().await.context("accept")?.await?;
|
||||
Ok::<_, anyhow::Error>((hub, conn))
|
||||
});
|
||||
let rx = client.connect(addr, ALPN_VIDEO).await?;
|
||||
let (_hub, tx) = accept.await??;
|
||||
let r = tokio::spawn(receive(rx));
|
||||
send(tx, &o).await?;
|
||||
r.await??;
|
||||
}
|
||||
"serve" => {
|
||||
let hub = endpoint(true).await?;
|
||||
// Direct addresses are learned over the first moments.
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let addr = URL_SAFE_NO_PAD.encode(serde_json::to_vec(&hub.addr())?);
|
||||
println!("connect with:\n{addr}");
|
||||
let conn = hub.accept().await.context("accept")?.await?;
|
||||
send(conn, &o).await?;
|
||||
}
|
||||
"connect" => {
|
||||
let addr = target.context("connect needs the address serve printed")?;
|
||||
let addr: iroh::EndpointAddr =
|
||||
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(addr.as_bytes())?)?;
|
||||
let client = endpoint(false).await?;
|
||||
let conn = client.connect(addr, ALPN_VIDEO).await?;
|
||||
receive(conn).await?;
|
||||
}
|
||||
other => bail!("unknown mode {other}"),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -7,19 +7,35 @@ use std::fmt;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use bytes::BytesMut;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use iroh::endpoint::{Connection, QuicTransportConfig, SendDatagramError};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use crate::keyframe::KeyframeSender;
|
||||
use crate::pyro::PyroSender;
|
||||
|
||||
use nesprotocol::MSG_DATA;
|
||||
use nesprotocol::datagram::{
|
||||
DGRAM_BUFFER_BYTES, DGRAM_HDR_LEN, MAX_FRAGMENTS_PER_FRAME, MIN_DGRAM_PAYLOAD, fragment_count,
|
||||
write_datagram_header,
|
||||
};
|
||||
use nesprotocol::pyrowave::PyroFrame;
|
||||
use nesprotocol::reliable::video_wants_reliable;
|
||||
|
||||
/// What a session's media writer is handed.
|
||||
///
|
||||
/// Both are refcounted, so a frame broadcast to several clients is shared
|
||||
/// rather than copied per client — which at PyroWave's frame sizes stops being
|
||||
/// a rounding error.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum MediaItem {
|
||||
/// A hardware-codec frame or an audio packet, laid out as the hub
|
||||
/// broadcasts it.
|
||||
Coded(Bytes),
|
||||
/// A whole PyroWave frame, which travels by rules of its own.
|
||||
PyroWave(Arc<PyroFrame>),
|
||||
}
|
||||
|
||||
/// Transport settings for an endpoint carrying media datagrams.
|
||||
///
|
||||
/// See [`DGRAM_BUFFER_BYTES`] for why the defaults are not enough.
|
||||
@@ -225,7 +241,7 @@ pub async fn run_datagram_writer(
|
||||
conn: Connection,
|
||||
kind: u8,
|
||||
label: &'static str,
|
||||
mut rx: tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>,
|
||||
mut rx: tokio::sync::mpsc::UnboundedReceiver<MediaItem>,
|
||||
relay_ms: Option<Arc<AtomicU32>>,
|
||||
keyframes_reliable: bool,
|
||||
// Set while this client has asked for a keyframe and not yet been sent
|
||||
@@ -234,7 +250,10 @@ pub async fn run_datagram_writer(
|
||||
// Counts frames withheld during a resynchronisation, so the bitrate
|
||||
// controller can tell a second it starved from a second the path did.
|
||||
withheld: Option<Arc<std::sync::atomic::AtomicU64>>,
|
||||
// Counts PyroWave frames skipped for want of room. Video only.
|
||||
pyro_skipped: Option<Arc<std::sync::atomic::AtomicU64>>,
|
||||
) {
|
||||
let mut pyro = pyro_skipped.map(|skipped| PyroSender::new(conn.clone(), skipped));
|
||||
let sender = DatagramSender::new(conn.clone(), kind);
|
||||
let keyframes = keyframes_reliable.then(|| KeyframeSender::new(conn, sender.clone()));
|
||||
let mut seq: u16 = 0;
|
||||
@@ -245,8 +264,25 @@ pub async fn run_datagram_writer(
|
||||
let mut warned_unsupported = false;
|
||||
let mut resync = ResyncGate::default();
|
||||
|
||||
while let Some(payload) = rx.recv().await {
|
||||
while let Some(item) = rx.recv().await {
|
||||
let t0 = std::time::Instant::now();
|
||||
let payload = match item {
|
||||
MediaItem::Coded(payload) => payload,
|
||||
// No keyframe stream and no resync gate: every PyroWave frame
|
||||
// stands alone, so there is nothing to resynchronise and no frame
|
||||
// worth a reliable stream more than another.
|
||||
MediaItem::PyroWave(frame) => {
|
||||
match pyro.as_mut() {
|
||||
Some(pyro) => pyro.send(&frame, label),
|
||||
None => debug!("{label}: a PyroWave frame on a carrier that has none"),
|
||||
}
|
||||
if let Some(ref relay) = relay_ms {
|
||||
let elapsed = t0.elapsed().as_secs_f32() * 1000.0;
|
||||
relay.store(elapsed.to_bits(), Ordering::Relaxed);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
};
|
||||
body.clear();
|
||||
nesprotocol::encode_frame_body(&mut body, MSG_DATA, seq, &payload);
|
||||
|
||||
|
||||
@@ -0,0 +1,311 @@
|
||||
//! PyroWave through the hub for real: IPC messages into the video listener,
|
||||
//! out of the datagram writer, over an iroh connection, into a collector.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use bytes::Bytes;
|
||||
use iroh::endpoint::{Connection, presets};
|
||||
use tokio::net::UnixDatagram;
|
||||
|
||||
use nesprotocol::pyrowave::{
|
||||
CollectedFrame, FLAG_DUPLICATE, FrameMeta, PyroCollector, PyroDatagramHeader, PyroFrame,
|
||||
chunk_frame, decode_pyro_datagram,
|
||||
};
|
||||
use nesprotocol::{ALPN_VIDEO, Carrier};
|
||||
|
||||
use crate::control::{Controller, Limits};
|
||||
use crate::session::SessionManager;
|
||||
|
||||
/// A frame of synthetic packets, each filled with bytes particular to it, so
|
||||
/// a packet delivered into the wrong place or the wrong frame shows. Packet 0
|
||||
/// stands in for the sequence header; one in every fifty is an oversized
|
||||
/// block that has to travel in pieces.
|
||||
pub(crate) fn synthetic_frame(id: u32, bytes: usize, packet: usize) -> PyroFrame {
|
||||
let mut data = Vec::with_capacity(bytes);
|
||||
let mut packets = Vec::new();
|
||||
let mut i = 0usize;
|
||||
while data.len() < bytes {
|
||||
let len = match i {
|
||||
0 => 8,
|
||||
_ if i.is_multiple_of(50) => nesprotocol::pyrowave::LARGEST_BLOCK_BYTES,
|
||||
_ => packet - (i * 13) % 200,
|
||||
};
|
||||
let start = data.len();
|
||||
let seed = (id as usize).wrapping_mul(7919) ^ i;
|
||||
data.extend((0..len).map(|k| (seed.wrapping_mul(31).wrapping_add(k) % 251) as u8));
|
||||
packets.push(start..data.len());
|
||||
i += 1;
|
||||
}
|
||||
PyroFrame {
|
||||
frame: id,
|
||||
meta: FrameMeta {
|
||||
ts_ms: id * 16,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
},
|
||||
critical: 3,
|
||||
data,
|
||||
packets,
|
||||
}
|
||||
}
|
||||
|
||||
struct Rig {
|
||||
socket_path: PathBuf,
|
||||
sender: UnixDatagram,
|
||||
client: Connection,
|
||||
mgr: Arc<SessionManager>,
|
||||
_hub: iroh::Endpoint,
|
||||
_client_ep: iroh::Endpoint,
|
||||
}
|
||||
|
||||
impl Drop for Rig {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_file(&self.socket_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// `client_buffer` sizes the client's datagram receive buffer; `None` is the
|
||||
/// client's real one.
|
||||
async fn rig_with(client_buffer: Option<usize>) -> Rig {
|
||||
static NEXT: AtomicU32 = AtomicU32::new(0);
|
||||
let socket_path = std::env::temp_dir().join(format!(
|
||||
"neshub-e2e-{}-{}.sock",
|
||||
std::process::id(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
let mgr = Arc::new(SessionManager::new(300_000));
|
||||
tokio::spawn({
|
||||
let mgr = mgr.clone();
|
||||
let path = socket_path.clone();
|
||||
async move { crate::ipc_listener::run_video_listener(path, mgr).await }
|
||||
});
|
||||
|
||||
let hub = iroh::Endpoint::builder(presets::N0)
|
||||
.alpns(vec![ALPN_VIDEO.to_vec()])
|
||||
.relay_mode(iroh::endpoint::RelayMode::Disabled)
|
||||
.transport_config(crate::dgram::media_transport_config())
|
||||
.bind()
|
||||
.await
|
||||
.expect("hub endpoint");
|
||||
let client_transport = match client_buffer {
|
||||
Some(bytes) => iroh::endpoint::QuicTransportConfig::builder()
|
||||
.datagram_send_buffer_size(nesprotocol::datagram::DGRAM_BUFFER_BYTES)
|
||||
.datagram_receive_buffer_size(Some(bytes))
|
||||
.build(),
|
||||
None => crate::dgram::media_transport_config(),
|
||||
};
|
||||
let client_ep = iroh::Endpoint::builder(presets::N0)
|
||||
.relay_mode(iroh::endpoint::RelayMode::Disabled)
|
||||
.transport_config(client_transport)
|
||||
.bind()
|
||||
.await
|
||||
.expect("client endpoint");
|
||||
|
||||
let accept = tokio::spawn({
|
||||
let hub = hub.clone();
|
||||
let mgr = mgr.clone();
|
||||
async move {
|
||||
let conn = hub.accept().await.expect("incoming").await.expect("conn");
|
||||
let (input, _) = tokio::sync::broadcast::channel(4);
|
||||
let (cmd, _cmd_rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let controller = Arc::new(tokio::sync::Mutex::new(Controller::new(Limits::new(4_000))));
|
||||
mgr.attach(
|
||||
conn.remote_id(),
|
||||
Carrier::Video,
|
||||
conn,
|
||||
input,
|
||||
cmd,
|
||||
controller,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
let client = client_ep
|
||||
.connect(hub.addr(), ALPN_VIDEO)
|
||||
.await
|
||||
.expect("dial the hub");
|
||||
accept.await.expect("accept");
|
||||
|
||||
// The listener binds on its own task; wait for the socket to exist.
|
||||
let sender = UnixDatagram::unbound().expect("unbound socket");
|
||||
for _ in 0..200 {
|
||||
if socket_path.exists() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(5)).await;
|
||||
}
|
||||
sender
|
||||
.connect(&socket_path)
|
||||
.expect("connect to the listener");
|
||||
|
||||
Rig {
|
||||
socket_path,
|
||||
sender,
|
||||
client,
|
||||
mgr,
|
||||
_hub: hub,
|
||||
_client_ep: client_ep,
|
||||
}
|
||||
}
|
||||
|
||||
async fn rig() -> Rig {
|
||||
rig_with(None).await
|
||||
}
|
||||
|
||||
async fn send_frame(sender: &UnixDatagram, f: &PyroFrame) {
|
||||
for m in chunk_frame(f.frame, f.meta, &f.data, &f.packets, f.critical).expect("chunks") {
|
||||
sender.send(&m).await.expect("ipc send");
|
||||
}
|
||||
}
|
||||
|
||||
/// Read datagrams until `want` frames have come out of the collector or the
|
||||
/// line goes quiet. `drop_datagram` decides, by arrival order and header,
|
||||
/// which ones the "network" loses.
|
||||
async fn collect(
|
||||
conn: &Connection,
|
||||
want: usize,
|
||||
mut drop_datagram: impl FnMut(usize, &PyroDatagramHeader) -> bool,
|
||||
) -> Vec<CollectedFrame<Bytes>> {
|
||||
let start = Instant::now();
|
||||
let now = || start.elapsed().as_micros() as u64;
|
||||
let mut collector = PyroCollector::new();
|
||||
let mut frames = Vec::new();
|
||||
let mut arrivals = 0usize;
|
||||
while frames.len() < want {
|
||||
let datagram =
|
||||
match tokio::time::timeout(Duration::from_millis(500), conn.read_datagram()).await {
|
||||
Ok(Ok(d)) => d,
|
||||
Ok(Err(e)) => panic!("connection failed: {e}"),
|
||||
Err(_) => break,
|
||||
};
|
||||
arrivals += 1;
|
||||
let (h, payload) = decode_pyro_datagram(&datagram).expect("a PyroWave datagram");
|
||||
if drop_datagram(arrivals, &h) {
|
||||
continue;
|
||||
}
|
||||
let at = datagram.len() - payload.len();
|
||||
frames.extend(collector.push(h, datagram.slice(at..), now()));
|
||||
}
|
||||
// Whatever is still in flight leaves at its deadline.
|
||||
frames.extend(collector.poll(u64::MAX));
|
||||
frames
|
||||
}
|
||||
|
||||
fn packets(f: &CollectedFrame<Bytes>) -> Vec<Vec<u8>> {
|
||||
f.packets.iter().map(|p| p.as_ref().to_vec()).collect()
|
||||
}
|
||||
|
||||
fn originals(f: &PyroFrame) -> Vec<Vec<u8>> {
|
||||
(0..f.packets.len()).map(|i| f.packet(i).to_vec()).collect()
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn frames_cross_the_hub_byte_for_byte() {
|
||||
let rig = rig().await;
|
||||
let sent: Vec<_> = (0..20).map(|i| synthetic_frame(i, 120_000, 1188)).collect();
|
||||
let reader = tokio::spawn({
|
||||
let conn = rig.client.clone();
|
||||
async move { collect(&conn, 20, |_, _| false).await }
|
||||
});
|
||||
for f in &sent {
|
||||
send_frame(&rig.sender, f).await;
|
||||
// About 60 Mbit/s: this is about the bytes, not about how fast they
|
||||
// go, and an unoptimised build's QUIC cannot carry much more. The
|
||||
// bench is where rates are measured.
|
||||
tokio::time::sleep(Duration::from_millis(16)).await;
|
||||
}
|
||||
let got = reader.await.expect("reader");
|
||||
|
||||
assert_eq!(
|
||||
rig.mgr.take_pyro_skipped().await,
|
||||
0,
|
||||
"a quiet path skipped frames"
|
||||
);
|
||||
assert_eq!(got.len(), sent.len());
|
||||
for (i, (g, s)) in got.iter().zip(&sent).enumerate() {
|
||||
assert!(g.is_whole(), "frame {i}: {}/{}", g.received, g.total);
|
||||
assert_eq!(g.seq, i as u16);
|
||||
assert_eq!(g.ts_ms, s.meta.ts_ms);
|
||||
assert_eq!(packets(g), originals(s), "frame {i} changed in transit");
|
||||
}
|
||||
}
|
||||
|
||||
/// With datagrams lost, what arrives is still exactly what was sent, minus
|
||||
/// the lost packets — never a packet stitched from two, never one from
|
||||
/// another frame — and the critical copies stand in for lost originals.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_lossy_path_loses_packets_and_nothing_else() {
|
||||
let rig = rig().await;
|
||||
let sent: Vec<_> = (0..20).map(|i| synthetic_frame(i, 120_000, 1188)).collect();
|
||||
let reader = tokio::spawn({
|
||||
let conn = rig.client.clone();
|
||||
// One in 37: about 4% loss, landing on every position in turn, the
|
||||
// critical datagrams at the head of a frame included. Copies are
|
||||
// spared, so that a lost critical original is always covered and the
|
||||
// assertion below can be exact.
|
||||
async move {
|
||||
collect(&conn, 20, |n, h| {
|
||||
h.flags & FLAG_DUPLICATE == 0 && n.is_multiple_of(37)
|
||||
})
|
||||
.await
|
||||
}
|
||||
});
|
||||
for f in &sent {
|
||||
send_frame(&rig.sender, f).await;
|
||||
tokio::time::sleep(Duration::from_millis(16)).await;
|
||||
}
|
||||
let got = reader.await.expect("reader");
|
||||
assert_eq!(got.len(), sent.len());
|
||||
|
||||
let mut partial = 0;
|
||||
for (g, s) in got.iter().zip(&sent) {
|
||||
let all = originals(s);
|
||||
let got = packets(g);
|
||||
// Every critical packet arrives: the copies cover a single loss.
|
||||
assert_eq!(&got[..s.critical], &all[..s.critical], "frame {}", s.frame);
|
||||
// And what arrived is an ordered subset of what was sent.
|
||||
let mut rest = all.iter();
|
||||
for p in &got {
|
||||
assert!(
|
||||
rest.any(|o| o == p),
|
||||
"frame {}: a packet arrived that was never sent",
|
||||
s.frame
|
||||
);
|
||||
}
|
||||
partial += usize::from(!g.is_whole());
|
||||
}
|
||||
assert!(partial > 0, "the loss never reached the collector");
|
||||
}
|
||||
|
||||
/// Handed frames faster than the path drains them, the hub skips whole
|
||||
/// frames rather than letting QUIC evict pieces of two.
|
||||
///
|
||||
/// The client's receive buffer is made larger than the whole burst, so a
|
||||
/// torn frame here can only be the sender's doing: a client too slow to read
|
||||
/// tears frames too, by its own buffer's eviction, and that is not what this
|
||||
/// is about.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_burst_is_skipped_whole_not_torn() {
|
||||
let rig = rig_with(Some(64 << 20)).await;
|
||||
let n = 30u32;
|
||||
let reader = tokio::spawn({
|
||||
let conn = rig.client.clone();
|
||||
async move { collect(&conn, n as usize, |_, _| false).await }
|
||||
});
|
||||
for i in 0..n {
|
||||
send_frame(&rig.sender, &synthetic_frame(i, 1_500_000, 1188)).await;
|
||||
}
|
||||
let got = reader.await.expect("reader");
|
||||
let skipped = rig.mgr.take_pyro_skipped().await as usize;
|
||||
|
||||
let torn = got.iter().filter(|f| !f.is_whole()).count();
|
||||
assert_eq!(torn, 0, "{torn} frames arrived damaged ({skipped} skipped)");
|
||||
assert_eq!(
|
||||
got.len() + skipped,
|
||||
n as usize,
|
||||
"frames went missing unaccounted"
|
||||
);
|
||||
}
|
||||
@@ -4,9 +4,11 @@ use std::sync::Arc;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{UnixDatagram, UnixListener};
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
use tracing::debug;
|
||||
|
||||
use crate::session::SessionManager;
|
||||
use nesprotocol::{CODEC_OPUS, STREAM_AUDIO, STREAM_VIDEO, decode_ipc_frame};
|
||||
use nesprotocol::pyrowave::FrameAssembler;
|
||||
use nesprotocol::{CODEC_OPUS, STREAM_AUDIO, STREAM_PYROWAVE, STREAM_VIDEO, decode_ipc_frame};
|
||||
|
||||
fn set_recv_buffer(socket: &UnixDatagram, size: libc::c_int) {
|
||||
unsafe {
|
||||
@@ -46,10 +48,28 @@ pub async fn run_video_listener(socket_path: PathBuf, session_manager: Arc<Sessi
|
||||
tracing::info!("Video IPC listening on {}", socket_path.display());
|
||||
|
||||
let mut buf = vec![0u8; 2 * 1024 * 1024];
|
||||
// PyroWave frames arrive as runs of messages; see `nesprotocol::pyrowave`.
|
||||
let mut pyrowave = FrameAssembler::new();
|
||||
let started = std::time::Instant::now();
|
||||
loop {
|
||||
match socket.recv(&mut buf).await {
|
||||
Ok(n) => {
|
||||
if let Some(decoded) = decode_ipc_frame(&buf[..n]) {
|
||||
if decoded.stream_type == STREAM_PYROWAVE {
|
||||
let now_ms = started.elapsed().as_millis() as u64;
|
||||
match pyrowave.push(&decoded, now_ms) {
|
||||
Ok(Some(frame)) => session_manager.broadcast_pyrowave(frame).await,
|
||||
Ok(None) => {}
|
||||
Err(e) => debug!("dropping a PyroWave IPC message: {e}"),
|
||||
}
|
||||
// Per frame, so debug: an encoder whose writes keep
|
||||
// timing out would say this sixty times a second.
|
||||
let abandoned = pyrowave.take_abandoned();
|
||||
if abandoned > 0 {
|
||||
debug!("abandoned {abandoned} PyroWave frame(s) missing a message");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if decoded.stream_type != STREAM_VIDEO {
|
||||
tracing::warn!(
|
||||
"unexpected stream type on video socket: {}",
|
||||
|
||||
+119
-2
@@ -1,7 +1,10 @@
|
||||
mod control;
|
||||
mod dgram;
|
||||
#[cfg(test)]
|
||||
mod e2e_tests;
|
||||
mod ipc_listener;
|
||||
mod keyframe;
|
||||
mod pyro;
|
||||
mod screenshot;
|
||||
mod session;
|
||||
mod ticket;
|
||||
@@ -84,6 +87,15 @@ struct Args {
|
||||
#[arg(long, env = "NESTRI_MAX_BITRATE")]
|
||||
max_bitrate_kbps: Option<u32>,
|
||||
|
||||
/// The PyroWave rate, in kbps, for a client that asks for PyroWave without
|
||||
/// naming one.
|
||||
///
|
||||
/// PyroWave is the LAN codec and runs at a set rate, outside the bitrate
|
||||
/// controller and above the ceiling: it is only ever used because a client
|
||||
/// asked for it.
|
||||
#[arg(long, env = "NESTRI_PYROWAVE_KBPS", default_value_t = 300_000)]
|
||||
pyrowave_kbps: u32,
|
||||
|
||||
/// Path for the gamepad IPC socket (neshub ↔ nesgamepad). neshub
|
||||
/// listens; the gamepad service dials in.
|
||||
#[arg(
|
||||
@@ -110,6 +122,41 @@ struct Args {
|
||||
/// chosen and the encoder's own default stood in for one.
|
||||
const DEFAULT_MAX_BITRATE_KBPS: u32 = 4_000;
|
||||
|
||||
/// What a PyroWave packet is sized to with no client to measure: a datagram
|
||||
/// at QUIC's minimum MTU always carries this much.
|
||||
const FALLBACK_PYRO_PACKET_BYTES: usize = 1100;
|
||||
|
||||
/// Name the PyroWave packet size in an encode command bound for nescapture.
|
||||
///
|
||||
/// Filled in here, as the command leaves, because what fits a datagram is a
|
||||
/// fact about the path *now*. Any other command passes untouched.
|
||||
fn fill_pyrowave_packet_size(cmd: &mut Vec<u8>, limit: Option<usize>) {
|
||||
if cmd.first() != Some(&nesprotocol::MSG_ENCODE_SETTINGS) {
|
||||
return;
|
||||
}
|
||||
let Some(mut settings) = nesprotocol::decode_encode_settings_ext(&cmd[1..]) else {
|
||||
return;
|
||||
};
|
||||
if settings.codec != nesprotocol::CODEC_PYROWAVE {
|
||||
return;
|
||||
}
|
||||
let size = limit
|
||||
.unwrap_or(FALLBACK_PYRO_PACKET_BYTES)
|
||||
.min(usize::from(u16::MAX));
|
||||
settings.packet_size = Some(size as u16);
|
||||
// Every field before it has to be present for it to be read.
|
||||
settings.bit_depth.get_or_insert(nesprotocol::DEPTH_8);
|
||||
settings
|
||||
.chroma
|
||||
.get_or_insert(nesprotocol::pyrowave::CHROMA_420);
|
||||
cmd.truncate(1);
|
||||
nesprotocol::encode_settings(cmd, &settings);
|
||||
tracing::info!(
|
||||
"PyroWave at {} kbps, packets of {size} bytes",
|
||||
settings.value
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
tracing_subscriber::fmt()
|
||||
@@ -169,7 +216,7 @@ async fn main() -> Result<()> {
|
||||
let (nescope_stats_tx, mut nescope_stats_rx) =
|
||||
tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
|
||||
|
||||
let session_manager = Arc::new(SessionManager::new());
|
||||
let session_manager = Arc::new(SessionManager::new(args.pyrowave_kbps));
|
||||
|
||||
// One controller for the box, not one per client: there is one encoder, so
|
||||
// there is one bitrate, and the client having the worst time is the one it
|
||||
@@ -182,9 +229,11 @@ async fn main() -> Result<()> {
|
||||
// IDR / encode settings command channel: input reader → nescapture
|
||||
let (cmd_tx, mut cmd_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
|
||||
{
|
||||
let mgr = session_manager.clone();
|
||||
tokio::spawn(async move {
|
||||
let cmd_path = std::path::PathBuf::from("/tmp/nescapture-cmd.sock");
|
||||
while let Some(bytes) = cmd_rx.recv().await {
|
||||
while let Some(mut bytes) = cmd_rx.recv().await {
|
||||
fill_pyrowave_packet_size(&mut bytes, mgr.pyro_packet_size().await);
|
||||
if let Ok(sock) = std::os::unix::net::UnixDatagram::unbound() {
|
||||
if sock.send_to(&bytes, &cmd_path).is_err() {
|
||||
tracing::warn!("nescapture cmd send failed at {}", cmd_path.display());
|
||||
@@ -262,6 +311,7 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
|
||||
let mut interval = tokio::time::interval(std::time::Duration::from_secs(1));
|
||||
let mut pyro_skipping = false;
|
||||
loop {
|
||||
interval.tick().await;
|
||||
|
||||
@@ -291,6 +341,22 @@ async fn main() -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
// Said when skipping starts and when it stops, and otherwise
|
||||
// only at debug: a path that cannot carry the rate skips every
|
||||
// second until somebody lowers it.
|
||||
let skipped = mgr.take_pyro_skipped().await;
|
||||
if skipped > 0 && !pyro_skipping {
|
||||
tracing::warn!(
|
||||
"skipping PyroWave frames: the path is not carrying the rate \
|
||||
({skipped} this second)"
|
||||
);
|
||||
} else if skipped == 0 && pyro_skipping {
|
||||
tracing::info!("no longer skipping PyroWave frames");
|
||||
} else if skipped > 0 {
|
||||
tracing::debug!("{skipped} PyroWave frames skipped this second");
|
||||
}
|
||||
pyro_skipping = skipped > 0;
|
||||
|
||||
let clients = mgr.client_count().await as u8;
|
||||
let (key_bps, delta_bps, keyframes) = mgr.video_breakdown();
|
||||
let (pipeline_p50_ms, pipeline_p95_ms, pipeline_max_ms) = mgr.pipeline_delays();
|
||||
@@ -469,3 +535,54 @@ async fn main() -> Result<()> {
|
||||
let _ = std::fs::remove_file(&args.ticket_ipc);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{FALLBACK_PYRO_PACKET_BYTES, fill_pyrowave_packet_size};
|
||||
use nesprotocol::{
|
||||
CODEC_AV1, CODEC_PYROWAVE, EncodeSettings, MSG_ENCODE_SETTINGS, MSG_IDR_REQUEST, RC_CBR,
|
||||
};
|
||||
|
||||
fn command(codec: u8) -> Vec<u8> {
|
||||
let mut cmd = vec![MSG_ENCODE_SETTINGS];
|
||||
nesprotocol::encode_settings(
|
||||
&mut cmd,
|
||||
&EncodeSettings {
|
||||
codec,
|
||||
rate_control: RC_CBR,
|
||||
value: 300_000,
|
||||
bit_depth: Some(0),
|
||||
chroma: Some(1),
|
||||
packet_size: None,
|
||||
},
|
||||
);
|
||||
cmd
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pyrowave_command_leaves_with_the_paths_packet_size() {
|
||||
let mut cmd = command(CODEC_PYROWAVE);
|
||||
fill_pyrowave_packet_size(&mut cmd, Some(1440));
|
||||
let s = nesprotocol::decode_encode_settings_ext(&cmd[1..]).unwrap();
|
||||
assert_eq!(s.packet_size, Some(1440));
|
||||
assert_eq!(
|
||||
(s.value, s.chroma),
|
||||
(300_000, Some(1)),
|
||||
"nothing else moved"
|
||||
);
|
||||
|
||||
let mut cmd = command(CODEC_PYROWAVE);
|
||||
fill_pyrowave_packet_size(&mut cmd, None);
|
||||
let s = nesprotocol::decode_encode_settings_ext(&cmd[1..]).unwrap();
|
||||
assert_eq!(s.packet_size, Some(FALLBACK_PYRO_PACKET_BYTES as u16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_other_command_passes_untouched() {
|
||||
for cmd in [command(CODEC_AV1), vec![MSG_IDR_REQUEST], vec![]] {
|
||||
let mut sent = cmd.clone();
|
||||
fill_pyrowave_packet_size(&mut sent, Some(1440));
|
||||
assert_eq!(sent, cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
//! Sending PyroWave frames.
|
||||
//!
|
||||
//! See `nesprotocol::pyrowave` for the wire and why PyroWave has a path of its
|
||||
//! own. This is the hub's half: pack each frame as one packet per datagram and
|
||||
//! decide whether to send it at all.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use bytes::Bytes;
|
||||
use iroh::endpoint::Connection;
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use nesprotocol::datagram::DGRAM_BUFFER_BYTES;
|
||||
use nesprotocol::pyrowave::{PYRO_DGRAM_HDR_LEN, PyroFrame, Skip, pack_datagrams, should_skip};
|
||||
|
||||
/// One connection's PyroWave sender.
|
||||
pub struct PyroSender {
|
||||
conn: Connection,
|
||||
/// Its own counter, apart from the hardware frames': a receiver collects
|
||||
/// each kind by its own sequence.
|
||||
seq: u16,
|
||||
skipped: Arc<AtomicU64>,
|
||||
warned_too_large: bool,
|
||||
}
|
||||
|
||||
impl PyroSender {
|
||||
pub fn new(conn: Connection, skipped: Arc<AtomicU64>) -> Self {
|
||||
Self {
|
||||
conn,
|
||||
seq: 0,
|
||||
skipped,
|
||||
warned_too_large: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Send one frame, or skip it.
|
||||
///
|
||||
/// A skipped frame does not use up a sequence number: nothing went out
|
||||
/// under it, and a hole would read at the far end as a frame the path
|
||||
/// lost.
|
||||
pub fn send(&mut self, frame: &PyroFrame, label: &str) {
|
||||
let Some(max) = self.conn.max_datagram_size() else {
|
||||
debug!("{label}: peer does not support QUIC datagrams");
|
||||
return;
|
||||
};
|
||||
let datagrams = match pack_datagrams(self.seq, frame, max) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
debug!("{label}: dropping PyroWave frame {}: {e}", frame.frame);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let backlog = DGRAM_BUFFER_BYTES.saturating_sub(self.conn.datagram_send_buffer_space());
|
||||
if let Some(skip) = should_skip(backlog, datagrams.buf.len(), DGRAM_BUFFER_BYTES) {
|
||||
self.skipped.fetch_add(1, Ordering::Relaxed);
|
||||
if skip == Skip::TooLarge && !self.warned_too_large {
|
||||
warn!(
|
||||
"{label}: a {} byte PyroWave frame cannot fit the {DGRAM_BUFFER_BYTES} byte \
|
||||
send buffer; frames this size are never sent. Lower the rate.",
|
||||
datagrams.buf.len()
|
||||
);
|
||||
self.warned_too_large = true;
|
||||
} else {
|
||||
debug!("{label}: skipped PyroWave frame {}: {skip:?}", frame.frame);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Taking the `Vec` is free, and each datagram is a slice of it.
|
||||
let buf = Bytes::from(datagrams.buf);
|
||||
let mut at = 0;
|
||||
for len in datagrams.lens {
|
||||
debug_assert!(len >= PYRO_DGRAM_HDR_LEN);
|
||||
let datagram = buf.slice(at..at + len);
|
||||
at += len;
|
||||
// Not `send_datagram_wait`, for the reason `dgram::send_frame`
|
||||
// gives; the guard above is what keeps this from evicting.
|
||||
if let Err(e) = self.conn.send_datagram(datagram) {
|
||||
debug!("{label}: PyroWave frame {} cut short: {e}", frame.frame);
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.seq = self.seq.wrapping_add(1);
|
||||
}
|
||||
}
|
||||
+241
-27
@@ -3,7 +3,7 @@ use std::sync::Arc;
|
||||
|
||||
use iroh::endpoint::Connection;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{debug, info};
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
use nesprotocol::datagram::{DGRAM_AUDIO, DGRAM_BUFFER_BYTES, DGRAM_VIDEO};
|
||||
use nesprotocol::input::{INPUT_KEY, INPUT_MOUSE_BUTTON, INPUT_MOUSE_MOVE, INPUT_MOUSE_WHEEL};
|
||||
@@ -17,7 +17,9 @@ use nesprotocol::{
|
||||
|
||||
use crate::control::{Controller, PathView};
|
||||
|
||||
use crate::dgram::run_datagram_writer;
|
||||
use crate::dgram::{MediaItem, run_datagram_writer};
|
||||
use bytes::Bytes;
|
||||
use nesprotocol::pyrowave::PyroFrame;
|
||||
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
|
||||
@@ -58,6 +60,13 @@ pub struct ClientSession {
|
||||
/// Overwritten rather than queued. A report describes the second that just
|
||||
/// passed, and an older one is not evidence about now.
|
||||
latest_report: Arc<std::sync::Mutex<Option<ReceiverReport>>>,
|
||||
/// PyroWave frames this client was not sent because its queue was full.
|
||||
pyro_skipped: Arc<AtomicU64>,
|
||||
/// Whether this client said it decodes the PyroWave format this hub
|
||||
/// carries. Only then is a request for PyroWave passed on.
|
||||
pyrowave_ok: Arc<AtomicBool>,
|
||||
/// The rate a PyroWave request that names none runs at.
|
||||
pyrowave_kbps: u32,
|
||||
relay_ms: Arc<AtomicU32>,
|
||||
input_broadcast: tokio::sync::broadcast::Sender<Vec<u8>>,
|
||||
/// This client's number on the gamepad socket, so the box's side can tell
|
||||
@@ -70,13 +79,13 @@ pub struct ClientSession {
|
||||
pending_gamepad_feedback: Option<tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>>,
|
||||
idr_cmd_tx: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
|
||||
controller: Arc<Mutex<Controller>>,
|
||||
send_video: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
|
||||
send_audio: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
|
||||
send_video: tokio::sync::mpsc::UnboundedSender<MediaItem>,
|
||||
send_audio: tokio::sync::mpsc::UnboundedSender<MediaItem>,
|
||||
send_cursor: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
|
||||
send_stats: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
|
||||
/// Receiving ends, held until the carrier that drains them connects.
|
||||
pending_video: Option<tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>>,
|
||||
pending_audio: Option<tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>>,
|
||||
pending_video: Option<tokio::sync::mpsc::UnboundedReceiver<MediaItem>>,
|
||||
pending_audio: Option<tokio::sync::mpsc::UnboundedReceiver<MediaItem>>,
|
||||
pending_cursor: Option<tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>>,
|
||||
pending_stats: Option<tokio::sync::mpsc::UnboundedReceiver<Vec<u8>>>,
|
||||
tasks: Vec<tokio::task::JoinHandle<()>>,
|
||||
@@ -105,10 +114,11 @@ impl ClientSession {
|
||||
relay_ms: Arc<AtomicU32>,
|
||||
idr_cmd_tx: tokio::sync::mpsc::UnboundedSender<Vec<u8>>,
|
||||
controller: Arc<Mutex<Controller>>,
|
||||
pyrowave_kbps: u32,
|
||||
) -> Self {
|
||||
let (gamepad_feedback_tx, gamepad_feedback_rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
let (video_tx, video_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
|
||||
let (audio_tx, audio_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
|
||||
let (video_tx, video_rx) = tokio::sync::mpsc::unbounded_channel::<MediaItem>();
|
||||
let (audio_tx, audio_rx) = tokio::sync::mpsc::unbounded_channel::<MediaItem>();
|
||||
let (cursor_tx, cursor_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
|
||||
let (stats_tx, stats_rx) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
|
||||
Self {
|
||||
@@ -117,6 +127,9 @@ impl ClientSession {
|
||||
awaiting_keyframe: Arc::new(AtomicBool::new(false)),
|
||||
withheld: Arc::new(AtomicU64::new(0)),
|
||||
latest_report: Arc::new(std::sync::Mutex::new(None)),
|
||||
pyro_skipped: Arc::new(AtomicU64::new(0)),
|
||||
pyrowave_ok: Arc::new(AtomicBool::new(false)),
|
||||
pyrowave_kbps,
|
||||
relay_ms,
|
||||
input_broadcast,
|
||||
gamepad_session,
|
||||
@@ -161,6 +174,7 @@ impl ClientSession {
|
||||
let relay_ms = self.relay_ms.clone();
|
||||
let awaiting = self.awaiting_keyframe.clone();
|
||||
let withheld = self.withheld.clone();
|
||||
let pyro_skipped = self.pyro_skipped.clone();
|
||||
// Keyframes go on reliable streams of their own, because a lost
|
||||
// keyframe freezes the picture until the next one instead of
|
||||
// costing a single frame. See `nesprotocol::reliable`.
|
||||
@@ -174,6 +188,7 @@ impl ClientSession {
|
||||
true,
|
||||
Some(awaiting),
|
||||
Some(withheld),
|
||||
Some(pyro_skipped),
|
||||
)
|
||||
.await
|
||||
}));
|
||||
@@ -187,8 +202,18 @@ impl ClientSession {
|
||||
// No reliable path offered: audio has no keyframes to promote,
|
||||
// and on its own connection it is no longer queued behind any.
|
||||
self.tasks.push(tokio::spawn(async move {
|
||||
run_datagram_writer(conn, DGRAM_AUDIO, "audio", rx, None, false, None, None)
|
||||
.await
|
||||
run_datagram_writer(
|
||||
conn,
|
||||
DGRAM_AUDIO,
|
||||
"audio",
|
||||
rx,
|
||||
None,
|
||||
false,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}));
|
||||
}
|
||||
Carrier::Input => {
|
||||
@@ -226,8 +251,12 @@ impl ClientSession {
|
||||
let awaiting = self.awaiting_keyframe.clone();
|
||||
let idr = self.idr_cmd_tx.clone();
|
||||
let controller = self.controller.clone();
|
||||
let pyrowave = PyroWaveGate {
|
||||
ok: self.pyrowave_ok.clone(),
|
||||
default_kbps: self.pyrowave_kbps,
|
||||
};
|
||||
self.tasks.push(tokio::spawn(async move {
|
||||
run_control_reader(conn, idr, reports, controller, awaiting).await
|
||||
run_control_reader(conn, idr, reports, controller, awaiting, pyrowave).await
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -247,6 +276,17 @@ impl ClientSession {
|
||||
self.latest_report.lock().ok()?.take()
|
||||
}
|
||||
|
||||
/// PyroWave frames skipped since the last call, cleared as it is read.
|
||||
pub fn take_pyro_skipped(&self) -> u64 {
|
||||
self.pyro_skipped.swap(0, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// The largest PyroWave packet one of this client's datagrams carries now.
|
||||
pub fn pyro_packet_limit(&self) -> Option<usize> {
|
||||
let max = self.video_conn.as_ref()?.max_datagram_size()?;
|
||||
Some(max.saturating_sub(nesprotocol::pyrowave::PYRO_DGRAM_HDR_LEN))
|
||||
}
|
||||
|
||||
/// What this end can see of the path, from the route actually in use.
|
||||
///
|
||||
/// A connection can hold several paths at once -- typically one through a
|
||||
@@ -284,14 +324,14 @@ impl ClientSession {
|
||||
/// only way it fails is a closed channel, which means the writer is already
|
||||
/// gone, and sixty warnings a second on the way down bury whatever actually
|
||||
/// ended the session.
|
||||
pub fn send_video_frame(&self, data: Vec<u8>) {
|
||||
if let Err(e) = self.send_video.send(data) {
|
||||
pub fn send_video_frame(&self, item: MediaItem) {
|
||||
if let Err(e) = self.send_video.send(item) {
|
||||
debug!("failed to send video data: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_audio_packet(&self, data: Vec<u8>) {
|
||||
if let Err(e) = self.send_audio.send(data) {
|
||||
pub fn send_audio_packet(&self, data: Bytes) {
|
||||
if let Err(e) = self.send_audio.send(MediaItem::Coded(data)) {
|
||||
debug!("failed to send audio data: {e}");
|
||||
}
|
||||
}
|
||||
@@ -499,6 +539,44 @@ async fn run_input_reader(
|
||||
.await;
|
||||
}
|
||||
|
||||
/// What the control reader needs to decide about a PyroWave request.
|
||||
#[derive(Clone)]
|
||||
struct PyroWaveGate {
|
||||
/// Set once the client's capabilities named PyroWave in this hub's format.
|
||||
ok: Arc<AtomicBool>,
|
||||
default_kbps: u32,
|
||||
}
|
||||
|
||||
/// Turn a client's PyroWave request into the command nescapture gets, or say
|
||||
/// why it cannot have one.
|
||||
///
|
||||
/// A rate of zero means "the hub's default". The packet size is left for the
|
||||
/// command forwarder, which fills it in as it sends: only the hub sees the
|
||||
/// path, and what fits a datagram is a fact about the moment the encoder is
|
||||
/// told, not the moment the client asked.
|
||||
fn pyrowave_request(
|
||||
request: nesprotocol::EncodeSettings,
|
||||
gate: &PyroWaveGate,
|
||||
) -> Result<nesprotocol::EncodeSettings, &'static str> {
|
||||
if !gate.ok.load(Ordering::Relaxed) {
|
||||
return Err("the client never said it decodes this hub's PyroWave format");
|
||||
}
|
||||
if request.rate_control != nesprotocol::RC_CBR {
|
||||
return Err("PyroWave runs at a set rate, and the request named none");
|
||||
}
|
||||
Ok(nesprotocol::EncodeSettings {
|
||||
value: if request.value == 0 {
|
||||
gate.default_kbps
|
||||
} else {
|
||||
request.value
|
||||
},
|
||||
bit_depth: Some(request.bit_depth.unwrap_or(nesprotocol::DEPTH_8)),
|
||||
chroma: Some(request.chroma.unwrap_or(nesprotocol::pyrowave::CHROMA_420)),
|
||||
packet_size: None,
|
||||
..request
|
||||
})
|
||||
}
|
||||
|
||||
/// Everything the client says that is not an input event.
|
||||
async fn run_control_reader(
|
||||
conn: Connection,
|
||||
@@ -506,12 +584,14 @@ async fn run_control_reader(
|
||||
latest_report: Arc<std::sync::Mutex<Option<ReceiverReport>>>,
|
||||
controller: Arc<Mutex<Controller>>,
|
||||
awaiting_keyframe: Arc<AtomicBool>,
|
||||
pyrowave: PyroWaveGate,
|
||||
) {
|
||||
run_framed_reader(conn, BIDI_CONTROL, "control", None, |msg_type, payload| {
|
||||
let idr_cmd_tx = idr_cmd_tx.clone();
|
||||
let latest_report = latest_report.clone();
|
||||
let controller = controller.clone();
|
||||
let awaiting_keyframe = awaiting_keyframe.clone();
|
||||
let pyrowave = pyrowave.clone();
|
||||
async move {
|
||||
match msg_type {
|
||||
MSG_IDR_REQUEST => {
|
||||
@@ -535,6 +615,21 @@ async fn run_control_reader(
|
||||
// decode.
|
||||
match nesprotocol::decode_client_caps(&payload) {
|
||||
Some(caps) => {
|
||||
// Recorded whatever the mode: it is a fact about the
|
||||
// client, consulted only if it asks for PyroWave.
|
||||
let format = nesprotocol::decode_pyrowave_format(&payload);
|
||||
let pyro = caps.supports_codec(nesprotocol::CODEC_PYROWAVE);
|
||||
pyrowave.ok.store(
|
||||
pyro && format == Some(nesprotocol::pyrowave::PYROWAVE_FORMAT),
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
if pyro && format != Some(nesprotocol::pyrowave::PYROWAVE_FORMAT) {
|
||||
info!(
|
||||
"client decodes PyroWave format {format:?}, this hub carries \
|
||||
{}; it will not be sent PyroWave",
|
||||
nesprotocol::pyrowave::PYROWAVE_FORMAT
|
||||
);
|
||||
}
|
||||
// Manual means a person is choosing, and the panel
|
||||
// they chose in sets the codec and the depth
|
||||
// together. A client joining afterwards must not
|
||||
@@ -563,6 +658,22 @@ async fn run_control_reader(
|
||||
"received encode settings from client ({} bytes)",
|
||||
payload.len()
|
||||
);
|
||||
let mut payload = payload;
|
||||
if let Some(request) = nesprotocol::decode_encode_settings_ext(&payload)
|
||||
&& request.codec == nesprotocol::CODEC_PYROWAVE
|
||||
{
|
||||
match pyrowave_request(request, &pyrowave) {
|
||||
Ok(settings) => {
|
||||
info!("client asked for PyroWave at {} kbps", settings.value);
|
||||
payload.clear();
|
||||
nesprotocol::encode_settings(&mut payload, &settings);
|
||||
}
|
||||
Err(why) => {
|
||||
warn!("refusing a PyroWave request: {why}");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// A person set this by hand, so the controller stops
|
||||
// deciding until it is told otherwise. Overriding a
|
||||
// person's setting a second later would take away the only
|
||||
@@ -778,10 +889,12 @@ pub struct SessionManager {
|
||||
audio_bytes: AtomicU64,
|
||||
last_audio_bytes: AtomicU64,
|
||||
relay_ms: Arc<AtomicU32>, // latest relay latency (f32 bits)
|
||||
/// The rate a PyroWave request that names none runs at.
|
||||
pyrowave_kbps: u32,
|
||||
}
|
||||
|
||||
impl SessionManager {
|
||||
pub fn new() -> Self {
|
||||
pub fn new(pyrowave_kbps: u32) -> Self {
|
||||
let (gamepad_tx, _) = tokio::sync::broadcast::channel(256);
|
||||
Self {
|
||||
sessions: Arc::new(Mutex::new(HashMap::new())),
|
||||
@@ -797,6 +910,7 @@ impl SessionManager {
|
||||
audio_bytes: AtomicU64::new(0),
|
||||
last_audio_bytes: AtomicU64::new(0),
|
||||
relay_ms: Arc::new(AtomicU32::new(0)),
|
||||
pyrowave_kbps,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -825,6 +939,7 @@ impl SessionManager {
|
||||
self.relay_ms.clone(),
|
||||
idr_cmd_tx,
|
||||
controller,
|
||||
self.pyrowave_kbps,
|
||||
)
|
||||
});
|
||||
session.attach(carrier, conn);
|
||||
@@ -885,7 +1000,10 @@ impl SessionManager {
|
||||
let Some(ts_bytes) = payload.get(2..6) else {
|
||||
return;
|
||||
};
|
||||
let ts_ms = u32::from_le_bytes(ts_bytes.try_into().unwrap());
|
||||
self.note_pipeline_ts(u32::from_le_bytes(ts_bytes.try_into().unwrap()));
|
||||
}
|
||||
|
||||
fn note_pipeline_ts(&self, ts_ms: u32) {
|
||||
let now_ms = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_millis() as u64)
|
||||
@@ -924,25 +1042,57 @@ impl SessionManager {
|
||||
self.video_delta_bytes
|
||||
.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
}
|
||||
let data = MediaItem::Coded(Bytes::from(data));
|
||||
let sessions = self.sessions.lock().await;
|
||||
if sessions.is_empty() {
|
||||
return;
|
||||
}
|
||||
for session in sessions.values() {
|
||||
session.send_video_frame(data.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand a PyroWave frame to every client.
|
||||
///
|
||||
/// Counted with the delta bytes: every PyroWave frame is intra, and
|
||||
/// counting them as keyframes would report sixty keyframes a second, which
|
||||
/// describes nothing.
|
||||
pub async fn broadcast_pyrowave(&self, frame: PyroFrame) {
|
||||
self.note_pipeline_ts(frame.meta.ts_ms);
|
||||
self.video_delta_bytes
|
||||
.fetch_add(frame.data.len() as u64, Ordering::Relaxed);
|
||||
let item = MediaItem::PyroWave(Arc::new(frame));
|
||||
let sessions = self.sessions.lock().await;
|
||||
for session in sessions.values() {
|
||||
session.send_video_frame(item.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// PyroWave frames skipped across every client since the last call.
|
||||
pub async fn take_pyro_skipped(&self) -> u64 {
|
||||
let sessions = self.sessions.lock().await;
|
||||
sessions
|
||||
.values()
|
||||
.map(ClientSession::take_pyro_skipped)
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// The PyroWave packet size every streaming client can carry: the smallest
|
||||
/// of theirs, since one encoder serves them all. `None` with no client
|
||||
/// streaming.
|
||||
pub async fn pyro_packet_size(&self) -> Option<usize> {
|
||||
let sessions = self.sessions.lock().await;
|
||||
sessions
|
||||
.values()
|
||||
.filter_map(ClientSession::pyro_packet_limit)
|
||||
.min()
|
||||
}
|
||||
|
||||
pub async fn broadcast_audio(&self, data: Vec<u8>) {
|
||||
// Counted before the early return, so the figure measures what neswire
|
||||
// delivered rather than what a client happened to be around for. A hub
|
||||
// with no client still knows whether audio is being produced.
|
||||
self.audio_bytes
|
||||
.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||
let data = Bytes::from(data);
|
||||
let sessions = self.sessions.lock().await;
|
||||
if sessions.is_empty() {
|
||||
return;
|
||||
}
|
||||
for session in sessions.values() {
|
||||
session.send_audio_packet(data.clone());
|
||||
}
|
||||
@@ -1098,7 +1248,7 @@ mod pipeline_delay_tests {
|
||||
|
||||
#[test]
|
||||
fn a_second_with_no_frames_reports_nothing() {
|
||||
let mgr = SessionManager::new();
|
||||
let mgr = SessionManager::new(0);
|
||||
assert_eq!(mgr.pipeline_delays(), (0, 0, 0));
|
||||
}
|
||||
|
||||
@@ -1109,7 +1259,7 @@ mod pipeline_delay_tests {
|
||||
// same time on every frame must read as zero, not as that constant --
|
||||
// which is what a plain subtraction would have reported, pinned at the
|
||||
// maximum the wire can carry.
|
||||
let mgr = SessionManager::new();
|
||||
let mgr = SessionManager::new(0);
|
||||
for i in 0..60u32 {
|
||||
mgr.note_pipeline_delay(&payload(i * 16));
|
||||
}
|
||||
@@ -1123,7 +1273,7 @@ mod pipeline_delay_tests {
|
||||
|
||||
#[test]
|
||||
fn draining_means_each_answer_describes_one_second() {
|
||||
let mgr = SessionManager::new();
|
||||
let mgr = SessionManager::new(0);
|
||||
mgr.note_pipeline_delay(&payload(0));
|
||||
assert!(mgr.pipeline_delays().0 == 0);
|
||||
assert_eq!(mgr.pipeline_delays(), (0, 0, 0));
|
||||
@@ -1131,7 +1281,7 @@ mod pipeline_delay_tests {
|
||||
|
||||
#[test]
|
||||
fn a_truncated_payload_is_ignored_rather_than_misread() {
|
||||
let mgr = SessionManager::new();
|
||||
let mgr = SessionManager::new(0);
|
||||
mgr.note_pipeline_delay(&[0u8, 0u8, 1u8]);
|
||||
assert_eq!(mgr.pipeline_delays(), (0, 0, 0));
|
||||
}
|
||||
@@ -1213,3 +1363,67 @@ mod input_batch_tests {
|
||||
assert!(events.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod pyrowave_request_tests {
|
||||
use super::{PyroWaveGate, pyrowave_request};
|
||||
use nesprotocol::pyrowave::{CHROMA_420, CHROMA_444};
|
||||
use nesprotocol::{CODEC_PYROWAVE, DEPTH_8, DEPTH_10, EncodeSettings, RC_CBR, RC_CQP};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
|
||||
fn gate(ok: bool) -> PyroWaveGate {
|
||||
PyroWaveGate {
|
||||
ok: Arc::new(AtomicBool::new(ok)),
|
||||
default_kbps: 300_000,
|
||||
}
|
||||
}
|
||||
|
||||
fn request(value: u32) -> EncodeSettings {
|
||||
EncodeSettings {
|
||||
codec: CODEC_PYROWAVE,
|
||||
rate_control: RC_CBR,
|
||||
value,
|
||||
bit_depth: None,
|
||||
chroma: None,
|
||||
packet_size: Some(9999),
|
||||
}
|
||||
}
|
||||
|
||||
/// The opt-in is only as safe as this: a client that never said it
|
||||
/// decodes the format must not get it by asking.
|
||||
#[test]
|
||||
fn a_client_without_the_format_is_refused() {
|
||||
assert!(pyrowave_request(request(100_000), &gate(false)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_rate_means_the_hubs_default() {
|
||||
let s = pyrowave_request(request(0), &gate(true)).unwrap();
|
||||
assert_eq!(s.value, 300_000);
|
||||
let s = pyrowave_request(request(150_000), &gate(true)).unwrap();
|
||||
assert_eq!(s.value, 150_000, "a named rate is not overruled");
|
||||
}
|
||||
|
||||
/// The client cannot see the path, so whatever packet size it sent is not
|
||||
/// passed on; the forwarder names one.
|
||||
#[test]
|
||||
fn the_clients_packet_size_is_not_trusted() {
|
||||
let s = pyrowave_request(request(0), &gate(true)).unwrap();
|
||||
assert_eq!(s.packet_size, None);
|
||||
assert_eq!((s.bit_depth, s.chroma), (Some(DEPTH_8), Some(CHROMA_420)));
|
||||
|
||||
let mut r = request(0);
|
||||
r.bit_depth = Some(DEPTH_10);
|
||||
r.chroma = Some(CHROMA_444);
|
||||
let s = pyrowave_request(r, &gate(true)).unwrap();
|
||||
assert_eq!((s.bit_depth, s.chroma), (Some(DEPTH_10), Some(CHROMA_444)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_quality_is_not_a_pyrowave_mode() {
|
||||
let mut r = request(0);
|
||||
r.rate_control = RC_CQP;
|
||||
assert!(pyrowave_request(r, &gate(true)).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,6 +148,7 @@ const READY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
|
||||
/// them listens on and answer in its place — and the answer that matters is the
|
||||
/// address a client is told to connect to. See `ticket::Untrusted`.
|
||||
pub const SERVICE_UID: u32 = 1000;
|
||||
pub const SERVICE_GID: u32 = 1000;
|
||||
|
||||
/// Where audio's socket lives, for both the services and the workload.
|
||||
///
|
||||
@@ -168,18 +169,6 @@ pub const SERVICE_UID: u32 = 1000;
|
||||
/// workload, which is the property [`crate::ticket::Untrusted`] depends on.
|
||||
pub const AUDIO_DIR: &str = "/run/pipewire";
|
||||
|
||||
/// Where the PulseAudio protocol is served, in [`AUDIO_DIR`] for the reason
|
||||
/// audio's own socket is.
|
||||
///
|
||||
/// pipewire-pulse is told this path by its configuration file in the image,
|
||||
/// which is not something this program can pass it, so the two are compared by
|
||||
/// a test rather than trusted to agree.
|
||||
pub const PULSE_SOCKET: &str = "/run/pipewire/pulse-native";
|
||||
|
||||
/// [`PULSE_SOCKET`] as a PulseAudio client is told it.
|
||||
pub const PULSE_SERVER: &str = "unix:/run/pipewire/pulse-native";
|
||||
pub const SERVICE_GID: u32 = 1000;
|
||||
|
||||
/// Where a service's runtime sockets live.
|
||||
pub const RUNTIME_DIR: &str = "/run/user/1000";
|
||||
|
||||
@@ -292,26 +281,6 @@ pub const STACK: &[Service] = &[
|
||||
umask: None,
|
||||
ready: None,
|
||||
},
|
||||
Service {
|
||||
name: "pipewire-pulse",
|
||||
argv: &["/usr/bin/pipewire-pulse"],
|
||||
env: &[
|
||||
("XDG_RUNTIME_DIR", RUNTIME_DIR),
|
||||
("PIPEWIRE_RUNTIME_DIR", AUDIO_DIR),
|
||||
("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"),
|
||||
],
|
||||
user: Some((SERVICE_UID, SERVICE_GID)),
|
||||
// Optional for the reason the sender is: everything that speaks
|
||||
// PipeWire itself is unaffected, and a session with sound missing is
|
||||
// degraded rather than unusable.
|
||||
cost: "anything that only speaks PulseAudio plays silently, and Wine is one",
|
||||
required: false,
|
||||
// The workload is its client, and is not this user.
|
||||
umask: Some(0),
|
||||
// Nothing in this table connects to it, but the workload does, and the
|
||||
// workload is started after the table.
|
||||
ready: Some(PULSE_SOCKET),
|
||||
},
|
||||
Service {
|
||||
name: "neswire",
|
||||
argv: &["/usr/bin/neswire"],
|
||||
@@ -932,7 +901,7 @@ mod tests {
|
||||
/// owner -- and the workload is not the owner.
|
||||
#[test]
|
||||
fn the_audio_socket_is_reachable_by_a_user_who_does_not_own_it() {
|
||||
for name in ["pipewire", "pipewire-pulse"] {
|
||||
for name in ["pipewire"] {
|
||||
let service = STACK
|
||||
.iter()
|
||||
.find(|s| s.name == name)
|
||||
@@ -945,32 +914,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The PulseAudio socket's path is written three times: here, in the
|
||||
/// client address the workload is given, and in pipewire-pulse's own
|
||||
/// configuration in the image. If any of them moves on its own, the game
|
||||
/// finds no server and plays silently, and nothing fails.
|
||||
#[test]
|
||||
fn pulse_is_served_where_the_workload_is_told_to_look() {
|
||||
assert!(
|
||||
PULSE_SOCKET.starts_with(AUDIO_DIR),
|
||||
"the workload can only reach sockets in {AUDIO_DIR}"
|
||||
);
|
||||
assert_eq!(PULSE_SERVER, format!("unix:{PULSE_SOCKET}"));
|
||||
|
||||
let pulse = STACK
|
||||
.iter()
|
||||
.find(|s| s.name == "pipewire-pulse")
|
||||
.expect("pulse is in the table");
|
||||
assert_eq!(pulse.ready, Some(PULSE_SOCKET));
|
||||
|
||||
let config =
|
||||
include_str!("../../../build/etc/pipewire/pipewire-pulse.conf.d/50-nestri.conf");
|
||||
assert!(
|
||||
config.contains(&format!("\"{PULSE_SERVER}\"")),
|
||||
"pipewire-pulse is configured to listen somewhere other than {PULSE_SOCKET}"
|
||||
);
|
||||
}
|
||||
|
||||
/// The two that failed on a real boot, and the reason each matters.
|
||||
#[test]
|
||||
fn every_service_has_somewhere_to_write() {
|
||||
|
||||
@@ -303,9 +303,6 @@ const GRAPHICS: &[(&str, &str)] = &[
|
||||
// reach and both are told where. Without this a game renders and plays
|
||||
// silently, having looked under its own uid and found nothing.
|
||||
("PIPEWIRE_RUNTIME_DIR", crate::services::AUDIO_DIR),
|
||||
// The same, for a client that speaks PulseAudio instead. It does not read
|
||||
// the variable above, and its default is under its own runtime directory.
|
||||
("PULSE_SERVER", crate::services::PULSE_SERVER),
|
||||
];
|
||||
|
||||
/// Mount one share where the descriptor says to put it.
|
||||
|
||||
Reference in New Issue
Block a user