moqros 0.8.0

Stream ROS 2 topics (images as video, any message as data) over Media over QUIC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! MoQ broadcasts -> ROS topics.

use std::sync::{Arc, Mutex};
use std::time::Duration;

use r2r::std_msgs::msg::Header;

use super::bridge::StatsSender;
use super::meter::{RateMeter, WarnOnce};
use super::{Bridge, QosProfile, RosImage, Teardown, image_into_ros, now_stamp, stamp};
use crate::{
	DataFormat, DataSettings, DataSubscriber, Error, ImageSubscriber, PixelFormat, Result, SubscribeOptions,
	Subscriber, Subscription,
};

/// Republish a MoQ broadcast onto a ROS topic, whatever it carries: video decoded into
/// images ([`RosTarget::encoding`], `rgb8` by default), or the messages of a data track.
///
/// Waits for the first subscription to learn what to publish, so this resolves once
/// `broadcast` is announced. A data track's ROS type comes from its catalog, or from
/// [`RosTarget::ros_type`] when given. The task resubscribes whenever the broadcast ends, so the
/// publisher side may restart freely, but fails if it comes back carrying something
/// else (video instead of data, or another format or message type).
///
/// Images are stamped with their capture time when the publisher announces capture times
/// (moqros does for ROS images: their `header.stamp`), and otherwise with the local receive
/// time; see [`RosTarget::stamp`]. Their `frame_id` is the publisher's unless
/// [`RosTarget::frame_id`] overrides it.
///
/// To wait for several broadcasts at once, use [`MoqToRos::subscribe`] and then
/// [`MoqToRos::spawn`]: only the latter needs the node.
pub async fn spawn_moq_to_ros(
	node: &mut r2r::Node,
	subscriber: Subscriber,
	broadcast: &str,
	target: RosTarget,
) -> Result<Bridge> {
	MoqToRos::subscribe(subscriber, broadcast).await.spawn(node, target)
}

/// The ROS topic [`spawn_moq_to_ros`] republishes a broadcast on.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RosTarget {
	/// Topic name to publish on.
	pub topic: String,
	/// QoS of the ROS publisher.
	pub qos: QosProfile,
	/// `header.frame_id` of republished images, overriding the one the publisher announces
	/// (empty if neither says).
	pub frame_id: Option<String>,
	/// Where the `header.stamp` of republished images comes from.
	pub stamp: StampSource,
	/// ROS message type of a data track, overriding the one its catalog announces.
	pub ros_type: Option<String>,
	/// Pixel encoding of republished images (`rgb8` by default); see
	/// [`Decoder::set_output_format`](crate::Decoder::set_output_format).
	pub encoding: PixelFormat,
}

/// Where the `header.stamp` of a republished image comes from.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StampSource {
	/// The image's capture time from the publisher, in its clock (which may be sim time), or
	/// the receive time if the publisher doesn't announce capture times.
	#[default]
	Source,
	/// The local wall-clock time the image was received.
	Receive,
}

crate::names::named_enum!(StampSource, "stamp source", {
	Source => "source",
	Receive => "receive",
});

impl RosTarget {
	/// Publish on `topic`, with the publisher's `frame_id`, capture times, and the catalog's
	/// message type.
	pub fn new(topic: impl Into<String>, qos: QosProfile) -> Self {
		Self {
			topic: topic.into(),
			qos,
			frame_id: None,
			stamp: StampSource::default(),
			ros_type: None,
			encoding: PixelFormat::Rgb8,
		}
	}

	/// Set [`RosTarget::encoding`].
	pub fn with_encoding(mut self, encoding: PixelFormat) -> Self {
		self.encoding = encoding;
		self
	}

	/// Set [`RosTarget::frame_id`].
	pub fn with_frame_id(mut self, frame_id: impl Into<String>) -> Self {
		self.frame_id = Some(frame_id.into());
		self
	}

	/// Set [`RosTarget::stamp`].
	pub fn with_stamp(mut self, stamp: StampSource) -> Self {
		self.stamp = stamp;
		self
	}

	/// Set [`RosTarget::ros_type`].
	pub fn with_ros_type(mut self, ros_type: impl Into<String>) -> Self {
		self.ros_type = Some(ros_type.into());
		self
	}
}

/// A MoQ broadcast that is subscribed to and ready to be republished on ROS.
pub struct MoqToRos {
	subscriber: Subscriber,
	broadcast: String,
	options: SubscribeOptions,
	first: Subscription,
}

impl MoqToRos {
	/// Subscribe to `broadcast`, retrying until it is announced and readable.
	pub async fn subscribe(subscriber: Subscriber, broadcast: &str) -> Self {
		Self::subscribe_with(subscriber, broadcast, SubscribeOptions::default()).await
	}

