Audiphi in Rust: egui port of the Python app, Spotify API fix

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
astar76 2026-10-24 17:58:16 -05:00
commit df744e47d5
49 changed files with 14201 additions and 0 deletions

4
.gitignore vendored Normal file
View file

@ -0,0 +1,4 @@
/target/
/releases/
*.AppImage
.directory

3911
Cargo.lock generated Normal file

File diff suppressed because it is too large Load diff

37
Cargo.toml Normal file
View file

@ -0,0 +1,37 @@
[package]
name = "audiphi"
version = "0.2.0"
edition = "2021"
description = "A Material 3 music downloader and quick player for any music service"
license = "MIT"
[dependencies]
eframe = { version = "0.37", default-features = false, features = ["glow", "wayland", "x11", "default_fonts"] }
lofty = "0.25"
libmpv2 = "6"
image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif", "bmp"] }
ureq = { version = "3", features = ["json"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
rustfft = "6"
resvg = { version = "0.45", default-features = false }
regex = "1"
urlencoding = "2"
base64 = "0.22"
dirs = "6"
rfd = { version = "0.17", default-features = false, features = ["xdg-portal", "pollster"] }
unicode-normalization = "0.1"
[profile.release]
opt-level = 3
lto = "thin"
codegen-units = 4
strip = true
[lib]
name = "audiphi"
path = "src/lib.rs"
[[bin]]
name = "audiphi"
path = "src/main.rs"

45
README.md Normal file
View file

@ -0,0 +1,45 @@
# Audiphi
A Material 3 music downloader and quick player, written in Rust (egui). Paste a link from almost any
music service (or type a song name) and Audiphi downloads it in the format and quality you pick, with
proper tags, cover art and synced lyrics. This is the Rust port of the Python/PyQt6 version
(`audiphi-python`); settings carry over (`~/.config/audiphi/settings.json`).
- **Any service.** YouTube Music, YouTube, SoundCloud, Bandcamp, Mixcloud, Audiomack and the other ~1,800
sites yt-dlp supports download directly. Spotify, Apple Music, Deezer, Tidal, Amazon Music, Qobuz and
other music pages are read for the song details and matched on YouTube Music (by ISRC when available).
- **Whole collections:** songs, albums, playlists, and artists (top songs or whole discography).
- **Any format:** MP3 (CBR or V0/V2/V4), M4A/AAC, Opus, OGG Vorbis, FLAC, ALAC, WAV, or the original stream.
- **Tags** from Deezer, iTunes and MusicBrainz, per field; **lyrics** from LRCLIB (synced or plain);
cover art; file name templates like `{album_artist}/{album}/{track:02} - {title}`.
- **Quick player** (libmpv) with a spectrum ring around the cover, wavy seek bar and click-to-seek lyrics.
- **Colours** from Caelestia's scheme, your desktop accent, the album art, or a colour you pick.
## Requirements
`yt-dlp`, `ffmpeg`, `mpv` (libmpv) and, for YouTube, a JavaScript runtime (`deno` recommended).
```bash
sudo pacman -S yt-dlp ffmpeg mpv deno # Arch
./install.sh # builds and installs to ~/.local
```
`audiphi 'https://…'` fetches the link straight away.
## Spotify
Without keys Spotify's public page lists the first 100 songs of a playlist. With free app keys
(<https://developer.spotify.com/dashboard>, pasted in **Settings › Spotify**) Audiphi uses the Web API.
Since Spotify's February 2026 changes the API only shows playlists the app owner owns or collaborates
on, has no artist top songs, and needs the owner to have Premium — whenever the API can't answer (or the
keys are wrong) Audiphi falls back to the public page instead of failing.
## Development
`src/core` is the engine (resolvers, matcher, metadata, lyrics, tagger, downloader); `src/ui` the widgets and
pages; `examples/probe.rs` exercises the engine from the command line
(`cargo run --example probe -- resolve <link>` / `download <link>` / `meta <title> <artist>`).
Setting `AUDIPHI_SHOTS=/dir` (and `AUDIPHI_SHOT_URL=<link>`) makes the app walk its tabs and save screenshots.
Built on yt-dlp, ffmpeg, mpv, lofty and egui. Tags from Deezer, iTunes and MusicBrainz; lyrics from LRCLIB.
Bundled fonts: Material Symbols (Apache 2.0) and Rubik (SIL OFL 1.1), licenses in `assets/fonts/`.

20
assets/audiphi.svg Normal file
View file

@ -0,0 +1,20 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#cdbdff"/>
<stop offset="1" stop-color="#6b52c8"/>
</linearGradient>
<linearGradient id="shine" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#ffffff" stop-opacity="0.35"/>
<stop offset="1" stop-color="#ffffff" stop-opacity="0"/>
</linearGradient>
</defs>
<!-- 9-lobed "cookie" shape from Material 3 Expressive -->
<path fill="url(#bg)" d="M128 10c14 0 22 12 34 15s25-3 35 5 8 21 14 32 19 15 22 28-7 22-7 38 10 25 7 38-16 17-22 28-4 24-14 32-23 2-35 5-20 15-34 15-22-12-34-15-25 3-35-5-8-21-14-32-19-15-22-28 7-22 7-38-10-25-7-38 16-17 22-28 4-24 14-32 23-2 35-5 20-15 34-15z"/>
<path fill="url(#shine)" d="M128 10c14 0 22 12 34 15s25-3 35 5 8 21 14 32 19 15 22 28c-30-18-66-28-105-28S58 72 28 90c3-13 16-17 22-28s4-24 14-32 23-2 35-5 20-15 29-15z"/>
<!-- music note -->
<path fill="#1d1236" d="M150 58v86.5a26 26 0 1 1-14-23V82l-34 8v66.5a26 26 0 1 1-14-23V78z" transform="translate(-6 -2)"/>
<!-- download arrow badge -->
<circle cx="178" cy="178" r="40" fill="#1d1236"/>
<path fill="#e9ddff" d="M170 156h16v24h12l-20 22-20-22h12z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View file

@ -0,0 +1,93 @@
Copyright 2015 The Rubik Project Authors (https://github.com/googlefonts/rubik)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

BIN
assets/fonts/Rubik.ttf Normal file

Binary file not shown.

53
examples/probe.rs Normal file
View file

@ -0,0 +1,53 @@
//! Command-line probe of the core: `cargo run --example probe -- resolve <url|text> [top|discography]`
//! or `... download <url|text>` to run the whole pipeline into /tmp.
use audiphi::core::{downloader::*, models::*, resolvers, settings::Settings};
use std::sync::{mpsc, Arc};
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let mut snap = Settings::load().snapshot();
if let Ok(id) = std::env::var("SPOT_ID") { snap["spotify"]["client_id"] = id.into(); snap["spotify"]["client_secret"] = std::env::var("SPOT_SECRET").unwrap_or_default().into(); }
let log = |k: &str, t: &str| eprintln!("[{k}] {t}");
match args[0].as_str() {
"resolve" | "download" => {
let mode = args.get(2).map(|s| s.as_str()).unwrap_or("top");
let r = match resolvers::resolve(&args[1], &snap, &log, mode) {
Ok(r) => r,
Err(e) => { println!("ERROR: {e}"); std::process::exit(1) }
};
println!("{} | {} | {} | {} tracks | service {} | note: {}", r.kind, r.title, r.subtitle, r.tracks.len(), r.service, r.note);
for t in r.tracks.iter().take(6) {
println!(" - {} – {} [{}] {:?}s isrc={} dl={} cover={}", t.artist(), t.title, t.album, t.duration, t.isrc, !t.download_url.is_empty(), !t.cover_url.is_empty());
}
if args[0] == "download" {
let (tx, rx) = mpsc::channel();
let mut m = Manager::new(2, tx, Arc::new(|| {}));
let o = DownloadOptions { output_dir: "/tmp/audiphi-test".into(), template: "{artist} - {title}".into(), format: args.get(3).cloned().unwrap_or("mp3".into()), bitrate: "192".into(), sample_rate: "source".into(), bit_depth: "16".into(), lyrics: "synced".into(), save_lrc: true, collection_folder: false };
let n = r.tracks.len().min(1);
m.enqueue(&r.tracks[..n], &o, &snap);
loop {
while let Ok(l) = rx.try_recv() { if l.kind != "progress" { eprintln!("[{}] {}", l.kind, l.text); } }
if m.counts().0 == 0 { break; }
std::thread::sleep(std::time::Duration::from_millis(200));
}
while let Ok(l) = rx.try_recv() { eprintln!("[{}] {}", l.kind, l.text); }
for h in &m.jobs { let j = h.job.lock().unwrap(); println!("{:?} {} {}", j.state, j.status, j.output_path); }
}
}
"meta" => {
let mut t = Track::new();
t.title = args[1].clone();
t.artists = vec![args[2].clone()];
let r = audiphi::core::metadata::search_all(&t, &["deezer".into(), "itunes".into(), "musicbrainz".into()], 1200, &log);
for (k, v) in r {
println!("{k}: {} candidates", v.len());
for c in v.iter().take(2) {
println!(" {:.2} {} – {} [{}] {} #{:?}/{:?} {} cover={}", c.score, c.artist(), c.title, c.album, c.year, c.track_number, c.track_total, c.genre, !c.cover_url.is_empty());
}
}
let l = audiphi::core::lyrics::fetch(&args[1], &args[2], "", Some(213.0));
println!("lyrics: {:?}", l.map(|l| (l.plain.len(), l.synced.len(), l.instrumental)));
}
_ => {}
}
}

10
install.sh Executable file
View file

@ -0,0 +1,10 @@
#!/bin/sh
# Builds Audiphi and installs it for the current user (~/.local), with an app-menu entry.
set -e
cd "$(dirname "$0")"
PREFIX="${PREFIX:-$HOME/.local}"
cargo build --release
install -Dm755 target/release/audiphi "$PREFIX/bin/audiphi"
install -Dm644 assets/audiphi.svg "$PREFIX/share/icons/hicolor/scalable/apps/audiphi.svg"
install -Dm644 packaging/audiphi.desktop "$PREFIX/share/applications/audiphi.desktop"
echo "Installed to $PREFIX/bin/audiphi (needs yt-dlp, ffmpeg, mpv's libmpv and, for YouTube, deno)."

View file

@ -0,0 +1,9 @@
[Desktop Entry]
Type=Application
Name=Audiphi
Comment=Music downloader and quick player for any music service
Exec=audiphi %U
Icon=audiphi
Categories=AudioVideo;Audio;Player;Network;
Terminal=false
StartupWMClass=audiphi

692
src/app.rs Normal file
View file

@ -0,0 +1,692 @@
//! The application: state, background events, and the window chrome (tabs, banners, snackbar).
use crate::core::downloader::{LogLine, Manager};
use crate::core::library::{self, LibraryItem};
use crate::core::lyrics::Lyrics;
use crate::core::metadata::Candidate;
use crate::core::models::ResolveResult;
use crate::core::settings::Settings;
use crate::core::{paths, ytdlp};
use crate::player::Player;
use crate::ui::controls::*;
use crate::ui::gfx::*;
use crate::ui::icons::Icons;
use crate::ui::images::Images;
use crate::ui::pages::{download, editor, player_page, queue, settings_page};
use crate::ui::theme::{with_alpha, Theme};
use crate::ui::widgets::*;
use eframe::egui::{self, Align2, Color32, Pos2, Rect, RichText, Sense, Vec2};
use std::collections::BTreeMap;
use std::sync::mpsc::{channel, Receiver, Sender};
use std::sync::Arc;
use std::time::{Duration, Instant};
pub const TAB_DOWNLOAD: usize = 0;
pub const TAB_QUEUE: usize = 1;
pub const TAB_PLAYER: usize = 2;
pub const TAB_SETTINGS: usize = 3;
pub enum Ev {
Resolved(u64, Result<ResolveResult, String>),
FetchInfo(u64, String),
Library(Vec<LibraryItem>),
LyricsFound(String, Result<Option<String>, String>),
Candidates(Result<BTreeMap<String, Vec<Candidate>>, String>),
EditorLyrics(Result<Lyrics, String>),
EditorCover(Option<Vec<u8>>),
SpotifyTest(String),
YtdlpUpdate(String),
Toast(String),
Log(u64, String, String),
}
pub struct LogEntry {
pub job: u64,
pub kind: String,
pub text: String,
}
pub struct Toast {
pub text: String,
pub action: Option<(String, usize)>,
pub at: Instant,
}
pub struct Confirm {
pub title: String,
pub text: String,
pub ok: String,
}
pub struct App {
pub ctx: egui::Context,
pub g: Gfx,
pub settings: Settings,
pub images: Images,
pub tab: usize,
pub tx: Sender<Ev>,
rx: Receiver<Ev>,
pub manager: Manager,
log_rx: Receiver<LogLine>,
pub logs: Vec<LogEntry>,
pub dl: download::State,
pub q: queue::State,
pub pl: player_page::State,
pub st: settings_page::State,
pub player: Player,
pub editor: Option<editor::Editor>,
pub confirm: Option<Confirm>,
pub toast: Option<Toast>,
cover_seed: Option<Color32>,
seed_key: String,
theme_rev: u64,
sys_mtime: Option<std::time::SystemTime>,
last_check: Instant,
last_frame: Instant,
pub quit_asked: bool,
pub quitting: bool,
pub ffmpeg_ok: bool,
pub ytdlp_ok: bool,
shots: Option<Shots>,
}
pub fn apply_visuals(ctx: &egui::Context, t: &Theme) {
let mut v = if t.dark { egui::Visuals::dark() } else { egui::Visuals::light() };
v.panel_fill = t.surface;
v.window_fill = t.surface_container;
v.extreme_bg_color = t.surface_container_highest;
v.faint_bg_color = t.surface_container_low;
v.code_bg_color = t.surface_container_high;
v.override_text_color = Some(t.on_surface);
v.hyperlink_color = t.primary;
v.selection.bg_fill = t.primary;
v.selection.stroke = egui::Stroke::new(1.0, t.on_primary);
v.window_stroke = egui::Stroke::new(1.0, with_alpha(t.outline_variant, 0.6));
v.window_corner_radius = cr(24.0);
v.menu_corner_radius = cr(14.0);
v.popup_shadow = egui::Shadow { offset: [0, 6], blur: 24, spread: 0, color: Color32::from_black_alpha(90) };
v.window_shadow = egui::Shadow { offset: [0, 10], blur: 40, spread: 0, color: Color32::from_black_alpha(110) };
let w = &mut v.widgets;
for (wd, bg) in [(&mut w.noninteractive, t.surface), (&mut w.inactive, t.surface_container_high), (&mut w.hovered, t.surface_container_highest), (&mut w.active, t.surface_container_highest), (&mut w.open, t.surface_container_highest)] {
wd.bg_fill = bg;
wd.weak_bg_fill = bg;
wd.fg_stroke.color = t.on_surface;
wd.corner_radius = cr(10.0);
wd.bg_stroke = egui::Stroke::NONE;
}
w.noninteractive.bg_stroke = egui::Stroke::new(1.0, t.outline_variant);
ctx.set_visuals(v);
ctx.global_style_mut(|s| {
s.spacing.item_spacing = egui::vec2(8.0, 6.0);
s.spacing.button_padding = egui::vec2(14.0, 7.0);
s.spacing.scroll = egui::style::ScrollStyle { floating: true, bar_width: 8.0, floating_width: 4.0, floating_allocated_width: 0.0, foreground_color: false, dormant_background_opacity: 0.0, active_background_opacity: 0.2, interact_background_opacity: 0.35, dormant_handle_opacity: 0.35, active_handle_opacity: 0.55, interact_handle_opacity: 0.8, ..egui::style::ScrollStyle::floating() };
s.interaction.tooltip_delay = 0.4;
});
}
impl App {
pub fn new(cc: &eframe::CreationContext<'_>, url: Option<String>) -> App {
let ctx = cc.egui_ctx.clone();
ctx.set_missing_glyph_policy(eframe::epaint::text::MissingGlyphPolicy::Tofu);
crate::ui::fonts::install(&ctx);
let settings = Settings::load();
let snap = settings.snapshot();
let theme = Theme::build(&snap, None);
apply_visuals(&ctx, &theme);
let g = Gfx { theme, icons: Icons::default(), ctx: ctx.clone() };
let (tx, rx) = channel();
let (log_tx, log_rx) = channel();
let repaint_ctx = ctx.clone();
let manager = Manager::new(settings.get_i64("download.concurrent").max(1) as usize, log_tx, Arc::new(move || repaint_ctx.request_repaint()));
let player = Player::new(&ctx, &settings);
let mut app = App {
images: Images::new(&ctx),
tab: (settings.get_i64("ui.last_tab").clamp(0, 3)) as usize,
dl: download::State::new(&settings),
q: queue::State::default(),
pl: player_page::State::default(),
st: settings_page::State::default(),
player,
editor: None,
confirm: None,
toast: None,
cover_seed: None,
seed_key: String::new(),
theme_rev: settings.revision,
sys_mtime: crate::ui::theme::system_mtime(),
last_check: Instant::now(),
last_frame: Instant::now(),
quit_asked: false,
quitting: false,
ffmpeg_ok: paths::find_ffmpeg(&settings.get_str("download.ffmpeg_path")).is_some(),
ytdlp_ok: paths::find_ytdlp().is_some(),
shots: std::env::var_os("AUDIPHI_SHOTS").map(|d| Shots { dir: d.into(), step: 0, started: Instant::now(), wait_until: 0.0, pending: None }),
logs: vec![],
manager,
log_rx,
tx,
rx,
settings,
g,
ctx,
};
app.rescan_library();
if let Some(u) = url {
app.open_url(&u);
}
app
}
// ---- helpers used by the pages --------------------------------------------------
pub fn toast(&mut self, text: impl Into<String>) {
self.toast = Some(Toast { text: text.into(), action: None, at: Instant::now() });
}
pub fn toast_action(&mut self, text: impl Into<String>, label: &str, tab: usize) {
self.toast = Some(Toast { text: text.into(), action: Some((label.into(), tab)), at: Instant::now() });
}
pub fn open_url(&mut self, url: &str) {
self.tab = TAB_DOWNLOAD;
self.dl.query = url.to_string();
download::fetch(self, "top");
}
pub fn rescan_library(&mut self) {
let dir = self.settings.library_dir();
let tx = self.tx.clone();
let ctx = self.ctx.clone();
self.pl.scanning = true;
std::thread::spawn(move || {
let _ = tx.send(Ev::Library(library::scan(&dir)));
ctx.request_repaint();
});
}
pub fn log(&mut self, job: u64, kind: &str, text: &str) {
self.logs.push(LogEntry { job, kind: kind.into(), text: text.into() });
if self.logs.len() > 6000 {
self.logs.drain(..1000);
}
}
pub fn play_file(&mut self, path: &str) {
self.tab = TAB_PLAYER;
let items = self.pl.visible_items();
self.player.set_queue(&items);
self.player.play_path(path);
}
pub fn edit_file(&mut self, path: &str) {
if !std::path::Path::new(path).is_file() {
self.toast("That file isn't there anymore");
return;
}
self.editor = Some(editor::Editor::for_file(path));
}
/// Run `work` on a thread and deliver its result as an event.
pub fn spawn<T: Send + 'static>(&self, work: impl FnOnce() -> T + Send + 'static, wrap: impl FnOnce(T) -> Ev + Send + 'static) {
let (tx, ctx) = (self.tx.clone(), self.ctx.clone());
std::thread::spawn(move || {
let v = work();
let _ = tx.send(wrap(v));
ctx.request_repaint();
});
}
// ---- events ----------------------------------------------------------------------
fn pump(&mut self) {
self.images.pump();
while let Ok(l) = self.log_rx.try_recv() {
self.log(l.job, &l.kind, &l.text);
}
while let Ok(ev) = self.rx.try_recv() {
match ev {
Ev::Resolved(token, r) => download::resolved(self, token, r),
Ev::FetchInfo(token, text) => {
if token == self.dl.token {
self.dl.detail = text;
}
}
Ev::Library(items) => {
self.pl.scanning = false;
self.pl.set_items(items);
let v = self.pl.visible_items();
self.player.set_queue(&v);
}
Ev::LyricsFound(path, r) => player_page::lyrics_found(self, &path, r),
Ev::Candidates(r) => {
if let Some(e) = &mut self.editor {
e.lookup_busy = false;
match r {
Ok(c) => e.candidates = Some(c),
Err(m) => e.error = m,
}
}
}
Ev::EditorLyrics(r) => {
if let Some(e) = &mut self.editor {
e.lyrics_busy = false;
match r {
Ok(l) if l.instrumental => e.lyrics_state = "LRCLIB lists this as instrumental".into(),
Ok(l) if l.found() => {
e.lyrics = if l.synced.is_empty() { l.plain } else { l.synced };
e.lyrics_touched = true;
}
Ok(_) => e.lyrics_state = "Nothing on LRCLIB for this song".into(),
Err(m) => e.lyrics_state = format!("Lookup failed: {m}"),
}
}
}
Ev::EditorCover(bytes) => {
if let Some(e) = &mut self.editor {
if let Some(b) = bytes {
e.set_cover(&mut self.images, b, true);
}
}
}
Ev::SpotifyTest(m) => {
self.st.spotify_status = m;
self.st.spotify_busy = false;
}
Ev::YtdlpUpdate(m) => {
self.st.ytdlp_note = m;
self.st.ytdlp_busy = false;
self.ytdlp_ok = paths::find_ytdlp().is_some();
}
Ev::Toast(t) => self.toast(t),
Ev::Log(job, kind, text) => self.log(job, &kind, &text),
}
}
}
fn check_theme(&mut self) {
let mut rebuild = false;
if self.theme_rev != self.settings.revision {
self.theme_rev = self.settings.revision;
rebuild = true;
}
if self.last_check.elapsed() > Duration::from_secs(2) {
self.last_check = Instant::now();
let m = crate::ui::theme::system_mtime();
if m != self.sys_mtime {
self.sys_mtime = m;
rebuild = true;
}
}
// follow the album art of what's playing
let key = self.player.cover_key.clone();
if key != self.seed_key {
if let Some(c) = self.images.accent(&key) {
self.seed_key = key;
self.cover_seed = Some(c);
rebuild = true;
} else if self.images.get(&key).is_some() {
self.seed_key = key;
}
}
if rebuild {
let t = Theme::build(&self.settings.snapshot(), self.cover_seed);
if !t.same_colors(&self.g.theme) || t.source != self.g.theme.source {
apply_visuals(&self.ctx, &t);
self.g.theme = t;
}
}
}
fn shortcuts(&mut self, ctx: &egui::Context) {
let typing = ctx.egui_wants_keyboard_input();
let (ctrl, keys, pasted): (bool, Vec<egui::Key>, Option<String>) = ctx.input(|i| {
let keys = i.events.iter().filter_map(|e| if let egui::Event::Key { key, pressed: true, modifiers, .. } = e { if modifiers.command || !modifiers.any() { Some(*key) } else { None } } else { None }).collect();
let pasted = i.events.iter().find_map(|e| if let egui::Event::Paste(s) = e { Some(s.clone()) } else { None });
(i.modifiers.command, keys, pasted)
});
for k in keys {
if ctrl {
match k {
egui::Key::Num1 => self.tab = 0,
egui::Key::Num2 => self.tab = 1,
egui::Key::Num3 => self.tab = 2,
egui::Key::Num4 => self.tab = 3,
egui::Key::L | egui::Key::F => {
self.tab = TAB_DOWNLOAD;
self.dl.focus_query = true;
}
egui::Key::Backtick => {
let v = !self.settings.get_bool("ui.show_terminal");
self.settings.set_bool("ui.show_terminal", v);
}
_ => {}
}
} else if k == egui::Key::Space && !typing && !self.player.path.is_empty() {
self.player.toggle();
}
}
if let (Some(text), false) = (pasted, typing) {
let t = text.trim();
if !t.is_empty() {
self.tab = TAB_DOWNLOAD;
self.dl.query = t.to_string();
download::fetch(self, "top");
}
}
}
fn handle_drops(&mut self, ctx: &egui::Context) {
let dropped = ctx.input(|i| i.raw.dropped_files.clone());
for f in dropped {
let p = f.path();
if paths::is_audio(p) {
self.play_file(&p.to_string_lossy());
return;
}
}
}
}
impl eframe::App for App {
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let now = Instant::now();
let dt = now.duration_since(self.last_frame).as_secs_f32().clamp(1.0 / 240.0, 0.1);
self.last_frame = now;
self.pump();
self.drive_shots(ctx);
self.handle_drops(ctx);
self.shortcuts(ctx);
self.check_theme();
self.settings.save_if_due();
let moving = self.player.tick();
if self.settings.get_bool("player.visualizer") && self.tab == TAB_PLAYER {
let n = self.settings.get_i64("player.visualizer_bars").clamp(16, 128) as usize;
let (pos, active) = (self.player.pos, self.player.playing);
self.player.spectrum.update(pos, n, active, dt);
}
if self.player.track_changed {
self.player.track_changed = false;
let key = self.player.cover_key.clone();
self.images.forget(&key);
self.images.request(&key, || crate::ui::images::Source::File(self.player.path.clone()), 900);
player_page::on_track_changed(self);
}
if let Some((done, failed)) = self.manager.poll_all_done() {
let text = format!("Downloads finished: {done} saved{}", if failed > 0 { format!(", {failed} failed") } else { String::new() });
self.toast_action(text.clone(), "Show", TAB_QUEUE);
if !ctx.input(|i| i.focused) {
let _ = std::process::Command::new("notify-send").args(["-a", crate::APP_NAME, &format!("{}", crate::APP_NAME), &text]).spawn();
}
self.rescan_library();
}
if let Some(t) = &self.toast {
if t.at.elapsed() > Duration::from_secs(6) {
self.toast = None;
}
}
if ctx.input(|i| i.viewport().close_requested()) && !self.quitting {
let active = self.manager.counts().0;
if active > 0 && !self.quit_asked {
ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
self.confirm = Some(Confirm { title: "Quit while downloading?".into(), text: format!("{active} download{} still running and will stop.", if active == 1 { " is" } else { "s are" }), ok: "Quit".into() });
} else {
self.quitting = true;
self.manager.cancel_all();
self.settings.set("ui.last_tab", serde_json::json!(self.tab));
self.settings.save();
self.player.stop();
}
}
if moving {
ctx.request_repaint_after(Duration::from_millis(16));
}
}
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
let ctx = ui.ctx().clone();
let t = self.g.theme.clone();
egui::Panel::top("tabs").frame(egui::Frame::NONE.fill(t.surface).inner_margin(egui::Margin { left: 16, right: 16, top: 10, bottom: 4 })).show_separator_line(false).show(ui, |ui| {
self.draw_tabs(ui);
self.draw_banners(ui);
});
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(t.surface)).show(ui, |ui| {
match self.tab {
TAB_DOWNLOAD => download::draw(self, ui),
TAB_QUEUE => queue::draw(self, ui),
TAB_PLAYER => player_page::draw(self, ui),
_ => settings_page::draw(self, ui),
}
});
self.draw_toast(&ctx);
self.draw_confirm(&ctx);
editor::show(self, &ctx);
if self.images.loading() {
ctx.request_repaint_after(Duration::from_millis(100));
}
}
fn on_exit(&mut self, _gl: Option<&eframe::glow::Context>) {
self.manager.cancel_all();
self.settings.set("ui.last_tab", serde_json::json!(self.tab));
self.settings.save();
self.player.stop();
}
}
impl App {
fn draw_tabs(&mut self, ui: &mut egui::Ui) {
let labels = [("download", "Download"), ("downloading", "Downloads"), ("play_circle", "Player"), ("settings", "Settings")];
let active = self.manager.counts().0;
ui.horizontal(|ui| {
let (rect, _) = ui.allocate_exact_size(Vec2::new(150.0, 40.0), Sense::hover());
let t = self.g.theme.clone();
self.g.icon_at(ui.painter(), Pos2::new(rect.left() + 16.0, rect.center().y), 26.0, "library_music_fill", t.primary);
ui.painter().text(Pos2::new(rect.left() + 38.0, rect.center().y), Align2::LEFT_CENTER, crate::APP_NAME, disp_semi(21.0), t.on_surface);
let total: f32 = 4.0 * 128.0;
let left = ((ui.available_width() - total) / 2.0).max(0.0);
ui.add_space(left);
for (i, (icon, label)) in labels.iter().enumerate() {
let sel = self.tab == i;
let (rect, resp) = ui.allocate_exact_size(Vec2::new(122.0, 40.0), Sense::click());
let t = &self.g.theme;
let hover = ui.ctx().animate_bool_with_time(resp.id.with("h"), resp.hovered(), 0.12);
let anim = ui.ctx().animate_bool_with_time(resp.id.with("s"), sel, 0.18);
let bg = mix_c(with_alpha(t.on_surface, hover * 0.06), t.secondary_container, anim);
ui.painter().rect_filled(rect, cr(20.0), bg);
let fg = mix_c(t.on_surface_variant, t.on_secondary_container, anim);
let fnt = if sel { font_semi(14.5) } else { font(14.5) };
let tw = ui.painter().layout_no_wrap(label.to_string(), fnt.clone(), Color32::WHITE).size().x;
let x0 = rect.center().x - (tw + 28.0) / 2.0;
self.g.icon(ui.painter(), Rect::from_center_size(Pos2::new(x0 + 10.0, rect.center().y), Vec2::splat(20.0)), if sel && i == 2 { "play_circle_fill" } else { icon }, fg);
ui.painter().text(Pos2::new(x0 + 28.0, rect.center().y), Align2::LEFT_CENTER, label, fnt, fg);
if i == TAB_QUEUE && active > 0 {
let c = Pos2::new(rect.right() - 12.0, rect.top() + 9.0);
ui.painter().circle_filled(c, 9.0, self.g.theme.primary);
ui.painter().text(c, Align2::CENTER_CENTER, active.min(99).to_string(), font_semi(11.0), self.g.theme.on_primary);
}
if resp.hovered() {
ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand);
}
if resp.clicked() {
self.tab = i;
}
}
});
}
fn draw_banners(&mut self, ui: &mut egui::Ui) {
let mut msgs = vec![];
if !self.ffmpeg_ok {
msgs.push("ffmpeg wasn't found. Downloads need it to convert audio — install it (e.g. “sudo pacman -S ffmpeg”) or set its location in Settings.");
}
if !self.ytdlp_ok {
msgs.push("yt-dlp wasn't found. Install it (e.g. “sudo pacman -S yt-dlp”) so Audiphi can download.");
}
for m in msgs {
let t = self.g.theme.clone();
ui.add_space(6.0);
let mut go = false;
egui::Frame::NONE.fill(t.error_container).corner_radius(cr(16.0)).inner_margin(egui::Margin::symmetric(16, 10)).show(ui, |ui| {
ui.horizontal(|ui| {
let (r, _) = ui.allocate_exact_size(Vec2::splat(22.0), Sense::hover());
self.g.icon(ui.painter(), r, "warning", t.on_error_container);
ui.label(RichText::new(m).color(t.on_error_container));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
go = button_h(ui, &mut self.g, None, "Settings", Kind::Text, 32.0).clicked();
});
});
});
if go {
self.tab = TAB_SETTINGS;
}
}
}
fn draw_toast(&mut self, ctx: &egui::Context) {
let Some(t) = self.toast.as_ref().map(|t| (t.text.clone(), t.action.clone())) else { return };
let th = self.g.theme.clone();
let mut act = None;
let mut close = false;
egui::Area::new(egui::Id::new("toast")).order(egui::Order::Foreground).anchor(Align2::CENTER_BOTTOM, Vec2::new(0.0, -86.0)).show(ctx, |ui| {
egui::Frame::NONE.fill(th.inverse_surface).corner_radius(cr(12.0)).inner_margin(egui::Margin::symmetric(18, 8)).shadow(egui::Shadow { offset: [0, 4], blur: 14, spread: 0, color: Color32::from_black_alpha(80) }).show(ui, |ui| {
ui.horizontal(|ui| {
ui.label(RichText::new(&t.0).color(th.inverse_on_surface).size(14.0));
if let Some((label, tab)) = &t.1 {
if ui.add(egui::Button::new(RichText::new(label).color(th.primary_container).strong()).frame(false)).clicked() {
act = Some(*tab);
}
}
if ui.add(egui::Button::new(RichText::new("✕").color(th.inverse_on_surface)).frame(false)).clicked() {
close = true;
}
});
});
});
if let Some(tab) = act {
self.tab = tab;
self.toast = None;
}
if close {
self.toast = None;
}
ctx.request_repaint_after(Duration::from_millis(500));
}
fn draw_confirm(&mut self, ctx: &egui::Context) {
let Some(c) = self.confirm.as_ref().map(|c| (c.title.clone(), c.text.clone(), c.ok.clone())) else { return };
let (mut ok, mut cancel) = (false, ctx.input(|i| i.key_pressed(egui::Key::Escape)));
let fr = egui::Frame::NONE.fill(self.g.theme.surface_container_high).corner_radius(cr(28.0)).inner_margin(egui::Margin::same(24));
egui::Modal::new(egui::Id::new("confirm")).frame(fr).backdrop_color(Color32::from_black_alpha(130)).show(ctx, |ui| {
ui.set_width(380.0);
ui.label(RichText::new(&c.0).font(disp_semi(20.0)).color(self.g.theme.on_surface));
ui.add_space(6.0);
ui.label(RichText::new(&c.1).color(self.g.theme.on_surface_variant));
ui.add_space(14.0);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ok = button(ui, &mut self.g, None, &c.2, Kind::Danger).clicked();
cancel |= button(ui, &mut self.g, None, "Cancel", Kind::Text).clicked();
});
});
if ok {
self.confirm = None;
self.quit_asked = true;
self.ctx.send_viewport_cmd(egui::ViewportCommand::Close);
} else if cancel {
self.confirm = None;
}
}
pub fn check_ytdlp_now(&mut self) -> Option<String> {
ytdlp::version()
}
}
/// Hidden test harness: `AUDIPHI_SHOTS=/dir AUDIPHI_SHOT_URL=<link>` walks the tabs, saving screenshots.
struct Shots {
dir: std::path::PathBuf,
step: usize,
started: Instant,
wait_until: f64,
pending: Option<Arc<std::sync::atomic::AtomicBool>>,
}
impl App {
fn drive_shots(&mut self, ctx: &egui::Context) {
let Some(mut sh) = self.shots.take() else { return };
let now = sh.started.elapsed().as_secs_f64();
if let Some(flag) = &sh.pending {
if flag.load(std::sync::atomic::Ordering::Relaxed) {
sh.pending = None;
}
}
if sh.pending.is_none() && now >= sh.wait_until {
let shoot = |sh: &mut Shots, name: &str| {
let flag = Arc::new(std::sync::atomic::AtomicBool::new(false));
sh.pending = Some(flag.clone());
let path = sh.dir.join(format!("{name}.png"));
let _ = std::fs::create_dir_all(&sh.dir);
let name = name.to_string();
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::ScreenshotCallback::new(move |img| {
let mut out = image::RgbaImage::new(img.width() as u32, img.height() as u32);
for (i, p) in img.pixels.iter().enumerate() {
out.put_pixel((i % img.width()) as u32, (i / img.width()) as u32, image::Rgba([p.r(), p.g(), p.b(), 255]));
}
let _ = out.save(&path);
eprintln!("shot {name}");
flag.store(true, std::sync::atomic::Ordering::Relaxed);
})));
};
match sh.step {
0 => { if now > 2.0 { shoot(&mut sh, "1-download-empty"); sh.step = 1; } }
1 => {
if let Ok(u) = std::env::var("AUDIPHI_SHOT_URL") {
self.dl.query = u;
download::fetch(self, "top");
}
sh.step = 2;
sh.wait_until = now + 1.0;
}
2 => {
if self.dl.result.is_some() || self.dl.error.is_some() || now > 60.0 {
sh.wait_until = now + 1.5;
sh.step = 3;
}
}
3 => { shoot(&mut sh, "2-download-result"); sh.step = 4; }
4 => {
if self.dl.result.is_some() {
self.editor = Some(editor::Editor::for_track(self.dl.result.as_ref().unwrap(), None));
sh.wait_until = now + 1.5;
}
sh.step = 5;
}
5 => { shoot(&mut sh, "3-editor"); sh.step = 6; }
6 => {
self.editor = None;
download::start_download_pub(self);
self.tab = TAB_QUEUE;
self.settings.set_bool("ui.show_terminal", true);
sh.wait_until = now + 25.0;
sh.step = 7;
}
7 => { shoot(&mut sh, "4-queue"); sh.step = 8; }
8 => {
self.tab = TAB_PLAYER;
if let Some(p) = self.pl.visible_items().first().map(|i| i.path.clone()) {
self.play_file(&p);
}
sh.wait_until = now + 4.0;
sh.step = 9;
}
9 => { shoot(&mut sh, "5-player"); sh.step = 10; }
10 => { self.tab = TAB_SETTINGS; sh.wait_until = now + 1.0; sh.step = 11; }
11 => { shoot(&mut sh, "6-settings"); sh.step = 12; }
_ => { if sh.pending.is_none() { ctx.send_viewport_cmd(egui::ViewportCommand::Close); self.quit_asked = true; } }
}
}
self.shots = Some(sh);
ctx.request_repaint_after(Duration::from_millis(100));
}
}

