re_importer 0.35.0

Handles importing of Rerun data from file using importer 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
//! MCAP file importer implementation.

use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;

use crossbeam::channel::Sender;
use re_chunk::RowId;
use re_lenses::Lenses;
use re_log_types::{SetStoreInfo, StoreId, StoreInfo};
use re_mcap::{DecoderIdentifier, DecoderRegistry, SelectedDecoders, TopicFilter};
use re_quota_channel::send_crossbeam;

use crate::{ImportedData, Importer, ImporterError, ImporterSettings, URDF_DECODER_IDENTIFIER};

const MCAP_IMPORTER_NAME: &str = "McapImporter";

/// An [`Importer`] for MCAP files.
///
/// There are many different ways to extract and interpret information from MCAP files.
/// For example, it might be interesting to query for particular fields of messages,
/// or show information directly in the Rerun viewer. Because use-cases can vary, the
/// [`McapImporter`] is made up of [`re_mcap::Decoder`]s, each representing different views of the
/// underlying data.
///
/// These decoders can be specified in the CLI when converting an MCAP file
/// to an .rrd. Here are a few examples:
/// - [`re_mcap::decoders::McapProtobufDecoder`]
/// - [`re_mcap::decoders::McapRawDecoder`]
#[derive(Clone)]
pub struct McapImporter {
    selected_decoders: SelectedDecoders,
    // TODO(RR-3491): We don't need the fallback logic anymore; use `OutputMode` instead.
    raw_fallback_enabled: bool,
    topic_filter: TopicFilter,
    time_range: Option<(u64, u64)>,
    recover: bool,
    lenses_by_time_type: HashMap<re_log_types::TimeType, Arc<Lenses>>,
}

impl Default for McapImporter {
    fn default() -> Self {
        Self::new(&SelectedDecoders::All)
    }
}

impl McapImporter {
    /// Creates a new [`McapImporter`] that uses the specified decoders.
    pub fn new(selected_decoders: &SelectedDecoders) -> Self {
        // Cache lenses for each supported timeline type.
        let mut lenses_by_time_type = HashMap::new();
        for time_type in [
            re_log_types::TimeType::TimestampNs,
            re_log_types::TimeType::DurationNs,
        ] {
            if let Some(lenses) = Self::build_lenses(selected_decoders, time_type) {
                lenses_by_time_type.insert(time_type, lenses);
            }
        }
        Self {
            selected_decoders: selected_decoders.clone(),
            raw_fallback_enabled: true,
            topic_filter: TopicFilter::default(),
            time_range: None,
            recover: false,
            lenses_by_time_type,
        }
    }

    /// Configures whether the raw decoder is used as a fallback for unsupported channels.
    pub fn with_raw_fallback(mut self, raw_fallback_enabled: bool) -> Self {
        self.raw_fallback_enabled = raw_fallback_enabled;
        self
    }

    /// Configures a regex-based topic filter.
    ///
    /// See [`TopicFilter`] for matching semantics.
    pub fn with_topic_filter(mut self, topic_filter: TopicFilter) -> Self {
        self.topic_filter = topic_filter;
        self
    }

    /// Restricts decoding to messages whose MCAP `log_time` falls in `[start, end)` (nanoseconds).
    ///
    /// This filters on the raw MCAP `log_time`, i.e. *before* any `timestamp_offset_ns` is applied
    /// and before content-derived timelines. Chunks whose index bounds fall entirely outside the
    /// range are skipped before decompression, so this bounds peak memory as well as output.
    /// `None` clears the filter.
    pub fn with_time_range(mut self, time_range: Option<(u64, u64)>) -> Self {
        self.time_range = time_range;
        self
    }

    /// Enables recovery of truncated / summary-less MCAP files.
    ///
    /// When set, [`Self::emit_chunks`] reconstructs a [`re_mcap::Summary`] in memory (via
    /// [`re_mcap::read_or_reconstruct_summary`]) if the file has no valid summary — the incomplete tail
    /// chunk/record is dropped with a warning, and channels declared only in the dropped tail are
    /// lost. The recovered statistics therefore only count the channels and messages that could be
    /// recovered.
    pub fn with_recover(mut self, recover: bool) -> Self {
        self.recover = recover;
        self
    }

    /// Returns the cached lenses for the given [`re_log_types::TimeType`].
    fn lenses_for(&self, time_type: re_log_types::TimeType) -> Option<Arc<Lenses>> {
        if time_type == re_log_types::TimeType::Sequence {
            re_log::error_once!("Sequence is not a supported timeline type for MCAP lenses");
            return None;
        }
        self.lenses_by_time_type.get(&time_type).cloned()
    }

    fn build_lenses(
        selected_decoders: &SelectedDecoders,
        time_type: re_log_types::TimeType,
    ) -> Option<Arc<Lenses>> {
        match super::lenses::mcap_lenses(selected_decoders, time_type) {
            Ok(Some(lenses)) => Some(Arc::new(lenses)),
            Ok(None) => None,
            Err(err) => {
                re_log::error_once!(
                    "Failed to build MCAP lenses: {err}. MCAP importer will run without them."
                );
                None
            }
        }
    }

