moosicbox_app_native 0.2.0

MoosicBox native App package
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
//! Real-time audio visualization for the native application.
//!
//! This module provides real-time waveform visualization for the currently playing track,
//! rendering animated audio waveforms on an HTML canvas. The visualization updates
//! periodically to show playback progress with a moving cursor.
//!
//! The module manages canvas dimensions, update intervals, and caches visualization data
//! for performance.

#![allow(clippy::module_name_repetitions)]

use std::{
    sync::{LazyLock, RwLock},
    time::{Duration, SystemTime},
};

use hyperchad::renderer::{
    Color,
    canvas::{self, CanvasAction, Pos},
};
use moosicbox_music_models::{ApiSource, id::Id};
use switchy::unsync::{futures::FutureExt, task::JoinHandle, util::CancellationToken};

use crate::STATE;

static INTERVAL_PERIOD: LazyLock<RwLock<Option<Duration>>> =
    LazyLock::new(|| RwLock::new(Some(Duration::from_millis(16))));
static DIMENSIONS: LazyLock<RwLock<(f32, f32)>> = LazyLock::new(|| RwLock::new((0.0, 0.0)));

/// Returns the current visualization canvas dimensions.
///
/// # Panics
///
/// * If the `DIMENSIONS` lock is poisoned
#[must_use]
pub fn get_dimensions() -> (f32, f32) {
    *DIMENSIONS.read().unwrap()
}

/// Sets the visualization canvas dimensions.
///
/// # Panics
///
/// * If the `DIMENSIONS` lock is poisoned
pub fn set_dimensions(width: f32, height: f32) {
    *DIMENSIONS.write().unwrap() = (width, height);
}

/// Sets the visualization update interval period.
///
/// # Panics
///
/// * If the `INTERVAL_PERIOD` lock is poisoned
pub fn set_interval_period(period: Duration) {
    *INTERVAL_PERIOD.write().unwrap() = Some(period);
}

/// Disables the visualization update interval.
///
/// # Panics
///
/// * If the `INTERVAL_PERIOD` lock is poisoned
pub fn disable_interval() {
    *INTERVAL_PERIOD.write().unwrap() = None;
}

/// Represents the currently playing track for visualization purposes.
///
/// This struct holds the information needed to render and update the audio waveform
/// visualization, including the track's identifier, playback position, and timing
/// information for calculating the cursor position.
#[derive(Debug, Clone)]
pub struct CurrentTrack {
    /// Unique identifier for the track.
    #[allow(unused)]
    id: Id,
    /// The API source the track belongs to (e.g., Library, Tidal, Qobuz).
    #[allow(unused)]
    api_source: ApiSource,
    /// Current playback position in seconds.
    #[allow(unused)]
    seek: f64,
    /// Total track duration in seconds.
    #[allow(unused)]
    duration: f64,
    /// Timestamp when the playback state was captured, used for calculating elapsed time.
    #[allow(unused)]
    time: SystemTime,
}

static PREV_CURSOR_X: LazyLock<RwLock<Option<f32>>> = LazyLock::new(|| RwLock::new(None));
static CURRENT_TRACK: LazyLock<RwLock<Option<CurrentTrack>>> = LazyLock::new(|| RwLock::new(None));
static INTERVAL: LazyLock<RwLock<Option<JoinHandle<()>>>> = LazyLock::new(|| RwLock::new(None));
static CANCEL_INTERVAL: LazyLock<RwLock<CancellationToken>> =
    LazyLock::new(|| RwLock::new(CancellationToken::new()));
static CURRENT_STROKE_COLOR: LazyLock<RwLock<Color>> = LazyLock::new(|| RwLock::new(Color::BLACK));

fn stroke_color(color: Color, canvas_actions: &mut Vec<CanvasAction>) {
    let current_color = *CURRENT_STROKE_COLOR.read().unwrap();
    if current_color != color {
        let len = canvas_actions.len();
        // compress stroke color actions
        for i in 1..=len {
            if canvas_actions[len - i].is_draw_action() {
                break;
            }
            if matches!(canvas_actions[len - i], CanvasAction::StrokeColor { .. }) {
                canvas_actions.remove(len - i);
            }
        }
        *CURRENT_STROKE_COLOR.write().unwrap() = color;
        canvas_actions.push(canvas::CanvasAction::StrokeColor(color));
    }
}

