suno_core/desired.rs
1//! Pure desired-state construction: clip target entries and playlist manifests.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::path::{Component, Path};
5
6use crate::extras::{M3u8Entry, render_clip_details, render_m3u8};
7use crate::hash::{
8 art_hash, art_url_hash, content_hash, embedded_art_hash, meta_hash, synced_lrc_source_hash,
9 webp_art_hash,
10};
11use crate::lineage::LineageContext;
12use crate::lyrics::render_clip_lyrics;
13use crate::model::Clip;
14use crate::model::Stem;
15use crate::naming::{
16 CharacterSet, NamingConfig, NamingRequest, render_clip_names, sanitise_name, stem_file_path,
17};
18use crate::reconcile::{AlbumDesired, Desired, DesiredArtifact, DesiredStem, PlaylistDesired};
19use crate::vocab::{ArtifactKind, AudioFormat, SourceMode, StemFormat, WebpEncodeSettings};
20
21/// The synthetic playlist id for the liked feed, rendered as "Liked Songs".
22///
23/// Suno playlist ids are UUIDs, so this short literal never collides with a real
24/// playlist id in the store keyspace.
25pub const LIKED_PLAYLIST_ID: &str = "liked";
26
27/// The per-song sidecar toggles resolved for a run: each embeds or writes one
28/// artefact (animated WebP cover, `.details.txt`, `.lyrics.txt`, synced `.lrc`,
29/// standalone `.mp4`). All default off.
30#[derive(Debug, Clone, Copy, Default)]
31pub struct ArtifactToggles {
32 pub animated_covers: bool,
33 pub details: bool,
34 pub lyrics: bool,
35 pub lrc: bool,
36 pub video: bool,
37 /// The animated-cover encode settings, folded into the embedded-cover hash
38 /// (see [`embedded_art_hash`]) so a settings change re-embeds existing covers.
39 pub webp: WebpEncodeSettings,
40}
41
42/// One fetched playlist to render: its stable id, display name, and ordered
43/// member clips (already non-trashed, in Suno order).
44pub struct PlaylistInput<'a> {
45 pub id: &'a str,
46 pub name: &'a str,
47 pub members: &'a [Clip],
48}
49
50/// Build the desired target state for a union of selected clips.
51///
52/// Naming is rendered as a batch so collisions are disambiguated globally. Each
53/// clip's `modes` is stamped from `modes_by_id` — every selected area (mirror
54/// and copy alike) that holds it — so a clip in both a `Mirror` and a `Copy`
55/// carries both and copy-wins protection holds (SYNC-8). Every clip must appear
56/// in the map; an empty `modes` would silently drop that protection, so it trips
57/// a `debug_assert` (D6) and in release defaults to unprotected.
58///
59/// `contexts` supplies each clip's resolved [`LineageContext`] (album, lineage
60/// tags, change hash), falling back to a self-rooted context when absent.
61/// `colliding_albums` is the set of root titles shared by more than one root; a
62/// clip in that set is folded into a `[{root_id8}]`-suffixed folder so two roots
63/// never share one. `colliding_ids` is the file-name counterpart: the set of
64/// clip ids sharing an `{id8}` with another distinct clip archive-wide, so a
65/// clip in it gets a stable full-id suffix regardless of the batch (#356).
66/// `toggles` gates the per-song sidecars in [`clip_artifacts`].
67#[allow(clippy::too_many_arguments)]
68pub fn build_desired(
69 clips: &[&Clip],
70 format: AudioFormat,
71 modes_by_id: &HashMap<String, Vec<SourceMode>>,
72 contexts: &HashMap<String, LineageContext>,
73 colliding_albums: &BTreeSet<String>,
74 colliding_ids: &BTreeSet<String>,
75 toggles: ArtifactToggles,
76 naming: &NamingConfig,
77) -> Vec<Desired> {
78 let lineages: Vec<LineageContext> = clips
79 .iter()
80 .map(|clip| {
81 contexts
82 .get(&clip.id)
83 .cloned()
84 .unwrap_or_else(|| LineageContext::own_root(clip))
85 })
86 .collect();
87 // The requests borrow `lineages`; scope them so the borrow ends before the
88 // lineages are moved into the desired entries below.
89 let names = {
90 let requests: Vec<NamingRequest<'_>> = clips
91 .iter()
92 .zip(&lineages)
93 .map(|(clip, lineage)| NamingRequest { clip, lineage })
94 .collect();
95 render_clip_names(&requests, naming, colliding_albums, colliding_ids)
96 };
97
98 clips
99 .iter()
100 .zip(names)
101 .zip(lineages)
102 .map(|((clip, name), lineage)| {
103 // The extensionless audio path; the sidecars swap the extension.
104 let base = rel_to_string(&name.relative_path);
105 let path = format!("{base}.{}", format.ext());
106 let meta_hash = meta_hash(clip, &lineage);
107 let modes = modes_by_id.get(&clip.id).cloned().unwrap_or_default();
108 // D6: empty modes would silently lose SYNC-8 copy protection.
109 debug_assert!(
110 !modes.is_empty(),
111 "clip {} has no modes in the union map",
112 clip.id
113 );
114 // Bind the artifacts before the struct literal so `&lineage` is
115 // borrowed (for the details render) before it is moved in below.
116 let artifacts = clip_artifacts(clip, &base, &lineage, toggles);
117 Desired {
118 clip: (*clip).clone(),
119 lineage,
120 path,
121 format,
122 meta_hash,
123 art_hash: embedded_art_hash(
124 clip,
125 toggles.animated_covers && format.embeds_animated_cover(),
126 &toggles.webp,
127 ),
128 // Always overwritten at the synced-lyrics resolve seam
129 // (`apply_synced_lrc`/`preview_synced_lrc`) before reconcile; the
130 // empty default only matters for this struct literal itself.
131 embedded_lyrics_hash: String::new(),
132 modes,
133 trashed: clip.is_trashed,
134 private: false,
135 artifacts,
136 // Stems are threaded in after this pure pass (they need a network
137 // listing); `None` means "no authoritative stem info", so a run
138 // without `download_stems` leaves any local stems untouched.
139 stems: None,
140 }
141 })
142 .collect()
143}
144
145/// Build the authoritative desired stem set for one clip from its listed stems.
146///
147/// Each stem file sits in the `{base}.stems/` sub-folder. Keys are the stable
148/// stem id (falling back to label, then a positional key), de-duplicated so
149/// blank or duplicate labels never collide. Stems are stored RAW (WAV or MP3),
150/// never transcoded; the rewrite hash tracks the stem's public URL. A `Wav` stem
151/// needs its own id to render, so an id-less stem falls back to `Mp3`.
152///
153/// Only ever called with an AUTHORITATIVE listing, so the result is safe to
154/// drive stem removals against.
155pub fn clip_stems(
156 base: &str,
157 stems: &[Stem],
158 stem_format: StemFormat,
159 character_set: CharacterSet,
160) -> Vec<DesiredStem> {
161 let mut seen: BTreeSet<String> = BTreeSet::new();
162 let mut out = Vec::new();
163 for (index, stem) in stems.iter().enumerate() {
164 let base_key = if !stem.id.is_empty() {
165 stem.id.clone()
166 } else if !stem.label.is_empty() {
167 stem.label.clone()
168 } else {
169 format!("stem{index}")
170 };
171 // Keep the key unique even when ids are blank and labels duplicate.
172 let mut key = base_key.clone();
173 let mut suffix = 1;
174 while !seen.insert(key.clone()) {
175 key = format!("{base_key}-{suffix}");
176 suffix += 1;
177 }
178 // Disambiguate by stable stem id when present, else the key, so two
179 // stems never map to the same file.
180 let disambiguator = if stem.id.is_empty() {
181 key.as_str()
182 } else {
183 stem.id.as_str()
184 };
185 // WAV needs the stem's own id to render; without one, store as MP3.
186 let format = if stem_format == StemFormat::Wav && stem.id.is_empty() {
187 StemFormat::Mp3
188 } else {
189 stem_format
190 };
191 let path = stem_file_path(
192 base,
193 &stem.label,
194 disambiguator,
195 format.ext(),
196 character_set,
197 );
198 out.push(DesiredStem {
199 key,
200 stem_id: stem.id.clone(),
201 path,
202 source_url: stem.url.clone(),
203 format,
204 hash: art_url_hash(&stem.url),
205 });
206 }
207 out
208}
209
210/// The per-clip sidecars desired alongside `base`, the extensionless audio path.
211///
212/// A static `CoverJpg` is emitted only when the clip has non-empty selected art;
213/// an empty art URL emits none, and reconcile reads a missing cover as
214/// UNKNOWN => KEEP, so a transient empty URL never removes an existing cover. The
215/// animated cover is not a sidecar: under `toggles.animated_covers` it is
216/// embedded as the audio file's front cover.
217///
218/// Text sidecars carry their body inline plus a `content_hash`, so an edit
219/// rewrites them even when `meta_hash` is unchanged. `DetailsTxt` is emitted
220/// whenever `toggles.details` is set; `LyricsTxt` only when the clip has lyrics,
221/// so no empty file is written. `Lrc` is emitted for every clip under
222/// `toggles.lrc` (alignment is knowable only from the endpoint, not the feed)
223/// with no inline body, resolved just before execution; a clip with neither
224/// alignment nor lyrics writes nothing, its emptiness cached so it is not
225/// re-fetched.
226fn clip_artifacts(
227 clip: &Clip,
228 base: &str,
229 lineage: &LineageContext,
230 toggles: ArtifactToggles,
231) -> Vec<DesiredArtifact> {
232 let mut artifacts = Vec::new();
233 if let Some(url) = clip.selected_image_url().filter(|u| !u.is_empty()) {
234 artifacts.push(DesiredArtifact {
235 kind: ArtifactKind::CoverJpg,
236 path: sidecar_path(base, ArtifactKind::CoverJpg),
237 source_url: url.to_owned(),
238 hash: art_hash(clip),
239 content: None,
240 });
241 }
242 if toggles.details {
243 let text = render_clip_details(clip, lineage);
244 artifacts.push(DesiredArtifact {
245 kind: ArtifactKind::DetailsTxt,
246 path: sidecar_path(base, ArtifactKind::DetailsTxt),
247 source_url: String::new(),
248 hash: content_hash(&text),
249 content: Some(text),
250 });
251 }
252 if toggles.lyrics
253 && let Some(text) = render_clip_lyrics(clip)
254 {
255 artifacts.push(DesiredArtifact {
256 kind: ArtifactKind::LyricsTxt,
257 path: sidecar_path(base, ArtifactKind::LyricsTxt),
258 source_url: String::new(),
259 hash: content_hash(&text),
260 content: Some(text),
261 });
262 }
263 if toggles.lrc {
264 artifacts.push(DesiredArtifact {
265 kind: ArtifactKind::Lrc,
266 path: sidecar_path(base, ArtifactKind::Lrc),
267 source_url: String::new(),
268 hash: synced_lrc_source_hash(&clip.id),
269 content: None,
270 });
271 }
272 if toggles.video && !clip.video_url.is_empty() {
273 artifacts.push(DesiredArtifact {
274 kind: ArtifactKind::VideoMp4,
275 path: sidecar_path(base, ArtifactKind::VideoMp4),
276 source_url: clip.video_url.clone(),
277 hash: art_url_hash(&clip.video_url),
278 content: None,
279 });
280 }
281 artifacts
282}
283
284/// The path of a per-clip sidecar built from the song's extensionless `base`.
285///
286/// The per-kind extension lives once on [`ArtifactKind::sidecar_suffix`] (#355),
287/// so the desired path and reconcile's stranded-sidecar relocation derive it
288/// from the same source. The `.expect` is only ever reached with a per-clip
289/// kind and fails loudly on a future miswiring, matching the codebase's
290/// existing guard style.
291fn sidecar_path(base: &str, kind: ArtifactKind) -> String {
292 format!(
293 "{base}{}",
294 kind.sidecar_suffix()
295 .expect("per-clip sidecar kind has a suffix")
296 )
297}
298
299/// Build the desired `.m3u8` playlists for this run from the fetched playlists.
300///
301/// Each input is rendered in Suno order: every member clip id is looked up in
302/// this run's `desired` audio set for its relative path, title, and duration. A
303/// member absent from that set is emitted as a `# (not in library)` comment (an
304/// empty relative path) rather than a dangling path (HARDENING L1). The content
305/// hash covers the whole rendered body so any name, order, path, title, or
306/// duration change rewrites the file (HARDENING B1), named
307/// `<sanitised name>.m3u8` at the library root.
308///
309/// Pure: the caller does the best-effort fetching, excludes any playlist whose
310/// member fetch failed, and appends the synthetic liked feed.
311pub fn build_playlist_desired(
312 inputs: &[PlaylistInput<'_>],
313 desired: &[Desired],
314) -> Vec<PlaylistDesired> {
315 let by_id: HashMap<&str, &Desired> = desired.iter().map(|d| (d.clip.id.as_str(), d)).collect();
316 inputs
317 .iter()
318 .map(|input| {
319 let entries: Vec<M3u8Entry<'_>> = input
320 .members
321 .iter()
322 .map(|member| match by_id.get(member.id.as_str()) {
323 Some(d) => M3u8Entry {
324 title: d.clip.title.as_str(),
325 duration_secs: d.clip.duration,
326 relative_path: d.path.as_str(),
327 },
328 None => M3u8Entry {
329 title: member.title.as_str(),
330 duration_secs: member.duration,
331 relative_path: "",
332 },
333 })
334 .collect();
335 let content = render_m3u8(input.name, &entries);
336 let hash = content_hash(&content);
337 let path = format!("{}.m3u8", sanitise_name(input.name));
338 PlaylistDesired {
339 id: input.id.to_owned(),
340 name: input.name.to_owned(),
341 path,
342 content,
343 hash,
344 }
345 })
346 .collect()
347}
348
349/// Render a relative path as a forward-slash string, dropping any non-normal
350/// component so the stored path is portable and never escapes the root.
351///
352/// The single source of truth for turning a rendered path into a stored/compared
353/// one: `/`-separated on every OS, so manifest paths, `parent_dir`, and the
354/// deletion-safety checks behave identically across platforms.
355pub(crate) fn rel_to_string(path: &Path) -> String {
356 path.components()
357 .filter_map(|component| match component {
358 Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
359 _ => None,
360 })
361 .collect::<Vec<_>>()
362 .join("/")
363}
364
365/// Derive the desired folder art for every album in `desired`, grouped by the
366/// stable root id (HARDENING H2).
367///
368/// This is pure: it groups the selected clips by their resolved `root_id`, then
369/// per album chooses the folder-art sources deterministically:
370///
371/// - `folder.jpg` comes from the MOST-PLAYED art-bearing variant; ties break to
372/// the EARLIEST `created_at`, then the lexicographically smallest id. Its hash
373/// is the chosen art's content hash ([`art_hash`]), so a most-played flip to a
374/// variant sharing the same art is a no-op downstream (H1).
375/// - `cover.webp` (only when `animated_covers` is set) comes from the
376/// EARLIEST-created variant with a non-empty `video_cover_url`; ties break to
377/// the smallest id. Its hash folds in the `webp` encode settings, so changing
378/// quality/lossless/effort re-transcodes it. `None` when no variant has an
379/// animated source.
380/// - `cover.mp4` (only when `raw_cover` is set) is that same variant's
381/// `video_cover_url` kept verbatim (no transcode), so `both` yields the raw
382/// source beside its WebP re-encode. `None` when no variant has an animated
383/// source.
384///
385/// The album folder is the common parent of the album's clips' audio paths (they
386/// share `{creator}/{album}/`); `folder.jpg` lands at `{album_dir}/folder.jpg`
387/// and the animated covers at `{album_dir}/cover.webp` / `{album_dir}/cover.mp4`.
388pub fn album_desired(
389 desired: &[Desired],
390 animated_covers: bool,
391 raw_cover: bool,
392 webp: WebpEncodeSettings,
393) -> Vec<AlbumDesired> {
394 let mut groups: BTreeMap<&str, Vec<&Desired>> = BTreeMap::new();
395 for d in desired {
396 groups
397 .entry(d.lineage.root_id.as_str())
398 .or_default()
399 .push(d);
400 }
401
402 groups
403 .into_iter()
404 .map(|(root_id, members)| {
405 let album_dir = album_dir_of(&members);
406 let folder_jpg = folder_jpg_source(&members).map(|source| DesiredArtifact {
407 kind: ArtifactKind::FolderJpg,
408 path: album_child(&album_dir, "folder.jpg"),
409 source_url: source.clip.selected_image_url().unwrap_or("").to_owned(),
410 hash: art_hash(&source.clip),
411 content: None,
412 });
413 let folder_webp = animated_covers
414 .then(|| folder_webp_source(&members))
415 .flatten()
416 .map(|source| DesiredArtifact {
417 kind: ArtifactKind::FolderWebp,
418 path: album_child(&album_dir, "cover.webp"),
419 source_url: source.clip.video_cover_url.clone(),
420 hash: webp_art_hash(&source.clip.video_cover_url, &webp),
421 content: None,
422 });
423 let folder_mp4 = raw_cover
424 .then(|| folder_webp_source(&members))
425 .flatten()
426 .map(|source| DesiredArtifact {
427 kind: ArtifactKind::FolderMp4,
428 path: album_child(&album_dir, "cover.mp4"),
429 source_url: source.clip.video_cover_url.clone(),
430 hash: art_url_hash(&source.clip.video_cover_url),
431 content: None,
432 });
433 AlbumDesired {
434 root_id: root_id.to_owned(),
435 folder_jpg,
436 folder_webp,
437 folder_mp4,
438 }
439 })
440 .collect()
441}
442
443/// The album folder: the common parent of the members' audio paths.
444///
445/// The album's clips share `{creator}/{album}/`, so any member's parent is the
446/// album dir; the smallest is taken so a stray differing path stays deterministic.
447fn album_dir_of(members: &[&Desired]) -> String {
448 members
449 .iter()
450 .map(|d| parent_dir(&d.path))
451 .min()
452 .unwrap_or("")
453 .to_owned()
454}
455
456/// The most-played art-bearing variant: the `folder.jpg` source.
457///
458/// Filtered to variants that carry selectable art, then the winner MAXIMISES
459/// `play_count`, breaking ties to the EARLIEST `created_at` and then the
460/// lexicographically smallest id, so selection is fully deterministic.
461fn folder_jpg_source<'a>(members: &[&'a Desired]) -> Option<&'a Desired> {
462 members
463 .iter()
464 .copied()
465 .filter(|d| {
466 d.clip
467 .selected_image_url()
468 .is_some_and(|url| !url.is_empty())
469 })
470 .min_by(|a, b| {
471 b.clip
472 .play_count
473 .cmp(&a.clip.play_count)
474 .then_with(|| a.clip.created_at.cmp(&b.clip.created_at))
475 .then_with(|| a.clip.id.cmp(&b.clip.id))
476 })
477}
478
479/// The first-created animated variant: the `cover.webp` source.
480///
481/// Filtered to variants with a non-empty `video_cover_url`, then the winner is
482/// the EARLIEST `created_at`, tie-broken by the smallest id for determinism.
483fn folder_webp_source<'a>(members: &[&'a Desired]) -> Option<&'a Desired> {
484 members
485 .iter()
486 .copied()
487 .filter(|d| !d.clip.video_cover_url.is_empty())
488 .min_by(|a, b| {
489 a.clip
490 .created_at
491 .cmp(&b.clip.created_at)
492 .then_with(|| a.clip.id.cmp(&b.clip.id))
493 })
494}
495
496/// The parent directory of a forward-slash relative path, or `""` at the root.
497fn parent_dir(path: &str) -> &str {
498 match path.rsplit_once('/') {
499 Some((dir, _)) => dir,
500 None => "",
501 }
502}
503
504/// Join an album dir and a file name with a forward slash, tolerating an empty
505/// dir (a path at the account root).
506fn album_child(album_dir: &str, name: &str) -> String {
507 if album_dir.is_empty() {
508 name.to_owned()
509 } else {
510 format!("{album_dir}/{name}")
511 }
512}
513
514#[cfg(test)]
515mod tests;