Files
Thing/src-tauri/src/music/decrypt/qq_footer.rs
T
2026-09-28 00:21:12 +08:00

232 lines
8.0 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! QQ音乐 **musicex** 尾部解析(QQ 客户端 ≥ 19.57 / Windows 22.x)。
//!
//! 新版客户端不再把 ekey 写进文件,只在末尾留 192 字节元数据,ekey 必须联网取。
//! 这个模块只做**纯解析**(无 IO、无网络),因此可以完整单测。
//!
//! ## 尾部布局(对照 `MUSIC_DECRYPT_PLAN.md` §3.2 与 qmc-decoder 的格式文档)
//!
//! ```text
//! +0x00 [4B] song_id uint32 LE
//! +0x04 [4B] quality_type1 uint32 LE
//! +0x08 [4B] quality_type2 uint32 LE
//! +0x0C [60B] media_mid UTF-16LE(可能以 NUL 结尾)
//! +0x48 [68B] filename UTF-16LE(含扩展名,如 O4M0xxxx.mgg)
//! +0x8C [48B] padding
//! +0xC0 [4B] footer_size uint32 LE(= 0xC0 = 192)
//! +0xC4 [4B] version uint32 LE(= 1)
//! +0xC8 [8B] magic "musicex\0"
//! ```
//!
//! 因此**音频段 = 文件大小 − footer_size**,且 footer 一定在文件末尾。
/// musicex 尾部魔术(含结尾 NUL)
pub const MUSICEX_MAGIC: &[u8; 8] = b"musicex\0";
/// 尾部固定长度(也是 footer_size 字段的期望值)
pub const MUSICEX_FOOTER_LEN: usize = 0xC0;
/// 解析出的 musicex 元数据
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MusiCexTail {
pub song_id: u32,
pub quality_type1: u32,
pub quality_type2: u32,
/// 歌曲 mid(取 ekey 需要)
pub media_mid: String,
/// 资源文件名(**必须含扩展名**,否则 API 返回 104005)
pub filename: String,
/// 尾部声明的长度(正常为 192)
pub footer_size: u32,
pub version: u32,
}
impl MusiCexTail {
/// 音频段长度(文件总大小 − 尾部长度)
pub fn audio_len(&self, file_size: u64) -> u64 {
file_size.saturating_sub(self.footer_size as u64)
}
/// 给 UI 的一行说明
pub fn note(&self) -> String {
if self.filename.is_empty() {
format!("musicex(songId={})", self.song_id)
} else {
format!("musicex · {}", self.filename)
}
}
}
/// 判断一段**文件尾部字节**是否是 musicex 尾部。
pub fn is_musicex_tail(buf: &[u8]) -> bool {
buf.len() >= 8 && &buf[buf.len() - 8..] == MUSICEX_MAGIC
}
/// 从文件末尾字节解析 musicex 尾部。
///
/// `buf` 必须至少包含整个尾部([`MUSICEX_FOOTER_LEN`] 字节),否则返回 `None`。
pub fn parse_musicex_tail(buf: &[u8]) -> Option<MusiCexTail> {
if !is_musicex_tail(buf) {
return None;
}
let n = buf.len();
let footer_size = le_u32(buf, n - 16)?;
let version = le_u32(buf, n - 12)?;
// footer_size 是尾部总长;它必须落在缓冲区里才谈得上解析字段
let footer_size_usize = footer_size as usize;
if footer_size_usize < MUSICEX_FOOTER_LEN || footer_size_usize > n {
return None;
}
let start = n - footer_size_usize;
Some(MusiCexTail {
song_id: le_u32(buf, start)?,
quality_type1: le_u32(buf, start + 4)?,
quality_type2: le_u32(buf, start + 8)?,
media_mid: utf16le_at(buf, start + 0x0C, 60)?,
filename: utf16le_at(buf, start + 0x48, 68)?,
footer_size,
version,
})
}
fn le_u32(b: &[u8], at: usize) -> Option<u32> {
let end = at.checked_add(4)?;
let s = b.get(at..end)?;
Some(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
}
/// 读取定长 UTF-16LE 字段并去掉结尾的 NUL。
///
/// 字段是定长补齐的,未用部分为 0;也可能不补 NUL 而恰好占满,故两种都要容忍。
fn utf16le_at(buf: &[u8], at: usize, byte_len: usize) -> Option<String> {
let end = at.checked_add(byte_len)?;
let s = buf.get(at..end)?;
let mut units: Vec<u16> = s
.chunks_exact(2)
.map(|c| u16::from_le_bytes([c[0], c[1]]))
.collect();
while units.last() == Some(&0) {
units.pop();
}
Some(String::from_utf16_lossy(&units))
}
#[cfg(test)]
mod tests {
use super::*;
/// 构造一个合法的 musicex 尾部
fn build_tail(song_id: u32, mid: &str, filename: &str) -> Vec<u8> {
let mut tail = vec![0u8; MUSICEX_FOOTER_LEN];
tail[0..4].copy_from_slice(&song_id.to_le_bytes());
tail[4..8].copy_from_slice(&2u32.to_le_bytes());
tail[8..12].copy_from_slice(&2u32.to_le_bytes());
write_utf16(&mut tail[0x0C..0x0C + 60], mid);
write_utf16(&mut tail[0x48..0x48 + 68], filename);
let n = tail.len();
tail[n - 16..n - 12].copy_from_slice(&(MUSICEX_FOOTER_LEN as u32).to_le_bytes());
tail[n - 12..n - 8].copy_from_slice(&1u32.to_le_bytes());
tail[n - 8..].copy_from_slice(MUSICEX_MAGIC);
tail
}
fn write_utf16(dst: &mut [u8], s: &str) {
for (i, unit) in s.encode_utf16().enumerate() {
let at = i * 2;
if at + 2 > dst.len() {
break;
}
dst[at..at + 2].copy_from_slice(&unit.to_le_bytes());
}
}
#[test]
fn parses_valid_footer() {
let tail = build_tail(0x0C27ABCD, "0012ABCDEF", "O4M00012ABCDEF.mgg");
let parsed = parse_musicex_tail(&tail).expect("应解析成功");
assert_eq!(parsed.song_id, 0x0C27ABCD);
assert_eq!(parsed.quality_type1, 2);
assert_eq!(parsed.quality_type2, 2);
assert_eq!(parsed.media_mid, "0012ABCDEF");
assert_eq!(parsed.filename, "O4M00012ABCDEF.mgg");
assert_eq!(parsed.footer_size, 192);
assert_eq!(parsed.version, 1);
}
/// 尾部前面还有音频数据时,解析结果不受影响(按 footer_size 定位)
#[test]
fn parses_footer_with_audio_prefix() {
let tail = build_tail(7, "mid123", "F00000mid123.mflac");
let mut file = vec![0xAAu8; 5000];
file.extend_from_slice(&tail);
let parsed = parse_musicex_tail(&file).expect("应解析成功");
assert_eq!(parsed.filename, "F00000mid123.mflac");
assert_eq!(parsed.audio_len(file.len() as u64), 5000);
}
/// 字段恰好占满、没有 NUL 终止符时也要能读全
#[test]
fn parses_full_width_field_without_nul() {
let name = "A".repeat(34); // 68 字节 = 34 个 UTF-16 单元,正好占满
let tail = build_tail(1, "M", &name);
let parsed = parse_musicex_tail(&tail).expect("应解析成功");
assert_eq!(parsed.filename, name);
}
/// 中文文件名(UTF-16LE)要能正确还原
#[test]
fn parses_cjk_filename() {
let tail = build_tail(1, "mid", "歌曲 名.mgg");
let parsed = parse_musicex_tail(&tail).unwrap();
assert_eq!(parsed.filename, "歌曲 名.mgg");
}
#[test]
fn rejects_non_musicex() {
assert!(!is_musicex_tail(b"not a magic at all"));
assert!(parse_musicex_tail(&[0u8; 192]).is_none());
// 魔术对但长度不合理
let mut bad = vec![0u8; 192];
let n = bad.len();
bad[n - 8..].copy_from_slice(MUSICEX_MAGIC);
bad[n - 16..n - 12].copy_from_slice(&0xFFFFu32.to_le_bytes());
assert!(parse_musicex_tail(&bad).is_none(), "footer_size 越界应拒绝");
}
#[test]
fn rejects_truncated_buffer() {
// 只有 16 字节,放不下 192 字节的尾部结构
let mut short = vec![0u8; 16];
let n = short.len();
short[n - 8..].copy_from_slice(MUSICEX_MAGIC);
short[n - 16..n - 12].copy_from_slice(&192u32.to_le_bytes());
assert!(parse_musicex_tail(&short).is_none());
}
#[test]
fn audio_len_saturates() {
let t = MusiCexTail {
footer_size: 192,
..Default::default()
};
assert_eq!(t.audio_len(1000), 808);
// 文件比尾部还小:不能下溢
assert_eq!(t.audio_len(10), 0);
}
#[test]
fn note_includes_filename_when_present() {
let t = MusiCexTail {
filename: "a.mgg".into(),
song_id: 5,
..Default::default()
};
assert!(t.note().contains("a.mgg"));
let empty = MusiCexTail {
song_id: 9,
..Default::default()
};
assert!(empty.note().contains("9"));
}
}