fluxfox 0.1.0

A library crate for working with floppy disk images for the IBM PC and compatibles.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
    FluxFox
    https://github.com/dbalsom/fluxfox

    Copyright 2024 Daniel Balsom

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the “Software”),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.

    --------------------------------------------------------------------------
*/
use crate::flux::pll::{Pll, PllDecodeStatEntry};
use crate::flux::{FluxStats, FluxTransition};
use crate::{DiskCh, DiskDataEncoding};
use bit_vec::BitVec;
use histogram::{Bucket, Histogram};
use std::cmp::Ordering;

/// Type of revolution.
/// `Source` is a direct read from the disk image.
/// `Synthetic` is a generated revolution, usually shifting a flux from one source revolution
///             to another.
#[derive(Copy, Clone, Debug)]
pub enum FluxRevolutionType {
    Source,
    Synthetic,
}

pub struct FluxRevolutionStats {
    pub rev_type: FluxRevolutionType,
    pub encoding: DiskDataEncoding,
    pub data_rate: f64,
    pub index_time: f64,
    pub ft_ct: usize,
    pub bitcell_ct: usize,
    pub first_ft: f64,
    pub last_ft: f64,
}

pub struct FluxRevolution {
    pub rev_type: FluxRevolutionType,
    pub ch: DiskCh,
    pub data_rate: Option<f64>,
    pub index_time: f64,
    pub flux_deltas: Vec<f64>,
    pub transitions: Vec<FluxTransition>,
    pub bitstream: BitVec,
    pub biterrors: BitVec,
    pub encoding: DiskDataEncoding,
    pub pll_stats: Vec<PllDecodeStatEntry>,
}

impl FluxRevolution {
    pub fn encoding(&self) -> DiskDataEncoding {
        self.encoding
    }

    pub fn stats(&self) -> FluxRevolutionStats {
        let computed_data_rate = self.bitstream.len() as f64 * (1.0 / self.index_time);
        FluxRevolutionStats {
            rev_type: self.rev_type,
            encoding: self.encoding,
            data_rate: self.data_rate.unwrap_or(computed_data_rate),
            index_time: self.index_time,
            ft_ct: self.flux_deltas.len(),
            bitcell_ct: self.bitstream.len(),
            first_ft: *self.flux_deltas.first().unwrap_or(&0.0),
            last_ft: *self.flux_deltas.last().unwrap_or(&0.0),
        }
    }

    pub fn from_f64(ch: DiskCh, deltas: &[f64], index_time: f64) -> Self {
        FluxRevolution {
            rev_type: FluxRevolutionType::Source,
            ch,
            data_rate: None,
            index_time,
            flux_deltas: deltas.to_vec(),
            transitions: Vec::with_capacity(deltas.len()),
            bitstream: BitVec::with_capacity(deltas.len() * 3),
            biterrors: BitVec::with_capacity(deltas.len() * 3),
            encoding: DiskDataEncoding::Mfm,
            pll_stats: Vec::new(),
        }
    }

    pub fn from_u16(ch: DiskCh, data: &[u16], index_time: f64, timebase: f64) -> Self {
        log::debug!("FluxRevolution::from_u16(): Using timebase of {:.3}ns", timebase * 1e9);
        let mut new = FluxRevolution {
            rev_type: FluxRevolutionType::Source,
            ch,
            data_rate: None,
            index_time,
            flux_deltas: Vec::with_capacity(data.len()),
            transitions: Vec::with_capacity(data.len()),
            bitstream: BitVec::with_capacity(data.len() * 3),
            biterrors: BitVec::with_capacity(data.len() * 3),
            encoding: DiskDataEncoding::Mfm,
            pll_stats: Vec::new(),
        };
        let mut nfa_count = 0;
        for cell in data {
            if *cell == 0 {
                nfa_count += 1;
                continue;
            }

            // Convert to float seconds
            let seconds = *cell as f64 * timebase;
            new.flux_deltas.push(seconds);
        }

        log::warn!("FluxRevolution::from_u16(): {} NFA cells found", nfa_count);
        new
    }

