Skip to main content

hang/catalog/video/
projection.rs

1use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
2
3/// How a rendition's decoded picture maps onto the viewer's field of view.
4///
5/// Absent means [`Rectilinear`](Self::Rectilinear). An unrecognized `kind` decodes to
6/// [`Projection::Unknown`] instead of failing, and a consumer treats it as absent.
7#[derive(Debug, Clone, PartialEq, Default)]
8#[non_exhaustive]
9pub enum Projection {
10	/// A flat picture.
11	#[default]
12	Rectilinear,
13
14	/// Longitude linear across the width and latitude down the height, the full 180 degrees,
15	/// surrounding a viewer at its centre.
16	Equirectangular {
17		/// The degrees of longitude the picture spans, centred straight ahead, in (0, 360].
18		/// Absent means 360; VR180 is 180.
19		fov: Option<f64>,
20	},
21
22	/// A projection this build does not recognize, preserved verbatim.
23	Unknown(UnknownProjection),
24}
25
26/// The raw JSON of a projection whose `kind` is not recognized.
27///
28/// Kept intact so a relay or transcoder that reparses and republishes a catalog round-trips it.
29#[derive(Debug, Clone, PartialEq)]
30pub struct UnknownProjection(serde_json::Map<String, serde_json::Value>);
31
32impl UnknownProjection {
33	/// The `kind` as it appeared on the wire.
34	pub fn kind(&self) -> &str {
35		// Deserialize refuses a projection without a string kind, so this is never empty.
36		self.0
37			.get("kind")
38			.and_then(serde_json::Value::as_str)
39			.unwrap_or_default()
40	}
41
42	/// The full JSON object, including `kind`.
43	pub fn fields(&self) -> &serde_json::Map<String, serde_json::Value> {
44		&self.0
45	}
46}
47
48impl Projection {
49	/// Refuse a field of view outside (0, 360] degrees.
50	pub(crate) fn check(&self) -> crate::Result<()> {
51		if let Self::Equirectangular { fov: Some(fov) } = self
52			&& !(*fov > 0.0 && *fov <= 360.0)
53		{
54			return Err(crate::Error::InvalidFieldOfView(*fov));
55		}
56		Ok(())
57	}
58}
59
60/// The projections this build knows, split out so the tagged representation stays derived.
61#[serde_with::serde_as]
62#[serde_with::skip_serializing_none]
63#[derive(Serialize, Deserialize)]
64#[serde(tag = "kind", rename_all = "camelCase")]
65enum Known {
66	Rectilinear,
67	Equirectangular {
68		#[serde(default)]
69		#[serde_as(as = "crate::catalog::NotNull")]
70		fov: Option<f64>,
71	},
72}
73
74impl Serialize for Projection {
75	fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
76		let known = match self {
77			Self::Rectilinear => Known::Rectilinear,
78			Self::Equirectangular { fov } => Known::Equirectangular { fov: *fov },
79			Self::Unknown(unknown) => return unknown.0.serialize(serializer),
80		};
81		known.serialize(serializer)
82	}
83}
84
85impl<'de> Deserialize<'de> for Projection {
86	fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
87		let object = serde_json::Map::deserialize(deserializer)?;
88
89		let Some(kind) = object.get("kind").and_then(serde_json::Value::as_str) else {
90			return Err(de::Error::custom("projection kind must be a string"));
91		};
92
93		// Only route kinds we know to the derived enum, so a malformed known projection is still
94		// a hard error instead of silently becoming Unknown.
95		let projection = match kind {
96			"rectilinear" | "equirectangular" => {
97				match Known::deserialize(serde_json::Value::Object(object)).map_err(de::Error::custom)? {
98					Known::Rectilinear => Self::Rectilinear,
99					Known::Equirectangular { fov } => Self::Equirectangular { fov },
100				}
101			}
102			_ => Self::Unknown(UnknownProjection(object)),
103		};
104		projection.check().map_err(de::Error::custom)?;
105		Ok(projection)
106	}
107}
108
109#[cfg(test)]
110mod tests {
111	use super::*;
112
113	#[test]
114	fn round_trips() {
115		for (json, projection) in [
116			(r#"{"kind":"rectilinear"}"#, Projection::Rectilinear),
117			(
118				r#"{"kind":"equirectangular"}"#,
119				Projection::Equirectangular { fov: None },
120			),
121			(
122				r#"{"kind":"equirectangular","fov":180.0}"#,
123				Projection::Equirectangular { fov: Some(180.0) },
124			),
125		] {
126			let parsed: Projection = serde_json::from_str(json).unwrap();
127			assert_eq!(parsed, projection);
128			assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
129		}
130	}
131
132	#[test]
133	fn unknown_round_trips() {
134		let json = r#"{"face":"front","kind":"cubemap"}"#;
135		let parsed: Projection = serde_json::from_str(json).unwrap();
136		let Projection::Unknown(unknown) = &parsed else {
137			panic!("expected unknown: {parsed:?}");
138		};
139		assert_eq!(unknown.kind(), "cubemap");
140		assert_eq!(serde_json::to_string(&parsed).unwrap(), json);
141	}
142
143	#[test]
144	fn unknown_fields_are_ignored() {
145		// A newer publisher may add a parameter to a known kind; this reader must not refuse it.
146		let parsed: Projection = serde_json::from_str(r#"{"kind":"rectilinear","fov":90}"#).unwrap();
147		assert_eq!(parsed, Projection::Rectilinear);
148	}
149
150	#[test]
151	fn malformed_known_is_refused() {
152		serde_json::from_str::<Projection>(r#"{"fov":180}"#).unwrap_err();
153		serde_json::from_str::<Projection>(r#"{"kind":5}"#).unwrap_err();
154		serde_json::from_str::<Projection>(r#"{"kind":"equirectangular","fov":"wide"}"#).unwrap_err();
155		for fov in ["0", "-90", "360.5"] {
156			let json = format!(r#"{{"kind":"equirectangular","fov":{fov}}}"#);
157			serde_json::from_str::<Projection>(&json).unwrap_err();
158		}
159	}
160
161	#[test]
162	fn fov_must_be_in_range() {
163		for fov in [0.0, -90.0, 360.5, f64::NAN, f64::INFINITY] {
164			Projection::Equirectangular { fov: Some(fov) }.check().unwrap_err();
165		}
166		for fov in [None, Some(0.5), Some(180.0), Some(360.0)] {
167			Projection::Equirectangular { fov }.check().unwrap();
168		}
169	}
170}