#[allow(clippy::too_many_arguments)]
async fn visualization_updated(
    cursor_width: f32,
    cursor_height: f32,
    bar_width: f32,
    bar_height: f32,
    gap: f32,
    visualization_width: f32,
    visualization_height: f32,
    duration: f32,
    prev_cursor_x: Option<f32>,
    last_update: SystemTime,
    progress_percent: f32,
    visualization: &[u8],
) {
    use crate::RENDERER;

    static BUFFER_WIDTH: f32 = 2.0f32;

    log::trace!("visualization_updated");

    let mut canvas_actions = if prev_cursor_x.is_some() {
        Vec::with_capacity(1)
    } else {
        Vec::with_capacity(visualization.len())
    };

    let cursor_half_width = cursor_width / 2.0;
    let step_1_second = visualization_width / duration;
    let delta = switchy::time::now()
        .duration_since(last_update)
        .unwrap()
        .as_secs_f32()
        * step_1_second;
    let cursor_x = visualization_width.mul_add(progress_percent, -cursor_half_width) + delta;
    let bar_y_offset = (visualization_height - bar_height) / 2.0;

    let clear_buffer = cursor_half_width + BUFFER_WIDTH;
    let left_cursor = prev_cursor_x.map(|x| if x < cursor_x { x } else { cursor_x });
    let right_cursor = prev_cursor_x.map_or(cursor_x, |x| if x > cursor_x { x } else { cursor_x });
    let clear_buffer_left = left_cursor.map(|x| x - clear_buffer);
    let clear_buffer_right = right_cursor + clear_buffer;

    if let Some(left) = clear_buffer_left {
        canvas_actions.push(canvas::CanvasAction::ClearRect(
            Pos(left, 0.0),
            Pos(clear_buffer_right, visualization_height),
        ));
    } else {
        canvas_actions.push(canvas::CanvasAction::Clear);
    }

    stroke_color(Color::from_hex("222"), &mut canvas_actions);

    let mut past = true;

    for (i, point) in visualization.iter().enumerate() {
        #[allow(clippy::cast_precision_loss)]
        let x = (i as f32) * (bar_width + gap);

        if let Some(left) = clear_buffer_left {
            if x + bar_width + gap < left {
                continue;
            }
            if x > clear_buffer_right {
                break;
            }
        }

        let height = f32::from(*point);
        let height = (height / 255.0) * bar_height;
        let height = if height < 2.0 { 2.0 } else { height };
        let y = (bar_height - height) / 2.0 + bar_y_offset;

        if past && x >= cursor_x {
            past = false;

            stroke_color(Color::WHITE, &mut canvas_actions);
        }

        canvas_actions.push(canvas::CanvasAction::FillRect(
            Pos(x, y),
            Pos(x + bar_width, y + height),
        ));
    }

    // draw cursor
    {
        let cursor_y_offset = (visualization_height - cursor_height) / 2.0;
        let x = cursor_x;
        let y = cursor_y_offset;
        let height = cursor_height;
        stroke_color(Color::WHITE, &mut canvas_actions);
        canvas_actions.push(canvas::CanvasAction::FillRect(
            Pos(x, y),
            Pos(x + cursor_width, y + height),
        ));
    }

    PREV_CURSOR_X.write().unwrap().replace(cursor_x);

    let view = canvas::CanvasUpdate {
        target: "visualization".to_string(),
        canvas_actions,
    };
    let response = RENDERER.get().unwrap().render_canvas(view).await;
    if let Err(e) = response {
        log::error!("Failed to render_canvas: {e:?}");
    }
}

async fn clear_canvas() {
    use hyperchad::renderer::canvas;

    use crate::RENDERER;

    let view = canvas::CanvasUpdate {
        target: "visualization".to_string(),
        canvas_actions: vec![canvas::CanvasAction::Clear],
    };
    let response = RENDERER.get().unwrap().render_canvas(view).await;
    if let Err(e) = response {
        log::error!("Failed to render_canvas: {e:?}");
    }
}