	/// Like [`MoqToRos::subscribe`], picking a video rendition by `options`, also when
	/// resubscribing.
	pub async fn subscribe_with(subscriber: Subscriber, broadcast: &str, options: SubscribeOptions) -> Self {
		let first = subscribe(&subscriber, broadcast, &options).await;
		Self {
			subscriber,
			broadcast: broadcast.to_string(),
			options,
			first,
		}
	}

	/// Broadcast name.
	pub fn broadcast(&self) -> &str {
		&self.broadcast
	}

	/// The data track's settings, or `None` if the broadcast carries video.
	pub fn data_settings(&self) -> Option<&crate::DataSettings> {
		match &self.first {
			Subscription::Images(_) => None,
			Subscription::Data(data) => Some(data.settings()),
		}
	}

	/// Create the ROS publisher for `target` and start republishing; see [`spawn_moq_to_ros`].
	pub fn spawn(self, node: &mut r2r::Node, target: RosTarget) -> Result<Bridge> {
		let RosTarget {
			topic,
			qos,
			frame_id,
			stamp,
			ros_type,
			encoding,
		} = target;
		let output = match &self.first {
			Subscription::Images(_) => {
				if matches!(encoding, PixelFormat::Uyvy | PixelFormat::Yuyv) {
					return Err(Error::InvalidSettings(format!("can't republish images as {encoding}")));
				}
				RosOutput::Images {
					publisher: node.create_publisher::<RosImage>(&topic, qos)?,
					frame_id,
					stamp,
					encoding,
				}
			}
			Subscription::Data(data) => {
				let settings = data.settings();
				let ros_type = ros_type
					.or_else(|| settings.ros_type.clone())
					.ok_or_else(|| Error::MissingRosType(self.broadcast.clone()))?;
				RosOutput::Data {
					publisher: node.create_publisher_untyped(&topic, &ros_type, qos)?,
					catalog: settings.clone(),
				}
			}
		};
		// The task hands its publisher back when it stops, for the teardown to destroy.
		let released = Arc::new(Mutex::new(None));
		let slot = released.clone();
		let bridge = Bridge::spawn(|stats| async move {
			let mut output = output;
			let result = republish(
				self.subscriber,
				self.broadcast,
				self.options,
				self.first,
				&mut output,
				stats,
			)
			.await;
			*slot.lock().unwrap_or_else(|err| err.into_inner()) = Some(output);
			result
		});
		Ok(bridge.with_teardown(Teardown::new(move |node| {
			if let Some(output) = released.lock().unwrap_or_else(|err| err.into_inner()).take() {
				output.destroy(node);
			}
		})))
	}
}

/// Subscribe to `broadcast`, retrying until it is announced and readable.
async fn subscribe(subscriber: &Subscriber, broadcast: &str, options: &SubscribeOptions) -> Subscription {
	loop {
		match subscriber.subscribe_with(broadcast, options).await {
			Ok(subscription) => return subscription,
			Err(err) => {
				tracing::warn!(%err, broadcast, "subscribe failed, retrying");
				tokio::time::sleep(Duration::from_secs(1)).await;
			}
		}
	}
}

/// Where [`republish`] sends what it receives.
///
/// r2r publishers are Send but not Sync, so this is only ever borrowed mutably:
/// a shared borrow held across an await would make the task non-Send.
enum RosOutput {
	Images {
		publisher: r2r::Publisher<RosImage>,
		/// Overrides the publisher's.
		frame_id: Option<String>,
		stamp: StampSource,
		encoding: PixelFormat,
	},
	Data {
		publisher: r2r::PublisherUntyped,
		/// What the first catalog announced; the publisher's type may override its `ros_type`.
		catalog: DataSettings,
	},
}

impl RosOutput {
	fn destroy(self, node: &mut r2r::Node) {
		match self {
			Self::Images { publisher, .. } => node.destroy_publisher(publisher),
			Self::Data { publisher, .. } => node.destroy_publisher_untyped(publisher),
		}
	}
}

