foxglove 0.24.0

Foxglove SDK
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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use std::sync::Arc;
use std::time::Duration;

use arc_swap::ArcSwapOption;
use bytes::Bytes;
use libwebrtc::prelude::*;
use libwebrtc::video_source::native::NativeVideoSource;
use tokio::sync::watch;
use tracing::{debug, error, warn};

use crate::RawChannel;
use crate::img2yuv::{ImageEncoding, ImageMessage, Yuv420Buffer};
use crate::throttler::Throttler;

/// Minimum width and height (in pixels) that we will hand to the libwebrtc video encoder.
///
/// H.264, VP8, and VP9 all encode in 16×16 macroblocks. Some encoder backends — notably
/// `libwebrtc`'s VAAPI H.264 encoder on Linux — do not validate this and can write out of
/// bounds when given sub-macroblock frames, which manifests as heap corruption later in
/// the process. Other backends (e.g. OpenH264) reject the frame but continue running.
/// Enforcing this minimum on our side guarantees safe behavior regardless of the codec
/// backend selected by libwebrtc.
const MIN_VIDEO_DIMENSION: u32 = 16;

/// Interval between throttled warnings for repeatedly-too-small frames on a single track.
const TOO_SMALL_WARN_INTERVAL: Duration = Duration::from_secs(30);

/// The input schema type for a video-capable channel.
///
/// Each variant identifies which message format decoder to use for extracting image data.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(clippy::enum_variant_names)]
pub enum VideoInputSchema {
    /// `foxglove.CompressedImage` with protobuf encoding.
    FoxgloveCompressedImage,
    /// `foxglove.RawImage` with protobuf encoding.
    FoxgloveRawImage,
    /// ROS 1 `sensor_msgs/CompressedImage` with ros1 encoding.
    #[cfg(feature = "img2yuv-ros1")]
    Ros1CompressedImage,
    /// ROS 1 `sensor_msgs/Image` with ros1 encoding.
    #[cfg(feature = "img2yuv-ros1")]
    Ros1Image,
    /// ROS 2 `sensor_msgs/msg/CompressedImage` with cdr encoding.
    #[cfg(feature = "img2yuv-ros2")]
    Ros2CompressedImage,
    /// ROS 2 `sensor_msgs/msg/Image` with cdr encoding.
    #[cfg(feature = "img2yuv-ros2")]
    Ros2Image,
}

/// Detect the video input schema from an (encoding, schema_name) pair.
///
/// Returns `Some(InputSchema)` if the channel carries an image type we can transcode to video.
fn detect_video_schema(encoding: &str, schema_name: &str) -> Option<VideoInputSchema> {
    match (encoding, schema_name) {
        ("protobuf", "foxglove.CompressedImage") => Some(VideoInputSchema::FoxgloveCompressedImage),
        ("protobuf", "foxglove.RawImage") => Some(VideoInputSchema::FoxgloveRawImage),
        #[cfg(feature = "img2yuv-ros1")]
        ("ros1", "sensor_msgs/CompressedImage") => Some(VideoInputSchema::Ros1CompressedImage),
        #[cfg(feature = "img2yuv-ros1")]
        ("ros1", "sensor_msgs/Image") => Some(VideoInputSchema::Ros1Image),
        #[cfg(feature = "img2yuv-ros2")]
        ("cdr", "sensor_msgs/msg/CompressedImage") => Some(VideoInputSchema::Ros2CompressedImage),
        #[cfg(feature = "img2yuv-ros2")]
        ("cdr", "sensor_msgs/msg/Image") => Some(VideoInputSchema::Ros2Image),
        _ => None,
    }
}

/// Convenience function to detect a video input schema from a [`RawChannel`].
pub fn get_video_input_schema(channel: &RawChannel) -> Option<VideoInputSchema> {
    let schema_name = channel.schema().map(|s| s.name.as_str()).unwrap_or("");
    detect_video_schema(channel.message_encoding(), schema_name)
}

/// Metadata extracted from image messages on a video channel.
///
/// Used to populate `foxglove.videoSourceEncoding` and `foxglove.videoFrameId` channel metadata,
/// which the app uses to reconstruct the original image format from the video track.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct VideoMetadata {
    /// The image encoding (pixel format or compression codec).
    pub(crate) encoding: ImageEncoding,
    /// The coordinate frame ID of the image source (e.g. `"camera_optical_frame"`).
    pub(crate) frame_id: String,
}

/// Newtype wrapping [`I420Buffer`] that implements [`Yuv420Buffer`].
struct I420Yuv420(I420Buffer);

impl Yuv420Buffer for I420Yuv420 {
    fn dimensions(&self) -> (u32, u32) {
        (self.0.width(), self.0.height())
    }