    /// Load chunks from MCAP bytes, calling `emit_chunk` for each produced chunk.
    ///
    /// Bypasses the [`Importer`] / [`ImportedData`] / `SetStoreInfo` ceremony.
    /// Uses the decoders, raw fallback, and lenses already configured on this importer.
    pub fn emit_chunks(
        &self,
        mcap: &[u8],
        timeline_type: re_log_types::TimeType,
        timestamp_offset_ns: Option<i64>,
        emit_chunk: &(dyn Fn(re_chunk::Chunk) + Send + Sync),
    ) -> Result<(), ImporterError> {
        let summary = re_mcap::read_or_reconstruct_summary(mcap, self.recover)
            .map_err(anyhow::Error::from)?;
        self.emit_chunks_with_summary(
            mcap,
            &summary,
            timeline_type,
            timestamp_offset_ns,
            emit_chunk,
        )
    }

    /// Like [`Self::emit_chunks`], but reuses an already-read [`re_mcap::Summary`] rather than
    /// parsing it from `mcap` again. The summary must be the one for `mcap`.
    ///
    /// Parsing the summary walks every chunk index, so for large files it is a real cost. When a
    /// single file is scanned repeatedly (e.g. windowed reads), read the summary once and pass it
    /// in here to avoid re-parsing it on every scan.
    pub fn emit_chunks_with_summary(
        &self,
        mcap: &[u8],
        summary: &re_mcap::Summary,
        timeline_type: re_log_types::TimeType,
        timestamp_offset_ns: Option<i64>,
        emit_chunk: &(dyn Fn(re_chunk::Chunk) + Send + Sync),
    ) -> Result<(), ImporterError> {
        // Tag the scope with the time range so each window of a windowed read is a distinct span.
        re_tracing::profile_function!(match self.time_range {
            Some((start, end)) => format!("log_time [{start}, {end})"),
            None => "full".to_owned(),
        });

        let lenses = self.lenses_for(timeline_type);

        // Apply time offset (if set) and make sure chunks are sorted by RowId before passing to the callback.
        let emit_final_chunk = |chunk: re_chunk::Chunk| {
            let mut chunk = apply_timestamp_offset(chunk, timestamp_offset_ns);
            chunk.sort_by_row_ids_if_needed();

            // If we hit this warning, we may be producing unnecessarily slow .rrd:s
            // See RR-4658 for details.
            chunk.warn_if_out_of_order();

            emit_chunk(chunk);
        };

        let on_chunk_with_transforms = |chunk: re_chunk::Chunk| {
            if let Some(ref lenses) = lenses {
                for result in lenses.apply(&chunk, &re_lenses::default_runtime()) {
                    match result {
                        Ok(chunk) => emit_final_chunk(chunk),
                        Err(partial) => {
                            for error in partial.errors() {
                                re_log::error_once!("Lens error: {error}");
                            }
                            if let Some(chunk) = partial.partial_chunk() {
                                emit_final_chunk(chunk);
                            }
                        }
                    }
                }
            } else {
                emit_final_chunk(chunk);
            }
        };

        DecoderRegistry::all_builtin(self.raw_fallback_enabled)
            .select(&self.selected_decoders)
            .plan(mcap, summary, &self.topic_filter)?
            .with_time_range(self.time_range)
            .run(mcap, summary, timeline_type, &on_chunk_with_transforms)?;

        if self
            .selected_decoders
            .contains(&DecoderIdentifier::from(URDF_DECODER_IDENTIFIER))
            && let Err(err) = super::robot_description::extract_urdf_from_robot_descriptions(
                mcap,
                summary,
                &self.topic_filter,
                self.recover,
                &on_chunk_with_transforms,
            )
        {
            re_log::warn_once!("Failed to extract URDF from robot_description topics: {err}");
        }

        Ok(())
    }
}

