Skip to main content

suno_core/
hash.rs

1//! Stable content sentinels for change detection.
2//!
3//! Reconcile compares a clip's current [`meta_hash`]/[`art_hash`] against the
4//! manifest to decide whether a file needs re-tagging. The hashes must be stable
5//! across runs, versions, and platforms, so they use FNV-1a over a fixed field
6//! encoding rather than the standard library's deliberately unspecified hasher.
7//!
8//! The hash inputs are the exact fields the tag writer embeds: [`meta_hash`]
9//! hashes the resolved [`TrackMetadata`], and [`art_hash`] tracks the chosen art
10//! URL. Anything embedded in the file is therefore in a hash, so an upstream
11//! change to it triggers a retag; anything not embedded (path-affecting or
12//! sidecar-only fields such as the animated-cover URL) is excluded.
13
14use std::hash::{Hash, Hasher};
15
16use crate::lineage::LineageContext;
17use crate::model::Clip;
18use crate::tag::TrackMetadata;
19use crate::vocab::WebpEncodeSettings;
20
21/// A short, stable hex digest of `bytes` (FNV-1a, 64-bit).
22fn digest(bytes: &[u8]) -> String {
23    let mut hasher = fnv::FnvHasher::default();
24    hasher.write(bytes);
25    format!("{:016x}", hasher.finish())
26}
27
28/// A stable sentinel over an arbitrary generated text artefact.
29///
30/// Used for playlists, whose `.m3u8` body is generated rather than fetched: the
31/// hash is taken over the full rendered text, so the playlist name, the member
32/// order, and every member's relative path, title, and duration all feed it, and
33/// any change that reaches the file triggers a rewrite. The render is
34/// deterministic, so the hash is stable across runs and platforms.
35pub fn content_hash(text: &str) -> String {
36    digest(text.as_bytes())
37}
38
39/// A sentinel for the clip's embedded tag set.
40///
41/// Hashes the resolved [`TrackMetadata`] actually written into the file (title,
42/// artist, album, date/year, lyrics, prompt, model, handle, and the resolved
43/// lineage tags), so a change to any embedded tag triggers a retag while a
44/// change to a non-embedded field (e.g. the animated-cover URL) does not. Taking
45/// [`TrackMetadata`] directly keeps it in lock-step with the tag writer: if a
46/// value is embedded, it is in this hash. Chosen art is tracked separately by
47/// [`art_hash`], and the embedded aligned lyrics (Suno's fetched alignment, not
48/// `clip.lyrics`) by
49/// [`ManifestEntry::embedded_lyrics_hash`](crate::manifest::ManifestEntry::embedded_lyrics_hash);
50/// both are the invariant's two exceptions, embedded but fingerprinted outside
51/// this hash.
52///
53/// A pure path change is handled as a rename, by comparing the rendered path
54/// with the stored one, not by this hash.
55pub fn meta_hash(clip: &Clip, lineage: &LineageContext) -> String {
56    let mut hasher = fnv::FnvHasher::default();
57    TrackMetadata::from_clip(clip, lineage).hash(&mut hasher);
58    format!("{:016x}", hasher.finish())
59}
60
61/// A stable digest of an artifact source URL (FNV-1a), or the empty string when
62/// `url` is empty.
63///
64/// Shared by [`art_hash`] (the embedded static cover) and the external animated
65/// cover sidecar, whose rewrite detection keys on the clip's `video_cover_url`
66/// rather than the selected image. Keeping both on the one helper means an empty
67/// URL always maps to the empty sentinel, the value reconcile reads as "no such
68/// artifact this run".
69pub fn art_url_hash(url: &str) -> String {
70    if url.is_empty() {
71        String::new()
72    } else {
73        digest(url.as_bytes())
74    }
75}
76
77/// A digest of a transcoded animated-cover source URL *and* the encode settings
78/// that shape its bytes, or the empty string when `url` is empty.
79///
80/// Unlike the raw `cover.mp4` (a verbatim copy, keyed on its URL alone via
81/// [`art_url_hash`]), the animated `cover.webp` and per-song `.webp` are a
82/// transcode: their bytes depend on quality, lossless, effort, frame-rate, and
83/// width as much as on the source. Folding those into the hash means a settings
84/// change (for example raising the default quality) re-encodes existing covers
85/// on the next run, exactly as a changed source URL does, rather than leaving
86/// them stale. An empty URL still maps to the empty "no artifact" sentinel.
87pub fn webp_art_hash(url: &str, settings: &WebpEncodeSettings) -> String {
88    if url.is_empty() {
89        return String::new();
90    }
91    let mut hasher = fnv::FnvHasher::default();
92    hasher.write(url.as_bytes());
93    hasher.write_u8(0);
94    write_webp_settings(&mut hasher, settings);
95    format!("{:016x}", hasher.finish())
96}
97
98/// Fold the WebP encode `settings` into `hasher` in a fixed field order. Shared
99/// by [`webp_art_hash`] and [`embedded_art_hash`] so the settings contribution
100/// to both sentinels stays bit-identical.
101fn write_webp_settings(hasher: &mut fnv::FnvHasher, settings: &WebpEncodeSettings) {
102    hasher.write_u8(settings.quality);
103    hasher.write_u8(u8::from(settings.lossless));
104    hasher.write_u8(settings.compression_level);
105    hasher.write_u32(settings.max_fps);
106    match settings.max_width {
107        Some(width) => {
108            hasher.write_u8(1);
109            hasher.write_u32(width);
110        }
111        None => hasher.write_u8(0),
112    }
113}
114
115/// The change-detection version for the synced `.lrc` body. Bump this when the
116/// rendered `.lrc` format changes so existing sidecars are rewritten on the next
117/// run (their stored hash then no longer matches, exactly as edited content
118/// would move a [`content_hash`]).
119pub const SYNCED_LRC_VERSION: u32 = 2;
120
121/// A stable per-clip source sentinel for the synced `.lrc` sidecar.
122///
123/// Suno's forced alignment for a given clip is immutable (the audio and its
124/// lyrics are fixed once generated), so the sidecar's rewrite detection keys on
125/// the clip id plus the render [`SYNCED_LRC_VERSION`] rather than the fetched
126/// body. This lets reconcile skip an unchanged clip WITHOUT a network fetch (the
127/// timed body is resolved only when a write is actually planned), while a
128/// version bump rewrites every sidecar. It mirrors how the cover sidecars key on
129/// their source URL rather than the fetched bytes ("the hash tracks the source").
130pub fn synced_lrc_source_hash(clip_id: &str) -> String {
131    content_hash(&format!("synced-lrc/v{SYNCED_LRC_VERSION}/{clip_id}"))
132}
133
134/// A sentinel for the embedded cover art: a digest of the selected art URL, or
135/// the empty string when the clip carries no art. A mismatch against the
136/// manifest means the file on disk holds stale art even if its tags are current.
137pub fn art_hash(clip: &Clip) -> String {
138    art_url_hash(clip.selected_image_url().unwrap_or(""))
139}
140
141/// The embedded-cover sentinel that accounts for the animated-WebP embed.
142///
143/// When `embed_animated` is set and the clip has a `video_cover_url`, the file
144/// embeds a bounded animated WebP, so its identity is the source URL, the encode
145/// `settings`, and the static image URL (folded in because the WebP falls back
146/// to that static JPEG when it will not fit, and a later static-art change must
147/// still re-tag a fallen-back file). It hashes the embed intent, not the runtime
148/// fit outcome, so a pure dry-run cannot know the encoded size and a fit fallback
149/// does not churn. Otherwise (feature off, no preview, or an ALAC target, which
150/// cannot embed WebP) it is the plain static [`art_hash`].
151///
152/// Gating on `video_cover_url` presence scopes an enable-time re-tag to clips
153/// that have a preview rather than the whole library. A preview is an immutable
154/// asset the v3 feed returns intact, so this does not flap, and a stale-preview
155/// fallback is bounded tag churn, never data loss.
156pub fn embedded_art_hash(
157    clip: &Clip,
158    embed_animated: bool,
159    settings: &WebpEncodeSettings,
160) -> String {
161    if embed_animated && !clip.video_cover_url.is_empty() {
162        let mut hasher = fnv::FnvHasher::default();
163        hasher.write(b"webp-embed\0");
164        hasher.write(clip.video_cover_url.as_bytes());
165        hasher.write_u8(0);
166        hasher.write(clip.selected_image_url().unwrap_or("").as_bytes());
167        hasher.write_u8(0);
168        write_webp_settings(&mut hasher, settings);
169        format!("{:016x}", hasher.finish())
170    } else {
171        art_hash(clip)
172    }
173}
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use crate::lineage::{EdgeType, ResolveStatus};
179
180    fn sample() -> Clip {
181        Clip {
182            title: "Electric Storm".to_owned(),
183            tags: "ambient, cinematic".to_owned(),
184            image_large_url: "https://cdn1.suno.ai/image_large_abc.jpeg".to_owned(),
185            image_url: "https://cdn1.suno.ai/image_abc.jpeg".to_owned(),
186            video_cover_url: String::new(),
187            prompt: "an orchestral storm".to_owned(),
188            lyrics: "thunder rolls\nover the plains".to_owned(),
189            gpt_description_prompt: "stormy".to_owned(),
190            handle: "alice".to_owned(),
191            display_name: "Alice".to_owned(),
192            ..Default::default()
193        }
194    }
195
196    /// The resolved lineage embedded alongside [`sample`]: an extension of a
197    /// parent under the "Weather Series" root, created in 2023.
198    fn sample_lineage() -> LineageContext {
199        LineageContext {
200            root_id: "root-1".to_owned(),
201            root_title: "Weather Series".to_owned(),
202            root_date: "2023-05-01T00:00:00Z".to_owned(),
203            parent_id: "parent-1".to_owned(),
204            edge_type: Some(EdgeType::Extend),
205            status: ResolveStatus::Resolved,
206            track: 0,
207            track_total: 0,
208        }
209    }
210
211    #[test]
212    fn meta_hash_is_stable() {
213        // Golden value: a change here means the sentinel encoding changed and
214        // every existing manifest would see a spurious retag. Change with care.
215        let h = meta_hash(&sample(), &sample_lineage());
216        assert_eq!(h, "d355c0c463e1f96c");
217        assert_eq!(h.len(), 16);
218        assert_eq!(h, meta_hash(&sample(), &sample_lineage()));
219    }
220
221    #[test]
222    fn art_hash_is_stable_and_empty_without_art() {
223        let h = art_hash(&sample());
224        assert_eq!(h.len(), 16);
225        assert_eq!(h, art_hash(&sample()));
226
227        let mut bare = sample();
228        bare.image_large_url = String::new();
229        bare.image_url = String::new();
230        bare.video_cover_url = String::new();
231        assert_eq!(art_hash(&bare), "");
232    }
233
234    #[test]
235    fn art_url_hash_is_stable_and_empty_for_empty_url() {
236        assert_eq!(art_url_hash(""), "");
237        let h = art_url_hash("https://cdn1.suno.ai/video_cover.mp4");
238        assert_eq!(h.len(), 16);
239        assert_eq!(h, art_url_hash("https://cdn1.suno.ai/video_cover.mp4"));
240        assert_ne!(h, art_url_hash("https://cdn1.suno.ai/other.mp4"));
241        // art_hash routes the selected image URL through the same helper.
242        assert_eq!(
243            art_hash(&sample()),
244            art_url_hash(sample().selected_image_url().unwrap())
245        );
246    }
247
248    #[test]
249    fn webp_art_hash_tracks_url_and_every_encode_setting() {
250        use crate::vocab::WebpEncodeSettings;
251        let url = "https://cdn1.suno.ai/video_cover.mp4";
252        let base = WebpEncodeSettings::default();
253        let h = webp_art_hash(url, &base);
254        assert_eq!(h.len(), 16);
255        assert_eq!(h, webp_art_hash(url, &base), "stable for the same inputs");
256        // Empty URL is the "no artifact" sentinel regardless of settings.
257        assert_eq!(webp_art_hash("", &base), "");
258        // A changed source URL re-transcodes.
259        assert_ne!(h, webp_art_hash("https://cdn1.suno.ai/other.mp4", &base));
260        // Every setting that shapes the output bytes moves the hash, so a
261        // settings change re-encodes an existing cover.
262        for mutate in [
263            |s: &mut WebpEncodeSettings| s.quality = s.quality.wrapping_sub(1),
264            |s: &mut WebpEncodeSettings| s.lossless = !s.lossless,
265            |s: &mut WebpEncodeSettings| s.compression_level = s.compression_level.wrapping_add(1),
266            |s: &mut WebpEncodeSettings| s.max_fps = s.max_fps.wrapping_add(1),
267            |s: &mut WebpEncodeSettings| s.max_width = None,
268        ] {
269            let mut settings = base;
270            mutate(&mut settings);
271            assert_ne!(h, webp_art_hash(url, &settings));
272        }
273    }
274
275    #[test]
276    fn meta_hash_tracks_the_artist_and_model_but_not_sidecar_only_fields() {
277        let lineage = sample_lineage();
278        let base = meta_hash(&sample(), &lineage);
279        // The artist (`display_name`) and model label are embedded tags, so an
280        // upstream change to either must retag.
281        let mut artist = sample();
282        artist.display_name = "Someone Else".to_owned();
283        assert_ne!(meta_hash(&artist, &lineage), base);
284        let mut model = sample();
285        model.model_name = "chirp-v9".to_owned();
286        assert_ne!(meta_hash(&model, &lineage), base);
287        // The animated-cover URL is a sidecar source, not an audio tag: it has
288        // its own hash and must not force a needless audio retag.
289        let mut cover = sample();
290        cover.video_cover_url = "https://cdn1.suno.ai/new_cover.mp4".to_owned();
291        assert_eq!(meta_hash(&cover, &lineage), base);
292    }
293
294    #[test]
295    fn meta_hash_changes_when_a_content_field_changes() {
296        let lineage = sample_lineage();
297        let base = meta_hash(&sample(), &lineage);
298        // Clip-side content fields. (Art lives in `art_hash`, not here.)
299        for mutate in [
300            |c: &mut Clip| c.title = "Different".to_owned(),
301            |c: &mut Clip| c.tags = "lofi".to_owned(),
302            |c: &mut Clip| c.handle = "bob".to_owned(),
303            |c: &mut Clip| c.lyrics = "new words".to_owned(),
304        ] {
305            let mut clip = sample();
306            mutate(&mut clip);
307            assert_ne!(meta_hash(&clip, &lineage), base);
308        }
309        // Resolved-lineage values that get embedded must also move the hash.
310        for mutate in [
311            |l: &mut LineageContext| l.parent_id = "other-parent".to_owned(),
312            |l: &mut LineageContext| l.root_id = "other-root".to_owned(),
313            |l: &mut LineageContext| l.root_title = "Other Album".to_owned(),
314            |l: &mut LineageContext| l.edge_type = Some(EdgeType::Cover),
315            |l: &mut LineageContext| l.root_date = "2099-01-01T00:00:00Z".to_owned(),
316        ] {
317            let mut lin = sample_lineage();
318            mutate(&mut lin);
319            assert_ne!(meta_hash(&sample(), &lin), base);
320        }
321    }
322
323    #[test]
324    fn art_hash_tracks_the_selected_url_in_preference_order() {
325        let mut clip = sample();
326        let large = art_hash(&clip);
327        clip.image_large_url = String::new();
328        let standard = art_hash(&clip);
329        assert_ne!(large, standard);
330        clip.image_url = String::new();
331        clip.video_cover_url = "https://cdn1.suno.ai/video_cover.jpeg".to_owned();
332        let video = art_hash(&clip);
333        assert_ne!(standard, video);
334    }
335
336    #[test]
337    fn content_hash_is_stable_and_tracks_any_change() {
338        let text = "#EXTM3U\n#PLAYLIST:Mix\n#EXTINF:60,One\nA/One.flac\n";
339        let h = content_hash(text);
340        assert_eq!(h.len(), 16);
341        assert_eq!(h, content_hash(text), "same text hashes the same");
342        // A different name, order, path, title, or duration changes the digest.
343        assert_ne!(
344            h,
345            content_hash("#EXTM3U\n#PLAYLIST:Other\n#EXTINF:60,One\nA/One.flac\n")
346        );
347        assert_ne!(
348            h,
349            content_hash("#EXTM3U\n#PLAYLIST:Mix\n#EXTINF:61,One\nA/One.flac\n")
350        );
351    }
352
353    #[test]
354    fn synced_lrc_source_hash_is_stable_per_clip_and_never_empty() {
355        let a = synced_lrc_source_hash("clip-a");
356        assert_eq!(a.len(), 16);
357        assert_eq!(a, synced_lrc_source_hash("clip-a"), "stable per clip id");
358        // Distinct clips get distinct sentinels; none is the empty ("absent")
359        // value, so a desired synced `.lrc` is never mistaken for "no artifact".
360        assert_ne!(a, synced_lrc_source_hash("clip-b"));
361        assert!(!a.is_empty());
362    }
363}