-
Notifications
You must be signed in to change notification settings - Fork 4
/
library.rs
3815 lines (3596 loc) · 141 KB
/
library.rs
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
//! Module containing utilities to properly manage a library of [Song]s,
//! for people wanting to e.g. implement a bliss plugin for an existing
//! audio player. A good resource to look at for inspiration is
//! [blissify](https://github.com/Polochon-street/blissify-rs)'s source code.
//!
//! Useful to have direct and easy access to functions that analyze
//! and store analysis of songs in a SQLite database, as well as retrieve it,
//! and make playlists directly from analyzed songs. All functions are as
//! thoroughly tested as possible, so you don't have to do it yourself,
//! including for instance bliss features version handling, etc.
//!
//! It works in three parts:
//! * The first part is the configuration part, which allows you to
//! specify extra information that your plugin might need that will
//! be automatically stored / retrieved when you instanciate a
//! [Library] (the core of your plugin).
//!
//! To do so implies specifying a configuration struct, that will implement
//! [AppConfigTrait], i.e. implement `Serialize`, `Deserialize`, and a
//! function to retrieve the [BaseConfig] (which is just a structure
//! holding the path to the configuration file and the path to the database).
//!
//! The most straightforward way to do so is to have something like this (
//! in this example, we assume that `path_to_extra_information` is something
//! you would want stored in your configuration file, path to a second music
//! folder for instance:
//! ```
//! use anyhow::Result;
//! use serde::{Deserialize, Serialize};
//! use std::path::PathBuf;
//! use std::num::NonZeroUsize;
//! use bliss_audio::BlissError;
//! use bliss_audio::library::{AppConfigTrait, BaseConfig};
//!
//! #[derive(Serialize, Deserialize, Clone, Debug)]
//! pub struct Config {
//! #[serde(flatten)]
//! pub base_config: BaseConfig,
//! pub music_library_path: PathBuf,
//! }
//!
//! impl AppConfigTrait for Config {
//! fn base_config(&self) -> &BaseConfig {
//! &self.base_config
//! }
//!
//! fn base_config_mut(&mut self) -> &mut BaseConfig {
//! &mut self.base_config
//! }
//! }
//! impl Config {
//! pub fn new(
//! music_library_path: PathBuf,
//! config_path: Option<PathBuf>,
//! database_path: Option<PathBuf>,
//! number_cores: Option<NonZeroUsize>,
//! ) -> Result<Self> {
//! // Note that by passing `(None, None)` here, the paths will
//! // be inferred automatically using user data dirs.
//! let base_config = BaseConfig::new(config_path, database_path, number_cores)?;
//! Ok(Self {
//! base_config,
//! music_library_path,
//! })
//! }
//! }
//! ```
//!
//! * The second part is the actual [Library] structure, that makes the
//! bulk of the plug-in. To initialize a library once with a given config,
//! you can do (here with a base configuration, requiring ffmpeg):
#![cfg_attr(
feature = "ffmpeg",
doc = r##"
```no_run
use anyhow::{Error, Result};
use bliss_audio::library::{BaseConfig, Library};
use bliss_audio::decoder::ffmpeg::FFmpeg;
use std::path::PathBuf;
let config_path = Some(PathBuf::from("path/to/config/config.json"));
let database_path = Some(PathBuf::from("path/to/config/bliss.db"));
let config = BaseConfig::new(config_path, database_path, None)?;
let library: Library<BaseConfig, FFmpeg> = Library::new(config)?;
# Ok::<(), Error>(())
```"##
)]
//! Once this is done, you can simply load the library by doing
//! `Library::from_config_path(config_path);`
//! * The third part is using the [Library] itself: it provides you with
//! utilies such as [Library::analyze_paths], which analyzes all songs
//! in given paths and stores it in the databases, as well as
//! [Library::playlist_from], which allows you to generate a playlist
//! from any given analyzed song(s), and [Library::playlist_from_custom],
//! which allows you to customize the way you generate playlists.
//!
//! The [Library] structure also comes with a [LibrarySong] song struct,
//! which represents a song stored in the database.
//!
//! It is made of a `bliss_song` field, containing the analyzed bliss
//! song (with the normal metatada such as the artist, etc), and an
//! `extra_info` field, which can be any user-defined serialized struct.
//! For most use cases, it would just be the unit type `()` (which is no
//! extra info), that would be used like
//! `library.playlist_from<()>(song, path, playlist_length)`,
//! but functions such as [Library::analyze_paths_extra_info] and
//! [Library::analyze_paths_convert_extra_info] let you customize what
//! information you store for each song.
//!
//! The files in
//! [examples/library.rs](https://github.com/Polochon-street/bliss-rs/blob/master/examples/library.rs)
//! and
//! [examples/libray_extra_info.rs](https://github.com/Polochon-street/bliss-rs/blob/master/examples/library_extra_info.rs)
//! should provide the user with enough information to start with. For a more
//! "real-life" example, the
//! [blissify](https://github.com/Polochon-street/blissify-rs)'s code is using
//! [Library] to implement bliss for a MPD player.
use crate::cue::CueInfo;
use crate::playlist::closest_album_to_group;
use crate::playlist::closest_to_songs;
use crate::playlist::dedup_playlist_custom_distance;
use crate::playlist::euclidean_distance;
use crate::playlist::DistanceMetricBuilder;
use anyhow::{bail, Context, Result};
#[cfg(all(not(test), not(feature = "integration-tests")))]
use dirs::config_local_dir;
#[cfg(all(not(test), not(feature = "integration-tests")))]
use dirs::data_local_dir;
use indicatif::{ProgressBar, ProgressStyle};
use log::warn;
use ndarray::Array2;
use rusqlite::params;
use rusqlite::params_from_iter;
use rusqlite::Connection;
use rusqlite::OptionalExtension;
use rusqlite::Params;
use rusqlite::Row;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::{HashMap, HashSet};
use std::env;
use std::fs;
use std::fs::create_dir_all;
use std::marker::PhantomData;
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::Mutex;
use std::thread;
use crate::decoder::Decoder as DecoderTrait;
use crate::Song;
use crate::FEATURES_VERSION;
use crate::{Analysis, BlissError, NUMBER_FEATURES};
use rusqlite::Error as RusqliteError;
use std::convert::TryInto;
use std::time::Duration;
/// Configuration trait, used for instance to customize
/// the format in which the configuration file should be written.
pub trait AppConfigTrait: Serialize + Sized + DeserializeOwned {
// Implementers have to provide these.
/// This trait should return the [BaseConfig] from the parent,
/// user-created `Config`.
fn base_config(&self) -> &BaseConfig;
// Implementers have to provide these.
/// This trait should return the [BaseConfig] from the parent,
/// user-created `Config`.
fn base_config_mut(&mut self) -> &mut BaseConfig;
// Default implementation to output the config as a JSON file.
/// Convert the current config to a [String], to be written to
/// a file.
///
/// The default writes a JSON file, but any format can be used,
/// using for example the various Serde libraries (`serde_yaml`, etc) -
/// just overwrite this method.
fn serialize_config(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(&self)?)
}
/// Set the number of desired cores for analysis, and write it to the
/// configuration file.
fn set_number_cores(&mut self, number_cores: NonZeroUsize) -> Result<()> {
self.base_config_mut().number_cores = number_cores;
self.write()
}
/// Get the number of desired cores for analysis, and write it to the
/// configuration file.
fn get_number_cores(&self) -> NonZeroUsize {
self.base_config().number_cores
}
/// Default implementation to load a config from a JSON file.
/// Reads from a string.
///
/// If you change the serialization format to use something else
/// than JSON, you need to also overwrite that function with the
/// format you chose.
fn deserialize_config(data: &str) -> Result<Self> {
Ok(serde_json::from_str(data)?)
}
/// Load a config from the specified path, using `deserialize_config`.
///
/// This method can be overriden in the very unlikely case
/// the user wants to do something Serde cannot.
fn from_path(path: &str) -> Result<Self> {
let data = fs::read_to_string(path)?;
Self::deserialize_config(&data)
}
// This default impl is what requires the `Serialize` supertrait
/// Write the configuration to a file using
/// [AppConfigTrait::serialize_config].
///
/// This method can be overriden
/// to not use [AppConfigTrait::serialize_config], in the very unlikely
/// case the user wants to do something Serde cannot.
fn write(&self) -> Result<()> {
let serialized = self.serialize_config()?;
fs::write(&self.base_config().config_path, serialized)?;
Ok(())
}
}
#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
/// The minimum configuration an application needs to work with
/// a [Library].
pub struct BaseConfig {
/// The path to where the configuration file should be stored,
/// e.g. `/home/foo/.local/share/bliss-rs/config.json`
pub config_path: PathBuf,
/// The path to where the database file should be stored,
/// e.g. `/home/foo/.local/share/bliss-rs/bliss.db`
pub database_path: PathBuf,
/// The latest features version a song has been analyzed
/// with.
pub features_version: u16,
/// The number of CPU cores an analysis will be performed with.
/// Defaults to the number of CPUs in the user's computer.
pub number_cores: NonZeroUsize,
/// The mahalanobis matrix used for mahalanobis distance.
/// Used to customize the distance metric beyond simple euclidean distance.
/// Uses ndarray's `serde` feature for serialization / deserialization.
/// Field would look like this:
/// "m": {"v": 1, "dim": [20, 20], "data": [1.0, 0.0, ..., 1.0]}
#[serde(default = "default_m")]
pub m: Array2<f32>,
}
fn default_m() -> Array2<f32> {
Array2::eye(NUMBER_FEATURES)
}
impl BaseConfig {
/// Because we spent some time using XDG_DATA_HOME instead of XDG_CONFIG_HOME
/// as the default folder, we have to jump through some hoops:
///
/// - Legacy path exists, new path doesn't exist => legacy path should be returned
/// - Legacy path exists, new path exists => new path should be returned
/// - Legacy path doesn't exist => new path should be returned
pub(crate) fn get_default_data_folder() -> Result<PathBuf> {
let error_message = "No suitable path found to store bliss' song database. Consider specifying such a path.";
let default_folder = env::var("XDG_CONFIG_HOME")
.map(|path| Path::new(&path).join("bliss-rs"))
.or_else(|_| {
config_local_dir()
.map(|p| p.join("bliss-rs"))
.with_context(|| error_message)
});
if let Ok(folder) = &default_folder {
if folder.exists() {
return Ok(folder.clone());
}
}
if let Ok(legacy_folder) = BaseConfig::get_legacy_data_folder() {
if legacy_folder.exists() {
return Ok(legacy_folder);
}
}
// If neither default_folder nor legacy_folder exist, return the default folder
default_folder
}
fn get_legacy_data_folder() -> Result<PathBuf> {
let path = match env::var("XDG_DATA_HOME") {
Ok(path) => Path::new(&path).join("bliss-rs"),
Err(_) => data_local_dir().with_context(|| "No suitable path found to store bliss' song database. Consider specifying such a path.")?.join("bliss-rs"),
};
Ok(path)
}
/// Create a new, basic config. Upon calls of `Config.write()`, it will be
/// written to `config_path`.
//
/// Any path omitted will instead default to a "clever" path using
/// data directory inference. The "clever" thinking is as follows:
/// - If the user specified only one of the paths, it will put the other
/// file in the same folder as the given path.
/// - If the user specified both paths, it will go with what the user
/// chose.
/// - If the user didn't select any path, it will try to put everything in
/// the user's configuration directory, i.e. XDG_CONFIG_HOME.
///
/// The number of cores is the number of cores that should be used for
/// any analysis. If not provided, it will default to the computer's
/// number of cores.
pub fn new(
config_path: Option<PathBuf>,
database_path: Option<PathBuf>,
number_cores: Option<NonZeroUsize>,
) -> Result<Self> {
let provided_database_path = database_path.is_some();
let provided_config_path = config_path.is_some();
let mut final_config_path = {
// User provided a path; let the future file creation determine
// whether it points to something valid or not
if let Some(path) = config_path {
path
} else {
Self::get_default_data_folder()?.join(Path::new("config.json"))
}
};
let mut final_database_path = {
if let Some(path) = database_path {
path
} else {
Self::get_default_data_folder()?.join(Path::new("songs.db"))
}
};
if provided_database_path && !provided_config_path {
final_config_path = final_database_path
.parent()
.ok_or(BlissError::ProviderError(String::from(
"provided database path was invalid.",
)))?
.join(Path::new("config.json"))
} else if !provided_database_path && provided_config_path {
final_database_path = final_config_path
.parent()
.ok_or(BlissError::ProviderError(String::from(
"provided config path was invalid.",
)))?
.join(Path::new("songs.db"))
}
let number_cores = number_cores.unwrap_or_else(|| {
thread::available_parallelism().unwrap_or(NonZeroUsize::new(1).unwrap())
});
Ok(Self {
config_path: final_config_path,
database_path: final_database_path,
features_version: FEATURES_VERSION,
number_cores,
m: Array2::eye(NUMBER_FEATURES),
})
}
}
impl AppConfigTrait for BaseConfig {
fn base_config(&self) -> &BaseConfig {
self
}
fn base_config_mut(&mut self) -> &mut BaseConfig {
self
}
}
/// A struct used to hold a collection of [Song]s, with convenience
/// methods to add, remove and update songs.
///
/// Provide it either the `BaseConfig`, or a `Config` extending
/// `BaseConfig`.
/// TODO code example
pub struct Library<Config, D: ?Sized> {
/// The configuration struct, containing both information
/// from `BaseConfig` as well as user-defined values.
pub config: Config,
/// SQL connection to the database.
pub sqlite_conn: Arc<Mutex<Connection>>,
decoder: PhantomData<D>,
}
/// Struct holding both a Bliss song, as well as any extra info
/// that a user would want to store in the database related to that
/// song.
///
/// The only constraint is that `extra_info` must be serializable, so,
/// something like
/// ```no_compile
/// #[derive(Serialize)]
/// struct ExtraInfo {
/// ignore: bool,
/// unique_id: i64,
/// }
/// let extra_info = ExtraInfo { ignore: true, unique_id = 123 };
/// let song = LibrarySong { bliss_song: song, extra_info };
/// ```
/// is totally possible.
#[derive(Debug, PartialEq, Clone)]
pub struct LibrarySong<T: Serialize + DeserializeOwned + Clone> {
/// Actual bliss song, containing the song's metadata, as well
/// as the bliss analysis.
pub bliss_song: Song,
/// User-controlled information regarding that specific song.
pub extra_info: T,
}
impl<T: Serialize + DeserializeOwned + Clone> AsRef<Song> for LibrarySong<T> {
fn as_ref(&self) -> &Song {
&self.bliss_song
}
}
// TODO add logging statement
// TODO maybe return number of elements updated / deleted / whatev in analysis
// functions?
// TODO should it really use anyhow errors?
// TODO make sure that the path to string is consistent
impl<Config: AppConfigTrait, D: ?Sized + DecoderTrait> Library<Config, D> {
const SQLITE_SCHEMA: &'static str = "
create table song (
id integer primary key,
path text not null unique,
duration float,
album_artist text,
artist text,
title text,
album text,
track_number integer,
disc_number integer,
genre text,
cue_path text,
audio_file_path text,
stamp timestamp default current_timestamp,
version integer,
analyzed boolean default false,
extra_info json,
error text
);
pragma foreign_keys = on;
create table feature (
id integer primary key,
song_id integer not null,
feature real not null,
feature_index integer not null,
unique(song_id, feature_index),
foreign key(song_id) references song(id) on delete cascade
)
";
const SQLITE_MIGRATIONS: &'static [&'static str] = &[
"",
"
alter table song add column track_number_1 integer;
update song set track_number_1 = s1.cast_track_number from (
select cast(track_number as int) as cast_track_number, id from song
) as s1 where s1.id = song.id and cast(track_number as int) != 0;
alter table song drop column track_number;
alter table song rename column track_number_1 to track_number;
",
"alter table song add column disc_number integer;",
"
-- Training triplets used to do metric learning, in conjunction with
-- a human-processed survey. In this table, songs pointed to
-- by song_1_id and song_2_id are closer together than they
-- are to the song pointed to by odd_one_out_id, i.e.
-- d(s1, s2) < d(s1, odd_one_out) and d(s1, s2) < d(s2, odd_one_out)
create table training_triplet (
id integer primary key,
song_1_id integer not null,
song_2_id integer not null,
odd_one_out_id integer not null,
stamp timestamp default current_timestamp,
foreign key(song_1_id) references song(id) on delete cascade,
foreign key(song_2_id) references song(id) on delete cascade,
foreign key(odd_one_out_id) references song(id) on delete cascade
)
",
];
/// Create a new [Library] object from the given Config struct that
/// implements the [AppConfigTrait].
/// writing the configuration to the file given in
/// `config.config_path`.
///
/// This function should only be called once, when a user wishes to
/// create a completely new "library".
/// Otherwise, load an existing library file using
/// [Library::from_config_path].
pub fn new(config: Config) -> Result<Self> {
if !config
.base_config()
.config_path
.parent()
.ok_or_else(|| {
BlissError::ProviderError(format!(
"specified path {} is not a valid file path.",
config.base_config().config_path.display()
))
})?
.is_dir()
{
create_dir_all(config.base_config().config_path.parent().unwrap())?;
}
let sqlite_conn = Connection::open(&config.base_config().database_path)?;
Library::<Config, D>::upgrade(&sqlite_conn).map_err(|e| {
BlissError::ProviderError(format!("Could not run database upgrade: {}", e))
})?;
config.write()?;
Ok(Self {
config,
sqlite_conn: Arc::new(Mutex::new(sqlite_conn)),
decoder: PhantomData,
})
}
fn upgrade(sqlite_conn: &Connection) -> Result<()> {
let version: u32 = sqlite_conn
.query_row("pragma user_version", [], |row| row.get(0))
.map_err(|e| {
BlissError::ProviderError(format!("Could not get database version: {}.", e))
})?;
let migrations = Library::<Config, D>::SQLITE_MIGRATIONS;
match version.cmp(&(migrations.len() as u32)) {
std::cmp::Ordering::Equal => return Ok(()),
std::cmp::Ordering::Greater => bail!(format!(
"bliss-rs version {} is older than the schema version {}",
version,
migrations.len()
)),
_ => (),
};
let number_tables: u32 = sqlite_conn
.query_row("select count(*) from pragma_table_list", [], |row| {
row.get(0)
})
.map_err(|e| {
BlissError::ProviderError(format!(
"Could not query initial database information: {}",
e
))
})?;
let is_database_new = number_tables <= 2;
if version == 0 && is_database_new {
sqlite_conn
.execute_batch(Library::<Config, D>::SQLITE_SCHEMA)
.map_err(|e| {
BlissError::ProviderError(format!("Could not initialize schema: {}.", e))
})?;
} else {
for migration in migrations.iter().skip(version as usize) {
sqlite_conn.execute_batch(migration).map_err(|e| {
BlissError::ProviderError(format!("Could not execute migration: {}.", e))
})?;
}
}
sqlite_conn
.execute(&format!("pragma user_version = {}", migrations.len()), [])
.map_err(|e| {
BlissError::ProviderError(format!("Could not update database version: {}.", e))
})?;
Ok(())
}
/// Load a library from a configuration path.
///
/// If no configuration path is provided, the path is
/// set using default data folder path.
pub fn from_config_path(config_path: Option<PathBuf>) -> Result<Self> {
let config_path: Result<PathBuf> =
config_path.map_or_else(|| Ok(BaseConfig::new(None, None, None)?.config_path), Ok);
let config_path = config_path?;
let data = fs::read_to_string(config_path)?;
let config = Config::deserialize_config(&data)?;
let sqlite_conn = Connection::open(&config.base_config().database_path)?;
Library::<Config, D>::upgrade(&sqlite_conn)?;
let mut library = Self {
config,
sqlite_conn: Arc::new(Mutex::new(sqlite_conn)),
decoder: PhantomData,
};
if !library.version_sanity_check()? {
warn!(
"Songs have been analyzed with different versions of bliss; \
older versions will be ignored from playlists. Update your \
bliss library to correct the issue."
);
}
Ok(library)
}
/// Check whether the library contains songs analyzed with different,
/// incompatible versions of bliss.
///
/// Returns true if the database is clean (only one version of the
/// features), and false otherwise.
pub fn version_sanity_check(&mut self) -> Result<bool> {
let connection = self
.sqlite_conn
.lock()
.map_err(|e| BlissError::ProviderError(e.to_string()))?;
let count: u32 = connection
.query_row("select count(distinct version) from song", [], |row| {
row.get(0)
})
.optional()?
.unwrap_or(0);
Ok(count <= 1)
}
/// Create a new [Library] object from a minimal configuration setup,
/// writing it to `config_path`.
pub fn new_from_base(
config_path: Option<PathBuf>,
database_path: Option<PathBuf>,
number_cores: Option<NonZeroUsize>,
) -> Result<Self>
where
BaseConfig: Into<Config>,
{
let base = BaseConfig::new(config_path, database_path, number_cores)?;
let config = base.into();
Self::new(config)
}
/// Build a playlist of `playlist_length` items from a set of already analyzed
/// songs in the library at `song_path`.
///
/// It uses the ExentedIsolationForest score as a distance between songs, and deduplicates
/// songs that are too close.
///
/// Generating a playlist from a single song is also possible, and is just the special case
/// where song_paths is a slice of length 1.
pub fn playlist_from<'a, T: Serialize + DeserializeOwned + Clone + 'a>(
&self,
song_paths: &[&str],
) -> Result<impl Iterator<Item = LibrarySong<T>> + 'a> {
self.playlist_from_custom(song_paths, &euclidean_distance, closest_to_songs, true)
}
/// Build a playlist of `playlist_length` items from a set of already analyzed
/// song(s) in the library `initial_song_paths`, using distance metric `distance`,
/// and sorting function `sort_by`.
/// Note: The resulting playlist includes the songs specified in `initial_song_paths`
/// at the beginning. Use [Iterator::skip] on the resulting iterator to avoid it.
///
/// You can use ready-to-use distance metrics such as
/// [ExtendedIsolationForest](extended_isolation_forest::Forest) or [euclidean_distance],
/// and ready-to-use sorting functions like [closest_to_songs] or
/// [crate::playlist::song_to_song].
///
/// If you want to use the sorting functions in a uniform manner, you can do something like
/// this:
/// ```
/// use bliss_audio::library::LibrarySong;
/// use bliss_audio::playlist::{closest_to_songs, song_to_song};
///
/// // The user would be choosing this
/// let use_closest_to_songs = true;
/// let sort = |x: &[LibrarySong<()>],
/// y: &[LibrarySong<()>],
/// z|
/// -> Box<dyn Iterator<Item = LibrarySong<()>>> {
/// match use_closest_to_songs {
/// false => Box::new(closest_to_songs(x, y, z)),
/// true => Box::new(song_to_song(x, y, z)),
/// }
/// };
/// ```
/// and use `playlist_from_custom` with that sort as `sort_by`.
///
/// Generating a playlist from a single song is also possible, and is just the special case
/// where song_paths is a slice with a single song.
pub fn playlist_from_custom<'a, T, F, I>(
&self,
initial_song_paths: &[&str],
distance: &'a dyn DistanceMetricBuilder,
sort_by: F,
deduplicate: bool,
) -> Result<impl Iterator<Item = LibrarySong<T>> + 'a>
where
T: Serialize + DeserializeOwned + Clone + 'a,
F: Fn(&[LibrarySong<T>], &[LibrarySong<T>], &'a dyn DistanceMetricBuilder) -> I,
I: Iterator<Item = LibrarySong<T>> + 'a,
{
let initial_songs: Vec<LibrarySong<T>> = initial_song_paths
.iter()
.map(|s| {
self.song_from_path(s).map_err(|_| {
BlissError::ProviderError(format!("song '{s}' has not been analyzed"))
})
})
.collect::<Result<Vec<_>, BlissError>>()?;
// Remove the initial songs, so they don't get
// sorted in the mess.
let songs = self
.songs_from_library()?
.into_iter()
.filter(|s| {
!initial_song_paths.contains(&&*s.bliss_song.path.to_string_lossy().to_string())
})
.collect::<Vec<_>>();
let iterator = sort_by(&initial_songs, &songs, distance);
let mut iterator: Box<dyn Iterator<Item = LibrarySong<T>>> =
Box::new(initial_songs.into_iter().chain(iterator));
if deduplicate {
iterator = Box::new(dedup_playlist_custom_distance(iterator, None, distance));
}
Ok(iterator)
}
/// Make a playlist of `number_albums` albums closest to the album
/// with title `album_title`.
/// The playlist starts with the album with `album_title`, and contains
/// `number_albums` on top of that one.
///
/// Returns the songs of each album ordered by bliss' `track_number`.
pub fn album_playlist_from<T: Serialize + DeserializeOwned + Clone + PartialEq>(
&self,
album_title: String,
number_albums: usize,
) -> Result<Vec<LibrarySong<T>>> {
let album = self.songs_from_album(&album_title)?;
// Every song should be from the same album. Hopefully...
let songs = self.songs_from_library()?;
let playlist = closest_album_to_group(album, songs)?;
let mut album_count = 0;
let mut index = 0;
let mut current_album = Some(album_title);
for song in playlist.iter() {
if song.bliss_song.album != current_album {
album_count += 1;
if album_count > number_albums {
break;
}
song.bliss_song.album.clone_into(&mut current_album);
}
index += 1;
}
let playlist = &playlist[..index];
Ok(playlist.to_vec())
}
/// Analyze and store all songs in `paths` that haven't been already analyzed.
///
/// Use this function if you don't have any extra data to bundle with each song.
///
/// Setting `delete_everything_else` to true will delete the paths that are
/// not mentionned in `paths_extra_info` from the database. If you do not
/// use it, because you only pass the new paths that need to be analyzed to
/// this function, make sure to delete yourself from the database the songs
/// that have been deleted from storage.
///
/// If your library
/// contains CUE files, pass the CUE file path only, and not individual
/// CUE track names: passing `vec![file.cue]` will add
/// individual tracks with the `cue_info` field set in the database.
pub fn update_library<P: Into<PathBuf>>(
&mut self,
paths: Vec<P>,
delete_everything_else: bool,
show_progress_bar: bool,
) -> Result<()> {
let paths_extra_info = paths.into_iter().map(|path| (path, ())).collect::<Vec<_>>();
self.update_library_convert_extra_info(
paths_extra_info,
delete_everything_else,
show_progress_bar,
|x, _, _| x,
)
}
/// Analyze and store all songs in `paths_extra_info` that haven't already
/// been analyzed, along with some extra metadata serializable, and known
/// before song analysis.
///
/// Setting `delete_everything_else` to true will delete the paths that are
/// not mentionned in `paths_extra_info` from the database. If you do not
/// use it, because you only pass the new paths that need to be analyzed to
/// this function, make sure to delete yourself from the database the songs
/// that have been deleted from storage.
pub fn update_library_extra_info<T: Serialize + DeserializeOwned + Clone, P: Into<PathBuf>>(
&mut self,
paths_extra_info: Vec<(P, T)>,
delete_everything_else: bool,
show_progress_bar: bool,
) -> Result<()> {
self.update_library_convert_extra_info(
paths_extra_info,
delete_everything_else,
show_progress_bar,
|extra_info, _, _| extra_info,
)
}
/// Analyze and store all songs in `paths_extra_info` that haven't
/// been already analyzed, as well as handling extra, user-specified metadata,
/// that can't directly be serializable,
/// or that need input from the analyzed Song to be processed. If you
/// just want to analyze and store songs along with some directly
/// serializable values, consider using [Library::update_library_extra_info],
/// or [Library::update_library] if you just want the analyzed songs
/// stored as is.
///
/// `paths_extra_info` is a tuple made out of song paths, along
/// with any extra info you want to store for each song.
/// If your library
/// contains CUE files, pass the CUE file path only, and not individual
/// CUE track names: passing `vec![file.cue]` will add
/// individual tracks with the `cue_info` field set in the database.
///
/// Setting `delete_everything_else` to true will delete the paths that are
/// not mentionned in `paths_extra_info` from the database. If you do not
/// use it, because you only pass the new paths that need to be analyzed to
/// this function, make sure to delete yourself from the database the songs
/// that have been deleted from storage.
///
/// `convert_extra_info` is a function that you should specify how
/// to convert that extra info to something serializable.
pub fn update_library_convert_extra_info<
T: Serialize + DeserializeOwned + Clone,
U,
P: Into<PathBuf>,
>(
&mut self,
paths_extra_info: Vec<(P, U)>,
delete_everything_else: bool,
show_progress_bar: bool,
convert_extra_info: fn(U, &Song, &Self) -> T,
) -> Result<()> {
let existing_paths = {
let connection = self
.sqlite_conn
.lock()
.map_err(|e| BlissError::ProviderError(e.to_string()))?;
let mut path_statement = connection.prepare(
"
select
path
from song where analyzed = true and version = ? order by id
",
)?;
#[allow(clippy::let_and_return)]
let return_value = path_statement
.query_map([FEATURES_VERSION], |row| {
Ok(row.get_unwrap::<usize, String>(0))
})?
.map(|x| PathBuf::from(x.unwrap()))
.collect::<HashSet<PathBuf>>();
return_value
};
let paths_extra_info: Vec<_> = paths_extra_info
.into_iter()
.map(|(x, y)| (x.into(), y))
.collect();
let paths: HashSet<_> = paths_extra_info.iter().map(|(p, _)| p.to_owned()).collect();
if delete_everything_else {
let paths_to_delete = existing_paths.difference(&paths);
self.delete_paths(paths_to_delete)?;
}
// Can't use hashsets because we need the extra info here too,
// and U might not be hashable.
let paths_to_analyze = paths_extra_info
.into_iter()
.filter(|(path, _)| !existing_paths.contains(path))
.collect::<Vec<(PathBuf, U)>>();
self.analyze_paths_convert_extra_info(
paths_to_analyze,
show_progress_bar,
convert_extra_info,
)
}
/// Analyze and store all songs in `paths`.
///
/// Updates the value of `features_version` in the config, using bliss'
/// latest version.
///
/// Use this function if you don't have any extra data to bundle with each song.
///
/// If your library
/// contains CUE files, pass the CUE file path only, and not individual
/// CUE track names: passing `vec![file.cue]` will add
/// individual tracks with the `cue_info` field set in the database.
pub fn analyze_paths<P: Into<PathBuf>>(
&mut self,
paths: Vec<P>,
show_progress_bar: bool,
) -> Result<()> {
let paths_extra_info = paths.into_iter().map(|path| (path, ())).collect::<Vec<_>>();
self.analyze_paths_convert_extra_info(paths_extra_info, show_progress_bar, |x, _, _| x)
}
/// Analyze and store all songs in `paths_extra_info`, along with some
/// extra metadata serializable, and known before song analysis.
///
/// Updates the value of `features_version` in the config, using bliss'
/// latest version.
/// If your library
/// contains CUE files, pass the CUE file path only, and not individual
/// CUE track names: passing `vec![file.cue]` will add
/// individual tracks with the `cue_info` field set in the database.
pub fn analyze_paths_extra_info<
T: Serialize + DeserializeOwned + std::fmt::Debug + Clone,
P: Into<PathBuf>,
>(
&mut self,
paths_extra_info: Vec<(P, T)>,
show_progress_bar: bool,
) -> Result<()> {
self.analyze_paths_convert_extra_info(
paths_extra_info,
show_progress_bar,
|extra_info, _, _| extra_info,
)
}
/// Analyze and store all songs in `paths_extra_info`, along with some
/// extra, user-specified metadata, that can't directly be serializable,
/// or that need input from the analyzed Song to be processed.
/// If you just want to analyze and store songs, along with some
/// directly serializable metadata values, consider using
/// [Library::analyze_paths_extra_info], or [Library::analyze_paths] for
/// the simpler use cases.
///
/// Updates the value of `features_version` in the config, using bliss'
/// latest version.
///
/// `paths_extra_info` is a tuple made out of song paths, along
/// with any extra info you want to store for each song. If your library
/// contains CUE files, pass the CUE file path only, and not individual
/// CUE track names: passing `vec![file.cue]` will add
/// individual tracks with the `cue_info` field set in the database.
///
/// `convert_extra_info` is a function that you should specify
/// to convert that extra info to something serializable.
pub fn analyze_paths_convert_extra_info<
T: Serialize + DeserializeOwned + Clone,
U,
P: Into<PathBuf>,
>(
&mut self,
paths_extra_info: Vec<(P, U)>,
show_progress_bar: bool,
convert_extra_info: fn(U, &Song, &Self) -> T,
) -> Result<()> {
let number_songs = paths_extra_info.len();
if number_songs == 0 {
log::info!("No (new) songs found.");
return Ok(());
}
log::info!(
"Analyzing {} songs, this might take some time…",
number_songs
);
let pb = if show_progress_bar {
ProgressBar::new(number_songs.try_into().unwrap())
} else {
ProgressBar::hidden()
};
let style = ProgressStyle::default_bar()
.template("[{elapsed_precise}] {bar:40} {pos:>7}/{len:7} {wide_msg}")?
.progress_chars("##-");
pb.set_style(style);
let mut paths_extra_info: HashMap<PathBuf, U> = paths_extra_info
.into_iter()
.map(|(x, y)| (x.into(), y))
.collect();
let mut cue_extra_info: HashMap<PathBuf, String> = HashMap::new();
let results = D::analyze_paths_with_cores(
paths_extra_info.keys(),
self.config.base_config().number_cores,
);
let mut success_count = 0;