65
src/core/covers.rs Normal file
View file

@ -0,0 +1,65 @@
//! Cover art: download, crop video thumbnails to a square, resize, re-encode as JPEG.
use super::http;
use image::{DynamicImage, GenericImageView};
pub fn fetch(url: &str) -> Option<Vec<u8>> {
if url.is_empty() {
return None;
}
match http::get_bytes(url) {
Ok(b) => Some(b),
// YouTube's maxres thumbnail is missing for some videos; try the smaller one.
Err(_) if url.contains("maxresdefault") => http::get_bytes(&url.replace("maxresdefault", "hqdefault")).ok(),
Err(_) => None,
}
}
/// hqdefault thumbnails are 4:3 with black bars around a 16:9 picture.
fn trim_letterbox(img: DynamicImage) -> DynamicImage {
let (w, h) = img.dimensions();
if w == 0 || h == 0 || ((w as f64 / h as f64) - 4.0 / 3.0).abs() > 0.02 {
return img;
}
let bar = ((h as f64 - w as f64 * 9.0 / 16.0) / 2.0).round() as u32;
if bar <= 2 || bar * 2 >= h {
return img;
}
let rgb = img.to_rgb8();
let bright = |x: u32, y: u32| {
let p = rgb.get_pixel(x, y);
p[0].max(p[1]).max(p[2])
};
let step = (w / 16).max(1) as usize;
let dark = (0..w).step_by(step).all(|x| bright(x, 1) < 24 && bright(x, bar - 2) < 24);
if dark {
img.crop_imm(0, bar, w, h - 2 * bar)
} else {
img
}
}
pub fn jpeg(img: &DynamicImage, quality: u8) -> Vec<u8> {
let mut out = Vec::new();
let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality);
let _ = img.to_rgb8().write_with_encoder(enc);
out
}
/// (jpeg_bytes, mime), or None when the data isn't an image.
pub fn process(data: &[u8], max_size: u32, square: bool) -> Option<(Vec<u8>, String)> {
let mut img = image::load_from_memory(data).ok()?;
img = trim_letterbox(img);
let (w, h) = img.dimensions();
if square && w != h {
let side = w.min(h);
// Only crop pictures that are clearly not square (video thumbnails).
if w.max(h) as f64 / side as f64 > 1.05 {
img = img.crop_imm((w - side) / 2, (h - side) / 2, side, side);
}
}
if max_size > 0 && img.width().max(img.height()) > max_size {
img = img.resize(max_size, max_size, image::imageops::FilterType::Lanczos3);
}
Some((jpeg(&img, 92), "image/jpeg".into()))
}

