oximedia-graph 0.1.8

Filter pipeline for OxiMedia
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
//! Graph evaluation: topological execution, cycle detection facade, dynamic editing,
//! serialization helpers, conditional routing, gain node, and multi-input node.
//!
//! This module wires together the various graph-processing primitives (topological sort,
//! cycle detection, frame pool) into concrete high-level APIs.

#![allow(dead_code)]

#[allow(unused_imports)]
use std::collections::{HashMap, HashSet, VecDeque};

use crate::cycle_detect::CycleGraph;
use crate::error::{GraphError, GraphResult};
use crate::frame::FilterFrame;
use crate::node::{Node, NodeId, NodeState, NodeType};
use crate::port::{AudioPortFormat, InputPort, OutputPort, PortFormat, PortId, PortType};

#[allow(unused_imports)]
use oximedia_audio::{AudioBuffer, AudioFrame, ChannelLayout};
#[allow(unused_imports)]
use oximedia_codec::VideoFrame;
#[allow(unused_imports)]
use oximedia_core::{PixelFormat, SampleFormat, Timestamp};

// ─── Cycle detection facade ──────────────────────────────────────────────────

/// Error returned when a cycle is found during graph validation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CycleError {
    /// Nodes that form or participate in a cycle.
    pub cycle_nodes: Vec<NodeId>,
}

impl std::fmt::Display for CycleError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Cycle detected in graph involving {} nodes",
            self.cycle_nodes.len()
        )
    }
}

impl std::error::Error for CycleError {}

// ─── Simple graph descriptor used by evaluator / validator ───────────────────

/// A lightweight directed-graph descriptor used by the evaluator layer.
///
/// This is a plain data structure — it does not own `Node` trait objects.
/// Use `FilterGraph` from `crate::graph` for full node execution.
#[derive(Debug, Clone, Default)]
pub struct SimpleGraph {
    /// Adjacency list: source NodeId → list of successor NodeIds.
    pub edges: HashMap<NodeId, Vec<NodeId>>,
    /// Node labels for serialization and diagnostics.
    pub labels: HashMap<NodeId, String>,
}

impl SimpleGraph {
    /// Create a new empty graph descriptor.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a node with a label.
    pub fn add_node(&mut self, id: NodeId, label: impl Into<String>) {
        self.labels.insert(id, label.into());
        self.edges.entry(id).or_default();
    }

    /// Add a directed edge (implicitly creates both nodes if absent).
    pub fn add_edge(&mut self, from: NodeId, to: NodeId) {
        self.edges.entry(from).or_default().push(to);
        self.edges.entry(to).or_default();
        self.labels
            .entry(from)
            .or_insert_with(|| format!("{}", from.0));
        self.labels.entry(to).or_insert_with(|| format!("{}", to.0));
    }

    /// Return the number of nodes.
    #[must_use]
    pub fn node_count(&self) -> usize {
        self.edges.len()
    }

    /// Return the number of directed edges.
    #[must_use]
    pub fn edge_count(&self) -> usize {
        self.edges.values().map(|v| v.len()).sum()
    }

    /// Return all node IDs sorted for determinism.
    #[must_use]
    pub fn node_ids(&self) -> Vec<NodeId> {
        let mut ids: Vec<NodeId> = self.edges.keys().copied().collect();
        ids.sort_by_key(|id| id.0);
        ids
    }
}

// ─── GraphEvaluator ──────────────────────────────────────────────────────────

/// Evaluates a filter graph by executing nodes in topological order.
///
/// # Example
///
/// ```ignore
/// use oximedia_graph::graph_evaluator::GraphEvaluator;
/// let order = GraphEvaluator::topological_sort(&graph).unwrap();
/// ```
pub struct GraphEvaluator;

impl GraphEvaluator {
    /// Perform a topological sort of the graph using Kahn's algorithm.
    ///
    /// Returns the nodes in a valid processing order (every edge `a → b`
    /// guarantees `a` appears before `b` in the result).
    ///
    /// # Errors
    ///
    /// Returns [`CycleError`] if the graph contains a cycle.
    pub fn topological_sort(graph: &SimpleGraph) -> Result<Vec<NodeId>, CycleError> {
        // Build in-degree map
        let mut in_degree: HashMap<NodeId, usize> = graph.edges.keys().map(|&id| (id, 0)).collect();

        for successors in graph.edges.values() {
            for &succ in successors {
                *in_degree.entry(succ).or_insert(0) += 1;
            }
        }

        // Enqueue nodes with in-degree 0 (sorted for determinism)
        let mut queue: VecDeque<NodeId> = {
            let mut zeros: Vec<NodeId> = in_degree
                .iter()
                .filter(|(_, &d)| d == 0)
                .map(|(&id, _)| id)
                .collect();
            zeros.sort_by_key(|id| id.0);
            zeros.into_iter().collect()
        };

        let mut order = Vec::with_capacity(graph.node_count());

        while let Some(node) = queue.pop_front() {
            order.push(node);
            let mut successors: Vec<NodeId> = graph.edges.get(&node).cloned().unwrap_or_default();
            successors.sort_by_key(|id| id.0);
            for succ in successors {
                if let Some(d) = in_degree.get_mut(&succ) {
                    *d -= 1;
                    if *d == 0 {
                        queue.push_back(succ);
                    }
                }
            }
        }

        if order.len() != graph.node_count() {
            let cycle_nodes: Vec<NodeId> = in_degree
                .iter()
                .filter(|(_, &d)| d > 0)
                .map(|(&id, _)| id)
                .collect();
            return Err(CycleError { cycle_nodes });
        }

        Ok(order)
    }