/// Feed `output` from `broadcast` forever, starting with `first` and resubscribing
/// whenever the broadcast ends.
async fn republish(
	subscriber: Subscriber,
	broadcast: String,
	options: SubscribeOptions,
	first: Subscription,
	output: &mut RosOutput,
	stats: StatsSender,
) -> Result<()> {
	let mut first = Some(first);
	loop {
		let subscription = match first.take() {
			Some(subscription) => subscription,
			None => subscribe(&subscriber, &broadcast, &options).await,
		};

		let ended = match (subscription, &mut *output) {
			(
				Subscription::Images(images),
				RosOutput::Images {
					publisher,
					frame_id,
					stamp,
					encoding,
				},
			) => republish_images(images, publisher, frame_id.as_deref(), *stamp, *encoding, &stats).await?,
			(Subscription::Data(data), RosOutput::Data { publisher, catalog }) => {
				if let Some((from, to)) = data_changed(catalog, data.settings()) {
					return Err(Error::BroadcastChanged { broadcast, from, to });
				}
				republish_data(data, publisher, catalog.format, &stats).await
			}
			(Subscription::Images(_), RosOutput::Data { .. }) => {
				return Err(Error::BroadcastChanged {
					broadcast,
					from: "data".into(),
					to: "video".into(),
				});
			}
			(Subscription::Data(_), RosOutput::Images { .. }) => {
				return Err(Error::NoVideo(broadcast));
			}
		};

		let sent = stats.snapshot().sent;
		match ended {
			None => tracing::info!(broadcast, sent, "broadcast ended, waiting for it to return"),
			Some(err) => tracing::warn!(%err, broadcast, sent, "subscription failed, resubscribing"),
		}
	}
}

/// How a resubscribed data track differs from the `first` one in ways the topic can't
/// follow, as `(from, to)`, if it does. The mode doesn't matter for republishing.
fn data_changed(first: &DataSettings, now: &DataSettings) -> Option<(String, String)> {
	let name = |settings: &DataSettings| {
		format!(
			"{} {}",
			settings.format,
			settings.ros_type.as_deref().unwrap_or("(untyped)")
		)
	};
	(first.format != now.format || first.ros_type != now.ros_type).then(|| (name(first), name(now)))
}

/// Publish decoded images until the subscription ends, returning why it did.
/// Fails only if ROS rejects a message.
async fn republish_images(
	mut images: ImageSubscriber,
	publisher: &mut r2r::Publisher<RosImage>,
	frame_id: Option<&str>,
	stamp_source: StampSource,
	encoding: PixelFormat,
	stats: &StatsSender,
) -> Result<Option<Error>> {
	images.set_output_format(encoding)?;
	let mut meter = RateMeter::new("MoQ -> ROS");
	loop {
		match images.next_image().await {
			Ok(Some(decoded)) => {
				stats.received();
				let header = Header {
					stamp: match (stamp_source, decoded.capture_time) {
						(StampSource::Source, Some(capture_time)) => stamp(capture_time),
						_ => now_stamp(),
					},
					frame_id: frame_id.or(images.frame_id()).unwrap_or_default().to_string(),
				};
				publisher.publish(&image_into_ros(decoded.image, header))?;
				stats.sent();
				meter.tick();
			}
			Ok(None) => return Ok(None),
			Err(err) => return Ok(Some(err)),
		}
	}
}

/// Publish data messages until the subscription ends, returning why it did.
///
/// Messages ROS rejects are skipped: a malformed payload says nothing about the next.
async fn republish_data(
	mut data: DataSubscriber,
	publisher: &mut r2r::PublisherUntyped,
	format: DataFormat,
	stats: &StatsSender,
) -> Option<Error> {
	let mut meter = RateMeter::new("MoQ -> ROS");
	let mut warned = WarnOnce::default();
	loop {
		let message = match data.next_message().await {
			Ok(Some(message)) => message,
			Ok(None) => return None,
			Err(err) => return Some(err),
		};
		stats.received();
		let published = match format {
			DataFormat::Json => serde_json::from_slice(&message.payload)
				.map_err(Error::from)
				.and_then(|value| publisher.publish(value).map_err(Error::from)),
			DataFormat::Cdr => publisher.publish_raw(&message.payload).map_err(Error::from),
		};
		match published {
			Ok(()) => {
				stats.sent();
				meter.tick();
			}
			Err(err) => {
				stats.dropped();
				if warned.first() {
					tracing::warn!(%err, "skipping message");
				}
			}
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn detects_data_track_changes() {
		let settings = |format, mode, ros_type: &str| DataSettings {
			format,
			mode,
			ros_type: Some(ros_type.into()),
		};
		let first = settings(DataFormat::Json, crate::DataMode::Snapshot, "std_msgs/msg/Header");
		assert_eq!(data_changed(&first, &first), None);
		// The mode doesn't change what the topic publishes.
		let stream = settings(DataFormat::Json, crate::DataMode::Stream, "std_msgs/msg/Header");
		assert_eq!(data_changed(&first, &stream), None);
		let cdr = settings(DataFormat::Cdr, crate::DataMode::Snapshot, "std_msgs/msg/Header");
		assert_eq!(
			data_changed(&first, &cdr),
			Some(("json std_msgs/msg/Header".into(), "cdr std_msgs/msg/Header".into()))
		);
		let string = settings(DataFormat::Json, crate::DataMode::Snapshot, "std_msgs/msg/String");
		assert!(data_changed(&first, &string).is_some());
	}
}