    fn yuv(&self) -> (&[u8], &[u8], &[u8]) {
        self.0.data()
    }

    fn yuv_mut(&mut self) -> (&mut [u8], &mut [u8], &mut [u8]) {
        self.0.data_mut()
    }

    fn yuv_strides(&self) -> (u32, u32, u32) {
        self.0.strides()
    }
}

/// Error during video encoding.
#[derive(Debug, thiserror::Error)]
enum VideoEncodeError {
    #[error("failed to decode image message: {0}")]
    Decode(String),
    #[error("failed to convert image to YUV420: {0}")]
    YuvConversion(#[from] crate::img2yuv::Error),
    #[error(
        "frame {width}x{height} is below the minimum encoder size {MIN_VIDEO_DIMENSION}x{MIN_VIDEO_DIMENSION}"
    )]
    TooSmall { width: u32, height: u32 },
}

/// Publishes video frames to a LiveKit video track.
///
/// Owns a bounded channel and a background processing task. Dropping the publisher
/// closes the channel, which terminates the task.
pub(crate) struct VideoPublisher {
    tx: flume::Sender<(Bytes, u64)>,
    rx: flume::Receiver<(Bytes, u64)>,
    #[allow(dead_code)]
    video_source: NativeVideoSource,
    /// The latest video metadata observed by the background transcoding task.
    metadata: Arc<ArcSwapOption<VideoMetadata>>,
}

impl VideoPublisher {
    /// The bounded channel capacity for frame back-pressure.
    const CHANNEL_CAPACITY: usize = 2;

    /// Creates a new video publisher and spawns the background processing task.
    ///
    /// When the background task observes a change in video metadata (encoding or frame_id),
    /// it updates `metadata` and signals via `video_metadata_tx` so the session's sender loop
    /// can re-advertise the channel.
    pub fn new(
        video_source: NativeVideoSource,
        input_schema: VideoInputSchema,
        video_metadata_tx: watch::Sender<()>,
    ) -> Self {
        let (tx, rx) = flume::bounded::<(Bytes, u64)>(Self::CHANNEL_CAPACITY);
        let metadata: Arc<ArcSwapOption<VideoMetadata>> = Arc::new(ArcSwapOption::empty());
        let source = video_source.clone();
        let consumer_rx = rx.clone();
        let task_metadata = metadata.clone();
        tokio::spawn(async move {
            let mut last_metadata: Option<VideoMetadata> = None;
            // Throttles `TooSmall` warnings so a stream of undersized frames doesn't
            // flood the log; other encode errors stay at debug level and are unthrottled.
            let mut too_small_throttler = Throttler::new(TOO_SMALL_WARN_INTERVAL);
            while let Ok((data, log_time_ns)) = consumer_rx.recv_async().await {
                let source = source.clone();
                let result = tokio::task::spawn_blocking(move || {
                    transcode_and_publish(input_schema, &source, &data, log_time_ns)
                })
                .await;
                match result {
                    Ok(Ok(new_metadata)) => {
                        if last_metadata.as_ref() != Some(&new_metadata) {
                            last_metadata = Some(new_metadata.clone());
                            task_metadata.store(Some(Arc::new(new_metadata)));
                            video_metadata_tx.send_modify(|_| {});
                        }
                    }
                    Ok(Err(VideoEncodeError::TooSmall { width, height })) => {
                        if too_small_throttler.try_acquire() {
                            warn!(
                                "video frame {width}x{height} is below the minimum encoder size {MIN_VIDEO_DIMENSION}x{MIN_VIDEO_DIMENSION}; dropping frame"
                            );
                        }
                    }
                    Ok(Err(e)) => {
                        debug!("video encode error: {e}");
                    }
                    Err(e) => {
                        error!("video encode task panicked: {e}");
                    }
                }
            }
        });
        Self {
            tx,
            rx,
            video_source,
            metadata,
        }
    }

    /// Returns the latest video metadata observed by this publisher, if any.
    pub fn metadata(&self) -> arc_swap::Guard<Option<Arc<VideoMetadata>>> {
        self.metadata.load()
    }

    /// Send a frame for encoding. Non-blocking: if the channel is full, the oldest frame
    /// is dropped to make room (head-drop for minimal latency on live video).
    ///
    /// `log_time_ns` is the message log time in nanoseconds since epoch, forwarded to the
    /// video encoder as frame timestamp.
    pub fn send(&self, data: Bytes, log_time_ns: u64) {
        let msg = (data, log_time_ns);
        match self.tx.try_send(msg) {
            Ok(()) => {}
            Err(flume::TrySendError::Full(msg)) => {
                let _ = self.rx.try_recv();
                let _ = self.tx.try_send(msg);
            }
            Err(flume::TrySendError::Disconnected(_)) => {
                warn!("video publisher channel closed");
            }
        }
    }
}

