1use crate::container_10d::crc32c::crc32c;
7use bytemuck::{Pod, Zeroable};
8
9pub const EMF_CONTAINER_MAGIC: [u8; 8] = *b"Q42EMF64";
11
12pub const EMF_CONTAINER_VERSION: u16 = 2;
14pub const EMF_EXTENDED_VERSION: u16 = 3;
16pub const EMF_LEGACY_VERSION: u16 = 1;
17pub const EMF_CHUNK_FLAG_BLAKE3_FULL: u16 = 1 << 2;
19
20pub const EMF_FLAG_3D_BRICK_8X8X8: u16 = 1 << 0;
22pub const EMF_FLAG_STOKES_POLARIZED: u16 = 1 << 1;
24pub const EMF_FLAG_SPECTRAL_BANDS: u16 = 1 << 2;
26pub const EMF_FLAG_BAO_VERIFIED: u16 = 1 << 3;
29
30pub const MAX_DENSE_CELLS: usize = 1_048_576;
32
33pub const EPSILON_0: f32 = 8.854_187_8e-12;
35pub const MU_0: f32 = 1.256_637_1e-6;
37pub const SPEED_OF_LIGHT: f32 = 299_792_458.0;
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum EmfError {
43 InvalidMagic,
44 InvalidVersion(u16),
45 InvalidHeaderSize,
46 ChecksumMismatch { stored: u32, computed: u32 },
47 BaoHashMismatch { chunk_index: usize },
48 FullHashMismatch { chunk_index: usize },
49 InvalidIntegrityEncoding { chunk_index: usize },
50 LegacyIntegrityRequiresOptIn,
51 ExtensionMetadata,
52 ExtensionLimits,
53 ExtensionHashMismatch,
54 AudioTrack { track_index:usize },
55 AudioHashMismatch { track_index:usize },
56 BufferTooSmall { required: usize, provided: usize },
57 FileByteLimit,
58 ChunkLimitExceeded,
59 PayloadOutOfBounds,
60 PayloadOverlap,
61 PayloadUnaligned,
62 DirectoryBounds,
63 DirectoryAlignment,
64 ArithmeticOverflow,
65 HilbertOrder,
68 DenseVolumeCap { cells: usize, cap: usize },
70}
71
72impl std::fmt::Display for EmfError {
73 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74 match self {
75 Self::InvalidMagic => write!(f, "Invalid EMF container magic"),
76 Self::InvalidVersion(v) => write!(f, "Unsupported EMF version: {v}"),
77 Self::InvalidHeaderSize => write!(f, "Invalid EMF header size"),
78 Self::ChecksumMismatch { stored, computed } => {
79 write!(f, "EMF CRC-32C mismatch: stored {stored:#010x}, computed {computed:#010x}")
80 }
81 Self::BaoHashMismatch { chunk_index } => {
82 write!(f, "EMF legacy truncated hash mismatch in chunk {chunk_index}")
83 }
84 Self::FullHashMismatch { chunk_index } => write!(f, "EMF full BLAKE3 seal mismatch in chunk {chunk_index}"),
85 Self::InvalidIntegrityEncoding { chunk_index } => write!(f, "EMF invalid full BLAKE3 seal encoding in chunk {chunk_index}"),
86 Self::ExtensionMetadata => write!(f,"EMF invalid or unsupported v3 metadata/extents"),
87 Self::ExtensionLimits => write!(f,"EMF v3 extension exceeds explicit limits"),
88 Self::ExtensionHashMismatch => write!(f,"EMF v3 extension full BLAKE3 mismatch"),
89 Self::AudioTrack{track_index} => write!(f,"EMF invalid PCM track {track_index}"),
90 Self::AudioHashMismatch{track_index} => write!(f,"EMF PCM track {track_index} full BLAKE3 mismatch"),
91 Self::LegacyIntegrityRequiresOptIn => write!(f, "EMF v1 truncated integrity requires explicit legacy migration admission"),
92 Self::BufferTooSmall { required, provided } => {
93 write!(f, "EMF buffer too small: required {required}, provided {provided}")
94 }
95 Self::FileByteLimit => write!(f, "EMF file exceeds max_file_bytes"),
96 Self::ChunkLimitExceeded => write!(f, "EMF chunk limit exceeded"),
97 Self::PayloadOutOfBounds => write!(f, "EMF payload slice out of bounds"),
98 Self::PayloadOverlap => write!(f, "EMF payload ranges overlap"),
99 Self::PayloadUnaligned => write!(f, "EMF payload is not 64-byte aligned"),
100 Self::DirectoryBounds => write!(f, "EMF chunk directory out of bounds"),
101 Self::DirectoryAlignment => write!(f, "EMF chunk directory not 64-byte aligned"),
102 Self::ArithmeticOverflow => write!(f, "Arithmetic overflow in EMF calculation"),
103 Self::HilbertOrder => write!(f, "EMF Hilbert brick order could not be inferred"),
104 Self::DenseVolumeCap { cells, cap } => {
105 write!(f, "EMF dense volume {cells} cells exceeds cap {cap}")
106 }
107 }
108 }
109}
110
111impl std::error::Error for EmfError {}
112
113#[repr(C, align(64))]
115#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
116pub struct EmfContainerHeader {
117 pub magic: [u8; 8],
119 pub version: u16,
121 pub flags: u16,
123 pub chunk_count: u32,
125 pub directory_offset: u64,
127 pub reference_epoch_s: f64,
129 pub grid_dims_bricks: [u32; 3],
131 pub voxel_size_meters: f32,
133 pub origin_meters: [f32; 3],
135 pub header_crc32c: u32,
137}
138
139impl Default for EmfContainerHeader {
140 fn default() -> Self {
141 Self {
142 magic: EMF_CONTAINER_MAGIC,
143 version: EMF_CONTAINER_VERSION,
144 flags: EMF_FLAG_3D_BRICK_8X8X8,
145 chunk_count: 0,
146 directory_offset: 64,
147 reference_epoch_s: 0.0,
148 grid_dims_bricks: [0, 0, 0],
149 voxel_size_meters: 1.0,
150 origin_meters: [0.0, 0.0, 0.0],
151 header_crc32c: 0,
152 }
153 }
154}
155
156impl EmfContainerHeader {
157 #[inline]
159 pub fn compute_crc32c(&self) -> u32 {
160 let bytes: &[u8; 64] = bytemuck::cast_ref(self);
161 crc32c(&bytes[..60])
162 }
163
164 #[inline]
166 pub fn update_crc(&mut self) {
167 self.header_crc32c = self.compute_crc32c();
168 }
169
170 #[inline]
172 pub fn validate(&self) -> Result<(), EmfError> {
173 if self.magic != EMF_CONTAINER_MAGIC {
174 return Err(EmfError::InvalidMagic);
175 }
176 if !matches!(self.version, EMF_LEGACY_VERSION | EMF_CONTAINER_VERSION | EMF_EXTENDED_VERSION) {
177 return Err(EmfError::InvalidVersion(self.version));
178 }
179 let computed = self.compute_crc32c();
180 if self.header_crc32c == computed {
181 Ok(())
182 } else {
183 Err(EmfError::ChecksumMismatch {
184 stored: self.header_crc32c,
185 computed,
186 })
187 }
188 }
189}
190
191#[repr(C, align(64))]
193#[derive(Copy, Clone, Debug, PartialEq, Pod, Zeroable)]
194pub struct EmfCellRecord64 {
195 pub e_field: [f32; 3],
197 pub b_field: [f32; 3],
199 pub poynting_flux: f32,
201 pub wavelength_nm: f32,
203 pub refractive_n: f32,
205 pub extinction_k: f32,
207 pub coherence_phase: f32,
209 pub stokes_q: f32,
211 pub stokes_u: f32,
213 pub stokes_v: f32,
215 pub spectral_sigma: f32,
217 pub confidence_alpha: f32,
219}
220
221impl Default for EmfCellRecord64 {
222 fn default() -> Self {
223 Self {
224 e_field: [0.0, 0.0, 0.0],
225 b_field: [0.0, 0.0, 0.0],
226 poynting_flux: 0.0,
227 wavelength_nm: 0.0,
228 refractive_n: 1.0,
229 extinction_k: 0.0,
230 coherence_phase: 0.0,
231 stokes_q: 0.0,
232 stokes_u: 0.0,
233 stokes_v: 0.0,
234 spectral_sigma: 0.0,
235 confidence_alpha: 1.0,
236 }
237 }
238}
239
240impl EmfCellRecord64 {
241 pub fn from_legacy_52b(legacy: &[f32; 13]) -> Self {
245 let amp = legacy[0];
246 let phase = legacy[1];
247 let freq = legacy[2];
248 let wavelength_nm = if freq > 0.0 {
249 (SPEED_OF_LIGHT as f64 * 1e9 / (freq as f64)) as f32
250 } else {
251 0.0
252 };
253 let e_field = [amp, 0.0, 0.0];
254 let b_mag = amp / SPEED_OF_LIGHT;
255 let b_field = [0.0, b_mag, 0.0];
256 let poynting_flux = (amp * amp) / (SPEED_OF_LIGHT * MU_0);
257
258 Self {
259 e_field,
260 b_field,
261 poynting_flux,
262 wavelength_nm,
263 refractive_n: 1.0,
264 extinction_k: 0.0,
265 coherence_phase: phase,
266 stokes_q: legacy[3],
267 stokes_u: legacy[4],
268 stokes_v: legacy[5],
269 spectral_sigma: legacy[6],
270 confidence_alpha: 1.0,
271 }
272 }
273
274 #[inline]
276 pub fn poynting_vector(&self) -> [f32; 3] {
277 let ex = self.e_field[0];
278 let ey = self.e_field[1];
279 let ez = self.e_field[2];
280 let bx = self.b_field[0];
281 let by = self.b_field[1];
282 let bz = self.b_field[2];
283
284 let cx = ey * bz - ez * by;
285 let cy = ez * bx - ex * bz;
286 let cz = ex * by - ey * bx;
287
288 [cx / MU_0, cy / MU_0, cz / MU_0]
289 }
290
291 #[inline]
293 pub fn poynting_flux_magnitude(&self) -> f32 {
294 let s = self.poynting_vector();
295 (s[0] * s[0] + s[1] * s[1] + s[2] * s[2]).sqrt()
296 }
297
298 #[inline]
300 pub fn e_magnitude(&self) -> f32 {
301 (self.e_field[0] * self.e_field[0]
302 + self.e_field[1] * self.e_field[1]
303 + self.e_field[2] * self.e_field[2])
304 .sqrt()
305 }
306
307 #[inline]
309 pub fn optical_frequency_hz(&self) -> f32 {
310 if self.wavelength_nm > 0.0 {
311 (SPEED_OF_LIGHT as f64 / (self.wavelength_nm as f64 * 1e-9)) as f32
312 } else {
313 0.0
314 }
315 }
316
317 #[inline]
320 pub fn effective_sigma(&self) -> f32 {
321 if self.spectral_sigma != 0.0 {
322 self.spectral_sigma
323 } else if self.wavelength_nm > 0.0 {
324 ((self.wavelength_nm - 400.0) / 300.0).clamp(0.0, 1.0)
325 } else {
326 0.0
327 }
328 }
329
330 #[inline]
332 pub fn energy_density(&self) -> f32 {
333 let e_sq = self.e_field[0] * self.e_field[0]
334 + self.e_field[1] * self.e_field[1]
335 + self.e_field[2] * self.e_field[2];
336 let b_sq = self.b_field[0] * self.b_field[0]
337 + self.b_field[1] * self.b_field[1]
338 + self.b_field[2] * self.b_field[2];
339
340 0.5 * (EPSILON_0 * e_sq + b_sq / MU_0)
341 }
342}