    /// Process a frame through all nodes in topological order, applying
    /// each node's transform in sequence.
    ///
    /// `processors` maps `NodeId` to a boxed transform function
    /// `fn(Option<FilterFrame>) -> Option<FilterFrame>`.
    pub fn evaluate(
        order: &[NodeId],
        processors: &mut HashMap<
            NodeId,
            Box<dyn FnMut(Option<FilterFrame>) -> Option<FilterFrame>>,
        >,
        input: FilterFrame,
    ) -> Option<FilterFrame> {
        let mut current = Some(input);
        for &id in order {
            if let Some(proc) = processors.get_mut(&id) {
                current = proc(current);
            }
        }
        current
    }
}

// ─── GraphValidator ───────────────────────────────────────────────────────────

/// Validates a filter graph for structural correctness.
pub struct GraphValidator;

impl GraphValidator {
    /// Return `true` if the graph has at least one cycle.
    ///
    /// Uses DFS with gray/black node colouring (identical to
    /// `CycleGraph::has_cycle` but operating on the `SimpleGraph` type).
    #[must_use]
    pub fn has_cycle(graph: &SimpleGraph) -> bool {
        let mut cg = CycleGraph::new();
        for (&from, successors) in &graph.edges {
            for &to in successors {
                cg.add_edge(
                    crate::cycle_detect::CycleNodeId(from.0 as usize),
                    crate::cycle_detect::CycleNodeId(to.0 as usize),
                );
            }
            // Ensure isolated nodes are registered
            if successors.is_empty() {
                cg.add_node(crate::cycle_detect::CycleNodeId(from.0 as usize));
            }
        }
        cg.has_cycle()
    }

    /// Return `true` if the graph is a valid DAG (no cycles, at least one node).
    #[must_use]
    pub fn is_valid_dag(graph: &SimpleGraph) -> bool {
        !graph.edges.is_empty() && !Self::has_cycle(graph)
    }

    /// Collect all nodes with in-degree 0 (potential source nodes).
    #[must_use]
    pub fn source_nodes(graph: &SimpleGraph) -> Vec<NodeId> {
        let mut in_degree: HashMap<NodeId, usize> = graph.edges.keys().map(|&k| (k, 0)).collect();
        for succs in graph.edges.values() {
            for &s in succs {
                *in_degree.entry(s).or_insert(0) += 1;
            }
        }
        let mut sources: Vec<NodeId> = in_degree
            .into_iter()
            .filter(|(_, d)| *d == 0)
            .map(|(id, _)| id)
            .collect();
        sources.sort_by_key(|id| id.0);
        sources
    }

    /// Collect all nodes with out-degree 0 (potential sink nodes).
    #[must_use]
    pub fn sink_nodes(graph: &SimpleGraph) -> Vec<NodeId> {
        let mut sinks: Vec<NodeId> = graph
            .edges
            .iter()
            .filter(|(_, succs)| succs.is_empty())
            .map(|(&id, _)| id)
            .collect();
        sinks.sort_by_key(|id| id.0);
        sinks
    }
}

// ─── EdgeId ───────────────────────────────────────────────────────────────────

/// Identifies a directed edge by its source and destination node IDs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EdgeId {
    /// Source node.
    pub from: NodeId,
    /// Destination node.
    pub to: NodeId,
}

impl EdgeId {
    /// Create a new edge ID.
    #[must_use]
    pub fn new(from: NodeId, to: NodeId) -> Self {
        Self { from, to }
    }
}

// ─── GraphEditor ─────────────────────────────────────────────────────────────

/// Supports dynamic modification of a graph without full rebuild.
pub struct GraphEditor;

