Skip to content

Add CXX API for KittenTTS - #2469

Merged
csukuangfj merged 3 commits into
k2-fsa:masterfrom
csukuangfj:cxx-api-kitten
Aug 8, 2025
Merged

csukuangfj merged 3 commits into
k2-fsa:masterfrom
csukuangfj:cxx-api-kitten

Conversation

@csukuangfj

@csukuangfj csukuangfj commented Aug 8, 2025 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features

    • Added a new C++ example demonstrating English text-to-speech synthesis using the Kitten model.
    • Introduced support for Kitten TTS model configuration in the API.
    • Included a progress callback feature during speech synthesis.
    • Updated the build system to support the new example and Kitten TTS model.
  • Documentation

    • Updated speaker ID mappings in code comments for clarity.
  • Chores

    • Enhanced automated testing to compile and verify the new Kitten TTS C++ example, including artifact upload of generated audio.

@coderabbitai

coderabbitai Bot commented Aug 8, 2025 •

Copy link
Copy Markdown
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@csukuangfj
csukuangfj requested a review from Copilot August 8, 2025 07:36

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds CXX API support for KittenTTS to the sherpa-onnx project, enabling C++ developers to use the KittenTTS text-to-speech model through a C++ interface.

Key changes:

  • Defines new C++ configuration structures for KittenTTS model parameters
  • Implements configuration mapping between C++ and C APIs
  • Adds a complete C++ example demonstrating KittenTTS usage

Reviewed Changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
sherpa-onnx/c-api/cxx-api.h Defines OfflineTtsKittenModelConfig struct and integrates it into OfflineTtsModelConfig
sherpa-onnx/c-api/cxx-api.cc Implements configuration mapping from C++ to C API for KittenTTS parameters
cxx-api-examples/kitten-tts-en-cxx-api.cc Complete C++ example demonstrating KittenTTS usage with configuration and audio generation
cxx-api-examples/CMakeLists.txt Adds build target for the new KittenTTS C++ example
c-api-examples/kitten-tts-en-c-api.c Updates voice mapping comments to reflect current KittenTTS voice names
.github/workflows/cxx-api.yaml Adds CI workflow step to test KittenTTS C++ API functionality

@@ -0,0 +1,73 @@
// cxx-api-examples/kitten-tts-en-cxx-api.c

Copilot AI Aug 8, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The file extension in the comment should be '.cc' to match the actual filename, not '.c'.

Suggested change
// cxx-api-examples/kitten-tts-en-cxx-api.c
// cxx-api-examples/kitten-tts-en-cxx-api.cc

Copilot uses AI. Check for mistakes.
WriteWave(filename, {audio.samples, audio.sample_rate});

fprintf(stderr, "Input text is: %s\n", text.c_str());
fprintf(stderr, "Speaker ID is is: %d\n", sid);

Copilot AI Aug 8, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a duplicated word 'is' in the output message. It should be 'Speaker ID is: %d\n'.

Suggested change
fprintf(stderr, "Speaker ID is is: %d\n", sid);
fprintf(stderr, "Speaker ID is: %d\n", sid);

Copilot uses AI. Check for mistakes.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (8)
c-api-examples/kitten-tts-en-c-api.c (1)

58-60: Kitten sid→voice mapping updated — looks good. Minor robustness nit.

The new mapping in comments matches the Kitten voices. Consider guarding against out-of-range sids at runtime to keep the example resilient across model updates.

You could add (outside this block) after creating TTS:

int32_t num_speakers = SherpaOnnxOfflineTtsNumSpeakers(tts);
if (sid < 0 || sid >= num_speakers) sid = 0;
cxx-api-examples/kitten-tts-en-cxx-api.cc (7)

25-31: Silence unused parameters in ProgressCallback

samples, num_samples, and arg are unused and will trigger warnings. Keep the signature but silence cleanly.

 static int32_t ProgressCallback(const float *samples, int32_t num_samples,
                                 float progress, void *arg) {
-  fprintf(stderr, "Progress: %.3f%%\n", progress * 100);
+  (void)samples;
+  (void)num_samples;
+  (void)arg;
+  std::fprintf(stderr, "Progress: %.3f%%\n", progress * 100);
   // return 1 to continue generating
   // return 0 to stop generating
   return 1;
 }

Note: This change assumes is included; otherwise switch to <stdio.h> and keep fprintf unqualified.