777
src/core/downloader.rs Normal file
View file

@ -0,0 +1,777 @@
//! The download pipeline and the queue that runs it.
//!
//! For each job: get full info -> find a match if the service can't be downloaded -> look up tags ->
//! pick the final name -> download with yt-dlp -> convert with ffmpeg -> cover art -> lyrics ->
//! write tags -> move into place.
use super::models::*;
use super::resolvers::{service_name, track_from_info};
use super::settings::{get_bool, get_i64, get_str};
use super::template::{render, track_values};
use super::textutil::*;
use super::{covers, lyrics, matcher, metadata, paths, tagger, ytdlp};
use serde_json::Value;
use std::collections::VecDeque;
use std::io::{BufRead, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::mpsc::Sender;
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
pub type Choices = &'static [(&'static str, &'static str)];
/// (key, label, bitrate choices). Numbers above 10 are kbps, 0-9 are VBR quality levels.
pub const FORMATS: &[(&str, &str, Choices)] = &[
("mp3", "MP3", &[("320", "320 kbps"), ("256", "256 kbps"), ("224", "224 kbps"), ("192", "192 kbps"), ("160", "160 kbps"), ("128", "128 kbps"), ("96", "96 kbps"), ("64", "64 kbps"), ("0", "V0 · VBR ~245 kbps"), ("2", "V2 · VBR ~190 kbps"), ("4", "V4 · VBR ~165 kbps")]),
("m4a", "M4A · AAC", &[("256", "256 kbps"), ("192", "192 kbps"), ("160", "160 kbps"), ("128", "128 kbps"), ("96", "96 kbps")]),
("opus", "Opus", &[("256", "256 kbps"), ("192", "192 kbps"), ("160", "160 kbps"), ("128", "128 kbps"), ("96", "96 kbps"), ("64", "64 kbps"), ("48", "48 kbps")]),
("vorbis", "OGG Vorbis", &[("320", "320 kbps"), ("256", "256 kbps"), ("192", "192 kbps"), ("160", "160 kbps"), ("128", "128 kbps"), ("96", "96 kbps")]),
("flac", "FLAC · lossless", &[]),
("alac", "ALAC · Apple lossless", &[]),
("wav", "WAV · uncompressed", &[]),
("best", "Original · no re-encode", &[]),
];
pub const SAMPLE_RATES: Choices = &[("source", "Same as source"), ("44100", "44.1 kHz"), ("48000", "48 kHz"), ("96000", "96 kHz")];
pub const BIT_DEPTHS: Choices = &[("16", "16-bit"), ("24", "24-bit")];
pub const LOSSLESS: &[&str] = &["flac", "alac", "wav"];
pub fn format_ext(fmt: &str) -> Option<&'static str> {
Some(match fmt {
"mp3" => "mp3",
"m4a" | "alac" => "m4a",
"opus" => "opus",
"vorbis" => "ogg",
"flac" => "flac",
"wav" => "wav",
_ => return None,
})
}
pub fn bitrates_for(fmt: &str) -> Choices {
FORMATS.iter().find(|f| f.0 == fmt).map(|f| f.2).unwrap_or(&[])
}
pub fn quality_label(fmt: &str, bitrate: &str, sample_rate: &str, bit_depth: &str) -> String {
if LOSSLESS.contains(&fmt) {
let sr = SAMPLE_RATES.iter().find(|s| s.0 == sample_rate).map(|s| s.1).unwrap_or("");
return format!("{bit_depth}-bit{}", if sample_rate == "source" { String::new() } else { format!(" · {sr}") });
}
if fmt == "best" {
return "original".into();
}
let label = bitrates_for(fmt).iter().find(|b| b.0 == bitrate).map(|b| b.1).unwrap_or(bitrate);
label.split(" · ").next().unwrap_or(label).replace(" kbps", "k")
}
/// ffmpeg output options that turn any source into the chosen format and quality.
pub fn encode_args(o: &DownloadOptions) -> Vec<String> {
let (mut codec, muxer) = match o.format.as_str() {
"m4a" => ("aac", "ipod"),
"opus" => ("libopus", "opus"),
"vorbis" => ("libvorbis", "ogg"),
"flac" => ("flac", "flac"),
"alac" => ("alac", "ipod"),
"wav" => ("pcm_s16le", "wav"),
_ => ("libmp3lame", "mp3"),
};
let deep = o.bit_depth == "24";
let mut a: Vec<String> = ["-map", "0:a:0", "-vn", "-sn", "-dn", "-map_metadata", "-1"].iter().map(|s| s.to_string()).collect();
if o.format == "wav" && deep {
codec = "pcm_s24le";
}
a.extend(["-c:a".into(), codec.into()]);
let rate = if o.sample_rate.is_empty() || o.sample_rate == "source" { "" } else { &o.sample_rate };
if !rate.is_empty() && (o.format != "opus" || ["8000", "12000", "16000", "24000", "48000"].contains(&rate)) {
a.extend(["-ar".into(), rate.into()]);
}
match o.format.as_str() {
"flac" => a.extend(if deep { vec!["-sample_fmt", "s32", "-bits_per_raw_sample", "24"] } else { vec!["-sample_fmt", "s16"] }.into_iter().map(String::from)),
"alac" => a.extend(["-sample_fmt".into(), if deep { "s32p" } else { "s16p" }.into()]),
f if !LOSSLESS.contains(&f) => {
let q: i64 = o.bitrate.parse().unwrap_or(0);
if f == "mp3" && (0..=9).contains(&q) && !o.bitrate.is_empty() {
a.extend(["-q:a".into(), q.to_string()]); // LAME VBR level
} else {
let mut kbps = if q > 10 { q } else { match f { "mp3" => 320, "m4a" => 256, "opus" => 160, "vorbis" => 256, _ => 192 } };
if f == "m4a" {
kbps = kbps.min(256); // FFmpeg's AAC encoder can't go meaningfully higher
}
a.extend(["-b:a".into(), format!("{kbps}k")]);
match f {
"mp3" => a.extend(["-abr".into(), "0".into()]), // constant bitrate
"opus" => a.extend(["-vbr".into(), "constrained".into()]),
"vorbis" => a.extend(["-minrate".into(), format!("{}k", kbps / 2), "-maxrate".into(), format!("{}k", kbps * 2)]),
_ => {}
}
}
}
_ => {}
}
a.extend(["-f".into(), muxer.into()]);
a
}
#[derive(Clone)]
pub struct JobHandle {
pub uid: u64,
pub job: Arc<Mutex<Job>>,
pub cancel: Arc<AtomicBool>,
}
pub struct LogLine {
pub job: u64,
pub kind: String,
pub text: String,
}
struct Shared {
queue: Mutex<VecDeque<(JobHandle, Arc<Value>)>>,
cv: Condvar,
running: AtomicUsize,
limit: AtomicUsize,
}
pub struct Manager {
pub jobs: Vec<JobHandle>,
shared: Arc<Shared>,
log_tx: Sender<LogLine>,
notify: Arc<dyn Fn() + Send + Sync>,
was_busy: bool,
}
impl Manager {
pub fn new(concurrent: usize, log_tx: Sender<LogLine>, notify: Arc<dyn Fn() + Send + Sync>) -> Manager {
let shared = Arc::new(Shared { queue: Mutex::new(VecDeque::new()), cv: Condvar::new(), running: AtomicUsize::new(0), limit: AtomicUsize::new(concurrent.max(1)) });
for _ in 0..8 {
let (sh, tx, nf) = (shared.clone(), log_tx.clone(), notify.clone());
std::thread::spawn(move || worker_loop(sh, tx, nf));
}
Manager { jobs: vec![], shared, log_tx, notify, was_busy: false }
}
pub fn set_concurrent(&self, n: usize) {
self.shared.limit.store(n.clamp(1, 8), Ordering::Relaxed);
self.shared.cv.notify_all();
}
pub fn enqueue(&mut self, tracks: &[Track], options: &DownloadOptions, snap: &Value) -> usize {
let snap = Arc::new(snap.clone());
for t in tracks {
let job = Job { uid: next_id(), track: t.clone(), options: options.clone(), state: JobState::Queued, progress: 0.0, speed: None, eta: None, status: "Waiting".into(), error: String::new(), output_path: String::new() };
let h = JobHandle { uid: job.uid, job: Arc::new(Mutex::new(job)), cancel: Arc::new(AtomicBool::new(false)) };
self.jobs.push(h.clone());
self.shared.queue.lock().unwrap().push_back((h, snap.clone()));
}
self.shared.cv.notify_all();
(self.notify)();
tracks.len()
}
pub fn cancel(&self, uid: u64) {
if let Some(h) = self.jobs.iter().find(|h| h.uid == uid) {
let mut j = h.job.lock().unwrap();
if !j.state.finished() {
h.cancel.store(true, Ordering::Relaxed);
if j.state == JobState::Queued {
j.state = JobState::Cancelled;
j.status = "Cancelled".into();
}
}
}
(self.notify)();
}
pub fn cancel_all(&self) {
for h in &self.jobs {
self.cancel(h.uid);
}
}
pub fn retry(&self, uid: u64, snap: &Value) {
let Some(h) = self.jobs.iter().find(|h| h.uid == uid) else { return };
{
let mut j = h.job.lock().unwrap();
if !j.state.finished() {
return;
}
h.cancel.store(false, Ordering::Relaxed);
j.state = JobState::Queued;
j.status = "Waiting".into();
j.error.clear();
j.progress = 0.0;
}
self.shared.queue.lock().unwrap().push_back((h.clone(), Arc::new(snap.clone())));
self.shared.cv.notify_all();
(self.notify)();
}
pub fn remove(&mut self, uid: u64) {
self.jobs.retain(|h| !(h.uid == uid && h.job.lock().unwrap().state.finished()));
}
pub fn clear_finished(&mut self) {
self.jobs.retain(|h| !matches!(h.job.lock().unwrap().state, JobState::Done | JobState::Skipped | JobState::Cancelled));
}
/// (active incl. queued, done, failed)
pub fn counts(&self) -> (usize, usize, usize) {
let (mut a, mut d, mut f) = (0, 0, 0);
for h in &self.jobs {
match h.job.lock().unwrap().state {
JobState::Done | JobState::Skipped => d += 1,
JobState::Failed => f += 1,
s if !s.finished() => a += 1,
_ => {}
}
}
(a, d, f)
}
/// Returns (done, failed) once when the queue empties.
pub fn poll_all_done(&mut self) -> Option<(usize, usize)> {
let (a, d, f) = self.counts();
let fire = self.was_busy && a == 0;
self.was_busy = a > 0;
fire.then_some((d, f))
}
pub fn log(&self, job: u64, kind: &str, text: &str) {
let _ = self.log_tx.send(LogLine { job, kind: kind.into(), text: text.into() });
}
}
fn worker_loop(sh: Arc<Shared>, log_tx: Sender<LogLine>, notify: Arc<dyn Fn() + Send + Sync>) {
loop {
let item = {
let mut q = sh.queue.lock().unwrap();
loop {
if sh.running.load(Ordering::Relaxed) < sh.limit.load(Ordering::Relaxed) {
if let Some(i) = q.pop_front() {
sh.running.fetch_add(1, Ordering::Relaxed);
break i;
}
}
q = sh.cv.wait_timeout(q, Duration::from_millis(500)).unwrap().0;
}
};
let (h, snap) = item;
run_job(&h, &snap, &log_tx, &notify);
sh.running.fetch_sub(1, Ordering::Relaxed);
sh.cv.notify_all();
}
}
enum Fail {
Cancelled,
Error(String),
}
impl From<String> for Fail {
fn from(s: String) -> Fail {
Fail::Error(s)
}
}
impl From<&str> for Fail {
fn from(s: &str) -> Fail {
Fail::Error(s.into())
}
}
struct Ctx<'a> {
h: &'a JobHandle,
snap: &'a Value,
tx: &'a Sender<LogLine>,
notify: &'a Arc<dyn Fn() + Send + Sync>,
last_emit: Mutex<Instant>,
}
impl Ctx<'_> {
fn log(&self, kind: &str, text: &str) {
let _ = self.tx.send(LogLine { job: self.h.uid, kind: kind.into(), text: text.into() });
(self.notify)();
}
fn update(&self, state: Option<JobState>, status: Option<&str>, force: bool) {
{
let mut j = self.h.job.lock().unwrap();
if let Some(s) = state {
j.state = s;
}
if let Some(s) = status {
j.status = s.into();
}
}
let mut last = self.last_emit.lock().unwrap();
if force || last.elapsed() > Duration::from_millis(120) {
*last = Instant::now();
(self.notify)();
}
}
fn check(&self) -> Result<(), Fail> {
if self.h.cancel.load(Ordering::Relaxed) {
Err(Fail::Cancelled)
} else {
Ok(())
}
}
}
fn short_error(msg: &str) -> String {
let first = msg.lines().next().unwrap_or("Unknown error");
if first.contains("Sign in to confirm") {
return "YouTube wants a sign-in: set “Cookies from browser” in Settings".into();
}
if first.contains("Video unavailable") || first.contains("Private video") {
return "This video is unavailable".into();
}
let l = first.to_lowercase();
if l.contains("ffmpeg") && (l.contains("not found") || l.contains("not installed")) {
return "ffmpeg is missing".into();
}
first.chars().take(160).collect()
}
fn retryable(msg: &str) -> bool {
["HTTP Error 403", "HTTP Error 5", "timed out", "Connection reset", "IncompleteRead", "fragment", "Read timed out"].iter().any(|s| msg.contains(s))
}
fn run_job(h: &JobHandle, snap: &Value, tx: &Sender<LogLine>, notify: &Arc<dyn Fn() + Send + Sync>) {
let ctx = Ctx { h, snap, tx, notify, last_emit: Mutex::new(Instant::now()) };
if h.cancel.load(Ordering::Relaxed) {
ctx.update(Some(JobState::Cancelled), Some("Cancelled"), true);
return;
}
let opts = h.job.lock().unwrap().options.clone();
let out_dir = PathBuf::from(paths::shellexpand(&opts.output_dir));
let tmp_dir = out_dir.join(".audiphi-partial");
let result = pipeline(&ctx, &out_dir, &tmp_dir);
// clean up this job's partial files
if let Ok(rd) = std::fs::read_dir(&tmp_dir) {
for e in rd.flatten() {
if e.file_name().to_string_lossy().starts_with(&format!("{}.", h.uid)) {
let _ = std::fs::remove_file(e.path());
}
}
}
let _ = std::fs::remove_dir(&tmp_dir); // only succeeds once every worker is done with it
match result {
Ok(()) => {}
Err(Fail::Cancelled) => {
ctx.log("warning", "Cancelled");
ctx.update(Some(JobState::Cancelled), Some("Cancelled"), true);
}
Err(Fail::Error(msg)) => {
h.job.lock().unwrap().error = msg.clone();
ctx.log("error", &msg);
ctx.update(Some(JobState::Failed), Some(&short_error(&msg)), true);
}
}
}
fn final_path(ctx: &Ctx, out_dir: &Path, ext: &str) -> PathBuf {
let j = ctx.h.job.lock().unwrap();
let (t, o) = (&j.track, &j.options);
let sep = get_str(ctx.snap, "download.artist_separator");
let sep = if sep.is_empty() { ", ".to_string() } else { sep };
let values = track_values(t, ext, &quality_label(&o.format, &o.bitrate, &o.sample_rate, &o.bit_depth), &sep);
let mut rel = render(&o.template, &values);
if o.collection_folder && !t.folder.is_empty() && !o.template.contains("{album") {
let f: Vec<String> = t.folder.iter().filter(|f| !f.is_empty()).map(|f| safe_component(f)).collect();
rel = format!("{}/{}", f.join("/"), rel);
} else if o.collection_folder && !t.playlist.is_empty() && t.folder.is_empty() && !o.template.contains("{playlist") {
rel = format!("{}/{}", safe_component(&t.playlist), rel);
}
out_dir.join(format!("{rel}.{ext}"))
}
fn resolve_collision(path: PathBuf, policy: &str) -> PathBuf {
if !path.exists() || policy == "overwrite" {
return path;
}
let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
let ext = path.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default();
(2..).map(|n| path.with_file_name(format!("{stem} ({n}){ext}"))).find(|c| !c.exists()).unwrap()
}
fn pipeline(ctx: &Ctx, out_dir: &Path, tmp_dir: &Path) -> Result<(), Fail> {
let uid = ctx.h.uid;
std::fs::create_dir_all(tmp_dir).map_err(|e| format!("Can't write to {}: {e}", out_dir.display()))?;
let log = |k: &str, t: &str| ctx.log(k, t);
let (title, artist) = { let j = ctx.h.job.lock().unwrap(); (j.track.display_title(), j.track.display_artist()) };
ctx.log("info", &format!("▶ {} – {}", if artist.is_empty() { "?" } else { &artist }, title));
let opts = ctx.h.job.lock().unwrap().options.clone();
let source = Some(get_str(ctx.snap, "download.search_source")).filter(|s| !s.is_empty()).unwrap_or_else(|| "ytmusic".into());
// 1. Services yt-dlp can't download from: find the same song on YouTube Music.
let needs_match = ctx.h.job.lock().unwrap().track.download_url.is_empty();
if needs_match {
ctx.update(Some(JobState::Matching), Some(&format!("Finding “{title}” on {}", service_name(&source))), true);
let t = ctx.h.job.lock().unwrap().track.clone();
let m = matcher::find_match(ctx.snap, &t, &source, &log).ok_or("Couldn't find this song on YouTube Music or YouTube")?;
let mut j = ctx.h.job.lock().unwrap();
j.track.download_url = m.download_url.clone();
j.track.matched = Some(MatchInfo { service: m.service.clone(), title: m.title.clone(), artist: m.artist(), url: m.download_url.clone(), score: m.score });
j.track.match_cover = m.cover_url.clone();
if j.track.album.is_empty() && !m.album.is_empty() && m.authoritative {
j.track.album = m.album.clone();
}
if j.track.duration.is_none() {
j.track.duration = m.duration;
}
}
ctx.check()?;
// 2. Full info from yt-dlp (one extraction, reused for the download).
ctx.update(Some(JobState::Resolving), Some("Getting stream info"), true);
let url = ctx.h.job.lock().unwrap().track.download_url.clone();
let mut info = extract_info(ctx, &url)?;
merge_info(ctx, &info);
ctx.check()?;
// 3. Tags from Deezer / iTunes / MusicBrainz, per the settings.
if !ctx.h.job.lock().unwrap().track.enriched {
ctx.update(Some(JobState::Metadata), Some("Looking up tags"), true);
let mut t = ctx.h.job.lock().unwrap().track.clone();
metadata::enrich(&mut t, ctx.snap, &log);
let mut j = ctx.h.job.lock().unwrap();
// keep anything the user edited while we were looking
let overrides = std::mem::take(&mut j.track.overrides);
j.track = Track { overrides, ..t };
}
ctx.check()?;
// 4. Final name; skip, rename or overwrite an existing file.
let policy = Some(get_str(ctx.snap, "download.existing")).filter(|s| !s.is_empty()).unwrap_or_else(|| "rename".into());
let probe_ext = format_ext(&opts.format).map(String::from).unwrap_or_else(|| js_str(&info, "ext", "m4a"));
let target = final_path(ctx, out_dir, &probe_ext);
if target.exists() && policy == "skip" {
{
let mut j = ctx.h.job.lock().unwrap();
j.output_path = target.to_string_lossy().into_owned();
j.progress = 1.0;
}
ctx.log("info", &format!("Already have {}, skipping", target.file_name().unwrap_or_default().to_string_lossy()));
ctx.update(Some(JobState::Skipped), Some(&format!("Already in {}", target.parent().and_then(|p| p.file_name()).map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "library".into()))), true);
return Ok(());
}
// 5. Download. YouTube sometimes answers 403 on a stream URL; fresh URLs from a second extraction usually work.
ctx.update(Some(JobState::Downloading), Some("Starting download"), true);
let mut downloaded = None;
for attempt in 0..3 {
match download(ctx, &info, tmp_dir, &opts) {
Ok(p) => {
downloaded = Some(p);
break;
}
Err(Fail::Error(e)) if attempt < 2 && retryable(&e) && !ctx.h.cancel.load(Ordering::Relaxed) => {
ctx.log("warning", &format!("Download failed ({}); retrying with fresh links", short_error(&e)));
ctx.update(Some(JobState::Resolving), Some("Retrying with fresh links"), true);
std::thread::sleep(Duration::from_millis(1500 * (attempt + 1)));
info = extract_info(ctx, &url)?;
}
Err(e) => return Err(e),
}
}
let mut downloaded = downloaded.ok_or("The download didn't finish")?;
ctx.check()?;
if opts.format != "best" {
let dur = info.get("duration").and_then(|d| d.as_f64()).or(ctx.h.job.lock().unwrap().track.duration);
downloaded = encode(ctx, &downloaded, dur, &opts, tmp_dir)?;
}
ctx.check()?;
// 6. Cover art.
let skip: Vec<String> = ctx.h.job.lock().unwrap().track.skip_fields.clone();
let cover = if get_bool(ctx.snap, "metadata.embed_cover") && !skip.contains(&"cover".to_string()) { cover_art(ctx) } else { None };
// 7. Lyrics.
let (lyric_text, synced_text) = fetch_lyrics(ctx, &opts);
// 8. Tags.
ctx.update(Some(JobState::Tagging), Some("Writing tags"), true);
let tags = build_tags(ctx, cover.as_ref().map(|c| c.0.clone()), &lyric_text, &skip);
if let Err(e) = tagger::write(&downloaded.to_string_lossy(), &tags, if opts.lyrics != "off" { &opts.lyrics } else { "off" }) {
ctx.log("warning", &format!("Couldn't write tags: {e}")); // a tagging hiccup shouldn't lose the download
}
// 9. Move into place.
let ext = downloaded.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default();
let final_p = resolve_collision(final_path(ctx, out_dir, &ext), &policy);
if let Some(p) = final_p.parent() {
std::fs::create_dir_all(p).map_err(|e| format!("Can't create {}: {e}", p.display()))?;
}
if std::fs::rename(&downloaded, &final_p).is_err() {
std::fs::copy(&downloaded, &final_p).map_err(|e| format!("Couldn't move the file into place: {e}"))?;
let _ = std::fs::remove_file(&downloaded);
}
ctx.h.job.lock().unwrap().output_path = final_p.to_string_lossy().into_owned();
if opts.save_lrc && (!synced_text.is_empty() || !lyric_text.is_empty()) {
let text = if synced_text.is_empty() { &lyric_text } else { &synced_text };
let _ = std::fs::write(final_p.with_extension("lrc"), text);
}
if let (Some(c), true) = (&cover, get_bool(ctx.snap, "metadata.save_cover_file")) {
if final_p.parent() != Some(out_dir) {
let cf = final_p.parent().unwrap().join("cover.jpg");
if !cf.exists() {
let _ = std::fs::write(cf, &c.0);
}
}
}
let size = std::fs::metadata(&final_p).map(|m| format_size(m.len() as f64)).unwrap_or_default();
ctx.h.job.lock().unwrap().progress = 1.0;
ctx.log("success", &format!("✓ Saved {} ({size})", final_p.display()));
ctx.update(Some(JobState::Done), Some(&format!("Saved · {size}")), true);
Ok(())
}
fn js_str(v: &Value, k: &str, d: &str) -> String {
v.get(k).and_then(|x| x.as_str()).filter(|s| !s.is_empty()).unwrap_or(d).to_string()
}
fn extract_info(ctx: &Ctx, url: &str) -> Result<Value, Fail> {
let log = |k: &str, t: &str| ctx.log(k, t);
let mut info = ytdlp::extract(ctx.snap, url, false, &[], &log)?;
if info.get("_type").and_then(|t| t.as_str()) == Some("playlist") {
info = info.get("entries").and_then(|e| e.as_array()).and_then(|e| e.iter().find(|x| x.is_object())).cloned().ok_or("Nothing to download at that link")?;
}
Ok(info)
}
fn merge_info(ctx: &Ctx, info: &Value) {
let mut j = ctx.h.job.lock().unwrap();
let url = j.track.download_url.clone();
let full = track_from_info(info, &url);
let t = &mut j.track;
if t.matched.is_none() {
if !full.title.is_empty() && (t.weak || t.title.is_empty()) {
t.title = full.title.clone();
}
if !full.artists.is_empty() && (t.weak || t.artists.is_empty()) {
t.artists = full.artists.clone();
}
macro_rules! fill {
($f:ident) => {
if !full.$f.is_empty() && (t.weak || t.$f.is_empty()) {
t.$f = full.$f.clone();
}
};
}
fill!(album);
fill!(album_artist);
fill!(year);
fill!(genre);
if full.track_number.is_some() && (t.weak || t.track_number.is_none()) {
t.track_number = full.track_number;
}
if full.disc_number.is_some() && (t.weak || t.disc_number.is_none()) {
t.disc_number = full.disc_number;
}
t.authoritative = t.authoritative || full.authoritative;
if t.service.is_empty() {
t.service = full.service.clone();
}
if t.source_id.is_empty() {
t.source_id = full.source_id.clone();
}
}
if t.duration.is_none() {
t.duration = full.duration;
}
if t.cover_url.is_empty() || t.weak {
if !full.cover_url.is_empty() {
t.cover_url = full.cover_url.clone();
}
}
t.thumbnail = full.cover_url;
t.weak = false;
}
fn download(ctx: &Ctx, info: &Value, tmp_dir: &Path, opts: &DownloadOptions) -> Result<PathBuf, Fail> {
let uid = ctx.h.uid;
let info_file = tmp_dir.join(format!("{uid}.info.json"));
std::fs::write(&info_file, serde_json::to_vec(info).unwrap_or_default()).map_err(|e| e.to_string())?;
let mut args = ytdlp::base_args(ctx.snap);
args.extend(["--load-info-json".into(), info_file.to_string_lossy().into_owned(), "-f".into(), "bestaudio/best".into(), "--newline".into(), "--no-warnings".into(), "--force-overwrites".into(),
"-o".into(), tmp_dir.join(format!("{uid}.%(ext)s")).to_string_lossy().into_owned(),
"--progress-template".into(), "download:[dl] %(progress.downloaded_bytes)s %(progress.total_bytes)s %(progress.total_bytes_estimate)s %(progress.speed)s %(progress.eta)s".into()]);
if opts.format == "best" {
args.extend(["-x".into(), "--audio-format".into(), "best".into()]);
}
let log = |k: &str, t: &str| ctx.log(k, t);
let num = |s: &str| s.parse::<f64>().ok();
let out = ytdlp::run(&args, Some(&ctx.h.cancel), &log, |line| {
if let Some(rest) = line.strip_prefix("[dl] ") {
let p: Vec<&str> = rest.split_whitespace().collect();
if p.len() >= 5 {
let done = num(p[0]).unwrap_or(0.0);
let total = num(p[1]).or(num(p[2])).unwrap_or(0.0);
let mut j = ctx.h.job.lock().unwrap();
if total > 0.0 {
j.progress = (done / total).min(1.0) as f32;
}
j.speed = num(p[3]);
j.eta = num(p[4]);
let mut parts = vec![format!("{:4.1}%", j.progress * 100.0)];
if total > 0.0 {
parts.push(format!("of {}", format_size(total)));
}
if let Some(s) = j.speed {
parts.push(format!("at {}/s", format_size(s)));
}
if let Some(e) = j.eta {
parts.push(format!("ETA {}", format_duration(Some(e))));
}
j.status = parts.join(" ");
j.state = JobState::Downloading;
drop(j);
ctx.update(None, None, false);
}
} else if line.contains("[ExtractAudio]") {
ctx.update(Some(JobState::Converting), Some("Remuxing"), true);
} else if !line.trim().is_empty() {
ctx.log("yt", line);
}
})?;
ctx.check()?;
if out.cancelled {
return Err(Fail::Cancelled);
}
if !out.ok {
return Err(Fail::Error(ytdlp::error_text(&out)));
}
ctx.h.job.lock().unwrap().progress = 1.0;
let mut found: Vec<PathBuf> = std::fs::read_dir(tmp_dir)
.map_err(|e| e.to_string())?
.flatten()
.map(|e| e.path())
.filter(|p| {
let n = p.file_name().unwrap_or_default().to_string_lossy().into_owned();
n.starts_with(&format!("{uid}.")) && !n.ends_with(".part") && !n.ends_with(".ytdl") && !n.ends_with(".json")
})
.collect();
found.sort_by_key(|p| std::cmp::Reverse(std::fs::metadata(p).and_then(|m| m.modified()).ok()));
found.into_iter().next().ok_or_else(|| Fail::Error("yt-dlp finished but the audio file is missing".into()))
}
fn encode(ctx: &Ctx, src: &Path, duration: Option<f64>, o: &DownloadOptions, tmp_dir: &Path) -> Result<PathBuf, Fail> {
let ffmpeg = paths::find_ffmpeg(&get_str(ctx.snap, "download.ffmpeg_path")).ok_or("ffmpeg wasn't found; install it or set its path in Settings")?;
let uid = ctx.h.uid;
let label = super::downloader::FORMATS.iter().find(|f| f.0 == o.format).map(|f| f.1.split(" · ").next().unwrap_or(f.1)).unwrap_or(&o.format).to_string();
let q = quality_label(&o.format, &o.bitrate, &o.sample_rate, &o.bit_depth);
let base = format!("Converting to {label} {q}").trim().to_string();
ctx.update(Some(JobState::Converting), Some(&base), true);
let ext = format_ext(&o.format).unwrap_or("mp3");
let dst = tmp_dir.join(format!("{uid}.out.{ext}"));
let mut cmd = Command::new(ffmpeg);
cmd.args(["-hide_banner", "-nostdin", "-y", "-loglevel", "error", "-progress", "pipe:1", "-i"]).arg(src).args(encode_args(o)).arg(&dst).stdout(Stdio::piped()).stderr(Stdio::piped());
let mut child = cmd.spawn().map_err(|e| format!("couldn't start ffmpeg: {e}"))?;
let stdout = child.stdout.take().unwrap();
let stderr = child.stderr.take().unwrap();
let child = Arc::new(Mutex::new(child));
let done = Arc::new(AtomicBool::new(false));
let (c2, d2, cancel) = (child.clone(), done.clone(), ctx.h.cancel.clone());
let watcher = std::thread::spawn(move || {
while !d2.load(Ordering::Relaxed) {
if cancel.load(Ordering::Relaxed) {
let _ = c2.lock().unwrap().kill();
break;
}
std::thread::sleep(Duration::from_millis(100));
}
});
let err_thread = std::thread::spawn(move || BufReader::new(stderr).lines().map_while(Result::ok).collect::<Vec<_>>().join("\n"));
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
if let (Some(us), Some(d)) = (line.strip_prefix("out_time_us="), duration.filter(|d| *d > 0.0)) {
if let Ok(us) = us.trim().parse::<f64>() {
let pct = (us / 1e4 / d).min(100.0);
ctx.update(None, Some(&format!("{base} · {pct:.0}%")), false);
}
}
}
let status = child.lock().unwrap().wait();
done.store(true, Ordering::Relaxed);
let _ = watcher.join();
let err = err_thread.join().unwrap_or_default();
ctx.check()?;
if !status.map(|s| s.success()).unwrap_or(false) || !dst.exists() {
return Err(Fail::Error(format!("ffmpeg failed: {}", err.lines().last().unwrap_or("unknown error"))));
}
let _ = std::fs::remove_file(src);
let final_p = tmp_dir.join(format!("{uid}.{ext}"));
std::fs::rename(&dst, &final_p).map_err(|e| e.to_string())?;
Ok(final_p)
}
fn cover_art(ctx: &Ctx) -> Option<(Vec<u8>, String)> {
let size = get_i64(ctx.snap, "metadata.cover_size").max(0) as u32;
let square = get_bool(ctx.snap, "metadata.cover_square");
let t = ctx.h.job.lock().unwrap().track.clone();
if let Some(d) = &t.cover_override {
return covers::process(d, size, false);
}
let mut seen = vec![];
for url in [&t.cover_url, &t.match_cover, &t.thumbnail] {
if url.is_empty() || seen.contains(&url) {
continue;
}
seen.push(url);
if let Some(data) = covers::fetch(url) {
if let Some(r) = covers::process(&data, size, square) {
return Some(r);
}
}
}
ctx.log("warning", "No cover art found");
None
}
fn fetch_lyrics(ctx: &Ctx, o: &DownloadOptions) -> (String, String) {
let t = ctx.h.job.lock().unwrap().track.clone();
if let Some(text) = &t.lyrics_override {
return (text.clone(), if lyrics::is_synced(text) { text.clone() } else { String::new() });
}
if o.lyrics == "off" && !o.save_lrc {
return Default::default();
}
ctx.update(Some(JobState::Lyrics), Some("Fetching lyrics"), true);
let found = match lyrics::fetch(&t.value("title"), &t.value("artist"), &t.value("album"), t.duration) {
Ok(f) => f,
Err(e) => {
ctx.log("warning", &format!("Lyrics lookup failed: {e}"));
return Default::default();
}
};
if found.instrumental {
ctx.log("info", "LRCLIB says it's instrumental");
return Default::default();
}
if !found.found() {
ctx.log("info", "No lyrics on LRCLIB");
return Default::default();
}
ctx.log("info", &format!("Lyrics found ({})", if found.synced.is_empty() { "plain text" } else { "synced" }));
let fallback = ctx.snap.pointer("/lyrics/fallback_plain").and_then(|v| v.as_bool()).unwrap_or(true);
let embed = match o.lyrics.as_str() {
"synced" => if !found.synced.is_empty() { found.synced.clone() } else if fallback { found.plain.clone() } else { String::new() },
"plain" => if !found.plain.is_empty() { found.plain.clone() } else { lyrics::lrc_to_plain(&found.synced) },
_ => String::new(),
};
(embed, found.synced)
}
fn build_tags(ctx: &Ctx, cover: Option<Vec<u8>>, lyric_text: &str, skip: &[String]) -> tagger::Tags {
let t = ctx.h.job.lock().unwrap().track.clone();
let sep = Some(get_str(ctx.snap, "download.artist_separator")).filter(|s| !s.is_empty()).unwrap_or_else(|| ", ".into());
let artist = t.overrides.get("artist").filter(|s| !s.is_empty()).cloned().unwrap_or_else(|| t.artists.join(&sep));
let mut comment = t.value("comment");
if comment.is_empty() && get_bool(ctx.snap, "download.write_source_comment") {
comment = if t.page_url.is_empty() { t.download_url.clone() } else { t.page_url.clone() };
}
tagger::Tags {
title: t.value("title"), artist, album: t.value("album"), album_artist: t.value("album_artist"),
track_number: to_int(&t.value("track_number")), track_total: to_int(&t.value("track_total")), disc_number: to_int(&t.value("disc_number")),
year: t.value("year"), genre: t.value("genre"), isrc: t.value("isrc"), comment, lyrics: lyric_text.into(), cover,
skip: skip.iter().cloned().collect(), ..Default::default()
}
}