/// Transcode the image message and publish it as a video frame.
///
/// Decodes the original image data, extracts metadata (encoding, frame_id),
/// encodes it as YUV 4:2:0, and publishes it to the video track.
/// Returns the extracted metadata on success.
fn transcode_and_publish(
    input_schema: VideoInputSchema,
    video_source: &NativeVideoSource,
    data: &[u8],
    log_time_ns: u64,
) -> Result<VideoMetadata, VideoEncodeError> {
    let image_msg = decode_image_message(input_schema, data)?;

    let metadata = VideoMetadata {
        encoding: image_msg.image.encoding(),
        frame_id: image_msg.frame_id.clone(),
    };

    let (width, height) = image_msg
        .image
        .probe_dimensions()
        .map_err(VideoEncodeError::YuvConversion)?;

    let (width, height) = validate_frame_dimensions(width, height)?;

    // Transcode to YUV 4:2:0.
    let mut buffer = I420Yuv420(I420Buffer::new(width, height));
    image_msg
        .image
        .to_yuv420(&mut buffer)
        .map_err(VideoEncodeError::YuvConversion)?;

    // Use the image message timestamp, if it had one, otherwise log_time.
    let timestamp_ns = match image_msg.timestamp {
        Some(ts) => ts.total_nanos(),
        None => log_time_ns,
    };

    // Publish the transcoded image to the video track.
    let frame = VideoFrame {
        rotation: VideoRotation::VideoRotation0,
        timestamp_us: (timestamp_ns / 1000) as i64,
        frame_metadata: None,
        buffer: buffer.0,
    };
    video_source.capture_frame(&frame);
    Ok(metadata)
}

/// Validates and normalizes frame dimensions for video encoding.
///
/// Aligns dimensions to even values (required for YUV 4:2:0) and rejects frames that are
/// too small for the encoder's macroblock size. Returns the even-aligned (width, height) on
/// success.
fn validate_frame_dimensions(width: u32, height: u32) -> Result<(u32, u32), VideoEncodeError> {
    let even_width = width & !1;
    let even_height = height & !1;
    if even_width == 0 || even_height == 0 {
        return Err(VideoEncodeError::YuvConversion(
            crate::img2yuv::Error::ZeroSized,
        ));
    }
    if even_width < MIN_VIDEO_DIMENSION || even_height < MIN_VIDEO_DIMENSION {
        return Err(VideoEncodeError::TooSmall { width, height });
    }
    Ok((even_width, even_height))
}

