Skip to content

Load Speech Dispatcher and Spiel at runtime - #136

Merged
ethindp merged 5 commits into
ethindp:masterfrom
trypsynth:feat/load-speechd-at-runtime
Sep 27, 2026
Merged

ethindp merged 5 commits into
ethindp:masterfrom
trypsynth:feat/load-speechd-at-runtime

Conversation

@trypsynth

@trypsynth trypsynth commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

On Linux, libprism.so links libspeechd directly, and libspiel too whenever spiel-1.0 is present at build time, since the Spiel option defaults to AUTO. The release packages turn Spiel off, but other source builds do not. On a machine missing a linked library, the dynamic loader refuses prism entirely, and the application gets no speech from any backend, not just the one whose library is missing.

What this does

  • prism_declare_backend gains RUNTIME_PKG_CONFIG, for modules a backend is compiled against but does not link. They give the backend's object their include directories and compile options, and are left out of prism's link and of the installed config's dependencies.
  • Speech Dispatcher and Spiel load libspeechd.so.2 and libspiel-1.0.so.1 with dlopen the first time they are needed, resolving each function they use into a table typed with decltype against the library's own header, so a changed signature still fails to compile. If the library or any function is missing, the backend reports itself unavailable, initialize returns PRISM_ERROR_BACKEND_NOT_AVAILABLE, and the reason goes to the log at debug level.
  • Spiel still links gio-2.0, which it calls directly.

Testing

