Skip to main content

pulse_pixelstream_types/
lib.rs

1//! Shared myko entity/command/report types for the pixelstreaming app. WASM-safe:
2//! the Leptos frontend and the native server both build against this crate, and
3//! the TS bindings are generated from it.
4//!
5//! One `#[myko_item]` per module (the macro emits per-module helpers that would
6//! otherwise collide).
7
8pub mod cam_pref;
9pub mod camera_home;
10pub mod collection;
11pub mod collection_membership;
12pub mod commands;
13pub mod control_lock;
14pub mod frame_capture;
15pub mod frame_capture_status;
16pub mod frame_capture_target;
17pub(crate) mod legacy_capture_run;
18pub(crate) mod legacy_shot_list;
19pub mod otio;
20pub mod recording_job;
21pub mod recording_job_request;
22pub mod recording_job_status;
23pub mod recording_plan;
24pub mod recording_request;
25pub mod recording_status;
26pub mod reports;
27pub mod shot;
28pub mod stream;
29pub mod timeline;
30pub mod viewer;
31
32/// Shared, validated editorial identity for synchronized nDisplay capture.
33/// Pulse Cluster owns the wire contract; Pixelstream authors and persists it.
34pub use pulse_capture_types::{
35    CaptureCollection, CaptureCollectionId, CaptureContext, CaptureLabel, CaptureLibraryId,
36    CollectionKind, CollectionPath, ContentRevision, EditorialContextError,
37    PixelstreamCollectionPathSegment, PixelstreamCollectionRef,
38};
39
40pub use cam_pref::*;
41pub use camera_home::*;
42pub use collection::*;
43pub use collection_membership::*;
44pub use commands::*;
45pub use control_lock::*;
46pub use frame_capture::*;
47pub use frame_capture_status::*;
48pub use frame_capture_target::*;
49pub use otio::*;
50pub use recording_job::*;
51pub use recording_job_request::*;
52pub use recording_job_status::*;
53pub use recording_plan::*;
54pub use recording_request::*;
55pub use recording_status::*;
56pub use reports::*;
57pub use shot::*;
58pub use stream::*;
59pub use timeline::*;
60pub use viewer::*;
61
62/// Force-link so the `#[myko_item]` / `#[myko_command]` / `#[myko_report]`
63/// inventory registrations are pulled into whichever binary depends on this
64/// crate. Call once at startup.
65pub fn link() {}
66
67#[cfg(test)]
68mod deser_tests {
69    use crate::{
70        collection::CollectionPathSegment,
71        commands::{JoinStream, MigrateOtioTimelines},
72        control_lock::ControlLock,
73        recording_job_request::{RecordingJobRequest, RecordingJobRequestId},
74        recording_job_status::{RecordingJobStatus, RecordingJobStatusId},
75        recording_plan::{RecordingJobAction, RecordingJobPhase, ShotEntryPlan},
76        recording_request::{RecordingKind, RecordingRequest, RecordingRequestId},
77        recording_status::{RecordingState, RecordingStatus, RecordingStatusId},
78        shot::{Shot, ShotId, ShotKind, DEFAULT_SHOT_LIBRARY_ID},
79        timeline::{ShotDirection, ShotEntry, ShotEntryMode, Timeline, TimelineId},
80        viewer::Viewer,
81        CaptureContext, CaptureLabel, CollectionPath, ContentRevision, StoredCaptureContext,
82    };
83
84    #[test]
85    fn shared_capture_context_uses_cluster_wire_contract() {
86        let context = CaptureContext {
87            collection: CollectionPath::try_from("cycle_4/moment_2".to_owned())
88                .unwrap()
89                .into(),
90            label: Some(CaptureLabel::try_from("hero orbit".to_owned()).unwrap()),
91            content_revision: Some(ContentRevision::try_from("workspace:42".to_owned()).unwrap()),
92        };
93        let value = serde_json::to_value(context).unwrap();
94        assert_eq!(value["collection"], "cycle_4/moment_2");
95        assert_eq!(value["label"], "hero orbit");
96        assert_eq!(value["contentRevision"], "workspace:42");
97    }
98
99    #[test]
100    fn stored_capture_context_is_wire_identical_to_the_bare_contract() {
101        // The newtype exists so this crate can implement Filterable for an
102        // entity field whose type another crate owns. It must be invisible on
103        // the wire: the prod event store holds ~1.5M events written before it
104        // existed, and a replay that fails here is a data-loss-grade upgrade.
105        let context = CaptureContext {
106            collection: CollectionPath::try_from("cycle_4/moment_2".to_owned())
107                .unwrap()
108                .into(),
109            label: Some(CaptureLabel::try_from("hero orbit".to_owned()).unwrap()),
110            content_revision: Some(ContentRevision::try_from("workspace:42".to_owned()).unwrap()),
111        };
112        let bare = serde_json::to_value(&context).unwrap();
113        let stored = serde_json::to_value(StoredCaptureContext(context.clone())).unwrap();
114        assert_eq!(bare, stored, "newtype changed the serialized form");
115
116        // And an event written before the newtype still reads back.
117        let replayed: StoredCaptureContext = serde_json::from_value(bare).unwrap();
118        assert_eq!(replayed.0, context);
119    }
120
121    #[test]
122    fn recording_job_status_replays_a_pre_newtype_event() {
123        // Shape taken from a persisted RecordingJobStatus event.
124        let json = r#"{"streamerId":"render-13","jobId":"job-1","captureContext":{"collection":"cycle_4/moment_2","label":"hero orbit","contentRevision":"workspace:42"},"id":"render-13"}"#;
125        let status = serde_json::from_str::<RecordingJobStatus>(json)
126            .expect("pre-newtype RecordingJobStatus must still deserialize");
127        let context = status
128            .capture_context
129            .as_ref()
130            .expect("captureContext preserved");
131        assert_eq!(
132            context.label.as_ref().map(CaptureLabel::as_str),
133            Some("hero orbit")
134        );
135        // Round-trips back to the same wire form.
136        let reserialized = serde_json::to_value(&status).unwrap();
137        assert_eq!(
138            reserialized["captureContext"]["collection"],
139            "cycle_4/moment_2"
140        );
141    }
142
143    // Exactly what the server sends over the wire (from a captured query-response).
144    #[test]
145    fn controllock_wire_deser() {
146        let j = r#"{"streamId":"s1","viewerId":"v1","clientId":"c1","id":"s1"}"#;
147        let r = serde_json::from_str::<ControlLock>(j);
148        assert!(r.is_ok(), "ControlLock deser failed: {:?}", r.err());
149    }
150
151    #[test]
152    fn viewer_wire_deser() {
153        let j = r#"{"streamId":"s1","viewerId":"v1","name":"n","color":"red","cursor":null,"clientId":"c1","id":"s1:v1"}"#;
154        let r = serde_json::from_str::<Viewer>(j);
155        assert!(r.is_ok(), "Viewer deser failed: {:?}", r.err());
156    }
157
158    #[test]
159    fn legacy_guest_join_stream_defaults_optional_identity() {
160        let j = r#"{"streamId":"s1","viewerId":"v1","name":"Anonymous Puffin","color":"red"}"#;
161        let join =
162            serde_json::from_str::<JoinStream>(j).expect("legacy JoinStream must deserialize");
163        assert_eq!(join.name, "Anonymous Puffin");
164        assert!(join.identity_issuer.is_none());
165        assert!(join.identity_subject.is_none());
166        assert!(join.avatar_url.is_none());
167    }
168
169    #[test]
170    fn shot_kind_uses_film_accurate_static_wire_term() {
171        assert_eq!(serde_json::to_value(ShotKind::Static).unwrap(), "static");
172        for legacy in ["stationary", "preset", "preset_hold"] {
173            let encoded = format!("\"{legacy}\"");
174            assert_eq!(
175                serde_json::from_str::<ShotKind>(&encoded).unwrap(),
176                ShotKind::Static
177            );
178        }
179        assert_eq!(
180            Shot::stable_id("shared", &ShotKind::Static, "Wide"),
181            "shared:shot:static:Wide"
182        );
183    }
184
185    #[test]
186    fn recording_status_uses_only_the_0_5_wire_contract() {
187        let status = RecordingStatus {
188            id: RecordingStatusId::from("render-13".to_owned()),
189            streamer_id: "render-13".to_owned(),
190            state: RecordingState::SavedToNas,
191            file_name: "capture.mp4".to_owned(),
192            error: String::new(),
193            started_at_ms: 1_785_460_000_000,
194        };
195        let value = serde_json::to_value(status).unwrap();
196        assert_eq!(value["state"], "ready_for_handoff");
197        assert_eq!(value["fileName"], "capture.mp4");
198        assert_eq!(value["startedAtMs"], 1_785_460_000_000_u64);
199        assert!(value.get("path").is_none());
200        assert!(value.get("startedAt").is_none());
201
202        let old = r#"{
203            "id":"render-13",
204            "streamerId":"render-13",
205            "state":"done",
206            "path":"capture.mp4",
207            "startedAt":1785460000000
208        }"#;
209        assert!(serde_json::from_str::<RecordingStatus>(old).is_err());
210    }
211
212    #[test]
213    fn recording_request_direction_is_backward_compatible_and_explicit() {
214        let legacy = r#"{
215            "id":"render-13",
216            "streamerId":"render-13",
217            "active":true,
218            "rig":"Hero Push Forward"
219        }"#;
220        let legacy = serde_json::from_str::<RecordingRequest>(legacy).unwrap();
221        assert_eq!(legacy.travel_direction, None);
222        assert_eq!(legacy.shot_index, None);
223        assert_eq!(legacy.capture_kind, RecordingKind::Video);
224
225        let reverse = RecordingRequest {
226            id: RecordingRequestId::from("render-13".to_owned()),
227            streamer_id: "render-13".to_owned(),
228            active: true,
229            capture_kind: RecordingKind::Screenshot,
230            rig: "Hero Push Forward".to_owned(),
231            preset: String::new(),
232            stream_name: String::new(),
233            travel_direction: Some(ShotDirection::Reverse),
234            shot_index: Some(8),
235            take_number: 1,
236            entry_id: "entry-8".to_owned(),
237            timeline_id: String::new(),
238            timeline_name: String::new(),
239            timeline_revision: 0,
240            collection_path: Vec::new(),
241            requested_at_ms: 1,
242        };
243        let value = serde_json::to_value(reverse).unwrap();
244        assert_eq!(value["travelDirection"], "reverse");
245        assert_eq!(value["shotIndex"], 8);
246        assert_eq!(value["captureKind"], "screenshot");
247    }
248
249    #[test]
250    fn recording_job_wire_contract_is_explicit_and_resume_safe() {
251        assert_eq!(
252            serde_json::to_value(RecordingJobAction::Pause).unwrap(),
253            "pause"
254        );
255        let item = ShotEntryPlan {
256            entry_id: "entry-1".to_owned(),
257            shot_id: "shot-1".to_owned(),
258            name: "Floor Dolly".to_owned(),
259            shot_index: Some(4),
260            kind: ShotKind::Moving,
261            target_name: "Floor Dolly".to_owned(),
262            translation_speed_cm_s: 10.0,
263            rotation_speed_deg_s: 2.0,
264            hold_duration_ms: 5_000,
265            travel_duration_ms: 30_000,
266            direction: ShotDirection::Reverse,
267            next_take_number: 1,
268            open_ended: false,
269        };
270        let request = RecordingJobRequest {
271            id: RecordingJobRequestId::from("render-02".to_owned()),
272            streamer_id: "render-02".to_owned(),
273            job_id: "job-1".to_owned(),
274            command_id: "command-1".to_owned(),
275            action: RecordingJobAction::Start,
276            capture_context: None,
277            timeline_id: "timeline-1".to_owned(),
278            timeline_name: "Client selects".to_owned(),
279            timeline_revision: 4,
280            collection_id: "launch-film".to_owned(),
281            collection_path: vec![
282                CollectionPathSegment {
283                    collection_id: "autumn-campaign".to_owned(),
284                    name: "Autumn campaign".to_owned(),
285                },
286                CollectionPathSegment {
287                    collection_id: "launch-film".to_owned(),
288                    name: "Launch film".to_owned(),
289                },
290            ],
291            entries: vec![item.clone()],
292            preset_duration_ms: 0,
293            translation_speed_cm_s: 0.0,
294            rotation_speed_deg_s: 0.0,
295            requested_at_ms: 10,
296        };
297        let value = serde_json::to_value(request).unwrap();
298        assert_eq!(value["action"], "start");
299        assert_eq!(value["timelineId"], "timeline-1");
300        assert_eq!(value["timelineName"], "Client selects");
301        assert_eq!(value["timelineRevision"], 4);
302        assert!(value.get("shotListId").is_none());
303        assert_eq!(value["collectionId"], "launch-film");
304        assert_eq!(value["collectionPath"][0]["name"], "Autumn campaign");
305        assert_eq!(value["collectionPath"][1]["name"], "Launch film");
306        assert_eq!(value["entries"][0]["translationSpeedCmS"], 10.0);
307        assert_eq!(value["entries"][0]["rotationSpeedDegS"], 2.0);
308        assert_eq!(value["entries"][0]["direction"], "reverse");
309        assert_eq!(value["entries"][0]["shotIndex"], 4);
310
311        let mut status = RecordingJobStatus {
312            id: RecordingJobStatusId::from("render-02".to_owned()),
313            streamer_id: "render-02".to_owned(),
314            job_id: "job-1".to_owned(),
315            capture_context: None,
316            timeline_id: "timeline-1".to_owned(),
317            timeline_name: "Client selects".to_owned(),
318            timeline_revision: 4,
319            collection_id: "launch-film".to_owned(),
320            collection_path: vec![CollectionPathSegment {
321                collection_id: "launch-film".to_owned(),
322                name: "Launch film".to_owned(),
323            }],
324            phase: RecordingJobPhase::Paused,
325            pause_requested: false,
326            entries: vec![item],
327            index: 0,
328            completed: 0,
329            error: "resume required".to_owned(),
330            updated_at_ms: 11,
331            elapsed_ms: 4_000,
332            estimated_total_ms: 90_000,
333            estimated_remaining_ms: 86_000,
334            takes: Vec::new(),
335            started_at_ms: 1,
336        };
337        assert!(status.can_resume());
338        assert_eq!(status.resume_progress(), (1, 1));
339        assert_eq!(serde_json::to_value(&status).unwrap()["phase"], "paused");
340
341        status.phase = RecordingJobPhase::Canceled;
342        assert!(!status.can_resume());
343
344        status.phase = RecordingJobPhase::Complete;
345        status.error = "1 take rejected; the job continued".to_owned();
346        assert!(status.can_resume());
347        assert_eq!(
348            status.summary(),
349            "Recording complete with warnings · 0 of 1 takes durable on NAS · 1 take rejected; the job continued"
350        );
351    }
352
353    #[test]
354    fn timeline_mode_migrates_legacy_enabled_values() {
355        assert_eq!(
356            serde_json::from_str::<ShotEntryMode>("true").unwrap(),
357            ShotEntryMode::Forward
358        );
359        assert_eq!(
360            serde_json::from_str::<ShotEntryMode>("false").unwrap(),
361            ShotEntryMode::Excluded
362        );
363        assert_eq!(
364            serde_json::from_str::<ShotEntryMode>(r#""both""#).unwrap(),
365            ShotEntryMode::Both
366        );
367
368        let legacy_shot = r#"{
369            "id":"render-02:moving:Floor Dolly",
370            "streamerId":"render-02",
371            "name":"Floor Dolly",
372            "kind":"moving",
373            "targetName":"Floor Dolly",
374            "translationSpeedCmS":10.0,
375            "rotationSpeedDegS":2.0,
376            "holdDurationMs":5000,
377            "batchMode":"excluded",
378            "sortOrder":0
379        }"#;
380        let shot = serde_json::from_str::<Shot>(legacy_shot).unwrap();
381        assert_eq!(shot.effective_library_id(), "shared");
382        assert_eq!(shot.default_entry_mode, ShotEntryMode::Excluded);
383        assert_eq!(shot.shot_index, 0);
384        let shot_wire = serde_json::to_value(shot).unwrap();
385        assert_eq!(shot_wire["sortOrder"], 0);
386        assert!(shot_wire.get("shotIndex").is_none());
387
388        let legacy_plan = r#"{
389            "shotId":"shot-1",
390            "name":"Floor Dolly",
391            "kind":"moving",
392            "targetName":"Floor Dolly",
393            "translationSpeedCmS":10.0,
394            "rotationSpeedDegS":2.0,
395            "holdDurationMs":5000
396        }"#;
397        let legacy_plan = serde_json::from_str::<ShotEntryPlan>(legacy_plan).unwrap();
398        assert_eq!(legacy_plan.direction, ShotDirection::Forward);
399        assert_eq!(legacy_plan.shot_index, None);
400    }
401
402    #[test]
403    fn legacy_clips_without_overrides_remain_compatible() {
404        let mut timeline = Timeline {
405            id: TimelineId::from(Timeline::legacy_default_id("render-02")),
406            library_id: "shared".to_owned(),
407            streamer_id: "render-02".to_owned(),
408            name: "Client selects".to_owned(),
409            revision: 3,
410            entries: vec![ShotEntry {
411                shot_id: "shot-a".to_owned(),
412                direction: ShotEntryMode::Both,
413                ..Default::default()
414            }],
415            sort_order: 0,
416        };
417
418        timeline.normalize_entries();
419        assert_eq!(timeline.entries.len(), 2);
420        assert_eq!(timeline.capture_count(), 2);
421        assert_eq!(timeline.next_revision(), 4);
422        assert!(timeline
423            .entries
424            .iter()
425            .all(|entry| !entry.entry_id.is_empty()));
426        assert_eq!(timeline.entries[0].direction, ShotEntryMode::Forward);
427        assert_eq!(timeline.entries[1].direction, ShotEntryMode::Reverse);
428
429        timeline.add_entry("shot-b", ShotEntryMode::Forward);
430
431        let first_entry_id = timeline.entries[0].entry_id.clone();
432        timeline.remove_entry(&first_entry_id);
433        assert_eq!(timeline.entries.len(), 2);
434
435        let value = serde_json::to_value(timeline).unwrap();
436        assert_eq!(value["entries"][0]["shotId"], "shot-a");
437        assert!(value["entries"][0].get("translationSpeedCmS").is_none());
438        assert!(value["entries"][0].get("rotationSpeedDegS").is_none());
439        assert!(value.get("clips").is_none());
440        assert!(value["entries"][0].get("cueId").is_none());
441        assert!(value["entries"][0].get("clipId").is_none());
442        assert!(value["entries"][0].get("mode").is_none());
443    }
444
445    #[test]
446    fn the_same_shot_has_independent_parameters_in_each_timeline() {
447        let shot = Shot {
448            id: ShotId::from("shared:shot:moving:hero"),
449            library_id: DEFAULT_SHOT_LIBRARY_ID.to_owned(),
450            streamer_id: String::new(),
451            name: "Hero".to_owned(),
452            kind: ShotKind::Moving,
453            target_name: "Hero".to_owned(),
454            translation_speed_cm_s: 10.0,
455            rotation_speed_deg_s: 2.0,
456            hold_duration_ms: 5_000,
457            travel_duration_ms: 30_000,
458            default_entry_mode: ShotEntryMode::Forward,
459            shot_index: 0,
460        };
461        let mut fast = ShotEntry::from_shot(&shot, ShotEntryMode::Forward);
462        let mut slow = ShotEntry::from_shot(&shot, ShotEntryMode::Forward);
463        fast.translation_speed_cm_s = Some(20.0);
464        fast.travel_duration_ms = Some(15_000);
465        slow.translation_speed_cm_s = Some(5.0);
466        slow.travel_duration_ms = Some(60_000);
467
468        assert_eq!(fast.resolved_shot(&shot).translation_speed_cm_s, 20.0);
469        assert_eq!(slow.resolved_shot(&shot).translation_speed_cm_s, 5.0);
470        assert_eq!(fast.resolved_shot(&shot).travel_duration_ms, 15_000);
471        assert_eq!(slow.resolved_shot(&shot).travel_duration_ms, 60_000);
472        assert_eq!(shot.translation_speed_cm_s, 10.0);
473    }
474
475    #[test]
476    fn timeline_normalizes_membership_without_persisting_a_second_index() {
477        let legacy = r#"{
478            "id":"render-02:timeline:legacy",
479            "streamerId":"render-02",
480            "name":"Legacy",
481            "version":0,
482            "entries":[
483                {"shotId":"shot-b","mode":"forward"},
484                {"shotId":"shot-a","mode":"reverse"}
485            ],
486            "sortOrder":0
487        }"#;
488        let mut timeline: Timeline = serde_json::from_str(legacy).unwrap();
489        timeline.normalize_entries();
490        assert_eq!(timeline.entries[0].shot_id, "shot-b");
491        assert_eq!(timeline.entries[1].shot_id, "shot-a");
492        assert!(serde_json::to_value(timeline).unwrap()["entries"][0]
493            .get("index")
494            .is_none());
495    }
496
497    #[test]
498    fn timeline_migration_accepts_the_myko_transaction_envelope() {
499        serde_json::from_str::<MigrateOtioTimelines>(r#"{"tx":"migration-tx"}"#)
500            .expect("migration command must accept Myko's map-shaped envelope");
501    }
502}
503
504// myko 6 requires every queryable field's type to implement `Filterable`.
505// Plain enums get value equality (`Eq`/`In` filters work as an operator would
506// expect); payload structs with no query-meaningful equality take the opaque
507// escape hatch, which renders their query field structurally absent.
508myko::impl_filterable_eq!(
509    crate::recording_plan::RecordingJobAction,
510    crate::recording_plan::RecordingJobPhase,
511    crate::recording_request::RecordingKind,
512    crate::recording_status::RecordingState,
513    crate::shot::ShotKind,
514    crate::timeline::ShotDirection,
515    crate::timeline::ShotEntryMode,
516    crate::frame_capture::FrameCapturePhase,
517);
518
519myko::impl_filterable_opaque!(
520    crate::frame_capture::FrameCaptureTarget,
521    StoredCaptureContext,
522);
523
524/// `CaptureContext` as an entity field.
525///
526/// Every field of a `#[myko_item]` needs `Filterable`, and this crate cannot
527/// implement it for `CaptureContext` — pulse-capture-types owns that type and
528/// the orphan rule forbids the impl. A newtype this crate does own can carry
529/// it, and `Unfilterable` is the right filter anyway: frozen editorial
530/// identity is payload, never a query axis.
531///
532/// `#[serde(transparent)]` means the wire form is exactly the bare contract
533/// type, so persisted events and TS bindings are unchanged — this exists for
534/// the type system, not for the format.
535#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, myko::TS)]
536#[serde(transparent)]
537#[ts(type = "unknown")]
538pub struct StoredCaptureContext(pub CaptureContext);
539
540impl From<CaptureContext> for StoredCaptureContext {
541    fn from(context: CaptureContext) -> Self {
542        Self(context)
543    }
544}
545
546impl From<StoredCaptureContext> for CaptureContext {
547    fn from(stored: StoredCaptureContext) -> Self {
548        stored.0
549    }
550}
551
552impl std::ops::Deref for StoredCaptureContext {
553    type Target = CaptureContext;
554
555    fn deref(&self) -> &Self::Target {
556        &self.0
557    }
558}