re_data_loader 0.31.3

Handles loading of Rerun data from file using data loader plugins
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
//! Handles loading of Rerun data from file using data loader plugins.

use std::collections::BTreeSet;
use std::sync::{Arc, LazyLock};

use re_chunk::{Chunk, ChunkResult};
use re_log_types::{ArrowMsg, EntityPath, LogMsg, RecordingId, StoreId, TimePoint};

// ----------------------------------------------------------------------------

mod load_file;
mod loader_archetype;
mod loader_directory;
mod loader_rrd;
mod loader_urdf;

#[cfg(not(target_arch = "wasm32"))]
pub mod lerobot;

// This loader currently only works when loading the entire dataset directory, and we cannot do that on web yet.
#[cfg(not(target_arch = "wasm32"))]
pub mod loader_lerobot;

// This loader currently uses native-only features under the hood, and we cannot do that on web yet.
pub mod loader_mcap;

#[cfg(not(target_arch = "wasm32"))]
mod loader_external;

pub use self::load_file::load_from_file_contents;
pub use self::loader_archetype::ArchetypeLoader;
pub use self::loader_directory::DirectoryLoader;
pub use self::loader_mcap::McapLoader;
pub use self::loader_rrd::RrdLoader;
pub use self::loader_urdf::{UrdfDataLoader, UrdfTree, joint_transform as urdf_joint_transform};
#[cfg(not(target_arch = "wasm32"))]
pub use self::{
    load_file::load_from_path,
    loader_external::{
        EXTERNAL_DATA_LOADER_INCOMPATIBLE_EXIT_CODE, EXTERNAL_DATA_LOADER_PREFIX, ExternalLoader,
        iter_external_loaders,
    },
    loader_lerobot::LeRobotDatasetLoader,
};

pub mod external {
    pub use urdf_rs;
}

// ----------------------------------------------------------------------------

/// The identifier used to enable or disable Foxglove lenses when loading MCAP files.
pub const FOXGLOVE_LENSES_IDENTIFIER: &str = "foxglove";

/// The identifier used to enable or disable URDF extraction from MCAP `robot_description` topics.
pub const URDF_DECODER_IDENTIFIER: &str = "urdf";

/// All decoder-like identifiers supported by [`McapLoader`].
///
/// This merges the built-in MCAP decoders from [`re_mcap`] and the semantic interpretation (e.g. lenses) that are in this crate.
pub fn supported_mcap_decoder_identifiers(
    raw_fallback_enabled: bool,
) -> Vec<re_mcap::DecoderIdentifier> {
    let mut identifiers = re_mcap::DecoderRegistry::all_builtin(raw_fallback_enabled)
        .all_identifiers()
        .into_iter()
        .map(re_mcap::DecoderIdentifier::from)
        .collect::<BTreeSet<_>>();

    identifiers.extend([
        re_mcap::DecoderIdentifier::from(FOXGLOVE_LENSES_IDENTIFIER),
        re_mcap::DecoderIdentifier::from(URDF_DECODER_IDENTIFIER),
    ]);

    identifiers.into_iter().collect()
}

// ----------------------------------------------------------------------------

/// Recommended settings for the [`DataLoader`].
///
/// The loader is free to ignore some or all of these.
///
/// External [`DataLoader`]s will be passed the following CLI parameters:
/// * `--application-id <application_id>`
/// * `--opened-application-id <opened_application_id>` (if set)
/// * `--recording-id <store_id>`
/// * `--opened-recording-id <opened_store_id>` (if set)
/// * `--entity-path-prefix <entity_path_prefix>` (if set)
/// * `--static` (if `timepoint` is set to the timeless timepoint)
/// * `--timeless` \[deprecated\] (if `timepoint` is set to the timeless timepoint)
/// * `--time_sequence <timeline1>=<seq1> <timeline2>=<seq2> ...` (if `timepoint` contains sequence data)
/// * `--time_duration_nanos <timeline1>=<duration1> <timeline2>=<duration2> ...` (if `timepoint` contains duration data) in nanos
/// * `--time_timestamp_nanos <timeline1>=<timestamp1> <timeline2>=<timestamp2> ...` (if `timepoint` contains timestamp data) in nanos since epoch
#[derive(Debug, Clone)]
pub struct DataLoaderSettings {
    /// The recommended [`re_log_types::ApplicationId`] to log the data to, based on the surrounding context.
    pub application_id: Option<re_log_types::ApplicationId>,