/// Decode raw message bytes into an [`ImageMessage`] based on the input schema.
fn decode_image_message<'a>(
    input_schema: VideoInputSchema,
    data: &'a [u8],
) -> Result<ImageMessage<'a>, VideoEncodeError> {
    match input_schema {
        VideoInputSchema::FoxgloveCompressedImage => {
            let msg = <crate::messages::CompressedImage as crate::Decode>::decode(data)
                .map_err(|e| VideoEncodeError::Decode(e.to_string()))?;
            ImageMessage::try_from(msg).map_err(|e| VideoEncodeError::Decode(e.to_string()))
        }
        VideoInputSchema::FoxgloveRawImage => {
            let msg = <crate::messages::RawImage as crate::Decode>::decode(data)
                .map_err(|e| VideoEncodeError::Decode(e.to_string()))?;
            ImageMessage::try_from(msg).map_err(|e| VideoEncodeError::Decode(e.to_string()))
        }
        #[cfg(feature = "img2yuv-ros1")]
        VideoInputSchema::Ros1CompressedImage => {
            let msg = crate::img2yuv::ros1::Ros1CompressedImage::decode(data)
                .map_err(|e| VideoEncodeError::Decode(e.to_string()))?;
            ImageMessage::try_from(msg).map_err(|e| VideoEncodeError::Decode(e.to_string()))
        }
        #[cfg(feature = "img2yuv-ros1")]
        VideoInputSchema::Ros1Image => {
            let msg = crate::img2yuv::ros1::Ros1Image::decode(data)
                .map_err(|e| VideoEncodeError::Decode(e.to_string()))?;
            ImageMessage::try_from(msg).map_err(|e| VideoEncodeError::Decode(e.to_string()))
        }
        #[cfg(feature = "img2yuv-ros2")]
        VideoInputSchema::Ros2CompressedImage => {
            let msg = crate::img2yuv::ros2::Ros2CompressedImage::decode(data)
                .map_err(|e| VideoEncodeError::Decode(e.to_string()))?;
            ImageMessage::try_from(msg).map_err(|e| VideoEncodeError::Decode(e.to_string()))
        }
        #[cfg(feature = "img2yuv-ros2")]
        VideoInputSchema::Ros2Image => {
            let msg = crate::img2yuv::ros2::Ros2Image::decode(data)
                .map_err(|e| VideoEncodeError::Decode(e.to_string()))?;
            ImageMessage::try_from(msg).map_err(|e| VideoEncodeError::Decode(e.to_string()))
        }
    }
}

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

    #[test]
    fn test_foxglove_compressed_image() {
        assert_eq!(
            detect_video_schema("protobuf", "foxglove.CompressedImage"),
            Some(VideoInputSchema::FoxgloveCompressedImage)
        );
    }

    #[test]
    fn test_foxglove_raw_image() {
        assert_eq!(
            detect_video_schema("protobuf", "foxglove.RawImage"),
            Some(VideoInputSchema::FoxgloveRawImage)
        );
    }

    #[cfg(feature = "img2yuv-ros1")]
    #[test]
    fn test_ros1_compressed_image() {
        assert_eq!(
            detect_video_schema("ros1", "sensor_msgs/CompressedImage"),
            Some(VideoInputSchema::Ros1CompressedImage)
        );
    }

    #[cfg(feature = "img2yuv-ros1")]
    #[test]
    fn test_ros1_image() {
        assert_eq!(
            detect_video_schema("ros1", "sensor_msgs/Image"),
            Some(VideoInputSchema::Ros1Image)
        );
    }

    #[cfg(feature = "img2yuv-ros2")]
    #[test]
    fn test_ros2_compressed_image() {
        assert_eq!(
            detect_video_schema("cdr", "sensor_msgs/msg/CompressedImage"),
            Some(VideoInputSchema::Ros2CompressedImage)
        );
    }

    #[cfg(feature = "img2yuv-ros2")]
    #[test]
    fn test_ros2_image() {
        assert_eq!(
            detect_video_schema("cdr", "sensor_msgs/msg/Image"),
            Some(VideoInputSchema::Ros2Image)
        );
    }

    #[test]
    fn test_unknown_schema() {
        assert_eq!(detect_video_schema("json", "SomeCustomType"), None);
        assert_eq!(detect_video_schema("protobuf", "foxglove.Pose"), None);
    }

    #[test]
    fn validate_frame_dimensions_rejects_too_small() {
        // Both axes below minimum
        let err = validate_frame_dimensions(15, 15).unwrap_err();
        assert!(matches!(
            err,
            VideoEncodeError::TooSmall {
                width: 15,
                height: 15
            }
        ));

        // Width below minimum, height at minimum
        let err = validate_frame_dimensions(15, 16).unwrap_err();
        assert!(matches!(
            err,
            VideoEncodeError::TooSmall {
                width: 15,
                height: 16
            }
        ));

        // Height below minimum, width at minimum
        let err = validate_frame_dimensions(16, 15).unwrap_err();
        assert!(matches!(
            err,
            VideoEncodeError::TooSmall {
                width: 16,
                height: 15
            }
        ));

        // Odd dimension that rounds down below minimum (17 & !1 == 16, but 15 & !1 == 14)
        let err = validate_frame_dimensions(15, 17).unwrap_err();
        assert!(matches!(
            err,
            VideoEncodeError::TooSmall {
                width: 15,
                height: 17
            }
        ));
    }

    #[test]
    fn validate_frame_dimensions_accepts_at_minimum() {
        // Exactly at the minimum boundary
        assert_eq!(validate_frame_dimensions(16, 16).unwrap(), (16, 16));

        // Just above minimum (odd values get even-aligned down)
        assert_eq!(validate_frame_dimensions(17, 17).unwrap(), (16, 16));

        // Larger values
        assert_eq!(validate_frame_dimensions(1920, 1080).unwrap(), (1920, 1080));
    }

    #[test]
    fn validate_frame_dimensions_rejects_zero_after_alignment() {
        // A 1×1 image rounds to 0×0
        let err = validate_frame_dimensions(1, 1).unwrap_err();
        assert!(matches!(
            err,
            VideoEncodeError::YuvConversion(crate::img2yuv::Error::ZeroSized)
        ));

        // Width 0
        let err = validate_frame_dimensions(0, 16).unwrap_err();
        assert!(matches!(
            err,
            VideoEncodeError::YuvConversion(crate::img2yuv::Error::ZeroSized)
        ));

        // Height 0
        let err = validate_frame_dimensions(16, 0).unwrap_err();
        assert!(matches!(
            err,
            VideoEncodeError::YuvConversion(crate::img2yuv::Error::ZeroSized)
        ));
    }
}