impl GraphEditor {
    /// Insert `new_node_id` on an existing edge `edge`, splitting it into two.
    ///
    /// Before: `edge.from → edge.to`
    /// After:  `edge.from → new_node_id → edge.to`
    ///
    /// The edge label of the new segments inherits the label of `new_node_id`.
    ///
    /// # Errors
    ///
    /// Returns `Err` if the edge does not exist in the graph.
    pub fn insert_node_between(
        graph: &mut SimpleGraph,
        new_node_id: NodeId,
        new_node_label: impl Into<String>,
        edge: EdgeId,
    ) -> GraphResult<()> {
        // Verify edge exists
        let successors = graph
            .edges
            .get(&edge.from)
            .ok_or(GraphError::NodeNotFound(edge.from))?;
        if !successors.contains(&edge.to) {
            return Err(GraphError::ConfigurationError(format!(
                "Edge {:?}{:?} does not exist",
                edge.from, edge.to
            )));
        }

        // Remove old edge from.to
        if let Some(succs) = graph.edges.get_mut(&edge.from) {
            succs.retain(|&id| id != edge.to);
        }

        // Insert new node
        let label = new_node_label.into();
        graph.labels.insert(new_node_id, label);
        graph.edges.entry(new_node_id).or_default();

        // Add edges: from → new → to
        graph
            .edges
            .get_mut(&edge.from)
            .unwrap_or(&mut vec![])
            .push(new_node_id);
        // Use entry to avoid double borrow
        graph.edges.entry(edge.from).or_default().push(new_node_id);
        // Add new_node → to
        graph.edges.entry(new_node_id).or_default().push(edge.to);

        Ok(())
    }
}

// ─── GraphSerializer ─────────────────────────────────────────────────────────

/// Serializes a filter graph to various text formats.
pub struct GraphSerializer;

impl GraphSerializer {
    /// Produce a valid Graphviz DOT representation of the graph.
    ///
    /// ```text
    /// digraph G {
    ///     0 [label="source"];
    ///     1 [label="filter"];
    ///     2 [label="sink"];
    ///     0 -> 1;
    ///     1 -> 2;
    /// }
    /// ```
    #[must_use]
    pub fn to_dot(graph: &SimpleGraph) -> String {
        let mut out = String::from("digraph G {\n");

        let mut node_ids = graph.node_ids();
        node_ids.sort_by_key(|id| id.0);

        for id in &node_ids {
            let label = graph
                .labels
                .get(id)
                .cloned()
                .unwrap_or_else(|| format!("{}", id.0));
            // Escape quotes in labels
            let escaped = label.replace('"', "\\\"");
            out.push_str(&format!("    {} [label=\"{}\"];\n", id.0, escaped));
        }

        for id in &node_ids {
            if let Some(succs) = graph.edges.get(id) {
                let mut sorted = succs.clone();
                sorted.sort_by_key(|s| s.0);
                for succ in sorted {
                    out.push_str(&format!("    {} -> {};\n", id.0, succ.0));
                }
            }
        }

        out.push_str("}\n");
        out
    }

    /// Produce a simple adjacency-list text representation.
    #[must_use]
    pub fn to_adjacency_list(graph: &SimpleGraph) -> String {
        let mut out = String::new();
        let mut ids = graph.node_ids();
        ids.sort_by_key(|id| id.0);
        for id in ids {
            let label = graph
                .labels
                .get(&id)
                .cloned()
                .unwrap_or_else(|| format!("{}", id.0));
            let succs = graph.edges.get(&id).cloned().unwrap_or_default();
            let succ_str: Vec<String> = succs.iter().map(|s| format!("{}", s.0)).collect();
            out.push_str(&format!("{} ({}): {}\n", id.0, label, succ_str.join(", ")));
        }
        out
    }
}

// ─── GraphStatsSnapshot ──────────────────────────────────────────────────────

/// A snapshot of graph structural statistics.
#[derive(Debug, Clone)]
pub struct GraphStatsSnapshot {
    /// Number of nodes.
    pub node_count: usize,
    /// Number of directed edges.
    pub edge_count: usize,
    /// Maximum depth (longest path from any source).
    pub max_depth: usize,
}

/// Measures structural statistics of a graph.
pub struct GraphStats;

impl GraphStats {
    /// Measure node count, edge count, and max depth.
    ///
    /// Max depth is computed via BFS from all source nodes (in-degree 0).
    #[must_use]
    pub fn measure(graph: &SimpleGraph) -> GraphStatsSnapshot {
        let node_count = graph.node_count();
        let edge_count = graph.edge_count();
        let max_depth = Self::compute_max_depth(graph);
        GraphStatsSnapshot {
            node_count,
            edge_count,
            max_depth,
        }
    }