    /// The recommended recording id to log the data to, based on the surrounding context.
    ///
    /// Log data to this recording if you want it to appear in a new recording shared by all
    /// data-loaders for the current loading session.
    pub recording_id: RecordingId,

    /// The [`re_log_types::StoreId`] that is currently opened in the viewer, if any.
    pub opened_store_id: Option<StoreId>,

    /// Whether `SetStoreInfo`s should be sent, regardless of the surrounding context.
    ///
    /// Only useful when creating a recording just-in-time directly in the viewer (which is what
    /// happens when importing things into the welcome screen).
    pub force_store_info: bool,

    /// What should the logged entity paths be prefixed with?
    pub entity_path_prefix: Option<EntityPath>,

    /// At what time(s) should the data be logged to?
    pub timepoint: Option<TimePoint>,

    /// If `true`, keep reading `.rrd` files past EOF, tailing new data as it arrives.
    ///
    /// Defaults to `false`.
    pub follow: bool,

    /// If set, an offset in nanoseconds to add to all `TimestampNs` time columns.
    pub timestamp_offset_ns: Option<i64>,

    /// The timeline type to use for timestamp timelines.
    ///
    /// Defaults to [`re_log_types::TimeType::TimestampNs`].
    /// When set to [`re_log_types::TimeType::DurationNs`], all timestamp timelines
    /// will be created as duration timelines instead.
    pub timeline_type: re_log_types::TimeType,
}

impl DataLoaderSettings {
    #[inline]
    pub fn recommended(recording_id: impl Into<RecordingId>) -> Self {
        Self {
            recording_id: recording_id.into(),
            application_id: None,
            opened_store_id: None,
            force_store_info: false,
            entity_path_prefix: None,
            timepoint: None,
            follow: false,
            timestamp_offset_ns: None,
            timeline_type: re_log_types::TimeType::TimestampNs,
        }
    }

    /// Returns the recommended [`re_log_types::StoreId`] to log the data to.
    pub fn recommended_store_id(&self) -> StoreId {
        StoreId::recording(
            self.application_id
                .clone()
                .unwrap_or_else(re_log_types::ApplicationId::random),
            self.recording_id.clone(),
        )
    }

    /// Returns the currently opened [`re_log_types::StoreId`] if any. Otherwise, returns the
    /// recommended store id.
    pub fn opened_store_id_or_recommended(&self) -> StoreId {
        self.opened_store_id
            .clone()
            .unwrap_or_else(|| self.recommended_store_id())
    }