impl Importer for McapImporter {
    fn name(&self) -> crate::ImporterName {
        MCAP_IMPORTER_NAME.into()
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn import_from_path(
        &self,
        settings: &crate::ImporterSettings,
        path: std::path::PathBuf,
        tx: Sender<crate::ImportedData>,
    ) -> Result<(), ImporterError> {
        if !path.is_file() || !has_mcap_extension(&path) {
            return Err(ImporterError::Incompatible(path)); // simply not interested
        }

        re_tracing::profile_function!();

        // NOTE(1): `spawn` is fine, this whole function is native-only.
        // NOTE(2): this must spawned on a dedicated thread to avoid a deadlock!
        // `load` will spawn a bunch of importers on the common rayon thread pool and wait for
        // their response via channels: we cannot be waiting for these responses on the
        // common rayon thread pool.
        let loader = self.clone();
        let settings = settings.clone();
        std::thread::Builder::new()
            .name(format!("load_mcap({path:?})"))
            .spawn(move || {
                let file = match std::fs::File::open(&path) {
                    Ok(f) => f,
                    Err(err) => {
                        re_log::error!("Failed to open MCAP file: {err}");
                        return;
                    }
                };

                // SAFETY: file-backed mmap; we don't modify the file while mapped.
                #[expect(unsafe_code)]
                let mmap = match unsafe { memmap2::Mmap::map(&file) } {
                    Ok(m) => m,
                    Err(err) => {
                        re_log::error!("Failed to mmap MCAP file: {err}");
                        return;
                    }
                };

                if let Err(err) = loader.load_and_send(&mmap, &settings, &tx) {
                    re_log::error!("Failed to load MCAP file: {err}");
                }
            })
            .map_err(|err| ImporterError::Other(err.into()))?;

        Ok(())
    }

    fn import_from_file_contents(
        &self,
        settings: &crate::ImporterSettings,
        filepath: std::path::PathBuf,
        contents: std::borrow::Cow<'_, [u8]>,
        tx: Sender<crate::ImportedData>,
    ) -> Result<(), crate::ImporterError> {
        if !has_mcap_extension(&filepath) {
            return Err(ImporterError::Incompatible(filepath)); // simply not interested
        }

        re_tracing::profile_function!();

        let contents = contents.into_owned();
        let loader = self.clone();
        let settings = settings.clone();

        // NOTE: this must be spawned on a dedicated thread to avoid a deadlock!
        // `load` will spawn a bunch of importers on the common rayon thread pool and wait for
        // their response via channels: we cannot be waiting for these responses on the
        // common rayon thread pool.
        cfg_select! {
            target_arch = "wasm32" => {
                loader.load_and_send(&contents, &settings, &tx)?;
            }
            _ => {
                std::thread::Builder::new()
                    .name(format!("load_mcap({filepath:?})"))
                    .spawn(move || {
                        if let Err(err) = loader.load_and_send(&contents, &settings, &tx) {
                            re_log::error!("Failed to load MCAP file: {err}");
                        }
                    })
                    .map_err(|err| ImporterError::Other(err.into()))?;
            }
        }

        Ok(())
    }
}

impl McapImporter {
    /// Send `SetStoreInfo` then decode chunks via [`Self::emit_chunks`],
    /// forwarding each chunk to the [`Importer`] channel.
    pub fn load_and_send(
        &self,
        mcap: &[u8],
        settings: &ImporterSettings,
        tx: &Sender<ImportedData>,
    ) -> Result<(), ImporterError> {
        re_log::debug!(
            "Loading MCAP with timeline type {:?}",
            settings.timeline_type
        );
        let store_id = settings.recommended_store_id();

        if send_crossbeam(
            tx,
            ImportedData::LogMsg(
                MCAP_IMPORTER_NAME.to_owned(),
                re_log_types::LogMsg::SetStoreInfo(store_info(store_id.clone())),
            ),
        )
        .is_err()
        {
            re_log::debug_once!(
                "Failed to send `SetStoreInfo` because smart channel closed unexpectedly."
            );
            return Ok(());
        }

        self.emit_chunks(
            mcap,
            settings.timeline_type,
            settings.timestamp_offset_ns,
            &|chunk| {
                send_chunk_to_channel(tx, &store_id, chunk);
            },
        )
    }
}

fn apply_timestamp_offset(mut chunk: re_chunk::Chunk, offset_ns: Option<i64>) -> re_chunk::Chunk {
    if let Some(offset_ns) = offset_ns {
        let offset_timelines: Vec<_> = chunk
            .timelines()
            .values()
            .filter(|time_col| time_col.timeline().typ() == re_log_types::TimeType::TimestampNs)
            .map(|time_col| time_col.offset_by_nanos(offset_ns))
            .collect();
        for time_col in offset_timelines {
            chunk.add_timeline(time_col).ok();
        }
    }
    chunk
}

fn send_chunk_to_channel(tx: &Sender<ImportedData>, store_id: &StoreId, chunk: re_chunk::Chunk) {
    if send_crossbeam(
        tx,
        ImportedData::Chunk(MCAP_IMPORTER_NAME.to_owned(), store_id.clone(), chunk),
    )
    .is_err()
    {
        // If the other side decided to hang up this is not our problem.
        re_log::debug_once!(
            "Failed to send chunk because the smart channel has been closed unexpectedly."
        );
    }
}

fn store_info(store_id: StoreId) -> SetStoreInfo {
    SetStoreInfo {
        row_id: *RowId::new(),
        info: StoreInfo::new(
            store_id,
            re_log_types::StoreSource::Other(MCAP_IMPORTER_NAME.to_owned()),
        ),
    }
}

/// Checks if a path has the `.mcap` extension.
fn has_mcap_extension(filepath: &Path) -> bool {
    filepath
        .extension()
        .map(|ext| ext.eq_ignore_ascii_case("mcap"))
        .unwrap_or(false)
}