Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,13 @@ if(TRTMC_BUILD_TESTS)
target_compile_options(test_cli PRIVATE -Wall -Wextra -Wpedantic)
add_test(NAME cli COMMAND test_cli)

add_executable(test_audio_codec_cli apps/cli/tests/test_audio_codec_cli.cpp)
target_include_directories(test_audio_codec_cli PRIVATE
${PROJECT_SOURCE_DIR}/core/runtime/include ${PROJECT_SOURCE_DIR}/apps)
target_link_libraries(test_audio_codec_cli PRIVATE trtmc_cli nlohmann_json::nlohmann_json)
target_compile_options(test_audio_codec_cli PRIVATE -Wall -Wextra -Wpedantic)
add_test(NAME audio_codec_cli COMMAND test_audio_codec_cli ${CMAKE_BINARY_DIR}/audio-codec-cli-data)

if(TRTMC_BUILD_SERVER)
add_executable(test_server_worker apps/server/tests/test_native_worker.cpp)
target_include_directories(test_server_worker PRIVATE
Expand Down
73 changes: 73 additions & 0 deletions apps/cli/cli.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,8 @@ const std::unordered_map<std::string, CommandSpec>& command_specs() {
{CommandKind::kSegmentPrompted,
{"--image", "--prompt", "--point-x", "--point-y", "--foreground"}}},
{"video-segment", {CommandKind::kVideoSegment, {"--frame", "--prompt"}}},
{"encode-audio", {CommandKind::kEncodeAudio, {"--input", "--output", "--num-codebooks"}}},
{"decode-audio", {CommandKind::kDecodeAudio, {"--input", "--output"}}},
{"generate-audio",
{CommandKind::kGenerateAudio,
{"--prompt", "--description", "--output", "--max-new-tokens", "--talker-max-new-tokens",
Expand Down Expand Up @@ -1159,6 +1161,73 @@ int dispatch(const Command& command, ITask& task, std::ostream& output) {
write_json(output, {{"frames", std::move(output_frames)}});
return EXIT_SUCCESS;
}
case CommandKind::kEncodeAudio: {
auto& codec = require_interface<IAudioCodec>(task);
const auto audio = io::read_wav_interleaved(require_option(command, "--input"));
const auto tokens = codec.encode({{audio.samples.data(), audio.samples.size()},
audio.sample_rate,
audio.channels,
int_option(command, "--num-codebooks", 0, 0)});
nlohmann::json encoded{{"codes", tokens.codes},
{"codebooks", tokens.codebooks},
{"frames", tokens.frames},
{"audio_frames", tokens.audio_frames},
{"sample_rate", tokens.sample_rate},
{"channels", tokens.channels},
{"codec_id", tokens.codec_id}};
const auto path = require_option(command, "--output");
std::ofstream file(path);
if (!file)
throw std::runtime_error("unable to open codec output: " + path);
file << encoded.dump() << '\n';
file.close();
if (!file)
throw std::runtime_error("unable to write codec output: " + path);
write_json(output,
{{"output", path}, {"codebooks", tokens.codebooks}, {"frames", tokens.frames}});
return EXIT_SUCCESS;
}
case CommandKind::kDecodeAudio: {
auto& codec = require_interface<IAudioCodec>(task);
std::ifstream file(require_option(command, "--input"));
if (!file)
throw std::runtime_error("unable to open codec input");
const auto json = nlohmann::json::parse(file);
auto integer = [](const nlohmann::json& value) -> std::int64_t {
if (!value.is_number_integer() ||
(value.is_number_unsigned() &&
value.get<std::uint64_t>() >
static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max())))
throw std::invalid_argument("codec metadata requires signed-range integers");
return value.get<std::int64_t>();
};
auto integer32 = [&](const nlohmann::json& value) -> std::int32_t {
const auto number = integer(value);
if (number < std::numeric_limits<std::int32_t>::min() ||
number > std::numeric_limits<std::int32_t>::max())
throw std::invalid_argument("codec integer exceeds int32 range");
return static_cast<std::int32_t>(number);
};
AudioCodecTokens tokens;
tokens.codebooks = integer32(json.at("codebooks"));
tokens.frames = integer(json.at("frames"));
tokens.audio_frames = integer(json.at("audio_frames"));
tokens.sample_rate = integer32(json.at("sample_rate"));
tokens.channels = integer32(json.at("channels"));
tokens.codec_id = json.at("codec_id").get<std::string>();
if (!json.at("codes").is_array())
throw std::invalid_argument("codec codes must be an integer array");
for (const auto& code : json.at("codes"))
tokens.codes.push_back(integer32(code));
const auto audio = codec.decode(tokens);
const auto path = require_option(command, "--output");
io::write_wav(audio, path);
write_json(output, {{"output", path},
{"sample_rate", audio.sample_rate},
{"channels", audio.num_channels},
{"num_samples", audio.num_samples}});
return EXIT_SUCCESS;
}
case CommandKind::kGenerateAudio: {
AudioGenerationConfig config;
config.max_new_tokens = int_option(command, "--max-new-tokens", 128, 1);
Expand Down Expand Up @@ -1640,6 +1709,7 @@ void print_usage(std::ostream& output) {
" predict-structure, disparity, depth, geometry,\n"
" segment,\n"
" segment-prompted, video-segment, generate-audio, transcribe,\n"
" encode-audio, decode-audio,\n"
" transcribe-batch, transcribe-streaming, speak, speech-session, generate-image,\n"
" generate-image-batch, generate-video,\n"
" solve, forecast, control, generate-world\n\n"
Expand All @@ -1651,6 +1721,9 @@ void print_usage(std::ostream& output) {
" [--cfg-scale S] [--sde-gamma S]\n\n"
"Text generation options:\n"
" [--source-language-token-id N] [--forced-bos-token-id N]\n\n"
"Audio codec input and output:\n"
" encode-audio --input WAV --output CODES.json [--num-codebooks N]\n"
" decode-audio --input CODES.json --output WAV\n\n"
"Offline transcription options:\n"
" [--beam-size N] [--length-penalty F] [--punctuation true|false]\n"
" [--max-input-seconds F] [--segment-length-seconds F]\n"
Expand Down
2 changes: 2 additions & 0 deletions apps/cli/cli.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ enum class CommandKind {
kSegmentPrompted,
kVideoSegment,
kGenerateAudio,
kEncodeAudio,
kDecodeAudio,
kTranscribe,
kTranscribeBatch,
kTranscribeStreaming,
Expand Down
118 changes: 118 additions & 0 deletions apps/cli/tests/test_audio_codec_cli.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "cli/cli.h"
#include "cli/io.h"
#include "task_runtime.h"

#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <nlohmann/json.hpp>
#include <sstream>
#include <stdexcept>

namespace {
void check(bool condition, const char* message) {
if (!condition)
throw std::runtime_error(message);
}
trtmc::cli::Command parse(std::vector<std::string> args) {
std::vector<char*> argv;
for (auto& arg : args)
argv.push_back(arg.data());
return trtmc::cli::parse_args(static_cast<int>(argv.size()), argv.data());
}
class Codec final : public trtmc::IAudioCodec {
public:
std::vector<float> captured;
trtmc::AudioCodecTokens encoded;
int decodes{0};
trtmc::AudioCodecTokens encode(const trtmc::AudioCodecRequest& request) override {
check(request.sample_rate == 8000 && request.channels == 2 && request.num_codebooks == 2,
"codec input format or codebook selection was changed");
captured.assign(request.samples.begin(), request.samples.end());
encoded = {{3, 7, 11, 13}, 2, 2, 3, 8000, 2, "test-checkpoint/profile"};
return encoded;
}
trtmc::AudioResult decode(const trtmc::AudioCodecTokens& tokens) override {
++decodes;
check(tokens.codes == encoded.codes && tokens.codebooks == 2 && tokens.frames == 2 &&
tokens.audio_frames == 3 && tokens.sample_rate == 8000 && tokens.channels == 2 &&
tokens.codec_id == "test-checkpoint/profile",
"codec metadata or integer tokens were changed");
return {captured, static_cast<std::int32_t>(captured.size()), 8000, 2};
}
};
} // namespace

int main(int argc, char** argv) {
try {
if (argc != 2)
throw std::invalid_argument("usage: test_audio_codec_cli TEMP_DIR");
const std::filesystem::path root(argv[1]);
std::filesystem::create_directories(root);
const auto wav = root / "input.wav", json_path = root / "codes.json",
output = root / "output.wav";
const std::vector<float> samples{0.25F, -0.125F, 0.5F, -0.25F, 0.75F, -0.5F};
trtmc::cli::io::write_wav({samples, 6, 8000, 2}, wav.string());
Codec codec;
check(trtmc::app::uses_existing_task_runtime(codec.task()),
"codec Task is not selected by the native loader");
std::ostringstream stream;
auto encode = parse({"trtmc", "encode-audio", "fixture.bundle", "--input", wav.string(),
"--output", json_path.string(), "--num-codebooks", "2"});
check(encode.kind == trtmc::cli::CommandKind::kEncodeAudio,
"encode command parsed incorrectly");
check(trtmc::cli::dispatch(encode, codec, stream) == 0 && codec.captured == samples,
"encode did not preserve interleaved PCM");
if (std::filesystem::exists("/dev/full")) {
auto full = encode;
full.options.at("--output") = "/dev/full";
std::ostringstream response;
bool write_failed = false;
try {
(void)trtmc::cli::dispatch(full, codec, response);
} catch (const std::runtime_error& error) {
write_failed =
std::string_view(error.what()).find("unable to write codec output:") == 0;
}
check(write_failed && response.str().empty(), "codec accepted a failed buffered write");
}
auto decode = parse({"trtmc", "decode-audio", "fixture.bundle", "--input",
json_path.string(), "--output", output.string()});
check(trtmc::cli::dispatch(decode, codec, stream) == 0, "decode command failed");
const auto audio = trtmc::cli::io::read_wav_interleaved(output.string());
check(audio.samples == samples && audio.sample_rate == 8000 && audio.channels == 2,
"decode did not preserve PCM geometry or values");
std::ifstream file(json_path);
const auto valid = nlohmann::json::parse(file);
for (int mode = 0; mode < 3; ++mode) {
auto invalid = valid;
if (mode == 0)
invalid["codes"][0] = std::uint64_t{4294967299ULL};
if (mode == 1)
invalid["frames"] = std::numeric_limits<std::uint64_t>::max();
if (mode == 2)
invalid["channels"] = 1.5;
{
std::ofstream bad(json_path);
bad << invalid.dump();
}
bool rejected = false;
try {
(void)trtmc::cli::dispatch(decode, codec, stream);
} catch (const std::invalid_argument&) {
rejected = true;
}
check(rejected && codec.decodes == 1, "invalid codec integers reached the family");
}
std::cout << "Audio codec PCM, integer payload, identity and metadata round trips passed\n";
return 0;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}
}
1 change: 1 addition & 0 deletions apps/task_runtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ inline bool uses_existing_task_runtime(std::string_view primary_task) noexcept {
IImageBatchGeneration::kTask,
IWorldModelGeneration::kTask,
IAudioGeneration::kTask,
IAudioCodec::kTask,
ITranscription::kTask,
IBatchTranscription::kTask,
IStreamingTranscription::kTask,
Expand Down
31 changes: 31 additions & 0 deletions core/runtime/include/trtmc/task.h
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,37 @@ struct AudioResult {
std::int32_t num_channels{1};
};

// Borrowed interleaved PCM; samples counts scalar values. A codec owns its
// supported rates, channels, codebook counts, padding and numerical policy.
struct AudioCodecRequest {
Span<const float> samples;
std::int32_t sample_rate{0};
std::int32_t channels{1};
// Zero selects the codec's declared default.
std::int32_t num_codebooks{0};
};

struct AudioCodecTokens {
// Contiguous codebook-major integer indices, codebooks x frames.
std::vector<std::int32_t> codes;
std::int32_t codebooks{0};
std::int64_t frames{0};
// Original PCM frames per channel, before codec padding.
std::int64_t audio_frames{0};
std::int32_t sample_rate{0};
std::int32_t channels{1};
// Opaque owner-defined codebook/profile identity, checked by the decoder.
std::string codec_id;
};

class IAudioCodec : public virtual ITask {
public:
static constexpr const char* kTask = "audio_codec";
const char* task() const noexcept override { return kTask; }
virtual AudioCodecTokens encode(const AudioCodecRequest& request) = 0;
virtual AudioResult decode(const AudioCodecTokens& tokens) = 0;
};

struct TranscriptionStreamConfig {
std::int32_t input_sample_rate{16000};
std::int32_t max_new_tokens{224};
Expand Down
35 changes: 35 additions & 0 deletions families/encodec/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# EnCodec 24 kHz

The FP32 profile targets `facebook/encodec_24khz` at revision
`c1dbe2ae3f1de713481a3b3e7c47f357092ee040`, using Transformers 5.3.0 as the
unmodified reference. It encodes one mono 6400-sample waveform at 24000 Hz into
two 1024-entry codebooks with 20 frames. This is the checkpoint's default
1.5 kbps setting. The first profile has a fixed input duration and rejects
other sample counts, formats, and codebook selections.

The family owns causal reflection padding, weight-normalized SEANet convolutions,
residual blocks, both two-layer LSTMs, Euclidean residual quantization, and the
waveform decoder. TensorRT loops express recurrent state updates and reset
their initial states on each request. All neural math executes in TensorRT;
the native runtime requires no Python, Torch or custom GPU kernels.

Native `IAudioCodec` requests and codebook payloads preserve integer indices,
PCM format, original audio length, and codec/profile identity. Decoding checks
all metadata and index bounds before execution. Returned vectors own storage.

```
trtmc encode-audio encodec.bundle --input input.wav --output codes.json
trtmc decode-audio encodec.bundle --input codes.json --output decoded.wav
```

Small model tests compare every encoder, recurrent and decoder stage at `5e-5`
absolute and relative tolerance. Real checkpoint tests require exact codebooks
and full PCM agreement at `5e-4` absolute / `1e-4` relative tolerance for speech,
tones, chirp, silence and repetition, plus recovery after invalid requests and
WAV/JSON CLI round trips.

Build `trtmc`, `trtmc_backend_trt`, `trtmc_model_encodec` and `encodec_e2e`, then
run `pytest families/encodec/tests --e2e-model encodec -q` with
`TRTMC_ENCODEC_MODEL_DIR`, `TRTMC_RUNTIME_ROOT` and `TRTMC_BINARY` set.
Quantization, mixed precision, sharding, dynamic KV caching, text, image, video,
stereo, chunk overlap, and amplitude normalization are outside this profile.
3 changes: 3 additions & 0 deletions families/encodec/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
"""EnCodec neural audio codec ownership."""
Loading
Loading