    /// Generates CLI flags from these settings, for external data loaders.
    pub fn to_cli_args(&self) -> Vec<String> {
        let Self {
            application_id,
            recording_id,
            opened_store_id,
            force_store_info: _,
            entity_path_prefix,
            timepoint,
            follow: _,
            timestamp_offset_ns: _,
            timeline_type: _,
        } = self;

        let mut args = Vec::new();

        if let Some(application_id) = application_id {
            args.extend(["--application-id".to_owned(), format!("{application_id}")]);
        }
        args.extend(["--recording-id".to_owned(), format!("{recording_id}")]);

        if let Some(opened_store_id) = opened_store_id {
            args.extend([
                "--opened-application-id".to_owned(),
                format!("{}", opened_store_id.application_id()),
            ]);

            args.extend([
                "--opened-recording-id".to_owned(),
                format!("{}", opened_store_id.recording_id()),
            ]);
        }

        if let Some(entity_path_prefix) = entity_path_prefix {
            args.extend([
                "--entity-path-prefix".to_owned(),
                format!("{entity_path_prefix}"),
            ]);
        }

        if let Some(timepoint) = timepoint {
            if timepoint.is_static() {
                args.push("--timeless".to_owned()); // for backwards compatibility
                args.push("--static".to_owned());
            }

            for (timeline, cell) in timepoint.iter() {
                match cell.typ() {
                    re_log_types::TimeType::Sequence => {
                        args.extend([
                            "--time_sequence".to_owned(),
                            format!("{timeline}={}", cell.value),
                        ]);

                        // for backwards compatibility:
                        args.extend([
                            "--sequence".to_owned(),
                            format!("{timeline}={}", cell.value),
                        ]);
                    }
                    re_log_types::TimeType::DurationNs => {
                        args.extend([
                            "--time_duration_nanos".to_owned(),
                            format!("{timeline}={}", cell.value),
                        ]);

                        // for backwards compatibility:
                        args.extend(["--time".to_owned(), format!("{timeline}={}", cell.value)]);
                    }
                    re_log_types::TimeType::TimestampNs => {
                        args.extend([
                            "--time_duration_nanos".to_owned(),
                            format!("{timeline}={}", cell.value),
                        ]);

                        // for backwards compatibility:
                        args.extend([
                            "--sequence".to_owned(),
                            format!("{timeline}={}", cell.value),
                        ]);
                    }
                }
            }
        }

        args
    }
}

pub type DataLoaderName = String;

/// A [`DataLoader`] loads data from a file path and/or a file's contents.
///
/// Files can be loaded in 3 different ways:
/// - via the Rerun CLI (`rerun myfile.jpeg`),
/// - using drag-and-drop,
/// - using the open dialog in the Rerun Viewer.
///
/// All these file loading methods support loading a single file, many files at once, or even
/// folders.
/// âš  Drag-and-drop of folders does not yet work on the web version of Rerun Viewer âš 
///
/// We only support loading files from the local filesystem at the moment, and consequently only
/// accept filepaths as input.
/// [There are plans to make this generic over any URI](https://github.com/rerun-io/rerun/issues/4525).
///
/// Rerun comes with a few [`DataLoader`]s by default:
/// - [`RrdLoader`] for [Rerun files].
/// - [`ArchetypeLoader`] for:
///     - [3D models]
///     - [Images]
///     - [Point clouds]
///     - [Text files]
/// - [`DirectoryLoader`] for recursively loading folders.
/// - [`ExternalLoader`], which looks for user-defined data loaders in $PATH.
///
/// ## Registering custom loaders
///
/// Checkout our [guide](https://www.rerun.io/docs/concepts/logging-and-ingestion/data-loaders/overview).
///
/// ## Execution
///
/// **All** known [`DataLoader`]s get called when a user tries to open a file, unconditionally.
/// This gives [`DataLoader`]s maximum flexibility to decide what files they are interested in, as
/// opposed to e.g. only being able to look at files' extensions.
///
/// If a [`DataLoader`] has no interest in the given file, it should fail as soon as possible
/// with a [`DataLoaderError::Incompatible`] error.
///
/// Iff all [`DataLoader`]s (including custom and external ones) return with a [`DataLoaderError::Incompatible`]
/// error, the Viewer will show an error message to the user indicating that the file type is not
/// supported.
///
/// On native, [`DataLoader`]s are executed in parallel.
///
/// [Rerun files]: crate::SUPPORTED_RERUN_EXTENSIONS
/// [3D models]: crate::SUPPORTED_MESH_EXTENSIONS
/// [Images]: crate::SUPPORTED_IMAGE_EXTENSIONS
/// [Point clouds]: crate::SUPPORTED_POINT_CLOUD_EXTENSIONS
/// [Text files]: crate::SUPPORTED_TEXT_EXTENSIONS
//
// TODO(#4525): `DataLoader`s should support arbitrary URIs
// TODO(#4527): Web Viewer `?url` parameter should accept anything our `DataLoader`s support
pub trait DataLoader: Send + Sync {
    /// Name of the [`DataLoader`].
    ///
    /// Should be globally unique.
    fn name(&self) -> DataLoaderName;