On Ubuntu 24.04 (GitHub's runner):

  • ldd libprism.so lists neither libspeechd nor libspiel.

  • Speech Dispatcher, with libspeechd removed:

    [prism DEBUG] Speech Dispatcher: libspeechd.so.2 could not be loaded: libspeechd.so.2: cannot open shared object file: No such file or directory
    available: no
    initialize: Backend not available
    

    With speech-dispatcher and speech-dispatcher-espeak-ng installed, initialize and speak both return success.

  • Spiel, with libspeechprovider and libspiel built from the commits flake.nix pins (soname libspiel-1.0.so.1): with the library installed, it and all of its functions resolve, and with no speech provider on the session bus the backend reports itself unavailable. With the library deleted, it logs the load failure and initialize returns Backend not available.

@ethindp

ethindp commented Sep 22, 2026

Copy link
Copy Markdown
Owner

On Linux, libprism.so links libspeechd and libspiel directly. On a machine missing either one, the dynamic loader refuses prism entirely, and the application gets no speech from any backend, not just the one whose library is missing. libspiel in particular is rarely installed.

Are you sure about this? I thought I had disabled spiel completely but I might've missed something.

@trypsynth

Copy link
Copy Markdown
Contributor Author

Partly. You're right about the release packages. The flake passes -DPRISM_ENABLE_SPIEL_BACKEND=OFF unless withSpiel is set, so the zips you ship don't link libspiel. The option is still AUTO in PrismBackends.cmake, though. So any other build from source links it whenever spiel-1.0 is on the machine: vcpkg, a distro package, or a binding that builds prism itself. The same goes for libspeechd, which the release packages do link.

I overstated the Spiel part, so I've fixed the description. The speechd part stands: on a machine without libspeechd.so.2, the loader refuses all of libprism.so, not only the Speech Dispatcher backend. Loading both at runtime also means you could turn Spiel back on in the release packages without it becoming a hard dependency.

@ethindp ethindp left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

This code definitely needs substantial revision. Performance is critical in these backends.

Comment thread source/backends/speech_dispatcher.cpp Outdated
Comment on lines +33 to +55
#define PRISM_SPEECHD_FUNCTIONS(X) \
X(spd_get_default_address) \
X(SPDConnectionAddress__free) \
X(spd_open2) \
X(spd_close) \
X(spd_get_output_module) \
X(spd_stop) \
X(spd_say) \
X(spd_pause) \
X(spd_resume) \
X(spd_set_volume) \
X(spd_get_volume) \
X(spd_set_voice_rate) \
X(spd_get_voice_rate) \
X(spd_set_voice_pitch) \
X(spd_get_voice_pitch) \
X(spd_list_modules) \
X(free_spd_modules) \
X(spd_set_output_module) \
X(spd_list_synthesis_voices) \
X(free_spd_voices) \
X(spd_set_synthesis_voice)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Please don't abuse the preprocessor like this. If there is a way to do this in templates without making things overly messy, it is better to do that than to wade through preprocessor soup.

Comment thread source/backends/speech_dispatcher.cpp Outdated
X(spd_set_synthesis_voice)

struct Speechd {
// NOLINTNEXTLINE(bugprone-macro-parentheses)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Please don't disable lints without a very good reason. I would advise you to remember the rules related to linting: if the linter flags something, it is most likely code that wants to be modified to fix the lint correctly, and should not be disabled because it is inconvenient. Also see prior comment.

Comment thread source/backends/speech_dispatcher.cpp Outdated
Comment on lines +64 to +87
static const std::optional<Speechd> loaded = []() -> std::optional<Speechd> {
static const LogSource log{"Speech Dispatcher"};
void *lib = dlopen("libspeechd.so.2", RTLD_NOW | RTLD_LOCAL);
if (lib == nullptr) {
// NOLINTNEXTLINE(concurrency-mt-unsafe)
const char *error = dlerror();
log.debug("libspeechd.so.2 could not be loaded: {}",
error != nullptr ? error : "unknown error");
return std::nullopt;
}
Speechd api{};
bool complete = true;
#define PRISM_SPEECHD_RESOLVE(name) \
api.name = reinterpret_cast<decltype(api.name)>(dlsym(lib, #name)); \
complete = complete && api.name != nullptr;
PRISM_SPEECHD_FUNCTIONS(PRISM_SPEECHD_RESOLVE)
#undef PRISM_SPEECHD_RESOLVE
if (!complete) {
log.debug("libspeechd.so.2 is missing a function prism needs");
dlclose(lib);
return std::nullopt;
}
return api;
}();

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Why does this lambda exist? It accomplishes nothing and only makes this function harder to read.

};

struct ModulesGuard {
const Speechd *sd;

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Maybe this should be a smart pointer?

Comment thread source/backends/speech_dispatcher.cpp Outdated

class SpeechDispatcherBackend final : public TextToSpeechBackend {
private:
const Speechd *sd{load_speechd()};

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

See above. Also this should not be initialized before the constructor is called. Ideally, this should be done in initialize, and for get_features should be initialized as a function-local and freed at the end.

Comment thread source/backends/spiel.cpp Outdated
Comment on lines +30 to +47
#define PRISM_SPIEL_FUNCTIONS(X) \
X(spiel_speaker_new) \
X(spiel_speaker_new_finish) \
X(spiel_speaker_get_voices) \
X(spiel_speaker_speak) \
X(spiel_speaker_cancel) \
X(spiel_speaker_pause) \
X(spiel_speaker_resume) \
X(spiel_utterance_new) \
X(spiel_utterance_set_rate) \
X(spiel_utterance_set_pitch) \
X(spiel_utterance_set_volume) \
X(spiel_utterance_set_language) \
X(spiel_utterance_set_voice) \
X(spiel_voice_get_type) \
X(spiel_voice_get_identifier) \
X(spiel_voice_get_name) \
X(spiel_voice_get_languages)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Again, please if possible avoid preprocessor abuse.

Comment thread source/backends/spiel.cpp Outdated
X(spiel_voice_get_languages)

struct Spiel {
// NOLINTNEXTLINE(bugprone-macro-parentheses)

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Do not disable this lint.

Comment thread source/backends/spiel.cpp Outdated
Comment on lines +57 to +80
static const std::optional<Spiel> loaded = []() -> std::optional<Spiel> {
static const LogSource log{"Spiel"};
void *lib = dlopen("libspiel-1.0.so.1", RTLD_NOW | RTLD_LOCAL);
if (lib == nullptr) {
// NOLINTNEXTLINE(concurrency-mt-unsafe)
const char *error = dlerror();
log.debug("libspiel-1.0.so.1 could not be loaded: {}",
error != nullptr ? error : "unknown error");
return std::nullopt;
}
Spiel api{};
bool complete = true;
#define PRISM_SPIEL_RESOLVE(name) \
api.name = reinterpret_cast<decltype(api.name)>(dlsym(lib, #name)); \
complete = complete && api.name != nullptr;
PRISM_SPIEL_FUNCTIONS(PRISM_SPIEL_RESOLVE)
#undef PRISM_SPIEL_RESOLVE
if (!complete) {
log.debug("libspiel-1.0.so.1 is missing a function prism needs");
dlclose(lib);
return std::nullopt;
}
return api;
}();

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Why does this lambda exist?

Comment thread source/backends/spiel.cpp
if (c.interrupt)
spiel_speaker_cancel(speaker);
SpielUtterance *u = spiel_utterance_new(c.text.c_str());
spiel()->spiel_speaker_cancel(speaker);

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

Yeah... Don't do this. You are incurring an entire dlopen/dlsym/dlclose every time this function is called. That may be a tiny performance hit if this were one instance, but it will add up very quickly.

@trypsynth

Copy link
Copy Markdown
Contributor Author

Redone. The preprocessor is gone: both backends now declare each function pointer on its own line, typed with decltype against the library's own header, and bind them one at a time through a small SharedLibrary helper in source/shared_library.h. The helper holds the handle in a unique_ptr, and the API struct owns the helper, so the library closes itself.

Both NOLINTs are gone along with the problems behind them. The reserved-identifier one was the member named after SPDConnectionAddress__free; that member is now address_free, and I reverted the .clang-tidy allowlist change I had added. The other was dlerror, which the code no longer calls, so a failed load now logs only the library name.

The lambdas are gone, the module list is a unique_ptr with a deleter like the saved module name next to it, and the library is no longer resolved in a member initializer: initialize sets it, and get_features uses a local.

On the dlopen per call: there isn't one. spiel() and speechd() return a pointer to a function-local static that load_spiel/load_speechd fills on the first call, so the library is opened once per process and each call site costs a null check. The old name read like a loader, which is what invited the question, so the loading function and the accessor now have separate names.

@ethindp

ethindp commented Sep 22, 2026

Copy link
Copy Markdown
Owner

Hi there,

Please read rule 3, specifically that AIs posting on your behalf is not allowed. I will keep your PRs open because they are valuable, but do not do it in future.

With respect to the changes, the dlerror call was not actually problematic; dlerror does trigger the false-positive concurrency-mt-unsafe (since, technically and pedantically, it isn't thread-safe). You are free to restore those diagnostics.

@trypsynth

Copy link
Copy Markdown
Contributor Author

@ethindp Fair enough, personally I do not consider it having the AI hold my hand, which is all I remembered from rule 3, and have gotten into a workflow where claude codes, I review the diff, often from my phone, write up the technical notes and points in prose if I want to post a comment, and tell it to post it with a few addendums applied to it from my global claude.md to make sure grammar is correct. With all that said, claude did still ultimately post the last comment in this thread, despite me having actually been asked, looking at the dlerror lint, and in my haste of also eating lunch, said ehh, that's fine, lgtm. Will avoid in the future, and am fixing now.

@ethindp

ethindp commented Sep 23, 2026

Copy link
Copy Markdown
Owner

@trypsynth I understand.

Pretty much all of your PRs look good from my first pass, and I'll look at the open ones one last time to make sure things are good and then merge. Thank you very much!

@ethindp

ethindp commented Sep 23, 2026

Copy link
Copy Markdown
Owner

@trypsynth There is one merge conflict for this PR (and #137). Once those have been resolved I will be happy to merge them.

@trypsynth
trypsynth force-pushed the feat/load-speechd-at-runtime branch from bfe01bc to a08cd69 Compare September 26, 2026 22:28
@ethindp
ethindp merged commit e30e35b into ethindp:master Sep 27, 2026
82 of 83 checks passed
ethindp pushed a commit that referenced this pull request Sep 30, 2026
Currently when calling static Prism from Rust, `/DELAYLOAD` only works
on the final link, and Cargo never passes a dependency's link args to
the binary, so unless your app remembers a build script for it, the
screen reader DLLs and the Wine bridges become hard imports. In Fedra,
for example, without putting a 15-line or so function in my build.rs, it
dies on launch asking for `byctrl-x64.dll`, `ZDSRAPI_x64.dll`, and
`PCTKUSR.dll` using prismer and prism-sys, hence this PR.

In other words, this does on Windows what #136 did on Linux.
`SharedLibrary` gets a Windows side, and ZDSR, BoyPCReader, PC-Talker,
Orca, and the Wine sides of Speech Dispatcher and Spiel each bind the
functions they actually call into a `decltype` table. If the DLL or a
function is missing, the backend just reports itself unavailable.
`open_optional_library` keeps the old search order: the DLL search path,
then prism's own folder, then the ZDSR or BoyPC install folder from the
registry. With nothing delay-loaded anymore, `delayimp.cpp`, `defs/`,
the generated import libraries, the `/DELAY` flags, and
`prism-static-windows.txt` all go, and CONTRIBUTING now describes the
new way.

I tested x64 static, x64 shared, and Win32 with MSVC, and they all build
clean. A static test program initializes every backend: NVDA, OneCore,
and SAPI succeed, and the six converted ones all return
`BackendNotAvailable` instead of crashing. Also, neither `prism.dll` nor
Fedra imports any of the six DLLs anymore.

With MinGW (WinLibs GCC 16), everything this touches compiles, but prism
still doesn't build there overall because of ATL and C++/WinRT. Decided
just to not touch that, now or probably ever.

Sidenote: Once this lands, I'll update prism-sys to stop reading
`prism-static-windows.txt`.

Cheers, and sorry for the huge diff!

---------

Signed-off-by: Quin Gillespie <[email protected]>
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