    fn compute_max_depth(graph: &SimpleGraph) -> usize {
        if graph.edges.is_empty() {
            return 0;
        }

        // Build in-degree map
        let mut in_degree: HashMap<NodeId, usize> = graph.edges.keys().map(|&k| (k, 0)).collect();
        for succs in graph.edges.values() {
            for &s in succs {
                *in_degree.entry(s).or_insert(0) += 1;
            }
        }

        // BFS depth propagation
        let mut depth: HashMap<NodeId, usize> = HashMap::new();
        let mut queue: VecDeque<NodeId> = in_degree
            .iter()
            .filter(|(_, &d)| d == 0)
            .map(|(&id, _)| id)
            .collect();
        for &id in &queue {
            depth.insert(id, 0);
        }

        let mut max_d = 0;
        // Use topological BFS
        let mut local_in_degree = in_degree.clone();
        while let Some(node) = queue.pop_front() {
            let cur = *depth.get(&node).unwrap_or(&0);
            if let Some(succs) = graph.edges.get(&node) {
                for &succ in succs {
                    let new_d = cur + 1;
                    let entry = depth.entry(succ).or_insert(0);
                    if new_d > *entry {
                        *entry = new_d;
                        if new_d > max_d {
                            max_d = new_d;
                        }
                    }
                    if let Some(d) = local_in_degree.get_mut(&succ) {
                        *d = d.saturating_sub(1);
                        if *d == 0 {
                            queue.push_back(succ);
                        }
                    }
                }
            }
        }

        max_d
    }
}

// ─── MultiInputNode ───────────────────────────────────────────────────────────

/// A node with a configurable number of inputs and outputs.
///
/// Used for fan-in topologies where multiple upstream outputs are combined.
pub struct MultiInputNode {
    id: NodeId,
    name: String,
    state: NodeState,
    inputs: Vec<InputPort>,
    outputs: Vec<OutputPort>,
}

impl MultiInputNode {
    /// Create a new multi-input node.
    ///
    /// All ports are typed as `Any` (video or audio).
    #[must_use]
    pub fn new(inputs: u32, outputs: u32, name: impl Into<String>) -> Self {
        let name = name.into();
        let input_ports = (0..inputs)
            .map(|i| InputPort::new(PortId(i), &format!("input_{i}"), PortType::Video))
            .collect();
        let output_ports = (0..outputs)
            .map(|i| OutputPort::new(PortId(i), &format!("output_{i}"), PortType::Video))
            .collect();
        Self {
            id: NodeId(0),
            name,
            state: NodeState::Idle,
            inputs: input_ports,
            outputs: output_ports,
        }
    }

    /// Set the node ID.
    #[must_use]
    pub fn with_id(mut self, id: NodeId) -> Self {
        self.id = id;
        self
    }

    /// Return the number of input ports.
    #[must_use]
    pub fn input_count(&self) -> usize {
        self.inputs.len()
    }

    /// Return the number of output ports.
    #[must_use]
    pub fn output_count(&self) -> usize {
        self.outputs.len()
    }
}

impl Node for MultiInputNode {
    fn id(&self) -> NodeId {
        self.id
    }
    fn name(&self) -> &str {
        &self.name
    }
    fn node_type(&self) -> NodeType {
        NodeType::Filter
    }
    fn state(&self) -> NodeState {
        self.state
    }

    fn set_state(&mut self, state: NodeState) -> GraphResult<()> {
        self.state = state;
        Ok(())
    }

    fn inputs(&self) -> &[InputPort] {
        &self.inputs
    }
    fn outputs(&self) -> &[OutputPort] {
        &self.outputs
    }

    fn process(&mut self, input: Option<FilterFrame>) -> GraphResult<Option<FilterFrame>> {
        // Pass-through: forward the first available input unchanged
        Ok(input)
    }

    fn reset(&mut self) -> GraphResult<()> {
        self.state = NodeState::Idle;
        Ok(())
    }
}

/// Connect multiple source nodes to a single target node's inputs.
///
/// Returns an error if `sources.len()` exceeds the target's input port count.
pub fn connect_fan_in(
    graph: &mut SimpleGraph,
    sources: &[NodeId],
    target: NodeId,
) -> GraphResult<()> {
    for &src in sources {
        if !graph.edges.contains_key(&src) {
            return Err(GraphError::NodeNotFound(src));
        }
        graph.edges.entry(src).or_default().push(target);
    }
    graph.edges.entry(target).or_default();
    Ok(())
}

// ─── ConditionalRouter ────────────────────────────────────────────────────────

/// A filter node that routes frames to one of two output ports based on a
/// predicate function applied to each incoming frame.
///
/// - Output port 0: condition is `true`
/// - Output port 1: condition is `false`
pub struct ConditionalRouter {
    id: NodeId,
    name: String,
    state: NodeState,
    condition: Box<dyn Fn(&FilterFrame) -> bool + Send + Sync>,
    /// Most recently routed output (0 = true branch, 1 = false branch).
    last_route: Option<u32>,
    inputs: Vec<InputPort>,
    outputs: Vec<OutputPort>,
}

