-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.zig
More file actions
262 lines (240 loc) · 12.5 KB
/
Copy pathbuild.zig
File metadata and controls
262 lines (240 loc) · 12.5 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
//! This build belongs to your app, written once by `native eject`:
//! the `native` CLI drives this file through `zig build`.
//! `addAppArtifacts` wires the standard app build (executable, run, test,
//! -Dplatform/-Dautomation/-Doptimize flags); we extend it with the
//! Shriflow platform shim (Obj-C), extra macOS frameworks, and — behind
//! `-Dlocal-stt` — the vendored whisper.cpp local engine (wired in P2b).
const std = @import("std");
const native_sdk = @import("native_sdk");
pub fn build(b: *std.Build) void {
const local_stt = b.option(bool, "local-stt", "Compile the whisper.cpp local STT engine") orelse false;
const parakeet_stt = b.option(bool, "parakeet-stt", "Compile the sherpa-onnx Parakeet local STT engine") orelse local_stt;
const artifacts = native_sdk.addAppArtifacts(b, b.dependency("native_sdk", .{}), .{ .name = "shriflow" });
const build_opts = b.addOptions();
build_opts.addOption(bool, "local_stt", local_stt);
build_opts.addOption(bool, "parakeet_stt", parakeet_stt);
const build_opts_mod = build_opts.createModule();
// exe and tests may share one module (same optimize mode) or not; extend
// each distinct module exactly once.
const exe_mod = artifacts.exe.root_module;
const test_mod = artifacts.tests.root_module;
extendModule(b, exe_mod, build_opts_mod, local_stt, parakeet_stt);
if (test_mod != exe_mod) extendModule(b, test_mod, build_opts_mod, local_stt, parakeet_stt);
}
fn extendModule(b: *std.Build, mod: *std.Build.Module, build_opts_mod: *std.Build.Module, local_stt: bool, parakeet_stt: bool) void {
mod.addImport("shriflow_build", build_opts_mod);
const target = mod.resolved_target orelse return;
if (target.result.os.tag != .macos) return;
// Obj-C shim: activation policy, NSPanel host (P1), pasteboard save/restore
// helpers. AppKit/AVFoundation/Accelerate are already linked by the SDK's
// linkPlatform; add what the dictation platform layer needs beyond that.
// Flags mirror the SDK's own appkit_host.m recipe (addAppArtifacts sets
// b.sysroot from xcrun before we run).
const sdk_include = if (b.sysroot) |sysroot| b.fmt("-I{s}/usr/include", .{sysroot}) else "";
const objc_flags: []const []const u8 = if (b.sysroot) |sysroot|
&.{ "-fobjc-arc", "-fno-sanitize=builtin", "-ObjC", "-mmacosx-version-min=11.0", "-isysroot", sysroot, sdk_include }
else
&.{ "-fobjc-arc", "-fno-sanitize=builtin", "-ObjC", "-mmacosx-version-min=11.0" };
mod.addCSourceFile(.{
.file = b.path("src/platform/panel_shim.m"),
.flags = objc_flags,
});
// linkPlatform only adds the framework search path to the exe module;
// the Debug test/model-contract module needs it too (duplicate adds on
// the exe module are harmless).
if (b.sysroot) |sysroot| {
mod.addFrameworkPath(.{ .cwd_relative = b.pathJoin(&.{ sysroot, "System/Library/Frameworks" }) });
}
mod.linkFramework("AppKit", .{}); // shim (NSApp/NSPanel); exe gets it from linkPlatform, tests need it here
mod.linkFramework("ApplicationServices", .{}); // AXUIElement*
mod.linkFramework("CoreGraphics", .{}); // CGEventTap / CGEventPost
mod.linkFramework("AudioToolbox", .{}); // AudioUnit HAL mic capture
mod.linkFramework("IOKit", .{}); // IOHIDCheckAccess (Input Monitoring)
mod.linkFramework("Security", .{}); // SecItem* keychain (API-key store)
mod.linkFramework("QuartzCore", .{}); // CAMediaTimingFunction (HUD fade)
// P2b: vendored whisper.cpp (Metal GPU + Accelerate) — compiled ONLY when
// `-Dlocal-stt=true`, so the default cloud-only build (and P0/other phases)
// never pays the whisper build cost and links without any C++/Metal.
if (local_stt) wireWhisper(b, mod);
if (parakeet_stt) wireSherpaOnnx(b, mod);
}
// sherpa-onnx is a pinned, static arm64 C API bundle fetched by
// scripts/fetch-sherpa-onnx.sh. Keeping it outside the source tree avoids a
// large binary blob in Git while producing a self-contained release binary.
fn wireSherpaOnnx(b: *std.Build, mod: *std.Build.Module) void {
const root = "vendor/sherpa-onnx";
const header = root ++ "/include/sherpa-onnx/c-api/c-api.h";
b.build_root.handle.access(b.graph.io, header, .{}) catch
@panic("Parakeet runtime missing. Run scripts/fetch-sherpa-onnx.sh before building with -Dparakeet-stt=true.");
mod.link_libc = true;
mod.link_libcpp = true;
mod.addIncludePath(b.path(root ++ "/include"));
for ([_][]const u8{
"libsherpa-onnx-c-api.a",
"libsherpa-onnx-core.a",
"libonnxruntime.a",
"libkaldi-native-fbank-core.a",
"libkaldi-decoder-core.a",
"libkissfft-float.a",
"libssentencepiece_core.a",
"libsherpa-onnx-fst.a",
"libsherpa-onnx-fstfar.a",
"libsherpa-onnx-kaldifst-core.a",
}) |name| {
mod.addObjectFile(b.path(b.fmt("{s}/lib/{s}", .{ root, name })));
}
mod.linkFramework("CoreFoundation", .{});
mod.linkFramework("CoreML", .{});
}
// ---------------------------------------------------------------------------
// P2b: whisper.cpp v1.9.1 vendored at vendor/whisper.cpp (committed sources,
// pinned tag v1.9.1 / commit f049fff). Compiled from source with the CPU +
// Metal backends and Accelerate; the Metal shader library is EMBEDDED into the
// binary (GGML_METAL_EMBED_LIBRARY) so the app is self-contained — no external
// .metal/.metallib to ship. Everything below is macOS/arm64 (checked by the
// caller's os.tag guard); CPU features come from the resolved (native) target,
// so no explicit -march is needed on Apple Silicon.
fn wireWhisper(b: *std.Build, mod: *std.Build.Module) void {
const w = "vendor/whisper.cpp";
const root = b.path(w);
// C++ (and libc) are required by ggml/whisper.
mod.link_libc = true;
mod.link_libcpp = true;
// Header search paths (module-global; harmless to the Zig code, needed by
// both the C/C++ TUs and stt_whispercpp.zig's @cImport of whisper.h).
for ([_][]const u8{
w ++ "/include", // whisper.h
w ++ "/ggml/include", // ggml.h, ggml-cpu.h, ...
w ++ "/ggml/src", // ggml-impl.h, ggml-common.h
w ++ "/ggml/src/ggml-cpu", // cpu backend internals
w ++ "/ggml/src/ggml-metal", // metal backend internals
w ++ "/src", // whisper-arch.h
}) |inc| mod.addIncludePath(b.path(inc));
const sysroot = b.sysroot;
// With -isysroot, Zig's clang does NOT auto-add <sysroot>/usr/include, so
// nested system headers like <libDER/DERItem.h> (reached via Foundation →
// Security by the Metal Obj-C TUs) go missing. Add it as -isystem (NOT plain
// -I): system-header semantics keep -Wnullability-completeness suppressed on
// the SDK's own <_stdio.h>, which a user -I would promote to hard errors in
// the ggml C++ TUs.
// `-iframework` (not the linker's `-F`) makes the SDK frameworks SYSTEM
// header dirs — Accelerate's <vDSP.h>/<lapack.h> use enum-forward-decls and
// nullability audits that clang only tolerates in system headers; as user
// headers (plain `-F`) they hard-error in the ggml C/C++ TUs.
const isysroot: []const []const u8 = if (sysroot) |s|
&.{
"-isysroot", s,
"-isystem", b.fmt("{s}/usr/include", .{s}),
"-iframework", b.fmt("{s}/System/Library/Frameworks", .{s}),
}
else
&.{};
// Shared preprocessor defines. GGML_VERSION/GGML_COMMIT are normally set by
// ggml's CMake (ggml.c references them); we pass the pinned values. The
// backend-registration TU keys backend inclusion on GGML_USE_* — statically
// linking CPU + Metal. Accelerate + CPU repack match ggml's macOS defaults.
const defs: []const []const u8 = &.{
"-DGGML_VERSION=\"0.15.1\"",
"-DGGML_COMMIT=\"f049fff\"",
"-DWHISPER_VERSION=\"1.9.1\"", // whisper.cpp references this (its CMake supplies it)
"-DGGML_SCHED_MAX_COPIES=4",
"-DGGML_USE_CPU",
"-DGGML_USE_METAL",
"-DGGML_USE_ACCELERATE",
"-DACCELERATE_NEW_LAPACK",
"-DACCELERATE_LAPACK_ILP64",
"-DGGML_USE_CPU_REPACK",
"-DGGML_METAL_EMBED_LIBRARY",
"-DGGML_METAL_NDEBUG",
"-DNDEBUG",
"-D_DARWIN_C_SOURCE",
"-D_XOPEN_SOURCE=600",
// ggml casts through incompatible pointer types by design; keep UBSan
// from trapping inside inference on a Debug (-Doptimize=Debug) build.
"-fno-sanitize=undefined",
};
const c_flags = concat(b, &.{ &.{"-std=gnu11"}, defs, isysroot });
// Exceptions + RTTI stay ON: gguf.cpp / ggml-backend-reg.cpp use try/throw.
const cpp_flags = concat(b, &.{ &.{"-std=gnu++17"}, defs, isysroot });
// Metal Obj-C TUs are written for manual retain/release (no ARC); do NOT
// pass -fobjc-arc (the SDK's own shim keeps ARC — this is per-file).
const objc_flags = concat(b, &.{ &.{"-std=gnu11"}, defs, isysroot });
// ggml-base + backend registry (C).
mod.addCSourceFiles(.{ .root = root, .flags = c_flags, .files = &.{
"ggml/src/ggml.c",
"ggml/src/ggml-alloc.c",
"ggml/src/ggml-quants.c",
"ggml/src/ggml-cpu/ggml-cpu.c",
"ggml/src/ggml-cpu/quants.c",
"ggml/src/ggml-cpu/arch/arm/quants.c",
} });
// ggml-base + backend registry + CPU backend + whisper (C++).
mod.addCSourceFiles(.{ .root = root, .flags = cpp_flags, .files = &.{
"ggml/src/ggml.cpp",
"ggml/src/ggml-backend.cpp",
"ggml/src/ggml-backend-meta.cpp",
"ggml/src/ggml-opt.cpp",
"ggml/src/ggml-threading.cpp",
"ggml/src/gguf.cpp",
"ggml/src/ggml-backend-reg.cpp",
"ggml/src/ggml-backend-dl.cpp",
"ggml/src/ggml-cpu/ggml-cpu.cpp",
"ggml/src/ggml-cpu/repack.cpp",
"ggml/src/ggml-cpu/hbm.cpp",
"ggml/src/ggml-cpu/traits.cpp",
"ggml/src/ggml-cpu/amx/amx.cpp",
"ggml/src/ggml-cpu/amx/mmq.cpp",
"ggml/src/ggml-cpu/binary-ops.cpp",
"ggml/src/ggml-cpu/unary-ops.cpp",
"ggml/src/ggml-cpu/vec.cpp",
"ggml/src/ggml-cpu/ops.cpp",
"ggml/src/ggml-cpu/arch/arm/repack.cpp",
"ggml/src/ggml-metal/ggml-metal.cpp",
"ggml/src/ggml-metal/ggml-metal-device.cpp",
"ggml/src/ggml-metal/ggml-metal-common.cpp",
"ggml/src/ggml-metal/ggml-metal-ops.cpp",
"src/whisper.cpp",
} });
// Metal backend Obj-C (device + context).
mod.addCSourceFiles(.{ .root = root, .flags = objc_flags, .files = &.{
"ggml/src/ggml-metal/ggml-metal-device.m",
"ggml/src/ggml-metal/ggml-metal-context.m",
} });
// Embed the Metal shader library: inline ggml-common.h and
// ggml-metal-impl.h into ggml-metal.metal (as ggml's CMake does), then wrap
// the merged source in an assembly stub exposing ggml_metallib_start/end
// which ggml-metal-device.m compiles at runtime via newLibraryWithSource.
const embed = b.addSystemCommand(&.{ "/bin/sh", "-c", metal_embed_script });
embed.addArg("shriflow-metal-embed"); // $0
const embed_dir = embed.addOutputDirectoryArg("metal-embed"); // $1 = OUT
embed.addArg(b.pathFromRoot(w ++ "/ggml/src/ggml-metal")); // $2 = MDIR
mod.addAssemblyFile(embed_dir.path(b, "ggml-metal-embed.s"));
// Frameworks the whisper stack needs beyond what the SDK/platform already
// link (AppKit/ApplicationServices/CoreGraphics/AudioToolbox/IOKit).
mod.linkFramework("Foundation", .{});
mod.linkFramework("Metal", .{});
mod.linkFramework("MetalKit", .{});
mod.linkFramework("Accelerate", .{});
}
const metal_embed_script =
\\set -e
\\OUT="$1"; MDIR="$2"
\\COMMON="$MDIR/../ggml-common.h"; IMPL="$MDIR/ggml-metal-impl.h"; SRC="$MDIR/ggml-metal.metal"
\\sed -e '/__embed_ggml-common.h__/r '"$COMMON" -e '/__embed_ggml-common.h__/d' "$SRC" > "$OUT/embed.tmp"
\\sed -e '/#include "ggml-metal-impl.h"/r '"$IMPL" -e '/#include "ggml-metal-impl.h"/d' "$OUT/embed.tmp" > "$OUT/ggml-metal-embed.metal"
\\rm -f "$OUT/embed.tmp"
\\{
\\ printf '.section __DATA,__ggml_metallib\n'
\\ printf '.globl _ggml_metallib_start\n'
\\ printf '_ggml_metallib_start:\n'
\\ printf '.incbin "%s/ggml-metal-embed.metal"\n' "$OUT"
\\ printf '.globl _ggml_metallib_end\n'
\\ printf '_ggml_metallib_end:\n'
\\} > "$OUT/ggml-metal-embed.s"
;
/// Flatten a list of flag slices into one contiguous slice (build-graph-owned).
fn concat(b: *std.Build, parts: []const []const []const u8) []const []const u8 {
var list: std.ArrayList([]const u8) = .empty;
for (parts) |p| list.appendSlice(b.allocator, p) catch @panic("OOM");
return list.toOwnedSlice(b.allocator) catch @panic("OOM");
}