    pub(crate) fn from_adjacent_pair(first: &FluxRevolution, second: &FluxRevolution) -> Vec<FluxRevolution> {
        let mut new_revolutions = Vec::new();

        let flux_ct_diff = (first.flux_deltas.len() as i64 - second.flux_deltas.len() as i64).abs();

        match first.flux_deltas.len().cmp(&second.flux_deltas.len()) {
            Ordering::Greater if flux_ct_diff == 2 => {
                log::debug!(
                    "FluxRevolution::from_adjacent_pair(): First revolution is candidate for flux shift to second."
                );

                let mut first_deltas = first.flux_deltas.clone();
                let shift_delta = first_deltas.pop();

                let mut second_deltas = second.flux_deltas.clone();
                second_deltas.insert(0, shift_delta.unwrap());

                let new_first = FluxRevolution {
                    rev_type: FluxRevolutionType::Synthetic,
                    ch: first.ch,
                    data_rate: first.data_rate,
                    index_time: first.index_time,
                    transitions: Vec::with_capacity(first_deltas.len()),
                    flux_deltas: first_deltas,
                    bitstream: BitVec::with_capacity(first.bitstream.capacity()),
                    biterrors: BitVec::with_capacity(first.bitstream.capacity()),
                    encoding: DiskDataEncoding::Mfm,
                    pll_stats: Vec::new(),
                };

                let new_second = FluxRevolution {
                    rev_type: FluxRevolutionType::Synthetic,
                    ch: second.ch,
                    data_rate: second.data_rate,
                    index_time: second.index_time,
                    transitions: Vec::with_capacity(second_deltas.len()),
                    flux_deltas: second_deltas,
                    bitstream: BitVec::with_capacity(second.bitstream.capacity()),
                    biterrors: BitVec::with_capacity(second.bitstream.capacity()),
                    encoding: DiskDataEncoding::Mfm,
                    pll_stats: Vec::new(),
                };

                new_revolutions.push(new_first);
                new_revolutions.push(new_second);
            }
            Ordering::Less if flux_ct_diff == 2 => {
                log::debug!(
                    "FluxRevolution::from_adjacent_pair(): Second revolution is candidate for flux shift to first."
                );

                let mut first_deltas = first.flux_deltas.clone();
                let mut second_deltas = second.flux_deltas.clone();

                let shift_delta = second_deltas.remove(0);
                first_deltas.push(shift_delta);

                let new_first = FluxRevolution {
                    rev_type: FluxRevolutionType::Synthetic,
                    ch: first.ch,
                    data_rate: first.data_rate,
                    index_time: first.index_time,
                    transitions: Vec::with_capacity(first_deltas.len()),
                    flux_deltas: first_deltas,
                    bitstream: BitVec::with_capacity(first.bitstream.capacity()),
                    biterrors: BitVec::with_capacity(first.bitstream.capacity()),
                    encoding: DiskDataEncoding::Mfm,
                    pll_stats: Vec::new(),
                };

                let new_second = FluxRevolution {
                    rev_type: FluxRevolutionType::Synthetic,
                    ch: second.ch,
                    data_rate: second.data_rate,
                    index_time: second.index_time,
                    transitions: Vec::with_capacity(second_deltas.len()),
                    flux_deltas: second_deltas,
                    bitstream: BitVec::with_capacity(second.bitstream.capacity()),
                    biterrors: BitVec::with_capacity(second.bitstream.capacity()),
                    encoding: DiskDataEncoding::Mfm,
                    pll_stats: Vec::new(),
                };

                new_revolutions.push(new_first);
                new_revolutions.push(new_second);
            }
            _ => {}
        }

        new_revolutions
    }

    pub(crate) fn ft_ct(&self) -> usize {
        self.flux_deltas.len()
    }

    #[allow(dead_code)]
    pub(crate) fn pll_stats(&self) -> &Vec<PllDecodeStatEntry> {
        &self.pll_stats
    }

    fn find_local_maxima(hist: &Histogram) -> Vec<(u64, std::ops::RangeInclusive<u64>)> {
        let mut peaks = vec![];
        let mut previous_bucket: Option<Bucket> = None;
        let mut current_bucket: Option<Bucket> = None;

        // Calculate total count for threshold
        let total_count: u64 = hist.into_iter().map(|bucket| bucket.count()).sum();
        let threshold = (total_count as f64 * 0.005).round() as u64;

        for bucket in hist.into_iter() {
            if let (Some(prev), Some(curr)) = (previous_bucket.as_ref(), current_bucket.as_ref()) {
                // Identify local maximum and apply threshold check
                if curr.count() >= prev.count() && curr.count() > bucket.count() && curr.count() >= threshold {
                    peaks.push((curr.count(), curr.start()..=curr.end()));
                }
            }
            // Update previous and current buckets
            previous_bucket = current_bucket.take();
            current_bucket = Some(bucket.clone());
        }

        peaks
    }

    pub fn base_transition_time(&self, hist: &Histogram) -> Option<f64> {
        let peaks = Self::find_local_maxima(hist);

        if peaks.len() < 2 {
            log::warn!("FluxRevolution::base_transition_time(): Not enough peaks found");
            return None;
        }

        let first_peak = &peaks[0].1;

        let range_median = (first_peak.start() + first_peak.end()) / 2;
        // Convert back to seconds
        Some(range_median as f64 / 1_000_000_000.0)
    }

