Skip to main content

mf4_rs/
column.rs

1//! Convert any MDF 4 file into a **column-oriented** MDF 4.20 file that is
2//! optimised for reading a single signal from cloud storage.
3//!
4//! # Output layout
5//!
6//! ```text
7//! ┌──────────────────────────────────────────────────────────────┐
8//! │ ##ID  ##HD                                                   │  metadata:
9//! │ ##FH / ##MD history, then per output group:                  │  one contiguous
10//! │   ##DG ##CG ##CN (+ ##TX/##MD/##CC/##SI they reference)      │  region at the
11//! │   ##DL listing the signal's data blocks                      │  front
12//! ├──────────────────────────────────────────────────────────────┤
13//! │ time 0:     ##DV ##DV ##DV …   (contiguous)                  │
14//! │ signal A:   ##DV ##DV …        (contiguous)                  │  data: every
15//! │ signal B:   ##DT …  ##SD       (VLSD stream right after)     │  signal's blocks
16//! │ time 1 …                                                     │  back to back
17//! ├──────────────────────────────────────────────────────────────┤
18//! │ ##AT attachments (if any)                                    │
19//! └──────────────────────────────────────────────────────────────┘
20//! ```
21//!
22//! * Every signal lives in its **own data group / channel group** holding just
23//!   that one channel ("column storage"). Its samples are written as a run of
24//!   data blocks of about [`ColumnOptions::block_size`] bytes, placed directly
25//!   after each other and listed by an equal-length `##DL` block, so one HTTP
26//!   range request fetches the whole signal.
27//! * Timestamps are **shared** using the MDF 4.2 *remote master* feature: the
28//!   master (time) channel of each source group is written once into its own
29//!   group, and every signal group points at it via `cg_cg_master` (channel
30//!   group flag bit 3). With [`ColumnOptions::share_identical_time`] source
31//!   groups whose time axes are byte-identical share one time group.
32//! * Every non-data block sits in one region at the front of the file, so a
33//!   reader learns the whole structure from a single prefix fetch. Since the
34//!   data-block sizes are all derivable from the metadata (equal-length `##DL`
35//!   lists plus the exact cycle counts), an index build never has to touch the
36//!   data region.
37//!
38//! # Streaming
39//!
40//! The output layout is fully computed from the source metadata before any
41//! sample is copied. The source data is then streamed **once** (in
42//! [`ColumnOptions::read_chunk_size`] pieces) and each channel's bytes are
43//! appended to a small per-channel buffer that is flushed straight to its
44//! pre-computed position in the output. Memory stays bounded by
45//! [`ColumnOptions::memory_budget`] regardless of file size; nothing is
46//! decoded, so the conversion is lossless (raw bytes, conversions, units,
47//! comments and sources are carried over).
48//!
49//! # Supported input
50//!
51//! Sorted and unsorted data groups, `##DT`/`##DV`/`##DL`/`##HL` data chains,
52//! invalidation bits, VLSD (`##SD`) channels, sources, conversions (any
53//! chain), file history and attachments. Not supported: compressed `##DZ`
54//! blocks (rejected with an error). Channels that cannot be represented as a
55//! single column — array (`##CA`) compositions and VLSD channels stored in a
56//! VLSD channel group — are skipped and listed in
57//! [`ColumnReport::skipped_channels`], as are structure (`##CN` composition)
58//! and synchronization channels.
59//!
60//! Not carried over: events (`##EV`), the channel hierarchy (`##CH`),
61//! channel attachment references and bus-event group flags. A group whose
62//! remote master has a different record count is written without a time
63//! axis (noted in [`ColumnReport::skipped_channels`]).
64
65use std::collections::{HashMap, HashSet};
66use std::hash::Hasher;
67
68use crate::blocks::common::{read_string_block_via_reader, BlockHeader};
69use crate::blocks::data_list_block::DataListBlock;
70use crate::blocks::identification_block::IdentificationBlock;
71use crate::error::MdfError;
72use crate::index::ByteRangeReader;
73
74/// Default payload size of one data block (4 MiB).
75pub const DEFAULT_BLOCK_SIZE: u64 = 4 * 1024 * 1024;
76/// Default cap on the memory used by the per-channel write buffers (64 MiB).
77pub const DEFAULT_MEMORY_BUDGET: u64 = 64 * 1024 * 1024;
78/// Default size of each sequential read from the source (4 MiB).
79pub const DEFAULT_READ_CHUNK: u64 = 4 * 1024 * 1024;
80
81/// Channel-group flag: the group stores VLSD data for another group's channel.
82const CG_FLAG_VLSD: u16 = 1;
83/// Channel-group flags: bus event / plain bus event group (a property of the
84/// source group's channel set, which a single-column group no longer has).
85const CG_FLAG_BUS_EVENTS: u16 = (1 << 1) | (1 << 2);
86pub use crate::blocks::channel_group_block::CG_FLAG_REMOTE_MASTER;
87const CN_FLAG_ALL_INVALID: u32 = 1;
88const CN_FLAG_INVAL_BIT_VALID: u32 = 1 << 1;
89const CN_FLAG_DEFAULT_X: u32 = 1 << 12;
90/// Upper bound for a single metadata block (sanity check against corrupt links).
91const MAX_METADATA_BLOCK: u64 = 256 * 1024 * 1024;
92/// Smallest per-channel write buffer, whatever the memory budget.
93const MIN_STREAM_BUFFER: usize = 4096;
94/// Header of every MDF block.
95const HDR: u64 = 24;
96
97/// Tuning for [`to_column_oriented`] / [`to_column_oriented_with`].
98#[derive(Debug, Clone)]
99pub struct ColumnOptions {
100    /// Target payload size of one data block, in bytes. Each block holds a
101    /// whole number of records; a signal larger than this is split into
102    /// several equally sized blocks written back to back and listed by a
103    /// `##DL` block. Default [`DEFAULT_BLOCK_SIZE`] (4 MiB).
104    pub block_size: u64,
105    /// Upper bound for the per-channel write buffers in bytes (each channel
106    /// gets `memory_budget / channels_in_group`, at least 4 KiB and at most
107    /// one block). Default [`DEFAULT_MEMORY_BUDGET`] (64 MiB).
108    ///
109    /// Because of the 4 KiB floor, a data group with more than
110    /// `memory_budget / 4096` channels uses more than `memory_budget`
111    /// (4 KiB per channel).
112    pub memory_budget: u64,
113    /// Size of each sequential read from the source. Default 4 MiB.
114    pub read_chunk_size: u64,
115    /// Merge time channels of different source groups when they hold exactly
116    /// the same raw timestamps (same layout, conversion and bytes), so all
117    /// their signals reference a single time group. Costs one extra read of
118    /// the candidate groups' data. Default `true`.
119    pub share_identical_time: bool,
120}
121
122impl Default for ColumnOptions {
123    fn default() -> Self {
124        Self {
125            block_size: DEFAULT_BLOCK_SIZE,
126            memory_budget: DEFAULT_MEMORY_BUDGET,
127            read_chunk_size: DEFAULT_READ_CHUNK,
128            share_identical_time: true,
129        }
130    }
131}
132
133/// Summary of a column-oriented conversion.
134#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
135pub struct ColumnReport {
136    /// Channel groups found in the source (excluding VLSD storage groups).
137    pub source_groups: usize,
138    /// Time (master) groups written.
139    pub time_groups: usize,
140    /// Signal groups written (one per signal).
141    pub signal_groups: usize,
142    /// Source groups whose time axis was identical to an earlier group's and
143    /// therefore shares that group's time channel.
144    pub shared_time_groups: usize,
145    /// Data blocks written (`##DV`/`##DT`/`##SD`).
146    pub data_blocks: usize,
147    /// Byte offset where the data region starts: everything before it is
148    /// metadata, so a reader fetching this prefix sees the whole structure.
149    pub metadata_size: u64,
150    /// Total size of the output file in bytes.
151    pub file_size: u64,
152    /// Channels that could not be represented as a column, as
153    /// `"group/channel: reason"` (or `"group: reason"` for a group whose
154    /// remote master had to be dropped).
155    pub skipped_channels: Vec<String>,
156}
157
158/// Destination of a column-oriented conversion.
159///
160/// The output layout is computed up front, so data is written at known
161/// absolute offsets rather than strictly sequentially.
162pub trait ColumnSink {
163    /// Write `bytes` at absolute file position `offset`. Positions never
164    /// written before must read back as zero (true for a fresh file or a
165    /// zero-filled buffer).
166    fn write_at(&mut self, offset: u64, bytes: &[u8]) -> Result<(), MdfError>;
167
168    /// Called once, before any write, with the final output size.
169    fn set_size(&mut self, _size: u64) -> Result<(), MdfError> {
170        Ok(())
171    }
172}
173
174impl ColumnSink for Vec<u8> {
175    fn write_at(&mut self, offset: u64, bytes: &[u8]) -> Result<(), MdfError> {
176        let start = usize::try_from(offset)
177            .map_err(|_| err("output offset exceeds the address space"))?;
178        let end = start + bytes.len();
179        if self.len() < end {
180            self.resize(end, 0);
181        }
182        self[start..end].copy_from_slice(bytes);
183        Ok(())
184    }
185
186    fn set_size(&mut self, size: u64) -> Result<(), MdfError> {
187        let size = usize::try_from(size).map_err(|_| err("output exceeds the address space"))?;
188        self.clear();
189        self.resize(size, 0);
190        Ok(())
191    }
192}
193
194/// [`ColumnSink`] over anything that is `Write + Seek` (e.g. a `File`).
195///
196/// Seeks only when the next write is not at the current position.
197pub struct SeekSink<W: std::io::Write + std::io::Seek> {
198    inner: W,
199    pos: Option<u64>,
200}
201
202impl<W: std::io::Write + std::io::Seek> SeekSink<W> {
203    pub fn new(inner: W) -> Self {
204        Self { inner, pos: None }
205    }
206
207    /// Flush and return the wrapped writer.
208    pub fn into_inner(mut self) -> Result<W, MdfError> {
209        self.inner.flush()?;
210        Ok(self.inner)
211    }
212}
213
214impl<W: std::io::Write + std::io::Seek> ColumnSink for SeekSink<W> {
215    fn write_at(&mut self, offset: u64, bytes: &[u8]) -> Result<(), MdfError> {
216        if self.pos != Some(offset) {
217            self.inner.seek(std::io::SeekFrom::Start(offset))?;
218        }
219        self.inner.write_all(bytes)?;
220        self.pos = Some(offset + bytes.len() as u64);
221        Ok(())
222    }
223
224    /// Extends the output to `size` up front (by writing its last byte), so
225    /// trailing alignment padding that no block covers is still present.
226    fn set_size(&mut self, size: u64) -> Result<(), MdfError> {
227        if size > 0 {
228            self.write_at(size - 1, &[0])?;
229        }
230        Ok(())
231    }
232}
233
234/// Convert the MDF file at `input` into a column-oriented MDF 4.20 file at
235/// `output` (see the [module docs](self) for the layout).
236///
237/// The source is streamed once with positional reads; memory use is bounded by
238/// [`ColumnOptions::memory_budget`]. Not available on `wasm32`; use
239/// [`to_column_oriented_with`] there.
240#[cfg(not(target_arch = "wasm32"))]
241pub fn to_column_oriented(
242    input: impl AsRef<std::path::Path>,
243    output: impl AsRef<std::path::Path>,
244    options: &ColumnOptions,
245) -> Result<ColumnReport, MdfError> {
246    let input = input.as_ref();
247    let output = output.as_ref();
248    if same_file(input, output) {
249        return Err(err("input and output must be different files"));
250    }
251    let path = input
252        .to_str()
253        .ok_or_else(|| err("input path is not valid UTF-8"))?;
254    // Plain positional reads rather than a memory map: the data is copied out
255    // in chunks either way, and this keeps the resident set small.
256    let mut reader = crate::index::FileRangeReader::new(path)?;
257    let file = std::fs::File::create(output)?;
258    let mut sink = SeekSink::new(std::io::BufWriter::with_capacity(1 << 20, file));
259    let result = to_column_oriented_with(&mut reader, &mut sink, options)
260        .and_then(|report| sink.into_inner().map(|_| report));
261    if result.is_err() {
262        // Best effort: do not leave a partial output file behind.
263        let _ = std::fs::remove_file(output);
264    }
265    result
266}
267
268#[cfg(not(target_arch = "wasm32"))]
269fn same_file(a: &std::path::Path, b: &std::path::Path) -> bool {
270    match (std::fs::canonicalize(a), std::fs::canonicalize(b)) {
271        (Ok(a), Ok(b)) => a == b,
272        _ => false,
273    }
274}
275
276/// Convert an in-memory MDF file into an in-memory column-oriented file.
277pub fn to_column_oriented_bytes(
278    input: &[u8],
279    options: &ColumnOptions,
280) -> Result<(Vec<u8>, ColumnReport), MdfError> {
281    let mut reader = SliceReader { data: input };
282    let mut out = Vec::new();
283    let report = to_column_oriented_with(&mut reader, &mut out, options)?;
284    Ok((out, report))
285}
286
287/// Core conversion over any [`ByteRangeReader`] source and [`ColumnSink`]
288/// destination.
289///
290/// Metadata is read first; then the sample data of each data group is
291/// streamed sequentially (plus one extra pass over the data groups whose
292/// time axes are candidates for sharing, and a counting pass over unsorted
293/// data groups).
294pub fn to_column_oriented_with<R, S>(
295    reader: &mut R,
296    sink: &mut S,
297    options: &ColumnOptions,
298) -> Result<ColumnReport, MdfError>
299where
300    R: ByteRangeReader<Error = MdfError>,
301    S: ColumnSink + ?Sized,
302{
303    if options.block_size == 0 {
304        return Err(err("block_size must be greater than zero"));
305    }
306    let chunk = options.read_chunk_size.clamp(64 * 1024, 1 << 30) as usize;
307
308    let mut src = walk_source(reader)?;
309    for dg in 0..src.dgs.len() {
310        count_records(reader, &mut src, dg, chunk)?;
311    }
312    let mut report = ColumnReport {
313        source_groups: src.groups.iter().filter(|g| !g.is_vlsd_storage()).count(),
314        ..Default::default()
315    };
316    let plan = plan_output(reader, &src, options, chunk, &mut report)?;
317    let layout = build_layout(reader, &src, plan, options)?;
318
319    sink.set_size(layout.file_size)?;
320    for (addr, bytes) in &layout.fixed_writes {
321        sink.write_at(*addr, bytes)?;
322    }
323    stream_data(reader, &src, &layout, options, chunk, sink)?;
324    for c in &layout.copies {
325        copy_range(reader, sink, c.from, c.to, c.len, chunk)?;
326    }
327
328    report.data_blocks = layout.groups.iter().map(|g| g.n_blocks as usize + usize::from(g.sd_len.is_some())).sum();
329    report.metadata_size = layout.metadata_end;
330    report.file_size = layout.file_size;
331    Ok(report)
332}
333
334// ---------------------------------------------------------------------------
335// Small helpers
336// ---------------------------------------------------------------------------
337
338fn err(msg: impl Into<String>) -> MdfError {
339    MdfError::BlockSerializationError(msg.into())
340}
341
342fn align8(v: u64) -> u64 {
343    (v + 7) & !7
344}
345
346fn u16_at(b: &[u8], o: usize) -> u16 {
347    u16::from_le_bytes([b[o], b[o + 1]])
348}
349
350fn u32_at(b: &[u8], o: usize) -> u32 {
351    u32::from_le_bytes(b[o..o + 4].try_into().unwrap())
352}
353
354fn u64_at(b: &[u8], o: usize) -> u64 {
355    u64::from_le_bytes(b[o..o + 8].try_into().unwrap())
356}
357
358/// Borrowing in-memory reader.
359struct SliceReader<'a> {
360    data: &'a [u8],
361}
362
363impl ByteRangeReader for SliceReader<'_> {
364    type Error = MdfError;
365
366    fn read_range(&mut self, offset: u64, length: u64) -> Result<Vec<u8>, MdfError> {
367        let end = offset
368            .checked_add(length)
369            .filter(|&e| e <= self.data.len() as u64)
370            .ok_or(MdfError::TooShortBuffer {
371                actual: self.data.len(),
372                expected: offset.saturating_add(length).min(usize::MAX as u64) as usize,
373                file: file!(),
374                line: line!(),
375            })?;
376        Ok(self.data[offset as usize..end as usize].to_vec())
377    }
378}
379
380/// A raw block split into its parts.
381struct RawBlock {
382    id: [u8; 4],
383    links: Vec<u64>,
384    data: Vec<u8>,
385}
386
387fn read_header<R>(reader: &mut R, addr: u64) -> Result<BlockHeader, MdfError>
388where
389    R: ByteRangeReader<Error = MdfError>,
390{
391    BlockHeader::from_bytes(&reader.read_range(addr, HDR)?)
392}
393
394fn read_block<R>(reader: &mut R, addr: u64) -> Result<RawBlock, MdfError>
395where
396    R: ByteRangeReader<Error = MdfError>,
397{
398    let header = read_header(reader, addr)?;
399    let links_len = header
400        .links_nr
401        .checked_mul(8)
402        .and_then(|l| l.checked_add(HDR))
403        .filter(|&l| l <= header.block_len)
404        .ok_or_else(|| err(format!("block at {addr:#x} has an inconsistent link count")))?;
405    if header.block_len > MAX_METADATA_BLOCK {
406        return Err(err(format!(
407            "block {} at {addr:#x} is implausibly large ({} bytes)",
408            header.id, header.block_len
409        )));
410    }
411    let bytes = reader.read_range(addr, header.block_len)?;
412    let mut id = [0u8; 4];
413    id.copy_from_slice(&bytes[0..4]);
414    let links = (0..header.links_nr as usize).map(|i| u64_at(&bytes, 24 + i * 8)).collect();
415    Ok(RawBlock { id, links, data: bytes[links_len as usize..].to_vec() })
416}
417
418fn assemble(id: &[u8; 4], links: &[u64], data: &[u8]) -> Vec<u8> {
419    let len = HDR as usize + links.len() * 8 + data.len();
420    let mut out = Vec::with_capacity(len);
421    out.extend_from_slice(id);
422    out.extend_from_slice(&0u32.to_le_bytes());
423    out.extend_from_slice(&(len as u64).to_le_bytes());
424    out.extend_from_slice(&(links.len() as u64).to_le_bytes());
425    for l in links {
426        out.extend_from_slice(&l.to_le_bytes());
427    }
428    out.extend_from_slice(data);
429    out
430}
431
432/// A `##TX`/`##MD` block holding `text` (NUL-terminated, 8-byte padded).
433fn text_block(id: &[u8; 4], text: &str) -> Vec<u8> {
434    let mut data = text.as_bytes().to_vec();
435    data.push(0);
436    data.resize(align8(HDR + data.len() as u64) as usize - HDR as usize, 0);
437    assemble(id, &[], &data)
438}
439
440fn block_header_bytes(id: &[u8; 4], block_len: u64, links_nr: u64) -> [u8; 24] {
441    let mut h = [0u8; 24];
442    h[0..4].copy_from_slice(id);
443    h[8..16].copy_from_slice(&block_len.to_le_bytes());
444    h[16..24].copy_from_slice(&links_nr.to_le_bytes());
445    h
446}
447
448// ---------------------------------------------------------------------------
449// Source model
450// ---------------------------------------------------------------------------
451
452#[derive(Clone, Copy, PartialEq, Eq)]
453enum BlockKind {
454    /// `##DT`: records with record id and invalidation bytes.
455    Dt,
456    /// `##DV`: records with data bytes only.
457    Dv,
458}
459
460#[derive(Clone)]
461struct SrcBlock {
462    data_offset: u64,
463    len: u64,
464    kind: BlockKind,
465}
466
467struct SrcChannel {
468    name: Option<String>,
469    links: Vec<u64>,
470    /// Data section (after the links): 72 bytes for MDF 4.
471    data: Vec<u8>,
472    channel_type: u8,
473    bit_offset: u8,
474    byte_offset: u32,
475    bit_count: u32,
476    flags: u32,
477    inval_pos: u32,
478}
479
480impl SrcChannel {
481    fn is_master(&self) -> bool {
482        self.channel_type == 2 || self.channel_type == 3
483    }
484
485    fn is_virtual(&self) -> bool {
486        self.channel_type == 3 || self.channel_type == 6
487    }
488
489    /// Bytes this channel occupies in a record (in `u64`, so corrupt bit
490    /// counts cannot overflow).
491    fn byte_len(&self) -> u64 {
492        if self.is_virtual() {
493            0
494        } else {
495            (self.bit_offset as u64 + self.bit_count as u64).div_ceil(8)
496        }
497    }
498
499    /// Whether the channel's bytes lie inside a record of `samples` data bytes.
500    fn fits(&self, samples: u32) -> bool {
501        self.bit_offset <= 7 && self.byte_offset as u64 + self.byte_len() <= samples as u64
502    }
503}
504
505struct SrcGroup {
506    dg: usize,
507    cg_addr: u64,
508    links: Vec<u64>,
509    record_id: u64,
510    flags: u16,
511    path_separator: u16,
512    samples: u32,
513    inval_bytes: u32,
514    name: Option<String>,
515    channels: Vec<SrcChannel>,
516    /// Records actually present in the data (filled by `count_records`).
517    records: u64,
518}
519
520impl SrcGroup {
521    fn is_vlsd_storage(&self) -> bool {
522        self.flags & CG_FLAG_VLSD != 0
523    }
524
525    fn remote_master_link(&self) -> u64 {
526        if self.flags & CG_FLAG_REMOTE_MASTER != 0 {
527            self.links.get(6).copied().unwrap_or(0)
528        } else {
529            0
530        }
531    }
532
533    fn label(&self) -> String {
534        self.name.clone().unwrap_or_else(|| format!("group@{:#x}", self.cg_addr))
535    }
536}
537
538struct SrcDg {
539    rec_id_len: u8,
540    comment: u64,
541    blocks: Vec<SrcBlock>,
542    groups: Vec<usize>,
543}
544
545struct Source {
546    hd: RawBlock,
547    dgs: Vec<SrcDg>,
548    groups: Vec<SrcGroup>,
549}
550
551fn walk_source<R>(reader: &mut R) -> Result<Source, MdfError>
552where
553    R: ByteRangeReader<Error = MdfError>,
554{
555    IdentificationBlock::from_bytes(&reader.read_range(0, 64)?)?;
556    let hd = read_block(reader, 64)?;
557    if &hd.id != b"##HD" || hd.links.len() < 6 {
558        return Err(MdfError::BlockIDError {
559            actual: String::from_utf8_lossy(&hd.id).into_owned(),
560            expected: "##HD".into(),
561        });
562    }
563
564    let mut dgs = Vec::new();
565    let mut groups = Vec::new();
566    let mut visited = HashSet::new();
567    let mut dg_addr = hd.links[0];
568    while dg_addr != 0 {
569        if !visited.insert(dg_addr) {
570            return Err(MdfError::BlockLinkError(format!("cycle in ##DG chain at {dg_addr:#x}")));
571        }
572        let dg = read_block(reader, dg_addr)?;
573        if &dg.id != b"##DG" || dg.links.len() < 4 || dg.data.is_empty() {
574            return Err(err(format!("expected a ##DG block at {dg_addr:#x}")));
575        }
576        let dg_index = dgs.len();
577        let mut src_dg = SrcDg {
578            rec_id_len: dg.data[0],
579            comment: dg.links[3],
580            blocks: collect_data_blocks(reader, dg.links[2])?,
581            groups: Vec::new(),
582        };
583        if !matches!(src_dg.rec_id_len, 0 | 1 | 2 | 4 | 8) {
584            return Err(err(format!("invalid record id size {} at {dg_addr:#x}", src_dg.rec_id_len)));
585        }
586
587        let mut cg_addr = dg.links[1];
588        while cg_addr != 0 {
589            if !visited.insert(cg_addr) {
590                return Err(MdfError::BlockLinkError(format!("cycle in ##CG chain at {cg_addr:#x}")));
591            }
592            let cg = read_block(reader, cg_addr)?;
593            if &cg.id != b"##CG" || cg.links.len() < 6 || cg.data.len() < 32 {
594                return Err(err(format!("expected a ##CG block at {cg_addr:#x}")));
595            }
596            let name = read_string_block_via_reader(reader, cg.links[2])?;
597            let next_cg = cg.links[0];
598            let mut channels = Vec::new();
599            let mut cn_addr = cg.links[1];
600            while cn_addr != 0 {
601                if !visited.insert(cn_addr) {
602                    return Err(MdfError::BlockLinkError(format!("cycle in ##CN chain at {cn_addr:#x}")));
603                }
604                let cn = read_block(reader, cn_addr)?;
605                if &cn.id != b"##CN" || cn.links.len() < 8 || cn.data.len() < 72 {
606                    return Err(err(format!("expected a ##CN block at {cn_addr:#x}")));
607                }
608                let d = &cn.data;
609                channels.push(SrcChannel {
610                    name: read_string_block_via_reader(reader, cn.links[2])?,
611                    channel_type: d[0],
612                    bit_offset: d[3],
613                    byte_offset: u32_at(d, 4),
614                    bit_count: u32_at(d, 8),
615                    flags: u32_at(d, 12),
616                    inval_pos: u32_at(d, 16),
617                    links: cn.links.clone(),
618                    data: cn.data.clone(),
619                });
620                cn_addr = cn.links[0];
621            }
622            src_dg.groups.push(groups.len());
623            groups.push(SrcGroup {
624                dg: dg_index,
625                cg_addr,
626                record_id: u64_at(&cg.data, 0),
627                flags: u16_at(&cg.data, 16),
628                path_separator: u16_at(&cg.data, 18),
629                samples: u32_at(&cg.data, 24),
630                inval_bytes: u32_at(&cg.data, 28),
631                links: cg.links,
632                name,
633                channels,
634                records: 0,
635            });
636            cg_addr = next_cg;
637        }
638        dgs.push(src_dg);
639        dg_addr = dg.links[0];
640    }
641    Ok(Source { hd, dgs, groups })
642}
643
644/// Follow a data group's `##DT`/`##DV`/`##DL`/`##HL` chain.
645fn collect_data_blocks<R>(reader: &mut R, addr: u64) -> Result<Vec<SrcBlock>, MdfError>
646where
647    R: ByteRangeReader<Error = MdfError>,
648{
649    let mut out = Vec::new();
650    collect_chain(reader, addr, &mut out, |id| match id {
651        b"##DT" => Some(BlockKind::Dt),
652        b"##DV" => Some(BlockKind::Dv),
653        _ => None,
654    })?;
655    Ok(out)
656}
657
658/// Follow a VLSD channel's `##SD`/`##DL`/`##HL` chain.
659fn collect_sd_blocks<R>(reader: &mut R, addr: u64) -> Result<Vec<SrcBlock>, MdfError>
660where
661    R: ByteRangeReader<Error = MdfError>,
662{
663    let mut out = Vec::new();
664    collect_chain(reader, addr, &mut out, |id| (id == b"##SD").then_some(BlockKind::Dt))?;
665    Ok(out)
666}
667
668fn collect_chain<R>(
669    reader: &mut R,
670    mut addr: u64,
671    out: &mut Vec<SrcBlock>,
672    leaf: impl Fn(&[u8]) -> Option<BlockKind>,
673) -> Result<(), MdfError>
674where
675    R: ByteRangeReader<Error = MdfError>,
676{
677    let mut visited = HashSet::new();
678    while addr != 0 {
679        if !visited.insert(addr) {
680            return Err(MdfError::BlockLinkError(format!("cycle in data chain at {addr:#x}")));
681        }
682        let header = read_header(reader, addr)?;
683        let id = header.id.as_bytes();
684        if let Some(kind) = leaf(id) {
685            out.push(SrcBlock { data_offset: addr + HDR, len: header.block_len.saturating_sub(HDR), kind });
686            return Ok(());
687        }
688        match id {
689            b"##DL" => {
690                let dl = read_block(reader, addr)?;
691                for &frag in dl.links.iter().skip(1) {
692                    if frag == 0 {
693                        continue;
694                    }
695                    let fh = read_header(reader, frag)?;
696                    match leaf(fh.id.as_bytes()) {
697                        Some(kind) => out.push(SrcBlock {
698                            data_offset: frag + HDR,
699                            len: fh.block_len.saturating_sub(HDR),
700                            kind,
701                        }),
702                        None => return Err(unsupported_block(&fh.id, frag)),
703                    }
704                }
705                addr = dl.links.first().copied().unwrap_or(0);
706            }
707            b"##HL" => {
708                let hl = read_block(reader, addr)?;
709                addr = hl.links.first().copied().unwrap_or(0);
710            }
711            _ => return Err(unsupported_block(&header.id, addr)),
712        }
713    }
714    Ok(())
715}
716
717fn unsupported_block(id: &str, addr: u64) -> MdfError {
718    if id == "##DZ" {
719        err(format!(
720            "compressed ##DZ data block at {addr:#x}: compressed MDF files are not supported"
721        ))
722    } else {
723        MdfError::BlockIDError { actual: id.to_string(), expected: "a data block".into() }
724    }
725}
726
727// ---------------------------------------------------------------------------
728// Record streaming
729// ---------------------------------------------------------------------------
730
731/// Framing information for the records of one data group.
732struct Framing {
733    id_len: usize,
734    /// `(record id, group position in dg.groups, record bytes after the id, is VLSD storage)`
735    by_id: HashMap<u64, (usize, usize, bool)>,
736    sorted: bool,
737}
738
739impl Framing {
740    fn new(src: &Source, dg: usize) -> Result<Self, MdfError> {
741        let d = &src.dgs[dg];
742        let sorted = d.groups.len() == 1;
743        let mut by_id = HashMap::new();
744        for (pos, &g) in d.groups.iter().enumerate() {
745            let grp = &src.groups[g];
746            let size = grp.samples as usize + grp.inval_bytes as usize;
747            if !sorted && by_id.insert(grp.record_id, (pos, size, grp.is_vlsd_storage())).is_some() {
748                return Err(err(format!("duplicate record id {} in an unsorted data group", grp.record_id)));
749            }
750            if sorted {
751                by_id.insert(0, (pos, size, grp.is_vlsd_storage()));
752            }
753        }
754        if !sorted && d.rec_id_len == 0 {
755            return Err(err("data group with several channel groups but no record ids"));
756        }
757        Ok(Self { id_len: d.rec_id_len as usize, by_id, sorted })
758    }
759
760    /// Length of the record at the start of `buf` and its group position, or
761    /// `None` if `buf` does not hold a complete record yet. `avail` is the
762    /// number of bytes left in the data group counting from the start of
763    /// `buf`; a record that cannot fit in them is an error (a truncated record
764    /// or a corrupt VLSD length), so nothing is ever buffered beyond the data.
765    fn next(
766        &self,
767        buf: &[u8],
768        avail: u64,
769        kind: BlockKind,
770        dv_size: usize,
771    ) -> Result<Option<(usize, usize, usize, bool)>, MdfError> {
772        let need = |len: usize| -> Result<bool, MdfError> {
773            if len as u64 > avail {
774                return Err(err(format!(
775                    "data ends inside a record ({len}-byte record, {avail} bytes left; truncated data or corrupt record length)"
776                )));
777            }
778            Ok(buf.len() >= len)
779        };
780        if kind == BlockKind::Dv {
781            return Ok(need(dv_size)?.then_some((dv_size, 0, 0, false)));
782        }
783        if self.sorted {
784            let (pos, size, _) = self.by_id[&0];
785            let len = self.id_len + size;
786            return Ok(need(len)?.then_some((len, pos, self.id_len, false)));
787        }
788        if !need(self.id_len)? {
789            return Ok(None);
790        }
791        let id = match self.id_len {
792            1 => buf[0] as u64,
793            2 => u16_at(buf, 0) as u64,
794            4 => u32_at(buf, 0) as u64,
795            _ => u64_at(buf, 0),
796        };
797        let &(pos, size, vlsd) = self
798            .by_id
799            .get(&id)
800            .ok_or_else(|| err(format!("unknown record id {id} in unsorted data group")))?;
801        if vlsd {
802            if !need(self.id_len + 4)? {
803                return Ok(None);
804            }
805            let len = self.id_len + 4 + u32_at(buf, self.id_len) as usize;
806            return Ok(need(len)?.then_some((len, pos, self.id_len, true)));
807        }
808        let len = self.id_len + size;
809        Ok(need(len)?.then_some((len, pos, self.id_len, false)))
810    }
811}
812
813/// Stream every record of data group `dg` once, calling `f(group_position,
814/// record_without_id)` for each fixed-length record (VLSD storage records are
815/// skipped). Records may straddle data-block boundaries. Returns the record
816/// count per group position.
817fn stream_records<R, F>(
818    reader: &mut R,
819    src: &Source,
820    dg: usize,
821    chunk: usize,
822    mut f: F,
823) -> Result<Vec<u64>, MdfError>
824where
825    R: ByteRangeReader<Error = MdfError>,
826    F: FnMut(usize, &[u8]) -> Result<(), MdfError>,
827{
828    let d = &src.dgs[dg];
829    let mut counts = vec![0u64; d.groups.len()];
830    if d.groups.is_empty() {
831        return Ok(counts);
832    }
833    let framing = Framing::new(src, dg)?;
834    let first = &src.groups[d.groups[0]];
835    let dv_size = first.samples as usize;
836    if d.blocks.iter().any(|b| b.kind == BlockKind::Dv) {
837        if !framing.sorted || first.inval_bytes != 0 {
838            return Err(err(
839                "##DV data blocks are only supported for sorted groups without invalidation bytes",
840            ));
841        }
842        if dv_size == 0 {
843            return Ok(counts);
844        }
845    }
846    if framing.sorted && framing.id_len + first.samples as usize + first.inval_bytes as usize == 0 {
847        return Ok(counts);
848    }
849
850    // Sorted data: read whole records per chunk so records only need
851    // re-assembly where they straddle a data-block boundary.
852    let chunk = if framing.sorted {
853        let dt_len = framing.id_len + first.samples as usize + first.inval_bytes as usize;
854        let rec = dt_len.max(dv_size).max(1);
855        (chunk / rec).max(1) * rec
856    } else {
857        chunk
858    };
859    let mut pending: Vec<u8> = Vec::new();
860    let mut kind = BlockKind::Dt;
861    // Data-group bytes not read yet.
862    let mut unread: u64 = d.blocks.iter().map(|b| b.len).sum();
863    for blk in &d.blocks {
864        if blk.kind != kind && !pending.is_empty() {
865            return Err(err("a record straddles a ##DT/##DV block boundary"));
866        }
867        kind = blk.kind;
868        let mut off = 0u64;
869        while off < blk.len {
870            let n = (blk.len - off).min(chunk as u64);
871            let bytes = reader.read_range(blk.data_offset + off, n)?;
872            off += n;
873            unread -= n;
874            let buf: &[u8] = if pending.is_empty() {
875                &bytes
876            } else {
877                pending.extend_from_slice(&bytes);
878                &pending
879            };
880            let mut pos = 0usize;
881            while pos < buf.len() {
882                let avail = (buf.len() - pos) as u64 + unread;
883                let Some((len, gpos, id_len, vlsd)) = framing.next(&buf[pos..], avail, kind, dv_size)? else {
884                    break;
885                };
886                if !vlsd {
887                    f(gpos, &buf[pos + id_len..pos + len])?;
888                }
889                counts[gpos] += 1;
890                pos += len;
891            }
892            pending = buf[pos..].to_vec();
893        }
894    }
895    Ok(counts)
896}
897
898/// Determine the number of records of every group in data group `dg`.
899///
900/// Sorted groups are counted from the data-block sizes (no data is read);
901/// unsorted groups need a pass over the records.
902fn count_records<R>(reader: &mut R, src: &mut Source, dg: usize, chunk: usize) -> Result<(), MdfError>
903where
904    R: ByteRangeReader<Error = MdfError>,
905{
906    let d = &src.dgs[dg];
907    if d.groups.len() == 1 {
908        let g = &src.groups[d.groups[0]];
909        let dt_size = d.rec_id_len as u64 + g.samples as u64 + g.inval_bytes as u64;
910        let (mut dt, mut dv) = (0u64, 0u64);
911        for b in &d.blocks {
912            match b.kind {
913                BlockKind::Dt => dt += b.len,
914                BlockKind::Dv => dv += b.len,
915            }
916        }
917        let n = dt.checked_div(dt_size).unwrap_or(0) + dv.checked_div(g.samples as u64).unwrap_or(0);
918        let gi = d.groups[0];
919        src.groups[gi].records = n;
920        return Ok(());
921    }
922    let counts = stream_records(reader, src, dg, chunk, |_, _| Ok(()))?;
923    let groups = src.dgs[dg].groups.clone();
924    for (pos, g) in groups.into_iter().enumerate() {
925        src.groups[g].records = counts[pos];
926    }
927    Ok(())
928}
929
930// ---------------------------------------------------------------------------
931// Planning
932// ---------------------------------------------------------------------------
933
934/// One output data group (= one channel group = one channel).
935struct OutGroup {
936    src_group: usize,
937    channel: usize,
938    is_time: bool,
939    /// Index (into the output groups) of the time group, for signal groups.
940    master: Option<usize>,
941    /// Bytes copied from each source record.
942    data_bytes: u32,
943    /// Whether an invalidation byte follows the data bytes.
944    inval: bool,
945    records: u64,
946    /// VLSD `##SD` source fragments (empty = fixed-length channel).
947    sd_blocks: Vec<SrcBlock>,
948    vlsd: bool,
949}
950
951impl OutGroup {
952    fn record_size(&self) -> u64 {
953        self.data_bytes as u64 + u64::from(self.inval)
954    }
955}
956
957/// Decide which output groups to write and which time group each signal uses.
958fn plan_output<R>(
959    reader: &mut R,
960    src: &Source,
961    options: &ColumnOptions,
962    chunk: usize,
963    report: &mut ColumnReport,
964) -> Result<Vec<OutGroup>, MdfError>
965where
966    R: ByteRangeReader<Error = MdfError>,
967{
968    // Local master channel of each source group.
969    let master_of: Vec<Option<usize>> = src
970        .groups
971        .iter()
972        .map(|g| {
973            if g.is_vlsd_storage() {
974                return None;
975            }
976            g.channels.iter().position(|c| c.is_master() && c.fits(g.samples))
977        })
978        .collect();
979
980    // Group representing each source group's time axis (identical axes merge).
981    let mut rep: Vec<usize> = (0..src.groups.len()).collect();
982    if options.share_identical_time {
983        merge_identical_time(reader, src, &master_of, chunk, &mut rep)?;
984    }
985    report.shared_time_groups =
986        (0..src.groups.len()).filter(|&g| master_of[g].is_some() && rep[g] != g).count();
987
988    let mut out: Vec<OutGroup> = Vec::new();
989    let mut time_out: HashMap<usize, usize> = HashMap::new();
990    let addr_to_group: HashMap<u64, usize> =
991        src.groups.iter().enumerate().map(|(i, g)| (g.cg_addr, i)).collect();
992
993    for (gi, g) in src.groups.iter().enumerate() {
994        if g.is_vlsd_storage() {
995            continue;
996        }
997        // Which source group provides this group's time axis? A remote master
998        // is only usable when it has one sample per record of this group.
999        let time_src = match master_of[gi] {
1000            Some(_) => Some(rep[gi]),
1001            None => {
1002                let remote = addr_to_group.get(&g.remote_master_link()).copied().filter(|&m| master_of[m].is_some());
1003                match remote {
1004                    Some(m) if src.groups[m].records == g.records => Some(rep[m]),
1005                    Some(m) => {
1006                        report.skipped_channels.push(format!(
1007                            "{}: remote master dropped ({} records, master group has {})",
1008                            g.label(),
1009                            g.records,
1010                            src.groups[m].records
1011                        ));
1012                        None
1013                    }
1014                    None => None,
1015                }
1016            }
1017        };
1018        // The time group is written the first time any group needs it.
1019        let master = time_src.map(|t| {
1020            *time_out.entry(t).or_insert_with(|| {
1021                let tg = &src.groups[t];
1022                let ch = &tg.channels[master_of[t].unwrap()];
1023                out.push(OutGroup {
1024                    src_group: t,
1025                    channel: master_of[t].unwrap(),
1026                    is_time: true,
1027                    master: None,
1028                    data_bytes: ch.byte_len() as u32, // fits in the u32 record
1029                    inval: has_inval(tg, ch),
1030                    records: tg.records,
1031                    sd_blocks: Vec::new(),
1032                    vlsd: false,
1033                });
1034                out.len() - 1
1035            })
1036        });
1037
1038        for (ci, ch) in g.channels.iter().enumerate() {
1039            if Some(ci) == master_of[gi] {
1040                continue;
1041            }
1042            let label = || format!("{}/{}", g.label(), ch.name.as_deref().unwrap_or("<unnamed>"));
1043            if !ch.fits(g.samples) {
1044                report.skipped_channels.push(format!("{}: lies outside the record", label()));
1045                continue;
1046            }
1047            if ch.is_master() {
1048                report.skipped_channels.push(format!("{}: additional master channel", label()));
1049                continue;
1050            }
1051            if ch.channel_type == 4 {
1052                // Its cn_data link (attachment/stream reference) is not carried over.
1053                report.skipped_channels.push(format!("{}: synchronization channels are not supported", label()));
1054                continue;
1055            }
1056            if ch.links[1] != 0 {
1057                let id = read_header(reader, ch.links[1])?.id;
1058                if id == "##CA" || id == "##CN" {
1059                    let kind = if id == "##CA" { "array (##CA)" } else { "structure (##CN composition)" };
1060                    report.skipped_channels.push(format!("{}: {kind} channels are not supported", label()));
1061                    continue;
1062                }
1063            }
1064            let mut sd_blocks = Vec::new();
1065            let mut vlsd = false;
1066            if ch.channel_type == 1 && ch.links[5] != 0 {
1067                let target = read_header(reader, ch.links[5])?;
1068                if target.id == "##CG" {
1069                    report.skipped_channels.push(format!(
1070                        "{}: VLSD data stored in a VLSD channel group is not supported",
1071                        label()
1072                    ));
1073                    continue;
1074                }
1075                sd_blocks = collect_sd_blocks(reader, ch.links[5])?;
1076                vlsd = true;
1077            }
1078            out.push(OutGroup {
1079                src_group: gi,
1080                channel: ci,
1081                is_time: false,
1082                master,
1083                data_bytes: ch.byte_len() as u32,
1084                inval: has_inval(g, ch),
1085                records: g.records,
1086                sd_blocks,
1087                vlsd,
1088            });
1089        }
1090    }
1091    report.time_groups = out.iter().filter(|o| o.is_time).count();
1092    report.signal_groups = out.len() - report.time_groups;
1093    Ok(out)
1094}
1095
1096fn has_inval(g: &SrcGroup, ch: &SrcChannel) -> bool {
1097    ch.flags & CN_FLAG_ALL_INVALID == 0
1098        && ch.flags & CN_FLAG_INVAL_BIT_VALID != 0
1099        && (ch.inval_pos / 8) < g.inval_bytes
1100}
1101
1102/// `(byte index in the record after the id, bit mask)` of the channel's
1103/// invalidation bit, when it uses one.
1104fn inval_bit(g: &SrcGroup, ch: &SrcChannel) -> Option<(usize, u8)> {
1105    has_inval(g, ch).then(|| {
1106        let bit = ch.inval_pos as usize;
1107        (g.samples as usize + bit / 8, 1u8 << (bit % 8))
1108    })
1109}
1110
1111/// Point `rep[g]` at the first group whose time axis is byte-identical to
1112/// `g`'s. Only groups with the same record count and master layout are
1113/// compared, so files without shareable axes pay nothing.
1114fn merge_identical_time<R>(
1115    reader: &mut R,
1116    src: &Source,
1117    master_of: &[Option<usize>],
1118    chunk: usize,
1119    rep: &mut [usize],
1120) -> Result<(), MdfError>
1121where
1122    R: ByteRangeReader<Error = MdfError>,
1123{
1124    type Key = (u64, u8, u8, u8, u32, u64, u32, u64, Option<String>, bool, Vec<u8>);
1125    let mut by_key: HashMap<Key, Vec<usize>> = HashMap::new();
1126    for (g, m) in master_of.iter().enumerate() {
1127        let Some(m) = *m else { continue };
1128        let grp = &src.groups[g];
1129        let ch = &grp.channels[m];
1130        let key = (
1131            grp.records,
1132            ch.channel_type,
1133            ch.data[2],
1134            ch.bit_offset,
1135            ch.bit_count,
1136            ch.byte_len(),
1137            ch.flags,
1138            ch.links[4], // same conversion block
1139            read_string_block_via_reader(reader, ch.links[6])?, // same unit
1140            has_inval(grp, ch),
1141            ch.data[..2].to_vec(),
1142        );
1143        by_key.entry(key).or_default().push(g);
1144    }
1145    let candidates: Vec<Vec<usize>> = by_key.into_values().filter(|v| v.len() > 1).collect();
1146    if candidates.is_empty() {
1147        return Ok(());
1148    }
1149
1150    // Hash the raw master bytes of every candidate, one pass per data group.
1151    let mut hashes: HashMap<usize, (u64, u64)> = HashMap::new();
1152    let wanted: HashSet<usize> = candidates.iter().flatten().copied().collect();
1153    for (dgi, d) in src.dgs.iter().enumerate() {
1154        let targets: Vec<(usize, usize)> = d
1155            .groups
1156            .iter()
1157            .enumerate()
1158            .filter(|(_, g)| wanted.contains(g))
1159            .map(|(pos, &g)| (pos, g))
1160            .collect();
1161        if targets.is_empty() {
1162            continue;
1163        }
1164        let mut hashers: HashMap<usize, ChunkedHasher> =
1165            targets.iter().map(|&(pos, _)| (pos, ChunkedHasher::default())).collect();
1166        // (byte offset, byte length, invalidation bit) of each master.
1167        type Span = (usize, usize, Option<(usize, u8)>);
1168        let spans: HashMap<usize, Span> = targets
1169            .iter()
1170            .map(|&(pos, g)| {
1171                let grp = &src.groups[g];
1172                let ch = &grp.channels[master_of[g].unwrap()];
1173                (pos, (ch.byte_offset as usize, ch.byte_len() as usize, inval_bit(grp, ch)))
1174            })
1175            .collect();
1176        stream_records(reader, src, dgi, chunk, |pos, rec| {
1177            if let (Some(h), Some(&(o, l, inval))) = (hashers.get_mut(&pos), spans.get(&pos)) {
1178                h.write(&rec[o..o + l]);
1179                if let Some((byte, mask)) = inval {
1180                    h.write(&[u8::from(rec[byte] & mask != 0)]);
1181                }
1182            }
1183            Ok(())
1184        })?;
1185        for (pos, g) in targets {
1186            hashes.insert(g, hashers.remove(&pos).unwrap().finish());
1187        }
1188    }
1189
1190    for group in candidates {
1191        let mut firsts: Vec<usize> = Vec::new();
1192        for g in group {
1193            match firsts.iter().find(|&&f| hashes[&f] == hashes[&g]) {
1194                Some(&f) => rep[g] = f,
1195                None => firsts.push(g),
1196            }
1197        }
1198    }
1199    Ok(())
1200}
1201
1202/// 128-bit content hash that does not depend on how the input is split.
1203#[derive(Default)]
1204struct ChunkedHasher {
1205    buf: Vec<u8>,
1206    a: std::collections::hash_map::DefaultHasher,
1207    b: std::collections::hash_map::DefaultHasher,
1208    len: u64,
1209}
1210
1211impl ChunkedHasher {
1212    const BLOCK: usize = 64 * 1024;
1213
1214    fn write(&mut self, bytes: &[u8]) {
1215        self.buf.extend_from_slice(bytes);
1216        self.len += bytes.len() as u64;
1217        if self.buf.len() >= Self::BLOCK {
1218            self.drain();
1219        }
1220    }
1221
1222    fn drain(&mut self) {
1223        self.a.write(&self.buf);
1224        self.b.write_u64(0x9e37_79b9_7f4a_7c15);
1225        self.b.write(&self.buf);
1226        self.buf.clear();
1227    }
1228
1229    fn finish(mut self) -> (u64, u64) {
1230        self.drain();
1231        self.a.write_u64(self.len);
1232        (self.a.finish(), self.b.finish())
1233    }
1234}
1235
1236// ---------------------------------------------------------------------------
1237// Layout
1238// ---------------------------------------------------------------------------
1239
1240/// Growable metadata region starting at absolute offset `base`.
1241struct MetaBuf {
1242    base: u64,
1243    buf: Vec<u8>,
1244}
1245
1246impl MetaBuf {
1247    fn new(base: u64) -> Self {
1248        Self { base, buf: Vec::new() }
1249    }
1250
1251    fn end(&self) -> u64 {
1252        self.base + self.buf.len() as u64
1253    }
1254
1255    fn reserve(&mut self, len: u64) -> u64 {
1256        let addr = align8(self.end());
1257        self.buf.resize((addr + len - self.base) as usize, 0);
1258        addr
1259    }
1260
1261    fn alloc(&mut self, bytes: &[u8]) -> u64 {
1262        let addr = self.reserve(bytes.len() as u64);
1263        self.put(addr, bytes);
1264        addr
1265    }
1266
1267    fn put(&mut self, addr: u64, bytes: &[u8]) {
1268        let start = (addr - self.base) as usize;
1269        self.buf[start..start + bytes.len()].copy_from_slice(bytes);
1270    }
1271}
1272
1273/// Deep-copies metadata blocks (`##TX`, `##MD`, `##CC`, `##SI`, `##FH`),
1274/// remapping their links; each source block is copied once.
1275#[derive(Default)]
1276struct Copier {
1277    memo: HashMap<u64, u64>,
1278    visiting: HashSet<u64>,
1279}
1280
1281impl Copier {
1282    fn copy<R>(&mut self, reader: &mut R, buf: &mut MetaBuf, addr: u64) -> Result<u64, MdfError>
1283    where
1284        R: ByteRangeReader<Error = MdfError>,
1285    {
1286        self.copy_inner(reader, buf, addr, 0)
1287    }
1288
1289    fn copy_inner<R>(&mut self, reader: &mut R, buf: &mut MetaBuf, addr: u64, depth: u32) -> Result<u64, MdfError>
1290    where
1291        R: ByteRangeReader<Error = MdfError>,
1292    {
1293        if addr == 0 {
1294            return Ok(0);
1295        }
1296        if let Some(&out) = self.memo.get(&addr) {
1297            return Ok(out);
1298        }
1299        if depth > 64 || self.visiting.contains(&addr) {
1300            return Err(MdfError::ConversionChainCycle { address: addr });
1301        }
1302        let mut blk = read_block(reader, addr)?;
1303        match &blk.id {
1304            b"##TX" | b"##MD" | b"##CC" | b"##SI" => {}
1305            // Chains (`next` links) are walked iteratively by the caller.
1306            // (`##AT` blocks are streamed by `copy_attachments` instead.)
1307            b"##FH" => {
1308                if let Some(next) = blk.links.first_mut() {
1309                    *next = 0;
1310                }
1311            }
1312            _ => return Ok(0),
1313        }
1314        self.visiting.insert(addr);
1315        for l in blk.links.iter_mut() {
1316            *l = self.copy_inner(reader, buf, *l, depth + 1)?;
1317        }
1318        self.visiting.remove(&addr);
1319        let out = buf.alloc(&assemble(&blk.id, &blk.links, &blk.data));
1320        self.memo.insert(addr, out);
1321        Ok(out)
1322    }
1323
1324    /// Copy a `next`-linked `##FH` chain; returns the first and last
1325    /// copied addresses.
1326    fn copy_chain<R>(&mut self, reader: &mut R, buf: &mut MetaBuf, mut addr: u64) -> Result<(u64, u64), MdfError>
1327    where
1328        R: ByteRangeReader<Error = MdfError>,
1329    {
1330        let (mut first, mut last) = (0u64, 0u64);
1331        let mut seen = HashSet::new();
1332        while addr != 0 && seen.insert(addr) {
1333            let next = read_block(reader, addr)?.links.first().copied().unwrap_or(0);
1334            let out = self.copy(reader, buf, addr)?;
1335            if out == 0 {
1336                break;
1337            }
1338            if last != 0 {
1339                buf.put(last + HDR, &out.to_le_bytes());
1340            } else {
1341                first = out;
1342            }
1343            last = out;
1344            addr = next;
1345        }
1346        Ok((first, last))
1347    }
1348}
1349
1350/// Final placement of one output group.
1351struct PlacedGroup {
1352    out: OutGroup,
1353    /// Payload bytes per data block (a whole number of records, 8-byte aligned).
1354    block_payload: u64,
1355    n_blocks: u64,
1356    total_bytes: u64,
1357    data_addr: u64,
1358    block_id: [u8; 4],
1359    sd_addr: u64,
1360    sd_len: Option<u64>,
1361}
1362
1363impl PlacedGroup {
1364    fn block_addr(&self, i: u64) -> u64 {
1365        self.data_addr + i * (HDR + self.block_payload)
1366    }
1367
1368    fn block_len(&self, i: u64) -> u64 {
1369        if i + 1 < self.n_blocks {
1370            self.block_payload
1371        } else {
1372            self.total_bytes - i * self.block_payload
1373        }
1374    }
1375}
1376
1377/// Source bytes copied verbatim to the output in chunks.
1378struct StreamCopy {
1379    from: u64,
1380    to: u64,
1381    len: u64,
1382}
1383
1384struct Layout {
1385    groups: Vec<PlacedGroup>,
1386    /// Pre-built metadata to write verbatim: `(address, bytes)`.
1387    fixed_writes: Vec<(u64, Vec<u8>)>,
1388    /// Large payloads (embedded attachments) streamed from the source.
1389    copies: Vec<StreamCopy>,
1390    metadata_end: u64,
1391    file_size: u64,
1392}
1393
1394fn build_layout<R>(
1395    reader: &mut R,
1396    src: &Source,
1397    plan: Vec<OutGroup>,
1398    options: &ColumnOptions,
1399) -> Result<Layout, MdfError>
1400where
1401    R: ByteRangeReader<Error = MdfError>,
1402{
1403    const ID_LEN: u64 = 64;
1404    const HD_LEN: u64 = 104;
1405    let mut meta = MetaBuf::new(ID_LEN + HD_LEN);
1406    let mut copier = Copier::default();
1407
1408    // File-level metadata: header comment, file history (+ our own entry).
1409    let hd_comment = copier.copy(reader, &mut meta, src.hd.links[5])?;
1410    let (mut fh_first, fh_last) = copier.copy_chain(reader, &mut meta, src.hd.links[1])?;
1411    let fh_md = meta.alloc(&text_block(
1412        b"##MD",
1413        &format!(
1414            "<FHcomment xmlns=\"http://www.asam.net/mdf/v4\"><TX>Converted to column-oriented MDF 4.20 \
1415             (one signal per channel group, shared time channels)</TX><tool_id>mf4-rs</tool_id>\
1416             <tool_vendor>mf4-rs</tool_vendor><tool_version>{}</tool_version></FHcomment>",
1417            env!("CARGO_PKG_VERSION")
1418        ),
1419    ));
1420    let mut fh_data = Vec::with_capacity(16);
1421    fh_data.extend_from_slice(&now_ns().to_le_bytes());
1422    fh_data.extend_from_slice(&[0u8; 8]); // tz/dst offsets, time flags (UTC), reserved
1423    let our_fh = meta.alloc(&assemble(b"##FH", &[0, fh_md], &fh_data));
1424    if fh_last != 0 {
1425        meta.put(fh_last + HDR, &our_fh.to_le_bytes());
1426    } else {
1427        fh_first = our_fh;
1428    }
1429
1430    // Metadata referenced by each output group (shared blocks copied once).
1431    struct GroupMeta {
1432        dg_comment: u64,
1433        cg_links: [u64; 3], // acq name, acq source, comment
1434        cn_links: [u64; 5], // name, source, conversion, unit, comment
1435    }
1436    let mut metas = Vec::with_capacity(plan.len());
1437    for og in &plan {
1438        let g = &src.groups[og.src_group];
1439        let ch = &g.channels[og.channel];
1440        let mut cg_links = [0u64; 3];
1441        for (slot, &l) in cg_links.iter_mut().zip(&[g.links[2], g.links[3], g.links[5]]) {
1442            *slot = copier.copy(reader, &mut meta, l)?;
1443        }
1444        let mut cn_links = [0u64; 5];
1445        for (slot, &l) in cn_links.iter_mut().zip(&[ch.links[2], ch.links[3], ch.links[4], ch.links[6], ch.links[7]]) {
1446            *slot = copier.copy(reader, &mut meta, l)?;
1447        }
1448        metas.push(GroupMeta {
1449            dg_comment: copier.copy(reader, &mut meta, src.dgs[g.dg].comment)?,
1450            cg_links,
1451            cn_links,
1452        });
1453    }
1454
1455    // Data placement: compute block geometry per group.
1456    let mut placed: Vec<PlacedGroup> = plan
1457        .into_iter()
1458        .map(|out| {
1459            let rs = out.record_size();
1460            let total = rs * out.records;
1461            let (payload, n) = if total == 0 {
1462                (0, 0)
1463            } else {
1464                // Whole records per block, payload a multiple of 8 so the
1465                // blocks of one signal sit back to back without padding.
1466                let step = 8 / gcd(rs, 8);
1467                let per_block = ((options.block_size / rs) / step * step).max(step);
1468                let payload = per_block * rs;
1469                if total <= payload { (total, 1) } else { (payload, total.div_ceil(payload)) }
1470            };
1471            PlacedGroup {
1472                block_id: if out.inval { *b"##DT" } else { *b"##DV" },
1473                out,
1474                block_payload: payload,
1475                n_blocks: n,
1476                total_bytes: total,
1477                data_addr: 0,
1478                sd_addr: 0,
1479                sd_len: None,
1480            }
1481        })
1482        .collect();
1483
1484    // Structural blocks, in output order: DG, CG, CN (+ DL).
1485    struct Addrs {
1486        dg: u64,
1487        cg: u64,
1488        cn: u64,
1489        dl: u64,
1490    }
1491    let mut addrs = Vec::with_capacity(placed.len());
1492    for p in &placed {
1493        let dg = meta.reserve(64);
1494        let cg = meta.reserve(if p.out.master.is_some() { 112 } else { 104 });
1495        let cn = meta.reserve(160);
1496        // Data is always referenced through an equal-length ##DL (even a
1497        // single block), so readers learn every block size from the metadata
1498        // prefix and never have to read a header in the data region.
1499        let dl = if p.n_blocks > 0 { meta.reserve(HDR + (p.n_blocks + 1) * 8 + 16) } else { 0 };
1500        addrs.push(Addrs { dg, cg, cn, dl });
1501    }
1502    let metadata_end = align8(meta.end());
1503
1504    let mut cursor = metadata_end;
1505    for p in placed.iter_mut() {
1506        if p.n_blocks > 0 {
1507            p.data_addr = cursor;
1508            cursor = align8(p.block_addr(p.n_blocks - 1) + HDR + p.block_len(p.n_blocks - 1));
1509        }
1510        if p.out.vlsd {
1511            let len: u64 = p.out.sd_blocks.iter().map(|b| b.len).sum();
1512            p.sd_addr = cursor;
1513            p.sd_len = Some(len);
1514            cursor = align8(cursor + HDR + len);
1515        }
1516    }
1517
1518    // Attachments go after the data so they never bloat the metadata prefix.
1519    let mut tail = Vec::new();
1520    let mut copies = Vec::new();
1521    let (at_first, file_size) = copy_attachments(reader, &mut copier, src.hd.links[3], cursor, &mut tail, &mut copies)?;
1522
1523    // Fill in the structural blocks.
1524    for (i, (p, a)) in placed.iter().zip(&addrs).enumerate() {
1525        let m = &metas[i];
1526        let g = &src.groups[p.out.src_group];
1527        let ch = &g.channels[p.out.channel];
1528        let next_dg = addrs.get(i + 1).map_or(0, |n| n.dg);
1529        let data_link = a.dl;
1530
1531        let mut dg_data = [0u8; 8];
1532        dg_data[0] = 0; // record id size
1533        meta.put(a.dg, &assemble(b"##DG", &[next_dg, a.cg, data_link, m.dg_comment], &dg_data));
1534
1535        let mut cg_links = vec![0, a.cn, m.cg_links[0], m.cg_links[1], 0, m.cg_links[2]];
1536        let mut flags = g.flags & !(CG_FLAG_VLSD | CG_FLAG_REMOTE_MASTER | CG_FLAG_BUS_EVENTS);
1537        if let Some(t) = p.out.master {
1538            cg_links.push(addrs[t].cg);
1539            flags |= CG_FLAG_REMOTE_MASTER;
1540        }
1541        let mut cg_data = Vec::with_capacity(32);
1542        cg_data.extend_from_slice(&0u64.to_le_bytes()); // record id
1543        cg_data.extend_from_slice(&p.out.records.to_le_bytes());
1544        cg_data.extend_from_slice(&flags.to_le_bytes());
1545        cg_data.extend_from_slice(&g.path_separator.to_le_bytes());
1546        cg_data.extend_from_slice(&0u32.to_le_bytes());
1547        cg_data.extend_from_slice(&p.out.data_bytes.to_le_bytes());
1548        cg_data.extend_from_slice(&u32::from(p.out.inval).to_le_bytes());
1549        meta.put(a.cg, &assemble(b"##CG", &cg_links, &cg_data));
1550
1551        let mut cn_data = ch.data[..72].to_vec();
1552        let mut cn_type = ch.channel_type;
1553        if cn_type == 5 {
1554            cn_type = 0; // maximum-length channel: keep the full bytes, drop the size link
1555        }
1556        cn_data[0] = cn_type;
1557        cn_data[4..8].copy_from_slice(&0u32.to_le_bytes()); // byte offset
1558        let mut cn_flags = ch.flags & !CN_FLAG_DEFAULT_X;
1559        if !p.out.inval {
1560            cn_flags &= !CN_FLAG_INVAL_BIT_VALID;
1561        }
1562        cn_data[12..16].copy_from_slice(&cn_flags.to_le_bytes());
1563        cn_data[16..20].copy_from_slice(&0u32.to_le_bytes()); // invalidation bit position
1564        cn_data[22..24].copy_from_slice(&0u16.to_le_bytes()); // attachment count
1565        let sd_link = if p.sd_len.is_some() { p.sd_addr } else { 0 };
1566        let cn_links = [0, 0, m.cn_links[0], m.cn_links[1], m.cn_links[2], sd_link, m.cn_links[3], m.cn_links[4]];
1567        meta.put(a.cn, &assemble(b"##CN", &cn_links, &cn_data));
1568
1569        if p.n_blocks > 0 {
1570            let links = (0..p.n_blocks).map(|b| p.block_addr(b)).collect();
1571            let dl = DataListBlock::new_equal(links, p.block_payload);
1572            meta.put(a.dl, &dl.to_bytes()?);
1573        }
1574    }
1575
1576    // ##ID + ##HD.
1577    let id = IdentificationBlock {
1578        version_identifier: "4.20    ".into(),
1579        version_number: 420,
1580        ..Default::default()
1581    };
1582    let first_dg = addrs.first().map_or(0, |a| a.dg);
1583    // Always the 104-byte MDF 4 ##HD (32-byte data section): the metadata
1584    // region is placed right after it.
1585    let mut hd_data = src.hd.data[..src.hd.data.len().min(32)].to_vec();
1586    hd_data.resize(32, 0);
1587    let hd = assemble(b"##HD", &[first_dg, fh_first, 0, at_first, 0, hd_comment], &hd_data);
1588
1589    let mut fixed_writes = vec![(0, id.to_bytes()?), (64, hd)];
1590    let MetaBuf { base, buf } = meta;
1591    fixed_writes.push((base, buf));
1592    fixed_writes.extend(tail);
1593    Ok(Layout { groups: placed, fixed_writes, copies, metadata_end, file_size })
1594}
1595
1596/// Size of the fixed part of an `##AT` data section (flags, creator index,
1597/// reserved, MD5, original and embedded size) before the embedded payload.
1598const AT_FIXED_DATA: u64 = 40;
1599
1600/// Lay out the `##AT` chain starting at `addr` from output offset `cursor`.
1601///
1602/// Each attachment's header, links and fixed fields (plus the `##TX`/`##MD`
1603/// blocks it references) go to `writes`; its embedded payload, which can be
1604/// arbitrarily large, is recorded in `copies` and streamed later. Returns the
1605/// first copied attachment's address and the end of the laid-out region.
1606fn copy_attachments<R>(
1607    reader: &mut R,
1608    copier: &mut Copier,
1609    mut addr: u64,
1610    mut cursor: u64,
1611    writes: &mut Vec<(u64, Vec<u8>)>,
1612    copies: &mut Vec<StreamCopy>,
1613) -> Result<(u64, u64), MdfError>
1614where
1615    R: ByteRangeReader<Error = MdfError>,
1616{
1617    let mut first = 0u64;
1618    // Index into `writes` of the previous attachment (to patch its `next`).
1619    let mut prev: Option<usize> = None;
1620    let mut seen = HashSet::new();
1621    while addr != 0 && seen.insert(addr) {
1622        let header = read_header(reader, addr)?;
1623        if header.id != "##AT" {
1624            break;
1625        }
1626        let links_len = header
1627            .links_nr
1628            .checked_mul(8)
1629            .and_then(|l| l.checked_add(HDR))
1630            .filter(|&l| header.links_nr >= 4 && l <= header.block_len && l <= MAX_METADATA_BLOCK)
1631            .ok_or_else(|| err(format!("##AT block at {addr:#x} has an inconsistent link count")))?;
1632        let fixed_len = header.block_len.min(links_len + AT_FIXED_DATA);
1633        let mut fixed = reader.read_range(addr, fixed_len)?;
1634        let next = u64_at(&fixed, HDR as usize);
1635
1636        // Referenced metadata (file name, MIME type, comment) first.
1637        let mut refs = MetaBuf::new(cursor);
1638        fixed[HDR as usize..HDR as usize + 8].copy_from_slice(&0u64.to_le_bytes());
1639        for i in 1..header.links_nr as usize {
1640            let at = HDR as usize + i * 8;
1641            let out = copier.copy(reader, &mut refs, u64_at(&fixed, at))?;
1642            fixed[at..at + 8].copy_from_slice(&out.to_le_bytes());
1643        }
1644        cursor = align8(refs.end());
1645        if !refs.buf.is_empty() {
1646            writes.push((refs.base, refs.buf));
1647        }
1648
1649        let out = cursor;
1650        if let Some(p) = prev {
1651            writes[p].1[HDR as usize..HDR as usize + 8].copy_from_slice(&out.to_le_bytes());
1652        } else {
1653            first = out;
1654        }
1655        prev = Some(writes.len());
1656        writes.push((out, fixed));
1657        if header.block_len > fixed_len {
1658            copies.push(StreamCopy { from: addr + fixed_len, to: out + fixed_len, len: header.block_len - fixed_len });
1659        }
1660        cursor = align8(out + header.block_len);
1661        addr = next;
1662    }
1663    Ok((first, cursor))
1664}
1665
1666fn gcd(a: u64, b: u64) -> u64 {
1667    if b == 0 { a } else { gcd(b, a % b) }
1668}
1669
1670/// Current time in ns since the Unix epoch (for the `##FH` entry).
1671fn now_ns() -> u64 {
1672    #[cfg(not(target_arch = "wasm32"))]
1673    {
1674        std::time::SystemTime::now()
1675            .duration_since(std::time::UNIX_EPOCH)
1676            .map(|d| d.as_nanos() as u64)
1677            .unwrap_or(0)
1678    }
1679    #[cfg(all(target_arch = "wasm32", feature = "wasm"))]
1680    {
1681        (js_sys::Date::now() * 1e6) as u64
1682    }
1683    #[cfg(all(target_arch = "wasm32", not(feature = "wasm")))]
1684    {
1685        0
1686    }
1687}
1688
1689// ---------------------------------------------------------------------------
1690// Data streaming
1691// ---------------------------------------------------------------------------
1692
1693/// Buffered writer for one output group's logical data stream; inserts the
1694/// data-block headers at the pre-computed positions.
1695struct ColumnStream<'a> {
1696    group: &'a PlacedGroup,
1697    written: u64,
1698    buf: Vec<u8>,
1699    cap: usize,
1700}
1701
1702impl ColumnStream<'_> {
1703    #[inline]
1704    fn push<S: ColumnSink + ?Sized>(&mut self, bytes: &[u8], sink: &mut S) -> Result<(), MdfError> {
1705        self.buf.extend_from_slice(bytes);
1706        if self.buf.len() >= self.cap {
1707            self.flush(sink)?;
1708        }
1709        Ok(())
1710    }
1711
1712    fn flush<S: ColumnSink + ?Sized>(&mut self, sink: &mut S) -> Result<(), MdfError> {
1713        let g = self.group;
1714        if self.written + self.buf.len() as u64 > g.total_bytes {
1715            return Err(err("more records than counted while streaming"));
1716        }
1717        let mut rest: &[u8] = &self.buf;
1718        while !rest.is_empty() {
1719            let block = self.written / g.block_payload;
1720            let pos = self.written % g.block_payload;
1721            let addr = g.block_addr(block);
1722            if pos == 0 {
1723                sink.write_at(addr, &block_header_bytes(&g.block_id, HDR + g.block_len(block), 0))?;
1724            }
1725            let n = ((g.block_len(block) - pos) as usize).min(rest.len());
1726            sink.write_at(addr + HDR + pos, &rest[..n])?;
1727            self.written += n as u64;
1728            rest = &rest[n..];
1729        }
1730        self.buf.clear();
1731        Ok(())
1732    }
1733}
1734
1735/// How to extract one output column from a source record.
1736struct Extract {
1737    stream: usize,
1738    offset: usize,
1739    len: usize,
1740    /// `(byte index in the record after the id, bit mask)` of the
1741    /// invalidation bit.
1742    inval: Option<(usize, u8)>,
1743}
1744
1745fn stream_data<R, S>(
1746    reader: &mut R,
1747    src: &Source,
1748    layout: &Layout,
1749    options: &ColumnOptions,
1750    chunk: usize,
1751    sink: &mut S,
1752) -> Result<(), MdfError>
1753where
1754    R: ByteRangeReader<Error = MdfError>,
1755    S: ColumnSink + ?Sized,
1756{
1757    // Output groups fed by each source group (time groups once, by their
1758    // representative source group).
1759    let mut by_src: Vec<Vec<&PlacedGroup>> = (0..src.groups.len()).map(|_| Vec::new()).collect();
1760    for p in &layout.groups {
1761        by_src[p.out.src_group].push(p);
1762    }
1763    for (dgi, d) in src.dgs.iter().enumerate() {
1764        let mut streams: Vec<ColumnStream> = Vec::new();
1765        let mut extracts: Vec<Vec<Extract>> = (0..d.groups.len()).map(|_| Vec::new()).collect();
1766        for (pos, &p) in d.groups.iter().enumerate().flat_map(|(pos, &g)| by_src[g].iter().map(move |p| (pos, p))) {
1767            if p.total_bytes == 0 {
1768                continue;
1769            }
1770            let g = &src.groups[p.out.src_group];
1771            let ch = &g.channels[p.out.channel];
1772            let inval = if p.out.inval { inval_bit(g, ch) } else { None };
1773            extracts[pos].push(Extract {
1774                stream: streams.len(),
1775                offset: ch.byte_offset as usize,
1776                len: p.out.data_bytes as usize,
1777                inval,
1778            });
1779            streams.push(ColumnStream { group: p, written: 0, buf: Vec::new(), cap: 0 });
1780        }
1781
1782        if !streams.is_empty() {
1783            let cap = (options.memory_budget / streams.len() as u64)
1784                .clamp(MIN_STREAM_BUFFER as u64, (options.block_size.max(MIN_STREAM_BUFFER as u64)).min(1 << 30))
1785                as usize;
1786            for s in streams.iter_mut() {
1787                s.cap = cap;
1788                s.buf.reserve(cap.min(s.group.total_bytes as usize) + 64);
1789            }
1790            stream_records(reader, src, dgi, chunk, |pos, rec| {
1791                for e in &extracts[pos] {
1792                    let s = &mut streams[e.stream];
1793                    s.push(&rec[e.offset..e.offset + e.len], sink)?;
1794                    if let Some((byte, mask)) = e.inval {
1795                        s.push(&[u8::from(rec[byte] & mask != 0)], sink)?;
1796                    }
1797                }
1798                Ok(())
1799            })?;
1800            for s in streams.iter_mut() {
1801                s.flush(sink)?;
1802                if s.written != s.group.total_bytes {
1803                    return Err(err(format!(
1804                        "record count changed while streaming ({} of {} bytes)",
1805                        s.written, s.group.total_bytes
1806                    )));
1807                }
1808            }
1809        }
1810
1811        // VLSD signal data: copy each channel's ##SD stream verbatim right
1812        // after its records, so the inline offsets stay valid.
1813        for p in d.groups.iter().flat_map(|&g| &by_src[g]) {
1814            let Some(sd_len) = p.sd_len else { continue };
1815            sink.write_at(p.sd_addr, &block_header_bytes(b"##SD", HDR + sd_len, 0))?;
1816            let mut at = p.sd_addr + HDR;
1817            for b in &p.out.sd_blocks {
1818                copy_range(reader, sink, b.data_offset, at, b.len, chunk)?;
1819                at += b.len;
1820            }
1821        }
1822    }
1823    Ok(())
1824}
1825
1826/// Copy `len` source bytes at `from` to output offset `to`, `chunk` at a time.
1827fn copy_range<R, S>(reader: &mut R, sink: &mut S, from: u64, to: u64, len: u64, chunk: usize) -> Result<(), MdfError>
1828where
1829    R: ByteRangeReader<Error = MdfError>,
1830    S: ColumnSink + ?Sized,
1831{
1832    let mut off = 0;
1833    while off < len {
1834        let n = (len - off).min(chunk as u64);
1835        sink.write_at(to + off, &reader.read_range(from + off, n)?)?;
1836        off += n;
1837    }
1838    Ok(())
1839}