Pure MoonBit FLAC encoder: turn interleaved PCM into a native .flac stream with fixed and LPC prediction, Rice partitioned residuals and stereo decorrelation.
状态:核心功能可用。STREAMINFO + MD5、定长块帧与 CRC-8/CRC-16、CONSTANT / VERBATIM / FIXED(0–4) / LPC(1–12) 子帧、Rice 分区搜索、立体声去相关、流式/增量编码均已实现;压缩率在 12 组测试信号中 11 组优于或持平 libFLAC 默认设置。具体版本与变更见 CHANGELOG。
moon add Sakuraqwq1/moonflac-encoder| 能力 | 状态 |
|---|---|
| fLaC 标记 + STREAMINFO(含 PCM 的 MD5) | ✅ |
| 定长块帧(默认 4096),可变块长按尾块处理 | ✅ |
| 帧头 CRC-8、帧尾 CRC-16 | ✅ |
| CONSTANT / VERBATIM 子帧 | ✅ |
| FIXED 0–4 阶预测 + Rice 残差(参数搜索) | ✅ |
| 位深 4–32 bit 路径、1–8 声道(8/16/24 经参考解码器验证;32 bit libsndfile 不支持) | ✅ |
| 立体声去相关(left/side、right/side、mid/side,按位代价选优) | ✅ |
| LPC 子帧(Levinson-Durbin + 15-bit 系数量化 + 移位选择) | ✅ |
| Rice 分区搜索(partition order 1–8) | ✅ |
| 流式 / 增量编码(StreamEncoder,STREAMINFO 的总样本数与摘要留空) | ✅ |
// 交织的有符号 PCM,已经缩放到 bits_per_sample 的二进制补码范围
let samples : Array[Int64] = [0L, 100L, 200L, 300L]
let flac : Bytes = @moonflac_encoder.encode(samples, 44100, 1, 16)# 自检:合成 1 秒 440 Hz 正弦,编码后打印 base64
moon run cmd/main -- selftest
# 把 base64 的 WAV 编码成 base64 的 FLAC
moon run cmd/main -- encode "$(base64 -w0 input.wav)"
# 生成测试信号(采样率 声道 位深 帧数 类型)
moon run cmd/main -- gen 44100 2 16 4096 0
# 同时输出源 PCM(base64),用于和任意解码器做逐位比对
moon run cmd/main -- gen 44100 2 16 4096 0 --pcm
# MD5 自检,验证摘要实现
moon run cmd/main -- md5 abclet encoder = @moonflac_encoder.stream_encoder(44100, 2, 16)
let mut out = @moonflac_encoder.stream_header(encoder) // fLaC + STREAMINFO
for chunk in incoming_pcm { // 任意切片大小
out = out + @moonflac_encoder.stream_write(encoder, chunk)
}
out = out + @moonflac_encoder.stream_finish(encoder) // 冲掉最后一个不满的块| 信号(4096 帧,16-bit) | 本编码器 | libFLAC 默认 | 差距 |
|---|---|---|---|
| 单声道正弦 | 1,326 B | 1,285 B | +3.2% |
| 立体声正弦 | 2,549 B | 2,607 B | −2.2% |
| 单声道双音 | 1,634 B | 1,977 B | −17.3% |
| 立体声双音 | 3,124 B | 3,918 B | −20.3% |
| 单声道谐波堆叠 | 1,468 B | 1,723 B | −14.8% |
| 单声道扫频 | 2,583 B | 3,451 B | −25.2% |
| 单声道噪声 | 7,948 B | 7,992 B | −0.6% |
| 单声道音乐型(和弦 + 包络 + 瞬态 + 底噪) | 4,725 B | 4,803 B | −1.6% |
| 立体声音乐型 | 8,767 B | 9,044 B | −3.1% |
python tools/verify.py matrix # 96 例跨解码器矩阵,逐样本比对 STREAMINFO 摘要
python tools/verify.py benchmark # 同一段 PCM 上与 libFLAC 的体积对比moon check --deny-warn
moon test --deny-warn
moon fmt --checkfn encode(samples : Array[Int64], sample_rate : Int, channels : Int, bits_per_sample : Int) -> Bytes raise EncodeErrorfn stream_encoder(sample_rate : Int, channels : Int, bits_per_sample : Int) -> StreamEncoder raise EncodeErrorfn version() -> StringInstall
Download zipPure MoonBit FLAC encoder: turn interleaved PCM into a native .flac stream with fixed and LPC prediction, Rice partitioned residuals and stereo decorrelation.