media.js
1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* mime 魔数纯函数模块 —— 全仓唯一魔数落点。
*
* 零副作用、零依赖:`base.js` 的 buildMediaParts 一行 import 消费;经 package.json 的 `"./media"`
* 子路径导出,供 `@drama/media-resolver` 复用(魔数表不在两包各写一份)。
*
* 魔数表移植自 game-ui `utils/media-resolver.js` 的 detectMimeFromBuffer。
*/
/**
* 按字节魔数嗅探 mime;命中返回 mime 字符串,未识别返回 null(不兜底 octet-stream)。
* @param {Buffer} buffer
* @returns {string | null}
*/
export function sniffMime(buffer) {
if (buffer.length < 4) return null
const h = buffer
// PNG 89 50 4E 47
if (h[0] === 0x89 && h[1] === 0x50 && h[2] === 0x4e && h[3] === 0x47) return 'image/png'
// JPEG FF D8 FF
if (h[0] === 0xff && h[1] === 0xd8 && h[2] === 0xff) return 'image/jpeg'
// GIF 47 49 46
if (h[0] === 0x47 && h[1] === 0x49 && h[2] === 0x46) return 'image/gif'
// WebP RIFF....WEBP
if (
h[0] === 0x52 && h[1] === 0x49 && h[2] === 0x46 && h[3] === 0x46 &&
h[8] === 0x57 && h[9] === 0x45 && h[10] === 0x42 && h[11] === 0x50
) return 'image/webp'
// BMP 42 4D
if (h[0] === 0x42 && h[1] === 0x4d) return 'image/bmp'
// MP4/MOV: offset4 66 74 79 70 (ftyp)
if (h[4] === 0x66 && h[5] === 0x74 && h[6] === 0x79 && h[7] === 0x70) return 'video/mp4'
return null
}
/** data URL 解析正则:`data:<mime>;base64,<payload>`。 */
const DATA_URL_RE = /^data:([^;,]+);base64,(.*)$/s
/**
* 解析 base64 data URL;合法返回 { mime, data },非法返回 null。
* @param {string} str
* @returns {{ mime:string, data:string } | null}
*/
export function parseDataUrl(str) {
const m = DATA_URL_RE.exec(str)
if (!m) return null
return { mime: m[1], data: m[2] }
}