195
src/core/http.rs Normal file
View file

@ -0,0 +1,195 @@
//! One shared ureq agent with sane timeouts and retries, plus the helpers the resolvers use.
use serde_json::Value;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use ureq::ResponseExt;
pub const BROWSER_UA: &str = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36";
pub const TIMEOUT: Duration = Duration::from_secs(20);
pub fn app_ua() -> String {
format!("{}/{} ( {} )", crate::APP_NAME, crate::VERSION, crate::HOMEPAGE)
}
#[derive(Debug, Clone)]
pub struct HttpError {
/// 0 for transport errors (DNS, TLS, timeout).
pub status: u16,
pub msg: String,
}
impl std::fmt::Display for HttpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.status > 0 {
write!(f, "HTTP {}: {}", self.status, self.msg)
} else {
write!(f, "{}", self.msg)
}
}
}
impl From<HttpError> for String {
fn from(e: HttpError) -> String {
e.to_string()
}
}
fn agent() -> &'static ureq::Agent {
static A: OnceLock<ureq::Agent> = OnceLock::new();
A.get_or_init(|| {
let cfg = ureq::Agent::config_builder().timeout_global(Some(TIMEOUT)).http_status_as_error(false).build();
ureq::Agent::new_with_config(cfg)
})
}
pub struct Reply {
pub status: u16,
pub url: String,
pub body: Vec<u8>,
pub headers: Vec<(String, String)>,
}
impl Reply {
pub fn text(&self, force_utf8: bool) -> String {
let _ = force_utf8;
String::from_utf8_lossy(&self.body).into_owned()
}
pub fn json(&self) -> Result<Value, HttpError> {
serde_json::from_slice(&self.body).map_err(|e| HttpError { status: self.status, msg: format!("bad JSON: {e}") })
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
pub fn ok(&self) -> bool {
(200..300).contains(&self.status)
}
fn check(self) -> Result<Reply, HttpError> {
if self.ok() {
Ok(self)
} else {
let snippet: String = String::from_utf8_lossy(&self.body).chars().take(200).collect();
Err(HttpError { status: self.status, msg: snippet })
}
}
}
pub fn query_string(params: &[(&str, String)]) -> String {
params.iter().map(|(k, v)| format!("{}={}", urlencoding::encode(k), urlencoding::encode(v))).collect::<Vec<_>>().join("&")
}
pub fn with_params(url: &str, params: &[(&str, String)]) -> String {
if params.is_empty() {
return url.to_string();
}
format!("{}{}{}", url, if url.contains('?') { "&" } else { "?" }, query_string(params))
}
fn finish(mut resp: ureq::http::Response<ureq::Body>) -> Result<Reply, HttpError> {
let status = resp.status().as_u16();
let url = resp.get_uri().to_string();
let headers = resp.headers().iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())).collect();
let body = resp.body_mut().with_config().limit(64 * 1024 * 1024).read_to_vec().map_err(|e| HttpError { status: 0, msg: e.to_string() })?;
Ok(Reply { status, url, body, headers })
}
fn terr(e: ureq::Error) -> HttpError {
HttpError { status: 0, msg: e.to_string() }
}
/// GET with up to three tries on transport errors and 429/5xx.
pub fn get(url: &str, headers: &[(&str, &str)]) -> Result<Reply, HttpError> {
let mut last = HttpError { status: 0, msg: "no attempt".into() };
for attempt in 0..3u32 {
if attempt > 0 {
std::thread::sleep(Duration::from_millis(600 * (1 << (attempt - 1))));
}
let mut req = agent().get(url);
for (k, v) in headers {
req = req.header(*k, *v);
}
match req.call().map_err(terr).and_then(finish) {
Ok(r) if r.status == 429 || (500..600).contains(&r.status) => {
last = HttpError { status: r.status, msg: String::from_utf8_lossy(&r.body).chars().take(200).collect() };
if r.status == 429 {
if let Some(s) = r.header("retry-after").and_then(|s| s.parse::<u64>().ok()) {
std::thread::sleep(Duration::from_secs(s.min(5)));
}
}
}
Ok(r) => return Ok(r),
Err(e) => last = e,
}
}
Err(last)
}
pub fn get_json(url: &str, params: &[(&str, String)], browser: bool, extra: &[(&str, &str)]) -> Result<Value, HttpError> {
let ua = if browser { BROWSER_UA.to_string() } else { app_ua() };
let mut h: Vec<(&str, &str)> = vec![("User-Agent", ua.as_str()), ("Accept", "application/json")];
h.extend_from_slice(extra);
get(&with_params(url, params), &h)?.check()?.json()
}
/// (final_url, body)
pub fn get_text(url: &str) -> Result<(String, String), HttpError> {
let r = get(url, &[("User-Agent", BROWSER_UA), ("Accept-Language", "en-US,en;q=0.8")])?.check()?;
let text = r.text(true);
Ok((r.url, text))
}
pub fn get_bytes(url: &str) -> Result<Vec<u8>, HttpError> {
Ok(get(url, &[("User-Agent", BROWSER_UA)])?.check()?.body)
}
/// Follow redirects and return the final URL (short links).
pub fn final_url(url: &str) -> Result<String, HttpError> {
Ok(get(url, &[("User-Agent", BROWSER_UA)])?.url)
}
pub fn post_json(url: &str, body: &Value, headers: &[(&str, &str)]) -> Result<Value, HttpError> {
let mut req = agent().post(url);
for (k, v) in headers {
req = req.header(*k, *v);
}
let resp = req.send_json(body).map_err(terr)?;
finish(resp)?.check()?.json()
}
/// Form POST; returns the raw reply so callers can read the status.
pub fn post_form(url: &str, form: &[(&str, &str)], headers: &[(&str, &str)]) -> Result<Reply, HttpError> {
let mut req = agent().post(url);
for (k, v) in headers {
req = req.header(*k, *v);
}
let resp = req.send_form(form.iter().map(|(k, v)| (*k, *v))).map_err(terr)?;
finish(resp)
}
/// At most one call per `interval` across threads (MusicBrainz asks for 1/s).
pub struct RateLimiter {
interval: Duration,
last: Mutex<Option<Instant>>,
}
impl RateLimiter {
pub const fn new(ms: u64) -> Self {
RateLimiter { interval: Duration::from_millis(ms), last: Mutex::new(None) }
}
pub fn wait(&self) {
let mut g = self.last.lock().unwrap();
if let Some(t) = *g {
let due = t + self.interval;
let now = Instant::now();
if due > now {
std::thread::sleep(due - now);
}
}
*g = Some(Instant::now());
}
}
pub fn b64(s: &str) -> String {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(s)
}

