Skip to main content

mf4_rs/parsing/
decoder.rs

1use crate::blocks::channel_block::ChannelBlock;
2use crate::blocks::common::DataType;
3use byteorder::{LittleEndian, BigEndian, ByteOrder};
4
5// Flag bit positions for cn_flags
6const CN_FLAG_ALL_INVALID: u32 = 0x01;  // Bit 0: All values are invalid
7const CN_FLAG_INVAL_BIT_VALID: u32 = 0x02;  // Bit 1: Invalidation bit is valid
8
9/// Integer data types are at most 64 bits wide (MDF 4.1 ยง6.6.3); a wider
10/// field cannot be decoded into a `u64` / `i64`.
11const MAX_INTEGER_BITS: usize = 64;
12
13/// Bits `[bit_offset, bit_offset + bit_count)` of a little-endian field.
14/// Folded into a `u128` so a 64-bit field shifted by up to 7 bits (9 bytes)
15/// keeps its high bits. `bit_count` <= 64, `slice` at most 16 bytes.
16#[inline(always)]
17fn bits_le(slice: &[u8], bit_offset: usize, bit_count: usize) -> u64 {
18    let raw = slice.iter().rev().fold(0u128, |acc, &b| (acc << 8) | b as u128);
19    mask_bits((raw >> bit_offset) as u64, bit_count)
20}
21
22/// [`bits_le`] for a big-endian field.
23#[inline(always)]
24fn bits_be(slice: &[u8], bit_offset: usize, bit_count: usize) -> u64 {
25    let raw = slice.iter().fold(0u128, |acc, &b| (acc << 8) | b as u128);
26    mask_bits((raw >> bit_offset) as u64, bit_count)
27}
28
29#[inline(always)]
30fn mask_bits(value: u64, bit_count: usize) -> u64 {
31    if bit_count >= 64 { value } else { value & ((1u64 << bit_count) - 1) }
32}
33
34/// Two's-complement sign extension of a `bit_count`-bit value (1..=64).
35#[inline(always)]
36fn sign_extend(value: u64, bit_count: usize) -> i64 {
37    let shift = 64 - bit_count.min(64) as u32;
38    ((value << shift) as i64) >> shift
39}
40
41/// The signal-data offset a VLSD channel's fixed-length field holds in
42/// `record` (an unsigned little-endian integer, 64 bits wide per the spec).
43pub(crate) fn vlsd_offset(channel: &ChannelBlock, record: &[u8], record_id_size: usize) -> Result<u64, crate::error::MdfError> {
44    let start = record_id_size + channel.byte_offset as usize;
45    let bit_offset = channel.bit_offset as usize;
46    let bit_count = channel.bit_count as usize;
47    let len = (bit_offset + bit_count).div_ceil(8);
48    match record.get(start..start + len) {
49        Some(field) if bit_count > 0 && bit_count <= MAX_INTEGER_BITS && bit_offset <= 7 => {
50            Ok(bits_le(field, bit_offset, bit_count))
51        }
52        Some(_) => Err(crate::error::MdfError::BlockSerializationError(format!(
53            "VLSD channel has a {bit_count}-bit offset field at bit offset {bit_offset}; \
54             the offset must be an integer of at most 64 bits"
55        ))),
56        None => Err(crate::error::MdfError::TooShortBuffer {
57            actual: record.len(),
58            expected: start + len,
59            file: file!(),
60            line: line!(),
61        }),
62    }
63}
64
65/// An enum representing the decoded value of a channel sample.
66#[derive(Debug, Clone, PartialEq)]
67pub enum DecodedValue {
68    UnsignedInteger(u64),
69    SignedInteger(i64),
70    Float(f64),
71    String(String),
72    ByteArray(Vec<u8>),
73    MimeSample(Vec<u8>),
74    MimeStream(Vec<u8>),
75    Unknown,
76}
77
78/// Result of decoding a channel value, including validity status.
79#[derive(Debug, Clone, PartialEq)]
80pub struct DecodedChannelValue {
81    pub value: DecodedValue,
82    pub is_valid: bool,
83}
84
85/// Checks if a channel value is valid based on invalidation bits.
86///
87/// According to MDF 4.1 spec section 4.21.5.1:
88/// - If cn_flags bit 0 is set (1), all values are invalid
89/// - If cn_flags bits 0 and 1 are both clear (0), all values are valid
90/// - Otherwise, must check the invalidation bit in the record
91///
92/// # Parameters
93/// - `record`: The complete record bytes including record ID, data, and invalidation bytes
94/// - `record_id_size`: Number of bytes for the record ID
95/// - `cg_data_bytes`: Number of bytes for the data portion (samples_byte_nr from channel group)
96/// - `channel`: The channel block containing flags and invalidation bit position
97///
98/// # Returns
99/// `true` if the value is valid, `false` if invalid
100pub fn check_value_validity(
101    record: &[u8],
102    record_id_size: usize,
103    cg_data_bytes: u32,
104    channel: &ChannelBlock,
105) -> bool {
106    // Check cn_flags first for shortcuts
107    if channel.flags & CN_FLAG_ALL_INVALID != 0 {
108        // Bit 0 set: all values are invalid
109        return false;
110    }
111    
112    if channel.flags & (CN_FLAG_ALL_INVALID | CN_FLAG_INVAL_BIT_VALID) == 0 {
113        // Bits 0 and 1 both clear: all values are valid
114        return true;
115    }
116    
117    // Must check the invalidation bit in the record
118    // Location: record_id + data_bytes + (cn_inval_bit_pos >> 3)
119    let inval_byte_offset = record_id_size + cg_data_bytes as usize 
120                          + (channel.pos_invalidation_bit >> 3) as usize;
121    let inval_bit_index = (channel.pos_invalidation_bit & 0x07) as usize;
122    
123    if inval_byte_offset < record.len() {
124        let inval_byte = record[inval_byte_offset];
125        let bit_is_set = (inval_byte >> inval_bit_index) & 0x01 != 0;
126        // If the invalidation bit is set (1), the value is INVALID
127        !bit_is_set
128    } else {
129        // No invalidation byte available, assume valid
130        true
131    }
132}
133
134/// Decodes a channel's sample from a record (legacy function without validity checking).
135///
136/// This function takes the raw record data, skips over the record ID,
137/// and then uses channel metadata (offsets, bit settings, and data type)
138/// from the given `ChannelBlock` to decode the sample. It supports numeric
139/// types (unsigned/signed integers, floats), strings (Latin1, UTF-8, UTF-16LE,
140/// UTF-16BE), byte arrays, and MIME samples/streams.
141/// 
142/// # Parameters
143/// - `record`: A slice containing the entire record's bytes.
144/// - `record_id_size`: The number of bytes reserved at the beginning of the record for the record ID.
145/// - `channel`: A reference to the channel metadata used for decoding.
146/// 
147/// # Returns
148/// An `Option<DecodedValue>` containing the decoded sample, or `None` if there isn't enough data.
149/// 
150/// # Note
151/// This function does NOT check invalidation bits. For full MDF spec compliance,
152/// use `decode_channel_value_with_validity` instead.
153pub fn decode_channel_value(
154    record: &[u8],
155    record_id_size: usize,
156    channel: &ChannelBlock,
157) -> Option<DecodedValue> {
158    decode_value_internal(record, record_id_size, channel)
159}
160
161/// Decodes a channel's sample from a record with validity checking.
162///
163/// This function performs the full MDF 4.1 spec-compliant decoding including
164/// invalidation bit checking. It returns both the decoded value and whether
165/// the value is valid according to the invalidation bits.
166/// 
167/// # Parameters
168/// - `record`: A slice containing the entire record's bytes (including invalidation bytes)
169/// - `record_id_size`: The number of bytes reserved at the beginning of the record for the record ID
170/// - `cg_data_bytes`: Number of data bytes in the record (samples_byte_nr from channel group)
171/// - `channel`: A reference to the channel metadata used for decoding
172/// 
173/// # Returns
174/// An `Option<DecodedChannelValue>` containing the decoded sample and validity status,
175/// or `None` if there isn't enough data to decode.
176pub fn decode_channel_value_with_validity(
177    record: &[u8],
178    record_id_size: usize,
179    cg_data_bytes: u32,
180    channel: &ChannelBlock,
181) -> Option<DecodedChannelValue> {
182    let value = decode_value_internal(record, record_id_size, channel)?;
183    let is_valid = check_value_validity(record, record_id_size, cg_data_bytes, channel);
184    
185    Some(DecodedChannelValue { value, is_valid })
186}
187
188/// Decode a single f64 value directly from a record, bypassing DecodedValue.
189/// Returns NaN for values that can't be decoded as f64.
190/// This is the fastest path for reading numeric channels.
191#[inline(always)]
192pub fn decode_f64_from_record(
193    record: &[u8],
194    record_id_size: usize,
195    channel: &ChannelBlock,
196) -> f64 {
197    let base_offset = record_id_size + channel.byte_offset as usize;
198    let bit_offset = channel.bit_offset as usize;
199    let bit_count = channel.bit_count as usize;
200
201    // For non-VLSD channels only
202    if channel.channel_type == 1 && channel.data != 0 {
203        return f64::NAN;
204    }
205
206    // bit_count == 0 has no value to decode (and would underflow the
207    // sign-bit computation below); bit_offset must be 0..=7 per the spec
208    // (larger values would overflow the shifts below).
209    if bit_count == 0 || bit_offset > 7 || bit_count > MAX_INTEGER_BITS {
210        return f64::NAN;
211    }
212
213    let num_bytes = (bit_offset + bit_count).div_ceil(8).max(1);
214    if base_offset + num_bytes > record.len() {
215        return f64::NAN;
216    }
217    let slice = &record[base_offset..base_offset + num_bytes];
218
219    match &channel.data_type {
220        DataType::FloatLE => {
221            if bit_offset == 0 {
222                if bit_count == 64 {
223                    return LittleEndian::read_f64(slice);
224                } else if bit_count == 32 {
225                    return LittleEndian::read_f32(slice) as f64;
226                }
227            }
228            // Fold into u128 so a 64-bit field spanning 9 bytes (bit_offset
229            // != 0) survives the shift, then drop the leading bit_offset bits.
230            let raw = slice.iter().rev().fold(0u128, |acc, &b| (acc << 8) | b as u128);
231            let raw = (raw >> bit_offset) as u64;
232            if bit_count == 32 {
233                f32::from_bits(raw as u32) as f64
234            } else if bit_count == 64 {
235                f64::from_bits(raw)
236            } else {
237                f64::NAN
238            }
239        },
240        DataType::FloatBE => {
241            if bit_offset == 0 {
242                if bit_count == 64 {
243                    return BigEndian::read_f64(slice);
244                } else if bit_count == 32 {
245                    return BigEndian::read_f32(slice) as f64;
246                }
247            }
248            let raw = slice.iter().fold(0u128, |acc, &b| (acc << 8) | b as u128);
249            let raw = (raw >> bit_offset) as u64;
250            if bit_count == 32 {
251                f32::from_bits(raw as u32) as f64
252            } else if bit_count == 64 {
253                f64::from_bits(raw)
254            } else {
255                f64::NAN
256            }
257        },
258        DataType::UnsignedIntegerLE => {
259            if bit_offset == 0 {
260                match bit_count {
261                    8 => return slice[0] as f64,
262                    16 => return LittleEndian::read_u16(slice) as f64,
263                    32 => return LittleEndian::read_u32(slice) as f64,
264                    64 => return LittleEndian::read_u64(slice) as f64,
265                    _ => {}
266                }
267            }
268            bits_le(slice, bit_offset, bit_count) as f64
269        },
270        DataType::UnsignedIntegerBE => {
271            if bit_offset == 0 {
272                match bit_count {
273                    8 => return slice[0] as f64,
274                    16 => return BigEndian::read_u16(slice) as f64,
275                    32 => return BigEndian::read_u32(slice) as f64,
276                    64 => return BigEndian::read_u64(slice) as f64,
277                    _ => {}
278                }
279            }
280            bits_be(slice, bit_offset, bit_count) as f64
281        },
282        DataType::SignedIntegerLE => {
283            if bit_offset == 0 {
284                match bit_count {
285                    8 => return (slice[0] as i8) as f64,
286                    16 => return LittleEndian::read_i16(slice) as f64,
287                    32 => return LittleEndian::read_i32(slice) as f64,
288                    64 => return LittleEndian::read_i64(slice) as f64,
289                    _ => {}
290                }
291            }
292            sign_extend(bits_le(slice, bit_offset, bit_count), bit_count) as f64
293        },
294        DataType::SignedIntegerBE => {
295            if bit_offset == 0 {
296                match bit_count {
297                    8 => return (slice[0] as i8) as f64,
298                    16 => return BigEndian::read_i16(slice) as f64,
299                    32 => return BigEndian::read_i32(slice) as f64,
300                    64 => return BigEndian::read_i64(slice) as f64,
301                    _ => {}
302                }
303            }
304            sign_extend(bits_be(slice, bit_offset, bit_count), bit_count) as f64
305        },
306        _ => f64::NAN,
307    }
308}
309
310/// Internal function that performs the actual value decoding.
311///
312/// This is the core decoding logic separated out so it can be used by both
313/// the legacy function and the new validity-aware function.
314fn decode_value_internal(
315    record: &[u8],
316    record_id_size: usize,
317    channel: &ChannelBlock,
318) -> Option<DecodedValue> {
319    
320    // Calculate the starting offset of this channel's data.
321    let base_offset = record_id_size + channel.byte_offset as usize;
322    let bit_offset = channel.bit_offset as usize;
323    let bit_count = channel.bit_count as usize;
324
325    let is_numeric = matches!(
326        channel.data_type,
327        DataType::UnsignedIntegerLE
328            | DataType::UnsignedIntegerBE
329            | DataType::SignedIntegerLE
330            | DataType::SignedIntegerBE
331            | DataType::FloatLE
332            | DataType::FloatBE
333    );
334
335    // bit_count == 0 has no value to decode (and would underflow the
336    // sign-bit computation for signed integers); bit_offset must be 0..=7
337    // per the spec (larger values would overflow the shifts below).
338    if is_numeric && (bit_count == 0 || bit_offset > 7 || bit_count > MAX_INTEGER_BITS) {
339        return None;
340    }
341
342    let slice: &[u8] = if channel.channel_type == 1 && channel.data != 0 {
343        // VLSD: the entire record *is* the payload. Numeric types are still
344        // read with a fixed width, so a short payload must yield None
345        // instead of panicking inside the fixed-width readers.
346        if is_numeric {
347            let needed = (bit_offset + bit_count).div_ceil(8).max(1);
348            if record.len() < needed {
349                return None;
350            }
351            &record[..needed]
352        } else {
353            record
354        }
355    } else {
356        // For non-numeric types, assume the field is stored in whole bytes.
357        let num_bytes = if matches!(channel.data_type,
358            DataType::StringLatin1 | DataType::StringUtf8 | DataType::StringUtf16LE | DataType::StringUtf16BE |
359            DataType::ByteArray | DataType::MimeSample | DataType::MimeStream)
360        {
361            bit_count / 8
362        } else {
363            (bit_offset + bit_count).div_ceil(8).max(1)
364        };
365
366        if base_offset + num_bytes > record.len() {
367            return None;
368        }
369        &record[base_offset..base_offset + num_bytes]
370    };
371
372    match &channel.data_type {
373        DataType::UnsignedIntegerLE => {
374            if bit_offset == 0 {
375                match bit_count {
376                    8 => return Some(DecodedValue::UnsignedInteger(slice[0] as u64)),
377                    16 => return Some(DecodedValue::UnsignedInteger(LittleEndian::read_u16(slice) as u64)),
378                    32 => return Some(DecodedValue::UnsignedInteger(LittleEndian::read_u32(slice) as u64)),
379                    64 => return Some(DecodedValue::UnsignedInteger(LittleEndian::read_u64(slice))),
380                    _ => {}
381                }
382            }
383            Some(DecodedValue::UnsignedInteger(bits_le(slice, bit_offset, bit_count)))
384        },
385        DataType::UnsignedIntegerBE => {
386            if bit_offset == 0 {
387                match bit_count {
388                    8 => return Some(DecodedValue::UnsignedInteger(slice[0] as u64)),
389                    16 => return Some(DecodedValue::UnsignedInteger(BigEndian::read_u16(slice) as u64)),
390                    32 => return Some(DecodedValue::UnsignedInteger(BigEndian::read_u32(slice) as u64)),
391                    64 => return Some(DecodedValue::UnsignedInteger(BigEndian::read_u64(slice))),
392                    _ => {}
393                }
394            }
395            Some(DecodedValue::UnsignedInteger(bits_be(slice, bit_offset, bit_count)))
396        },
397        DataType::SignedIntegerLE => {
398            if bit_offset == 0 {
399                match bit_count {
400                    8 => return Some(DecodedValue::SignedInteger(slice[0] as i8 as i64)),
401                    16 => return Some(DecodedValue::SignedInteger(LittleEndian::read_i16(slice) as i64)),
402                    32 => return Some(DecodedValue::SignedInteger(LittleEndian::read_i32(slice) as i64)),
403                    64 => return Some(DecodedValue::SignedInteger(LittleEndian::read_i64(slice))),
404                    _ => {}
405                }
406            }
407            Some(DecodedValue::SignedInteger(sign_extend(bits_le(slice, bit_offset, bit_count), bit_count)))
408        },
409        DataType::SignedIntegerBE => {
410            if bit_offset == 0 {
411                match bit_count {
412                    8 => return Some(DecodedValue::SignedInteger(slice[0] as i8 as i64)),
413                    16 => return Some(DecodedValue::SignedInteger(BigEndian::read_i16(slice) as i64)),
414                    32 => return Some(DecodedValue::SignedInteger(BigEndian::read_i32(slice) as i64)),
415                    64 => return Some(DecodedValue::SignedInteger(BigEndian::read_i64(slice))),
416                    _ => {}
417                }
418            }
419            Some(DecodedValue::SignedInteger(sign_extend(bits_be(slice, bit_offset, bit_count), bit_count)))
420        },
421        DataType::FloatLE => {
422            if bit_offset == 0 {
423                if bit_count == 32 {
424                    return Some(DecodedValue::Float(LittleEndian::read_f32(slice) as f64));
425                } else if bit_count == 64 {
426                    return Some(DecodedValue::Float(LittleEndian::read_f64(slice)));
427                }
428            }
429            // Fold into u128 so a 64-bit field spanning 9 bytes (bit_offset
430            // != 0) survives the shift, then drop the leading bit_offset bits.
431            let raw = slice.iter().rev().fold(0u128, |acc, &b| (acc << 8) | b as u128);
432            let raw = (raw >> bit_offset) as u64;
433            if bit_count == 32 {
434                Some(DecodedValue::Float(f32::from_bits(raw as u32) as f64))
435            } else if bit_count == 64 {
436                Some(DecodedValue::Float(f64::from_bits(raw)))
437            } else {
438                None
439            }
440        },
441        DataType::FloatBE => {
442            if bit_offset == 0 {
443                if bit_count == 32 {
444                    return Some(DecodedValue::Float(BigEndian::read_f32(slice) as f64));
445                } else if bit_count == 64 {
446                    return Some(DecodedValue::Float(BigEndian::read_f64(slice)));
447                }
448            }
449            let raw = slice.iter().fold(0u128, |acc, &b| (acc << 8) | b as u128);
450            let raw = (raw >> bit_offset) as u64;
451            if bit_count == 32 {
452                Some(DecodedValue::Float(f32::from_bits(raw as u32) as f64))
453            } else if bit_count == 64 {
454                Some(DecodedValue::Float(f64::from_bits(raw)))
455            } else {
456                None
457            }
458        },
459        DataType::StringLatin1 => {
460            // Latin1: each byte maps directly to a character. The value is a
461            // NUL-terminated string: stop at the first NUL byte (matches
462            // asammdf) instead of only trimming trailing NULs.
463            let end = slice.iter().position(|&b| b == 0).unwrap_or(slice.len());
464            let s: String = slice[..end].iter().map(|&b| b as char).collect();
465            Some(DecodedValue::String(s))
466        },
467        DataType::StringUtf8 => {
468            let end = slice.iter().position(|&b| b == 0).unwrap_or(slice.len());
469            match std::str::from_utf8(&slice[..end]) {
470                Ok(s) => Some(DecodedValue::String(s.to_string())),
471                Err(_) => Some(DecodedValue::String(String::from("<Invalid UTF8>")))
472            }
473        },
474        DataType::StringUtf16LE => {
475            // An odd byte count cannot form a code unit: drop the trailing
476            // byte instead of refusing to decode the value.
477            let even = &slice[..slice.len() & !1];
478            let u16_data: Vec<u16> = even.chunks_exact(2)
479                .map(LittleEndian::read_u16)
480                .collect();
481            let end = u16_data.iter().position(|&u| u == 0).unwrap_or(u16_data.len());
482            match String::from_utf16(&u16_data[..end]) {
483                Ok(s) => Some(DecodedValue::String(s)),
484                Err(_) => Some(DecodedValue::String(String::from("<Invalid UTF16LE>")))
485            }
486        },
487        DataType::StringUtf16BE => {
488            let even = &slice[..slice.len() & !1];
489            let u16_data: Vec<u16> = even.chunks_exact(2)
490                .map(BigEndian::read_u16)
491                .collect();
492            let end = u16_data.iter().position(|&u| u == 0).unwrap_or(u16_data.len());
493            match String::from_utf16(&u16_data[..end]) {
494                Ok(s) => Some(DecodedValue::String(s)),
495                Err(_) => Some(DecodedValue::String(String::from("<Invalid UTF16BE>")))
496            }
497        },
498        DataType::ByteArray => Some(DecodedValue::ByteArray(slice.to_vec())),
499        DataType::MimeSample => Some(DecodedValue::MimeSample(slice.to_vec())),
500        DataType::MimeStream => Some(DecodedValue::MimeStream(slice.to_vec())),
501        _ => Some(DecodedValue::Unknown),
502    }
503}