68-70: Qualify fprintf and fix a typo

  • Prefer std::fprintf when including .
  • Fix “is is”.
-  fprintf(stderr, "Input text is: %s\n", text.c_str());
-  fprintf(stderr, "Speaker ID is is: %d\n", sid);
-  fprintf(stderr, "Saved to: %s\n", filename.c_str());
+  std::fprintf(stderr, "Input text is: %s\n", text.c_str());
+  std::fprintf(stderr, "Speaker ID is: %d\n", sid);
+  std::fprintf(stderr, "Saved to: %s\n", filename.c_str());

57-58: Use a float literal

Minor: make the literal type match the variable.

-  float speed = 1.0;  // larger -> faster in speech speed
+  float speed = 1.0f;  // larger -> faster in speech speed

37-41: Avoid hardcoding model paths; add basic existence checks or CLI flags

Hardcoded relative paths reduce portability and make CI/local runs brittle if the working directory differs. Consider either:

  • Accepting a --model-dir argument (and compose the file paths), or
  • Reading a KITTTEN_MODEL_DIR environment variable, and
  • Checking that each file exists, failing with a clear message.

Example minimal change (C++17 filesystem):

+#include <filesystem>
+namespace fs = std::filesystem;
 ...
-  config.model.kitten.model = "./kitten-nano-en-v0_1-fp16/model.fp16.onnx";
-  config.model.kitten.voices = "./kitten-nano-en-v0_1-fp16/voices.bin";
-  config.model.kitten.tokens = "./kitten-nano-en-v0_1-fp16/tokens.txt";
-  config.model.kitten.data_dir = "./kitten-nano-en-v0_1-fp16/espeak-ng-data";
+  std::string model_dir = (argc > 1) ? argv[1] : "./kitten-nano-en-v0_1-fp16";
+  config.model.kitten.model = model_dir + "/model.fp16.onnx";
+  config.model.kitten.voices = model_dir + "/voices.bin";
+  config.model.kitten.tokens = model_dir + "/tokens.txt";
+  config.model.kitten.data_dir = model_dir + "/espeak-ng-data";
+
+  for (auto&& p : {config.model.kitten.model,
+                   config.model.kitten.voices,
+                   config.model.kitten.tokens,
+                   config.model.kitten.data_dir}) {
+    if (!fs::exists(p)) {
+      std::fprintf(stderr, "Path does not exist: %s\n", p.c_str());
+      return 1;
+    }
+  }

If you prefer not to add filesystem, at least accept a model_dir CLI arg.


59-64: Prefer runtime flag over compile-time #if to toggle callback

Switching between callback/no-callback via #if 0 requires rebuilding. A simple runtime flag or heuristic is more user-friendly.

-#if 0
-  // If you don't want to use a callback, then please enable this branch
-  GeneratedAudio audio = tts.Generate(text, sid, speed);
-#else
-  GeneratedAudio audio = tts.Generate(text, sid, speed, ProgressCallback);
-#endif
+  const bool use_callback = true;  // or derive from argc/argv
+  GeneratedAudio audio = use_callback
+                             ? tts.Generate(text, sid, speed, ProgressCallback)
+                             : tts.Generate(text, sid, speed);

66-66: Consider basic result validation before writing WAV

If synthesis fails and returns empty audio, WriteWave will still emit a tiny file. A simple guard helps with debugging.

-  WriteWave(filename, {audio.samples, audio.sample_rate});
+  if (audio.samples.empty() || audio.sample_rate <= 0) {
+    std::fprintf(stderr, "No audio generated. Check model paths/config.\n");
+    return 1;
+  }
+  WriteWave(filename, {audio.samples, audio.sample_rate});

If the API guarantees non-empty audio on success, feel free to skip—just verify this assumption against the new Kitten TTS API behavior.


1-1: Fix filename in header comment

Nit: The header says .c, but this file is .cc.

-// cxx-api-examples/kitten-tts-en-cxx-api.c
+// cxx-api-examples/kitten-tts-en-cxx-api.cc
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f0ff58f and f7e1564.