88
src/core/library.rs Normal file
View file

@ -0,0 +1,88 @@
//! Scanning the music folder for the player's library, with a small cache so rescans are quick.
use super::{paths, tagger};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LibraryItem {
pub path: String,
pub title: String,
pub artist: String,
pub album: String,
pub duration: f64,
pub mtime: f64,
pub size: u64,
}
fn cache_file() -> PathBuf {
paths::cache_dir().join("library-rs.json")
}
fn load_cache() -> HashMap<String, LibraryItem> {
std::fs::read_to_string(cache_file()).ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
}
fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(rd) = std::fs::read_dir(dir) else { return };
for e in rd.flatten() {
let p = e.path();
let name = e.file_name().to_string_lossy().into_owned();
if name.starts_with('.') {
continue;
}
if p.is_dir() {
walk(&p, out);
} else if paths::is_audio(&p) {
out.push(p);
}
}
}
pub fn scan(folder: &str) -> Vec<LibraryItem> {
let root = PathBuf::from(paths::shellexpand(folder));
if !root.is_dir() {
return vec![];
}
let cache = load_cache();
let mut files = vec![];
walk(&root, &mut files);
let mut fresh = HashMap::new();
let mut items = vec![];
for p in files {
let Ok(md) = std::fs::metadata(&p) else { continue };
let mtime = md.modified().ok().and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs_f64()).unwrap_or(0.0);
let key = p.to_string_lossy().into_owned();
let item = match cache.get(&key) {
Some(h) if (h.mtime - mtime).abs() < 1e-3 && h.size == md.len() => h.clone(),
_ => {
let t = tagger::read(&key, false);
LibraryItem {
title: if t.title.is_empty() { p.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default() } else { t.title },
artist: t.artist,
album: t.album,
duration: t.duration.unwrap_or(0.0),
mtime,
size: md.len(),
path: key.clone(),
}
}
};
fresh.insert(key, item.clone());
items.push(item);
}
if let Ok(s) = serde_json::to_string(&fresh) {
let _ = std::fs::write(cache_file(), s);
}
items
}
pub fn forget(path: &str) {
let mut c = load_cache();
if c.remove(path).is_some() {
if let Ok(s) = serde_json::to_string(&c) {
let _ = std::fs::write(cache_file(), s);
}
}
}