async fn update_visualization(
    visualization_width: f32,
    visualization_height: f32,
    track: CurrentTrack,
) {
    use std::{collections::BTreeMap, sync::Arc};

    use switchy::unsync::sync::RwLock;

    static CURSOR_WIDTH: f32 = 2.0;
    static BAR_WIDTH: f32 = 1.0;
    static GAP: f32 = 2.0;

    static CACHE: LazyLock<RwLock<BTreeMap<String, Arc<[u8]>>>> =
        LazyLock::new(|| RwLock::new(BTreeMap::new()));

    let track_id = track.id;
    let api_source = track.api_source;
    let seek = track.seek;
    let duration = track.duration;
    let last_update = track.time;
    let prev_cursor_x = *PREV_CURSOR_X.read().unwrap();
    let bar_height = visualization_height - 5.0;
    let cursor_height = visualization_height;

    #[allow(clippy::cast_possible_truncation)]
    let progress_percent = (seek / duration) as f32;
    #[allow(clippy::cast_possible_truncation)]
    let duration = duration as f32;

    log::trace!(
        "update_visualization: track_id={track_id} api_source={api_source} seek={seek} visualization_width={visualization_width} visualization_height={visualization_height}"
    );

    let key = format!("{api_source}|{track_id}|{visualization_width}|{visualization_height}");

    let mut binding = CACHE.write().await;
    if let Some(data) = binding.get(&key) {
        visualization_updated(
            CURSOR_WIDTH,
            cursor_height,
            BAR_WIDTH,
            bar_height,
            GAP,
            visualization_width,
            visualization_height,
            duration,
            prev_cursor_x,
            last_update,
            progress_percent,
            data,
        )
        .await;
        return;
    }

    clear_canvas().await;

    *PREV_CURSOR_X.write().unwrap() = None;
    let prev_cursor_x = None;

    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    let max = (visualization_width / (BAR_WIDTH + GAP)).round() as usize;

    let resp = STATE
        .api_proxy_get(
            format!("files/track/visualization?trackId={track_id}&source={api_source}&max={max}"),
            None,
        )
        .await;
    let Ok(value) = resp else {
        moosicbox_assert::die_or_error!("Failed to get visualization: {:?}", resp.err().unwrap());
        return;
    };

    let buf: Result<Arc<[u8]>, _> = serde_json::from_value(value);
    let Ok(buf) = buf else {
        moosicbox_assert::die_or_error!(
            "Failed to get visualization data from response: {:?}",
            buf.err().unwrap()
        );
        return;
    };

    binding.insert(key, buf.clone());

    drop(binding);

    visualization_updated(
        CURSOR_WIDTH,
        cursor_height,
        BAR_WIDTH,
        bar_height,
        GAP,
        visualization_width,
        visualization_height,
        duration,
        prev_cursor_x,
        last_update,
        progress_percent,
        &buf,
    )
    .await;
}

async fn tick_visualization() {
    let Some(current_track) = CURRENT_TRACK.read().unwrap().clone() else {
        moosicbox_assert::die_or_panic!("Current track not set");
    };
    let (visualization_width, visualization_height) = get_dimensions();

    update_visualization(visualization_width, visualization_height, current_track).await;
}

/// Checks and updates the visualization based on the current playback state.
///
/// # Panics
///
/// * If the `CURRENT_TRACK` lock is poisoned
pub async fn check_visualization_update() {
    let session = STATE.get_current_session_ref().await;
    if let Some(session) = session {
        if let Some(position) = session.position
            && let Some(track) = session.playlist.tracks.get(position as usize)
        {
            let track_id = track.track_id.clone();
            let duration = track.duration;
            let api_source = track.api_source.clone();
            let seek = session.seek.unwrap_or_default();
            let playing = session.playing;
            drop(session);
            CURRENT_TRACK.write().unwrap().replace(CurrentTrack {
                id: track_id,
                api_source,
                seek,
                duration,
                time: switchy::time::now(),
            });

            if let Some(interval_period) = { *INTERVAL_PERIOD.read().unwrap() } {
                let mut interval = INTERVAL.write().unwrap();
                let mut cancel_interval = CANCEL_INTERVAL.write().unwrap();
                if playing && !interval.is_some() {
                    cancel_interval.cancel();
                    let token = CancellationToken::new();
                    *cancel_interval = token.clone();
                    drop(cancel_interval);
                    interval.replace(switchy::unsync::task::spawn(async move {
                        let mut interval = switchy::unsync::time::interval(interval_period);

                        while !token.is_cancelled() {
                            switchy::unsync::select! {
                                _ = interval.tick() => {}
                                () = token.cancelled().fuse() => {
                                    break;
                                }
                            };
                            tick_visualization().await;
                        }
                    }));
                } else {
                    if !playing && interval.is_some() {
                        interval.take();
                        cancel_interval.cancel();
                    }
                    drop(cancel_interval);
                }

                drop(interval);
            }

            tick_visualization().await;
        }
    } else {
        drop(session);
    }
}