Skip to main content

qualia_core_db/sparql_library/
sparql_mm.rs

1//! SPARQL-MM (Multimedia) Support
2//!
3//! Implements SPARQL-MM for media fragments and time-series windowing.
4//! Supports Media Annotations Ontology (MA Ontology, <http://www.w3.org/ns/ma-ont#>).
5//!
6//! V6 repair: MA/C2PA constants use canonical `q_hash` (no placeholder collisions);
7//! caller-buffered region/time queries; real spatial intersection; honest C2PA status.
8
9use crate::q_hash;
10use crate::sparql_ast::*;
11use crate::NQuin;
12
13/// Media Annotations Ontology predicate hashes (`q_hash` of canonical IRIs).
14pub mod ma_ont {
15    use crate::q_hash;
16
17    pub const HAS_FRAGMENT: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasFragment");
18    pub const HAS_TEMPORAL_FRAGMENT: u64 =
19        q_hash("http://www.w3.org/ns/ma-ont#hasTemporalFragment");
20    pub const HAS_SPATIAL_FRAGMENT: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasSpatialFragment");
21    pub const HAS_TRACK_FRAGMENT: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasTrackFragment");
22
23    pub const HAS_START_TIME: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasStartTime");
24    pub const HAS_END_TIME: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasEndTime");
25    pub const DURATION: u64 = q_hash("http://www.w3.org/ns/ma-ont#duration");
26
27    pub const HAS_X: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasX");
28    pub const HAS_Y: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasY");
29    pub const HAS_WIDTH: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasWidth");
30    pub const HAS_HEIGHT: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasHeight");
31
32    pub const HAS_TRACK: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasTrack");
33    pub const HAS_TRACK_NAME: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasTrackName");
34    pub const HAS_TRACK_NUMBER: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasTrackNumber");
35
36    pub const HAS_FORMAT: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasFormat");
37    pub const HAS_MIME_TYPE: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasMimeType");
38    pub const HAS_CODEC: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasCodec");
39
40    pub const HAS_BITRATE: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasBitrate");
41    pub const HAS_FRAMERATE: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasFramerate");
42    pub const HAS_SAMPLERATE: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasSamplerate");
43    pub const HAS_CHANNELS: u64 = q_hash("http://www.w3.org/ns/ma-ont#hasChannels");
44
45    /// Qualia extension: packed media time base (ms), separate from Lamport bits.
46    pub const MEDIA_TIME_MS: u64 = q_hash("https://ns.webizen.org/q42/mediaTimeMs");
47}
48
49/// C2PA predicate hashes (`q_hash` of documented IRIs — vocabulary for graph edges only).
50pub mod c2pa {
51    use crate::q_hash;
52
53    pub const HAS_CREDENTIAL: u64 = q_hash("http://ns.c2pa.org/credentials/hasCredential");
54    pub const HAS_MANIFEST: u64 = q_hash("http://ns.c2pa.org/manifest/hasManifest");
55    pub const HAS_SIGNATURE: u64 = q_hash("http://ns.c2pa.org/signature/hasSignature");
56    pub const HAS_PROVENANCE: u64 = q_hash("http://ns.c2pa.org/provenance/hasProvenance");
57    pub const HAS_ASSERTION: u64 = q_hash("http://ns.c2pa.org/assertion/hasAssertion");
58
59    pub const CREATED_AT: u64 = q_hash("http://ns.c2pa.org/provenance/createdAt");
60    pub const CREATED_BY: u64 = q_hash("http://ns.c2pa.org/provenance/createdBy");
61    pub const MODIFIED_AT: u64 = q_hash("http://ns.c2pa.org/provenance/modifiedAt");
62    pub const MODIFIED_BY: u64 = q_hash("http://ns.c2pa.org/provenance/modifiedBy");
63    pub const HAS_TOOL: u64 = q_hash("http://ns.c2pa.org/provenance/hasTool");
64
65    pub const DERIVED_FROM: u64 = q_hash("http://ns.c2pa.org/asset/derivedFrom");
66    pub const COMPONENT_OF: u64 = q_hash("http://ns.c2pa.org/asset/componentOf");
67    pub const HAS_COMPONENT: u64 = q_hash("http://ns.c2pa.org/asset/hasComponent");
68
69    pub const IS_VERIFIED: u64 = q_hash("http://ns.c2pa.org/validation/isVerified");
70    pub const VERIFICATION_STATUS: u64 = q_hash("http://ns.c2pa.org/validation/verificationStatus");
71    pub const HAS_CERTIFICATE: u64 = q_hash("http://ns.c2pa.org/validation/hasCertificate");
72}
73
74/// Honest C2PA verification status (design §6.3.7).
75/// Field presence alone is never "verified".
76#[repr(u8)]
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
78pub enum C2paVerificationStatus {
79    /// No C2PA path implemented for this asset.
80    Unsupported = 0,
81    /// Manifest/claim edges present; no crypto check run.
82    ParsedOnly = 1,
83    /// Integrity hash matched; signature not checked.
84    IntegrityChecked = 2,
85    /// Signature verified against key material (not yet implemented here).
86    SignatureVerified = 3,
87    /// Full trust chain evaluated (not yet implemented here).
88    TrustChainEvaluated = 4,
89}
90
91/// Media fragment dimensions
92#[repr(C)]
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum MediaFragmentDimension {
95    Temporal {
96        start: u64,
97        end: u64,
98    },
99    Spatial {
100        x: u32,
101        y: u32,
102        width: u32,
103        height: u32,
104    },
105    Track {
106        track_id: u64,
107        track_number: u32,
108    },
109}
110
111/// Media fragment
112#[repr(C)]
113#[derive(Debug, Clone, Copy)]
114pub struct MediaFragment {
115    pub media_uri: u64,
116    pub dimensions: [Option<MediaFragmentDimension>; 4],
117    pub dimension_count: u8,
118}
119
120/// Time window type
121#[repr(C)]
122#[derive(Debug, Clone, Copy, PartialEq, Eq)]
123pub enum WindowType {
124    Tumbling { size_ms: u64 },
125    // NOTE: this WindowType is a SPARQL-MM media-fragment window, NOT a
126    // continuous-query (RSP-QL/C-SPARQL) stream window over the graph. Streaming
127    // SPARQL is planned but unimplemented — see
128    // docs/plans/immersive-sparql-hypermedia-profile.md §15d.
129    Sliding { size_ms: u64, slide_ms: u64 },
130    Session { gap_ms: u64 },
131}
132
133/// Time window
134#[repr(C)]
135#[derive(Debug, Clone, Copy)]
136pub struct TimeWindow {
137    pub window_type: WindowType,
138    pub start_ms: u64,
139    pub end_ms: u64,
140}
141
142/// SPARQL-MM Media Handler
143pub struct SparqlMmHandler<'a> {
144    pub quins: &'a [NQuin],
145    pub windows: [TimeWindow; 64],
146    pub window_count: u8,
147    pub media_fragments: [MediaFragment; 128],
148    pub fragment_count: u8,
149}
150
151impl<'a> SparqlMmHandler<'a> {
152    /// Creates a handler over `quins` — the NQuin slice all mm/ma predicates scan.
153    pub fn new(quins: &'a [NQuin]) -> Self {
154        Self {
155            quins,
156            windows: [TimeWindow {
157                window_type: WindowType::Tumbling { size_ms: 1000 },
158                start_ms: 0,
159                end_ms: 0,
160            }; 64],
161            window_count: 0,
162            media_fragments: [MediaFragment {
163                media_uri: 0,
164                dimensions: [None; 4],
165                dimension_count: 0,
166            }; 128],
167            fragment_count: 0,
168        }
169    }
170
171    /// Build a media fragment from **explicit** dimensions (no hash-derived pseudo-parse).
172    ///
173    /// Callers that only have a media URI hash must pass dimensions separately —
174    /// inventing temporal/spatial ranges from hash bits is forbidden (design §6.3.6).
175    pub fn make_media_fragment(
176        media_uri: u64,
177        dimensions: &[MediaFragmentDimension],
178    ) -> Result<MediaFragment, String> {
179        if dimensions.len() > 4 {
180            return Err("At most 4 fragment dimensions".to_string());
181        }
182        let mut fragment = MediaFragment {
183            media_uri,
184            dimensions: [None; 4],
185            dimension_count: 0,
186        };
187        for (i, d) in dimensions.iter().enumerate() {
188            fragment.dimensions[i] = Some(*d);
189            fragment.dimension_count += 1;
190        }
191        Ok(fragment)
192    }
193
194    /// Legacy entry: returns a fragment with **media_uri only** (no invented dimensions).
195    /// Prefer `make_media_fragment` with explicit temporal/spatial/track dims.
196    pub fn parse_media_fragment(&mut self, fragment_uri: u64) -> Result<MediaFragment, String> {
197        Self::make_media_fragment(fragment_uri, &[])
198    }
199
200    /// Pack xywh into a single object payload (same layout as vision `pack_bbox` family).
201    #[inline]
202    pub fn pack_spatial_u64(x: u32, y: u32, width: u32, height: u32) -> u64 {
203        // Clamp to u16 lanes for fixed packing (normalized or pixel coords ≤ 65535).
204        let x = (x.min(0xFFFF)) as u64;
205        let y = (y.min(0xFFFF)) as u64;
206        let w = (width.min(0xFFFF)) as u64;
207        let h = (height.min(0xFFFF)) as u64;
208        x | (y << 16) | (w << 32) | (h << 48)
209    }
210
211    #[inline]
212    /// `SparqlMmHandler::unpack_spatial_u64`.
213    pub fn unpack_spatial_u64(v: u64) -> (u32, u32, u32, u32) {
214        (
215            (v & 0xFFFF) as u32,
216            ((v >> 16) & 0xFFFF) as u32,
217            ((v >> 32) & 0xFFFF) as u32,
218            ((v >> 48) & 0xFFFF) as u32,
219        )
220    }
221
222    /// Axis-aligned box intersection (x,y,w,h).
223    #[inline]
224    pub fn spatial_intersects(
225        ax: u32,
226        ay: u32,
227        aw: u32,
228        ah: u32,
229        bx: u32,
230        by: u32,
231        bw: u32,
232        bh: u32,
233    ) -> bool {
234        let ax1 = ax.saturating_add(aw);
235        let ay1 = ay.saturating_add(ah);
236        let bx1 = bx.saturating_add(bw);
237        let by1 = by.saturating_add(bh);
238        ax < bx1 && ax1 > bx && ay < by1 && ay1 > by
239    }
240
241    /// Media time from a quin: unifies explicit `ma_ont::MEDIA_TIME_MS` and
242    /// `ma_ont::HAS_START_TIME` (stored in the `object` field) with vision observation
243    /// quins that pack the frame index or millisecond timestamp in metadata bits 16..48.
244    pub fn media_time_ms(quin: &NQuin) -> Option<u64> {
245        if quin.predicate == ma_ont::MEDIA_TIME_MS || quin.predicate == ma_ont::HAS_START_TIME {
246            Some(quin.object)
247        } else {
248            let meta_time = (quin.metadata >> 16) & 0xFFFF_FFFF;
249            if meta_time > 0 {
250                Some(meta_time)
251            } else {
252                None
253            }
254        }
255    }
256
257    /// Get MA Ontology property for a media resource
258    pub fn get_ma_property(&self, media_uri: u64, predicate: u64) -> Result<u64, String> {
259        for quin in self.quins {
260            if quin.subject == media_uri && quin.predicate == predicate {
261                return Ok(quin.object);
262            }
263        }
264        Err("Property not found".to_string())
265    }
266
267    /// Get temporal fragment using MA Ontology
268    pub fn get_temporal_fragment(&self, media_uri: u64) -> Result<(u64, u64), String> {
269        let start = self.get_ma_property(media_uri, ma_ont::HAS_START_TIME)?;
270        let end = self.get_ma_property(media_uri, ma_ont::HAS_END_TIME)?;
271        Ok((start, end))
272    }
273
274    /// Get spatial fragment using MA Ontology
275    pub fn get_spatial_fragment(&self, media_uri: u64) -> Result<(u32, u32, u32, u32), String> {
276        let x = self.get_ma_property(media_uri, ma_ont::HAS_X)? as u32;
277        let y = self.get_ma_property(media_uri, ma_ont::HAS_Y)? as u32;
278        let width = self.get_ma_property(media_uri, ma_ont::HAS_WIDTH)? as u32;
279        let height = self.get_ma_property(media_uri, ma_ont::HAS_HEIGHT)? as u32;
280        Ok((x, y, width, height))
281    }
282
283    /// Get track fragment using MA Ontology
284    pub fn get_track_fragment(&self, media_uri: u64) -> Result<(u64, u32), String> {
285        let track_id = self.get_ma_property(media_uri, ma_ont::HAS_TRACK)?;
286        let track_number = self.get_ma_property(media_uri, ma_ont::HAS_TRACK_NUMBER)? as u32;
287        Ok((track_id, track_number))
288    }
289
290    /// Add a media fragment
291    pub fn add_media_fragment(&mut self, fragment: MediaFragment) -> Result<u8, String> {
292        if self.fragment_count >= 128 {
293            return Err("Fragment overflow".to_string());
294        }
295        let idx = self.fragment_count;
296        self.media_fragments[idx as usize] = fragment;
297        self.fragment_count += 1;
298        Ok(idx)
299    }
300
301    /// Create a tumbling time window
302    pub fn create_tumbling_window(&mut self, size_ms: u64, start_ms: u64) -> Result<u8, String> {
303        if self.window_count >= 64 {
304            return Err("Window overflow".to_string());
305        }
306        let idx = self.window_count;
307        self.windows[idx as usize] = TimeWindow {
308            window_type: WindowType::Tumbling { size_ms },
309            start_ms,
310            end_ms: start_ms + size_ms,
311        };
312        self.window_count += 1;
313        Ok(idx)
314    }
315
316    /// Create a sliding time window
317    pub fn create_sliding_window(
318        &mut self,
319        size_ms: u64,
320        slide_ms: u64,
321        start_ms: u64,
322    ) -> Result<u8, String> {
323        if self.window_count >= 64 {
324            return Err("Window overflow".to_string());
325        }
326        let idx = self.window_count;
327        self.windows[idx as usize] = TimeWindow {
328            window_type: WindowType::Sliding { size_ms, slide_ms },
329            start_ms,
330            end_ms: start_ms + size_ms,
331        };
332        self.window_count += 1;
333        Ok(idx)
334    }
335
336    /// Create a session window
337    pub fn create_session_window(&mut self, gap_ms: u64, start_ms: u64) -> Result<u8, String> {
338        if self.window_count >= 64 {
339            return Err("Window overflow".to_string());
340        }
341        let idx = self.window_count;
342        self.windows[idx as usize] = TimeWindow {
343            window_type: WindowType::Session { gap_ms },
344            start_ms,
345            end_ms: 0, // Dynamic
346        };
347        self.window_count += 1;
348        Ok(idx)
349    }
350
351    /// Query quins within a time window (heap-compatible wrapper).
352    /// Prefer `query_window_into` on hot paths.
353    pub fn query_window(
354        &self,
355        window_id: u8,
356        _timestamp_field: u64,
357    ) -> Result<Vec<&NQuin>, String> {
358        let mut buf = [None; 256];
359        let n = self.query_window_into(window_id, &mut buf)?;
360        Ok(buf[..n].iter().filter_map(|x| *x).collect())
361    }
362
363    /// Caller-buffered window query. Uses **media time** when
364    /// `predicate == MEDIA_TIME_MS`; otherwise falls back to metadata low 29 bits
365    /// with the understanding that that path is Lamport-mixed (not pure media time).
366    pub fn query_window_into(
367        &'a self,
368        window_id: u8,
369        out: &mut [Option<&'a NQuin>],
370    ) -> Result<usize, String> {
371        let window = self
372            .windows
373            .get(window_id as usize)
374            .filter(|_| (window_id as usize) < self.window_count as usize)
375            .ok_or("Window ID out of bounds")?;
376
377        let mut w = 0usize;
378        for quin in self.quins {
379            let t = if let Some(ms) = Self::media_time_ms(quin) {
380                ms
381            } else {
382                quin.metadata & 0x1FFF_FFFF
383            };
384            if t >= window.start_ms && t <= window.end_ms {
385                if w >= out.len() {
386                    break;
387                }
388                out[w] = Some(quin);
389                w += 1;
390            }
391        }
392        Ok(w)
393    }
394
395    /// Query media fragment (heap wrapper). Prefer `query_media_fragment_into`.
396    pub fn query_media_fragment(&self, fragment_id: u8) -> Result<Vec<&NQuin>, String> {
397        let mut buf = [None; 256];
398        let n = self.query_media_fragment_into(fragment_id, &mut buf)?;
399        Ok(buf[..n].iter().filter_map(|x| *x).collect())
400    }
401
402    /// Caller-buffered media-fragment query with real spatial intersection.
403    pub fn query_media_fragment_into(
404        &'a self,
405        fragment_id: u8,
406        out: &mut [Option<&'a NQuin>],
407    ) -> Result<usize, String> {
408        let fragment = self
409            .media_fragments
410            .get(fragment_id as usize)
411            .filter(|_| (fragment_id as usize) < self.fragment_count as usize)
412            .ok_or("Fragment ID out of bounds")?;
413
414        let mut w = 0usize;
415        for quin in self.quins {
416            if !self.check_fragment_match(quin, fragment) {
417                continue;
418            }
419            if w >= out.len() {
420                break;
421            }
422            out[w] = Some(quin);
423            w += 1;
424        }
425        Ok(w)
426    }
427
428    fn check_fragment_match(&self, quin: &NQuin, fragment: &MediaFragment) -> bool {
429        if fragment.dimension_count == 0 {
430            return quin.subject == fragment.media_uri
431                || self.quin_linked_to_media(quin, fragment.media_uri);
432        }
433
434        if !(quin.subject == fragment.media_uri
435            || self.quin_linked_to_media(quin, fragment.media_uri))
436        {
437            return false;
438        }
439
440        for i in 0..fragment.dimension_count as usize {
441            let Some(dim) = fragment.dimensions[i] else {
442                continue;
443            };
444            match dim {
445                MediaFragmentDimension::Temporal { start, end } => {
446                    let Some(quin_time) = Self::media_time_ms(quin).or_else(|| {
447                        if quin.predicate == ma_ont::HAS_START_TIME
448                            || quin.predicate == ma_ont::HAS_END_TIME
449                        {
450                            Some(quin.object)
451                        } else {
452                            None
453                        }
454                    }) else {
455                        // No media-time payload on this quin → temporal dim does not reject.
456                        continue;
457                    };
458                    if quin_time < start || quin_time > end {
459                        return false;
460                    }
461                }
462                MediaFragmentDimension::Spatial {
463                    x,
464                    y,
465                    width,
466                    height,
467                } => {
468                    // If this quin carries a box, require intersection; else pass.
469                    if let Some((qx, qy, qw, qh)) = self.quin_spatial_box(quin) {
470                        if !Self::spatial_intersects(qx, qy, qw, qh, x, y, width, height) {
471                            return false;
472                        }
473                    }
474                }
475                MediaFragmentDimension::Track { track_id, .. } => {
476                    let is_track_pred = quin.predicate == ma_ont::HAS_TRACK
477                        || quin.predicate == ma_ont::HAS_TRACK_NUMBER
478                        || quin.predicate == q_hash("https://ns.webizen.org/q42/hasTrackId");
479                    if is_track_pred && quin.object != track_id {
480                        return false;
481                    }
482                }
483            }
484        }
485        true
486    }
487
488    fn quin_linked_to_media(&self, quin: &NQuin, media_uri: u64) -> bool {
489        if quin.subject == media_uri {
490            return true;
491        }
492        // Observation pattern: media --VisualObservation--> instance
493        for q in self.quins {
494            if q.subject == media_uri && q.object == quin.subject {
495                return true;
496            }
497        }
498        false
499    }
500
501    /// Resolve a box for this quin: packed HAS_SPATIAL_FRAGMENT object, or HAS_X/Y/W/H props.
502    fn quin_spatial_box(&self, quin: &NQuin) -> Option<(u32, u32, u32, u32)> {
503        if quin.predicate == ma_ont::HAS_SPATIAL_FRAGMENT
504            || quin.predicate == q_hash("https://ns.webizen.org/q42/hasBoundingBox")
505        {
506            let (x, y, w, h) = Self::unpack_spatial_u64(quin.object);
507            // hasBoundingBox stores x0,y0,x1,y1 not x,y,w,h — convert if x1>x0 style.
508            if quin.predicate == q_hash("https://ns.webizen.org/q42/hasBoundingBox") {
509                let x1 = w;
510                let y1 = h;
511                let width = x1.saturating_sub(x);
512                let height = y1.saturating_sub(y);
513                return Some((x, y, width, height));
514            }
515            return Some((x, y, w, h));
516        }
517        // Compose from component properties on same subject.
518        let mut x = None;
519        let mut y = None;
520        let mut width = None;
521        let mut height = None;
522        for q in self.quins {
523            if q.subject != quin.subject {
524                continue;
525            }
526            match q.predicate {
527                p if p == ma_ont::HAS_X => x = Some(q.object as u32),
528                p if p == ma_ont::HAS_Y => y = Some(q.object as u32),
529                p if p == ma_ont::HAS_WIDTH => width = Some(q.object as u32),
530                p if p == ma_ont::HAS_HEIGHT => height = Some(q.object as u32),
531                _ => {}
532            }
533        }
534        match (x, y, width, height) {
535            (Some(x), Some(y), Some(w), Some(h)) => Some((x, y, w, h)),
536            _ => None,
537        }
538    }
539
540    /// Get media duration using MA Ontology
541    pub fn get_media_duration(&self, media_uri: u64) -> Result<u64, String> {
542        self.get_ma_property(media_uri, ma_ont::DURATION)
543    }
544
545    /// Get media dimensions using MA Ontology
546    pub fn get_media_dimensions(&self, media_uri: u64) -> Result<(u32, u32), String> {
547        let width = self.get_ma_property(media_uri, ma_ont::HAS_WIDTH)? as u32;
548        let height = self.get_ma_property(media_uri, ma_ont::HAS_HEIGHT)? as u32;
549        Ok((width, height))
550    }
551
552    /// Get media format using MA Ontology
553    pub fn get_media_format(&self, media_uri: u64) -> Result<u64, String> {
554        self.get_ma_property(media_uri, ma_ont::HAS_FORMAT)
555    }
556
557    /// Get media MIME type using MA Ontology
558    pub fn get_media_mime_type(&self, media_uri: u64) -> Result<u64, String> {
559        self.get_ma_property(media_uri, ma_ont::HAS_MIME_TYPE)
560    }
561
562    /// Get media codec using MA Ontology
563    pub fn get_media_codec(&self, media_uri: u64) -> Result<u64, String> {
564        self.get_ma_property(media_uri, ma_ont::HAS_CODEC)
565    }
566
567    /// Get media bitrate using MA Ontology
568    pub fn get_media_bitrate(&self, media_uri: u64) -> Result<u64, String> {
569        self.get_ma_property(media_uri, ma_ont::HAS_BITRATE)
570    }
571
572    /// Get media framerate using MA Ontology
573    pub fn get_media_framerate(&self, media_uri: u64) -> Result<u64, String> {
574        self.get_ma_property(media_uri, ma_ont::HAS_FRAMERATE)
575    }
576
577    /// C2PA: Get content credential for media
578    pub fn get_credential(&self, media_uri: u64) -> Result<u64, String> {
579        self.get_ma_property(media_uri, c2pa::HAS_CREDENTIAL)
580    }
581
582    /// C2PA: Get manifest for media
583    pub fn get_manifest(&self, media_uri: u64) -> Result<u64, String> {
584        self.get_ma_property(media_uri, c2pa::HAS_MANIFEST)
585    }
586
587    /// C2PA: Get signature for media
588    pub fn get_signature(&self, media_uri: u64) -> Result<u64, String> {
589        self.get_ma_property(media_uri, c2pa::HAS_SIGNATURE)
590    }
591
592    /// C2PA: Get provenance for media
593    pub fn get_provenance(&self, media_uri: u64) -> Result<u64, String> {
594        self.get_ma_property(media_uri, c2pa::HAS_PROVENANCE)
595    }
596
597    /// C2PA: Check if media is cryptographically verified.
598    ///
599    /// Honest policy: a stored `isVerified=1` edge is **not** sufficient.
600    /// Returns `Ok(true)` only when status is SignatureVerified or TrustChainEvaluated.
601    /// Today this engine never reaches those levels → typically `Ok(false)` or Err.
602    pub fn is_verified(&self, media_uri: u64) -> Result<bool, String> {
603        let status = self.c2pa_status(media_uri)?;
604        Ok(matches!(
605            status,
606            C2paVerificationStatus::SignatureVerified | C2paVerificationStatus::TrustChainEvaluated
607        ))
608    }
609
610    /// Honest verification ladder for C2PA (design §6.3.7).
611    pub fn c2pa_status(&self, media_uri: u64) -> Result<C2paVerificationStatus, String> {
612        let has_manifest = self.get_ma_property(media_uri, c2pa::HAS_MANIFEST).is_ok();
613        let has_sig = self.get_ma_property(media_uri, c2pa::HAS_SIGNATURE).is_ok();
614        if !has_manifest && !has_sig {
615            return Ok(C2paVerificationStatus::Unsupported);
616        }
617
618        // This accessor has graph references, not the original payload/hash,
619        // signature, key or evaluated trust policy. Nonzero references and an
620        // asserted isVerified edge cannot establish any verification tier.
621        // Keep the original graph/provenance accessible while reporting only
622        // what this path actually did. A native verifier must supply a separate
623        // verified-result integration before higher statuses can be returned.
624        Ok(C2paVerificationStatus::ParsedOnly)
625    }
626
627    /// C2PA: Get verification status as u64 enum discriminant.
628    pub fn get_verification_status(&self, media_uri: u64) -> Result<u64, String> {
629        Ok(self.c2pa_status(media_uri)? as u64)
630    }
631
632    /// C2PA: Get creation timestamp
633    pub fn get_created_at(&self, media_uri: u64) -> Result<u64, String> {
634        self.get_ma_property(media_uri, c2pa::CREATED_AT)
635    }
636
637    /// C2PA: Get creator
638    pub fn get_created_by(&self, media_uri: u64) -> Result<u64, String> {
639        self.get_ma_property(media_uri, c2pa::CREATED_BY)
640    }
641
642    /// C2PA: Get modification timestamp
643    pub fn get_modified_at(&self, media_uri: u64) -> Result<u64, String> {
644        self.get_ma_property(media_uri, c2pa::MODIFIED_AT)
645    }
646
647    /// C2PA: Get modifier
648    pub fn get_modified_by(&self, media_uri: u64) -> Result<u64, String> {
649        self.get_ma_property(media_uri, c2pa::MODIFIED_BY)
650    }
651
652    /// C2PA: Get tool used to create media
653    pub fn get_tool(&self, media_uri: u64) -> Result<u64, String> {
654        self.get_ma_property(media_uri, c2pa::HAS_TOOL)
655    }
656
657    /// C2PA: Get source asset (derived from)
658    pub fn get_derived_from(&self, media_uri: u64) -> Result<u64, String> {
659        self.get_ma_property(media_uri, c2pa::DERIVED_FROM)
660    }
661
662    /// C2PA: Get parent asset (component of)
663    pub fn get_component_of(&self, media_uri: u64) -> Result<u64, String> {
664        self.get_ma_property(media_uri, c2pa::COMPONENT_OF)
665    }
666
667    /// C2PA: Get component assets
668    pub fn get_components(&self, media_uri: u64) -> Result<Vec<u64>, String> {
669        let mut components = Vec::new();
670        for quin in self.quins {
671            if quin.subject == media_uri && quin.predicate == c2pa::HAS_COMPONENT {
672                components.push(quin.object);
673            }
674        }
675        Ok(components)
676    }
677
678    /// C2PA: Verify content signature.
679    /// **Unsupported** in this build — always returns `Ok(false)` if a signature
680    /// edge exists (ParsedOnly), or `Err` if missing. Never claims crypto success.
681    pub fn verify_signature(&self, media_uri: u64) -> Result<bool, String> {
682        let _signature = self.get_signature(media_uri)?;
683        // Real signature verification is out of scope for SPARQL-MM accessors.
684        Ok(false)
685    }
686
687    /// Aggregate over time window
688    pub fn window_aggregate(
689        &self,
690        window_id: u8,
691        aggregate_fn: fn(&[&NQuin]) -> u64,
692    ) -> Result<u64, String> {
693        let quins = self.query_window(window_id, 0)?;
694        Ok(aggregate_fn(&quins))
695    }
696}
697
698impl<'a> Default for SparqlMmHandler<'a> {
699    fn default() -> Self {
700        Self::new(&[])
701    }
702}
703
704/// SPARQL-MM extension functions
705pub fn mm_duration(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
706    if args.is_empty() {
707        return false;
708    }
709    let media_uri = args[0];
710
711    let handler = SparqlMmHandler::new(quins);
712    match handler.get_media_duration(media_uri) {
713        Ok(duration) => {
714            result.slots[0] = Some(duration);
715            true
716        }
717        Err(_) => false,
718    }
719}
720
721/// `mm:dimensions` predicate — binds the media dimension fields of a matched quin.
722pub fn mm_dimensions(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
723    if args.is_empty() {
724        return false;
725    }
726    let media_uri = args[0];
727
728    let handler = SparqlMmHandler::new(quins);
729    match handler.get_media_dimensions(media_uri) {
730        Ok((width, height)) => {
731            result.slots[0] = Some(width as u64);
732            result.slots[1] = Some(height as u64);
733            true
734        }
735        Err(_) => false,
736    }
737}
738
739/// `mm:temporalFragment` predicate — binds temporal-fragment fields.
740pub fn mm_temporal_fragment(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
741    if args.len() < 2 {
742        return false;
743    }
744    let media_uri = args[0];
745    let start = args[1];
746    let end = args.get(2).copied().unwrap_or(start);
747
748    let mut handler = SparqlMmHandler::new(quins);
749    let fragment = MediaFragment {
750        media_uri,
751        dimensions: [
752            Some(MediaFragmentDimension::Temporal { start, end }),
753            None,
754            None,
755            None,
756        ],
757        dimension_count: 1,
758    };
759
760    match handler.add_media_fragment(fragment) {
761        Ok(_) => {
762            result.slots[0] = Some(1); // Success
763            true
764        }
765        Err(_) => false,
766    }
767}
768
769/// MA Ontology extension functions
770pub fn ma_format(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
771    if args.is_empty() {
772        return false;
773    }
774    let media_uri = args[0];
775
776    let handler = SparqlMmHandler::new(quins);
777    match handler.get_media_format(media_uri) {
778        Ok(format) => {
779            result.slots[0] = Some(format);
780            true
781        }
782        Err(_) => false,
783    }
784}
785
786/// `ma:mimeType` predicate — binds the MIME type.
787pub fn ma_mime_type(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
788    if args.is_empty() {
789        return false;
790    }
791    let media_uri = args[0];
792
793    let handler = SparqlMmHandler::new(quins);
794    match handler.get_media_mime_type(media_uri) {
795        Ok(mime_type) => {
796            result.slots[0] = Some(mime_type);
797            true
798        }
799        Err(_) => false,
800    }
801}
802
803/// `ma:codec` predicate — binds the codec field.
804pub fn ma_codec(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
805    if args.is_empty() {
806        return false;
807    }
808    let media_uri = args[0];
809
810    let handler = SparqlMmHandler::new(quins);
811    match handler.get_media_codec(media_uri) {
812        Ok(codec) => {
813            result.slots[0] = Some(codec);
814            true
815        }
816        Err(_) => false,
817    }
818}
819
820/// `ma:bitrate` predicate — binds the bitrate field.
821pub fn ma_bitrate(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
822    if args.is_empty() {
823        return false;
824    }
825    let media_uri = args[0];
826
827    let handler = SparqlMmHandler::new(quins);
828    match handler.get_media_bitrate(media_uri) {
829        Ok(bitrate) => {
830            result.slots[0] = Some(bitrate);
831            true
832        }
833        Err(_) => false,
834    }
835}
836/// `ma:framerate` predicate — binds the framerate field.
837pub fn ma_framerate(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
838    if args.is_empty() {
839        return false;
840    }
841    let media_uri = args[0];
842
843    let handler = SparqlMmHandler::new(quins);
844    match handler.get_media_framerate(media_uri) {
845        Ok(framerate) => {
846            result.slots[0] = Some(framerate);
847            true
848        }
849        Err(_) => false,
850    }
851}
852
853/// C2PA extension functions
854
855/// c2pa:credential - get content credential
856pub fn c2pa_credential(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
857    if args.is_empty() {
858        return false;
859    }
860    let media_uri = args[0];
861
862    let handler = SparqlMmHandler::new(quins);
863    match handler.get_credential(media_uri) {
864        Ok(credential) => {
865            result.slots[0] = Some(credential);
866            true
867        }
868        Err(_) => false,
869    }
870}
871
872/// c2pa:isVerified - check if media is verified
873pub fn c2pa_is_verified(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
874    if args.is_empty() {
875        return false;
876    }
877    let media_uri = args[0];
878
879    let handler = SparqlMmHandler::new(quins);
880    match handler.is_verified(media_uri) {
881        Ok(verified) => {
882            result.slots[0] = Some(if verified { 1 } else { 0 });
883            true
884        }
885        Err(_) => false,
886    }
887}
888
889/// c2pa:verificationStatus - get verification status
890pub fn c2pa_verification_status(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
891    if args.is_empty() {
892        return false;
893    }
894    let media_uri = args[0];
895
896    let handler = SparqlMmHandler::new(quins);
897    match handler.get_verification_status(media_uri) {
898        Ok(status) => {
899            result.slots[0] = Some(status);
900            true
901        }
902        Err(_) => false,
903    }
904}
905
906/// c2pa:createdAt - get creation timestamp
907pub fn c2pa_created_at(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
908    if args.is_empty() {
909        return false;
910    }
911    let media_uri = args[0];
912
913    let handler = SparqlMmHandler::new(quins);
914    match handler.get_created_at(media_uri) {
915        Ok(timestamp) => {
916            result.slots[0] = Some(timestamp);
917            true
918        }
919        Err(_) => false,
920    }
921}
922
923/// c2pa:createdBy - get creator
924pub fn c2pa_created_by(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
925    if args.is_empty() {
926        return false;
927    }
928    let media_uri = args[0];
929
930    let handler = SparqlMmHandler::new(quins);
931    match handler.get_created_by(media_uri) {
932        Ok(creator) => {
933            result.slots[0] = Some(creator);
934            true
935        }
936        Err(_) => false,
937    }
938}
939
940/// c2pa:verifySignature - verify content signature
941pub fn c2pa_verify_signature(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
942    if args.is_empty() {
943        return false;
944    }
945    let media_uri = args[0];
946
947    let handler = SparqlMmHandler::new(quins);
948    match handler.verify_signature(media_uri) {
949        Ok(verified) => {
950            result.slots[0] = Some(if verified { 1 } else { 0 });
951            true
952        }
953        Err(_) => false,
954    }
955}
956
957/// c2pa:derivedFrom - get source asset
958pub fn c2pa_derived_from(args: &[u64], quins: &[NQuin], result: &mut BindingRow) -> bool {
959    if args.is_empty() {
960        return false;
961    }
962    let media_uri = args[0];
963
964    let handler = SparqlMmHandler::new(quins);
965    match handler.get_derived_from(media_uri) {
966        Ok(source) => {
967            result.slots[0] = Some(source);
968            true
969        }
970        Err(_) => false,
971    }
972}
973
974#[cfg(test)]
975mod tests {
976    use super::*;
977
978    #[test]
979    fn test_mm_handler_creation() {
980        let quins = vec![];
981        let handler = SparqlMmHandler::new(&quins);
982        assert_eq!(handler.window_count, 0);
983    }
984
985    #[test]
986    fn test_create_tumbling_window() {
987        let quins = vec![];
988        let mut handler = SparqlMmHandler::new(&quins);
989
990        let result = handler.create_tumbling_window(1000, 0);
991        assert!(result.is_ok());
992        assert_eq!(handler.window_count, 1);
993    }
994
995    #[test]
996    fn test_create_sliding_window() {
997        let quins = vec![];
998        let mut handler = SparqlMmHandler::new(&quins);
999
1000        let result = handler.create_sliding_window(1000, 500, 0);
1001        assert!(result.is_ok());
1002        assert_eq!(handler.window_count, 1);
1003    }
1004
1005    #[test]
1006    fn test_parse_media_fragment_no_invented_dims() {
1007        let quins = vec![];
1008        let mut handler = SparqlMmHandler::new(&quins);
1009
1010        let fragment = handler.parse_media_fragment(12345).unwrap();
1011        assert_eq!(fragment.media_uri, 12345);
1012        assert_eq!(fragment.dimension_count, 0);
1013    }
1014
1015    #[test]
1016    fn ma_ont_constants_are_distinct() {
1017        // Former placeholders collided (HAS_FRAGMENT == HAS_CODEC etc.).
1018        assert_ne!(ma_ont::HAS_FRAGMENT, ma_ont::HAS_CODEC);
1019        assert_ne!(ma_ont::HAS_BITRATE, ma_ont::HAS_TEMPORAL_FRAGMENT);
1020        assert_ne!(ma_ont::HAS_X, ma_ont::HAS_Y);
1021        assert_ne!(c2pa::HAS_CREDENTIAL, c2pa::HAS_MANIFEST);
1022        assert_ne!(c2pa::DERIVED_FROM, ma_ont::HAS_MIME_TYPE);
1023    }
1024
1025    #[test]
1026    fn spatial_intersection_real() {
1027        assert!(SparqlMmHandler::spatial_intersects(
1028            0, 0, 10, 10, 5, 5, 10, 10
1029        ));
1030        assert!(!SparqlMmHandler::spatial_intersects(
1031            0, 0, 10, 10, 20, 20, 5, 5
1032        ));
1033    }
1034
1035    #[test]
1036    fn query_window_into_media_time() {
1037        let media = q_hash("media:clip");
1038        let quins = [
1039            NQuin {
1040                subject: media,
1041                predicate: ma_ont::MEDIA_TIME_MS,
1042                object: 500,
1043                context: 0,
1044                metadata: 0,
1045                parity: 0,
1046            },
1047            NQuin {
1048                subject: media,
1049                predicate: ma_ont::MEDIA_TIME_MS,
1050                object: 2500,
1051                context: 0,
1052                metadata: 0,
1053                parity: 0,
1054            },
1055        ];
1056        // Fix parity for honesty (not required for query)
1057        let mut handler = SparqlMmHandler::new(&quins);
1058        handler.create_tumbling_window(1000, 0).unwrap(); // [0,1000]
1059        let mut out = [None; 8];
1060        let n = handler.query_window_into(0, &mut out).unwrap();
1061        assert_eq!(n, 1);
1062        assert_eq!(out[0].unwrap().object, 500);
1063    }
1064
1065    #[test]
1066    fn query_media_fragment_into_spatial() {
1067        let media = q_hash("media:img");
1068        let packed = SparqlMmHandler::pack_spatial_u64(10, 10, 50, 50);
1069        let quins = [NQuin {
1070            subject: media,
1071            predicate: ma_ont::HAS_SPATIAL_FRAGMENT,
1072            object: packed,
1073            context: 0,
1074            metadata: 0,
1075            parity: 0,
1076        }];
1077        let mut handler = SparqlMmHandler::new(&quins);
1078        let frag = SparqlMmHandler::make_media_fragment(
1079            media,
1080            &[MediaFragmentDimension::Spatial {
1081                x: 20,
1082                y: 20,
1083                width: 20,
1084                height: 20,
1085            }],
1086        )
1087        .unwrap();
1088        handler.add_media_fragment(frag).unwrap();
1089        let mut out = [None; 4];
1090        let n = handler.query_media_fragment_into(0, &mut out).unwrap();
1091        assert_eq!(n, 1);
1092    }
1093
1094    #[test]
1095    fn c2pa_never_claims_verified_from_field_presence() {
1096        let media = q_hash("media:photo");
1097        let quins = [
1098            NQuin {
1099                subject: media,
1100                predicate: c2pa::HAS_SIGNATURE,
1101                object: 0xABC,
1102                context: 0,
1103                metadata: 0,
1104                parity: 0,
1105            },
1106            NQuin {
1107                subject: media,
1108                predicate: c2pa::IS_VERIFIED,
1109                object: 1,
1110                context: 0,
1111                metadata: 0,
1112                parity: 0,
1113            },
1114        ];
1115        let handler = SparqlMmHandler::new(&quins);
1116        assert_eq!(
1117            handler.c2pa_status(media).unwrap(),
1118            C2paVerificationStatus::ParsedOnly
1119        );
1120        assert!(!handler.is_verified(media).unwrap());
1121        assert!(!handler.verify_signature(media).unwrap());
1122    }
1123
1124    #[test]
1125    fn c2pa_manifest_certificate_and_claimed_anchor_do_not_fabricate_verification() {
1126        let media = q_hash("media:unverified-claims");
1127        let certificate = q_hash("certificate:claimed");
1128        let mut quins = vec![];
1129        for (subject, predicate, object) in [
1130            (media, c2pa::HAS_MANIFEST, 7), (media, c2pa::HAS_ASSERTION, 8),
1131            (media, c2pa::HAS_SIGNATURE, 9), (media, c2pa::HAS_CERTIFICATE, certificate),
1132            (certificate, c2pa::CREATED_BY, 10), (certificate, c2pa::HAS_PROVENANCE, 11),
1133            (media, c2pa::IS_VERIFIED, 1), (media, c2pa::VERIFICATION_STATUS, 4),
1134        ] {
1135            let mut quin = NQuin { subject, predicate, object, context: 0, metadata: 0, parity: 0 };
1136            quin.recalculate_parity(); quins.push(quin);
1137        }
1138        let handler = SparqlMmHandler::new(&quins);
1139        assert_eq!(handler.c2pa_status(media).unwrap(), C2paVerificationStatus::ParsedOnly);
1140        assert!(!handler.is_verified(media).unwrap());
1141        assert!(!handler.verify_signature(media).unwrap());
1142        assert_eq!(handler.get_manifest(media).unwrap(), 7);
1143        assert_eq!(handler.get_signature(media).unwrap(), 9);
1144        assert_eq!(SparqlMmHandler::new(&[]).c2pa_status(media).unwrap(), C2paVerificationStatus::Unsupported);
1145    }
1146}