131
src/core/lyrics.rs Normal file
View file

@ -0,0 +1,131 @@
//! Lyrics from LRCLIB (free, no key) and an LRC parser for the player.
use super::http;
use super::textutil::{clean_title, match_score, strip_feat};
use super::Res;
use regex::Regex;
use serde_json::Value;
use std::sync::LazyLock;
const API: &str = "https://lrclib.net/api";
static TS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[(\d{1,3}):(\d{1,2})(?:[.:](\d{1,3}))?\]").unwrap());
static OFFSET: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?im)^\[offset:\s*([+-]?\d+)\]").unwrap());
static WORD_TS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<\d+:\d+(?:\.\d+)?>").unwrap());
static ANY_BRACKET: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[[^\]]*\]").unwrap());
#[derive(Clone, Debug, Default)]
pub struct Lyrics {
pub plain: String,
pub synced: String,
pub instrumental: bool,
}
impl Lyrics {
pub fn found(&self) -> bool {
!self.plain.is_empty() || !self.synced.is_empty() || self.instrumental
}
}
fn from_record(r: &Value) -> Lyrics {
let s = |k: &str| r.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();
Lyrics { plain: s("plainLyrics"), synced: s("syncedLyrics"), instrumental: r.get("instrumental").and_then(|v| v.as_bool()).unwrap_or(false) }
}
/// LRCLIB has junk records (e.g. a lone "[00:00.00]probe"); real lyrics have a few lines.
fn usable(r: &Value) -> bool {
if r.get("instrumental").and_then(|v| v.as_bool()).unwrap_or(false) {
return true;
}
let text = r.get("syncedLyrics").and_then(|v| v.as_str()).filter(|s| !s.is_empty()).or_else(|| r.get("plainLyrics").and_then(|v| v.as_str())).unwrap_or("");
text.lines().filter(|l| !ANY_BRACKET.replace_all(l, "").trim().is_empty()).count() >= 3
}
pub fn fetch(title: &str, artist: &str, album: &str, duration: Option<f64>) -> Res<Lyrics> {
let title_q = strip_feat(&clean_title(title));
let artist_q = artist.split(',').next().unwrap_or("").trim().to_string();
let ua = http::app_ua();
let hdr = [("Lrclib-Client", ua.as_str())];
let base = [("track_name", title_q.clone()), ("artist_name", artist_q.clone())];
let mut attempts: Vec<Vec<(&str, String)>> = vec![];
if let Some(d) = duration.filter(|d| *d > 0.0) {
let d = format!("{}", d.round() as i64);
if !album.is_empty() {
let mut a = base.to_vec();
a.push(("album_name", album.to_string()));
a.push(("duration", d.clone()));
attempts.push(a);
}
let mut a = base.to_vec();
a.push(("duration", d));
attempts.push(a);
}
for params in attempts {
match http::get_json(&format!("{API}/get"), &params, false, &hdr) {
Ok(r) if usable(&r) => return Ok(from_record(&r)),
Ok(_) => {}
Err(e) if e.status == 404 => {}
Err(e) => return Err(e.to_string()),
}
}
let mut results = http::get_json(&format!("{API}/search"), &base, false, &hdr)?;
if results.as_array().map(|a| a.is_empty()).unwrap_or(true) {
results = http::get_json(&format!("{API}/search"), &[("q", format!("{artist_q} {title_q}"))], false, &hdr)?;
}
let mut best: Option<&Value> = None;
let mut best_score = 0.0;
for r in results.as_array().into_iter().flatten() {
if !usable(r) {
continue;
}
let name = r.get("trackName").and_then(|v| v.as_str()).unwrap_or("");
let art = r.get("artistName").and_then(|v| v.as_str()).unwrap_or("");
let mut score = match_score(&title_q, &[artist_q.clone()], duration, name, &[art.to_string()], r.get("duration").and_then(|v| v.as_f64()));
if r.get("syncedLyrics").and_then(|v| v.as_str()).map(|s| !s.is_empty()).unwrap_or(false) {
score += 0.05;
}
if score > best_score {
best = Some(r);
best_score = score;
}
}
Ok(match best {
Some(r) if best_score >= 0.6 => from_record(r),
_ => Lyrics::default(),
})
}
pub fn is_synced(text: &str) -> bool {
!text.is_empty() && TS.find_iter(text).count() >= 3
}
/// [(milliseconds, line)] sorted by time. Lines with several stamps appear once per stamp.
pub fn parse_lrc(text: &str) -> Vec<(i64, String)> {
let offset = OFFSET.captures(text).and_then(|c| c[1].parse::<i64>().ok()).unwrap_or(0);
let mut out = vec![];
for raw in text.lines() {
let stamps: Vec<_> = TS.captures_iter(raw).collect();
if stamps.is_empty() {
continue;
}
let line = TS.replace_all(raw, "");
let line = WORD_TS.replace_all(&line, "").trim().to_string();
for s in stamps {
let m: i64 = s[1].parse().unwrap_or(0);
let sec: i64 = s[2].parse().unwrap_or(0);
let frac = s.get(3).map(|f| f.as_str()).unwrap_or("0");
let ms: i64 = format!("{frac:0<3}")[..3].parse().unwrap_or(0);
out.push(((m * 60000 + sec * 1000 + ms - offset).max(0), line.clone()));
}
}
out.sort_by_key(|x| x.0);
out
}
pub fn lrc_to_plain(text: &str) -> String {
let lines: Vec<String> = parse_lrc(text).into_iter().map(|x| x.1).collect();
if lines.is_empty() {
text.to_string()
} else {
lines.join("\n")
}
}

