diff --git a/.gitignore b/.gitignore index 2b40b22..eb4f281 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,7 @@ install_manifest.txt !CMakeLists.txt # CMake scripts that belong to the repo, not to a build directory. !tests/*.cmake +!/cmake/*.cmake # Python __pycache__/ diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 2277c03..f179126 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -240,6 +240,16 @@ These are the touch points the German addition went through, in order: **HTTP server (`src/server/`).** A Rust crate (axum + tokio) that links `libkokoro` through hand-written C API declarations (`ffi.rs`) and serves an OpenAI-compatible API. CMake builds it with cargo (`KOKORO_BUILD_SERVER`) and copies `kokoro-server` next to `libkokoro`; `build.rs` links against the library and sets the rpath. +`cmake/KokoroRustTarget.cmake` maps the CMake target (not the host) to a Rust triple that cargo builds with `--target`, +taking the Linux C library (glibc or musl) from the toolchain's own triple. `-DKOKORO_RUST_TARGET=` overrides +it. Targets with no mapping (Android, iOS, macOS universal) default the server OFF, and a triple whose Rust standard +library is missing fails at configure time; the probe uses the rustc cargo will (`RUSTC`, else `PATH`, else the one +beside cargo). Cross builds link with the configured C compiler, which must already default to the Rust triple: a +compiler that takes its target from `CMAKE_C_COMPILER_TARGET` (clang cross builds) needs `-DKOKORO_RUST_LINKER`. +An existing `CARGO_TARGET__LINKER` in the environment takes precedence over `KOKORO_RUST_LINKER`; unset it +when the wrapper is needed. `KOKORO_RUST_LINKER` only applies to non-MSVC cross builds; MSVC cross builds must set +`CARGO_TARGET__LINKER` directly. aarch64 MinGW maps to `aarch64-pc-windows-gnullvm`; i686 and x86_64 MinGW +map to `*-pc-windows-gnu`. - `Engine` (`engine.rs`) owns the one context; `Audio` frees the samples with `kokoro_audio_free` on drop. - `AppState` (`routes.rs`) keeps the engine behind a `tokio::sync::Mutex`. A request waits for the lock without a thread, then synthesizes in `spawn_blocking`, which also reads the thread-local `kokoro_last_error()`. diff --git a/CMakeLists.txt b/CMakeLists.txt index 14e771c..74f6a53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -188,27 +188,68 @@ if (CMAKE_SOURCE_DIR STREQUAL PROJECT_SOURCE_DIR) else() set(KOKORO_IS_TOP_LEVEL OFF) endif() -# HTTP server: a Rust crate in src/server, built by cargo against libkokoro and copied next to it. -option(KOKORO_BUILD_SERVER "Build kokoro-server (needs a Rust toolchain)" ${KOKORO_IS_TOP_LEVEL}) +# HTTP server: a Rust crate in src/server, built by cargo for the CMake target's Rust triple and copied next to +# libkokoro. +include(cmake/KokoroRustTarget.cmake) +set(KOKORO_RUST_TARGET "" CACHE STRING "Rust target triple for kokoro-server (empty: derived from the CMake target)") +set(KOKORO_RUST_LINKER "" CACHE STRING + "Linker for kokoro-server cross builds (empty: the configured C compiler, for non-MSVC cross toolchains)") +if (KOKORO_RUST_TARGET) + set(KOKORO_RUST_TRIPLE "${KOKORO_RUST_TARGET}") +else() + kokoro_rust_target(KOKORO_RUST_TRIPLE) +endif() +if (KOKORO_IS_TOP_LEVEL AND KOKORO_RUST_TRIPLE) + set(kokoro_server_default ON) +else() + set(kokoro_server_default OFF) +endif() +option(KOKORO_BUILD_SERVER "Build kokoro-server (needs a Rust toolchain)" ${kokoro_server_default}) if (KOKORO_BUILD_SERVER) + if (NOT KOKORO_RUST_TRIPLE) + message(FATAL_ERROR "kokoro-server: no Rust target triple for ${CMAKE_SYSTEM_NAME}/${CMAKE_SYSTEM_PROCESSOR}; " + "set -DKOKORO_RUST_TARGET= or configure with -DKOKORO_BUILD_SERVER=OFF") + endif() find_program(CARGO cargo HINTS "$ENV{CARGO_HOME}/bin" "$ENV{HOME}/.cargo/bin" "$ENV{USERPROFILE}/.cargo/bin") if (NOT CARGO) message(FATAL_ERROR "cargo not found: install Rust (https://rustup.rs) or configure with -DKOKORO_BUILD_SERVER=OFF") endif() + kokoro_rustc(KOKORO_RUSTC_COMPILER "${CARGO}" kokoro_rustc_export) + message(STATUS "kokoro-server Rust target: ${KOKORO_RUST_TRIPLE}") + kokoro_require_rust_std("${KOKORO_RUSTC_COMPILER}" "${KOKORO_RUST_TRIPLE}") set(KOKORO_CARGO_TARGET_DIR "${CMAKE_BINARY_DIR}/cargo") set(KOKORO_CARGO_PROFILE "$,dev,release>") + # cargo --target puts artifacts in //. + set(KOKORO_CARGO_OUT_DIR "${KOKORO_CARGO_TARGET_DIR}/${KOKORO_RUST_TRIPLE}/$,debug,release>") set(KOKORO_CARGO_ENV "CARGO_TARGET_DIR=${KOKORO_CARGO_TARGET_DIR}" "KOKORO_LIB_DIR=$" "KOKORO_INSTALL_LIBDIR=${CMAKE_INSTALL_LIBDIR}") + if (kokoro_rustc_export) + # No rustc on PATH: hand Cargo the one beside it so the probe and the build use the same compiler. + list(APPEND KOKORO_CARGO_ENV "RUSTC=${KOKORO_RUSTC_COMPILER}") + endif() + # Non-MSVC-ABI cross toolchains: link with the CMake C compiler unless the caller already chose a linker. rustc + # passes no --target to a cc driver, so the linker must already default to the Rust triple: pass a prefixed cross + # compiler or a wrapper through KOKORO_RUST_LINKER when the compiler takes its target from CMAKE_C_COMPILER_TARGET. + string(TOUPPER "${KOKORO_RUST_TRIPLE}" kokoro_triple_env) + string(REPLACE "-" "_" kokoro_triple_env "${kokoro_triple_env}") + if (CMAKE_CROSSCOMPILING AND NOT KOKORO_RUST_TRIPLE MATCHES "-msvc$" + AND NOT DEFINED ENV{CARGO_TARGET_${kokoro_triple_env}_LINKER}) + if (KOKORO_RUST_LINKER) + list(APPEND KOKORO_CARGO_ENV "CARGO_TARGET_${kokoro_triple_env}_LINKER=${KOKORO_RUST_LINKER}") + else() + list(APPEND KOKORO_CARGO_ENV "CARGO_TARGET_${kokoro_triple_env}_LINKER=${CMAKE_C_COMPILER}") + endif() + endif() set(KOKORO_SERVER_EXE "kokoro-server${CMAKE_EXECUTABLE_SUFFIX}") add_custom_target(kokoro_server ALL COMMAND ${CMAKE_COMMAND} -E env ${KOKORO_CARGO_ENV} - "${CARGO}" build --locked --profile ${KOKORO_CARGO_PROFILE} + "${CARGO}" build --locked --profile ${KOKORO_CARGO_PROFILE} --target ${KOKORO_RUST_TRIPLE} --manifest-path "${CMAKE_CURRENT_SOURCE_DIR}/src/server/Cargo.toml" COMMAND ${CMAKE_COMMAND} -E copy_if_different - "${KOKORO_CARGO_TARGET_DIR}/$,debug,release>/${KOKORO_SERVER_EXE}" + "${KOKORO_CARGO_OUT_DIR}/${KOKORO_SERVER_EXE}" "$/${KOKORO_SERVER_EXE}" COMMENT "Building kokoro-server with cargo" VERBATIM diff --git a/README.md b/README.md index 08b6a2d..79d454e 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ A high-performance, lightweight C++ inference implementation of the [Kokoro](htt - **CMake** (3.15+) - **Ninja** (recommended; `uv run bootstrap.py build` uses it when it is in `PATH`) - **C++ compiler** (C++17 support required) -- **Rust** (1.80+, via [rustup](https://rustup.rs)): builds `kokoro-server`; configure with `-DKOKORO_BUILD_SERVER=OFF` to skip it +- **Rust** (1.80+, via [rustup](https://rustup.rs)): builds `kokoro-server` for the CMake target (cross builds need `rustup target add `, and a C compiler that already targets that triple, or `-DKOKORO_RUST_LINKER=` for non-MSVC cross builds—MSVC cross builds set `CARGO_TARGET__LINKER` directly); if `CARGO_TARGET__LINKER` is already set in the environment it takes precedence over `KOKORO_RUST_LINKER`—unset it when you need CMake to pass the wrapper; a macOS universal build (`CMAKE_OSX_ARCHITECTURES` set) may detect no single Rust target and default `KOKORO_BUILD_SERVER` OFF—set `-DKOKORO_RUST_TARGET=` and `-DKOKORO_BUILD_SERVER=ON` to enable it (a universal server needs separate architecture builds); configure with `-DKOKORO_BUILD_SERVER=OFF` to skip it - **[uv](https://docs.astral.sh/uv/)**: runs `bootstrap.py` and `voice_tool.py`, and installs their Python dependencies (Python 3.10+, click) into `.venv` on first use ## Setup @@ -270,7 +270,7 @@ MIT - **CMake** (3.15+) - **Ninja**(推荐;`uv run bootstrap.py build` 在 `PATH` 中找到它时使用) - **C++ 编译器** (需要支持 C++17) -- **Rust**(1.80+,通过 [rustup](https://rustup.rs) 安装):用于构建 `kokoro-server`;配置时加 `-DKOKORO_BUILD_SERVER=OFF` 可跳过 +- **Rust**(1.80+,通过 [rustup](https://rustup.rs) 安装):为 CMake 目标平台构建 `kokoro-server`(交叉编译需先运行 `rustup target add `,且 C 编译器需已面向同一目标平台,否则非 MSVC 交叉编译用 `-DKOKORO_RUST_LINKER=`,MSVC 交叉编译直接设置 `CARGO_TARGET__LINKER`);若环境中已设置 `CARGO_TARGET__LINKER`,则优先于 `KOKORO_RUST_LINKER`(需要 CMake 传递包装器时请取消其设置);macOS 通用构建(设置 `CMAKE_OSX_ARCHITECTURES`)可能无法检测到单一 Rust 目标,从而默认关闭 `KOKORO_BUILD_SERVER`(通过 `-DKOKORO_RUST_TARGET=` 和 `-DKOKORO_BUILD_SERVER=ON` 启用;通用服务器需分别为各架构构建);配置时加 `-DKOKORO_BUILD_SERVER=OFF` 可跳过 - **[uv](https://docs.astral.sh/uv/)**:用于运行 `bootstrap.py` 和 `voice_tool.py`,首次运行时会将其 Python 依赖(Python 3.10+、click)安装到 `.venv` ## 准备 @@ -496,7 +496,7 @@ Implementación ligera y de alto rendimiento en C++ de la inferencia del modelo - **CMake** (3.15+) - **Ninja** (recomendado; `uv run bootstrap.py build` lo usa si está en el `PATH`) - **Compilador de C++** (con soporte de C++17) -- **Rust** (1.80+, con [rustup](https://rustup.rs)): compila `kokoro-server`; configura con `-DKOKORO_BUILD_SERVER=OFF` para omitirlo +- **Rust** (1.80+, con [rustup](https://rustup.rs)): compila `kokoro-server` para la plataforma destino de CMake (la compilación cruzada necesita `rustup target add ` y un compilador de C que ya apunte a esa plataforma, o `-DKOKORO_RUST_LINKER=` para compilaciones cruzadas no MSVC—las compilaciones cruzadas MSVC establecen `CARGO_TARGET__LINKER` directamente); si `CARGO_TARGET__LINKER` ya está definido en el entorno, tiene prioridad sobre `KOKORO_RUST_LINKER`—desactívelo si necesita que CMake pase el wrapper; una compilación universal de macOS (`CMAKE_OSX_ARCHITECTURES` definido) puede no detectar un objetivo Rust único y desactivar `KOKORO_BUILD_SERVER` por defecto—use `-DKOKORO_RUST_TARGET=` y `-DKOKORO_BUILD_SERVER=ON` para habilitarlo (un servidor universal requiere compilaciones separadas por arquitectura); configura con `-DKOKORO_BUILD_SERVER=OFF` para omitirlo - **[uv](https://docs.astral.sh/uv/)**: ejecuta `bootstrap.py` y `voice_tool.py`, e instala sus dependencias de Python (Python 3.10+, click) en `.venv` la primera vez ## Preparación @@ -743,7 +743,7 @@ Eine schnelle, schlanke C++-Implementierung der Inferenz des TTS-Modells [Kokoro - **CMake** (3.15+) - **Ninja** (empfohlen; `uv run bootstrap.py build` verwendet es, wenn es im `PATH` liegt) - **C++-Compiler** (mit C++17-Unterstützung) -- **Rust** (1.80+, über [rustup](https://rustup.rs)): baut `kokoro-server`; mit `-DKOKORO_BUILD_SERVER=OFF` konfigurieren, um es auszulassen +- **Rust** (1.80+, über [rustup](https://rustup.rs)): baut `kokoro-server` für die CMake-Zielplattform (Cross-Builds brauchen `rustup target add ` und einen C-Compiler, der bereits auf diese Zielplattform zeigt, oder `-DKOKORO_RUST_LINKER=` für nicht-MSVC-Cross-Builds—MSVC-Cross-Builds setzen `CARGO_TARGET__LINKER` direkt); ist `CARGO_TARGET__LINKER` bereits in der Umgebung gesetzt, hat es Vorrang vor `KOKORO_RUST_LINKER`—deaktivieren Sie es, wenn CMake den Wrapper übergeben soll; ein universeller macOS-Build (`CMAKE_OSX_ARCHITECTURES` gesetzt) kann kein einzelnes Rust-Ziel erkennen und `KOKORO_BUILD_SERVER` standardmäßig deaktivieren—setzen Sie `-DKOKORO_RUST_TARGET=` und `-DKOKORO_BUILD_SERVER=ON`, um es zu aktivieren (ein universeller Server erfordert separate Builds pro Architektur); mit `-DKOKORO_BUILD_SERVER=OFF` konfigurieren, um es auszulassen - **[uv](https://docs.astral.sh/uv/)**: führt `bootstrap.py` und `voice_tool.py` aus und installiert beim ersten Aufruf ihre Python-Abhängigkeiten (Python 3.10+, click) in `.venv` ## Einrichtung diff --git a/cmake/KokoroRustTarget.cmake b/cmake/KokoroRustTarget.cmake new file mode 100644 index 0000000..79719ef --- /dev/null +++ b/cmake/KokoroRustTarget.cmake @@ -0,0 +1,122 @@ +# Maps the CMake target (not the host) to a Rust target triple for kokoro-server. + +# MSVC ABI: cl, clang-cl, and GNU-frontend clang++ targeting *-windows-msvc (where CMake leaves MSVC false). +function(_kokoro_msvc_abi out_var) + if (MSVC OR CMAKE_CXX_SIMULATE_ID STREQUAL "MSVC") + set(${out_var} TRUE PARENT_SCOPE) + else() + set(${out_var} FALSE PARENT_SCOPE) + endif() +endfunction() + +# Rust arch for the target, or "" when unknown or when several macOS architectures are requested. +function(_kokoro_rust_arch out_var) + _kokoro_msvc_abi(msvc_abi) + if (msvc_abi) + set(arch_id "${MSVC_CXX_ARCHITECTURE_ID}") + elseif (APPLE AND CMAKE_OSX_ARCHITECTURES) + set(arch_id "${CMAKE_OSX_ARCHITECTURES}") + else() + set(arch_id "${CMAKE_SYSTEM_PROCESSOR}") + endif() + string(TOLOWER "${arch_id}" arch_id) + if (arch_id MATCHES "^(x64|x86_64|amd64)$") + set(arch x86_64) + elseif (arch_id MATCHES "^(arm64|aarch64)$") + set(arch aarch64) + elseif (arch_id MATCHES "^(x86|i[3-6]86)$") + set(arch i686) + else() + set(arch "") + endif() + set(${out_var} "${arch}" PARENT_SCOPE) +endfunction() + +# C library of the Linux target, from the toolchain's own triple: musl, else gnu. +function(_kokoro_linux_libc out_var) + set(triple "${CMAKE_C_COMPILER_TARGET}") + if (NOT triple AND CMAKE_C_COMPILER AND NOT MSVC) + execute_process(COMMAND "${CMAKE_C_COMPILER}" -dumpmachine + OUTPUT_VARIABLE triple OUTPUT_STRIP_TRAILING_WHITESPACE RESULT_VARIABLE status ERROR_QUIET) + if (NOT status EQUAL 0) + set(triple "") + endif() + endif() + if (triple MATCHES "musl") + set(libc musl) + else() + set(libc gnu) # glibc, or a toolchain triple that does not say + endif() + set(${out_var} "${libc}" PARENT_SCOPE) +endfunction() + +# Rust vendor-os(-env) suffix for the target, or "" when unsupported (Android, iOS, BSDs, ...). +function(_kokoro_rust_os out_var) + _kokoro_msvc_abi(msvc_abi) + _kokoro_rust_arch(arch) + if (WIN32 AND msvc_abi) + set(os pc-windows-msvc) + elseif (WIN32 AND MINGW) + if (arch STREQUAL "aarch64") + set(os pc-windows-gnullvm) + else() + set(os pc-windows-gnu) + endif() + elseif (CMAKE_SYSTEM_NAME STREQUAL "Darwin") + set(os apple-darwin) + elseif (CMAKE_SYSTEM_NAME STREQUAL "Linux") + _kokoro_linux_libc(libc) + set(os "unknown-linux-${libc}") + else() + set(os "") + endif() + set(${out_var} "${os}" PARENT_SCOPE) +endfunction() + +# Sets out_var to the Rust triple for the CMake target, or "" when there is no mapping. +function(kokoro_rust_target out_var) + _kokoro_rust_arch(arch) + _kokoro_rust_os(os) + if (arch AND os) + set(${out_var} "${arch}-${os}" PARENT_SCOPE) + else() + set(${out_var} "" PARENT_SCOPE) + endif() +endfunction() + +# Sets out_var to the rustc Cargo will use: an explicit RUSTC, else the rustc on PATH, else the one beside cargo +# (exported to Cargo through out_export, since Cargo would not find that one). A build.rustc in .cargo/config.toml is +# not visible here, so the probe can only be stricter than the build. +function(kokoro_rustc out_var cargo out_export) + if (DEFINED ENV{RUSTC} AND NOT "$ENV{RUSTC}" STREQUAL "") + set(rustc "$ENV{RUSTC}") + set(export FALSE) + else() + find_program(_kokoro_path_rustc rustc) + if (_kokoro_path_rustc) + set(rustc "${_kokoro_path_rustc}") + set(export FALSE) + else() + get_filename_component(cargo_dir "${cargo}" DIRECTORY) + find_program(_kokoro_beside_rustc rustc HINTS "${cargo_dir}") + if (NOT _kokoro_beside_rustc) + message(FATAL_ERROR "rustc not found: ${cargo} is present but no rustc is on PATH or beside it") + endif() + set(rustc "${_kokoro_beside_rustc}") + set(export TRUE) + endif() + endif() + set(${out_var} "${rustc}" PARENT_SCOPE) + set(${out_export} "${export}" PARENT_SCOPE) +endfunction() + +# Fails configuration unless rustc has the standard library for the triple. +function(kokoro_require_rust_std rustc triple) + execute_process(COMMAND "${rustc}" --print target-libdir --target "${triple}" + OUTPUT_VARIABLE libdir OUTPUT_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE status ERROR_QUIET) + if (NOT status EQUAL 0 OR NOT IS_DIRECTORY "${libdir}") + message(FATAL_ERROR "Rust has no standard library for ${triple}: run `rustup target add ${triple}`, " + "set -DKOKORO_RUST_TARGET=, or configure with -DKOKORO_BUILD_SERVER=OFF") + endif() +endfunction() diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 204caad..2d13ce1 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -43,13 +43,14 @@ if (KOKORO_BUILD_SERVER) "-DCARGO=${CARGO}" "-DMANIFEST=${PROJECT_SOURCE_DIR}/src/server/Cargo.toml" "-DPROFILE=${KOKORO_CARGO_PROFILE}" + "-DTARGET=${KOKORO_RUST_TRIPLE}" "-DDLLS=${server_dlls_arg}" -P "${CMAKE_CURRENT_LIST_DIR}/stage_test_dlls.cmake") set_tests_properties(server_stage_dlls PROPERTIES FIXTURES_SETUP server_dlls) endif() add_test(NAME server COMMAND ${CMAKE_COMMAND} -E env ${server_test_env} - "${CARGO}" test --locked --profile ${KOKORO_CARGO_PROFILE} + "${CARGO}" test --locked --profile ${KOKORO_CARGO_PROFILE} --target ${KOKORO_RUST_TRIPLE} --manifest-path "${PROJECT_SOURCE_DIR}/src/server/Cargo.toml") if (WIN32) set_tests_properties(server PROPERTIES FIXTURES_REQUIRED server_dlls) diff --git a/tests/stage_test_dlls.cmake b/tests/stage_test_dlls.cmake index 590d49e..fe7b993 100644 --- a/tests/stage_test_dlls.cmake +++ b/tests/stage_test_dlls.cmake @@ -5,9 +5,10 @@ # with --message-format=json where they are, then copy the DLLs into the application directory of each one, which the # loader searches before System32. # -# Parameters: CARGO (cargo executable), MANIFEST (Cargo.toml of the crate), PROFILE (cargo profile name), DLLS (the DLLs -# to stage, '|'-separated because a test command line cannot carry a ';' list). The caller provides the build -# environment (CARGO_TARGET_DIR, KOKORO_LIB_DIR, ...). +# Parameters: CARGO (cargo executable), MANIFEST (Cargo.toml of the crate), PROFILE (cargo profile name), TARGET (the +# Rust triple CMake builds for; empty for an explicit host build), DLLS (the DLLs to stage, '|'-separated because a test +# command line cannot carry a ';' list). The caller provides the build environment (CARGO_TARGET_DIR, KOKORO_LIB_DIR, +# ...). cmake_minimum_required(VERSION 3.15) foreach(var CARGO MANIFEST PROFILE DLLS) @@ -16,9 +17,14 @@ foreach(var CARGO MANIFEST PROFILE DLLS) endif() endforeach() string(REPLACE "|" ";" dlls "${DLLS}") +# Stage beside the same triple the `server` test runs, not the host binaries cargo builds without --target. +set(target_args "") +if (DEFINED TARGET AND NOT "${TARGET}" STREQUAL "") + set(target_args --target "${TARGET}") +endif() execute_process( - COMMAND "${CARGO}" test --locked --profile "${PROFILE}" --no-run --message-format=json + COMMAND "${CARGO}" test --locked --profile "${PROFILE}" --no-run --message-format=json ${target_args} --manifest-path "${MANIFEST}" OUTPUT_VARIABLE cargo_json ERROR_VARIABLE cargo_log