Skip to main content

fc_ui/capabilities/media/
waveform.rs

1//! Audio waveform visualization using vertical bars.
2
3use gpui::{prelude::FluentBuilder as _, *};
4
5struct WaveformPaintData {
6    data: Vec<f32>,
7    bar_width: f32,
8    gap: f32,
9    color: Hsla,
10    active_color: Hsla,
11    playback_position: f32,
12}
13
14#[derive(IntoElement)]
15pub struct Waveform {
16    data: Vec<f32>,
17    bar_width: Pixels,
18    gap: Pixels,
19    color: Option<Hsla>,
20    active_color: Option<Hsla>,
21    playback_position: f32,
22    style: StyleRefinement,
23}
24
25impl Waveform {
26    pub fn new() -> Self {
27        Self {
28            data: Vec::new(),
29            bar_width: px(3.0),
30            gap: px(2.0),
31            color: None,
32            active_color: None,
33            playback_position: 0.0,
34            style: StyleRefinement::default(),
35        }
36    }
37
38    pub fn data(mut self, data: &[f32]) -> Self {
39        self.data = data.to_vec();
40        self
41    }
42
43    pub fn bar_width(mut self, width: Pixels) -> Self {
44        self.bar_width = width;
45        self
46    }
47
48    pub fn gap(mut self, gap: Pixels) -> Self {
49        self.gap = gap;
50        self
51    }
52
53    pub fn color(mut self, color: Hsla) -> Self {
54        self.color = Some(color);
55        self
56    }
57
58    pub fn active_color(mut self, color: Hsla) -> Self {
59        self.active_color = Some(color);
60        self
61    }
62
63    pub fn playback_position(mut self, position: f32) -> Self {
64        self.playback_position = position.clamp(0.0, 1.0);
65        self
66    }
67}
68
69impl Default for Waveform {
70    fn default() -> Self {
71        Self::new()
72    }
73}
74
75impl Styled for Waveform {
76    fn style(&mut self) -> &mut StyleRefinement {
77        &mut self.style
78    }
79}
80
81impl RenderOnce for Waveform {
82    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
83        let theme = crate::capabilities::foundation::theme::use_theme(cx);
84        let user_style = self.style;
85
86        let default_color = theme.tokens.muted_foreground.opacity(0.4);
87        let default_active = theme.tokens.primary;
88
89        let paint_data = WaveformPaintData {
90            data: self.data,
91            bar_width: self.bar_width / px(1.0),
92            gap: self.gap / px(1.0),
93            color: self.color.unwrap_or(default_color),
94            active_color: self.active_color.unwrap_or(default_active),
95            playback_position: self.playback_position,
96        };
97
98        div()
99            .relative()
100            .when(user_style.size.width.is_none(), |this| this.w_full())
101            .when(user_style.size.height.is_none(), |this| this.h(px(48.0)))
102            .child(
103                canvas(
104                    move |_bounds, _window, _cx| paint_data,
105                    move |bounds, data, window, _cx| {
106                        paint_waveform(bounds, &data, window);
107                    },
108                )
109                .absolute()
110                .inset_0()
111                .size_full(),
112            )
113            .map(|this| {
114                let mut el = this;
115                el.style().refine(&user_style);
116                el
117            })
118    }
119}
120
121fn paint_waveform(bounds: Bounds<Pixels>, data: &WaveformPaintData, window: &mut Window) {
122    if data.data.is_empty() || bounds.size.width <= px(0.0) || bounds.size.height <= px(0.0) {
123        return;
124    }
125
126    let bar_w = data.bar_width;
127    let gap_w = data.gap;
128    let step = bar_w + gap_w;
129
130    if step <= 0.0 {
131        return;
132    }
133
134    let available_width = bounds.size.width / px(1.0);
135    let max_bars = (available_width / step).floor() as usize;
136
137    if max_bars == 0 {
138        return;
139    }
140
141    let bar_count = max_bars.min(data.data.len());
142    let active_bar_boundary = (data.playback_position * bar_count as f32).floor() as usize;
143    let height_f = bounds.size.height / px(1.0);
144
145    for i in 0..bar_count {
146        let sample_idx = if bar_count < data.data.len() {
147            (i as f32 / bar_count as f32 * data.data.len() as f32) as usize
148        } else {
149            i
150        };
151
152        let amplitude = data
153            .data
154            .get(sample_idx)
155            .copied()
156            .unwrap_or(0.0)
157            .clamp(0.0, 1.0);
158        let bar_height = (amplitude * height_f).max(2.0);
159
160        let x = bounds.left() + px(i as f32 * step);
161        let y = bounds.top() + px((height_f - bar_height) * 0.5);
162
163        let bar_color = if i < active_bar_boundary {
164            data.active_color
165        } else {
166            data.color
167        };
168
169        window.paint_quad(PaintQuad {
170            bounds: Bounds {
171                origin: point(x, y),
172                size: gpui::size(px(bar_w), px(bar_height)),
173            },
174            corner_radii: Corners::all(px(bar_w * 0.5)),
175            background: bar_color.into(),
176            border_widths: Edges::default(),
177            border_color: transparent_black(),
178            border_style: BorderStyle::default(),
179            continuous_corners: false,
180            transform: Default::default(),
181            blend_mode: Default::default(),
182        });
183    }
184}