101
src/core/matcher.rs Normal file
View file

@ -0,0 +1,101 @@
//! Finding a downloadable recording for tracks from services yt-dlp can't download from
//! (Spotify, Apple Music, Deezer, Tidal, Amazon Music...): search YouTube Music, YouTube or
//! SoundCloud and keep the closest match by name, artist and length.
use super::metadata::{jarr, js};
use super::models::Track;
use super::textutil::*;
use super::{ytdlp, ytmusic, Log};
use serde_json::Value;
pub fn search_ytdlp(snap: &Value, query: &str, site: &str, limit: usize, log: Log) -> Result<Vec<Track>, String> {
let info = ytdlp::extract(snap, &format!("{site}{limit}:{query}"), true, &[], log)?;
let mut out = vec![];
for e in jarr(&info, "entries") {
let url = js(e, "url");
if url.is_empty() {
continue;
}
let uploader = Some(js(e, "channel")).filter(|s| !s.is_empty()).unwrap_or_else(|| js(e, "uploader"));
let (artist, title) = split_artist_title(&js(e, "title"), &uploader);
let mut t = Track::new();
t.title = title;
t.artists = if artist.is_empty() { vec![] } else { vec![artist.clone()] };
t.duration = e.get("duration").and_then(|d| d.as_f64());
t.download_url = url.clone();
t.page_url = url;
t.source_id = js(e, "id");
t.service = if site == "ytsearch" { "youtube".into() } else { "soundcloud".into() };
t.cover_url = jarr(e, "thumbnails").last().map(|t| js(t, "url")).unwrap_or_default();
t.official = uploader.ends_with(" - Topic") || uploader.to_lowercase() == artist.to_lowercase();
t.uploader = uploader;
out.push(t);
}
Ok(out)
}
/// The best downloadable candidate for `track`, or None.
pub fn find_match(snap: &Value, track: &Track, source: &str, log: Log) -> Option<Track> {
let title = strip_feat(&clean_title(&track.value("title")));
let artist = track.value("artist");
let artists: Vec<String> = if track.artists.is_empty() { vec![artist] } else { track.artists.clone() }.iter().filter(|a| !a.is_empty()).map(|a| clean_artist(a)).collect();
let query = format!("{} {}", artists.first().cloned().unwrap_or_default(), title).trim().to_string();
let mut candidates: Vec<Track> = vec![];
if source == "ytmusic" {
// An ISRC search pins the exact recording when we have one.
if !track.isrc.is_empty() {
match ytmusic::search_songs(&track.isrc, 3) {
Ok(list) => {
for mut c in list {
if track.duration.is_none() || c.duration.is_none() || (c.duration.unwrap() - track.duration.unwrap()).abs() <= 4.0 {
c.isrc_hit = true;
candidates.push(c);
}
}
}
Err(e) => log("warning", &format!("ISRC search failed: {e}")),
}
}
match ytmusic::search_songs(&query, 10) {
Ok(list) => candidates.extend(list),
Err(e) => log("warning", &format!("YouTube Music search failed: {e}")),
}
}
if source == "soundcloud" {
match search_ytdlp(snap, &query, "scsearch", 8, log) {
Ok(l) => candidates.extend(l),
Err(e) => log("warning", &format!("SoundCloud search failed: {e}")),
}
}
let score = |c: &Track| {
let mut s = match_score(&title, &artists, track.duration, &c.title, &c.artists, c.duration);
if c.isrc_hit {
s += 0.1;
}
if c.official {
s += 0.05;
}
s
};
let mut scored: Vec<(f64, Track)> = candidates.into_iter().map(|c| (score(&c), c)).collect();
let sort = |v: &mut Vec<(f64, Track)>| v.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
sort(&mut scored);
if scored.first().map(|s| s.0 < 0.7).unwrap_or(true) {
// Songs search came up short: try plain YouTube.
match search_ytdlp(snap, &format!("{query} audio"), "ytsearch", 8, log) {
Ok(extra) => {
scored.extend(extra.into_iter().map(|c| (score(&c), c)));
sort(&mut scored);
}
Err(e) => log("warning", &format!("YouTube search failed: {e}")),
}
}
let (best_score, mut best) = scored.into_iter().next()?;
log("match", &format!("Matched “{} – {}” on {} ({:.0}%) {}", best.artist(), best.title, best.service, best_score * 100.0, best.download_url));
if best_score < 0.45 {
return None;
}
best.score = best_score;
Some(best)
}

509
src/core/metadata.rs Normal file
View file

