#foxglove #reading #channel #schema #record #file #mcap

mcap-rs

A library for reading and writing Foxglove MCAP files

3 releases

0.3.4 Sep 30, 2022
0.3.3 Sep 21, 2022
0.3.2 Sep 21, 2022
0.3.1 Sep 21, 2022

#184 in Robotics

Apache-2.0

92KB
2K SLoC

mcap-rs

...has been upstreamed into the Foxglove MCAP repo! Use the mcap crate for the latest Rust MCAP goodness.


lib.rs:

A library for manipulating Foxglove MCAP files, both reading:

use std::fs;

use anyhow::{Context, Result};
use camino::Utf8Path;
use memmap::Mmap;

fn map_mcap<P: AsRef<Utf8Path>>(p: P) -> Result<Mmap> {
    let fd = fs::File::open(p.as_ref()).context("Couldn't open MCAP file")?;
    unsafe { Mmap::map(&fd) }.context("Couldn't map MCAP file")
}

fn read_it() -> Result<()> {
    let mapped = map_mcap("in.mcap")?;

    for message in mcap_rs::MessageStream::new(&mapped)? {
        println!("{:?}", message?);
        // Or whatever else you'd like to do...
    }
    Ok(())
}

or writing:

use std::{collections::BTreeMap, fs, io::BufWriter};

use anyhow::Result;

use mcap_rs::{Channel, records::MessageHeader, Writer};

fn write_it() -> Result<()> {
    // To set the profile or compression options, see mcap_rs::WriteOptions.
    let mut out = Writer::new(
        BufWriter::new(fs::File::create("out.mcap")?)
    )?;

    // Channels and schemas are automatically assigned ID as they're serialized,
    // and automatically deduplicated with `Arc` when deserialized.
    let my_channel = Channel {
        topic: String::from("cool stuff"),
        schema: None,
        message_encoding: String::from("application/octet-stream"),
        metadata: BTreeMap::default()
    };

    let channel_id = out.add_channel(&my_channel)?;

    out.write_to_known_channel(
        &MessageHeader {
            channel_id,
            sequence: 25,
            log_time: 6,
            publish_time: 24
        },
        &[1, 2, 3]
    )?;
    out.write_to_known_channel(
        &MessageHeader {
            channel_id,
            sequence: 32,
            log_time: 23,
            publish_time: 25
        },
        &[3, 4, 5]
    )?;

    out.finish()?;

    Ok(())
}

Dependencies

~6MB
~112K SLoC