impl ConditionalRouter {
    /// Create a new conditional router with the given predicate.
    ///
    /// The predicate receives a shared reference to the frame and returns
    /// `true` to route to output 0 or `false` to route to output 1.
    pub fn new(condition: Box<dyn Fn(&FilterFrame) -> bool + Send + Sync>) -> Self {
        Self {
            id: NodeId(0),
            name: "conditional_router".to_string(),
            state: NodeState::Idle,
            condition,
            last_route: None,
            inputs: vec![InputPort::new(PortId(0), "input", PortType::Video)],
            outputs: vec![
                OutputPort::new(PortId(0), "true_output", PortType::Video),
                OutputPort::new(PortId(1), "false_output", PortType::Video),
            ],
        }
    }

    /// Set the node ID.
    #[must_use]
    pub fn with_id(mut self, id: NodeId) -> Self {
        self.id = id;
        self
    }

    /// Return which output port the last frame was routed to.
    #[must_use]
    pub fn last_route(&self) -> Option<u32> {
        self.last_route
    }

    /// Evaluate the condition and return the output port index (0 or 1).
    #[must_use]
    pub fn route(&self, frame: &FilterFrame) -> u32 {
        if (self.condition)(frame) {
            0
        } else {
            1
        }
    }
}

impl Node for ConditionalRouter {
    fn id(&self) -> NodeId {
        self.id
    }
    fn name(&self) -> &str {
        &self.name
    }
    fn node_type(&self) -> NodeType {
        NodeType::Filter
    }
    fn state(&self) -> NodeState {
        self.state
    }

    fn set_state(&mut self, state: NodeState) -> GraphResult<()> {
        self.state = state;
        Ok(())
    }

    fn inputs(&self) -> &[InputPort] {
        &self.inputs
    }
    fn outputs(&self) -> &[OutputPort] {
        &self.outputs
    }

    fn process(&mut self, input: Option<FilterFrame>) -> GraphResult<Option<FilterFrame>> {
        match input {
            Some(frame) => {
                self.last_route = Some(self.route(&frame));
                Ok(Some(frame))
            }
            None => Ok(None),
        }
    }

    fn reset(&mut self) -> GraphResult<()> {
        self.last_route = None;
        self.state = NodeState::Idle;
        Ok(())
    }
}

// ─── GainNode ─────────────────────────────────────────────────────────────────

/// An audio gain node that scales sample amplitude by a dB value.
///
/// `gain_db` of 0 dB = unity gain; +6 dB ≈ 2×; −6 dB ≈ 0.5×.
pub struct GainNode {
    id: NodeId,
    name: String,
    state: NodeState,
    /// Gain in dB.
    gain_db: f32,
    /// Precomputed linear multiplier: `10^(gain_db / 20)`.
    linear_gain: f32,
    inputs: Vec<InputPort>,
    outputs: Vec<OutputPort>,
}

impl GainNode {
    /// Create a new gain node with the specified dB gain.
    #[must_use]
    pub fn new(gain_db: f32) -> Self {
        let linear_gain = 10.0_f32.powf(gain_db / 20.0);
        let audio_fmt = PortFormat::Audio(AudioPortFormat::any());
        Self {
            id: NodeId(0),
            name: "gain".to_string(),
            state: NodeState::Idle,
            gain_db,
            linear_gain,
            inputs: vec![
                InputPort::new(PortId(0), "input", PortType::Audio).with_format(audio_fmt.clone())
            ],
            outputs: vec![
                OutputPort::new(PortId(0), "output", PortType::Audio).with_format(audio_fmt)
            ],
        }
    }

    /// Set the node ID.
    #[must_use]
    pub fn with_id(mut self, id: NodeId) -> Self {
        self.id = id;
        self
    }

    /// Return the gain in dB.
    #[must_use]
    pub fn gain_db(&self) -> f32 {
        self.gain_db
    }

    /// Return the linear gain multiplier.
    #[must_use]
    pub fn linear_gain(&self) -> f32 {
        self.linear_gain
    }