    /// Loads data from a file on the local filesystem and sends it to `tx`.
    ///
    /// This is generally called when opening files with the Rerun CLI or via the open menu in the
    /// Rerun Viewer on native platforms.
    ///
    /// The passed-in `store_id` is a shared recording created by the file loading machinery:
    /// implementers can decide to use it or not (e.g. it might make sense to log all images with a
    /// similar name in a shared recording, while an rrd file is already its own recording).
    ///
    /// `path` isn't necessarily a _file_ path, but can be a directory as well: implementers are
    /// free to handle that however they decide.
    ///
    /// ## Error handling
    ///
    /// Most implementers of `load_from_path` are expected to be asynchronous in nature.
    ///
    /// Asynchronous implementers should make sure to fail early (and thus synchronously) when
    /// possible (e.g. didn't even manage to open the file).
    /// Otherwise, they should log errors that happen in an asynchronous context.
    ///
    /// If a [`DataLoader`] has no interest in the given file, it should fail as soon as possible
    /// with a [`DataLoaderError::Incompatible`] error.
    #[cfg(not(target_arch = "wasm32"))]
    fn load_from_path(
        &self,
        settings: &DataLoaderSettings,
        path: std::path::PathBuf,
        tx: crossbeam::channel::Sender<LoadedData>,
    ) -> Result<(), DataLoaderError>;

    /// Loads data from in-memory file contents and sends it to `tx`.
    ///
    /// This is generally called when opening files via drag-and-drop or when using the web viewer.
    ///
    /// The passed-in `store_id` is a shared recording created by the file loading machinery:
    /// implementers can decide to use it or not (e.g. it might make sense to log all images with a
    /// similar name in a shared recording, while an rrd file is already its own recording).
    ///
    /// The `path` of the file is given for informational purposes (e.g. to extract the file's
    /// extension): implementers should _not_ try to read from disk as there is likely isn't a
    /// filesystem available to begin with.
    /// `path` is guaranteed to be a file path.
    ///
    /// When running on the web (wasm), `filepath` only contains the file name.
    ///
    /// ## Error handling
    ///
    /// Most implementers of `load_from_file_contents` are expected to be asynchronous in nature.
    ///
    /// Asynchronous implementers should make sure to fail early (and thus synchronously) when
    /// possible (e.g. didn't even manage to open the file).
    /// Otherwise, they should log errors that happen in an asynchronous context.
    ///
    /// If a [`DataLoader`] has no interest in the given file, it should fail as soon as possible
    /// with a [`DataLoaderError::Incompatible`] error.
    fn load_from_file_contents(
        &self,
        settings: &DataLoaderSettings,
        filepath: std::path::PathBuf,
        contents: std::borrow::Cow<'_, [u8]>,
        tx: crossbeam::channel::Sender<LoadedData>,
    ) -> Result<(), DataLoaderError>;
}