@ -0,0 +1,509 @@
//! Free, keyless metadata lookups (Deezer, iTunes, MusicBrainz) and choosing tags per field.
use super::http::{self, RateLimiter};
use super::models::Track;
use super::settings::{get_bool, get_f64, get_i64, lookup};
use super::textutil::*;
use super::Log;
use regex::Regex;
use serde_json::Value;
use std::collections::BTreeMap;
static MB_LIMIT: RateLimiter = RateLimiter::new(1100);
pub fn provider_name(p: &str) -> &'static str {
match p {
"deezer" => "Deezer",
"itunes" => "iTunes",
"musicbrainz" => "MusicBrainz",
_ => "Source",
}
}
#[derive(Clone, Debug, Default)]
pub struct Candidate {
pub provider: String,
pub title: String,
pub artists: Vec<String>,
pub album: String,
pub album_artist: String,
pub track_number: Option<i64>,
pub track_total: Option<i64>,
pub disc_number: Option<i64>,
pub year: String,
pub genre: String,
pub isrc: String,
pub cover_url: String,
pub duration: Option<f64>,
pub score: f64,
pub id: String,
pub url: String,
pub album_id: Option<i64>,
}
impl Candidate {
pub fn artist(&self) -> String {
self.artists.join(", ")
}
}
pub fn js(v: &Value, k: &str) -> String {
match v.get(k) {
Some(Value::String(s)) => s.clone(),
Some(Value::Number(n)) => n.to_string(),
_ => String::new(),
}
}
pub fn ji(v: &Value, k: &str) -> Option<i64> {
v.get(k).and_then(|x| x.as_i64().or_else(|| x.as_f64().map(|f| f as i64)))
}
pub fn jf(v: &Value, k: &str) -> Option<f64> {
v.get(k).and_then(|x| x.as_f64())
}
pub fn jarr<'a>(v: &'a Value, k: &str) -> &'a [Value] {
v.get(k).and_then(|x| x.as_array()).map(|a| a.as_slice()).unwrap_or(&[])
}
fn score(track: &Track, title: &str, artists: &[String], c: &Candidate) -> f64 {
let mut s = match_score(title, artists, track.duration, &c.title, &c.artists, c.duration);
s -= album_penalty(&track.album, &c.album);
// Between equally good matches, prefer the album release over a single.
static SINGLE: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| Regex::new(r"(?i)-\s*(single|ep)$").unwrap());
if !c.album.is_empty() && normalize(&c.album) != normalize(&c.title) && !SINGLE.is_match(&c.album) {
s += 0.02;
}
s.max(0.0)
}
fn query_parts(track: &Track) -> (String, Vec<String>) {
let title = strip_feat(&clean_title(&track.value("title")));
let artist = track.value("artist");
static SPLIT: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| Regex::new(r"(?i),|&| x | feat\.? ").unwrap());
let artists = if artist.is_empty() { vec![] } else { SPLIT.split(&artist).map(|a| a.trim().to_string()).filter(|a| !a.is_empty()).collect() };
(title, artists)
}
fn sort(mut v: Vec<Candidate>) -> Vec<Candidate> {
v.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));
v
}
// ---- iTunes --------------------------------------------------------------------
pub fn itunes_cover(url: &str, size: i64) -> String {
static R: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| Regex::new(r"/\d+x\d+bb\.").unwrap());
if url.is_empty() {
return String::new();
}
R.replace(url, format!("/{size}x{size}bb.")).into_owned()
}
fn itunes_candidate(r: &Value, cover_size: i64) -> Candidate {
let artist = js(r, "artistName");
Candidate {
provider: "itunes".into(),
title: js(r, "trackName"),
artists: vec![artist.clone()],
album: js(r, "collectionName"),
album_artist: Some(js(r, "collectionArtistName")).filter(|s| !s.is_empty()).unwrap_or(artist),
track_number: ji(r, "trackNumber"),
track_total: ji(r, "trackCount"),
disc_number: ji(r, "discNumber"),
year: parse_year(&js(r, "releaseDate")),
genre: js(r, "primaryGenreName"),
cover_url: itunes_cover(&js(r, "artworkUrl100"), cover_size),
duration: ji(r, "trackTimeMillis").filter(|m| *m > 0).map(|m| m as f64 / 1000.0),
id: js(r, "trackId"),
url: js(r, "trackViewUrl"),
..Default::default()
}
}
pub fn search_itunes(track: &Track, cover_size: i64) -> Result<Vec<Candidate>, String> {
let (title, artists) = query_parts(track);
let term = format!("{} {}", artists.first().cloned().unwrap_or_default(), title).trim().to_string();
let data = http::get_json("https://itunes.apple.com/search", &[("term", term), ("entity", "song".into()), ("limit", "15".into()), ("media", "music".into())], false, &[])?;
let out = jarr(&data, "results")
.iter()
.map(|r| {
let mut c = itunes_candidate(r, cover_size);
c.score = score(track, &title, &artists, &c);
c
})
.collect();
Ok(sort(out))
}
pub fn itunes_lookup(id: &str, country: &str, entity: Option<&str>) -> Result<Vec<Value>, String> {
let mut p = vec![("id", id.to_string()), ("country", country.to_string())];
if let Some(e) = entity {
p.push(("entity", e.to_string()));
}
Ok(jarr(&http::get_json("https://itunes.apple.com/lookup", &p, false, &[])?, "results").to_vec())
}
// ---- Deezer --------------------------------------------------------------------
pub fn deezer_cover(url: &str, size: i64) -> String {
static R: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| Regex::new(r"/\d+x\d+-").unwrap());
if url.is_empty() {
return String::new();
}
let s = size.min(1900);
R.replace(url, format!("/{s}x{s}-")).into_owned()
}
pub fn search_deezer(track: &Track, cover_size: i64) -> Result<Vec<Candidate>, String> {
let (title, artists) = query_parts(track);
let q = format!("{} {}", artists.first().cloned().unwrap_or_default(), title).trim().to_string();
let data = http::get_json("https://api.deezer.com/search", &[("q", q), ("limit", "15".into())], false, &[])?;
if let Some(e) = data.get("error") {
return Err(js(e, "message"));
}
let out = jarr(&data, "data")
.iter()
.map(|r| {
let album = r.get("album").cloned().unwrap_or(Value::Null);
let mut c = Candidate {
provider: "deezer".into(),
title: js(r, "title"),
artists: vec![js(r.get("artist").unwrap_or(&Value::Null), "name")],
album: js(&album, "title"),
cover_url: deezer_cover(&js(&album, "cover_xl"), cover_size),
duration: jf(r, "duration"),
isrc: js(r, "isrc"),
id: js(r, "id"),
url: js(r, "link"),
album_id: ji(&album, "id"),
..Default::default()
};
c.score = score(track, &title, &artists, &c);
c
})
.collect();
Ok(sort(out))
}
/// Search results lack track numbers, dates and genres; fetch them for the chosen one.
pub fn deezer_details(mut c: Candidate, cover_size: i64) -> Candidate {
let go = |c: &mut Candidate| -> Result<(), String> {
let t = http::get_json(&format!("https://api.deezer.com/track/{}", c.id), &[], false, &[])?;
if t.get("error").is_some() {
return Ok(());
}
c.track_number = ji(&t, "track_position").or(c.track_number);
c.disc_number = ji(&t, "disk_number").or(c.disc_number);
let y = parse_year(&js(&t, "release_date"));
if !y.is_empty() {
c.year = y;
}
if !js(&t, "isrc").is_empty() {
c.isrc = js(&t, "isrc");
}
let main: Vec<String> = jarr(&t, "contributors").iter().filter(|x| js(x, "role") == "Main").map(|x| js(x, "name")).collect();
if !main.is_empty() {
c.artists = main;
}
let album_id = t.get("album").and_then(|a| ji(a, "id")).or(c.album_id);
if let Some(id) = album_id {
let a = http::get_json(&format!("https://api.deezer.com/album/{id}"), &[], false, &[])?;
if a.get("error").is_none() {
if !js(&a, "title").is_empty() {
c.album = js(&a, "title");
}
c.album_artist = js(a.get("artist").unwrap_or(&Value::Null), "name");
c.track_total = ji(&a, "nb_tracks");
c.genre = a.get("genres").map(|g| jarr(g, "data")).and_then(|g| g.first()).map(|g| js(g, "name")).unwrap_or_default();
let y = parse_year(&js(&a, "release_date"));
if !y.is_empty() {
c.year = y;
}
let cv = deezer_cover(&js(&a, "cover_xl"), cover_size);
if !cv.is_empty() {
c.cover_url = cv;
}
}
}
Ok(())
};
let _ = go(&mut c); // details are a bonus
c
}
// ---- MusicBrainz ---------------------------------------------------------------
fn lucene(t: &str) -> String {
static R: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| Regex::new(r#"([+\-!(){}\[\]^"~*?:\\/]|&&|\|\|)"#).unwrap());
R.replace_all(t, r"\$1").into_owned()
}
pub fn search_musicbrainz(track: &Track, cover_size: i64) -> Result<Vec<Candidate>, String> {
let (title, artists) = query_parts(track);
let mut q = format!("recording:\"{}\"", lucene(&title));
if let Some(a) = artists.first() {
q += &format!(" AND artist:\"{}\"", lucene(a));
}
MB_LIMIT.wait();
let data = http::get_json("https://musicbrainz.org/ws/2/recording", &[("query", q), ("fmt", "json".into()), ("limit", "10".into())], false, &[])?;
let mut out = vec![];
for r in jarr(&data, "recordings") {
let credit = jarr(r, "artist-credit");
let names: Vec<String> = credit.iter().map(|x| js(x, "name")).collect();
let rank = |rel: &&Value| {
let group = rel.get("release-group").cloned().unwrap_or(Value::Null);
(
js(rel, "status") == "Official",
js(&group, "primary-type") == "Album",
jarr(&group, "secondary-types").is_empty(),
-(parse_year(&js(rel, "date")).parse::<i64>().unwrap_or(9999)),
)
};
let rel = jarr(r, "releases").iter().max_by_key(rank).cloned().unwrap_or(Value::Null);
let media = jarr(&rel, "media").first().cloned().unwrap_or(Value::Null);
let tr = jarr(&media, "track").first().cloned().unwrap_or(Value::Null);
let size = if cover_size >= 1000 { 1200 } else { 500 };
let rel_credit = jarr(&rel, "artist-credit");
let album_artist = (if rel_credit.is_empty() { credit } else { rel_credit }).iter().map(|x| js(x, "name")).collect::<Vec<_>>().join(", ");
let mut tags: Vec<&Value> = jarr(r, "tags").iter().collect();
tags.sort_by_key(|t| -ji(t, "count").unwrap_or(0));
let mut c = Candidate {
provider: "musicbrainz".into(),
title: js(r, "title"),
artists: names,
album: js(&rel, "title"),
album_artist,
track_number: to_int(&js(&tr, "number")),
track_total: ji(&media, "track-count"),
disc_number: ji(&media, "position"),
year: parse_year(&{
let d = js(&rel, "date");
if d.is_empty() { js(r, "first-release-date") } else { d }
}),
isrc: jarr(r, "isrcs").first().and_then(|v| v.as_str()).unwrap_or("").to_string(),
cover_url: if js(&rel, "id").is_empty() { String::new() } else { format!("https://coverartarchive.org/release/{}/front-{size}", js(&rel, "id")) },
duration: ji(r, "length").filter(|l| *l > 0).map(|l| l as f64 / 1000.0),
id: js(r, "id"),
url: format!("https://musicbrainz.org/recording/{}", js(r, "id")),
genre: tags.first().map(|t| title_case(&js(t, "name"))).unwrap_or_default(),
..Default::default()
};
c.score = score(track, &title, &artists, &c);
out.push(c);
}
Ok(sort(out))
}
fn title_case(s: &str) -> String {
s.split(' ').map(|w| {
let mut cs = w.chars();
match cs.next() {
Some(f) => f.to_uppercase().collect::<String>() + &cs.as_str().to_lowercase(),
None => String::new(),
}
}).collect::<Vec<_>>().join(" ")
}
pub fn search_one(name: &str, track: &Track, cover_size: i64) -> Result<Vec<Candidate>, String> {
match name {
"deezer" => search_deezer(track, cover_size),
"itunes" => search_itunes(track, cover_size),
"musicbrainz" => search_musicbrainz(track, cover_size),
_ => Ok(vec![]),
}
}
/// Every enabled provider's candidates, best first.
pub fn search_all(track: &Track, providers: &[String], cover_size: i64, log: Log) -> BTreeMap<String, Vec<Candidate>> {
let mut results = BTreeMap::new();
std::thread::scope(|s| {
let handles: Vec<_> = providers.iter().map(|p| (p.clone(), s.spawn(move || search_one(p, track, cover_size)))).collect();
for (name, h) in handles {
match h.join().unwrap_or_else(|_| Err("panicked".into())) {
Ok(c) => {
results.insert(name, c);
}
Err(e) => {
log("warning", &format!("{} lookup failed: {e}", provider_name(&name)));
results.insert(name, vec![]);
}
}
}
});
results
}
// ---- choosing values per field -------------------------------------------------
const ALBUM_FIELDS: &[&str] = &["album", "album_artist", "track_number", "disc_number", "year", "cover"];
fn auto_order(key: &str) -> &'static [&'static str] {
match key {
"genre" => &["itunes", "deezer", "musicbrainz"],
"isrc" => &["deezer", "musicbrainz", "itunes"],
"cover" => &["itunes", "deezer", "musicbrainz"],
_ => &["deezer", "itunes", "musicbrainz"],
}
}
/// Providers by match quality; near-ties (within 0.05) keep the field's preferred order.
fn ranked(best: &BTreeMap<String, Candidate>, order: &[&str]) -> Vec<String> {
let present: Vec<&str> = order.iter().copied().filter(|p| best.contains_key(*p)).collect();
if present.is_empty() {
return vec![];
}
let top = present.iter().map(|p| best[*p].score).fold(f64::MIN, f64::max);
let (near, rest): (Vec<&str>, Vec<&str>) = present.into_iter().partition(|p| best[*p].score >= top - 0.05);
let mut rest = rest;
rest.sort_by(|a, b| best[*b].score.partial_cmp(&best[*a].score).unwrap_or(std::cmp::Ordering::Equal));
near.into_iter().chain(rest).map(String::from).collect()
}
fn candidate_str(c: &Candidate, key: &str) -> Option<String> {
let non = |s: &str| Some(s.to_string()).filter(|s| !s.is_empty());
let num = |n: Option<i64>| n.map(|n| n.to_string());
match key {
"cover" => non(&c.cover_url),
"album" => non(&c.album),
"album_artist" => non(&c.album_artist),
"year" => non(&c.year),
"genre" => non(&c.genre),
"isrc" => non(&c.isrc),
"title" => non(&c.title),
"track_number" => num(c.track_number),
"disc_number" => num(c.disc_number),
_ => None,
}
}
fn apply(track: &mut Track, key: &str, cand: &Candidate) {
match key {
"artist" => track.artists = cand.artists.iter().filter(|a| !a.is_empty()).cloned().collect(),
"cover" => track.cover_url = cand.cover_url.clone(),
"track_number" => {
track.track_number = cand.track_number;
if cand.track_total.is_some() {
track.track_total = cand.track_total;
}
}
"title" => track.title = cand.title.clone(),
"album" => track.album = cand.album.clone(),
"album_artist" => track.album_artist = cand.album_artist.clone(),
"disc_number" => track.disc_number = cand.disc_number,
"year" => track.year = cand.year.clone(),
"genre" => track.genre = cand.genre.clone(),
"isrc" => track.isrc = cand.isrc.clone(),
_ => {}
}
}
fn has_value(c: &Candidate, key: &str) -> bool {
if key == "artist" { !c.artists.is_empty() } else { candidate_str(c, key).is_some() }
}
/// Fill the track's tags from the best matches, following the per-field settings.
pub fn enrich(track: &mut Track, snap: &Value, log: Log) -> BTreeMap<String, Vec<Candidate>> {
if !get_bool(snap, "metadata.enabled") {
track.enriched = true;
return BTreeMap::new();
}
let mut providers: Vec<String> = lookup(snap, "metadata.providers").and_then(|v| v.as_object()).map(|o| o.iter().filter(|(_, v)| v.as_bool().unwrap_or(false)).map(|(k, _)| k.clone()).collect()).unwrap_or_default();
let fields: Vec<(String, String)> = lookup(snap, "metadata.fields").and_then(|v| v.as_object()).map(|o| o.iter().map(|(k, v)| (k.clone(), v.as_str().unwrap_or("auto").to_string())).collect()).unwrap_or_default();
// A field pinned to a provider needs that provider even when it is off for "auto".
for (_, src) in &fields {
if ["deezer", "itunes", "musicbrainz"].contains(&src.as_str()) && !providers.contains(src) {
providers.push(src.clone());
}
}
let threshold = { let t = get_f64(snap, "metadata.match_threshold"); if t > 0.0 { t } else { 0.72 } };
let cover_size = { let c = get_i64(snap, "metadata.cover_size"); if c > 0 { c } else { 1200 } };
let results = if providers.is_empty() { BTreeMap::new() } else { search_all(track, &providers, cover_size, log) };
let mut best: BTreeMap<String, Candidate> = BTreeMap::new();
for (name, cands) in &results {
if let Some(c) = cands.first().filter(|c| c.score >= threshold) {
best.insert(name.clone(), c.clone());
}
}
if let Some(d) = best.remove("deezer") {
best.insert("deezer".into(), deezer_details(d, cover_size));
}
for (name, c) in &best {
log("meta", &format!("{}: {} – {} [{}] (match {:.0}%)", provider_name(name), c.artist(), c.title, c.album, c.score * 100.0));
}
if !providers.is_empty() && best.is_empty() {
log("warning", "No confident metadata match; keeping the source's tags");
}
// When the source already names the album, only trust candidates from that album for album fields.
let same_album = |track: &Track, c: &Candidate| !(track.authoritative && !track.album.is_empty()) || similarity(&track.album, &c.album) >= 0.6;
let album_cands: Vec<&str> = ["deezer", "itunes", "musicbrainz"].into_iter().filter(|n| best.get(*n).map(|c| same_album(track, c)).unwrap_or(false)).collect();
let album_source = album_cands.iter().max_by(|a, b| best[**a].score.partial_cmp(&best[**b].score).unwrap_or(std::cmp::Ordering::Equal)).map(|s| s.to_string());
let mut skip: Vec<String> = track.skip_fields.clone();
for (key, src) in &fields {
if track.overrides.contains_key(key) {
continue;
}
if src == "off" {
if !skip.contains(key) {
skip.push(key.clone());
}
continue;
}
skip.retain(|k| k != key);
if src == "source" {
continue;
}
let order: Vec<String> = if ["deezer", "itunes", "musicbrainz"].contains(&src.as_str()) {
vec![src.clone()]
} else if ALBUM_FIELDS.contains(&key.as_str()) && album_source.is_some() {
let a = album_source.clone().unwrap();
let mut o = vec![a.clone()];
o.extend(ranked(&best, auto_order(key)).into_iter().filter(|p| *p != a));
o
} else {
ranked(&best, auto_order(key))
};
let source_has = match key.as_str() {
"cover" => !track.cover_url.is_empty(),
"artist" => !track.artists.is_empty(),
"title" => !track.title.is_empty(),
"album" => !track.album.is_empty(),
"album_artist" => !track.album_artist.is_empty(),
"year" => !track.year.is_empty(),
_ => false,
};
if src == "auto" && source_has && (key == "title" || key == "artist" || (track.authoritative && ["album", "album_artist", "year"].contains(&key.as_str()))) {
continue; // what the user picked names the song; Spotify and friends also know their albums
}
let mut usable: Vec<&Candidate> = order.iter().filter_map(|n| best.get(n)).filter(|c| !ALBUM_FIELDS.contains(&key.as_str()) || same_album(track, c)).collect();
if key == "isrc" {
usable.retain(|c| c.score >= 0.9); // an ISRC pins one exact recording
}
if key == "year" && src == "auto" {
if let Some(top) = usable.first().map(|c| c.score) {
let years: Vec<&String> = usable.iter().filter(|c| !c.year.is_empty() && c.score >= top - 0.05).map(|c| &c.year).collect();
if let Some(y) = years.into_iter().min() {
track.year = y.clone();
}
}
continue;
}
if let Some(c) = usable.into_iter().find(|c| has_value(c, key)) {
let c = c.clone();
apply(track, key, &c);
}
}
skip.sort();
track.skip_fields = skip;
track.enriched = true;
results
}
/// The tag editor's 'use this match' button: take every field from one candidate.
pub fn apply_candidate(track: &mut Track, c: &Candidate) {
for key in ["title", "artist", "album", "album_artist", "track_number", "disc_number", "year", "genre", "isrc", "cover"] {
if has_value(c, key) {
apply(track, key, c);
}
}
}

25
src/core/mod.rs Normal file
View file

@ -0,0 +1,25 @@
//! Everything that isn't UI: link resolving, matching, tags, lyrics, downloading.
pub mod covers;
pub mod downloader;
pub mod http;
pub mod library;
pub mod lyrics;
pub mod matcher;
pub mod metadata;
pub mod models;
pub mod paths;
pub mod resolvers;
pub mod settings;
pub mod spotify;
pub mod tagger;
pub mod template;
pub mod textutil;
pub mod ytdlp;
pub mod ytmusic;
/// Log callback: (kind, text). Kinds: info, warning, error, success, yt, meta, match, progress, debug.
pub type Log<'a> = &'a (dyn Fn(&str, &str) + Sync);
pub type Res<T> = Result<T, String>;
pub fn no_log(_: &str, _: &str) {}

Some files were not shown because too many files have changed in this diff Show more