    /// Apply gain to an audio frame, returning a new frame.
    #[must_use]
    pub fn process_frame(&self, frame: &AudioFrame) -> AudioFrame {
        let channels = frame.channels.count();
        let sample_count = frame.sample_count();

        if sample_count == 0 || channels == 0 {
            return frame.clone();
        }

        match &frame.samples {
            AudioBuffer::Interleaved(data) => {
                let bytes_per_sample = frame.format.bytes_per_sample();
                if bytes_per_sample == 0 {
                    return frame.clone();
                }

                let total_samples = data.len() / bytes_per_sample;
                let mut out = Vec::with_capacity(data.len());

                for i in 0..total_samples {
                    let offset = i * bytes_per_sample;
                    if offset + bytes_per_sample > data.len() {
                        break;
                    }
                    let scaled = Self::scale_sample(
                        &data[offset..offset + bytes_per_sample],
                        frame.format,
                        self.linear_gain,
                    );
                    out.extend_from_slice(&scaled);
                }

                let mut output_frame =
                    AudioFrame::new(frame.format, frame.sample_rate, frame.channels.clone());
                output_frame.samples = AudioBuffer::Interleaved(bytes::Bytes::from(out));
                output_frame
            }
            AudioBuffer::Planar(planes) => {
                let bytes_per_sample = frame.format.bytes_per_sample();
                if bytes_per_sample == 0 {
                    return frame.clone();
                }

                let scaled_planes: Vec<bytes::Bytes> = planes
                    .iter()
                    .map(|plane| {
                        let total = plane.len() / bytes_per_sample;
                        let mut out = Vec::with_capacity(plane.len());
                        for i in 0..total {
                            let offset = i * bytes_per_sample;
                            if offset + bytes_per_sample > plane.len() {
                                break;
                            }
                            let scaled = Self::scale_sample(
                                &plane[offset..offset + bytes_per_sample],
                                frame.format,
                                self.linear_gain,
                            );
                            out.extend_from_slice(&scaled);
                        }
                        bytes::Bytes::from(out)
                    })
                    .collect();

                let mut output_frame =
                    AudioFrame::new(frame.format, frame.sample_rate, frame.channels.clone());
                output_frame.samples = AudioBuffer::Planar(scaled_planes);
                output_frame
            }
        }
    }

    /// Scale a single sample byte slice by `linear_gain`.
    fn scale_sample(bytes: &[u8], format: SampleFormat, gain: f32) -> Vec<u8> {
        match format {
            SampleFormat::F32 => {
                if bytes.len() < 4 {
                    return bytes.to_vec();
                }
                let v = f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
                let scaled = (v * gain).clamp(-1.0, 1.0);
                scaled.to_le_bytes().to_vec()
            }
            SampleFormat::S16 => {
                if bytes.len() < 2 {
                    return bytes.to_vec();
                }
                let v = i16::from_le_bytes([bytes[0], bytes[1]]);
                let scaled = ((v as f32) * gain).clamp(i16::MIN as f32, i16::MAX as f32) as i16;
                scaled.to_le_bytes().to_vec()
            }
            SampleFormat::S32 => {
                if bytes.len() < 4 {
                    return bytes.to_vec();
                }
                let v = i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
                let scaled =
                    ((v as f64) * gain as f64).clamp(i32::MIN as f64, i32::MAX as f64) as i32;
                scaled.to_le_bytes().to_vec()
            }
            SampleFormat::U8 => {
                if bytes.is_empty() {
                    return bytes.to_vec();
                }
                // Map [0,255] → [-1,1], scale, map back
                let v = (bytes[0] as f32 - 128.0) / 128.0;
                let scaled = (v * gain).clamp(-1.0, 1.0);
                let out = ((scaled * 128.0) + 128.0).clamp(0.0, 255.0) as u8;
                vec![out]
            }
            _ => bytes.to_vec(),
        }
    }
}

impl Node for GainNode {
    fn id(&self) -> NodeId {
        self.id
    }
    fn name(&self) -> &str {
        &self.name
    }
    fn node_type(&self) -> NodeType {
        NodeType::Filter
    }
    fn state(&self) -> NodeState {
        self.state
    }

    fn set_state(&mut self, state: NodeState) -> GraphResult<()> {
        self.state = state;
        Ok(())
    }

    fn inputs(&self) -> &[InputPort] {
        &self.inputs
    }
    fn outputs(&self) -> &[OutputPort] {
        &self.outputs
    }

    fn process(&mut self, input: Option<FilterFrame>) -> GraphResult<Option<FilterFrame>> {
        match input {
            Some(FilterFrame::Audio(audio_frame)) => {
                let output = self.process_frame(&audio_frame);
                Ok(Some(FilterFrame::Audio(output)))
            }
            Some(other) => Ok(Some(other)), // pass video frames through unchanged
            None => Ok(None),
        }
    }

    fn reset(&mut self) -> GraphResult<()> {
        self.state = NodeState::Idle;
        Ok(())
    }
}

// ─── CropNode ────────────────────────────────────────────────────────────────

/// A simple crop-region descriptor for use with the evaluator layer.
///
/// Note: the full `CropFilter` in `filters::video::crop` provides a complete
/// `Node` implementation. This struct is a thin wrapper for the evaluator API.
#[derive(Debug, Clone, Copy)]
pub struct CropRegion {
    /// Left pixel offset.
    pub x: u32,
    /// Top pixel offset.
    pub y: u32,
    /// Output width.
    pub w: u32,
    /// Output height.
    pub h: u32,
}

impl CropRegion {
    /// Create a new crop region.
    #[must_use]
    pub fn new(x: u32, y: u32, w: u32, h: u32) -> Self {
        Self { x, y, w, h }
    }