/// Errors that might happen when loading data through a [`DataLoader`].
#[derive(thiserror::Error, Debug)]
pub enum DataLoaderError {
    #[cfg(not(target_arch = "wasm32"))]
    #[error(transparent)]
    IO(#[from] std::io::Error),

    #[error(transparent)]
    Arrow(#[from] arrow::error::ArrowError),

    #[error(transparent)]
    Chunk(#[from] re_chunk::ChunkError),

    #[error(transparent)]
    Decode(#[from] re_log_encoding::DecodeError),

    #[error("No data-loader support for {0:?}")]
    Incompatible(std::path::PathBuf),

    #[error(transparent)]
    Mcap(#[from] ::mcap::McapError),

    #[error("{}", re_error::format(.0))]
    Other(#[from] anyhow::Error),
}

impl DataLoaderError {
    #[inline]
    pub fn is_path_not_found(&self) -> bool {
        match self {
            #[cfg(not(target_arch = "wasm32"))]
            Self::IO(err) => err.kind() == std::io::ErrorKind::NotFound,
            _ => false,
        }
    }

    #[inline]
    pub fn is_incompatible(&self) -> bool {
        matches!(self, Self::Incompatible { .. })
    }
}

/// What [`DataLoader`]s load.
///
/// This makes it trivial for [`DataLoader`]s to build the data in whatever form is
/// most convenient for them, whether it is raw components, arrow chunks or even
/// full-on [`LogMsg`]s.
#[derive(Debug)]
pub enum LoadedData {
    Chunk(DataLoaderName, re_log_types::StoreId, Chunk),
    ArrowMsg(DataLoaderName, re_log_types::StoreId, ArrowMsg),
    LogMsg(DataLoaderName, LogMsg),
}

impl LoadedData {
    /// Returns the name of the [`DataLoader`] that generated this data.
    #[inline]
    pub fn data_loader_name(&self) -> &DataLoaderName {
        match self {
            Self::Chunk(name, ..) | Self::ArrowMsg(name, ..) | Self::LogMsg(name, ..) => name,
        }
    }

    /// Pack the data into a [`LogMsg`].
    #[inline]
    pub fn into_log_msg(self) -> ChunkResult<LogMsg> {
        match self {
            Self::Chunk(_name, store_id, chunk) => {
                Ok(LogMsg::ArrowMsg(store_id, chunk.to_arrow_msg()?))
            }

            Self::ArrowMsg(_name, store_id, msg) => Ok(LogMsg::ArrowMsg(store_id, msg)),

            Self::LogMsg(_name, msg) => Ok(msg),
        }
    }

    /// Convert the data into a [`Chunk`], ignoring all non-chunk-related things.
    pub fn into_chunk(self) -> Option<Chunk> {
        match self {
            Self::Chunk(_name, _store_id, chunk) => Some(chunk),
            Self::ArrowMsg(_name, _store_id, arrow_msg) => Chunk::from_arrow_msg(&arrow_msg).ok(),
            Self::LogMsg(_name, msg) => match msg {
                LogMsg::ArrowMsg(_store_id, arrow_msg) => Chunk::from_arrow_msg(&arrow_msg).ok(),
                LogMsg::SetStoreInfo { .. } | LogMsg::BlueprintActivationCommand { .. } => None,
            },
        }
    }
}

// ----------------------------------------------------------------------------

/// Keeps track of all builtin [`DataLoader`]s.
///
/// Lazy initialized the first time a file is opened.
static BUILTIN_LOADERS: LazyLock<Vec<Arc<dyn DataLoader>>> = LazyLock::new(|| {
    vec![
        Arc::new(RrdLoader) as Arc<dyn DataLoader>,
        Arc::new(ArchetypeLoader),
        Arc::new(DirectoryLoader),
        Arc::new(McapLoader::default()),
        #[cfg(not(target_arch = "wasm32"))]
        Arc::new(LeRobotDatasetLoader),
        #[cfg(not(target_arch = "wasm32"))]
        Arc::new(ExternalLoader),
        Arc::new(UrdfDataLoader),
    ]
});

/// Iterator over all registered [`DataLoader`]s.
#[inline]
pub fn iter_loaders() -> impl Iterator<Item = Arc<dyn DataLoader>> {
    BUILTIN_LOADERS
        .clone()
        .into_iter()
        .chain(CUSTOM_LOADERS.read().clone())
}

/// Keeps track of all custom [`DataLoader`]s.
///
/// Use [`register_custom_data_loader`] to add new loaders.
static CUSTOM_LOADERS: LazyLock<parking_lot::RwLock<Vec<Arc<dyn DataLoader>>>> =
    LazyLock::new(parking_lot::RwLock::default);

/// Register a custom [`DataLoader`].
///
/// Any time the Rerun Viewer opens a file or directory, this custom loader will be notified.
/// Refer to [`DataLoader`]'s documentation for more information.
#[inline]
pub fn register_custom_data_loader(loader: impl DataLoader + 'static) {
    CUSTOM_LOADERS.write().push(Arc::new(loader));
}

// ----------------------------------------------------------------------------

/// Empty string if no extension.
#[inline]
pub(crate) fn extension(path: &std::path::Path) -> String {
    path.extension()
        .unwrap_or_default()
        .to_ascii_lowercase()
        .to_string_lossy()
        .to_string()
}

// ----------------------------------------------------------------------------

// …given that all feature flags are turned on for the `image` crate.
pub const SUPPORTED_IMAGE_EXTENSIONS: &[&str] = &[
    "avif", "bmp", "dds", "exr", "farbfeld", "ff", "gif", "hdr", "ico", "jpeg", "jpg", "pam",
    "pbm", "pgm", "png", "ppm", "tga", "tif", "tiff", "webp",
];

pub const SUPPORTED_DEPTH_IMAGE_EXTENSIONS: &[&str] = &["rvl", "png"];

pub const SUPPORTED_VIDEO_EXTENSIONS: &[&str] = &["mp4"];

pub const SUPPORTED_MESH_EXTENSIONS: &[&str] = &["glb", "gltf", "obj", "stl", "dae"];

// TODO(#4532): `.ply` data loader should support 2D point cloud & meshes
pub const SUPPORTED_POINT_CLOUD_EXTENSIONS: &[&str] = &["ply"];

pub const SUPPORTED_RERUN_EXTENSIONS: &[&str] = &["rbl", "rrd"];

/// 3rd party formats with built-in support.
pub const SUPPORTED_THIRD_PARTY_FORMATS: &[&str] = &["mcap", "urdf"];

// TODO(#4555): Add catch-all builtin `DataLoader` for text files
pub const SUPPORTED_TEXT_EXTENSIONS: &[&str] = &["txt", "md"];

/// All file extension supported by our builtin [`DataLoader`]s.
pub fn supported_extensions() -> impl Iterator<Item = &'static str> {
    SUPPORTED_RERUN_EXTENSIONS
        .iter()
        .chain(SUPPORTED_THIRD_PARTY_FORMATS)
        .chain(SUPPORTED_IMAGE_EXTENSIONS)
        .chain(SUPPORTED_DEPTH_IMAGE_EXTENSIONS)
        .chain(SUPPORTED_VIDEO_EXTENSIONS)
        .chain(SUPPORTED_MESH_EXTENSIONS)
        .chain(SUPPORTED_POINT_CLOUD_EXTENSIONS)
        .chain(SUPPORTED_TEXT_EXTENSIONS)
        .copied()
}

/// Is this a supported file extension by any of our builtin [`DataLoader`]s?
pub fn is_supported_file_extension(extension: &str) -> bool {
    re_log::debug_assert!(
        !extension.starts_with('.'),
        "Expected extension without period, but got {extension:?}"
    );
    let extension = extension.to_lowercase();
    supported_extensions().any(|ext| ext == extension)
}

/// Detect the file format from the first bytes of a file (magic bytes).
///
/// Returns the file extension (e.g., `"rrd"`, `"mcap"`, `"png"`) if the format is recognized.
///
/// Delegates to [`re_sdk_types::components::MediaType::guess_from_data`] which handles
/// Robotics-specific formats (RRD, MCAP, PLY) and standard formats (PNG, JPEG, GLB, MP4, etc.).
pub fn detect_format_from_bytes(bytes: &[u8]) -> Option<String> {
    let media_type = re_sdk_types::components::MediaType::guess_from_data(bytes)?;
    media_type.file_extension().map(|e| e.to_owned())
}

/// Map a MIME content type to a file extension.
///
/// Returns `None` for types that are too generic to be useful (e.g. `application/octet-stream`)
/// or for unrecognized types.
///
/// Delegates to [`re_sdk_types::components::MediaType::file_extension`].
pub fn content_type_to_extension(content_type: &str) -> Option<String> {
    // Take just the MIME type, ignoring parameters like charset
    let mime = content_type.split(';').next()?.trim();

    // Skip overly generic types
    if mime == "application/octet-stream" {
        return None;
    }

    let media_type = re_sdk_types::components::MediaType(mime.to_owned().into());
    media_type.file_extension().map(|e| e.to_owned())
}

#[test]
fn test_supported_extensions() {
    assert!(is_supported_file_extension("rrd"));
    assert!(is_supported_file_extension("mcap"));
    assert!(is_supported_file_extension("png"));
    assert!(is_supported_file_extension("urdf"));
}

#[test]
fn test_supported_mcap_decoder_identifiers() {
    let identifiers = supported_mcap_decoder_identifiers(true);
    let as_strings = identifiers
        .iter()
        .map(ToString::to_string)
        .collect::<Vec<_>>();

    // Check that expected identifiers are present.
    assert!(as_strings.contains(&FOXGLOVE_LENSES_IDENTIFIER.to_owned()));
    assert!(as_strings.contains(&URDF_DECODER_IDENTIFIER.to_owned()));
    assert!(as_strings.contains(&"raw".to_owned()));
    assert!(as_strings.contains(&"protobuf".to_owned()));
    assert!(as_strings.contains(&"ros2msg".to_owned()));

    // Check that all identifiers are unique.
    let unique = as_strings.iter().collect::<std::collections::BTreeSet<_>>();
    assert_eq!(as_strings.len(), unique.len());
}

#[test]
fn test_detect_format_from_bytes() {
    assert_eq!(
        detect_format_from_bytes(b"RRF2xxxxx").as_deref(),
        Some("rrd")
    );
    assert_eq!(
        detect_format_from_bytes(b"RRF0xxxxx").as_deref(),
        Some("rrd")
    );
    assert_eq!(
        detect_format_from_bytes(&[0x89, 0x4D, 0x43, 0x41, 0x50, 0x30, 0x0D, 0x0A]).as_deref(),
        Some("mcap")
    );
    assert_eq!(
        detect_format_from_bytes(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]).as_deref(),
        Some("png")
    );
    assert_eq!(
        detect_format_from_bytes(&[0xFF, 0xD8, 0xFF, 0xE0]).as_deref(),
        Some("jpg")
    );
    assert_eq!(
        detect_format_from_bytes(b"glTFxxxx").as_deref(),
        Some("glb")
    );
    assert_eq!(
        detect_format_from_bytes(b"ply\nxxx").as_deref(),
        Some("ply")
    );
    assert_eq!(detect_format_from_bytes(b"unknown").as_deref(), None);
    assert_eq!(detect_format_from_bytes(b"").as_deref(), None);
}

#[test]
fn test_content_type_to_extension() {
    assert_eq!(
        content_type_to_extension("image/png").as_deref(),
        Some("png")
    );
    assert_eq!(
        content_type_to_extension("image/png; charset=utf-8").as_deref(),
        Some("png")
    );
    assert_eq!(
        content_type_to_extension("image/jpeg").as_deref(),
        Some("jpg")
    );
    assert_eq!(
        content_type_to_extension("video/mp4").as_deref(),
        Some("mp4")
    );
    assert_eq!(
        content_type_to_extension("model/gltf-binary").as_deref(),
        Some("glb")
    );
    assert_eq!(
        content_type_to_extension("application/x-rerun").as_deref(),
        Some("rrd")
    );
    assert_eq!(
        content_type_to_extension("application/octet-stream").as_deref(),
        None
    );
}