    pub fn histogram(&self, percent: f32) -> Histogram {
        // from docs:
        // grouping_power should be set such that 2^(-1 * grouping_power) is an acceptable relative error.
        // Rephrased, we can plug in the acceptable relative error into grouping_power = ceil(log2(1/e)).
        // For example, if we want to limit the error to 0.1% (0.001) we should set grouping_power = 7.

        // Max value power of 2^14 = 16384 (16us)
        // Grouping power of 3 produces sharp spikes without false maxima
        let mut hist = Histogram::new(3, 14).unwrap();

        let take_count = (self.flux_deltas.len() as f32 * percent).round() as usize;
        log::debug!("FluxRevolution::histogram(): Taking {} flux deltas", take_count);
        for delta_ns in self
            .flux_deltas
            .iter()
            .take(take_count)
            .map(|d| (*d * 1_000_000_000.0) as u64)
        {
            _ = hist.increment(delta_ns);
        }

        let peaks = Self::find_local_maxima(&hist);

        for peak in peaks {
            log::debug!(
                "FluxRevolution::histogram(): Peak at range: {:?} ct: {}",
                peak.1,
                peak.0
            );
        }

        //Self::print_horizontal_histogram_with_labels(&hist, 16);

        hist
    }

    /// Debugging function to print a historgram in ASCII.
    #[allow(dead_code)]
    fn print_horizontal_histogram_with_labels(hist: &Histogram, height: usize) {
        let mut max_count = 0;
        let mut buckets = vec![];

        // Step 1: Collect buckets and find max count for scaling
        for bucket in hist.into_iter() {
            max_count = max_count.max(bucket.count());
            buckets.push(bucket);
        }

        // Step 2: Initialize 2D array for histogram, filled with spaces
        let width = buckets.len();
        let mut graph = vec![vec![' '; width]; height];

        // Step 3: Plot each bucket count as a column of asterisks
        for (i, bucket) in buckets.iter().enumerate() {
            let bar_height = if max_count > 0 {
                (bucket.count() as f64 / max_count as f64 * height as f64).round() as usize
            }
            else {
                0
            };
            for row in (height - bar_height)..height {
                graph[row][i] = '*';
            }
        }

        // Step 4: Print the graph row by row
        for row in &graph {
            println!("{}", row.iter().collect::<String>());
        }

        // Step 5: Print bucket start values vertically
        let max_label_len = buckets.iter().map(|b| b.start().to_string().len()).max().unwrap_or(0);
        for i in 0..max_label_len {
            let row: String = buckets
                .iter()
                .map(|b| {
                    let label = b.start().to_string();
                    label.chars().nth(i).unwrap_or(' ')
                })
                .collect();
            println!("{}", row);
        }
    }

    pub fn transition_ct(&self) -> usize {
        self.transitions.len()
    }

    pub fn transition_avg(&self) -> f64 {
        let mut t_sum = 0.0;
        let mut t_ct = 0;
        for t in self.flux_deltas.iter() {
            if *t > 0.0 {
                t_ct += 1;
                t_sum += *t;
            }
        }
        t_sum / t_ct as f64
    }

    pub fn bitstream_data(&self) -> (Vec<u8>, usize) {
        (self.bitstream.to_bytes(), self.bitstream.len())
    }

    pub fn decode(&mut self, pll: &mut Pll) {
        self.transitions = pll.decode_transitions(self);
        //self.decode_bitstream();
        log::trace!(
            "FluxRevolution::decode(): Decoded {} transitions into {} bits, ratio: {}",
            self.transitions.len(),
            self.bitstream.len(),
            self.bitstream.len() as f64 / self.transitions.len() as f64
        );
    }

    pub fn decode_direct(&mut self, pll: &mut Pll) -> FluxStats {
        let mut decode_result = pll.decode(self, DiskDataEncoding::Mfm);
        let encoding = decode_result
            .flux_stats
            .detect_encoding()
            .unwrap_or(DiskDataEncoding::Mfm);

        if decode_result.markers.is_empty() && matches!(encoding, DiskDataEncoding::Fm) {
            // If we detected FM encoding, decode again as FM
            log::warn!("FluxRevolution::decode(): No markers found. Track might be FM encoded? Re-decoding...");

            let fm_result = pll.decode(self, DiskDataEncoding::Fm);
            if fm_result.markers.is_empty() {
                log::warn!("FluxRevolution::decode(): No markers found in FM decode. Keeping MFM.");
                self.encoding = DiskDataEncoding::Mfm;
            }
            else {
                log::debug!("FluxRevolution::decode(): Found FM marker! Setting track to FM encoding.");
                self.encoding = DiskDataEncoding::Fm;
                decode_result = fm_result;
            }
        }

        self.bitstream = decode_result.bits;

        log::trace!(
            "FluxRevolution::decode(): Decoded {} transitions into {} bits with {} encoding, ratio: {}",
            self.flux_deltas.len(),
            self.bitstream.len(),
            self.encoding,
            self.bitstream.len() as f64 / self.flux_deltas.len() as f64
        );

        self.data_rate = Some(self.bitstream.len() as f64 * (1.0 / self.index_time) / 2.0);
        self.pll_stats = decode_result.pll_stats;
        decode_result.flux_stats
    }

    pub fn delta_iter(&self) -> std::slice::Iter<f64> {
        self.flux_deltas.iter()
    }
}