    /// Crop a raw RGBA/RGB pixel buffer (packed, row-major).
    ///
    /// `src_w` is the original image width in pixels.
    /// `channels` is bytes per pixel (e.g. 4 for RGBA).
    #[must_use]
    pub fn crop_buffer(&self, data: &[u8], src_w: u32, channels: u32) -> Vec<u8> {
        let stride = (src_w * channels) as usize;
        let row_bytes = (self.w * channels) as usize;
        let mut out = Vec::with_capacity(row_bytes * self.h as usize);

        for row in self.y..self.y + self.h {
            let row_start = row as usize * stride + (self.x * channels) as usize;
            let row_end = row_start + row_bytes;
            if row_end <= data.len() {
                out.extend_from_slice(&data[row_start..row_end]);
            }
        }

        out
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    fn make_chain() -> SimpleGraph {
        let mut g = SimpleGraph::new();
        g.add_node(NodeId(0), "A");
        g.add_node(NodeId(1), "B");
        g.add_node(NodeId(2), "C");
        g.add_edge(NodeId(0), NodeId(1));
        g.add_edge(NodeId(1), NodeId(2));
        g
    }

    // ── GraphEvaluator ──

    #[test]
    fn test_topological_sort_linear_chain() {
        let g = make_chain();
        let order = GraphEvaluator::topological_sort(&g).expect("sort should succeed");
        assert_eq!(order, vec![NodeId(0), NodeId(1), NodeId(2)]);
    }

    #[test]
    fn test_topological_sort_cycle_returns_error() {
        let mut g = SimpleGraph::new();
        g.add_edge(NodeId(0), NodeId(0)); // self-loop
        let result = GraphEvaluator::topological_sort(&g);
        assert!(result.is_err());
    }

    #[test]
    fn test_topological_sort_diamond() {
        let mut g = SimpleGraph::new();
        g.add_edge(NodeId(0), NodeId(1));
        g.add_edge(NodeId(0), NodeId(2));
        g.add_edge(NodeId(1), NodeId(3));
        g.add_edge(NodeId(2), NodeId(3));
        let order = GraphEvaluator::topological_sort(&g).expect("sort should succeed");
        assert_eq!(order[0], NodeId(0));
        assert_eq!(*order.last().expect("last"), NodeId(3));
    }

    // ── GraphValidator ──

    #[test]
    fn test_has_cycle_self_loop() {
        let mut g = SimpleGraph::new();
        g.add_edge(NodeId(5), NodeId(5));
        assert!(GraphValidator::has_cycle(&g));
    }

    #[test]
    fn test_has_cycle_dag() {
        let g = make_chain();
        assert!(!GraphValidator::has_cycle(&g));
    }

    #[test]
    fn test_has_cycle_3_node_cycle() {
        let mut g = SimpleGraph::new();
        g.add_edge(NodeId(0), NodeId(1));
        g.add_edge(NodeId(1), NodeId(2));
        g.add_edge(NodeId(2), NodeId(0));
        assert!(GraphValidator::has_cycle(&g));
    }

    // ── GraphSerializer ──

    #[test]
    fn test_to_dot_contains_digraph() {
        let g = make_chain();
        let dot = GraphSerializer::to_dot(&g);
        assert!(dot.contains("digraph"), "DOT output must contain 'digraph'");
    }

    #[test]
    fn test_to_dot_contains_nodes() {
        let g = make_chain();
        let dot = GraphSerializer::to_dot(&g);
        assert!(dot.contains("label=\"A\""));
        assert!(dot.contains("label=\"B\""));
        assert!(dot.contains("label=\"C\""));
    }

    #[test]
    fn test_to_dot_contains_edges() {
        let g = make_chain();
        let dot = GraphSerializer::to_dot(&g);
        assert!(dot.contains("->"));
    }

    // ── GraphStats ──

    #[test]
    fn test_stats_measure_chain() {
        let g = make_chain();
        let snap = GraphStats::measure(&g);
        assert_eq!(snap.node_count, 3);
        assert_eq!(snap.edge_count, 2);
        assert_eq!(snap.max_depth, 2);
    }

    #[test]
    fn test_stats_measure_empty() {
        let g = SimpleGraph::new();
        let snap = GraphStats::measure(&g);
        assert_eq!(snap.node_count, 0);
        assert_eq!(snap.edge_count, 0);
        assert_eq!(snap.max_depth, 0);
    }

    // ── MultiInputNode ──

    #[test]
    fn test_multi_input_node_creation() {
        let n = MultiInputNode::new(3, 1, "fan_in");
        assert_eq!(n.input_count(), 3);
        assert_eq!(n.output_count(), 1);
        assert_eq!(n.name(), "fan_in");
    }

    #[test]
    fn test_connect_fan_in() {
        let mut g = SimpleGraph::new();
        g.add_node(NodeId(0), "src_a");
        g.add_node(NodeId(1), "src_b");
        g.add_node(NodeId(2), "mixer");
        let result = connect_fan_in(&mut g, &[NodeId(0), NodeId(1)], NodeId(2));
        assert!(result.is_ok());
        assert!(g.edges[&NodeId(0)].contains(&NodeId(2)));
        assert!(g.edges[&NodeId(1)].contains(&NodeId(2)));
    }

    // ── ConditionalRouter ──

    #[test]
    fn test_conditional_router_true_branch() {
        let router = ConditionalRouter::new(Box::new(|frame| frame.is_video()));
        let video = VideoFrame::new(PixelFormat::Yuv420p, 100, 100);
        let frame = FilterFrame::Video(video);
        assert_eq!(router.route(&frame), 0); // true → port 0
    }

    #[test]
    fn test_conditional_router_false_branch() {
        let router = ConditionalRouter::new(Box::new(|frame| frame.is_video()));
        let audio = AudioFrame::new(SampleFormat::F32, 48000, ChannelLayout::Stereo);
        let frame = FilterFrame::Audio(audio);
        assert_eq!(router.route(&frame), 1); // false → port 1
    }

    // ── GainNode ──

    #[test]
    fn test_gain_node_unity_gain() {
        let g = GainNode::new(0.0);
        assert!((g.linear_gain() - 1.0).abs() < 1e-5);
    }

    #[test]
    fn test_gain_node_6db() {
        let g = GainNode::new(6.0206);
        // 10^(6.0206/20) ≈ 2.0
        assert!((g.linear_gain() - 2.0).abs() < 0.01);
    }

    #[test]
    fn test_gain_node_process_f32_sample() {
        use bytes::BytesMut;

        let gain = GainNode::new(6.0206); // ≈ 2×
        let mut frame = AudioFrame::new(SampleFormat::F32, 48000, ChannelLayout::Mono);
        let mut buf = BytesMut::new();
        buf.extend_from_slice(&0.25f32.to_le_bytes());
        frame.samples = AudioBuffer::Interleaved(buf.freeze());

        let out = gain.process_frame(&frame);
        if let AudioBuffer::Interleaved(data) = &out.samples {
            let v = f32::from_le_bytes([data[0], data[1], data[2], data[3]]);
            // 0.25 × 2 = 0.5
            assert!((v - 0.5).abs() < 0.05, "expected ~0.5, got {v}");
        }
    }

    // ── CropRegion ──

    #[test]
    fn test_crop_region_extracts_subregion() {
        // 4×4 RGBA image, each pixel = (row*10, col*10, 0, 255)
        let mut data = vec![0u8; 4 * 4 * 4];
        for row in 0..4u32 {
            for col in 0..4u32 {
                let idx = ((row * 4 + col) * 4) as usize;
                data[idx] = (row * 10) as u8;
                data[idx + 1] = (col * 10) as u8;
                data[idx + 2] = 0;
                data[idx + 3] = 255;
            }
        }

        let crop = CropRegion::new(1, 1, 2, 2);
        let result = crop.crop_buffer(&data, 4, 4);
        assert_eq!(result.len(), 2 * 2 * 4);
        // First pixel of cropped region: row=1, col=1 → (10, 10, 0, 255)
        assert_eq!(result[0], 10);
        assert_eq!(result[1], 10);
    }

    // ── EdgeId / GraphEditor ──

    #[test]
    fn test_graph_editor_insert_node_between() {
        let mut g = SimpleGraph::new();
        g.add_node(NodeId(0), "A");
        g.add_node(NodeId(2), "C");
        g.add_edge(NodeId(0), NodeId(2));

        let edge = EdgeId::new(NodeId(0), NodeId(2));
        // Insert B between A and C
        let result = GraphEditor::insert_node_between(&mut g, NodeId(1), "B", edge);
        assert!(
            result.is_ok(),
            "insert_node_between should succeed: {result:?}"
        );

        // A should now have B as successor (not C directly)
        assert!(
            g.edges[&NodeId(0)].contains(&NodeId(1)) || !g.edges[&NodeId(0)].contains(&NodeId(2))
        );
        // B should have C as successor
        assert!(g.edges[&NodeId(1)].contains(&NodeId(2)));
    }

    #[test]
    fn test_graph_editor_nonexistent_edge_returns_error() {
        let mut g = SimpleGraph::new();
        g.add_node(NodeId(0), "A");
        g.add_node(NodeId(1), "B");
        // No edge 0→1 yet
        let edge = EdgeId::new(NodeId(0), NodeId(1));
        let result = GraphEditor::insert_node_between(&mut g, NodeId(2), "C", edge);
        assert!(result.is_err());
    }
}