madamiru 0.6.0

Dynamic multi-multimedia player
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
use std::collections::{BTreeSet, HashMap, HashSet};

use itertools::Itertools;

use crate::{lang, path::StrictPath};

mod placeholder {
    pub const PLAYLIST: &str = "<playlist>";
}

pub fn fill_placeholders_in_path(path: &StrictPath, playlist: Option<&StrictPath>) -> StrictPath {
    let playlist = playlist
        .and_then(|x| x.parent_if_file().ok())
        .unwrap_or_else(StrictPath::cwd);
    path.replace_raw_prefix(placeholder::PLAYLIST, playlist.raw_ref())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RefreshContext {
    Launch,
    Edit,
    Playlist,
    Automatic,
    Manual,
}

#[derive(
    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum Source {
    Path { path: StrictPath },
    Glob { pattern: String },
}

impl Source {
    pub fn new_path(path: StrictPath) -> Self {
        Self::Path { path }
    }

    pub fn new_glob(pattern: String) -> Self {
        Self::Glob { pattern }
    }

    pub fn kind(&self) -> SourceKind {
        match self {
            Self::Path { .. } => SourceKind::Path,
            Self::Glob { .. } => SourceKind::Glob,
        }
    }

    pub fn set_kind(&mut self, kind: SourceKind) {
        let raw = self.raw();

        match kind {
            SourceKind::Path => {
                *self = Self::new_path(StrictPath::new(raw));
            }
            SourceKind::Glob => {
                *self = Self::new_glob(raw.to_string());
            }
        }
    }

    pub fn path(&self) -> Option<&StrictPath> {
        match self {
            Self::Path { path } => Some(path),
            Self::Glob { .. } => None,
        }
    }

    pub fn is_empty(&self) -> bool {
        match self {
            Self::Path { path } => path.raw_ref().trim().is_empty(),
            Self::Glob { pattern } => pattern.trim().is_empty(),
        }
    }

    pub fn raw(&self) -> &str {
        match self {
            Self::Path { path } => path.raw_ref(),
            Self::Glob { pattern } => pattern,
        }
    }

    pub fn reset(&mut self, raw: String) {
        match self {
            Self::Path { path } => {
                path.reset(raw);
            }
            Self::Glob { pattern } => {
                *pattern = raw;
            }
        }
    }

    pub fn fill_placeholders(&self, playlist: &StrictPath) -> Self {
        match self {
            Self::Path { path } => Self::Path {
                path: fill_placeholders_in_path(path, Some(playlist)),
            },
            Self::Glob { pattern } => Self::Glob {
                pattern: match pattern.strip_prefix(placeholder::PLAYLIST) {
                    Some(suffix) => format!("{}{}", playlist.render(), suffix),
                    None => pattern.clone(),
                },
            },
        }
    }

    pub fn has_playlist_placeholder(&self) -> bool {
        self.raw().contains(placeholder::PLAYLIST)
    }
}

impl Default for Source {
    fn default() -> Self {
        Self::Path {
            path: Default::default(),
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SourceKind {
    #[default]
    Path,
    Glob,
}

impl SourceKind {
    pub const ALL: &'static [Self] = &[Self::Path, Self::Glob];
}

impl ToString for SourceKind {
    fn to_string(&self) -> String {
        match self {
            Self::Path => lang::thing::path(),
            Self::Glob => lang::thing::glob(),
        }
    }
}

#[derive(Debug)]
enum Mime {
    /// From the `infer` crate.
    /// Based on magic bytes without system dependencies, but not exhaustive.
    Pure(&'static str),
    /// From the `tree_magic_mini` crate.
    /// Uses the system's shared database on Linux and Mac,
    /// but not viable for Windows without bundling GPL data.
    #[allow(unused)]
    Database(&'static str),
    /// From the `mime_guess` crate.
    /// Guesses based on the file extension.
    Extension(mime_guess::Mime),
}

impl Mime {
    fn essence(&self) -> &str {
        match self {
            Self::Pure(raw) => raw,
            Self::Database(raw) => raw,
            Self::Extension(mime) => mime.essence_str(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Scan {
    Source {
        source: Source,
        original_source: Option<Source>,
        playlist: Option<StrictPath>,
        context: RefreshContext,
    },
    Identify {
        source: Source,
        path: StrictPath,
        context: RefreshContext,
    },
    Found {
        source: Source,
        media: Media,
        context: RefreshContext,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Category {
    Image,
    #[cfg(feature = "audio")]
    Audio,
    #[cfg(feature = "video")]
    Video,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum AnimatedImage {
    Apng,
    Gif,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Media {
    Image {
        path: StrictPath,
    },
    Svg {
        path: StrictPath,
    },
    AnimatedImage {
        path: StrictPath,
        kind: AnimatedImage,
    },
    #[cfg(feature = "audio")]
    Audio {
        path: StrictPath,
    },
    #[cfg(feature = "video")]
    Video {
        path: StrictPath,
    },
}

impl Media {
    pub fn category(&self) -> Category {
        match self {
            Self::Image { .. } => Category::Image,
            Self::Svg { .. } => Category::Image,
            Self::AnimatedImage { .. } => Category::Image,
            #[cfg(feature = "audio")]
            Self::Audio { .. } => Category::Audio,
            #[cfg(feature = "video")]
            Self::Video { .. } => Category::Video,
        }
    }

    pub fn path(&self) -> &StrictPath {
        match self {
            Self::Image { path } => path,
            Self::Svg { path } => path,
            Self::AnimatedImage { path, .. } => path,
            #[cfg(feature = "audio")]
            Self::Audio { path } => path,
            #[cfg(feature = "video")]
            Self::Video { path } => path,
        }
    }

    fn identify(path: &StrictPath) -> Option<Self> {
        let inferrable = match path.as_std_path_buf() {
            Ok(pb) => pb,
            Err(e) => {
                log::error!("Unable to parse path: {path:?} | {e:?}");
                return None;
            }
        };

        #[allow(clippy::unnecessary_lazy_evaluations)]
        let mime = infer::get_from_path(&inferrable)
            .map_err(|e| {
                log::error!("Error inferring file type: {path:?} | {e:?}");
                e
            })
            .ok()
            .flatten()
            .map(|x| Mime::Pure(x.mime_type()))
            .or_else(|| {
                #[cfg(target_os = "windows")]
                {
                    None
                }
                #[cfg(not(target_os = "windows"))]
                {
                    tree_magic_mini::from_filepath(&inferrable).map(Mime::Database)
                }
            })
            .or_else(|| mime_guess::from_path(&inferrable).first().map(Mime::Extension));

        log::debug!("Inferred file type '{mime:?}': {path:?}");

        mime.and_then(|mime| {
            let mime = mime.essence();

            let extension = path.file_extension().map(|x| x.to_lowercase());

            #[cfg(feature = "video")]
            if mime.starts_with("video/") && extension.as_ref().is_none_or(|ext| ext != "m4a") {
                // The exact formats supported will depend on the user's GStreamer plugins,
                // so just go ahead and try it. Some that work by default on Windows:
                // * video/mp4
                // * video/mpeg
                // * video/quicktime
                // * video/webm
                // * video/x-m4v
                // * video/x-matroska
                // * video/x-msvideo
                return Some(Self::Video {
                    path: path.normalized(),
                });
            }

            match mime {
                #[cfg(feature = "audio")]
                "audio/mpeg" | "audio/m4a" | "audio/opus" | "audio/x-flac" | "audio/x-wav" => Some(Self::Audio {
                    path: path.normalized(),
                }),
                #[cfg(feature = "audio")]
                "video/mp4" if extension.as_ref().is_some_and(|ext| ext == "m4a") => Some(Self::Audio {
                    path: path.normalized(),
                }),
                "image/bmp" | "image/jpeg" | "image/tiff" | "image/vnd.microsoft.icon" | "image/webp" => {
                    Some(Self::Image {
                        path: path.normalized(),
                    })
                }
                "image/png" => {
                    if is_animated_png(path) {
                        Some(Self::AnimatedImage {
                            path: path.normalized(),
                            kind: AnimatedImage::Apng,
                        })
                    } else {
                        Some(Self::Image {
                            path: path.normalized(),
                        })
                    }
                }
                "image/gif" => Some(Self::AnimatedImage {
                    path: path.normalized(),
                    kind: AnimatedImage::Gif,
                }),
                "image/svg+xml" => Some(Self::Svg {
                    path: path.normalized(),
                }),
                "text/xml" if extension.as_ref().is_some_and(|ext| ext == "svg") => Some(Self::Svg {
                    path: path.normalized(),
                }),
                _ => None,
            }
        })
    }
}

pub type SourceMap = HashMap<Source, HashSet<Media>>;

#[derive(Debug, Default, Clone)]
pub struct Collection {
    media: SourceMap,
    errored: HashSet<Media>,
}

impl Collection {
    pub fn clear(&mut self) {
        self.media.clear();
    }

    pub fn prune(&mut self, sources: &[Source]) {
        self.media.retain(|k, _| sources.contains(k));
    }

    pub fn mark_error(&mut self, media: &Media) {
        self.errored.insert(media.clone());
    }

    pub fn is_error(&self, media: &Media) -> bool {
        self.errored.contains(media)
    }

    pub fn is_outdated(&self, media: &Media, sources: &[Source]) -> bool {
        if sources.is_empty() {
            return true;
        }

        sources
            .iter()
            .filter_map(|source| self.media.get(source))
            .all(|known| !known.contains(media))
    }

    pub fn find(scan: Scan) -> Vec<Scan> {
        match scan {
            Scan::Source {
                source,
                original_source,
                playlist,
                context,
            } => {
                let basis = playlist
                    .as_ref()
                    .and_then(|x| x.parent_if_file().ok())
                    .unwrap_or_else(StrictPath::cwd);

                let filled = source.fill_placeholders(&basis);
                let original_source = original_source.unwrap_or(source);

                match filled {
                    Source::Path { path } => {
                        if path.is_file() {
                            log::debug!("Source is file: {path:?}");
                            vec![Scan::Identify {
                                path,
                                source: original_source,
                                context,
                            }]
                        } else if path.is_dir() {
                            log::debug!("Source is directory: {path:?}");
                            path.joined("*")
                                .glob()
                                .into_iter()
                                .filter(|x| x.is_file())
                                .map(|file| {
                                    log::debug!("Found file from directory: {file:?} <- {path:?}");
                                    Scan::Identify {
                                        path: file,
                                        source: original_source.clone(),
                                        context,
                                    }
                                })
                                .collect()
                        } else if path.is_symlink() {
                            log::debug!("Source is symlink: {path:?}");
                            match path.interpreted() {
                                Ok(target) => {
                                    log::debug!("Found target from symlink: {target:?} <- {path:?}");
                                    vec![Scan::Source {
                                        source: Source::new_path(target),
                                        original_source: Some(original_source),
                                        playlist,
                                        context,
                                    }]
                                }
                                Err(error) => {
                                    log::error!("Failed to traverse symlink: {path:?} | {error:?}");
                                    vec![]
                                }
                            }
                        } else {
                            log::debug!("Source is unknown path: {path:?}");
                            vec![]
                        }
                    }
                    Source::Glob { pattern } => StrictPath::new(pattern.clone())
                        .glob()
                        .into_iter()
                        .map(|file| {
                            log::debug!("Found file from glob: {file:?} <- {pattern}");
                            Scan::Source {
                                source: Source::new_path(file),
                                original_source: Some(original_source.clone()),
                                playlist: playlist.clone(),
                                context,
                            }
                        })
                        .collect(),
                }
            }
            Scan::Identify { path, source, context } => match Media::identify(&path) {
                Some(media) => vec![Scan::Found { media, source, context }],
                None => vec![],
            },
            Scan::Found { media, source, context } => vec![Scan::Found { media, source, context }],
        }
    }

    pub fn insert(&mut self, source: Source, media: Media) {
        self.media.entry(source).or_default().insert(media);
    }

    pub fn one_new(&self, sources: &[Source], old: HashSet<&Media>) -> Option<Media> {
        use rand::seq::SliceRandom;

        let mut media: Vec<_> = sources
            .iter()
            .filter_map(|source| self.media.get(source))
            .flatten()
            .unique()
            .collect();
        media.shuffle(&mut rand::rng());

        media
            .into_iter()
            .find(|media| !self.errored.contains(media) && !old.contains(media))
            .cloned()
    }

    pub fn all_for_sources(&self, sources: &[Source]) -> BTreeSet<&Media> {
        sources
            .iter()
            .filter_map(|source| self.media.get(source))
            .flatten()
            .unique()
            .collect()
    }
}

fn is_animated_png(path: &StrictPath) -> bool {
    let reader = match path.open_buffered() {
        Ok(handle) => handle,
        Err(e) => {
            log::error!("Unable to open PNG: {e:?}");
            return false;
        }
    };

    let decoder = png::Decoder::new(reader);

    let reader = match decoder.read_info() {
        Ok(reader) => reader,
        Err(e) => {
            log::error!("Unable to decode PNG: {e:?}");
            return false;
        }
    };

    let info = reader.info();

    info.is_animated()
}

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

    #[test]
    fn can_fill_placeholders_in_path_with_match() {
        let source = Source::new_path(StrictPath::new(format!("{}/foo", placeholder::PLAYLIST)));
        let playlist = StrictPath::new("/tmp");
        let filled = Source::new_path(StrictPath::new("/tmp/foo"));
        assert_eq!(filled, source.fill_placeholders(&playlist))
    }

    #[test]
    fn can_fill_placeholders_in_path_without_match() {
        let source = Source::new_path(StrictPath::new(format!("/{}/foo", placeholder::PLAYLIST)));
        let playlist = StrictPath::new("/tmp");
        assert_eq!(source, source.fill_placeholders(&playlist))
    }

    #[test]
    fn can_fill_placeholders_in_glob_with_match() {
        let source = Source::new_glob(format!("{}/foo", placeholder::PLAYLIST));
        let playlist = StrictPath::new("/tmp");
        let filled = Source::new_glob("/tmp/foo".to_string());
        assert_eq!(filled, source.fill_placeholders(&playlist))
    }

    #[test]
    fn can_fill_placeholders_in_glob_without_match() {
        let source = Source::new_glob(format!("/{}/foo", placeholder::PLAYLIST));
        let playlist = StrictPath::new("/tmp");
        assert_eq!(source, source.fill_placeholders(&playlist))
    }
}