📒 Files selected for processing (6)
  • .github/workflows/cxx-api.yaml (1 hunks)
  • c-api-examples/kitten-tts-en-c-api.c (1 hunks)
  • cxx-api-examples/CMakeLists.txt (1 hunks)
  • cxx-api-examples/kitten-tts-en-cxx-api.cc (1 hunks)
  • sherpa-onnx/c-api/cxx-api.cc (1 hunks)
  • sherpa-onnx/c-api/cxx-api.h (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-06T04:18:47.981Z
Learnt from: litongjava
PR: k2-fsa/sherpa-onnx#2440
File: sherpa-onnx/java-api/src/main/java/com/k2fsa/sherpa/onnx/core/Core.java:4-6
Timestamp: 2025-08-06T04:18:47.981Z
Learning: In sherpa-onnx Java API, the native library names in Core.java (WIN_NATIVE_LIBRARY_NAME = "sherpa-onnx-jni.dll", UNIX_NATIVE_LIBRARY_NAME = "libsherpa-onnx-jni.so", MACOS_NATIVE_LIBRARY_NAME = "libsherpa-onnx-jni.dylib") are copied directly from the compiled binary filenames and should not be changed to match other libraries' naming conventions.

Applied to files:

  • cxx-api-examples/CMakeLists.txt
🔇 Additional comments (6)
cxx-api-examples/CMakeLists.txt (1)

127-129: Add Kitten TTS C++ example target — LGTM.

Target and linkage mirror other TTS examples and are gated behind SHERPA_ONNX_ENABLE_TTS.

sherpa-onnx/c-api/cxx-api.cc (1)

395-400: Initialize Kitten TTS fields in OfflineTts::Create — LGTM.

Field wiring (model/voices/tokens/data_dir/length_scale) is consistent with other TTS configs.

sherpa-onnx/c-api/cxx-api.h (2)

397-405: Introduce OfflineTtsKittenModelConfig — LGTM.

Shape and defaults align with existing TTS configs. No ABI hazards beyond the expected header-only wrapper growth.


410-410: Extend OfflineTtsModelConfig with kitten — LGTM.

Keeps ordering consistent with other TTS models; matches the implementation wiring in cxx-api.cc.

.github/workflows/cxx-api.yaml (2)

90-128: Add Kitten TTS CI step — LGTM.

Build/link flags, model download, env library paths, run, and artifact upload follow existing patterns.


90-128: Artifact filename correctly matches example output

The example C++ code defines the output filename as ./generated-kitten-en-cxx.wav, which exactly matches the path used in the workflow’s upload step. No changes are needed here.

Comment on lines +21 to +24
#include <string>

#include "sherpa-onnx/c-api/cxx-api.h"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add missing headers for types and I/O

This file uses int32_t and fprintf but doesn’t include the corresponding headers. Depending on transitive includes is fragile and can break on some toolchains.

Apply:

 #include <string>
+#include <cstdint>
+#include <cstdio>

 #include "sherpa-onnx/c-api/cxx-api.h"

Also qualify calls to fprintf (see below) or include <stdio.h> instead if you prefer using the global namespace.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
#include <string>
#include "sherpa-onnx/c-api/cxx-api.h"
#include <string>
#include <cstdint>
#include <cstdio>
#include "sherpa-onnx/c-api/cxx-api.h"
🤖 Prompt for AI Agents
In cxx-api-examples/kitten-tts-en-cxx-api.cc around lines 21 to 24, the file
uses int32_t and fprintf without including the necessary headers. Add #include
<cstdint> for int32_t and either #include <cstdio> and qualify fprintf with
std:: or include <stdio.h> to use fprintf in the global namespace. This ensures
the code compiles reliably across different toolchains.

return 1;
}

int32_t main(int32_t argc, char *argv[]) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Use a standard-conforming main signature

C++ requires main to return int (not int32_t). Using int32_t is non-standard and may fail on some platforms.

-int32_t main(int32_t argc, char *argv[]) {
+int main(int argc, char *argv[]) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
int32_t main(int32_t argc, char *argv[]) {
int main(int argc, char *argv[]) {
🤖 Prompt for AI Agents
In cxx-api-examples/kitten-tts-en-cxx-api.cc at line 33, the main function is
declared with a return type of int32_t, which is non-standard in C++. Change the
return type of main from int32_t to int to conform to the C++ standard and
ensure compatibility across platforms.

@csukuangfj
csukuangfj merged commit e6bfab7 into k2-fsa:master Aug 8, 2025
@csukuangfj
csukuangfj deleted the cxx-api-kitten branch August 8, 2025 07:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants