mf4-rs 4.2.0

mf4-rs is a Rust library for working with ASAM MDF 4 (Measurement Data Format) files.
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
// Functions for creating and linking MDF structure blocks
use super::*;
use crate::blocks::channel_block::ChannelBlock;
use crate::blocks::channel_group_block::ChannelGroupBlock;
use crate::blocks::conversion::{ConversionBlock, ConversionType};
use crate::blocks::data_group_block::DataGroupBlock;
use crate::blocks::header_block::HeaderBlock;
use crate::blocks::identification_block::IdentificationBlock;
use crate::blocks::text_block::TextBlock;
use crate::blocks::common::BlockHeader;

impl MdfWriter {
    /// Initializes a new MDF 4.1 file with identification and header blocks.
    ///
    /// The header's absolute start time (`HD.abs_time`) is set to the current
    /// system time in nanoseconds since the Unix epoch. Use
    /// [`MdfWriter::set_start_time`] afterwards to overwrite it with a
    /// specific timestamp.
    pub fn init_mdf_file(&mut self) -> Result<(u64, u64), MdfError> {
        let id_block = IdentificationBlock::default();
        let id_bytes = id_block.to_bytes()?;
        let id_pos = self.write_block_with_id(&id_bytes, "id_block")?;

        let mut hd_block = HeaderBlock::default();
        // `SystemTime::now()` is unsupported (and panics) on
        // `wasm32-unknown-unknown`; leave `abs_time` at 0 there and let the
        // caller set it explicitly via [`MdfWriter::set_start_time`].
        #[cfg(not(target_arch = "wasm32"))]
        {
            hd_block.abs_time = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_nanos() as u64)
                .unwrap_or(0);
        }
        let hd_bytes = hd_block.to_bytes()?;
        let hd_pos = self.write_block_with_id(&hd_bytes, "hd_block")?;
        Ok((id_pos, hd_pos))
    }

    /// Overwrite the start-time fields of the file's `##HD` block.
    ///
    /// `init_mdf_file` writes default time metadata, which loses the
    /// wall-clock anchor when authoring a file derived from another (for
    /// example, [`crate::cut::cut_mdf_by_time`] copying a window out of a
    /// source MF4). Call this after `init_mdf_file` to anchor the output
    /// to a specific timestamp.
    ///
    /// HD field offsets touched: 72 (`abs_time` u64), 80 (`tz_offset` i16),
    /// 82 (`daylight_save_time` i16), 84 (`time_flags` u8),
    /// 85 (`time_quality` u8).
    pub fn set_start_time_with(
        &mut self,
        abs_time_ns: u64,
        tz_offset_min: i16,
        dst_offset_min: i16,
        time_flags: u8,
        time_quality: u8,
    ) -> Result<(), MdfError> {
        self.update_block_u64("hd_block", 72, abs_time_ns)?;
        let tz = tz_offset_min.to_le_bytes();
        let dst = dst_offset_min.to_le_bytes();
        self.update_block_u8("hd_block", 80, tz[0])?;
        self.update_block_u8("hd_block", 81, tz[1])?;
        self.update_block_u8("hd_block", 82, dst[0])?;
        self.update_block_u8("hd_block", 83, dst[1])?;
        self.update_block_u8("hd_block", 84, time_flags)?;
        self.update_block_u8("hd_block", 85, time_quality)?;
        Ok(())
    }

    /// Adds a data group block to the file and links it from the header block.
    pub fn add_data_group(&mut self, prev_dg_id: Option<&str>) -> Result<String, MdfError> {
        let dg_count = self.block_positions.keys().filter(|k| k.starts_with("dg_")).count();
        let dg_id = format!("dg_{}", dg_count);
        let dg_block = DataGroupBlock::default();
        let dg_bytes = dg_block.to_bytes()?;
        let _pos = self.write_block_with_id(&dg_bytes, &dg_id)?;

        match prev_dg_id {
            None => {
                let hd_dg_link_offset = 24;
                self.update_block_link("hd_block", hd_dg_link_offset, &dg_id)?;
            }
            Some(prev) => {
                let prev_off = 24;
                self.update_block_link(prev, prev_off, &dg_id)?;
            }
        }
        Ok(dg_id)
    }

    /// Adds a channel group block to the specified data group and links it.
    pub fn add_channel_group_with_dg<F>(
        &mut self,
        dg_id: &str,
        prev_cg_id: Option<&str>,
        configure: F,
    ) -> Result<String, MdfError>
    where
        F: FnOnce(&mut ChannelGroupBlock),
    {
        let cg_count = self.block_positions.keys().filter(|k| k.starts_with("cg_")).count();
        let cg_id = format!("cg_{}", cg_count);

        let mut cg_block = ChannelGroupBlock::default();
        configure(&mut cg_block);

        // Remember the configured invalidation byte count so
        // `start_data_block` can include it in the record layout.
        self.cg_inval_bytes
            .insert(cg_id.clone(), cg_block.invalidation_bytes_nr);

        let cg_bytes = cg_block.to_bytes()?;
        let _pos = self.write_block_with_id(&cg_bytes, &cg_id)?;

        match prev_cg_id {
            None => {
                let dg_cg_link_offset = 32;
                self.update_block_link(dg_id, dg_cg_link_offset, &cg_id)?;
            }
            Some(prev) => {
                let prev_cg_off = 24;
                self.update_block_link(prev, prev_cg_off, &cg_id)?;
            }
        }
        Ok(cg_id)
    }

    /// Adds a channel group and automatically creates a new data group for it.
    pub fn add_channel_group_with<F>(
        &mut self,
        prev_cg_id: Option<&str>,
        configure: F,
    ) -> Result<String, MdfError>
    where
        F: FnOnce(&mut ChannelGroupBlock),
    {
        let dg_id = match self.last_dg.clone() {
            Some(last) => self.add_data_group(Some(&last))?,
            None => self.add_data_group(None)?,
        };
        self.last_dg = Some(dg_id.clone());
        let cg_id = self.add_channel_group_with_dg(&dg_id, prev_cg_id, configure)?;
        self.cg_to_dg.insert(cg_id.clone(), dg_id);
        self.cg_offsets.insert(cg_id.clone(), 0);
        self.cg_channels.insert(cg_id.clone(), Vec::new());
        self.cg_channel_ids.insert(cg_id.clone(), Vec::new());
        Ok(cg_id)
    }

    /// Creates and writes a simple value-to-text conversion block.
    pub fn write_value_to_text_conversion(
        &mut self,
        mapping: &[(i64, &str)],
        default_text: &str,
        channel_id: Option<&str>,
    ) -> Result<(String, u64), MdfError> {
        self.ensure_no_open_data_block("write_value_to_text_conversion")?;
        let cc_count = self.block_positions.keys().filter(|k| k.starts_with("cc_")).count();
        let cc_id = format!("cc_{}", cc_count);

        let mut refs = Vec::new();
        for (idx, (_, txt)) in mapping.iter().enumerate() {
            let tx_id = format!("tx_{}_{}", cc_id, idx);
            let tx_block = TextBlock::new(txt);
            let tx_bytes = tx_block.to_bytes()?;
            let pos = self.write_block_with_id(&tx_bytes, &tx_id)?;
            refs.push(pos);
        }
        let tx_default_id = format!("tx_{}_default", cc_id);
        let tx_default = TextBlock::new(default_text);
        let tx_bytes = tx_default.to_bytes()?;
        let default_pos = self.write_block_with_id(&tx_bytes, &tx_default_id)?;
        refs.push(default_pos);

        let vals: Vec<f64> = mapping.iter().map(|(v, _)| *v as f64).collect();

        let block = ConversionBlock {
            header: BlockHeader { id: "##CC".into(), reserved0: 0, block_len: 0, links_nr: 0 },
            cc_tx_name: None,
            cc_md_unit: None,
            cc_md_comment: None,
            cc_cc_inverse: None,
            cc_ref: refs,
            cc_type: ConversionType::ValueToText,
            cc_precision: 0,
            cc_flags: 0b10,
            cc_ref_count: (mapping.len() + 1) as u16,
            cc_val_count: mapping.len() as u16,
            cc_phy_range_min: Some(0.0),
            cc_phy_range_max: Some(0.0),
            cc_val: vals,
            formula: None,
            resolved_texts: None,
            resolved_conversions: None,
            default_conversion: None,
        };
        let cc_bytes = block.to_bytes()?;
        let pos = self.write_block_with_id(&cc_bytes, &cc_id)?;

        if let Some(cn) = channel_id {
            let conv_offset = 56u64;
            self.update_block_link(cn, conv_offset, &cc_id)?;
        }
        Ok((cc_id, pos))
    }

    /// Creates and writes a linear conversion block (`phys = offset + factor *
    /// raw`), linking it to `channel_id` when given.
    pub fn write_linear_conversion(
        &mut self,
        offset: f64,
        factor: f64,
        channel_id: Option<&str>,
    ) -> Result<(String, u64), MdfError> {
        self.ensure_no_open_data_block("write_linear_conversion")?;
        let cc_count = self.block_positions.keys().filter(|k| k.starts_with("cc_")).count();
        let cc_id = format!("cc_{}", cc_count);
        let block = ConversionBlock {
            header: BlockHeader { id: "##CC".into(), reserved0: 0, block_len: 0, links_nr: 0 },
            cc_tx_name: None,
            cc_md_unit: None,
            cc_md_comment: None,
            cc_cc_inverse: None,
            cc_ref: Vec::new(),
            cc_type: ConversionType::Linear,
            cc_precision: 0,
            cc_flags: 0,
            cc_ref_count: 0,
            cc_val_count: 2,
            cc_phy_range_min: None,
            cc_phy_range_max: None,
            cc_val: vec![offset, factor],
            formula: None,
            resolved_texts: None,
            resolved_conversions: None,
            default_conversion: None,
        };
        let cc_bytes = block.to_bytes()?;
        let pos = self.write_block_with_id(&cc_bytes, &cc_id)?;
        if let Some(cn) = channel_id {
            self.update_block_link(cn, 56, &cc_id)?;
        }
        Ok((cc_id, pos))
    }

    /// Metadata blocks are written at the current file position, which lies
    /// inside an open `##DT` block while records are being written; refuse
    /// instead of corrupting the data.
    fn ensure_no_open_data_block(&self, what: &str) -> Result<(), MdfError> {
        if self.open_dts.is_empty() {
            return Ok(());
        }
        Err(MdfError::BlockSerializationError(format!(
            "{what} must be called before start_data_block (a data block is open)"
        )))
    }

    /// Write a `##TX` block holding `name` and link it as the channel group's
    /// `acq_name_addr`.
    ///
    /// The MDF 4 specification places the acquisition name link at offset 40
    /// (the third link slot) inside the `##CG` block.
    pub fn set_channel_group_name(
        &mut self,
        cg_id: &str,
        name: &str,
    ) -> Result<(), MdfError> {
        let tx_id = format!("tx_cg_name_{cg_id}");
        let tx_block = TextBlock::new(name);
        let tx_bytes = tx_block.to_bytes()?;
        self.write_block_with_id(&tx_bytes, &tx_id)?;
        let acq_name_link_offset = 40;
        self.update_block_link(cg_id, acq_name_link_offset, &tx_id)
    }

    /// Write a `##TX` block holding `comment` and link it as the channel
    /// group's `comment_addr`.
    ///
    /// The comment link is at offset 64 inside the `##CG` block.
    pub fn set_channel_group_comment(
        &mut self,
        cg_id: &str,
        comment: &str,
    ) -> Result<(), MdfError> {
        let tx_id = format!("tx_cg_comment_{cg_id}");
        let tx_block = TextBlock::new(comment);
        let tx_bytes = tx_block.to_bytes()?;
        self.write_block_with_id(&tx_bytes, &tx_id)?;
        let comment_link_offset = 64;
        self.update_block_link(cg_id, comment_link_offset, &tx_id)
    }

    /// Adds a channel block to the specified channel group and links it.
    pub fn add_channel_with<F>(
        &mut self,
        cg_id: &str,
        prev_cn_id: Option<&str>,
        configure: F,
    ) -> Result<String, MdfError>
    where
        F: FnOnce(&mut ChannelBlock),
    {
        self.add_channel_impl(cg_id, prev_cn_id, configure, true)
    }

    /// Like [`add_channel_with`](Self::add_channel_with), but never auto-assigns `byte_offset`: the value
    /// set by `configure` — including a legitimate `0` on a channel that is
    /// not first in the record — is written verbatim. Use when cloning
    /// channels whose record layout is copied from another file and must be
    /// preserved exactly (cut/merge).
    pub fn add_channel_preserving_offsets<F>(
        &mut self,
        cg_id: &str,
        prev_cn_id: Option<&str>,
        configure: F,
    ) -> Result<String, MdfError>
    where
        F: FnOnce(&mut ChannelBlock),
    {
        self.add_channel_impl(cg_id, prev_cn_id, configure, false)
    }

    fn add_channel_impl<F>(
        &mut self,
        cg_id: &str,
        prev_cn_id: Option<&str>,
        configure: F,
        auto_offset: bool,
    ) -> Result<String, MdfError>
    where
        F: FnOnce(&mut ChannelBlock),
    {
        let cn_count = self.block_positions.keys().filter(|k| k.starts_with("cn_")).count();
        let cn_id = format!("cn_{}", cn_count);

        let mut ch = ChannelBlock::default();
        configure(&mut ch);
        if ch.bit_count == 0 { ch.bit_count = ch.data_type.default_bits(); }
        // A VLSD channel's record slot is always a u64 offset into the ##SD
        // stream, regardless of the payload data type.
        if ch.channel_type == 1 { ch.bit_count = 64; }
        if let Some(off) = self.cg_offsets.get_mut(cg_id) {
            if auto_offset && ch.byte_offset == 0 { ch.byte_offset = *off as u32; }
            let used = (ch.bit_offset as usize + ch.bit_count as usize).div_ceil(8);
            // Keep the running offset monotonic so a later auto-placed
            // channel can never overlap an explicitly placed one.
            *off = (*off).max(ch.byte_offset as usize + used);
        }

        // Never serialize a placeholder `data` link for VLSD channels: the
        // in-memory sentinel (e.g. `ch.data = 1`) is not a valid block
        // address, and if the writer is finalized before `finish_data_block`
        // patches the link, readers would follow a bogus pointer.
        // `finish_data_block` / `finish_signal_data_block` write the real
        // ##SD address later.
        let cn_bytes = if ch.channel_type == 1 && ch.data != 0 {
            let mut on_disk = ch.clone();
            on_disk.data = 0;
            on_disk.to_bytes()?
        } else {
            ch.to_bytes()?
        };
        let cn_pos = self.write_block_with_id(&cn_bytes, &cn_id)?;
        if let Some(channel_name) = &ch.name {
            let tx_id = format!("tx_name_{}", cn_id);
            let tx_block = TextBlock::new(channel_name);
            let tx_bytes = tx_block.to_bytes()?;
            let tx_pos = self.write_block_with_id(&tx_bytes, &tx_id)?;
            let name_link_offset = 40;
            self.update_link(cn_pos + name_link_offset, tx_pos)?;
        }

        let entry = self.cg_channels.entry(cg_id.to_string()).or_default();
        entry.push(ch.clone());
        let idx = entry.len() - 1;
        self.cg_channel_ids.entry(cg_id.to_string()).or_default().push(cn_id.clone());
        self.channel_map.insert(cn_id.clone(), (cg_id.to_string(), idx));

        match prev_cn_id {
            None => {
                let cg_cn_link_offset = 32;
                self.update_block_link(cg_id, cg_cn_link_offset, &cn_id)?;
            }
            Some(prev_cn) => {
                let prev_cn_next_link_offset = 24;
                self.update_block_link(prev_cn, prev_cn_next_link_offset, &cn_id)?;
            }
        }
        Ok(cn_id)
    }

    /// Mark an existing channel as the time (master) channel.
    pub fn set_time_channel(&mut self, cn_id: &str) -> Result<(), MdfError> {
        const CHANNEL_TYPE_OFFSET: u64 = 88;
        const SYNC_TYPE_OFFSET: u64 = 89;
        self.update_block_u8(cn_id, CHANNEL_TYPE_OFFSET, 2)?;
        self.update_block_u8(cn_id, SYNC_TYPE_OFFSET, 1)?;

        if let Some((cg, idx)) = self.channel_map.get(cn_id).cloned()
            && let Some(chs) = self.cg_channels.get_mut(&cg)
                && let Some(ch) = chs.get_mut(idx) {
                    ch.channel_type = 2;
                    ch.sync_type = 1;
                }
        Ok(())
    }
}