From 953391c171048c9fa2714e093fcb187bcb9743a9 Mon Sep 17 00:00:00 2001 From: Robin Getz Date: Sat, 26 Sep 2026 20:26:27 -0400 Subject: [PATCH 01/11] repo wide : Name SDRangel-owned threads for debugging Assign descriptive names to SDRangel threads so thread activity can be identified when investigating multi-threaded behavior, including crashes, leaks, and synchronization issues in debuggers and others tools. Use compact names to fit platform thread-name limits (14 chars) while retaining the component and thread role where possible. Signed-off-by: Robin Getz --- httpserver/httpconnectionhandler.cpp | 1 + plugins/channelmimo/beamsteeringcwmod/beamsteeringcwmod.cpp | 1 + plugins/channelmimo/doa2/doa2.cpp | 1 + plugins/channelmimo/interferometer/interferometer.cpp | 1 + plugins/channelrx/chanalyzer/chanalyzer.cpp | 2 ++ plugins/channelrx/channelpower/channelpower.cpp | 1 + plugins/channelrx/demodadsb/adsbdemod.cpp | 1 + plugins/channelrx/demodadsb/adsbdemodsinkworker.h | 1 + plugins/channelrx/demodais/aisdemod.cpp | 1 + plugins/channelrx/demodam/amdemod.cpp | 1 + plugins/channelrx/demodapt/aptdemod.cpp | 2 ++ plugins/channelrx/demodatv/atvdemod.cpp | 1 + plugins/channelrx/demodbfm/bfmdemod.cpp | 1 + plugins/channelrx/demodchirpchat/chirpchatdemod.cpp | 2 ++ plugins/channelrx/demoddab/dabdemod.cpp | 1 + plugins/channelrx/demoddatv/datvideorender.h | 2 ++ plugins/channelrx/demoddsc/dscdemod.cpp | 1 + plugins/channelrx/demoddsd/dsddemod.cpp | 1 + plugins/channelrx/demodendoftrain/endoftraindemod.cpp | 1 + plugins/channelrx/demodfreedv/freedvdemod.cpp | 1 + plugins/channelrx/demodft8/ft8demod.cpp | 1 + plugins/channelrx/demodft8/ft8demodbaseband.cpp | 2 ++ plugins/channelrx/demodils/ilsdemod.cpp | 1 + plugins/channelrx/demodinmarsat/inmarsatdemod.cpp | 1 + plugins/channelrx/demodm17/m17demod.cpp | 1 + plugins/channelrx/demodmeshcore/meshcoredemod.cpp | 4 ++++ plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp | 4 ++++ plugins/channelrx/demodnavtex/navtexdemod.cpp | 1 + plugins/channelrx/demodnfm/nfmdemod.cpp | 1 + plugins/channelrx/demodpacket/packetdemod.cpp | 1 + plugins/channelrx/demodpager/pagerdemod.cpp | 1 + plugins/channelrx/demodradiosonde/radiosondedemod.cpp | 1 + plugins/channelrx/demodrtty/rttydemod.cpp | 1 + plugins/channelrx/demodssb/ssbdemod.cpp | 1 + plugins/channelrx/demodvor/vordemod.cpp | 1 + plugins/channelrx/demodvormc/vordemodmc.cpp | 1 + plugins/channelrx/demodwfm/wfmdemod.cpp | 1 + plugins/channelrx/filesink/filesink.cpp | 1 + plugins/channelrx/freqscanner/freqscanner.cpp | 1 + plugins/channelrx/freqtracker/freqtracker.cpp | 1 + plugins/channelrx/heatmap/heatmap.cpp | 1 + plugins/channelrx/localsink/localsink.cpp | 1 + plugins/channelrx/localsink/localsinksink.cpp | 1 + plugins/channelrx/noisefigure/noisefigure.cpp | 1 + plugins/channelrx/radioastronomy/radioastronomy.cpp | 2 ++ plugins/channelrx/radioclock/radioclock.cpp | 1 + plugins/channelrx/remotesink/remotesink.cpp | 1 + plugins/channelrx/remotesink/remotesinksink.cpp | 1 + plugins/channelrx/remotetcpsink/remotetcpsink.cpp | 1 + plugins/channelrx/sigmffilesink/sigmffilesink.cpp | 1 + plugins/channelrx/udpsink/udpsink.cpp | 1 + plugins/channelrx/wdsprx/wdsprx.cpp | 1 + plugins/channeltx/filesource/filesource.cpp | 1 + plugins/channeltx/localsource/localsource.cpp | 1 + plugins/channeltx/localsource/localsourcesource.cpp | 4 +++- plugins/channeltx/mod802.15.4/ieee_802_15_4_mod.cpp | 1 + plugins/channeltx/modais/aismod.cpp | 1 + plugins/channeltx/modam/ammod.cpp | 1 + plugins/channeltx/modatv/atvmod.cpp | 1 + plugins/channeltx/modchirpchat/chirpchatmod.cpp | 1 + plugins/channeltx/moddatv/datvmod.cpp | 1 + plugins/channeltx/modfreedv/freedvmod.cpp | 1 + plugins/channeltx/modm17/m17mod.cpp | 1 + plugins/channeltx/modm17/m17modsource.cpp | 1 + plugins/channeltx/modmeshcore/meshcoremod.cpp | 1 + plugins/channeltx/modmeshtastic/meshtasticmod.cpp | 1 + plugins/channeltx/modnfm/nfmmod.cpp | 1 + plugins/channeltx/modpacket/packetmod.cpp | 1 + plugins/channeltx/modpsk31/psk31mod.cpp | 1 + plugins/channeltx/modrtty/rttymod.cpp | 1 + plugins/channeltx/modssb/ssbmod.cpp | 1 + plugins/channeltx/modwfm/wfmmod.cpp | 1 + plugins/channeltx/remotesource/remotesource.cpp | 1 + plugins/channeltx/remotesource/remotesourcesource.cpp | 1 + plugins/channeltx/udpsource/udpsource.cpp | 1 + plugins/feature/afc/afc.cpp | 1 + plugins/feature/ambe/ambeengine.cpp | 1 + plugins/feature/aprs/aprs.cpp | 1 + plugins/feature/demodanalyzer/demodanalyzer.cpp | 1 + plugins/feature/denoiser/denoiser.cpp | 1 + plugins/feature/gs232controller/gs232controller.cpp | 1 + plugins/feature/morsedecoder/morsedecoder.cpp | 1 + plugins/feature/pertester/pertester.cpp | 1 + plugins/feature/remotecontrol/remotecontrol.cpp | 1 + plugins/feature/rigctlserver/rigctlserver.cpp | 1 + plugins/feature/satellitetracker/satellitetracker.cpp | 1 + plugins/feature/sid/sid.cpp | 1 + plugins/feature/simpleptt/simpleptt.cpp | 1 + plugins/feature/startracker/startracker.cpp | 1 + plugins/feature/vorlocalizer/vorlocalizer.cpp | 1 + plugins/samplemimo/audiocatsiso/audiocatsiso.cpp | 3 +++ plugins/samplemimo/bladerf2mimo/bladerf2mithread.cpp | 1 + plugins/samplemimo/bladerf2mimo/bladerf2mothread.cpp | 1 + plugins/samplemimo/limesdrmimo/limesdrmithread.cpp | 1 + plugins/samplemimo/plutosdrmimo/plutosdrmithread.cpp | 1 + plugins/samplemimo/plutosdrmimo/plutosdrmothread.cpp | 1 + plugins/samplemimo/testmi/testmi.cpp | 2 ++ plugins/samplemimo/testmosync/testmosync.cpp | 1 + plugins/samplemimo/xtrxmimo/xtrxmithread.cpp | 1 + plugins/samplemimo/xtrxmimo/xtrxmothread.cpp | 1 + plugins/samplesink/aaroniartsaoutput/aaroniartsaoutput.cpp | 1 + plugins/samplesink/audiooutput/audiooutput.cpp | 1 + plugins/samplesink/bladerf1output/bladerf1outputthread.cpp | 1 + plugins/samplesink/bladerf2output/bladerf2outputthread.cpp | 1 + plugins/samplesink/fileoutput/fileoutput.cpp | 1 + plugins/samplesink/hackrfoutput/hackrfoutputthread.cpp | 1 + plugins/samplesink/limesdroutput/limesdroutputthread.cpp | 1 + plugins/samplesink/plutosdroutput/plutosdroutputthread.cpp | 1 + plugins/samplesink/remoteoutput/remoteoutput.cpp | 1 + plugins/samplesink/remoteoutput/udpsinkfec.cpp | 1 + plugins/samplesink/soapysdroutput/soapysdroutputthread.cpp | 1 + plugins/samplesink/testsink/testsinkoutput.cpp | 1 + plugins/samplesink/usrpoutput/usrpoutputthread.cpp | 1 + plugins/samplesink/xtrxoutput/xtrxoutputthread.cpp | 1 + plugins/samplesource/aaroniartsainput/aaroniartsainput.cpp | 1 + plugins/samplesource/airspy/airspyinput.cpp | 1 + plugins/samplesource/airspyhf/airspyhfinput.cpp | 1 + .../androidsdrdriverinput/androidsdrdriverinput.cpp | 1 + plugins/samplesource/audioinput/audioinput.cpp | 1 + plugins/samplesource/bladerf1input/bladerf1inputthread.cpp | 1 + plugins/samplesource/bladerf2input/bladerf2inputthread.cpp | 1 + plugins/samplesource/fcdpro/fcdprothread.cpp | 1 + plugins/samplesource/fcdproplus/fcdproplusthread.cpp | 1 + plugins/samplesource/fileinput/fileinput.cpp | 1 + plugins/samplesource/fobos/fobosinput.cpp | 1 + plugins/samplesource/hackrfinput/hackrfinputthread.cpp | 1 + plugins/samplesource/kiwisdr/kiwisdrinput.cpp | 1 + plugins/samplesource/perseus/perseusinput.cpp | 1 + plugins/samplesource/plutosdrinput/plutosdrinputthread.cpp | 1 + plugins/samplesource/remotetcpinput/remotetcpinput.cpp | 1 + plugins/samplesource/rtlsdr/rtlsdrthread.cpp | 1 + plugins/samplesource/sdrplay/sdrplaythread.cpp | 1 + plugins/samplesource/sigmffileinput/sigmffileinput.cpp | 1 + plugins/samplesource/soapysdrinput/soapysdrinputthread.cpp | 1 + plugins/samplesource/testsource/testsourceinput.cpp | 1 + plugins/samplesource/usrpinput/usrpinputthread.cpp | 1 + plugins/samplesource/xtrxinput/xtrxinputthread.cpp | 1 + sdrbase/audio/audiodevicemanager.cpp | 2 ++ sdrbase/pipes/datapipes.cpp | 1 + sdrbase/pipes/messagepipes.cpp | 1 + sdrbase/pipes/messagepipeslegacy.cpp | 1 + sdrgui/gui/samplingdevicedialog.cpp | 1 + 142 files changed, 160 insertions(+), 1 deletion(-) diff --git a/httpserver/httpconnectionhandler.cpp b/httpserver/httpconnectionhandler.cpp index 272458010..376fc74f2 100644 --- a/httpserver/httpconnectionhandler.cpp +++ b/httpserver/httpconnectionhandler.cpp @@ -13,6 +13,7 @@ HttpConnectionHandler::HttpConnectionHandler(QSettings* settings, HttpRequestHan { Q_ASSERT(settings != 0); Q_ASSERT(requestHandler != 0); + setObjectName("httpCnnctnHndlr"); this->settings = settings; this->listenerSettings = 0; this->requestHandler = requestHandler; diff --git a/plugins/channelmimo/beamsteeringcwmod/beamsteeringcwmod.cpp b/plugins/channelmimo/beamsteeringcwmod/beamsteeringcwmod.cpp index 8f303b1e3..4f52f4540 100644 --- a/plugins/channelmimo/beamsteeringcwmod/beamsteeringcwmod.cpp +++ b/plugins/channelmimo/beamsteeringcwmod/beamsteeringcwmod.cpp @@ -102,6 +102,7 @@ void BeamSteeringCWMod::startSources() qDebug("BeamSteeringCWMod::startSources"); m_thread = new QThread(this); + m_thread->setObjectName("BeamSteerCWMod"); m_basebandSource = new BeamSteeringCWModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channelmimo/doa2/doa2.cpp b/plugins/channelmimo/doa2/doa2.cpp index 87e9e9bdc..555823380 100644 --- a/plugins/channelmimo/doa2/doa2.cpp +++ b/plugins/channelmimo/doa2/doa2.cpp @@ -105,6 +105,7 @@ void DOA2::startSinks() qDebug("DOA2::startSinks"); m_thread = new QThread(this); + m_thread->setObjectName("DOA2"); m_basebandSink = new DOA2Baseband(m_fftSize); m_basebandSink->setScopeSink(&m_scopeSink); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelmimo/interferometer/interferometer.cpp b/plugins/channelmimo/interferometer/interferometer.cpp index 6db7cd563..f92f0d30a 100644 --- a/plugins/channelmimo/interferometer/interferometer.cpp +++ b/plugins/channelmimo/interferometer/interferometer.cpp @@ -124,6 +124,7 @@ void Interferometer::startSinks() qDebug("Interferometer::startSinks"); m_thread = new QThread(this); + m_thread->setObjectName("Interferometer"); m_basebandSink = new InterferometerBaseband(m_fftSize); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->setScopeSink(&m_scopeSink); diff --git a/plugins/channelrx/chanalyzer/chanalyzer.cpp b/plugins/channelrx/chanalyzer/chanalyzer.cpp index ba4d7da43..f49e656ac 100644 --- a/plugins/channelrx/chanalyzer/chanalyzer.cpp +++ b/plugins/channelrx/chanalyzer/chanalyzer.cpp @@ -53,6 +53,8 @@ ChannelAnalyzer::ChannelAnalyzer(DeviceAPI *deviceAPI) : { qDebug("ChannelAnalyzer::ChannelAnalyzer"); setObjectName(m_channelId); + m_thread.setObjectName("Channelyzer"); + getChannelSampleRate(); m_basebandSink = new ChannelAnalyzerBaseband(); m_basebandSink->moveToThread(&m_thread); diff --git a/plugins/channelrx/channelpower/channelpower.cpp b/plugins/channelrx/channelpower/channelpower.cpp index 5d4f724d8..32e0579a4 100644 --- a/plugins/channelrx/channelpower/channelpower.cpp +++ b/plugins/channelrx/channelpower/channelpower.cpp @@ -49,6 +49,7 @@ ChannelPower::ChannelPower(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("ChannelPower"); m_basebandSink = new ChannelPowerBaseband(); m_basebandSink->setChannel(this); diff --git a/plugins/channelrx/demodadsb/adsbdemod.cpp b/plugins/channelrx/demodadsb/adsbdemod.cpp index d03bfcd0c..78085f698 100644 --- a/plugins/channelrx/demodadsb/adsbdemod.cpp +++ b/plugins/channelrx/demodadsb/adsbdemod.cpp @@ -64,6 +64,7 @@ ADSBDemod::ADSBDemod(DeviceAPI *devieAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("ADSBDemodBB"); m_basebandSink = new ADSBDemodBaseband(); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/demodadsb/adsbdemodsinkworker.h b/plugins/channelrx/demodadsb/adsbdemodsinkworker.h index 38a8c45d4..ab8e2c3aa 100644 --- a/plugins/channelrx/demodadsb/adsbdemodsinkworker.h +++ b/plugins/channelrx/demodadsb/adsbdemodsinkworker.h @@ -66,6 +66,7 @@ public: m_correlationThresholdLinear(0.02f), m_crc() { + setObjectName("ADSBDemodWork"); } void run() override; MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } diff --git a/plugins/channelrx/demodais/aisdemod.cpp b/plugins/channelrx/demodais/aisdemod.cpp index 3c745e8e1..156fa8d97 100644 --- a/plugins/channelrx/demodais/aisdemod.cpp +++ b/plugins/channelrx/demodais/aisdemod.cpp @@ -51,6 +51,7 @@ AISDemod::AISDemod(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("AISDemod"); m_basebandSink = new AISDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodam/amdemod.cpp b/plugins/channelrx/demodam/amdemod.cpp index f66b6a004..feaf22aea 100644 --- a/plugins/channelrx/demodam/amdemod.cpp +++ b/plugins/channelrx/demodam/amdemod.cpp @@ -127,6 +127,7 @@ void AMDemod::start() qDebug("AMDemod::start"); m_thread = new QThread(); + m_thread->setObjectName("AMDemod"); m_basebandSink = new AMDemodBaseband(); m_basebandSink->setChannel(this); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/demodapt/aptdemod.cpp b/plugins/channelrx/demodapt/aptdemod.cpp index 4628bb56e..be6ace9ae 100644 --- a/plugins/channelrx/demodapt/aptdemod.cpp +++ b/plugins/channelrx/demodapt/aptdemod.cpp @@ -54,6 +54,8 @@ APTDemod::APTDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_imageThread.setObjectName("APTDemodImage"); + m_thread.setObjectName("APTDemodBB"); m_basebandSink = new APTDemodBaseband(); m_basebandSink->moveToThread(&m_thread); diff --git a/plugins/channelrx/demodatv/atvdemod.cpp b/plugins/channelrx/demodatv/atvdemod.cpp index 27d20ce5a..6f7410631 100644 --- a/plugins/channelrx/demodatv/atvdemod.cpp +++ b/plugins/channelrx/demodatv/atvdemod.cpp @@ -41,6 +41,7 @@ ATVDemod::ATVDemod(DeviceAPI *deviceAPI) : { qDebug("ATVDemod::ATVDemod"); setObjectName(m_channelId); + m_thread.setObjectName("ATVDemodBB"); m_basebandSink = new ATVDemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") diff --git a/plugins/channelrx/demodbfm/bfmdemod.cpp b/plugins/channelrx/demodbfm/bfmdemod.cpp index 47f42ed63..f50006ae6 100644 --- a/plugins/channelrx/demodbfm/bfmdemod.cpp +++ b/plugins/channelrx/demodbfm/bfmdemod.cpp @@ -126,6 +126,7 @@ void BFMDemod::start() qDebug() << "BFMDemod::start"; m_thread = new QThread(); + m_thread->setObjectName("BFMDemod"); m_basebandSink = new BFMDemodBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->setChannel(this); diff --git a/plugins/channelrx/demodchirpchat/chirpchatdemod.cpp b/plugins/channelrx/demodchirpchat/chirpchatdemod.cpp index bddc7f512..d8dbf8e12 100644 --- a/plugins/channelrx/demodchirpchat/chirpchatdemod.cpp +++ b/plugins/channelrx/demodchirpchat/chirpchatdemod.cpp @@ -136,6 +136,7 @@ void ChirpChatDemod::start() qDebug() << "ChirpChatDemod::start"; m_decoderThread = new QThread(this); + m_decoderThread->setObjectName("CCDemod:decode"); m_decoder = new ChirpChatDemodDecoder(); m_decoder->setOutputMessageQueue(getInputMessageQueue()); m_decoder->setNbSymbolBits(m_settings.m_spreadFactor, m_settings.m_deBits); @@ -151,6 +152,7 @@ void ChirpChatDemod::start() m_decoderThread->start(); m_thread = new QThread(this); + m_thread->setObjectName("CCDemod:bb"); m_basebandSink = new ChirpChatDemodBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->setDecoderMessageQueue(m_decoder->getInputMessageQueue()); diff --git a/plugins/channelrx/demoddab/dabdemod.cpp b/plugins/channelrx/demoddab/dabdemod.cpp index b0daca5d6..da489a8d8 100644 --- a/plugins/channelrx/demoddab/dabdemod.cpp +++ b/plugins/channelrx/demoddab/dabdemod.cpp @@ -79,6 +79,7 @@ DABDemod::DABDemod(DeviceAPI *deviceAPI) : m_reportTII(0) { setObjectName(m_channelId); + m_thread.setObjectName("DABDemodBB"); m_basebandSink = new DABDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demoddatv/datvideorender.h b/plugins/channelrx/demoddatv/datvideorender.h index ed79aa37f..88124e5ed 100644 --- a/plugins/channelrx/demoddatv/datvideorender.h +++ b/plugins/channelrx/demoddatv/datvideorender.h @@ -187,6 +187,7 @@ class DATVideoRenderThread : public QThread public: DATVideoRenderThread() { + setObjectName("DATVideoRender"); m_renderer = nullptr; m_stream = nullptr; m_renderingVideo = false; @@ -194,6 +195,7 @@ class DATVideoRenderThread : public QThread DATVideoRenderThread(DATVideoRender *renderer, DATVideostream *stream) { + setObjectName("DATVideoRender"); m_renderer = renderer; m_stream = stream; m_renderingVideo = false; diff --git a/plugins/channelrx/demoddsc/dscdemod.cpp b/plugins/channelrx/demoddsc/dscdemod.cpp index 36f2aa49b..6c0beae46 100644 --- a/plugins/channelrx/demoddsc/dscdemod.cpp +++ b/plugins/channelrx/demoddsc/dscdemod.cpp @@ -52,6 +52,7 @@ DSCDemod::DSCDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("DSCDemodBB"); m_basebandSink = new DSCDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demoddsd/dsddemod.cpp b/plugins/channelrx/demoddsd/dsddemod.cpp index 11c6d1998..9994413d4 100644 --- a/plugins/channelrx/demoddsd/dsddemod.cpp +++ b/plugins/channelrx/demoddsd/dsddemod.cpp @@ -155,6 +155,7 @@ void DSDDemod::start() qDebug() << "DSDDemod::start"; m_thread = new QThread(); + m_thread->setObjectName("DSDDemod"); m_basebandSink = new DSDDemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/demodendoftrain/endoftraindemod.cpp b/plugins/channelrx/demodendoftrain/endoftraindemod.cpp index 997ca1301..f3444cab9 100644 --- a/plugins/channelrx/demodendoftrain/endoftraindemod.cpp +++ b/plugins/channelrx/demodendoftrain/endoftraindemod.cpp @@ -47,6 +47,7 @@ EndOfTrainDemod::EndOfTrainDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("EndOfTrainBB"); m_basebandSink = new EndOfTrainDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodfreedv/freedvdemod.cpp b/plugins/channelrx/demodfreedv/freedvdemod.cpp index e0687f46a..7e1fda8d6 100644 --- a/plugins/channelrx/demodfreedv/freedvdemod.cpp +++ b/plugins/channelrx/demodfreedv/freedvdemod.cpp @@ -55,6 +55,7 @@ FreeDVDemod::FreeDVDemod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("FreeDVDemod"); m_basebandSink = new FreeDVDemodBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/demodft8/ft8demod.cpp b/plugins/channelrx/demodft8/ft8demod.cpp index 377c787e0..412dd26ad 100644 --- a/plugins/channelrx/demodft8/ft8demod.cpp +++ b/plugins/channelrx/demodft8/ft8demod.cpp @@ -157,6 +157,7 @@ void FT8Demod::start() qDebug() << "FT8Demod::start"; m_thread = new QThread(); + m_thread->setObjectName("FT8Demod"); m_basebandSink = new FT8DemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/demodft8/ft8demodbaseband.cpp b/plugins/channelrx/demodft8/ft8demodbaseband.cpp index c9188de73..8525c87ae 100644 --- a/plugins/channelrx/demodft8/ft8demodbaseband.cpp +++ b/plugins/channelrx/demodft8/ft8demodbaseband.cpp @@ -42,6 +42,7 @@ FT8DemodBaseband::FT8DemodBaseband() : m_ft8WorkerBuffer = new int16_t[FT8DemodSettings::m_ft8SampleRate*15]; m_workerThread = new QThread(); + m_workerThread->setObjectName("FT8DemodBB:W"); m_ft8DemodWorker = new FT8DemodWorker(); m_ft8DemodWorker->moveToThread(m_workerThread); @@ -63,6 +64,7 @@ FT8DemodBaseband::FT8DemodBaseband() : m_workerThread->start(); m_pskReporterThread = new QThread(); + m_pskReporterThread->setObjectName("pskReporter"); m_pskReporterWorker = new PskReporterWorker(); m_ft8DemodWorker->setPSKReportingMessageQueue(m_pskReporterWorker->getInputMessageQueue()); m_pskReporterWorker->moveToThread(m_pskReporterThread); diff --git a/plugins/channelrx/demodils/ilsdemod.cpp b/plugins/channelrx/demodils/ilsdemod.cpp index 111ccc463..2d5f69eff 100644 --- a/plugins/channelrx/demodils/ilsdemod.cpp +++ b/plugins/channelrx/demodils/ilsdemod.cpp @@ -60,6 +60,7 @@ ILSDemod::ILSDemod(DeviceAPI *deviceAPI) : m_angle(NAN) { setObjectName(m_channelId); + m_thread.setObjectName("ILSDemodBB"); m_basebandSink = new ILSDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodinmarsat/inmarsatdemod.cpp b/plugins/channelrx/demodinmarsat/inmarsatdemod.cpp index 1e5865d8c..845859c4c 100644 --- a/plugins/channelrx/demodinmarsat/inmarsatdemod.cpp +++ b/plugins/channelrx/demodinmarsat/inmarsatdemod.cpp @@ -47,6 +47,7 @@ InmarsatDemod::InmarsatDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("InmarsatBB"); m_basebandSink = new InmarsatDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodm17/m17demod.cpp b/plugins/channelrx/demodm17/m17demod.cpp index 46285c615..e30f4fd46 100644 --- a/plugins/channelrx/demodm17/m17demod.cpp +++ b/plugins/channelrx/demodm17/m17demod.cpp @@ -133,6 +133,7 @@ void M17Demod::start() qDebug() << "M17Demod::start"; m_thread = new QThread(this); + m_thread->setObjectName("M17Demod"); m_basebandSink = new M17DemodBaseband(); m_basebandSink->setChannel(this); m_basebandSink->setDemodInputMessageQueue(&m_inputMessageQueue); diff --git a/plugins/channelrx/demodmeshcore/meshcoredemod.cpp b/plugins/channelrx/demodmeshcore/meshcoredemod.cpp index 4825a20b7..33f188cd8 100644 --- a/plugins/channelrx/demodmeshcore/meshcoredemod.cpp +++ b/plugins/channelrx/demodmeshcore/meshcoredemod.cpp @@ -296,6 +296,7 @@ void MeshcoreDemod::startPipelines(const std::vector& configs) runtime.settings = config.settings; runtime.decoderThread = new QThread(); + runtime.decoderThread->setObjectName(QString("MCDemod:dc:%1").arg(runtime.id)); runtime.decoder = new MeshcoreDemodDecoder(); runtime.decoder->setOutputMessageQueue(getInputMessageQueue()); runtime.decoder->setPipelineMetadata(runtime.id, runtime.name, runtime.presetName); @@ -305,6 +306,7 @@ void MeshcoreDemod::startPipelines(const std::vector& configs) runtime.decoderThread->start(); runtime.basebandThread = new QThread(); + runtime.basebandThread->setObjectName(QString("MCDemod:bb:%1").arg(runtime.id)); runtime.basebandSink = new MeshcoreDemodBaseband(); if (config.id == 0) { @@ -464,6 +466,7 @@ void MeshcoreDemod::applyExtraPipelineSettings(const QVectorsetObjectName(QString("MCDemod:dc:%1").arg(runtime.id)); runtime.decoder = new MeshcoreDemodDecoder(); runtime.decoder->setOutputMessageQueue(getInputMessageQueue()); runtime.decoder->setPipelineMetadata(runtime.id, runtime.name, runtime.presetName); @@ -472,6 +475,7 @@ void MeshcoreDemod::applyExtraPipelineSettings(const QVectorstart(); runtime.basebandThread = new QThread(); + runtime.basebandThread->setObjectName(QString("MCDemod:bb:%1").arg(runtime.id)); runtime.basebandSink = new MeshcoreDemodBaseband(); // Secondary pipelines (id != 0) do not own the spectrum visualiser. runtime.basebandSink->setDecoderMessageQueue(runtime.decoder->getInputMessageQueue()); diff --git a/plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp b/plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp index 245d4c979..06db1daaf 100644 --- a/plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp +++ b/plugins/channelrx/demodmeshtastic/meshtasticdemod.cpp @@ -295,6 +295,7 @@ void MeshtasticDemod::startPipelines(const std::vector& configs) runtime.settings = config.settings; runtime.decoderThread = new QThread(); + runtime.decoderThread->setObjectName(QString("Mesh:dc:%1").arg(config.id)); runtime.decoder = new MeshtasticDemodDecoder(); runtime.decoder->setOutputMessageQueue(getInputMessageQueue()); runtime.decoder->setPipelineMetadata(runtime.id, runtime.name, runtime.presetName); @@ -304,6 +305,7 @@ void MeshtasticDemod::startPipelines(const std::vector& configs) runtime.decoderThread->start(); runtime.basebandThread = new QThread(); + runtime.basebandThread->setObjectName(QString("Mesh:bb:%1").arg(config.id)); runtime.basebandSink = new MeshtasticDemodBaseband(); if (config.id == 0) { @@ -463,6 +465,7 @@ void MeshtasticDemod::applyExtraPipelineSettings(const QVectorsetObjectName(QString("Mesh:dc:%1").arg(config.id)); runtime.decoder = new MeshtasticDemodDecoder(); runtime.decoder->setOutputMessageQueue(getInputMessageQueue()); runtime.decoder->setPipelineMetadata(runtime.id, runtime.name, runtime.presetName); @@ -471,6 +474,7 @@ void MeshtasticDemod::applyExtraPipelineSettings(const QVectorstart(); runtime.basebandThread = new QThread(); + runtime.basebandThread->setObjectName(QString("Mesh:bb:%1").arg(config.id)); runtime.basebandSink = new MeshtasticDemodBaseband(); // Secondary pipelines (id != 0) do not own the spectrum visualiser. runtime.basebandSink->setDecoderMessageQueue(runtime.decoder->getInputMessageQueue()); diff --git a/plugins/channelrx/demodnavtex/navtexdemod.cpp b/plugins/channelrx/demodnavtex/navtexdemod.cpp index 265eacb7c..8594f7044 100644 --- a/plugins/channelrx/demodnavtex/navtexdemod.cpp +++ b/plugins/channelrx/demodnavtex/navtexdemod.cpp @@ -52,6 +52,7 @@ NavtexDemod::NavtexDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("NavtexDemodBB"); m_basebandSink = new NavtexDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodnfm/nfmdemod.cpp b/plugins/channelrx/demodnfm/nfmdemod.cpp index 92c4fc289..cd1814476 100644 --- a/plugins/channelrx/demodnfm/nfmdemod.cpp +++ b/plugins/channelrx/demodnfm/nfmdemod.cpp @@ -129,6 +129,7 @@ void NFMDemod::start() qDebug() << "NFMDemod::start"; m_thread = new QThread(); + m_thread->setObjectName("NFMDemod"); m_basebandSink = new NFMDemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/demodpacket/packetdemod.cpp b/plugins/channelrx/demodpacket/packetdemod.cpp index bc8b70f11..1f1ef5ae3 100644 --- a/plugins/channelrx/demodpacket/packetdemod.cpp +++ b/plugins/channelrx/demodpacket/packetdemod.cpp @@ -51,6 +51,7 @@ PacketDemod::PacketDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("PacketDemodBB"); m_basebandSink = new PacketDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodpager/pagerdemod.cpp b/plugins/channelrx/demodpager/pagerdemod.cpp index 9f01a7ea2..a37be646d 100644 --- a/plugins/channelrx/demodpager/pagerdemod.cpp +++ b/plugins/channelrx/demodpager/pagerdemod.cpp @@ -47,6 +47,7 @@ PagerDemod::PagerDemod(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("PagerDemodBB"); m_basebandSink = new PagerDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodradiosonde/radiosondedemod.cpp b/plugins/channelrx/demodradiosonde/radiosondedemod.cpp index 65758e3d8..b6fde1014 100644 --- a/plugins/channelrx/demodradiosonde/radiosondedemod.cpp +++ b/plugins/channelrx/demodradiosonde/radiosondedemod.cpp @@ -49,6 +49,7 @@ RadiosondeDemod::RadiosondeDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("RadiosondeDeBB"); m_basebandSink = new RadiosondeDemodBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodrtty/rttydemod.cpp b/plugins/channelrx/demodrtty/rttydemod.cpp index f50637209..15b92fd84 100644 --- a/plugins/channelrx/demodrtty/rttydemod.cpp +++ b/plugins/channelrx/demodrtty/rttydemod.cpp @@ -52,6 +52,7 @@ RttyDemod::RttyDemod(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("RttyDemodBB"); m_basebandSink = new RttyDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/demodssb/ssbdemod.cpp b/plugins/channelrx/demodssb/ssbdemod.cpp index 4c5378f96..da2d99eb6 100644 --- a/plugins/channelrx/demodssb/ssbdemod.cpp +++ b/plugins/channelrx/demodssb/ssbdemod.cpp @@ -143,6 +143,7 @@ void SSBDemod::start() qDebug() << "SSBDemod::start"; m_thread = new QThread(); + m_thread->setObjectName("SSBDemod"); m_basebandSink = new SSBDemodBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/demodvor/vordemod.cpp b/plugins/channelrx/demodvor/vordemod.cpp index a09de93f5..70ce88c95 100644 --- a/plugins/channelrx/demodvor/vordemod.cpp +++ b/plugins/channelrx/demodvor/vordemod.cpp @@ -133,6 +133,7 @@ void VORDemod::start() qDebug("VORDemod::start"); m_thread = new QThread(); + m_thread->setObjectName("VORDemod"); m_basebandSink = new VORDemodBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/demodvormc/vordemodmc.cpp b/plugins/channelrx/demodvormc/vordemodmc.cpp index 315cf2edd..afe1d16d1 100644 --- a/plugins/channelrx/demodvormc/vordemodmc.cpp +++ b/plugins/channelrx/demodvormc/vordemodmc.cpp @@ -50,6 +50,7 @@ VORDemodMC::VORDemodMC(DeviceAPI *deviceAPI) : m_basebandSampleRate(0) { setObjectName(m_channelId); + m_thread.setObjectName("VORDemodMCBB"); m_basebandSink = new VORDemodMCBaseband(); m_basebandSink->moveToThread(&m_thread); diff --git a/plugins/channelrx/demodwfm/wfmdemod.cpp b/plugins/channelrx/demodwfm/wfmdemod.cpp index b2552c864..ca2a613f0 100644 --- a/plugins/channelrx/demodwfm/wfmdemod.cpp +++ b/plugins/channelrx/demodwfm/wfmdemod.cpp @@ -132,6 +132,7 @@ void WFMDemod::start() qDebug() << "WFMDemod::start"; m_thread = new QThread(this); + m_thread->setObjectName("WFMDemod"); m_basebandSink = new WFMDemodBaseband(); m_basebandSink->setChannel(this); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/filesink/filesink.cpp b/plugins/channelrx/filesink/filesink.cpp index 33f8697dc..f9e7d0945 100644 --- a/plugins/channelrx/filesink/filesink.cpp +++ b/plugins/channelrx/filesink/filesink.cpp @@ -145,6 +145,7 @@ void FileSink::start() qDebug("FileSink::start"); m_thread = new QThread(); + m_thread->setObjectName("FileSink"); m_basebandSink = new FileSinkBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/freqscanner/freqscanner.cpp b/plugins/channelrx/freqscanner/freqscanner.cpp index b29957194..fda833270 100644 --- a/plugins/channelrx/freqscanner/freqscanner.cpp +++ b/plugins/channelrx/freqscanner/freqscanner.cpp @@ -154,6 +154,7 @@ void FreqScanner::start() qDebug("FreqScanner::start"); m_thread = new QThread(); + m_thread->setObjectName("FreqScanner"); m_basebandSink = new FreqScannerBaseband(this); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/freqtracker/freqtracker.cpp b/plugins/channelrx/freqtracker/freqtracker.cpp index 99f71a521..b614e641b 100644 --- a/plugins/channelrx/freqtracker/freqtracker.cpp +++ b/plugins/channelrx/freqtracker/freqtracker.cpp @@ -130,6 +130,7 @@ void FreqTracker::start() qDebug("FreqTracker::start"); m_thread = new QThread(this); + m_thread->setObjectName("FreqTracker"); m_basebandSink = new FreqTrackerBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->setMessageQueueToInput(getInputMessageQueue()); diff --git a/plugins/channelrx/heatmap/heatmap.cpp b/plugins/channelrx/heatmap/heatmap.cpp index 3d3d8b3bc..b05aa6782 100644 --- a/plugins/channelrx/heatmap/heatmap.cpp +++ b/plugins/channelrx/heatmap/heatmap.cpp @@ -48,6 +48,7 @@ HeatMap::HeatMap(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("HeatMapBB"); m_basebandSink = new HeatMapBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/localsink/localsink.cpp b/plugins/channelrx/localsink/localsink.cpp index c96fc6575..2b95bd981 100644 --- a/plugins/channelrx/localsink/localsink.cpp +++ b/plugins/channelrx/localsink/localsink.cpp @@ -148,6 +148,7 @@ void LocalSink::startProcessing() qDebug("LocalSink::startProcessing"); m_thread = new QThread(this); + m_thread->setObjectName("LocalSink"); m_basebandSink = new LocalSinkBaseband(); m_basebandSink->setSpectrumSink(&m_spectrumVis); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/localsink/localsinksink.cpp b/plugins/channelrx/localsink/localsinksink.cpp index d3dcf60ab..26fe15c7d 100644 --- a/plugins/channelrx/localsink/localsinksink.cpp +++ b/plugins/channelrx/localsink/localsinksink.cpp @@ -38,6 +38,7 @@ LocalSinkSink::LocalSinkSink() : m_sampleRate(48000), m_deviceSampleRate(48000) { + m_sinkWorkerThread.setObjectName("LocalSinkSinkWr"); m_sampleFifo.setSize(SampleSinkFifo::getSizePolicy(4000000)); // m_fftFilter = new fftfilt(0.1f, 0.4f, 1<setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/radioastronomy/radioastronomy.cpp b/plugins/channelrx/radioastronomy/radioastronomy.cpp index 107b19211..f11ecf638 100644 --- a/plugins/channelrx/radioastronomy/radioastronomy.cpp +++ b/plugins/channelrx/radioastronomy/radioastronomy.cpp @@ -74,6 +74,8 @@ RadioAstronomy::RadioAstronomy(DeviceAPI *deviceAPI) : { qDebug("RadioAstronomy::RadioAstronomy"); setObjectName(m_channelId); + m_thread.setObjectName("RadioAstroBB"); + m_workerThread.setObjectName("RadioAstroWk"); m_basebandSink = new RadioAstronomyBaseband(this); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/radioclock/radioclock.cpp b/plugins/channelrx/radioclock/radioclock.cpp index 9401aed96..c0f5232a0 100644 --- a/plugins/channelrx/radioclock/radioclock.cpp +++ b/plugins/channelrx/radioclock/radioclock.cpp @@ -51,6 +51,7 @@ RadioClock::RadioClock(DeviceAPI *deviceAPI) : m_centerFrequency(0) { setObjectName(m_channelId); + m_thread.setObjectName("RadioClockBB"); m_basebandSink = new RadioClockBaseband(); m_basebandSink->setMessageQueueToChannel(getInputMessageQueue()); diff --git a/plugins/channelrx/remotesink/remotesink.cpp b/plugins/channelrx/remotesink/remotesink.cpp index 2956a6167..313c8054f 100644 --- a/plugins/channelrx/remotesink/remotesink.cpp +++ b/plugins/channelrx/remotesink/remotesink.cpp @@ -130,6 +130,7 @@ void RemoteSink::start() qDebug("RemoteSink::start: m_basebandSampleRate: %d", m_basebandSampleRate); m_thread = new QThread(); + m_thread->setObjectName("RemoteSink"); m_basebandSink = new RemoteSinkBaseband(); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/remotesink/remotesinksink.cpp b/plugins/channelrx/remotesink/remotesinksink.cpp index fbe19e9f3..60142cd3a 100644 --- a/plugins/channelrx/remotesink/remotesinksink.cpp +++ b/plugins/channelrx/remotesink/remotesinksink.cpp @@ -44,6 +44,7 @@ RemoteSinkSink::RemoteSinkSink() : m_dataPort(9090) { qDebug("RemoteSinkSink::RemoteSinkSink"); + m_senderThread.setObjectName("RmtSnkSnkSnd"); applySettings(QStringList(), m_settings, true); } diff --git a/plugins/channelrx/remotetcpsink/remotetcpsink.cpp b/plugins/channelrx/remotetcpsink/remotetcpsink.cpp index 46ad2907d..f466f17f7 100644 --- a/plugins/channelrx/remotetcpsink/remotetcpsink.cpp +++ b/plugins/channelrx/remotetcpsink/remotetcpsink.cpp @@ -59,6 +59,7 @@ RemoteTCPSink::RemoteTCPSink(DeviceAPI *deviceAPI) : m_removeRequest(nullptr) { setObjectName(m_channelId); + m_thread.setObjectName("RemoteTCPSinkBB"); m_basebandSink = new RemoteTCPSinkBaseband(); m_basebandSink->setMessageQueueToChannel(&m_inputMessageQueue); diff --git a/plugins/channelrx/sigmffilesink/sigmffilesink.cpp b/plugins/channelrx/sigmffilesink/sigmffilesink.cpp index 5d826ea2d..7469e5f6d 100644 --- a/plugins/channelrx/sigmffilesink/sigmffilesink.cpp +++ b/plugins/channelrx/sigmffilesink/sigmffilesink.cpp @@ -144,6 +144,7 @@ void SigMFFileSink::start() qDebug("SigMFFileSink::start"); m_thread = new QThread(); + m_thread->setObjectName("SigMFFileSink"); m_basebandSink = new SigMFFileSinkBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channelrx/udpsink/udpsink.cpp b/plugins/channelrx/udpsink/udpsink.cpp index 6480bdddf..721b5d505 100644 --- a/plugins/channelrx/udpsink/udpsink.cpp +++ b/plugins/channelrx/udpsink/udpsink.cpp @@ -57,6 +57,7 @@ UDPSink::UDPSink(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("UDPSink"); m_basebandSink = new UDPSinkBaseband(); m_basebandSink->setSpectrum(&m_spectrumVis); m_basebandSink->moveToThread(m_thread); diff --git a/plugins/channelrx/wdsprx/wdsprx.cpp b/plugins/channelrx/wdsprx/wdsprx.cpp index 079fa17ba..86136645b 100644 --- a/plugins/channelrx/wdsprx/wdsprx.cpp +++ b/plugins/channelrx/wdsprx/wdsprx.cpp @@ -145,6 +145,7 @@ void WDSPRx::start() qDebug() << "WDSPRx::start"; m_thread = new QThread(); + m_thread->setObjectName("WDSPRx"); m_basebandSink = new WDSPRxBaseband(); m_basebandSink->setFifoLabel(QString("%1 [%2:%3]") .arg(m_channelId) diff --git a/plugins/channeltx/filesource/filesource.cpp b/plugins/channeltx/filesource/filesource.cpp index 551e90ea9..380df5bb4 100644 --- a/plugins/channeltx/filesource/filesource.cpp +++ b/plugins/channeltx/filesource/filesource.cpp @@ -59,6 +59,7 @@ FileSource::FileSource(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("FileSource"); m_basebandSource = new FileSourceBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/localsource/localsource.cpp b/plugins/channeltx/localsource/localsource.cpp index da3ca869d..1fefc231f 100644 --- a/plugins/channeltx/localsource/localsource.cpp +++ b/plugins/channeltx/localsource/localsource.cpp @@ -53,6 +53,7 @@ LocalSource::LocalSource(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("LocalSource"); m_basebandSource = new LocalSourceBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/localsource/localsourcesource.cpp b/plugins/channeltx/localsource/localsourcesource.cpp index 266abd0f2..e2ceb0158 100644 --- a/plugins/channeltx/localsource/localsourcesource.cpp +++ b/plugins/channeltx/localsource/localsourcesource.cpp @@ -26,7 +26,9 @@ LocalSourceSource::LocalSourceSource() : m_chunkSize(0), m_localSamplesIndex(0), m_localSamplesIndexOffset(0) -{} +{ + m_sinkWorkerThread.setObjectName("LocalSrcSrcWrk"); +} LocalSourceSource::~LocalSourceSource() {} diff --git a/plugins/channeltx/mod802.15.4/ieee_802_15_4_mod.cpp b/plugins/channeltx/mod802.15.4/ieee_802_15_4_mod.cpp index 4a96860d2..c5debfd21 100644 --- a/plugins/channeltx/mod802.15.4/ieee_802_15_4_mod.cpp +++ b/plugins/channeltx/mod802.15.4/ieee_802_15_4_mod.cpp @@ -60,6 +60,7 @@ IEEE_802_15_4_Mod::IEEE_802_15_4_Mod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("802_15_4_Mod"); m_basebandSource = new IEEE_802_15_4_ModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modais/aismod.cpp b/plugins/channeltx/modais/aismod.cpp index 27e3ab039..5f5649b4e 100644 --- a/plugins/channeltx/modais/aismod.cpp +++ b/plugins/channeltx/modais/aismod.cpp @@ -62,6 +62,7 @@ AISMod::AISMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("AISMod"); m_basebandSource = new AISModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modam/ammod.cpp b/plugins/channeltx/modam/ammod.cpp index 1a2feba19..60a8c967e 100644 --- a/plugins/channeltx/modam/ammod.cpp +++ b/plugins/channeltx/modam/ammod.cpp @@ -116,6 +116,7 @@ void AMMod::start() qDebug("AMMod::start"); m_thread = new QThread(this); + m_thread->setObjectName("AMMod"); m_basebandSource = new AMModBaseband(); m_basebandSource->setInputFileStream(&m_ifstream); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modatv/atvmod.cpp b/plugins/channeltx/modatv/atvmod.cpp index 87ab166c8..00e6055b7 100644 --- a/plugins/channeltx/modatv/atvmod.cpp +++ b/plugins/channeltx/modatv/atvmod.cpp @@ -62,6 +62,7 @@ ATVMod::ATVMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("ATVMod"); m_basebandSource = new ATVModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modchirpchat/chirpchatmod.cpp b/plugins/channeltx/modchirpchat/chirpchatmod.cpp index 1b5165244..475df317c 100644 --- a/plugins/channeltx/modchirpchat/chirpchatmod.cpp +++ b/plugins/channeltx/modchirpchat/chirpchatmod.cpp @@ -61,6 +61,7 @@ ChirpChatMod::ChirpChatMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("ChirpChatMod"); m_basebandSource = new ChirpChatModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/moddatv/datvmod.cpp b/plugins/channeltx/moddatv/datvmod.cpp index 84c133720..2c8088864 100644 --- a/plugins/channeltx/moddatv/datvmod.cpp +++ b/plugins/channeltx/moddatv/datvmod.cpp @@ -63,6 +63,7 @@ DATVMod::DATVMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("DATVMod"); m_basebandSource = new DATVModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modfreedv/freedvmod.cpp b/plugins/channeltx/modfreedv/freedvmod.cpp index 3a7a242c7..6c6777e02 100644 --- a/plugins/channeltx/modfreedv/freedvmod.cpp +++ b/plugins/channeltx/modfreedv/freedvmod.cpp @@ -63,6 +63,7 @@ FreeDVMod::FreeDVMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("FreeDVMod"); m_basebandSource = new FreeDVModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setInputFileStream(&m_ifstream); diff --git a/plugins/channeltx/modm17/m17mod.cpp b/plugins/channeltx/modm17/m17mod.cpp index 141ebc3fe..b69465e02 100644 --- a/plugins/channeltx/modm17/m17mod.cpp +++ b/plugins/channeltx/modm17/m17mod.cpp @@ -62,6 +62,7 @@ M17Mod::M17Mod(DeviceAPI *deviceAPI) : m_loopPacketTimer.setInterval(m_settings.m_loopPacketInterval*1000); m_thread = new QThread(this); + m_thread->setObjectName("M17Mod"); m_basebandSource = new M17ModBaseband(); m_basebandSource->setInputFileStream(&m_ifstream); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modm17/m17modsource.cpp b/plugins/channeltx/modm17/m17modsource.cpp index 58aadd27d..888eab0e3 100644 --- a/plugins/channeltx/modm17/m17modsource.cpp +++ b/plugins/channeltx/modm17/m17modsource.cpp @@ -43,6 +43,7 @@ M17ModSource::M17ModSource() : m_preemphasisFilter(m_preemphasis*48000) { m_audioFifo.setLabel("M17ModSource.m_audioFifo"); + m_processorThread.setObjectName("M17ModSourceWrk"); m_feedbackAudioFifo.setLabel("M17ModSource.m_feedbackAudioFifo"); m_audioBuffer.resize(24000); m_audioBufferFill = 0; diff --git a/plugins/channeltx/modmeshcore/meshcoremod.cpp b/plugins/channeltx/modmeshcore/meshcoremod.cpp index 0a45a083e..b56a2a0f7 100644 --- a/plugins/channeltx/modmeshcore/meshcoremod.cpp +++ b/plugins/channeltx/modmeshcore/meshcoremod.cpp @@ -66,6 +66,7 @@ MeshcoreMod::MeshcoreMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("MeshcoreMod"); m_basebandSource = new MeshcoreModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modmeshtastic/meshtasticmod.cpp b/plugins/channeltx/modmeshtastic/meshtasticmod.cpp index 6840495d2..6c5304bdb 100644 --- a/plugins/channeltx/modmeshtastic/meshtasticmod.cpp +++ b/plugins/channeltx/modmeshtastic/meshtasticmod.cpp @@ -64,6 +64,7 @@ MeshtasticMod::MeshtasticMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("MeshtasticMod"); m_basebandSource = new MeshtasticModBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/modnfm/nfmmod.cpp b/plugins/channeltx/modnfm/nfmmod.cpp index 6a1fbc261..951e4e419 100644 --- a/plugins/channeltx/modnfm/nfmmod.cpp +++ b/plugins/channeltx/modnfm/nfmmod.cpp @@ -113,6 +113,7 @@ void NFMMod::start() qDebug("NFMMod::start"); m_thread = new QThread(this); + m_thread->setObjectName("NFMMod"); m_basebandSource = new NFMModBaseband(); m_basebandSource->setInputFileStream(&m_ifstream); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modpacket/packetmod.cpp b/plugins/channeltx/modpacket/packetmod.cpp index b1dc4a224..f1daffecd 100644 --- a/plugins/channeltx/modpacket/packetmod.cpp +++ b/plugins/channeltx/modpacket/packetmod.cpp @@ -64,6 +64,7 @@ PacketMod::PacketMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("PacketMod"); m_basebandSource = new PacketModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modpsk31/psk31mod.cpp b/plugins/channeltx/modpsk31/psk31mod.cpp index 4fdae2cdf..753c33892 100644 --- a/plugins/channeltx/modpsk31/psk31mod.cpp +++ b/plugins/channeltx/modpsk31/psk31mod.cpp @@ -60,6 +60,7 @@ PSK31::PSK31(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("PSK31"); m_basebandSource = new PSK31Baseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modrtty/rttymod.cpp b/plugins/channeltx/modrtty/rttymod.cpp index 9197e83e7..5e5af410d 100644 --- a/plugins/channeltx/modrtty/rttymod.cpp +++ b/plugins/channeltx/modrtty/rttymod.cpp @@ -60,6 +60,7 @@ RttyMod::RttyMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("RttyMod"); m_basebandSource = new RttyModBaseband(); m_basebandSource->setSpectrumSampleSink(&m_spectrumVis); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/modssb/ssbmod.cpp b/plugins/channeltx/modssb/ssbmod.cpp index 874acfa83..649e48f3e 100644 --- a/plugins/channeltx/modssb/ssbmod.cpp +++ b/plugins/channeltx/modssb/ssbmod.cpp @@ -65,6 +65,7 @@ SSBMod::SSBMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("SSBMod"); m_basebandSource = new SSBModBaseband(); m_basebandSource->setSpectrumSink(&m_spectrumVis); m_basebandSource->setInputFileStream(&m_ifstream); diff --git a/plugins/channeltx/modwfm/wfmmod.cpp b/plugins/channeltx/modwfm/wfmmod.cpp index 4c37b6d68..d2065548d 100644 --- a/plugins/channeltx/modwfm/wfmmod.cpp +++ b/plugins/channeltx/modwfm/wfmmod.cpp @@ -61,6 +61,7 @@ WFMMod::WFMMod(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("WFMMod"); m_basebandSource = new WFMModBaseband(); m_basebandSource->setInputFileStream(&m_ifstream); m_basebandSource->setChannel(this); diff --git a/plugins/channeltx/remotesource/remotesource.cpp b/plugins/channeltx/remotesource/remotesource.cpp index 7459bf27b..23a161504 100644 --- a/plugins/channeltx/remotesource/remotesource.cpp +++ b/plugins/channeltx/remotesource/remotesource.cpp @@ -57,6 +57,7 @@ RemoteSource::RemoteSource(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("RemoteSource"); m_basebandSource = new RemoteSourceBaseband(); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/channeltx/remotesource/remotesourcesource.cpp b/plugins/channeltx/remotesource/remotesourcesource.cpp index 05adf7db1..a500f1601 100644 --- a/plugins/channeltx/remotesource/remotesourcesource.cpp +++ b/plugins/channeltx/remotesource/remotesourcesource.cpp @@ -30,6 +30,7 @@ RemoteSourceSource::RemoteSourceSource() : m_nbUncorrectableErrors(0), m_channelSampleRate(48000) { + m_sourceWorkerThread.setObjectName("RmtSrcSrcWrk"); connect(&m_dataQueue, SIGNAL(dataBlockEnqueued()), this, SLOT(handleData()), Qt::QueuedConnection); m_cm256p = m_cm256.isInitialized() ? &m_cm256 : 0; m_currentMeta.init(); diff --git a/plugins/channeltx/udpsource/udpsource.cpp b/plugins/channeltx/udpsource/udpsource.cpp index 656a483d9..9838a3a19 100644 --- a/plugins/channeltx/udpsource/udpsource.cpp +++ b/plugins/channeltx/udpsource/udpsource.cpp @@ -50,6 +50,7 @@ UDPSource::UDPSource(DeviceAPI *deviceAPI) : setObjectName(m_channelId); m_thread = new QThread(this); + m_thread->setObjectName("UDPSource"); m_basebandSource = new UDPSourceBaseband(); m_basebandSource->setSpectrumSink(&m_spectrumVis); m_basebandSource->moveToThread(m_thread); diff --git a/plugins/feature/afc/afc.cpp b/plugins/feature/afc/afc.cpp index b697408e9..6c292bb14 100644 --- a/plugins/feature/afc/afc.cpp +++ b/plugins/feature/afc/afc.cpp @@ -95,6 +95,7 @@ void AFC::start() qDebug("AFC::start"); m_thread = new QThread(); + m_thread->setObjectName("AFC"); m_worker = new AFCWorker(getWebAPIAdapterInterface()); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/ambe/ambeengine.cpp b/plugins/feature/ambe/ambeengine.cpp index ca8f66f61..03a9d4b8e 100644 --- a/plugins/feature/ambe/ambeengine.cpp +++ b/plugins/feature/ambe/ambeengine.cpp @@ -249,6 +249,7 @@ bool AMBEEngine::registerController(const std::string& deviceRef) m_controllers.push_back(AMBEController()); m_controllers.back().worker = worker; m_controllers.back().thread = new QThread(); + m_controllers.back().thread->setObjectName("AMBE:" + QString::fromStdString(deviceRef)); m_controllers.back().device = deviceRef; m_controllers.back().worker->moveToThread(m_controllers.back().thread); diff --git a/plugins/feature/aprs/aprs.cpp b/plugins/feature/aprs/aprs.cpp index 8e2f41af9..fc796b027 100644 --- a/plugins/feature/aprs/aprs.cpp +++ b/plugins/feature/aprs/aprs.cpp @@ -97,6 +97,7 @@ void APRS::start() { qDebug("APRS::start"); m_thread = new QThread(); + m_thread->setObjectName("APRS"); m_worker = new APRSWorker(this, m_webAPIAdapterInterface); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/demodanalyzer/demodanalyzer.cpp b/plugins/feature/demodanalyzer/demodanalyzer.cpp index f94a717ed..e1e80baff 100644 --- a/plugins/feature/demodanalyzer/demodanalyzer.cpp +++ b/plugins/feature/demodanalyzer/demodanalyzer.cpp @@ -101,6 +101,7 @@ void DemodAnalyzer::start() qDebug("DemodAnalyzer::start"); m_thread = new QThread(); + m_thread->setObjectName("DemodAnalyzer"); m_worker = new DemodAnalyzerWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/denoiser/denoiser.cpp b/plugins/feature/denoiser/denoiser.cpp index af2baa8f3..e4e242484 100644 --- a/plugins/feature/denoiser/denoiser.cpp +++ b/plugins/feature/denoiser/denoiser.cpp @@ -103,6 +103,7 @@ void Denoiser::start() qDebug("Denoiser::start"); m_thread = new QThread(); + m_thread->setObjectName("Denoiser"); m_worker = new DenoiserWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/gs232controller/gs232controller.cpp b/plugins/feature/gs232controller/gs232controller.cpp index 4394ade07..d27d4bbd0 100644 --- a/plugins/feature/gs232controller/gs232controller.cpp +++ b/plugins/feature/gs232controller/gs232controller.cpp @@ -120,6 +120,7 @@ void GS232Controller::start() qDebug("GS232Controller::start"); m_thread = new QThread(); + m_thread->setObjectName("GS232Controller"); m_worker = new GS232ControllerWorker(this); m_worker->moveToThread(m_thread); QObject::connect(m_thread, &QThread::started, m_worker, &GS232ControllerWorker::startWork); diff --git a/plugins/feature/morsedecoder/morsedecoder.cpp b/plugins/feature/morsedecoder/morsedecoder.cpp index 69ab896ad..5616d0b02 100644 --- a/plugins/feature/morsedecoder/morsedecoder.cpp +++ b/plugins/feature/morsedecoder/morsedecoder.cpp @@ -100,6 +100,7 @@ void MorseDecoder::start() qDebug("MorseDecoder::start"); m_thread = new QThread(); + m_thread->setObjectName("MorseDecoder"); m_worker = new MorseDecoderWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/pertester/pertester.cpp b/plugins/feature/pertester/pertester.cpp index 1155bba05..82564bec6 100644 --- a/plugins/feature/pertester/pertester.cpp +++ b/plugins/feature/pertester/pertester.cpp @@ -77,6 +77,7 @@ void PERTester::start() qDebug("PERTester::start"); m_thread = new QThread(); + m_thread->setObjectName("PERTester"); m_worker = new PERTesterWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/remotecontrol/remotecontrol.cpp b/plugins/feature/remotecontrol/remotecontrol.cpp index c3a5c5d46..638f73963 100644 --- a/plugins/feature/remotecontrol/remotecontrol.cpp +++ b/plugins/feature/remotecontrol/remotecontrol.cpp @@ -54,6 +54,7 @@ void RemoteControl::start() qDebug() << "RemoteControl::start"; m_thread = new QThread(); + m_thread->setObjectName("RemoteControl"); m_worker = new RemoteControlWorker(); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/rigctlserver/rigctlserver.cpp b/plugins/feature/rigctlserver/rigctlserver.cpp index 332f7895a..87febeba8 100644 --- a/plugins/feature/rigctlserver/rigctlserver.cpp +++ b/plugins/feature/rigctlserver/rigctlserver.cpp @@ -43,6 +43,7 @@ RigCtlServer::RigCtlServer(WebAPIAdapterInterface *webAPIAdapterInterface) : { qDebug("RigCtlServer::RigCtlServer: webAPIAdapterInterface: %p", webAPIAdapterInterface); setObjectName(m_featureId); + m_thread.setObjectName("RigCtlServerBB"); m_worker = new RigCtlServerWorker(webAPIAdapterInterface); m_worker->moveToThread(&m_thread); setState(StIdle); diff --git a/plugins/feature/satellitetracker/satellitetracker.cpp b/plugins/feature/satellitetracker/satellitetracker.cpp index a82232e7f..d2908a673 100644 --- a/plugins/feature/satellitetracker/satellitetracker.cpp +++ b/plugins/feature/satellitetracker/satellitetracker.cpp @@ -90,6 +90,7 @@ void SatelliteTracker::start() } m_thread = new QThread(); + m_thread->setObjectName("SatTracker"); m_worker = new SatelliteTrackerWorker(this, m_webAPIAdapterInterface); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/sid/sid.cpp b/plugins/feature/sid/sid.cpp index 7617b54ff..74ebc7d83 100644 --- a/plugins/feature/sid/sid.cpp +++ b/plugins/feature/sid/sid.cpp @@ -71,6 +71,7 @@ void SIDMain::start() { qDebug("SIDMain::start"); m_thread = new QThread(); + m_thread->setObjectName("SIDMain"); m_worker = new SIDWorker(this, m_webAPIAdapterInterface); m_worker->moveToThread(m_thread); QObject::connect(m_thread, &QThread::started, m_worker, &SIDWorker::startWork); diff --git a/plugins/feature/simpleptt/simpleptt.cpp b/plugins/feature/simpleptt/simpleptt.cpp index 5d991e3da..7faf0dff3 100644 --- a/plugins/feature/simpleptt/simpleptt.cpp +++ b/plugins/feature/simpleptt/simpleptt.cpp @@ -81,6 +81,7 @@ void SimplePTT::start() qDebug("SimplePTT::start"); m_thread = new QThread(); + m_thread->setObjectName("SimplePTT"); m_worker = new SimplePTTWorker(getWebAPIAdapterInterface()); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/startracker/startracker.cpp b/plugins/feature/startracker/startracker.cpp index 1fa53a1c4..eb601c5b2 100644 --- a/plugins/feature/startracker/startracker.cpp +++ b/plugins/feature/startracker/startracker.cpp @@ -106,6 +106,7 @@ void StarTracker::start() qDebug("StarTracker::start"); m_thread = new QThread(); + m_thread->setObjectName("StarTracker"); m_worker = new StarTrackerWorker(this, m_webAPIAdapterInterface); m_worker->moveToThread(m_thread); diff --git a/plugins/feature/vorlocalizer/vorlocalizer.cpp b/plugins/feature/vorlocalizer/vorlocalizer.cpp index 113d8ae3c..1398dea0d 100644 --- a/plugins/feature/vorlocalizer/vorlocalizer.cpp +++ b/plugins/feature/vorlocalizer/vorlocalizer.cpp @@ -99,6 +99,7 @@ void VORLocalizer::start() qDebug("VORLocalizer::start"); m_thread = new QThread(); + m_thread->setObjectName("VORLocalizer"); m_worker = new VorLocalizerWorker(getWebAPIAdapterInterface()); m_worker->moveToThread(m_thread); diff --git a/plugins/samplemimo/audiocatsiso/audiocatsiso.cpp b/plugins/samplemimo/audiocatsiso/audiocatsiso.cpp index 70d295ae1..f2f08092d 100644 --- a/plugins/samplemimo/audiocatsiso/audiocatsiso.cpp +++ b/plugins/samplemimo/audiocatsiso/audiocatsiso.cpp @@ -131,6 +131,7 @@ bool AudioCATSISO::startRx() audioDeviceManager->addAudioSource(&m_inputFifo, getInputMessageQueue(), m_rxAudioDeviceIndex); m_inputWorkerThread = new QThread(); + m_inputWorkerThread->setObjectName(QString("AudCATrx:%1").arg(m_rxAudioDeviceIndex)); m_inputWorker = new AudioCATInputWorker(&m_sampleMIFifo, &m_inputFifo); m_inputWorker->moveToThread(m_inputWorkerThread); @@ -147,6 +148,7 @@ bool AudioCATSISO::startRx() qDebug() << "AudioCATSISO::startRx: start CAT"; m_catWorkerThread = new QThread(); + m_catWorkerThread->setObjectName(QString("AudCATwk:%1").arg(m_rxAudioDeviceIndex)); m_catWorker = new AudioCATSISOCATWorker(); m_catWorker->moveToThread(m_catWorkerThread); @@ -193,6 +195,7 @@ bool AudioCATSISO::startTx() audioDeviceManager->addAudioSink(&m_outputFifo, getInputMessageQueue(), m_txAudioDeviceIndex); m_outputWorkerThread = new QThread(); + m_outputWorkerThread->setObjectName(QString("AudCATtx:%1").arg(m_txAudioDeviceIndex)); m_outputWorker = new AudioCATOutputWorker(&m_sampleMOFifo, &m_outputFifo); m_outputWorker->moveToThread(m_outputWorkerThread); diff --git a/plugins/samplemimo/bladerf2mimo/bladerf2mithread.cpp b/plugins/samplemimo/bladerf2mimo/bladerf2mithread.cpp index c88938886..d4f2df51b 100644 --- a/plugins/samplemimo/bladerf2mimo/bladerf2mithread.cpp +++ b/plugins/samplemimo/bladerf2mimo/bladerf2mithread.cpp @@ -31,6 +31,7 @@ BladeRF2MIThread::BladeRF2MIThread(struct bladerf* dev, QObject* parent) : m_fcPos(0), m_iqOrder(true) { + setObjectName("BladeRF2MI"); qDebug("BladeRF2MIThread::BladeRF2MIThread"); m_buf = new qint16[2*DeviceBladeRF2::blockSize*2]; diff --git a/plugins/samplemimo/bladerf2mimo/bladerf2mothread.cpp b/plugins/samplemimo/bladerf2mimo/bladerf2mothread.cpp index 4c9591e8b..365d2075a 100644 --- a/plugins/samplemimo/bladerf2mimo/bladerf2mothread.cpp +++ b/plugins/samplemimo/bladerf2mimo/bladerf2mothread.cpp @@ -28,6 +28,7 @@ BladeRF2MOThread::BladeRF2MOThread(struct bladerf* dev, QObject* parent) : m_log2Interp(0), m_fcPos(0) { + setObjectName("BladeRF2MO"); qDebug("BladeRF2MOThread::BladeRF2MOThread"); m_buf = new qint16[2*DeviceBladeRF2::blockSize*2]; } diff --git a/plugins/samplemimo/limesdrmimo/limesdrmithread.cpp b/plugins/samplemimo/limesdrmimo/limesdrmithread.cpp index c4d15861d..46e244a48 100644 --- a/plugins/samplemimo/limesdrmimo/limesdrmithread.cpp +++ b/plugins/samplemimo/limesdrmimo/limesdrmithread.cpp @@ -27,6 +27,7 @@ LimeSDRMIThread::LimeSDRMIThread(lms_stream_t* stream0, lms_stream_t* stream1, Q m_sampleFifo(nullptr), m_iqOrder(true) { + setObjectName("LimeSDRMI"); qDebug("LimeSDRMIThread::LimeSDRMIThread"); for (unsigned int i = 0; i < 2; i++) { diff --git a/plugins/samplemimo/plutosdrmimo/plutosdrmithread.cpp b/plugins/samplemimo/plutosdrmimo/plutosdrmithread.cpp index bcadfee9d..39c841579 100644 --- a/plugins/samplemimo/plutosdrmimo/plutosdrmithread.cpp +++ b/plugins/samplemimo/plutosdrmimo/plutosdrmithread.cpp @@ -29,6 +29,7 @@ PlutoSDRMIThread::PlutoSDRMIThread(DevicePlutoSDRBox* plutoBox, QObject* parent) m_fcPos(0), m_iqOrder(true) { + setObjectName("PlutoSDRMI"); qDebug("PlutoSDRMIThread::PlutoSDRMIThread"); m_buf[0] = new qint16[2*m_plutoSDRBlockSizeSamples]; m_buf[1] = new qint16[2*m_plutoSDRBlockSizeSamples]; diff --git a/plugins/samplemimo/plutosdrmimo/plutosdrmothread.cpp b/plugins/samplemimo/plutosdrmimo/plutosdrmothread.cpp index 7a2014e2c..baf7cebb0 100644 --- a/plugins/samplemimo/plutosdrmimo/plutosdrmothread.cpp +++ b/plugins/samplemimo/plutosdrmimo/plutosdrmothread.cpp @@ -29,6 +29,7 @@ PlutoSDRMOThread::PlutoSDRMOThread(DevicePlutoSDRBox* plutoBox, QObject* parent) m_log2Interp(0), m_fcPos(0) { + setObjectName("PlutoSDRMO"); qDebug("PlutoSDRMOThread::PlutoSDRMOThread"); m_buf[0] = new qint16[2*PlutoSDRMIMOSettings::m_plutoSDRBlockSizeSamples]; m_buf[1] = new qint16[2*PlutoSDRMIMOSettings::m_plutoSDRBlockSizeSamples]; diff --git a/plugins/samplemimo/testmi/testmi.cpp b/plugins/samplemimo/testmi/testmi.cpp index 7934a9eb6..8feade0e7 100644 --- a/plugins/samplemimo/testmi/testmi.cpp +++ b/plugins/samplemimo/testmi/testmi.cpp @@ -95,11 +95,13 @@ bool TestMI::startRx() qDebug("TestMI::startRx"); m_testSourceWorkers.push_back(new TestMIWorker(&m_sampleMIFifo, 0)); m_testSourceWorkerThreads.push_back(new QThread()); + m_testSourceWorkerThreads.back()->setObjectName("TestMI:0"); m_testSourceWorkers.back()->moveToThread(m_testSourceWorkerThreads.back()); m_testSourceWorkers.back()->setSamplerate(m_settings.m_streams[0].m_sampleRate); m_testSourceWorkers.push_back(new TestMIWorker(&m_sampleMIFifo, 1)); m_testSourceWorkerThreads.push_back(new QThread()); + m_testSourceWorkerThreads.back()->setObjectName("TestMI:1"); m_testSourceWorkers.back()->moveToThread(m_testSourceWorkerThreads.back()); m_testSourceWorkers.back()->setSamplerate(m_settings.m_streams[1].m_sampleRate); diff --git a/plugins/samplemimo/testmosync/testmosync.cpp b/plugins/samplemimo/testmosync/testmosync.cpp index b316b3c47..e8bd2f027 100644 --- a/plugins/samplemimo/testmosync/testmosync.cpp +++ b/plugins/samplemimo/testmosync/testmosync.cpp @@ -74,6 +74,7 @@ bool TestMOSync::startTx() qDebug("TestMOSync::startTx"); m_sinkWorkerThread = new QThread(); + m_sinkWorkerThread->setObjectName("TestMOSync"); m_sinkWorker = new TestMOSyncWorker(); m_sinkWorker->moveToThread(m_sinkWorkerThread); diff --git a/plugins/samplemimo/xtrxmimo/xtrxmithread.cpp b/plugins/samplemimo/xtrxmimo/xtrxmithread.cpp index 5080c3cac..060b0fe58 100644 --- a/plugins/samplemimo/xtrxmimo/xtrxmithread.cpp +++ b/plugins/samplemimo/xtrxmimo/xtrxmithread.cpp @@ -30,6 +30,7 @@ XTRXMIThread::XTRXMIThread(struct xtrx_dev *dev, QObject* parent) : m_sampleFifo(nullptr), m_iqOrder(true) { + setObjectName("XTRXMI"); qDebug("XTRXMIThread::XTRXMIThread"); for (unsigned int i = 0; i < 2; i++) { diff --git a/plugins/samplemimo/xtrxmimo/xtrxmothread.cpp b/plugins/samplemimo/xtrxmimo/xtrxmothread.cpp index dd011d06c..5ab258085 100644 --- a/plugins/samplemimo/xtrxmimo/xtrxmothread.cpp +++ b/plugins/samplemimo/xtrxmimo/xtrxmothread.cpp @@ -29,6 +29,7 @@ XTRXMOThread::XTRXMOThread(struct xtrx_dev *dev, QObject* parent) : m_dev(dev), m_sampleFifo(nullptr) { + setObjectName("XTRXMO"); qDebug("XTRXMOThread::XTRXMOThread"); m_buf = new qint16[2*DeviceXTRX::blockSize*2]; std::fill(m_buf, m_buf + 2*DeviceXTRX::blockSize*2, 0); diff --git a/plugins/samplesink/aaroniartsaoutput/aaroniartsaoutput.cpp b/plugins/samplesink/aaroniartsaoutput/aaroniartsaoutput.cpp index 1f556aa2d..383507d8b 100644 --- a/plugins/samplesink/aaroniartsaoutput/aaroniartsaoutput.cpp +++ b/plugins/samplesink/aaroniartsaoutput/aaroniartsaoutput.cpp @@ -93,6 +93,7 @@ bool AaroniaRTSAOutput::start() qDebug() << "AaroniaRTSAOutput::start"; m_workerThread = new QThread(); + m_workerThread->setObjectName("AaroniaRTSAOut"); m_worker = new AaroniaRTSAOutputWorker(&m_sampleSourceFifo); m_worker->moveToThread(m_workerThread); diff --git a/plugins/samplesink/audiooutput/audiooutput.cpp b/plugins/samplesink/audiooutput/audiooutput.cpp index 2978c1f5e..fd99ad57c 100644 --- a/plugins/samplesink/audiooutput/audiooutput.cpp +++ b/plugins/samplesink/audiooutput/audiooutput.cpp @@ -85,6 +85,7 @@ bool AudioOutput::start() audioDeviceManager->addAudioSink(&m_audioFifo, getInputMessageQueue(), m_audioDeviceIndex); m_workerThread = new QThread(); + m_workerThread->setObjectName("AudioOutput:wrk"); m_worker = new AudioOutputWorker(&m_sampleSourceFifo, &m_audioFifo); m_worker->moveToThread(m_workerThread); diff --git a/plugins/samplesink/bladerf1output/bladerf1outputthread.cpp b/plugins/samplesink/bladerf1output/bladerf1outputthread.cpp index 922bc7c46..6da2f40f8 100644 --- a/plugins/samplesink/bladerf1output/bladerf1outputthread.cpp +++ b/plugins/samplesink/bladerf1output/bladerf1outputthread.cpp @@ -30,6 +30,7 @@ Bladerf1OutputThread::Bladerf1OutputThread(struct bladerf* dev, SampleSourceFifo m_sampleFifo(sampleFifo), m_log2Interp(0) { + setObjectName("Bladerf1Output"); std::fill(m_buf, m_buf + 2*BLADERFOUTPUT_BLOCKSIZE, 0); } diff --git a/plugins/samplesink/bladerf2output/bladerf2outputthread.cpp b/plugins/samplesink/bladerf2output/bladerf2outputthread.cpp index 3869d3274..fd4f4c5d7 100644 --- a/plugins/samplesink/bladerf2output/bladerf2outputthread.cpp +++ b/plugins/samplesink/bladerf2output/bladerf2outputthread.cpp @@ -27,6 +27,7 @@ BladeRF2OutputThread::BladeRF2OutputThread(struct bladerf* dev, unsigned int nbT m_dev(dev), m_nbChannels(nbTxChannels) { + setObjectName("BladeRF2Output"); qDebug("BladeRF2OutputThread::BladeRF2OutputThread"); m_channels = new Channel[nbTxChannels]; m_buf = new qint16[2*DeviceBladeRF2::blockSize*nbTxChannels]; diff --git a/plugins/samplesink/fileoutput/fileoutput.cpp b/plugins/samplesink/fileoutput/fileoutput.cpp index f9544c0f2..f9a013805 100644 --- a/plugins/samplesink/fileoutput/fileoutput.cpp +++ b/plugins/samplesink/fileoutput/fileoutput.cpp @@ -49,6 +49,7 @@ FileOutput::FileOutput(DeviceAPI *deviceAPI) : m_deviceDescription("FileOutput"), m_masterTimer(deviceAPI->getMasterTimer()) { + m_fileOutputWorkerThread.setObjectName("FileOutputWrk"); m_deviceAPI->setNbSinkStreams(1); m_networkManager = new QNetworkAccessManager(); } diff --git a/plugins/samplesink/hackrfoutput/hackrfoutputthread.cpp b/plugins/samplesink/hackrfoutput/hackrfoutputthread.cpp index 82d3076e0..fd182ae62 100644 --- a/plugins/samplesink/hackrfoutput/hackrfoutputthread.cpp +++ b/plugins/samplesink/hackrfoutput/hackrfoutputthread.cpp @@ -30,6 +30,7 @@ HackRFOutputThread::HackRFOutputThread(hackrf_device* dev, SampleSourceFifo* sam m_log2Interp(0), m_fcPos(2) { + setObjectName("HackRFOutput"); std::fill(m_buf, m_buf + 2*HACKRF_BLOCKSIZE, 0); } diff --git a/plugins/samplesink/limesdroutput/limesdroutputthread.cpp b/plugins/samplesink/limesdroutput/limesdroutputthread.cpp index e7bb34219..f07901fb3 100644 --- a/plugins/samplesink/limesdroutput/limesdroutputthread.cpp +++ b/plugins/samplesink/limesdroutput/limesdroutputthread.cpp @@ -29,6 +29,7 @@ LimeSDROutputThread::LimeSDROutputThread(lms_stream_t* stream, SampleSourceFifo* m_sampleFifo(sampleFifo), m_log2Interp(0) { + setObjectName("LimeSDROutput"); std::fill(m_buf, m_buf + 2*DeviceLimeSDR::blockSize, 0); } diff --git a/plugins/samplesink/plutosdroutput/plutosdroutputthread.cpp b/plugins/samplesink/plutosdroutput/plutosdroutputthread.cpp index 6fe5a5e30..0b2edd286 100644 --- a/plugins/samplesink/plutosdroutput/plutosdroutputthread.cpp +++ b/plugins/samplesink/plutosdroutput/plutosdroutputthread.cpp @@ -27,6 +27,7 @@ PlutoSDROutputThread::PlutoSDROutputThread(uint32_t blocksizeSamples, DevicePlut m_sampleFifo(sampleFifo), m_log2Interp(0) { + setObjectName("PlutoSDROutput"); m_buf = new qint16[blocksizeSamples*2]; } diff --git a/plugins/samplesink/remoteoutput/remoteoutput.cpp b/plugins/samplesink/remoteoutput/remoteoutput.cpp index e39eb9218..34a22ae8b 100644 --- a/plugins/samplesink/remoteoutput/remoteoutput.cpp +++ b/plugins/samplesink/remoteoutput/remoteoutput.cpp @@ -50,6 +50,7 @@ RemoteOutput::RemoteOutput(DeviceAPI *deviceAPI) : m_settings(), m_masterTimer(deviceAPI->getMasterTimer()) { + m_remoteOutputWorkerThread.setObjectName("RemoteOutputWrk"); m_deviceAPI->setNbSinkStreams(1); m_networkManager = new QNetworkAccessManager(); QObject::connect( diff --git a/plugins/samplesink/remoteoutput/udpsinkfec.cpp b/plugins/samplesink/remoteoutput/udpsinkfec.cpp index 2de770f08..4f9b40b9c 100644 --- a/plugins/samplesink/remoteoutput/udpsinkfec.cpp +++ b/plugins/samplesink/remoteoutput/udpsinkfec.cpp @@ -46,6 +46,7 @@ UDPSinkFEC::UDPSinkFEC() : m_currentMetaFEC.init(); m_senderThread = new QThread(this); + m_senderThread->setObjectName("UDPSinkFEC"); m_remoteOutputSender = new RemoteOutputSender(); m_remoteOutputSender->moveToThread(m_senderThread); } diff --git a/plugins/samplesink/soapysdroutput/soapysdroutputthread.cpp b/plugins/samplesink/soapysdroutput/soapysdroutputthread.cpp index 24663b40d..091d37457 100644 --- a/plugins/samplesink/soapysdroutput/soapysdroutputthread.cpp +++ b/plugins/samplesink/soapysdroutput/soapysdroutputthread.cpp @@ -36,6 +36,7 @@ SoapySDROutputThread::SoapySDROutputThread(SoapySDR::Device* dev, unsigned int n m_errors(0), m_consecutiveErrors(0) { + setObjectName("SoapySDROutput"); qDebug("SoapySDROutputThread::SoapySDROutputThread"); m_channels = new Channel[nbTxChannels]; } diff --git a/plugins/samplesink/testsink/testsinkoutput.cpp b/plugins/samplesink/testsink/testsinkoutput.cpp index 0fc27f2ed..51dab516b 100644 --- a/plugins/samplesink/testsink/testsinkoutput.cpp +++ b/plugins/samplesink/testsink/testsinkoutput.cpp @@ -72,6 +72,7 @@ bool TestSinkOutput::start() qDebug() << "TestSinkOutput::start"; m_testSinkWorkerThread = new QThread(); + m_testSinkWorkerThread->setObjectName("TestSinkOutput"); m_testSinkWorker = new TestSinkWorker(&m_sampleSourceFifo); m_testSinkWorker->moveToThread(m_testSinkWorkerThread); diff --git a/plugins/samplesink/usrpoutput/usrpoutputthread.cpp b/plugins/samplesink/usrpoutput/usrpoutputthread.cpp index 2c9bcc20e..ceac5c6f4 100644 --- a/plugins/samplesink/usrpoutput/usrpoutputthread.cpp +++ b/plugins/samplesink/usrpoutput/usrpoutputthread.cpp @@ -36,6 +36,7 @@ USRPOutputThread::USRPOutputThread(uhd::tx_streamer::sptr stream, size_t bufSamp m_sampleFifo(sampleFifo), m_log2Interp(0) { + setObjectName("USRPOutput"); // *2 as samples are I+Q m_buf = new qint16[2 * bufSamples]; std::fill(m_buf, m_buf + 2 * bufSamples, 0); diff --git a/plugins/samplesink/xtrxoutput/xtrxoutputthread.cpp b/plugins/samplesink/xtrxoutput/xtrxoutputthread.cpp index ce9adc4b8..9f92e91c0 100644 --- a/plugins/samplesink/xtrxoutput/xtrxoutputthread.cpp +++ b/plugins/samplesink/xtrxoutput/xtrxoutputthread.cpp @@ -31,6 +31,7 @@ XTRXOutputThread::XTRXOutputThread(struct xtrx_dev *dev, unsigned int nbChannels m_nbChannels(nbChannels), m_uniqueChannelIndex(uniqueChannelIndex) { + setObjectName("XTRXOutput"); qDebug("XTRXOutputThread::XTRXOutputThread: nbChannels: %u uniqueChannelIndex: %u", nbChannels, uniqueChannelIndex); m_channels = new Channel[2]; } diff --git a/plugins/samplesource/aaroniartsainput/aaroniartsainput.cpp b/plugins/samplesource/aaroniartsainput/aaroniartsainput.cpp index 93ed2382c..c5383c59f 100644 --- a/plugins/samplesource/aaroniartsainput/aaroniartsainput.cpp +++ b/plugins/samplesource/aaroniartsainput/aaroniartsainput.cpp @@ -101,6 +101,7 @@ bool AaroniaRTSAInput::start() } m_aaroniaRTSAWorkerThread = new QThread(); + m_aaroniaRTSAWorkerThread->setObjectName("AaroniaRTSAIn"); m_aaroniaRTSAWorker = new AaroniaRTSAInputWorker(&m_sampleFifo); m_aaroniaRTSAWorker->setInputMessageQueue(getInputMessageQueue()); m_aaroniaRTSAWorker->moveToThread(m_aaroniaRTSAWorkerThread); diff --git a/plugins/samplesource/airspy/airspyinput.cpp b/plugins/samplesource/airspy/airspyinput.cpp index 2941db548..97677a3d8 100644 --- a/plugins/samplesource/airspy/airspyinput.cpp +++ b/plugins/samplesource/airspy/airspyinput.cpp @@ -206,6 +206,7 @@ bool AirspyInput::start() } m_airspyWorkerThread = new QThread(); + m_airspyWorkerThread->setObjectName("AirspyInput"); m_airspyWorker = new AirspyWorker(m_dev, &m_sampleFifo); m_airspyWorker->moveToThread(m_airspyWorkerThread); diff --git a/plugins/samplesource/airspyhf/airspyhfinput.cpp b/plugins/samplesource/airspyhf/airspyhfinput.cpp index d8c8e6aa4..592026dd0 100644 --- a/plugins/samplesource/airspyhf/airspyhfinput.cpp +++ b/plugins/samplesource/airspyhf/airspyhfinput.cpp @@ -180,6 +180,7 @@ bool AirspyHFInput::start() } m_airspyHFWorkerThread = new QThread(); + m_airspyHFWorkerThread->setObjectName("AirspyHFInput"); m_airspyHFWorker = new AirspyHFWorker(m_dev, &m_sampleFifo, &m_replayBuffer); m_airspyHFWorker->moveToThread(m_airspyHFWorkerThread); int sampleRateIndex = m_settings.m_devSampleRateIndex; diff --git a/plugins/samplesource/androidsdrdriverinput/androidsdrdriverinput.cpp b/plugins/samplesource/androidsdrdriverinput/androidsdrdriverinput.cpp index 7b1647fde..7dad3df00 100644 --- a/plugins/samplesource/androidsdrdriverinput/androidsdrdriverinput.cpp +++ b/plugins/samplesource/androidsdrdriverinput/androidsdrdriverinput.cpp @@ -49,6 +49,7 @@ AndroidSDRDriverInput::AndroidSDRDriverInput(DeviceAPI *deviceAPI) : m_androidSDRDriverInputTCPPHandler(nullptr), m_deviceDescription("AndroidSDRDriverInput") { + m_thread.setObjectName("AndroidSDRBB"); m_sampleFifo.setLabel(m_deviceDescription); m_sampleFifo.setSize(48000 * 8); m_androidSDRDriverInputTCPPHandler = new AndroidSDRDriverInputTCPHandler(&m_sampleFifo, m_deviceAPI); diff --git a/plugins/samplesource/audioinput/audioinput.cpp b/plugins/samplesource/audioinput/audioinput.cpp index ca0e8744c..7c0d81934 100644 --- a/plugins/samplesource/audioinput/audioinput.cpp +++ b/plugins/samplesource/audioinput/audioinput.cpp @@ -107,6 +107,7 @@ bool AudioInput::start() audioDeviceManager->addAudioSource(&m_fifo, getInputMessageQueue(), m_audioDeviceIndex); m_workerThread = new QThread(); + m_workerThread->setObjectName("AudioInput"); m_worker = new AudioInputWorker(&m_sampleFifo, &m_fifo); m_worker->moveToThread(m_workerThread); diff --git a/plugins/samplesource/bladerf1input/bladerf1inputthread.cpp b/plugins/samplesource/bladerf1input/bladerf1inputthread.cpp index 58d393d0b..eff99ae50 100644 --- a/plugins/samplesource/bladerf1input/bladerf1inputthread.cpp +++ b/plugins/samplesource/bladerf1input/bladerf1inputthread.cpp @@ -37,6 +37,7 @@ Bladerf1InputThread::Bladerf1InputThread(struct bladerf* dev, SampleSinkFifo* sa m_fcPos(0), m_iqOrder(true) { + setObjectName("Bladerf1Input"); std::fill(m_buf, m_buf + 2*BLADERF_BLOCKSIZE, 0); } diff --git a/plugins/samplesource/bladerf2input/bladerf2inputthread.cpp b/plugins/samplesource/bladerf2input/bladerf2inputthread.cpp index 34ba363fb..36b77b346 100644 --- a/plugins/samplesource/bladerf2input/bladerf2inputthread.cpp +++ b/plugins/samplesource/bladerf2input/bladerf2inputthread.cpp @@ -26,6 +26,7 @@ BladeRF2InputThread::BladeRF2InputThread(struct bladerf* dev, unsigned int nbRxC m_nbChannels(nbRxChannels), m_iqOrder(true) { + setObjectName("BladeRF2Input"); qDebug("BladeRF2InputThread::BladeRF2InputThread"); m_channels = new Channel[nbRxChannels]; diff --git a/plugins/samplesource/fcdpro/fcdprothread.cpp b/plugins/samplesource/fcdpro/fcdprothread.cpp index a3c16600d..1438b15c5 100644 --- a/plugins/samplesource/fcdpro/fcdprothread.cpp +++ b/plugins/samplesource/fcdpro/fcdprothread.cpp @@ -40,6 +40,7 @@ FCDProThread::FCDProThread(SampleSinkFifo* sampleFifo, AudioFifo *fcdFIFO, QObje m_convertBuffer(fcd_traits::convBufSize), m_sampleFifo(sampleFifo) { + setObjectName("FCDPro"); start(); } diff --git a/plugins/samplesource/fcdproplus/fcdproplusthread.cpp b/plugins/samplesource/fcdproplus/fcdproplusthread.cpp index 072f74005..3de662d46 100644 --- a/plugins/samplesource/fcdproplus/fcdproplusthread.cpp +++ b/plugins/samplesource/fcdproplus/fcdproplusthread.cpp @@ -40,6 +40,7 @@ FCDProPlusThread::FCDProPlusThread(SampleSinkFifo* sampleFifo, AudioFifo *fcdFIF m_convertBuffer(fcd_traits::convBufSize), m_sampleFifo(sampleFifo) { + setObjectName("FCDProPlus"); start(); } diff --git a/plugins/samplesource/fileinput/fileinput.cpp b/plugins/samplesource/fileinput/fileinput.cpp index eca61566e..4f1113aad 100644 --- a/plugins/samplesource/fileinput/fileinput.cpp +++ b/plugins/samplesource/fileinput/fileinput.cpp @@ -64,6 +64,7 @@ FileInput::FileInput(DeviceAPI *deviceAPI) : m_recordLengthMuSec(0), m_startingTimeStamp(0) { + m_fileInputWorkerThread.setObjectName("FileInputWrk"); m_sampleFifo.setLabel(m_deviceDescription); m_deviceAPI->setNbSourceStreams(1); qDebug("FileInput::FileInput: device source engine: %p", m_deviceAPI->getDeviceSourceEngine()); diff --git a/plugins/samplesource/fobos/fobosinput.cpp b/plugins/samplesource/fobos/fobosinput.cpp index 291d857ba..b043d4cf7 100644 --- a/plugins/samplesource/fobos/fobosinput.cpp +++ b/plugins/samplesource/fobos/fobosinput.cpp @@ -125,6 +125,7 @@ bool FOBOSInput::start() } m_workerThread = new QThread(); + m_workerThread->setObjectName("FOBOSInput"); m_worker = new FOBOSWorker(&m_sampleFifo); m_worker->moveToThread(m_workerThread); diff --git a/plugins/samplesource/hackrfinput/hackrfinputthread.cpp b/plugins/samplesource/hackrfinput/hackrfinputthread.cpp index 54d27c870..2fb18f13d 100644 --- a/plugins/samplesource/hackrfinput/hackrfinputthread.cpp +++ b/plugins/samplesource/hackrfinput/hackrfinputthread.cpp @@ -34,6 +34,7 @@ HackRFInputThread::HackRFInputThread(hackrf_device* dev, SampleSinkFifo* sampleF m_fcPos(0), m_iqOrder(true) { + setObjectName("HackRFInput"); std::fill(m_buf, m_buf + 2*HACKRF_BLOCKSIZE, 0); } diff --git a/plugins/samplesource/kiwisdr/kiwisdrinput.cpp b/plugins/samplesource/kiwisdr/kiwisdrinput.cpp index 8aec9769c..702359d7a 100644 --- a/plugins/samplesource/kiwisdr/kiwisdrinput.cpp +++ b/plugins/samplesource/kiwisdr/kiwisdrinput.cpp @@ -103,6 +103,7 @@ bool KiwiSDRInput::start() } m_kiwiSDRWorkerThread = new QThread(); + m_kiwiSDRWorkerThread->setObjectName("KiwiSDRInput"); m_kiwiSDRWorker = new KiwiSDRWorker(&m_sampleFifo); m_kiwiSDRWorker->setInputMessageQueue(getInputMessageQueue()); m_kiwiSDRWorker->moveToThread(m_kiwiSDRWorkerThread); diff --git a/plugins/samplesource/perseus/perseusinput.cpp b/plugins/samplesource/perseus/perseusinput.cpp index fb27c2715..a5367533a 100644 --- a/plugins/samplesource/perseus/perseusinput.cpp +++ b/plugins/samplesource/perseus/perseusinput.cpp @@ -88,6 +88,7 @@ bool PerseusInput::start() // start / stop streaming is done in the thread. m_perseusWorkerThread = new QThread(); + m_perseusWorkerThread->setObjectName("PerseusInput"); m_perseusWorker = new PerseusWorker(m_perseusDescriptor, &m_sampleFifo); m_perseusWorker->moveToThread(m_perseusWorkerThread); qDebug("PerseusInput::start: worker created"); diff --git a/plugins/samplesource/plutosdrinput/plutosdrinputthread.cpp b/plugins/samplesource/plutosdrinput/plutosdrinputthread.cpp index 2a38ed5c5..05bfc61ad 100644 --- a/plugins/samplesource/plutosdrinput/plutosdrinputthread.cpp +++ b/plugins/samplesource/plutosdrinput/plutosdrinputthread.cpp @@ -33,6 +33,7 @@ PlutoSDRInputThread::PlutoSDRInputThread(uint32_t blocksizeSamples, DevicePlutoS m_phasor(0), m_iqOrder(true) { + setObjectName("PlutoSDRInput"); m_buf = new qint16[blocksizeSamples*2]; // (I,Q) -> 2 * int16_t m_bufConv = new qint16[blocksizeSamples*2]; // (I,Q) -> 2 * int16_t } diff --git a/plugins/samplesource/remotetcpinput/remotetcpinput.cpp b/plugins/samplesource/remotetcpinput/remotetcpinput.cpp index 9b90f0fad..5f1c9d894 100644 --- a/plugins/samplesource/remotetcpinput/remotetcpinput.cpp +++ b/plugins/samplesource/remotetcpinput/remotetcpinput.cpp @@ -58,6 +58,7 @@ RemoteTCPInput::RemoteTCPInput(DeviceAPI *deviceAPI) : m_azimuth(std::numeric_limits::quiet_NaN()), m_elevation(std::numeric_limits::quiet_NaN()) { + m_thread.setObjectName("RemoteTCPInBB"); m_sampleFifo.setLabel(m_deviceDescription); m_sampleFifo.setSize(48000 * 8); m_remoteInputTCPPHandler = new RemoteTCPInputTCPHandler(&m_sampleFifo, m_deviceAPI, &m_replayBuffer); diff --git a/plugins/samplesource/rtlsdr/rtlsdrthread.cpp b/plugins/samplesource/rtlsdr/rtlsdrthread.cpp index db1cc1eec..a4c0a05ff 100644 --- a/plugins/samplesource/rtlsdr/rtlsdrthread.cpp +++ b/plugins/samplesource/rtlsdr/rtlsdrthread.cpp @@ -38,6 +38,7 @@ RTLSDRThread::RTLSDRThread(rtlsdr_dev_t* dev, SampleSinkFifo* sampleFifo, Replay m_sampleFifo(sampleFifo), m_replayBuffer(replayBuffer) { + setObjectName("RTLSDR"); applySettings(settings, QStringList(), true); connect(&m_inputMessageQueue, &MessageQueue::messageEnqueued, this, &RTLSDRThread::handleInputMessages); } diff --git a/plugins/samplesource/sdrplay/sdrplaythread.cpp b/plugins/samplesource/sdrplay/sdrplaythread.cpp index ce35a8baa..e47b1ff35 100644 --- a/plugins/samplesource/sdrplay/sdrplaythread.cpp +++ b/plugins/samplesource/sdrplay/sdrplaythread.cpp @@ -31,6 +31,7 @@ SDRPlayThread::SDRPlayThread(mirisdr_dev_t* dev, SampleSinkFifo* sampleFifo, QOb m_fcPos(0), m_iqOrder(true) { + setObjectName("SDRPlay"); } SDRPlayThread::~SDRPlayThread() diff --git a/plugins/samplesource/sigmffileinput/sigmffileinput.cpp b/plugins/samplesource/sigmffileinput/sigmffileinput.cpp index d4a893cb9..f307dc75c 100644 --- a/plugins/samplesource/sigmffileinput/sigmffileinput.cpp +++ b/plugins/samplesource/sigmffileinput/sigmffileinput.cpp @@ -64,6 +64,7 @@ SigMFFileInput::SigMFFileInput(DeviceAPI *deviceAPI) : m_settings() { m_sampleFifo.setLabel(m_deviceDescription); + m_fileInputWorkerThread.setObjectName("SigMFInputWrk"); m_deviceAPI->setNbSourceStreams(1); qDebug("SigMFFileInput::SigMFFileInput: device source engine: %p", m_deviceAPI->getDeviceSourceEngine()); qDebug("SigMFFileInput::SigMFFileInput: device source engine message queue: %p", m_deviceAPI->getDeviceEngineInputMessageQueue()); diff --git a/plugins/samplesource/soapysdrinput/soapysdrinputthread.cpp b/plugins/samplesource/soapysdrinput/soapysdrinputthread.cpp index a1296c7d3..1b0aa839c 100644 --- a/plugins/samplesource/soapysdrinput/soapysdrinputthread.cpp +++ b/plugins/samplesource/soapysdrinput/soapysdrinputthread.cpp @@ -36,6 +36,7 @@ SoapySDRInputThread::SoapySDRInputThread(SoapySDR::Device* dev, unsigned int nbR m_decimatorType(DecimatorFloat), m_iqOrder(true) { + setObjectName("SoapySDRInput"); qDebug("SoapySDRInputThread::SoapySDRInputThread"); m_channels = new Channel[nbRxChannels]; } diff --git a/plugins/samplesource/testsource/testsourceinput.cpp b/plugins/samplesource/testsource/testsourceinput.cpp index 488d7c25c..0141a8577 100644 --- a/plugins/samplesource/testsource/testsourceinput.cpp +++ b/plugins/samplesource/testsource/testsourceinput.cpp @@ -98,6 +98,7 @@ bool TestSourceInput::start() } m_testSourceWorkerThread = new QThread(); + m_testSourceWorkerThread->setObjectName("TestSourceInput"); m_testSourceWorker = new TestSourceWorker(&m_sampleFifo); m_testSourceWorker->moveToThread(m_testSourceWorkerThread); diff --git a/plugins/samplesource/usrpinput/usrpinputthread.cpp b/plugins/samplesource/usrpinput/usrpinputthread.cpp index 5a5209109..aea4a2f74 100644 --- a/plugins/samplesource/usrpinput/usrpinputthread.cpp +++ b/plugins/samplesource/usrpinput/usrpinputthread.cpp @@ -39,6 +39,7 @@ USRPInputThread::USRPInputThread(uhd::rx_streamer::sptr stream, size_t bufSample m_replayBuffer(replayBuffer), m_log2Decim(0) { + setObjectName("USRPInput"); // *2 as samples are I+Q m_buf = new qint16[2*bufSamples]; std::fill(m_buf, m_buf + 2*bufSamples, 0); diff --git a/plugins/samplesource/xtrxinput/xtrxinputthread.cpp b/plugins/samplesource/xtrxinput/xtrxinputthread.cpp index de1ee8071..c93c7a3ba 100644 --- a/plugins/samplesource/xtrxinput/xtrxinputthread.cpp +++ b/plugins/samplesource/xtrxinput/xtrxinputthread.cpp @@ -31,6 +31,7 @@ XTRXInputThread::XTRXInputThread(struct xtrx_dev *dev, unsigned int nbChannels, m_uniqueChannelIndex(uniqueChannelIndex), m_iqOrder(true) { + setObjectName("XTRXInput"); qDebug("XTRXInputThread::XTRXInputThread: nbChannels: %u uniqueChannelIndex: %u", nbChannels, uniqueChannelIndex); m_channels = new Channel[2]; diff --git a/sdrbase/audio/audiodevicemanager.cpp b/sdrbase/audio/audiodevicemanager.cpp index 97414ce79..e89a95ba0 100644 --- a/sdrbase/audio/audiodevicemanager.cpp +++ b/sdrbase/audio/audiodevicemanager.cpp @@ -290,6 +290,7 @@ void AudioDeviceManager::addAudioSink(AudioFifo* audioFifo, MessageQueue *sample if (m_audioOutputs.find(outputDeviceIndex) == m_audioOutputs.end()) { QThread *thread = new QThread(); + thread->setObjectName(QString("AudioOut:%1").arg(outputDeviceIndex)); AudioOutputDevice *audioOutputDevice = new AudioOutputDevice(); m_audioOutputs[outputDeviceIndex] = audioOutputDevice; m_audioOutputThreads[outputDeviceIndex] = thread; @@ -383,6 +384,7 @@ void AudioDeviceManager::addAudioSource(AudioFifo* audioFifo, MessageQueue *samp if (m_audioInputs.find(inputDeviceIndex) == m_audioInputs.end()) { QThread *thread = new QThread(); + thread->setObjectName(QString("AudioIn:%1").arg(inputDeviceIndex)); AudioInputDevice *audioInputDevice = new AudioInputDevice(); m_audioInputs[inputDeviceIndex] = audioInputDevice; m_audioInputThreads[inputDeviceIndex] = thread; diff --git a/sdrbase/pipes/datapipes.cpp b/sdrbase/pipes/datapipes.cpp index c5c3a05b2..c27ea3bd7 100644 --- a/sdrbase/pipes/datapipes.cpp +++ b/sdrbase/pipes/datapipes.cpp @@ -23,6 +23,7 @@ DataPipes::DataPipes() : m_registrations(&m_dataFifoStore) { + m_gcThread.setObjectName("DataPipes:gc"); m_gcWorker = new DataPipesGCWorker(m_registrations); m_gcWorker->moveToThread(&m_gcThread); startGC(); diff --git a/sdrbase/pipes/messagepipes.cpp b/sdrbase/pipes/messagepipes.cpp index 1104e0150..da3cc98a3 100644 --- a/sdrbase/pipes/messagepipes.cpp +++ b/sdrbase/pipes/messagepipes.cpp @@ -23,6 +23,7 @@ MessagePipes::MessagePipes() : m_registrations(&m_messageQueueStore) { + m_gcThread.setObjectName("MessagePipes:gc"); m_gcWorker = new MessagePipesGCWorker(m_registrations); m_gcWorker->moveToThread(&m_gcThread); startGC(); diff --git a/sdrbase/pipes/messagepipeslegacy.cpp b/sdrbase/pipes/messagepipeslegacy.cpp index a563efcb3..220faaf4d 100644 --- a/sdrbase/pipes/messagepipeslegacy.cpp +++ b/sdrbase/pipes/messagepipeslegacy.cpp @@ -26,6 +26,7 @@ MessagePipesLegacy::MessagePipesLegacy() { + m_gcThread.setObjectName("LgcyMsgPipe:gc"); m_gcWorker = new MessagePipesLegacyGCWorker(); m_gcWorker->setC2FRegistrations( m_registrations.getMutex(), diff --git a/sdrgui/gui/samplingdevicedialog.cpp b/sdrgui/gui/samplingdevicedialog.cpp index 25a0eccd3..383d6eed9 100644 --- a/sdrgui/gui/samplingdevicedialog.cpp +++ b/sdrgui/gui/samplingdevicedialog.cpp @@ -145,6 +145,7 @@ void SamplingDeviceDialog::on_refreshDevices_clicked() m_progressDialog->show(); SamplingDeviceDialogWorker *worker = new SamplingDeviceDialogWorker(m_deviceType); QThread *thread = new QThread(); + thread->setObjectName(QString("Sampling:%1").arg(m_deviceType)); worker->moveToThread(thread); connect(thread, &QThread::started, worker, &SamplingDeviceDialogWorker::enumerateDevices); connect(worker, &SamplingDeviceDialogWorker::finishedWork, thread, &QThread::quit); From 8b13ca699a51175f0eb8bd55f83ce02008b28b09 Mon Sep 17 00:00:00 2001 From: Jon Beniston Date: Sun, 27 Sep 2026 10:12:25 +0100 Subject: [PATCH 02/11] Add NVIDIA Denoiser support. Add VST3 effects plugins support. --- cmake/cpack/deploy_mac.cmake.in | 6 + .../feature/demodanalyzer/demodanalyzer.cpp | 83 +- plugins/feature/demodanalyzer/demodanalyzer.h | 13 +- .../demodanalyzer/demodanalyzergui.cpp | 2 +- .../feature/demodanalyzer/demodanalyzergui.h | 2 +- .../demodanalyzer/demodanalyzersettings.cpp | 1 + plugins/feature/demodanalyzer/readme.md | 7 +- plugins/feature/denoiser/CMakeLists.txt | 29 + plugins/feature/denoiser/denoiser.cpp | 441 +- plugins/feature/denoiser/denoiser.h | 43 +- plugins/feature/denoiser/denoisergui.cpp | 517 ++- plugins/feature/denoiser/denoisergui.h | 19 +- plugins/feature/denoiser/denoisergui.ui | 158 +- plugins/feature/denoiser/denoisersettings.cpp | 83 +- plugins/feature/denoiser/denoisersettings.h | 10 + plugins/feature/denoiser/denoiserworker.cpp | 344 +- plugins/feature/denoiser/denoiserworker.h | 58 +- .../feature/denoiser/nvidiaaudioeffects.cpp | 302 ++ plugins/feature/denoiser/nvidiaaudioeffects.h | 41 + plugins/feature/denoiser/readme.md | 73 +- plugins/feature/denoiser/vst3/LICENSE.txt | 27 + plugins/feature/denoiser/vst3/vst3_c_api.h | 3777 +++++++++++++++++ plugins/feature/denoiser/vst3effect.cpp | 1415 ++++++ plugins/feature/denoiser/vst3effect.h | 87 + plugins/feature/denoiser/vst3scan.cpp | 83 + sdrbase/maincore.cpp | 1 + sdrbase/maincore.h | 22 + .../webapi/doc/swagger/include/Denoiser.yaml | 25 + .../api/swagger/include/Denoiser.yaml | 25 + .../code/qt5/client/SWGDenoiserSettings.cpp | 110 +- .../code/qt5/client/SWGDenoiserSettings.h | 32 + 31 files changed, 7646 insertions(+), 190 deletions(-) create mode 100644 plugins/feature/denoiser/nvidiaaudioeffects.cpp create mode 100644 plugins/feature/denoiser/nvidiaaudioeffects.h create mode 100644 plugins/feature/denoiser/vst3/LICENSE.txt create mode 100644 plugins/feature/denoiser/vst3/vst3_c_api.h create mode 100644 plugins/feature/denoiser/vst3effect.cpp create mode 100644 plugins/feature/denoiser/vst3effect.h create mode 100644 plugins/feature/denoiser/vst3scan.cpp diff --git a/cmake/cpack/deploy_mac.cmake.in b/cmake/cpack/deploy_mac.cmake.in index 6ef9054f6..6d5af1ee5 100644 --- a/cmake/cpack/deploy_mac.cmake.in +++ b/cmake/cpack/deploy_mac.cmake.in @@ -11,6 +11,12 @@ execute_process (COMMAND mkdir ${CPACK_TEMPORARY_INSTALL_DIRECTORY}/SDRangel.app execute_process (COMMAND pwd) execute_process (COMMAND cp sdrangel ${CPACK_TEMPORARY_INSTALL_DIRECTORY}/SDRangel.app/Contents/MacOS/SDRangel) +# The Denoiser launches the VST3 scanner beside the app executable. +if(EXISTS "@CMAKE_BINARY_DIR@/sdrangel-vst3-scan") + file(COPY "@CMAKE_BINARY_DIR@/sdrangel-vst3-scan" + DESTINATION "${CPACK_TEMPORARY_INSTALL_DIRECTORY}/SDRangel.app/Contents/MacOS") +endif() + # Add RPATHS to libraries so macdeployqt can find out and copy all dependencies message ("Adding RPATHs to executables and libraries") diff --git a/plugins/feature/demodanalyzer/demodanalyzer.cpp b/plugins/feature/demodanalyzer/demodanalyzer.cpp index f94a717ed..5b95dc95e 100644 --- a/plugins/feature/demodanalyzer/demodanalyzer.cpp +++ b/plugins/feature/demodanalyzer/demodanalyzer.cpp @@ -207,12 +207,21 @@ bool DemodAnalyzer::handleMessage(const Message& cmd) else if (MsgSelectChannel::match(cmd)) { MsgSelectChannel& cfg = (MsgSelectChannel&) cmd; - ChannelAPI *selectedChannel = cfg.getChannel(); + QObject *selectedChannel = cfg.getChannel(); + if (!selectedChannel) { + return true; + } qDebug("DemodAnalyzer::handleMessage: MsgSelectChannel: %p %s", selectedChannel, qPrintable(selectedChannel->objectName())); setChannel(selectedChannel); - MainCore::MsgChannelDemodQuery *msg = MainCore::MsgChannelDemodQuery::create(); - selectedChannel->getInputMessageQueue()->push(msg); + if (m_selectedChannel == selectedChannel) + { + if (auto *channel = qobject_cast(selectedChannel)) { + channel->getInputMessageQueue()->push(MainCore::MsgChannelDemodQuery::create()); + } else if (auto *feature = qobject_cast(selectedChannel)) { + feature->getInputMessageQueue()->push(MainCore::MsgChannelDemodQuery::create()); + } + } return true; } @@ -221,32 +230,17 @@ bool DemodAnalyzer::handleMessage(const Message& cmd) qDebug() << "DemodAnalyzer::handleMessage: MainCore::MsgChannelDemodReport"; MainCore::MsgChannelDemodReport& report = (MainCore::MsgChannelDemodReport&) cmd; - if (report.getChannelAPI() == m_selectedChannel) - { - m_sampleRate = report.getSampleRate(); - m_scopeVis.setLiveRate(m_sampleRate); - - if (m_running) { - m_worker->applySampleRate(m_sampleRate); - } - - DSPSignalNotification *msg = new DSPSignalNotification(0, m_sampleRate); - m_spectrumVis.getInputMessageQueue()->push(msg); - - if (m_dataPipe) - { - DataFifo *fifo = qobject_cast(m_dataPipe->m_element); - - if (fifo) { - fifo->setSize(2*m_sampleRate); - } - } + if (report.getChannelAPI() == m_selectedChannel) { + applyReportedSampleRate(report.getSampleRate()); + } - if (getMessageQueueToGUI()) - { - MsgReportSampleRate *msg = MsgReportSampleRate::create(m_sampleRate); - getMessageQueueToGUI()->push(msg); - } + return true; + } + else if (MainCore::MsgFeatureDemodReport::match(cmd)) + { + const auto& report = static_cast(cmd); + if (report.getFeature() == m_selectedChannel) { + applyReportedSampleRate(report.getSampleRate()); } return true; @@ -257,6 +251,35 @@ bool DemodAnalyzer::handleMessage(const Message& cmd) } } +void DemodAnalyzer::applyReportedSampleRate(int sampleRate) +{ + if (sampleRate <= 0) { + return; + } + + m_sampleRate = sampleRate; + m_scopeVis.setLiveRate(m_sampleRate); + + if (m_running) { + m_worker->applySampleRate(m_sampleRate); + } + + m_spectrumVis.getInputMessageQueue()->push(new DSPSignalNotification(0, m_sampleRate)); + + if (m_dataPipe) + { + DataFifo *fifo = qobject_cast(m_dataPipe->m_element); + + if (fifo) { + fifo->setSize(2*m_sampleRate); + } + } + + if (getMessageQueueToGUI()) { + getMessageQueueToGUI()->push(MsgReportSampleRate::create(m_sampleRate)); + } +} + QByteArray DemodAnalyzer::serialize() const { return m_settings.serialize(); @@ -331,7 +354,7 @@ void DemodAnalyzer::getAvailableChannelsReport() } -void DemodAnalyzer::setChannel(ChannelAPI *selectedChannel) +void DemodAnalyzer::setChannel(QObject *selectedChannel) { if ((selectedChannel == m_selectedChannel) || (m_availableChannels.indexOfObject(selectedChannel) == -1)) { return; @@ -342,7 +365,7 @@ void DemodAnalyzer::setChannel(ChannelAPI *selectedChannel) if (m_selectedChannel) { ObjectPipe *pipe = mainCore->getDataPipes().unregisterProducerToConsumer(m_selectedChannel, this, "demod"); - DataFifo *fifo = qobject_cast(pipe->m_element); + DataFifo *fifo = pipe ? qobject_cast(pipe->m_element) : nullptr; if ((fifo) && m_running) { diff --git a/plugins/feature/demodanalyzer/demodanalyzer.h b/plugins/feature/demodanalyzer/demodanalyzer.h index c241c992d..209b0a5fd 100644 --- a/plugins/feature/demodanalyzer/demodanalyzer.h +++ b/plugins/feature/demodanalyzer/demodanalyzer.h @@ -118,15 +118,15 @@ public: MESSAGE_CLASS_DECLARATION public: - ChannelAPI *getChannel() { return m_channel; } - static MsgSelectChannel* create(ChannelAPI *channel) { + QObject *getChannel() { return m_channel; } + static MsgSelectChannel* create(QObject *channel) { return new MsgSelectChannel(channel); } protected: - ChannelAPI *m_channel; + QObject *m_channel; - MsgSelectChannel(ChannelAPI *channel) : + MsgSelectChannel(QObject *channel) : Message(), m_channel(channel) { } @@ -209,7 +209,7 @@ private: ScopeVis m_scopeVis; AvailableChannelOrFeatureList m_availableChannels; AvailableChannelOrFeatureHandler m_availableChannelOrFeatureHandler; - ChannelAPI *m_selectedChannel; + QObject *m_selectedChannel; ObjectPipe *m_dataPipe; int m_sampleRate; @@ -220,7 +220,8 @@ private: void stop(); void applySettings(const DemodAnalyzerSettings& settings, const QList& settingsKeys, bool force = false); void notifyUpdate(const QStringList& renameFrom, const QStringList& renameTo); - void setChannel(ChannelAPI *selectedChannel); + void setChannel(QObject *selectedChannel); + void applyReportedSampleRate(int sampleRate); void webapiReverseSendSettings(const QList& featureSettingsKeys, const DemodAnalyzerSettings& settings, bool force); private slots: diff --git a/plugins/feature/demodanalyzer/demodanalyzergui.cpp b/plugins/feature/demodanalyzer/demodanalyzergui.cpp index a7fe64ae4..267cd64e5 100644 --- a/plugins/feature/demodanalyzer/demodanalyzergui.cpp +++ b/plugins/feature/demodanalyzer/demodanalyzergui.cpp @@ -316,7 +316,7 @@ void DemodAnalyzerGUI::on_channels_currentIndexChanged(int index) { if ((index >= 0) && (index < m_availableChannels.size())) { - m_selectedChannel = qobject_cast(m_availableChannels[index].m_object); + m_selectedChannel = m_availableChannels[index].m_object; DemodAnalyzer::MsgSelectChannel *msg = DemodAnalyzer::MsgSelectChannel::create(m_selectedChannel); m_demodAnalyzer->getInputMessageQueue()->push(msg); } diff --git a/plugins/feature/demodanalyzer/demodanalyzergui.h b/plugins/feature/demodanalyzer/demodanalyzergui.h index 90c345e00..64cf9fb3b 100644 --- a/plugins/feature/demodanalyzer/demodanalyzergui.h +++ b/plugins/feature/demodanalyzer/demodanalyzergui.h @@ -70,7 +70,7 @@ private: ScopeVis* m_scopeVis; MessageQueue m_inputMessageQueue; AvailableChannelOrFeatureList m_availableChannels; - ChannelAPI *m_selectedChannel; + QObject *m_selectedChannel; MovingAverageUtil m_channelPowerAvg; explicit DemodAnalyzerGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature, QWidget* parent = nullptr); diff --git a/plugins/feature/demodanalyzer/demodanalyzersettings.cpp b/plugins/feature/demodanalyzer/demodanalyzersettings.cpp index 452cc7eef..9b179aa08 100644 --- a/plugins/feature/demodanalyzer/demodanalyzersettings.cpp +++ b/plugins/feature/demodanalyzer/demodanalyzersettings.cpp @@ -49,6 +49,7 @@ const QStringList DemodAnalyzerSettings::m_channelURIs = { QStringLiteral("sdrangel.channel.wfmdemod"), QStringLiteral("sdrangel.channeltx.modwfm"), QStringLiteral("sdrangel.channel.wdsprx"), + QStringLiteral("sdrangel.feature.denoiser"), }; DemodAnalyzerSettings::DemodAnalyzerSettings() : diff --git a/plugins/feature/demodanalyzer/readme.md b/plugins/feature/demodanalyzer/readme.md index 22d040346..c24bfbcb1 100644 --- a/plugins/feature/demodanalyzer/readme.md +++ b/plugins/feature/demodanalyzer/readme.md @@ -3,6 +3,7 @@

Introduction

This plugin can be used to analyze the real demodulated signal from some Rx channel plugins. It can also be used to view the modulating signal of some Tx channel plugins. +It can also display filtered audio from some feature plugins. Rx plugins are: @@ -32,6 +33,10 @@ Tx plugins are: - SSB modulator - WFM modulator +Features are: + + - Denoiser feature +

General interface

![Demod Analyzer plugin GUI](../../../doc/img/DemodAnalyzer_plugin.png) @@ -58,7 +63,7 @@ This button starts or stops the plugin

A.3: Channel selection

-Use this combo to select which channel to use for display. Channel is selected upon change. If channel is not changed or there is only one in the list you have to use the (re)apply button (A.4) to effectively connect the channel to the analyzer. +Use this combo to select which channel or feature to use for display. The source is selected upon change. If the selection is not changed or there is only one in the list, use the (re)apply button (A.4) to connect it to the analyzer.

A.4: (Re)apply channel selection

diff --git a/plugins/feature/denoiser/CMakeLists.txt b/plugins/feature/denoiser/CMakeLists.txt index e8cb69faa..b9a88a7f4 100644 --- a/plugins/feature/denoiser/CMakeLists.txt +++ b/plugins/feature/denoiser/CMakeLists.txt @@ -1,11 +1,20 @@ project(denoiser) +if(APPLE) + find_library(VST3_COREFOUNDATION_FRAMEWORK CoreFoundation) + if(NOT VST3_COREFOUNDATION_FRAMEWORK) + message(FATAL_ERROR "CoreFoundation is required for VST3 support on macOS") + endif() +endif() + set(denoiser_SOURCES denoiser.cpp denoisersettings.cpp denoiserplugin.cpp denoiserworker.cpp denoiserwebapiadapter.cpp + nvidiaaudioeffects.cpp + vst3effect.cpp ) set(denoiser_HEADERS @@ -14,6 +23,8 @@ set(denoiser_HEADERS denoiserplugin.h denoiserworker.h denoiserwebapiadapter.h + nvidiaaudioeffects.h + vst3effect.h ) include_directories( @@ -56,6 +67,8 @@ endif() target_link_libraries(${TARGET_NAME} PRIVATE Qt::Core + ${CMAKE_DL_LIBS} + ${VST3_COREFOUNDATION_FRAMEWORK} ${TARGET_LIB} sdrbase ${TARGET_LIB_GUI} @@ -64,6 +77,22 @@ target_link_libraries(${TARGET_NAME} PRIVATE install(TARGETS ${TARGET_NAME} DESTINATION ${INSTALL_FOLDER}) +if(NOT SERVER_MODE) + add_executable(sdrangel-vst3-scan vst3scan.cpp vst3effect.cpp) + target_link_libraries(sdrangel-vst3-scan PRIVATE Qt::Core ${CMAKE_DL_LIBS} ${VST3_COREFOUNDATION_FRAMEWORK}) + if(WIN32) + set(VST3_SCAN_RUNTIME_DIR "${SDRANGEL_BINARY_BIN_DIR}") + else() + set(VST3_SCAN_RUNTIME_DIR "${CMAKE_BINARY_DIR}") + endif() + set_target_properties(sdrangel-vst3-scan PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${VST3_SCAN_RUNTIME_DIR}" + RUNTIME_OUTPUT_DIRECTORY_DEBUG "${VST3_SCAN_RUNTIME_DIR}" + RUNTIME_OUTPUT_DIRECTORY_RELEASE "${VST3_SCAN_RUNTIME_DIR}" + RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO "${VST3_SCAN_RUNTIME_DIR}") + install(TARGETS sdrangel-vst3-scan DESTINATION ${INSTALL_BIN_DIR}) +endif() + # Install debug symbols if (WIN32) install(FILES $ CONFIGURATIONS Debug RelWithDebInfo DESTINATION ${INSTALL_FOLDER} ) diff --git a/plugins/feature/denoiser/denoiser.cpp b/plugins/feature/denoiser/denoiser.cpp index af2baa8f3..a6eb426a9 100644 --- a/plugins/feature/denoiser/denoiser.cpp +++ b/plugins/feature/denoiser/denoiser.cpp @@ -19,6 +19,8 @@ #include #include #include +#include +#include #include "SWGFeatureSettings.h" #include "SWGFeatureActions.h" @@ -31,6 +33,7 @@ #include "maincore.h" #include "denoiserworker.h" +#include "vst3effect.h" #include "denoiser.h" MESSAGE_CLASS_DEFINITION(Denoiser::MsgConfigureDenoiser, Message) @@ -39,6 +42,37 @@ MESSAGE_CLASS_DEFINITION(Denoiser::MsgReportChannels, Message) MESSAGE_CLASS_DEFINITION(Denoiser::MsgSelectChannel, Message) MESSAGE_CLASS_DEFINITION(Denoiser::MsgReportSampleRate, Message) +namespace { + +QString vst3ParametersJson(const QMap& values) +{ + QJsonObject object; + + for (auto it = values.cbegin(); it != values.cend(); ++it) { + object.insert(QString::number(it.key()), it.value()); + } + + return QString::fromUtf8(QJsonDocument(object).toJson(QJsonDocument::Compact)); +} + +QMap parseVst3Parameters(const QString& json) +{ + QMap values; + const QJsonObject object = QJsonDocument::fromJson(json.toUtf8()).object(); + + for (auto it = object.begin(); it != object.end(); ++it) + { + bool validId = false; + const quint32 id = it.key().toUInt(&validId); + const double value = it.value().toDouble(-1.0); + if (validId && value >= 0.0 && value <= 1.0) values.insert(id, value); + } + + return values; +} + +} + const char* const Denoiser::m_featureIdURI = "sdrangel.feature.denoiser"; const char* const Denoiser::m_featureId = "Denoiser"; @@ -49,7 +83,8 @@ Denoiser::Denoiser(WebAPIAdapterInterface *webAPIAdapterInterface) : m_worker(nullptr), m_availableChannelOrFeatureHandler(DenoiserSettings::m_channelURIs), m_selectedChannel(nullptr), - m_dataPipe(nullptr) + m_dataPipe(nullptr), + m_sampleRate(0) { qDebug("Denoiser::Denoiser: webAPIAdapterInterface: %p", webAPIAdapterInterface); setObjectName(m_featureId); @@ -101,6 +136,8 @@ void Denoiser::start() return; } + useDefaultSampleRate(); + qDebug("Denoiser::start"); m_thread = new QThread(); m_worker = new DenoiserWorker(); @@ -126,6 +163,7 @@ void Denoiser::start() ); m_worker->setMessageQueueToFeature(getInputMessageQueue()); + m_worker->setDemodProducer(this); m_worker->startWork(); setState(StRunning); m_thread->start(); @@ -152,6 +190,7 @@ void Denoiser::start() m_running = true; + configureVst3(); } void Denoiser::stop() @@ -164,6 +203,8 @@ void Denoiser::stop() qDebug("Denoiser::stop"); m_running = false; + m_worker->setVst3Effect(nullptr); + m_vst3Effect.reset(); if (m_dataPipe) { @@ -189,7 +230,7 @@ double Denoiser::getMagSqAvg() const bool Denoiser::handleMessage(const Message& cmd) { - if (MsgConfigureDenoiser::match(cmd)) + if (MsgConfigureDenoiser::match(cmd)) { MsgConfigureDenoiser& cfg = (MsgConfigureDenoiser&) cmd; qDebug() << "Denoiser::handleMessage: MsgConfigureDenoiser"; @@ -197,6 +238,32 @@ bool Denoiser::handleMessage(const Message& cmd) return true; } + else if (DenoiserWorker::MsgReportNvidiaStatus::match(cmd)) + { + const auto& report = static_cast(cmd); + if (m_running && m_settings.m_enableDenoiser && + m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Nvidia) + { + if (report.getError().isEmpty()) { + m_state = StRunning; + } else { + m_errorMessage = report.getError(); + m_state = StError; + } + } + return true; + } + else if (DenoiserWorker::MsgReportVst3Status::match(cmd)) + { + const auto& report = static_cast(cmd); + if (m_running && m_settings.m_enableDenoiser && + m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Vst3) + { + m_errorMessage = report.getError(); + m_state = StError; + } + return true; + } else if (MsgStartStop::match(cmd)) { MsgStartStop& cfg = (MsgStartStop&) cmd; @@ -213,42 +280,40 @@ bool Denoiser::handleMessage(const Message& cmd) else if (MsgSelectChannel::match(cmd)) { MsgSelectChannel& cfg = (MsgSelectChannel&) cmd; - ChannelAPI *selectedChannel = cfg.getChannel(); + QObject *selectedChannel = cfg.getChannel(); + if (!selectedChannel) { + return true; + } qDebug("Denoiser::handleMessage: MsgSelectChannel: %p %s", selectedChannel, qPrintable(selectedChannel->objectName())); setChannel(selectedChannel); - MainCore::MsgChannelDemodQuery *msg = MainCore::MsgChannelDemodQuery::create(); - selectedChannel->getInputMessageQueue()->push(msg); + if (m_selectedChannel == selectedChannel) { + querySelectedSource(); + } return true; } + else if (MainCore::MsgChannelDemodQuery::match(cmd)) + { + reportDemodSampleRate(); + return true; + } else if (MainCore::MsgChannelDemodReport::match(cmd)) { qDebug() << "Denoiser::handleMessage: MainCore::MsgChannelDemodReport"; MainCore::MsgChannelDemodReport& report = (MainCore::MsgChannelDemodReport&) cmd; - if (report.getChannelAPI() == m_selectedChannel) - { - m_sampleRate = report.getSampleRate(); - - if (m_running) { - m_worker->applySampleRate(m_sampleRate); - } - - if (m_dataPipe) - { - DataFifo *fifo = qobject_cast(m_dataPipe->m_element); - - if (fifo) { - fifo->setSize(2*m_sampleRate); - } - } + if (report.getChannelAPI() == m_selectedChannel) { + applyReportedSampleRate(report.getSampleRate()); + } - if (getMessageQueueToGUI()) - { - MsgReportSampleRate *msg = MsgReportSampleRate::create(m_sampleRate); - getMessageQueueToGUI()->push(msg); - } + return true; + } + else if (MainCore::MsgFeatureDemodReport::match(cmd)) + { + const auto& report = static_cast(cmd); + if (report.getFeature() == m_selectedChannel) { + applyReportedSampleRate(report.getSampleRate()); } return true; @@ -303,24 +368,189 @@ void Denoiser::applySettings(const DenoiserSettings& settings, const QListsetParameter(it.key(), it.value()); + } + } + } +} + +QVector Denoiser::vst3Parameters() const +{ + return m_vst3Effect ? m_vst3Effect->parameters() : QVector(); +} + +bool Denoiser::hasVst3Effect() const +{ + return m_vst3Effect != nullptr; +} + +QString Denoiser::vst3ParameterText(quint32 id, double value) const +{ + return m_vst3Effect ? m_vst3Effect->parameterText(id, value) : QString::number(value, 'f', 3); +} + +void Denoiser::configureVst3() +{ + if (!m_worker) { + return; + } + m_worker->setVst3Effect(nullptr); + m_vst3Effect.reset(); + if (!m_running || !m_settings.m_enableDenoiser || + m_settings.m_denoiserType != DenoiserSettings::DenoiserType::DenoiserType_Vst3) + { + return; + } + if (m_sampleRate <= 0) { + return; + } + if (m_settings.m_vst3ModulePath.isEmpty() || m_settings.m_vst3ClassId.size() != 16) + { + m_errorMessage = QStringLiteral("Select a VST3 audio effect"); + m_state = StError; + return; + } + auto effect = std::make_unique(); + QString error; + if (!effect->open(m_settings.m_vst3ModulePath, m_settings.m_vst3ClassId, m_sampleRate, 2, error, m_settings.m_vst3State)) + { + m_errorMessage = QStringLiteral("VST3: %1. Audio is passing through.").arg(error); + m_state = StError; + qWarning() << m_errorMessage; + return; + } + for (auto it = m_settings.m_vst3Parameters.cbegin(); it != m_settings.m_vst3Parameters.cend(); ++it) { + effect->setParameter(it.key(), it.value()); + } + m_worker->setVst3Effect(effect.get()); + m_vst3Effect = std::move(effect); + if (m_state == StError) { + m_state = StRunning; + } +} + +void Denoiser::useDefaultSampleRate() +{ + if (!m_selectedChannel || m_sampleRate > 0) { + return; + } + + m_sampleRate = 48000; + + if (m_dataPipe) + { + DataFifo *fifo = qobject_cast(m_dataPipe->m_element); + if (fifo) { + fifo->setSize(2 * m_sampleRate); + } + } + + if (getMessageQueueToGUI()) { + getMessageQueueToGUI()->push(MsgReportSampleRate::create(m_sampleRate)); + } + reportDemodSampleRate(); +} + +void Denoiser::applyReportedSampleRate(int sampleRate) +{ + if (sampleRate <= 0) return; + + const bool sampleRateChanged = m_sampleRate != sampleRate; + m_sampleRate = sampleRate; + + if (m_running && (sampleRateChanged || !m_vst3Effect || + m_settings.m_denoiserType != DenoiserSettings::DenoiserType::DenoiserType_Vst3)) + { + m_worker->applySampleRate(m_sampleRate); + configureVst3(); + if (sampleRateChanged && m_state == StError && + m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Nvidia) + { + m_state = StRunning; + } + } + + if (m_dataPipe) + { + DataFifo *fifo = qobject_cast(m_dataPipe->m_element); + if (fifo) fifo->setSize(2 * m_sampleRate); + } + + if (getMessageQueueToGUI()) { + getMessageQueueToGUI()->push(MsgReportSampleRate::create(m_sampleRate)); + } + if (sampleRateChanged) reportDemodSampleRate(); +} + +void Denoiser::reportDemodSampleRate() +{ + QList pipes; + MainCore::instance()->getMessagePipes().getMessagePipes(this, "reportdemod", pipes); + + for (const auto& pipe : pipes) + { + MessageQueue *queue = qobject_cast(pipe->m_element); + if (queue) { + queue->push(MainCore::MsgFeatureDemodReport::create(this, m_sampleRate)); + } + } } void Denoiser::channelsOrFeaturesChanged(const QStringList& renameFrom, const QStringList& renameTo) { - m_availableChannels = m_availableChannelOrFeatureHandler.getAvailableChannelOrFeatureList(); + m_availableChannels.clear(); + for (const auto& source : m_availableChannelOrFeatureHandler.getAvailableChannelOrFeatureList()) { + if (source.m_object != this) { + m_availableChannels.append(source); + } + } + + for (int i = 0; i < renameFrom.size() && i < renameTo.size(); ++i) + { + if (m_settings.m_selectedSource == renameFrom.at(i)) { + m_settings.m_selectedSource = renameTo.at(i); + } + } + + if (!m_settings.m_selectedSource.isEmpty()) { + restoreSelectedSource(); + } notifyUpdate(renameFrom, renameTo); } -void Denoiser::notifyUpdate(const QStringList& renameFrom, const QStringList& renameTo) +void Denoiser::notifyUpdate(const QStringList& renameFrom, const QStringList& renameTo, bool autoSelect) { if (getMessageQueueToGUI()) { - MsgReportChannels *msg = MsgReportChannels::create(renameFrom, renameTo); + MsgReportChannels *msg = MsgReportChannels::create(renameFrom, renameTo, m_selectedChannel, autoSelect); msg->getAvailableChannels() = m_availableChannels; getMessageQueueToGUI()->push(msg); } @@ -332,18 +562,86 @@ void Denoiser::getAvailableChannelsReport() } -void Denoiser::setChannel(ChannelAPI *selectedChannel) +void Denoiser::querySelectedSource() { - if ((selectedChannel == m_selectedChannel) || (m_availableChannels.indexOfObject(selectedChannel) == -1)) { + if (auto *channel = qobject_cast(m_selectedChannel)) { + channel->getInputMessageQueue()->push(MainCore::MsgChannelDemodQuery::create()); + } else if (auto *feature = qobject_cast(m_selectedChannel)) { + feature->getInputMessageQueue()->push(MainCore::MsgChannelDemodQuery::create()); + } +} + +void Denoiser::restoreSelectedSource() +{ + if (m_settings.m_selectedSource.isEmpty()) + { + setChannel(nullptr); return; } + const int index = m_availableChannels.indexOfLongId(m_settings.m_selectedSource); + if (index < 0) + { + setChannel(nullptr, true); + return; + } + + QObject *source = m_availableChannels.at(index).m_object; + if (source != m_selectedChannel) + { + setChannel(source); + if (source == m_selectedChannel) + { + querySelectedSource(); + } + else + { + const int currentIndex = m_availableChannels.indexOfObject(m_selectedChannel); + m_settings.m_selectedSource = currentIndex >= 0 ? m_availableChannels.at(currentIndex).getLongId() : QString(); + } + } +} + +void Denoiser::setChannel(QObject *selectedChannel, bool preserveSavedSource) +{ + if (selectedChannel == m_selectedChannel) { + return; + } + + const int selectedIndex = selectedChannel ? m_availableChannels.indexOfObject(selectedChannel) : -1; + if (selectedChannel && selectedIndex < 0) { + return; + } + + QObject *upstream = selectedChannel; + while (auto *denoiser = qobject_cast(upstream)) + { + if (denoiser == this) + { + qWarning() << "Denoiser: rejecting a cyclic denoiser connection"; + notifyUpdate(QStringList{}, QStringList{}, false); + return; + } + upstream = denoiser->m_selectedChannel; + } + + m_sampleRate = 0; + if (m_running) + { + m_worker->setVst3Effect(nullptr); + m_vst3Effect.reset(); + m_worker->applySampleRate(0); + } + if (getMessageQueueToGUI()) { + getMessageQueueToGUI()->push(MsgReportSampleRate::create(0)); + } + MainCore *mainCore = MainCore::instance(); if (m_selectedChannel) { ObjectPipe *pipe = mainCore->getDataPipes().unregisterProducerToConsumer(m_selectedChannel, this, "demod"); - DataFifo *fifo = qobject_cast(pipe->m_element); + DataFifo *fifo = pipe ? qobject_cast(pipe->m_element) : nullptr; if ((fifo) && m_running) { @@ -363,6 +661,17 @@ void Denoiser::setChannel(ChannelAPI *selectedChannel) } } + m_dataPipe = nullptr; + m_selectedChannel = nullptr; + + if (!selectedChannel) + { + if (!preserveSavedSource) { + m_settings.m_selectedSource.clear(); + } + return; + } + m_dataPipe = mainCore->getDataPipes().registerProducerToConsumer(selectedChannel, this, "demod"); connect(m_dataPipe, SIGNAL(toBeDeleted(int, QObject*)), this, SLOT(handleDataPipeToBeDeleted(int, QObject*))); DataFifo *fifo = qobject_cast(m_dataPipe->m_element); @@ -397,6 +706,13 @@ void Denoiser::setChannel(ChannelAPI *selectedChannel) } m_selectedChannel = selectedChannel; + m_settings.m_selectedSource = m_availableChannels.at(selectedIndex).getLongId(); + useDefaultSampleRate(); + if (m_running) + { + m_worker->applySampleRate(m_sampleRate); + configureVst3(); + } } int Denoiser::webapiRun(bool run, @@ -452,6 +768,12 @@ void Denoiser::webapiFormatFeatureSettings( { response.getDenoiserSettings()->setDenoiserType(static_cast(settings.m_denoiserType)); response.getDenoiserSettings()->setEnableDenoiser(settings.m_enableDenoiser ? 1 : 0); + response.getDenoiserSettings()->setNvidiaIntensity(settings.m_nvidiaIntensity); + response.getDenoiserSettings()->setNvidiaVad(settings.m_nvidiaVad ? 1 : 0); + *response.getDenoiserSettings()->getVst3ModulePath() = settings.m_vst3ModulePath; + *response.getDenoiserSettings()->getVst3ClassId() = QString::fromLatin1(settings.m_vst3ClassId.toHex()); + *response.getDenoiserSettings()->getVst3Parameters() = vst3ParametersJson(settings.m_vst3Parameters); + *response.getDenoiserSettings()->getVst3State() = QString::fromLatin1(settings.m_vst3State.toBase64()); response.getDenoiserSettings()->setAudioMute(settings.m_audioMute ? 1 : 0); response.getDenoiserSettings()->setVolumeTenths(settings.m_volumeTenths); if (response.getDenoiserSettings()->getAudioDeviceName()) { @@ -506,12 +828,34 @@ void Denoiser::webapiUpdateFeatureSettings( const QStringList& featureSettingsKeys, SWGSDRangel::SWGFeatureSettings& response) { - if (featureSettingsKeys.contains("denoiserType")) { - settings.m_denoiserType = static_cast(response.getDenoiserSettings()->getDenoiserType()); + if (featureSettingsKeys.contains("denoiserType")) + { + const int type = response.getDenoiserSettings()->getDenoiserType(); + if (type >= 0 && type <= 3) { + settings.m_denoiserType = static_cast(type); + } } if (featureSettingsKeys.contains("enableDenoiser")) { settings.m_enableDenoiser = response.getDenoiserSettings()->getEnableDenoiser() != 0; } + if (featureSettingsKeys.contains("nvidiaIntensity")) { + settings.m_nvidiaIntensity = qBound(0, response.getDenoiserSettings()->getNvidiaIntensity(), 100); + } + if (featureSettingsKeys.contains("nvidiaVad")) { + settings.m_nvidiaVad = response.getDenoiserSettings()->getNvidiaVad() != 0; + } + if (featureSettingsKeys.contains("vst3ModulePath") && response.getDenoiserSettings()->getVst3ModulePath()) { + settings.m_vst3ModulePath = *response.getDenoiserSettings()->getVst3ModulePath(); + } + if (featureSettingsKeys.contains("vst3ClassId") && response.getDenoiserSettings()->getVst3ClassId()) { + settings.m_vst3ClassId = QByteArray::fromHex(response.getDenoiserSettings()->getVst3ClassId()->toLatin1()); + } + if (featureSettingsKeys.contains("vst3Parameters") && response.getDenoiserSettings()->getVst3Parameters()) { + settings.m_vst3Parameters = parseVst3Parameters(*response.getDenoiserSettings()->getVst3Parameters()); + } + if (featureSettingsKeys.contains("vst3State") && response.getDenoiserSettings()->getVst3State()) { + settings.m_vst3State = QByteArray::fromBase64(response.getDenoiserSettings()->getVst3State()->toLatin1()); + } if (featureSettingsKeys.contains("audioMute")) { settings.m_audioMute = response.getDenoiserSettings()->getAudioMute() != 0; } @@ -585,6 +929,24 @@ void Denoiser::webapiReverseSendSettings(const QList& featureSettingsKe if (featureSettingsKeys.contains("enableDenoiser") || force) { swgDenoiserSettings->setEnableDenoiser(settings.m_enableDenoiser ? 1 : 0); } + if (featureSettingsKeys.contains("nvidiaIntensity") || force) { + swgDenoiserSettings->setNvidiaIntensity(settings.m_nvidiaIntensity); + } + if (featureSettingsKeys.contains("nvidiaVad") || force) { + swgDenoiserSettings->setNvidiaVad(settings.m_nvidiaVad ? 1 : 0); + } + if (featureSettingsKeys.contains("vst3ModulePath") || force) { + swgDenoiserSettings->setVst3ModulePath(new QString(settings.m_vst3ModulePath)); + } + if (featureSettingsKeys.contains("vst3ClassId") || force) { + swgDenoiserSettings->setVst3ClassId(new QString(QString::fromLatin1(settings.m_vst3ClassId.toHex()))); + } + if (featureSettingsKeys.contains("vst3Parameters") || force) { + swgDenoiserSettings->setVst3Parameters(new QString(vst3ParametersJson(settings.m_vst3Parameters))); + } + if (featureSettingsKeys.contains("vst3State") || force) { + swgDenoiserSettings->setVst3State(new QString(QString::fromLatin1(settings.m_vst3State.toBase64()))); + } if (featureSettingsKeys.contains("audioMute") || force) { swgDenoiserSettings->setAudioMute(settings.m_audioMute ? 1 : 0); } @@ -680,6 +1042,17 @@ void Denoiser::handleDataPipeToBeDeleted(int reason, QObject *object) } m_selectedChannel = nullptr; + m_dataPipe = nullptr; + m_sampleRate = 0; + if (m_running) + { + m_worker->setVst3Effect(nullptr); + m_vst3Effect.reset(); + m_worker->applySampleRate(0); + } + if (getMessageQueueToGUI()) { + getMessageQueueToGUI()->push(MsgReportSampleRate::create(0)); + } } } diff --git a/plugins/feature/denoiser/denoiser.h b/plugins/feature/denoiser/denoiser.h index 63153233d..7c9f2de47 100644 --- a/plugins/feature/denoiser/denoiser.h +++ b/plugins/feature/denoiser/denoiser.h @@ -21,15 +21,18 @@ #include #include #include +#include #include "feature/feature.h" #include "util/message.h" #include "availablechannelorfeaturehandler.h" #include "denoisersettings.h" +#include "vst3effect.h" class WebAPIAdapterInterface; class DenoiserWorker; +class Vst3Effect; class QNetworkAccessManager; class QNetworkReply; class QThread; @@ -94,20 +97,28 @@ public: AvailableChannelOrFeatureList& getAvailableChannels() { return m_availableChannels; } const QStringList& getRenameFrom() const { return m_renameFrom; } const QStringList& getRenameTo() const { return m_renameTo; } + QObject *getSelectedChannel() const { return m_selectedChannel; } + bool getAutoSelect() const { return m_autoSelect; } - static MsgReportChannels* create(const QStringList& renameFrom, const QStringList& renameTo) { - return new MsgReportChannels(renameFrom, renameTo); + static MsgReportChannels* create(const QStringList& renameFrom, const QStringList& renameTo, + QObject *selectedChannel, bool autoSelect) { + return new MsgReportChannels(renameFrom, renameTo, selectedChannel, autoSelect); } private: AvailableChannelOrFeatureList m_availableChannels; QStringList m_renameFrom; QStringList m_renameTo; + QObject *m_selectedChannel; + bool m_autoSelect; - MsgReportChannels(const QStringList& renameFrom, const QStringList& renameTo) : + MsgReportChannels(const QStringList& renameFrom, const QStringList& renameTo, + QObject *selectedChannel, bool autoSelect) : Message(), m_renameFrom(renameFrom), - m_renameTo(renameTo) + m_renameTo(renameTo), + m_selectedChannel(selectedChannel), + m_autoSelect(autoSelect) {} }; @@ -115,15 +126,15 @@ public: MESSAGE_CLASS_DECLARATION public: - ChannelAPI *getChannel() { return m_channel; } - static MsgSelectChannel* create(ChannelAPI *channel) { + QObject *getChannel() { return m_channel; } + static MsgSelectChannel* create(QObject *channel) { return new MsgSelectChannel(channel); } protected: - ChannelAPI *m_channel; + QObject *m_channel; - MsgSelectChannel(ChannelAPI *channel) : + MsgSelectChannel(QObject *channel) : Message(), m_channel(channel) { } @@ -191,6 +202,9 @@ public: void getAvailableChannelsReport(); void setLevelMeter(QObject *levelMeter) { m_levelMeter = levelMeter; } + QVector vst3Parameters() const; + bool hasVst3Effect() const; + QString vst3ParameterText(quint32 id, double value) const; static const char* const m_featureIdURI; static const char* const m_featureId; @@ -201,9 +215,10 @@ private: bool m_running; DenoiserWorker *m_worker; DenoiserSettings m_settings; + std::unique_ptr m_vst3Effect; AvailableChannelOrFeatureList m_availableChannels; AvailableChannelOrFeatureHandler m_availableChannelOrFeatureHandler; - ChannelAPI *m_selectedChannel; + QObject *m_selectedChannel; ObjectPipe *m_dataPipe; int m_sampleRate; QObject *m_levelMeter = nullptr; @@ -214,8 +229,14 @@ private: void start(); void stop(); void applySettings(const DenoiserSettings& settings, const QList& settingsKeys, bool force = false); - void notifyUpdate(const QStringList& renameFrom, const QStringList& renameTo); - void setChannel(ChannelAPI *selectedChannel); + void configureVst3(); + void useDefaultSampleRate(); + void applyReportedSampleRate(int sampleRate); + void reportDemodSampleRate(); + void notifyUpdate(const QStringList& renameFrom, const QStringList& renameTo, bool autoSelect = true); + void querySelectedSource(); + void restoreSelectedSource(); + void setChannel(QObject *selectedChannel, bool preserveSavedSource = false); void webapiReverseSendSettings(const QList& featureSettingsKeys, const DenoiserSettings& settings, bool force); private slots: diff --git a/plugins/feature/denoiser/denoisergui.cpp b/plugins/feature/denoiser/denoisergui.cpp index 505bb5783..a0b65894f 100644 --- a/plugins/feature/denoiser/denoisergui.cpp +++ b/plugins/feature/denoiser/denoisergui.cpp @@ -17,6 +17,22 @@ #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include #include "feature/featureuiset.h" #include "gui/basicfeaturesettingsdialog.h" @@ -47,6 +63,7 @@ void DenoiserGUI::resetToDefaults() { m_settings.resetToDefaults(); displaySettings(); + updateChannelList(true); applySettings(true); } @@ -61,6 +78,7 @@ bool DenoiserGUI::deserialize(const QByteArray& data) { m_feature->setWorkspaceIndex(m_settings.m_workspaceIndex); displaySettings(); + updateChannelList(true); applySettings(true); return true; } @@ -84,9 +102,18 @@ bool DenoiserGUI::handleMessage(const Message& message) m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings()); } + const auto requestedType = m_settings.m_denoiserType; blockApplySettings(true); displaySettings(); blockApplySettings(false); + if (cfg.getForce() || cfg.getSettingsKeys().contains("selectedSource")) { + updateChannelList(true); + } + if (m_settings.m_denoiserType != requestedType) + { + m_settingsKeys.append("denoiserType"); + applySettings(); + } return true; } @@ -95,7 +122,14 @@ bool DenoiserGUI::handleMessage(const Message& message) qDebug("DenoiserGUI::handleMessage: Denoiser::MsgReportChannels"); Denoiser::MsgReportChannels& report = (Denoiser::MsgReportChannels&) message; m_availableChannels = report.getAvailableChannels(); - updateChannelList(); + m_selectedChannel = report.getSelectedChannel(); + for (int i = 0; i < report.getRenameFrom().size() && i < report.getRenameTo().size(); ++i) + { + if (m_settings.m_selectedSource == report.getRenameFrom().at(i)) { + m_settings.m_selectedSource = report.getRenameTo().at(i); + } + } + updateChannelList(report.getAutoSelect()); return true; } @@ -142,7 +176,7 @@ DenoiserGUI::DenoiserGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Featu ui(new Ui::DenoiserGUI), m_pluginAPI(pluginAPI), m_featureUISet(featureUISet), - m_sampleRate(48000), + m_sampleRate(0), m_doApplySettings(true), m_selectedChannel(nullptr) { @@ -151,6 +185,14 @@ DenoiserGUI::DenoiserGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Featu m_helpURL = "plugins/feature/denoiser/readme.md"; RollupContents *rollupContents = getRollupContents(); ui->setupUi(rollupContents); + using DenoiserType = DenoiserSettings::DenoiserType; + ui->denoiserType->setItemData(0, static_cast(DenoiserType::DenoiserType_None)); + ui->denoiserType->setItemData(1, static_cast(DenoiserType::DenoiserType_RNnoise)); + ui->denoiserType->setItemData(2, static_cast(DenoiserType::DenoiserType_Nvidia)); + ui->denoiserType->setItemData(3, static_cast(DenoiserType::DenoiserType_Vst3)); +#if !defined(Q_OS_WIN) && !defined(Q_OS_LINUX) + ui->denoiserType->removeItem(static_cast(DenoiserSettings::DenoiserType::DenoiserType_Nvidia)); +#endif rollupContents->arrangeRollups(); connect(rollupContents, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); @@ -183,6 +225,14 @@ DenoiserGUI::DenoiserGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Featu DenoiserGUI::~DenoiserGUI() { + if (m_vst3ScanProcess) + { + QProcess *process = m_vst3ScanProcess; + m_vst3ScanProcess = nullptr; + QObject::disconnect(process, nullptr, this, nullptr); + process->kill(); + process->waitForFinished(1000); + } delete ui; } @@ -206,7 +256,18 @@ void DenoiserGUI::displaySettings() ui->record->setChecked(m_settings.m_recordToFile); ui->fileNameText->setText(m_settings.m_fileRecordName); ui->showFileDialog->setEnabled(!m_settings.m_recordToFile); - ui->denoiserType->setCurrentIndex(static_cast(m_settings.m_denoiserType)); + int typeIndex = ui->denoiserType->findData(static_cast(m_settings.m_denoiserType)); + if (typeIndex < 0) + { + m_settings.m_denoiserType = DenoiserSettings::DenoiserType::DenoiserType_RNnoise; + typeIndex = ui->denoiserType->findData(static_cast(m_settings.m_denoiserType)); + } + ui->denoiserType->setCurrentIndex(typeIndex); + updateControls(); + displayVst3Selection(); + ui->nvidiaIntensity->setValue(m_settings.m_nvidiaIntensity); + ui->nvidiaIntensityText->setText(QStringLiteral("%1%").arg(m_settings.m_nvidiaIntensity)); + ui->nvidiaVad->setChecked(m_settings.m_nvidiaVad); ui->enable->setChecked(m_settings.m_enableDenoiser); ui->audioMute->setChecked(m_settings.m_audioMute); ui->volume->setValue(m_settings.m_volumeTenths); @@ -218,36 +279,56 @@ void DenoiserGUI::displaySettings() void DenoiserGUI::displaySampleRate(int sampleRate) { + if (sampleRate <= 0) + { + ui->sinkSampleRateText->setText(tr("-- kS/s")); + ui->sinkSampleRateText->setToolTip(tr("Waiting for the selected channel's sample rate")); + return; + } QString s = QString::number(sampleRate/1000.0, 'f', 1); ui->sinkSampleRateText->setText(tr("%1 kS/s").arg(s)); + ui->sinkSampleRateText->setToolTip(QString()); } -void DenoiserGUI::updateChannelList() +void DenoiserGUI::updateChannelList(bool autoSelect) { - ui->channels->blockSignals(true); - ui->channels->clear(); - - AvailableChannelOrFeatureList::const_iterator it = m_availableChannels.begin(); - int selectedItem = -1; - - for (int i = 0; it != m_availableChannels.end(); ++it, i++) { - ui->channels->addItem(it->getLongId()); + const QSignalBlocker blocker(ui->channels); + ui->channels->clear(); - if (it->m_object == m_selectedChannel) { - selectedItem = i; + for (const auto& source : m_availableChannels) { + ui->channels->addItem(source.getLongId()); } - } - ui->channels->blockSignals(false); - - if (m_availableChannels.size() > 0) - { - if (selectedItem >= 0) { - ui->channels->setCurrentIndex(selectedItem); - } else { - ui->channels->setCurrentIndex(0); + int selectedItem = -1; + if (autoSelect) + { + if (!m_settings.m_selectedSource.isEmpty()) + { + selectedItem = m_availableChannels.indexOfLongId(m_settings.m_selectedSource); + } + else + { + selectedItem = m_availableChannels.indexOfObject(m_selectedChannel); + if (selectedItem < 0 && !m_availableChannels.isEmpty()) { + selectedItem = 0; + } + } } + else + { + selectedItem = m_availableChannels.indexOfObject(m_selectedChannel); + if (selectedItem < 0) { + m_settings.m_selectedSource.clear(); + } + } + ui->channels->setCurrentIndex(selectedItem); + } + + // Adding the first item selects it while signals are blocked. Send the + // selection explicitly so the feature registers its data and rate pipes. + if (ui->channels->currentIndex() >= 0) { + on_channels_currentIndexChanged(ui->channels->currentIndex()); } } @@ -296,6 +377,9 @@ void DenoiserGUI::on_startStop_toggled(bool checked) { if (m_doApplySettings) { + if (checked && !m_vst3ScanAttempted) { + scanVst3Plugins({}, true); + } Denoiser::MsgStartStop *message = Denoiser::MsgStartStop::create(checked); m_denoiser->getInputMessageQueue()->push(message); @@ -309,7 +393,8 @@ void DenoiserGUI::on_channels_currentIndexChanged(int index) { if ((index >= 0) && (index < m_availableChannels.size())) { - m_selectedChannel = qobject_cast(m_availableChannels[index].m_object); + m_selectedChannel = m_availableChannels[index].m_object; + m_settings.m_selectedSource = m_availableChannels[index].getLongId(); Denoiser::MsgSelectChannel *msg = Denoiser::MsgSelectChannel::create(m_selectedChannel); m_denoiser->getInputMessageQueue()->push(msg); } @@ -360,11 +445,381 @@ void DenoiserGUI::on_showFileDialog_clicked(bool checked) void DenoiserGUI::on_denoiserType_currentIndexChanged(int index) { - m_settings.m_denoiserType = static_cast(index); + if (index < 0) { + return; + } + m_settings.m_denoiserType = static_cast(ui->denoiserType->itemData(index).toInt()); + if (m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Vst3 && !m_vst3ScanAttempted) { + scanVst3Plugins({}, true); + } + updateControls(); m_settingsKeys.append("denoiserType"); applySettings(); } +void DenoiserGUI::updateControls() +{ + RollupContents *rollups = getRollupContents(); + const int previousContentHeight = rollups->arrangeRollups(); + const bool showNvidia = m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Nvidia; + ui->nvidiaIntensityLabel->setVisible(showNvidia); + ui->nvidiaIntensity->setVisible(showNvidia); + ui->nvidiaIntensityText->setVisible(showNvidia); + ui->nvidiaVad->setVisible(showNvidia); + + const bool showVst3 = m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Vst3; + ui->vst3Plugin->setVisible(showVst3); + ui->vst3Refresh->setVisible(showVst3); + ui->vst3Browse->setVisible(showVst3); + ui->vst3Parameters->setVisible(showVst3); + ui->settingsContainer->layout()->invalidate(); + ui->settingsContainer->layout()->activate(); + const int contentHeight = rollups->arrangeRollups(); + layout()->activate(); + sizeToContents(); + + if (isVisible() && !isMaximized()) { + resize(qMax(width(), minimumWidth()), qMax(height() + contentHeight - previousContentHeight, minimumHeight())); + } +} + +void DenoiserGUI::displayVst3Selection() +{ + const QSignalBlocker blocker(ui->vst3Plugin); + ui->vst3Plugin->clear(); + int selected = -1; + for (const Vst3PluginInfo& plugin : m_vst3Plugins) + { + const int index = ui->vst3Plugin->count(); + ui->vst3Plugin->addItem(plugin.name); + ui->vst3Plugin->setItemData(index, plugin.modulePath, Qt::ToolTipRole); + if (plugin.modulePath == m_settings.m_vst3ModulePath && plugin.classId == m_settings.m_vst3ClassId) { + selected = index; + } + } + if (selected < 0 && !m_settings.m_vst3ModulePath.isEmpty()) + { + selected = ui->vst3Plugin->count(); + ui->vst3Plugin->addItem(QFileInfo(m_settings.m_vst3ModulePath).fileName() + tr(" (saved)")); + ui->vst3Plugin->setItemData(selected, m_settings.m_vst3ModulePath, Qt::ToolTipRole); + } + if (selected >= 0) { + ui->vst3Plugin->setCurrentIndex(selected); + } else { + ui->vst3Plugin->setCurrentIndex(-1); + } +} + +void DenoiserGUI::scanVst3Plugins(const QStringList& paths, bool automatic) +{ + if (m_vst3ScanProcess) { + return; + } + if (paths.isEmpty()) { + m_vst3ScanAttempted = true; + } + auto *process = new QProcess(this); + m_vst3ScanProcess = process; + ui->vst3Refresh->setText(tr("Scanning...")); + ui->vst3Refresh->setToolTip(QString()); + ui->vst3Refresh->setEnabled(false); + ui->vst3Browse->setEnabled(false); + const QString scanner = QDir(QCoreApplication::applicationDirPath()).filePath( +#ifdef Q_OS_WIN + QStringLiteral("sdrangel-vst3-scan.exe") +#else + QStringLiteral("sdrangel-vst3-scan") +#endif + ); + process->setProgram(scanner); + process->setArguments(paths); + connect(process, qOverload(&QProcess::finished), this, + [this, process, automatic](int exitCode, QProcess::ExitStatus status) { + if (m_vst3ScanProcess != process) return; + const QJsonDocument document = QJsonDocument::fromJson(process->readAllStandardOutput()); + if (status != QProcess::NormalExit || exitCode != 0 || !document.isArray()) + { + const QString error = tr("The VST3 scanner failed. A plugin may have crashed during discovery."); + if (automatic) { + ui->vst3Refresh->setToolTip(error); + } else { + QMessageBox::warning(this, tr("VST3 scan"), error); + } + displayVst3Selection(); + } + else + { + for (const QJsonValue& value : document.array()) + { + const QJsonObject object = value.toObject(); + Vst3PluginInfo plugin; + plugin.modulePath = object.value(QStringLiteral("path")).toString(); + plugin.classId = QByteArray::fromHex(object.value(QStringLiteral("id")).toString().toLatin1()); + plugin.name = object.value(QStringLiteral("name")).toString(); + if (plugin.modulePath.isEmpty() || plugin.classId.size() != 16) continue; + bool duplicate = false; + for (const Vst3PluginInfo& known : m_vst3Plugins) + { + if (known.modulePath == plugin.modulePath && known.classId == plugin.classId) + { + duplicate = true; + break; + } + } + if (!duplicate) { + m_vst3Plugins.append(plugin); + } + } + displayVst3Selection(); + if (m_vst3Plugins.isEmpty()) + { + const QString message = tr("No VST3 audio effects were found."); + if (automatic) { + ui->vst3Refresh->setToolTip(message); + } else { + QMessageBox::information(this, tr("VST3 effects"), message); + } + } + } + ui->vst3Refresh->setText(tr("Scan")); + ui->vst3Refresh->setEnabled(true); + ui->vst3Browse->setEnabled(true); + m_vst3ScanProcess = nullptr; + process->deleteLater(); + }); + connect(process, &QProcess::errorOccurred, this, [this, process, automatic](QProcess::ProcessError error) { + if (error != QProcess::FailedToStart || m_vst3ScanProcess != process) { + return; + } + const QString message = tr("Could not launch the VST3 scanner: %1").arg(process->errorString()); + if (automatic) { + ui->vst3Refresh->setToolTip(message); + } else { + QMessageBox::warning(this, tr("VST3 scan"), message); + } + displayVst3Selection(); + ui->vst3Refresh->setText(tr("Scan")); + ui->vst3Refresh->setEnabled(true); + ui->vst3Browse->setEnabled(true); + m_vst3ScanProcess = nullptr; + process->deleteLater(); + }); + process->start(); + QPointer guarded(process); + QTimer::singleShot(300000, this, [guarded]() { + if (guarded && guarded->state() != QProcess::NotRunning) guarded->kill(); + }); +} + +void DenoiserGUI::on_vst3Plugin_currentIndexChanged(int index) +{ + if (index < 0 || index >= m_vst3Plugins.size()) { + return; + } + const Vst3PluginInfo& plugin = m_vst3Plugins[index]; + m_settings.m_vst3ModulePath = plugin.modulePath; + m_settings.m_vst3ClassId = plugin.classId; + m_settings.m_vst3Parameters.clear(); + m_settings.m_vst3State.clear(); + m_settingsKeys.append("vst3ModulePath"); + m_settingsKeys.append("vst3ClassId"); + m_settingsKeys.append("vst3Parameters"); + m_settingsKeys.append("vst3State"); + applySettings(); +} + +void DenoiserGUI::on_vst3Refresh_clicked() +{ + m_vst3Plugins.clear(); + scanVst3Plugins(); +} + +void DenoiserGUI::on_vst3Browse_clicked() +{ +#ifdef Q_OS_WIN + const QString path = QFileDialog::getOpenFileName(this, tr("Select VST3 effect"), QString(), tr("VST3 effects (*.vst3)")); +#else + const QString path = QFileDialog::getExistingDirectory(this, tr("Select VST3 bundle")); +#endif + if (!path.isEmpty()) { + scanVst3Plugins({path}); + } +} + +void DenoiserGUI::on_vst3Parameters_clicked() +{ + if (m_settings.m_vst3ModulePath.isEmpty() || m_settings.m_vst3ClassId.size() != 16) + { + QMessageBox::information(this, tr("VST3 parameters"), + tr("Select a VST3 effect from the list first.")); + return; + } + + // Keep the editor instance independent of the audio worker. Audio format or + // channel changes can then recreate the processing instance safely. + auto parameterEffect = std::make_unique(); + QString error; + if (!parameterEffect->open(m_settings.m_vst3ModulePath, m_settings.m_vst3ClassId, + m_sampleRate > 0 ? m_sampleRate : 48000, 2, error, m_settings.m_vst3State)) + { + QMessageBox::warning(this, tr("VST3 parameters"), + tr("Could not load the selected VST3 effect: %1").arg(error)); + return; + } + for (auto it = m_settings.m_vst3Parameters.cbegin(); it != m_settings.m_vst3Parameters.cend(); ++it) { + parameterEffect->setParameter(it.key(), it.value()); + } + parameterEffect->setParameterEditCallback([this](quint32 id, double value) { + if (m_settings.m_vst3Parameters.value(id, -1.0) == value) { + return; + } + m_settings.m_vst3Parameters.insert(id, value); + m_settingsKeys.append("vst3Parameters"); + applySettings(); + }); + + QDialog dialog(this); + dialog.setWindowTitle(tr("VST3 parameters")); + auto *outer = new QVBoxLayout(&dialog); + if (!m_denoiser->hasVst3Effect()) + { + auto *notice = new QLabel(tr("Live processing was unavailable when this dialog opened. Changes are saved and applied when the effect loads."), &dialog); + notice->setWordWrap(true); + outer->addWidget(notice); + } + QString editorError; + auto *nativeScroll = new QScrollArea(&dialog); + nativeScroll->setWidgetResizable(false); + if (QWidget *editor = parameterEffect->createEditorWidget(nativeScroll->viewport(), editorError)) + { + nativeScroll->setWidget(editor); + outer->addWidget(nativeScroll); + if (QScreen *screen = dialog.screen()) + { + const QRect available = screen->availableGeometry(); + dialog.resize(qMin(editor->width() + 36, available.width() - 80), + qMin(editor->height() + 64, available.height() - 80)); + } + else + { + dialog.adjustSize(); + } + dialog.exec(); + saveVst3State(*parameterEffect); + return; + } + delete nativeScroll; + + const QVector parameters = parameterEffect->parameters(); + bool hasEditableParameter = false; + for (const Vst3ParameterInfo& parameter : parameters) + { + if (!parameter.readOnly && !parameter.hidden) + { + hasEditableParameter = true; + break; + } + } + if (!hasEditableParameter) + { + QMessageBox::information(this, tr("VST3 parameters"), + tr("This VST3 effect has no available editor or editable parameters. %1").arg(editorError)); + return; + } + dialog.resize(440, 500); + auto *scroll = new QScrollArea(&dialog); + scroll->setWidgetResizable(true); + outer->addWidget(scroll); + auto *content = new QWidget(scroll); + auto *layout = new QVBoxLayout(content); + for (const Vst3ParameterInfo& parameter : parameters) + { + if (parameter.readOnly || parameter.hidden) { + continue; + } + auto *row = new QWidget(content); + auto *rowLayout = new QHBoxLayout(row); + auto *name = new QLabel(parameter.name, row); + name->setMinimumWidth(130); + auto *slider = new QSlider(Qt::Horizontal, row); + const int maximum = parameter.steps > 0 ? qMin(parameter.steps, 10000) : 1000; + slider->setRange(0, maximum); + const double value = m_settings.m_vst3Parameters.value(parameter.id, parameter.currentValue); + slider->setValue(qRound(value * maximum)); + auto *valueLabel = new QLabel(parameterEffect->parameterText(parameter.id, value), row); + valueLabel->setMinimumWidth(70); + valueLabel->setMaximumWidth(120); + rowLayout->addWidget(name); + rowLayout->addWidget(slider, 1); + rowLayout->addWidget(valueLabel); + layout->addWidget(row); + connect(slider, &QSlider::valueChanged, &dialog, [this, parameter, maximum, valueLabel, effect = parameterEffect.get()](int raw) { + const double normalized = static_cast(raw) / maximum; + effect->setParameter(parameter.id, normalized); + valueLabel->setText(effect->parameterText(parameter.id, normalized)); + m_settings.m_vst3Parameters.insert(parameter.id, normalized); + m_settingsKeys.append("vst3Parameters"); + applySettings(); + }); + } + layout->addStretch(); + scroll->setWidget(content); + dialog.exec(); + saveVst3State(*parameterEffect); +} + +void DenoiserGUI::saveVst3State(Vst3Effect& effect) +{ + QString error; + const QByteArray state = effect.state(error); + if (state.isEmpty()) + { + qWarning() << "DenoiserGUI::saveVst3State:" << error; + return; + } + + // Editor changes such as presets may bypass performEdit, so refresh the saved + // parameter values. Otherwise they would override the state when it is restored. + bool parametersChanged = false; + for (auto it = m_settings.m_vst3Parameters.begin(); it != m_settings.m_vst3Parameters.end(); ++it) + { + const double value = effect.parameterValue(it.key()); + if (value >= 0.0 && value != it.value()) + { + it.value() = value; + parametersChanged = true; + } + } + + if (state == m_settings.m_vst3State && !parametersChanged) { + return; + } + m_settings.m_vst3State = state; + m_settingsKeys.append("vst3State"); + if (parametersChanged) { + m_settingsKeys.append("vst3Parameters"); + } + applySettings(); +} + +void DenoiserGUI::on_nvidiaIntensity_valueChanged(int value) +{ + ui->nvidiaIntensityText->setText(QStringLiteral("%1%").arg(value)); + if (ui->nvidiaIntensity->isSliderDown() || m_settings.m_nvidiaIntensity == value) { + return; + } + m_settings.m_nvidiaIntensity = value; + m_settingsKeys.append("nvidiaIntensity"); + applySettings(); +} + +void DenoiserGUI::on_nvidiaVad_toggled(bool checked) +{ + m_settings.m_nvidiaVad = checked; + m_settingsKeys.append("nvidiaVad"); + applySettings(); +} + void DenoiserGUI::on_enable_toggled(bool checked) { m_settings.m_enableDenoiser = checked; @@ -415,6 +870,9 @@ void DenoiserGUI::tick() void DenoiserGUI::updateFeatureState() { updateStartStopButton(ui->startStop); + if (m_denoiser->getState() == Feature::StRunning && !m_vst3ScanAttempted) { + scanVst3Plugins({}, true); + } } void DenoiserGUI::displayNRenabled() @@ -445,6 +903,15 @@ void DenoiserGUI::makeUIConnections() QObject::connect(ui->record, &ButtonSwitch::toggled, this, &DenoiserGUI::on_record_toggled); QObject::connect(ui->showFileDialog, &QPushButton::clicked, this, &DenoiserGUI::on_showFileDialog_clicked); QObject::connect(ui->denoiserType, qOverload(&QComboBox::currentIndexChanged), this, &DenoiserGUI::on_denoiserType_currentIndexChanged); + QObject::connect(ui->nvidiaIntensity, &QSlider::valueChanged, this, &DenoiserGUI::on_nvidiaIntensity_valueChanged); + QObject::connect(ui->nvidiaIntensity, &QSlider::sliderReleased, this, [this]() { + on_nvidiaIntensity_valueChanged(ui->nvidiaIntensity->value()); + }); + QObject::connect(ui->nvidiaVad, &QCheckBox::toggled, this, &DenoiserGUI::on_nvidiaVad_toggled); + QObject::connect(ui->vst3Plugin, qOverload(&QComboBox::currentIndexChanged), this, &DenoiserGUI::on_vst3Plugin_currentIndexChanged); + QObject::connect(ui->vst3Refresh, &QPushButton::clicked, this, &DenoiserGUI::on_vst3Refresh_clicked); + QObject::connect(ui->vst3Browse, &QPushButton::clicked, this, &DenoiserGUI::on_vst3Browse_clicked); + QObject::connect(ui->vst3Parameters, &QPushButton::clicked, this, &DenoiserGUI::on_vst3Parameters_clicked); QObject::connect(ui->enable, &ButtonSwitch::toggled, this, &DenoiserGUI::on_enable_toggled); QObject::connect(ui->audioMute, &ButtonSwitch::toggled, this, &DenoiserGUI::on_audioMute_toggled); QObject::connect(ui->volume, &QDial::valueChanged, this, &DenoiserGUI::on_volume_valueChanged); diff --git a/plugins/feature/denoiser/denoisergui.h b/plugins/feature/denoiser/denoisergui.h index 7e3fa589e..c76eec283 100644 --- a/plugins/feature/denoiser/denoisergui.h +++ b/plugins/feature/denoiser/denoisergui.h @@ -27,11 +27,13 @@ #include "settings/rollupstate.h" #include "denoisersettings.h" +#include "vst3effect.h" class PluginAPI; class FeatureUISet; class Denoiser; class Feature; +class QProcess; namespace Ui { class DenoiserGUI; @@ -65,8 +67,11 @@ private: Denoiser* m_denoiser; MessageQueue m_inputMessageQueue; AvailableChannelOrFeatureList m_availableChannels; - ChannelAPI *m_selectedChannel; + QObject *m_selectedChannel; MovingAverageUtil m_channelPowerAvg; + QVector m_vst3Plugins; + QProcess *m_vst3ScanProcess = nullptr; + bool m_vst3ScanAttempted = false; explicit DenoiserGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature, QWidget* parent = nullptr); virtual ~DenoiserGUI(); @@ -76,7 +81,11 @@ private: void displaySettings(); void displaySampleRate(int sampleRate); void displayNRenabled(); - void updateChannelList(); + void updateControls(); + void displayVst3Selection(); + void saveVst3State(Vst3Effect& effect); + void scanVst3Plugins(const QStringList& paths = {}, bool automatic = false); + void updateChannelList(bool autoSelect); bool handleMessage(const Message& message); void makeUIConnections(); @@ -90,6 +99,12 @@ private slots: void on_record_toggled(bool checked); void on_showFileDialog_clicked(bool checked); void on_denoiserType_currentIndexChanged(int index); + void on_nvidiaIntensity_valueChanged(int value); + void on_nvidiaVad_toggled(bool checked); + void on_vst3Plugin_currentIndexChanged(int index); + void on_vst3Refresh_clicked(); + void on_vst3Browse_clicked(); + void on_vst3Parameters_clicked(); void on_enable_toggled(bool checked); void on_audioMute_toggled(bool checked); void on_volume_valueChanged(int value); diff --git a/plugins/feature/denoiser/denoisergui.ui b/plugins/feature/denoiser/denoisergui.ui index b9e716f9b..ffe4eb921 100644 --- a/plugins/feature/denoiser/denoisergui.ui +++ b/plugins/feature/denoiser/denoisergui.ui @@ -93,8 +93,11 @@ + + Audio source channel or feature + - Chan + Source @@ -137,14 +140,14 @@ 00000.0 kS/s - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter - Qt::Horizontal + Qt::Orientation::Horizontal @@ -166,13 +169,13 @@ Channel power - Qt::LeftToRight + Qt::LayoutDirection::LeftToRight -100.0 dB - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter @@ -201,6 +204,16 @@ RNnoise + + + NVIDIA Noise Removal + + + + + VST3 Effect + + @@ -227,7 +240,7 @@ - Qt::Horizontal + Qt::Orientation::Horizontal @@ -257,10 +270,125 @@ + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Strength + + + + + + + Noise removal strength: lower values preserve more weak speech + + + 100 + + + 100 + + + Qt::Orientation::Horizontal + + + + + + + 100% + + + + + + + Voice activity detection: may suppress weak or misclassified speech + + + VAD + + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 0 + 0 + + + + Selected VST3 audio effect + + + + + + + Scan installed VST3 effects + + + Scan + + + + + + + Select a VST3 module outside standard plugin folders + + + ... + + + + + + + Edit the effect's parameters + + + Params + + + + + - Qt::Horizontal + Qt::Orientation::Horizontal @@ -310,7 +438,7 @@ 1.0 - Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + Qt::AlignmentFlag::AlignRight|Qt::AlignmentFlag::AlignTrailing|Qt::AlignmentFlag::AlignVCenter @@ -338,7 +466,7 @@ - Qt::Horizontal + Qt::Orientation::Horizontal @@ -402,7 +530,7 @@ ... - Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter + Qt::AlignmentFlag::AlignLeading|Qt::AlignmentFlag::AlignLeft|Qt::AlignmentFlag::AlignVCenter @@ -412,17 +540,17 @@ - - ButtonSwitch - QToolButton -
gui/buttonswitch.h
-
RollupContents QWidget
gui/rollupcontents.h
1
+ + ButtonSwitch + QToolButton +
gui/buttonswitch.h
+
LevelMeterVU QWidget diff --git a/plugins/feature/denoiser/denoisersettings.cpp b/plugins/feature/denoiser/denoisersettings.cpp index e695554f6..bee017736 100644 --- a/plugins/feature/denoiser/denoisersettings.cpp +++ b/plugins/feature/denoiser/denoisersettings.cpp @@ -20,6 +20,9 @@ #include "audio/audiodevicemanager.h" #include "denoisersettings.h" +#include +#include +#include const QStringList DenoiserSettings::m_channelURIs = { QStringLiteral("sdrangel.channel.amdemod"), @@ -31,6 +34,7 @@ const QStringList DenoiserSettings::m_channelURIs = { QStringLiteral("sdrangel.channel.ssbdemod"), QStringLiteral("sdrangel.channel.wfmdemod"), QStringLiteral("sdrangel.channel.wdsprx"), + QStringLiteral("sdrangel.feature.denoiser"), }; DenoiserSettings::DenoiserSettings() : @@ -42,10 +46,17 @@ DenoiserSettings::DenoiserSettings() : void DenoiserSettings::resetToDefaults() { m_denoiserType = DenoiserType::DenoiserType_RNnoise; + m_selectedSource.clear(); m_title = "Denoiser"; m_enableDenoiser = true; m_audioMute = false; m_volumeTenths = 10; + m_nvidiaIntensity = 100; + m_nvidiaVad = false; + m_vst3ModulePath.clear(); + m_vst3ClassId.clear(); + m_vst3Parameters.clear(); + m_vst3State.clear(); m_audioDeviceName = AudioDeviceManager::m_defaultDeviceName; m_rgbColor = 0xffd700; // gold m_useReverseAPI = false; @@ -84,6 +95,17 @@ QByteArray DenoiserSettings::serialize() const s.writeString(15, m_audioDeviceName); s.writeBool(16, m_enableDenoiser); s.writeS32(17, m_volumeTenths); + s.writeS32(18, m_nvidiaIntensity); + s.writeBool(19, m_nvidiaVad); + s.writeString(20, m_vst3ModulePath); + s.writeBlob(21, m_vst3ClassId); + QJsonObject parameters; + for (auto it = m_vst3Parameters.cbegin(); it != m_vst3Parameters.cend(); ++it) { + parameters.insert(QString::number(it.key()), it.value()); + } + s.writeBlob(22, QJsonDocument(parameters).toJson(QJsonDocument::Compact)); + s.writeString(23, m_selectedSource); + s.writeBlob(24, m_vst3State); return s.final(); } @@ -105,7 +127,7 @@ bool DenoiserSettings::deserialize(const QByteArray& data) uint32_t utmp; d.readS32(1, &itmp, 1); - m_denoiserType = static_cast(itmp); + m_denoiserType = static_cast(itmp >= 0 && itmp <= 3 ? itmp : 1); d.readString(2, &m_title, "Denoiser"); d.readU32(3, &m_rgbColor, 0xffd700); // gold d.readBool(4, &m_useReverseAPI, false); @@ -137,6 +159,26 @@ bool DenoiserSettings::deserialize(const QByteArray& data) d.readString(15, &m_audioDeviceName, AudioDeviceManager::m_defaultDeviceName); d.readBool(16, &m_enableDenoiser, true); d.readS32(17, &m_volumeTenths, 10); + d.readS32(18, &m_nvidiaIntensity, 100); + m_nvidiaIntensity = qBound(0, m_nvidiaIntensity, 100); + d.readBool(19, &m_nvidiaVad, false); + d.readString(20, &m_vst3ModulePath, ""); + d.readBlob(21, &m_vst3ClassId); + bytetmp.clear(); + d.readBlob(22, &bytetmp); + m_vst3Parameters.clear(); + const QJsonObject parameters = QJsonDocument::fromJson(bytetmp).object(); + for (auto it = parameters.begin(); it != parameters.end(); ++it) + { + bool validId = false; + const quint32 id = it.key().toUInt(&validId); + const double value = it.value().toDouble(-1.0); + if (validId && value >= 0.0 && value <= 1.0) { + m_vst3Parameters.insert(id, value); + } + } + d.readString(23, &m_selectedSource, ""); + d.readBlob(24, &m_vst3State); return true; } @@ -149,6 +191,9 @@ bool DenoiserSettings::deserialize(const QByteArray& data) void DenoiserSettings::applySettings(const QStringList& settingsKeys, const DenoiserSettings& settings) { + if (settingsKeys.contains("selectedSource")) { + m_selectedSource = settings.m_selectedSource; + } if (settingsKeys.contains("denoiserType")) { m_denoiserType = settings.m_denoiserType; } @@ -161,6 +206,24 @@ void DenoiserSettings::applySettings(const QStringList& settingsKeys, const Deno if (settingsKeys.contains("volumeTenths")) { m_volumeTenths = settings.m_volumeTenths; } + if (settingsKeys.contains("nvidiaIntensity")) { + m_nvidiaIntensity = qBound(0, settings.m_nvidiaIntensity, 100); + } + if (settingsKeys.contains("nvidiaVad")) { + m_nvidiaVad = settings.m_nvidiaVad; + } + if (settingsKeys.contains("vst3ModulePath")) { + m_vst3ModulePath = settings.m_vst3ModulePath; + } + if (settingsKeys.contains("vst3ClassId")) { + m_vst3ClassId = settings.m_vst3ClassId; + } + if (settingsKeys.contains("vst3Parameters")) { + m_vst3Parameters = settings.m_vst3Parameters; + } + if (settingsKeys.contains("vst3State")) { + m_vst3State = settings.m_vst3State; + } if (settingsKeys.contains("audioDeviceName")) { m_audioDeviceName = settings.m_audioDeviceName; } @@ -200,6 +263,9 @@ QString DenoiserSettings::getDebugString(const QStringList& settingsKeys, bool f { QString debugString; + if (settingsKeys.contains("selectedSource") || force) { + debugString += QString("Selected source: %1 ").arg(m_selectedSource); + } if (settingsKeys.contains("denoiserType") || force) { debugString += QString("DenoiserType: %1 ").arg(static_cast(m_denoiserType)); } @@ -212,6 +278,21 @@ QString DenoiserSettings::getDebugString(const QStringList& settingsKeys, bool f if (settingsKeys.contains("volumeTenths") || force) { debugString += QString("Volume : %1 ").arg(m_volumeTenths/10.0); } + if (settingsKeys.contains("nvidiaIntensity") || force) { + debugString += QString("NVIDIA intensity: %1%% ").arg(m_nvidiaIntensity); + } + if (settingsKeys.contains("nvidiaVad") || force) { + debugString += QString("NVIDIA VAD: %1 ").arg(m_nvidiaVad ? "true" : "false"); + } + if (settingsKeys.contains("vst3ModulePath") || force) { + debugString += QString("VST3 module: %1 ").arg(m_vst3ModulePath); + } + if (settingsKeys.contains("vst3ClassId") || force) { + debugString += QString("VST3 class: %1 ").arg(QString::fromLatin1(m_vst3ClassId.toHex())); + } + if (settingsKeys.contains("vst3State") || force) { + debugString += QString("VST3 state: %1 bytes ").arg(m_vst3State.size()); + } if (settingsKeys.contains("audioDeviceName") || force) { debugString += QString("Audio Device Name: %1 ").arg(m_audioDeviceName); } diff --git a/plugins/feature/denoiser/denoisersettings.h b/plugins/feature/denoiser/denoisersettings.h index e75a26728..93511522e 100644 --- a/plugins/feature/denoiser/denoisersettings.h +++ b/plugins/feature/denoiser/denoisersettings.h @@ -20,6 +20,7 @@ #include #include #include +#include class Serializable; @@ -29,12 +30,21 @@ struct DenoiserSettings { DenoiserType_None = 0, DenoiserType_RNnoise = 1, + DenoiserType_Nvidia = 2, + DenoiserType_Vst3 = 3, }; DenoiserType m_denoiserType; + QString m_selectedSource; bool m_enableDenoiser; bool m_audioMute; int m_volumeTenths; + int m_nvidiaIntensity; + bool m_nvidiaVad; + QString m_vst3ModulePath; + QByteArray m_vst3ClassId; + QMap m_vst3Parameters; + QByteArray m_vst3State; //!< Opaque plugin state from Vst3Effect::state() QString m_audioDeviceName; QString m_title; quint32 m_rgbColor; diff --git a/plugins/feature/denoiser/denoiserworker.cpp b/plugins/feature/denoiser/denoiserworker.cpp index 2b70fce7f..3010e7fad 100644 --- a/plugins/feature/denoiser/denoiserworker.cpp +++ b/plugins/feature/denoiser/denoiserworker.cpp @@ -18,28 +18,44 @@ #include "dsp/wavfilerecord.h" #include "audio/audiodevicemanager.h" #include "dsp/dspengine.h" +#include "pipes/datapipes.h" +#include "maincore.h" #include "rnnoise.h" +#include +#include #include "denoiserworker.h" +#include "vst3effect.h" const int DenoiserWorker::m_levelNbSamples = 480; // 10 ms at 48 kHz MESSAGE_CLASS_DEFINITION(DenoiserWorker::MsgConfigureDenoiserWorker, Message) MESSAGE_CLASS_DEFINITION(DenoiserWorker::MsgConnectFifo, Message) +MESSAGE_CLASS_DEFINITION(DenoiserWorker::MsgReportNvidiaStatus, Message) +MESSAGE_CLASS_DEFINITION(DenoiserWorker::MsgReportVst3Status, Message) DenoiserWorker::DenoiserWorker(QObject *parent) : QObject(parent), m_dataFifo(nullptr), + m_demodProducer(nullptr), m_sinkSampleRate(0), m_msgQueueToFeature(nullptr), m_magsq(0.0), - m_sampleBufferSize(0), m_channelPowerAvg(), m_wavFileRecord(nullptr), m_recordSilenceNbSamples(0), m_recordSilenceCount(0), m_nbBytes(0), - m_rnnoiseFill(0) + m_rnnoiseFill(0), + m_nvidiaFill(0), + m_nvidiaInitAttempted(false), + m_nvidiaReady(false), + m_nvidiaResetPending(false), + m_nvidiaStatusReported(false), + m_nvidiaGeneration(0), + m_vst3Effect(nullptr), + m_vst3Fill(0), + m_vst3FailureReported(false) { m_audioBuffer.resize(4800); m_audioBufferFill = 0; @@ -53,6 +69,7 @@ DenoiserWorker::~DenoiserWorker() m_inputMessageQueue.clear(); DSPEngine::instance()->getAudioDeviceManager()->removeAudioSink(getAudioFifo()); rnnoise_destroy(m_rnnoiseState); + m_nvidiaDenoiser.shutdown(); } void DenoiserWorker::reset() @@ -106,24 +123,56 @@ void DenoiserWorker::feedPart( m_nbBytes = nbBytes; int countSamples = (end - begin) / nbBytes; - if (countSamples > m_sampleBufferSize) - { - m_sampleBuffer.resize(countSamples); - m_sampleBufferSize = countSamples; - } + m_sampleBuffer.clear(); + m_sampleBuffer.reserve(countSamples); for (int i = 0; i < countSamples; i++) { processSample(dataType, begin, i); } + flushAudio(); + if (m_settings.m_recordToFile && m_wavFileRecord) { for (const auto& sample : m_sampleBuffer) { writeSampleToFile(sample); } + } + + m_sampleBuffer.clear(); +} + +void DenoiserWorker::flushAudio() +{ + if (m_audioBufferFill == 0) return; + + if (m_demodProducer) + { + QList pipes; + MainCore::instance()->getDataPipes().getDataPipes(m_demodProducer, "demod", pipes); + const auto *data = reinterpret_cast(m_audioBuffer.data()); + const unsigned int byteCount = static_cast(m_audioBufferFill * sizeof(AudioSample)); + + for (const auto& pipe : pipes) + { + DataFifo *fifo = qobject_cast(pipe->m_element); + if (fifo) { + fifo->write(data, byteCount, DataFifo::DataTypeCI16); + } + } + } + + if (m_settings.m_audioMute) { + std::fill_n(m_audioBuffer.begin(), m_audioBufferFill, AudioSample{0, 0}); + } - m_sampleBuffer.clear(); + const std::size_t written = m_audioFifo.write(reinterpret_cast(m_audioBuffer.data()), m_audioBufferFill); + if (written != m_audioBufferFill) + { + qDebug("DenoiserWorker::flushAudio: %lu/%lu audio samples written", written, m_audioBufferFill); + m_audioFifo.clear(); } + m_audioBufferFill = 0; } void DenoiserWorker::writeSampleToFile(const Sample& sample) @@ -271,8 +320,12 @@ void DenoiserWorker::applySettings(const DenoiserSettings& settings, const QStri // TODO: handle sample rate change } - if (settingsKeys.contains("enableDenoiser") || settingsKeys.contains("denoiserType") || force) { + if (settingsKeys.contains("enableDenoiser") || settingsKeys.contains("denoiserType") || + settingsKeys.contains("nvidiaIntensity") || + settingsKeys.contains("nvidiaVad") || force) + { m_rnnoiseFill = 0; + resetNvidia(); } if (force) { @@ -280,12 +333,35 @@ void DenoiserWorker::applySettings(const DenoiserSettings& settings, const QStri } else { m_settings.applySettings(settingsKeys, settings); } + if (force || settingsKeys.contains("denoiserType") || settingsKeys.contains("vst3ModulePath") || + settingsKeys.contains("vst3ClassId") || settingsKeys.contains("enableDenoiser")) + { + m_vst3Fill = 0; + m_vst3FailureReported = false; + } + + // applySettings runs on the worker thread. Release the CUDA effect as soon as + // this backend is no longer in use, even if no more NVIDIA samples arrive. + if (m_nvidiaResetPending && (!m_settings.m_enableDenoiser || + m_settings.m_denoiserType != DenoiserSettings::DenoiserType::DenoiserType_Nvidia)) + { + m_nvidiaDenoiser.shutdown(); + m_nvidiaResetPending = false; + } } void DenoiserWorker::applySampleRate(int sampleRate) { QMutexLocker mutexLocker(&m_mutex); + + if (m_sinkSampleRate == sampleRate) { + return; + } + m_sinkSampleRate = sampleRate; + resetNvidia(); + m_vst3Fill = 0; + m_vst3FailureReported = false; if (m_wavFileRecord) { @@ -297,8 +373,82 @@ void DenoiserWorker::applySampleRate(int sampleRate) } } +void DenoiserWorker::setVst3Effect(Vst3Effect *effect) +{ + QMutexLocker mutexLocker(&m_mutex); + m_vst3Effect = effect; + m_vst3Fill = 0; + m_vst3FailureReported = false; +} + +void DenoiserWorker::resetNvidia() +{ + // Caller holds m_mutex. The model itself is released on the worker thread. + m_nvidiaFill = 0; + m_nvidiaInitAttempted = false; + m_nvidiaReady = false; + m_nvidiaResetPending = true; + m_nvidiaStatusReported = false; + ++m_nvidiaGeneration; +} + +void DenoiserWorker::prepareNvidia() +{ + int sampleRate; + float intensity; + bool vad; + quint32 generation; + + { + QMutexLocker mutexLocker(&m_mutex); + + if (m_nvidiaInitAttempted || !m_settings.m_enableDenoiser || + m_settings.m_denoiserType != DenoiserSettings::DenoiserType::DenoiserType_Nvidia) { + return; + } + + if (m_nvidiaResetPending) + { + m_nvidiaDenoiser.shutdown(); + m_nvidiaResetPending = false; + } + + m_nvidiaInitAttempted = true; + sampleRate = m_sinkSampleRate; + intensity = qBound(0, m_settings.m_nvidiaIntensity, 100) / 100.0f; + vad = m_settings.m_nvidiaVad; + generation = m_nvidiaGeneration; + } + + // Loading the model can take seconds. Do it without m_mutex so the feature + // thread is not blocked by applySampleRate() or setVst3Effect() meanwhile. + // m_nvidiaDenoiser is only used on this thread, as NVIDIA requires. + QString error; + bool ready = false; + + if (sampleRate != 48000) { + error = QStringLiteral("NVIDIA Noise Removal requires 48 kHz input; got %1 Hz.").arg(sampleRate); + } else { + ready = m_nvidiaDenoiser.initialize(error, intensity, vad); + } + + QMutexLocker mutexLocker(&m_mutex); + + if (generation != m_nvidiaGeneration) { + return; // Settings or rate changed while loading; reset and retry on the next data. + } + + m_nvidiaReady = ready; + + if (!ready) { + reportNvidiaError(error + QStringLiteral(" Audio is passing through.")); + } +} + void DenoiserWorker::handleData() { + prepareNvidia(); + QMutexLocker mutexLocker(&m_mutex); while ((m_dataFifo->fill() > 0) && (m_inputMessageQueue.size() == 0)) @@ -347,11 +497,14 @@ void DenoiserWorker::processSample( m_magsq = re*re; m_channelPowerAvg(m_magsq); - if ((!m_settings.m_enableDenoiser || m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_None) && !m_settings.m_audioMute) { + if (!m_settings.m_enableDenoiser || m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_None) { processI16DenoiserNone(samplefp); - } - else if ((m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_RNnoise) && !m_settings.m_audioMute) { + } else if (m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_RNnoise) { processI16DenoiserRNNoise(samplefp); + } else if (m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Nvidia) { + processNvidiaSample(samplefp); + } else if (m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Vst3) { + processVst3Sample(samplefp, samplefp); } } break; @@ -366,11 +519,14 @@ void DenoiserWorker::processSample( m_magsq = re*re + im*im; m_channelPowerAvg(m_magsq); - if ((!m_settings.m_enableDenoiser || m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_None) && !m_settings.m_audioMute) { + if (!m_settings.m_enableDenoiser || m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_None) { processCI16DenoiserNone(samplefpRe, samplefpIm); - } - else if ((m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_RNnoise) && !m_settings.m_audioMute) { + } else if (m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_RNnoise) { processCI16DenoiserRNNoise(samplefpRe, samplefpIm); + } else if (m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Nvidia) { + processNvidiaSample((samplefpRe + samplefpIm) / 2.0); + } else if (m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Vst3) { + processVst3Sample(samplefpRe, samplefpIm); } } break; @@ -389,15 +545,7 @@ void DenoiserWorker::processI16DenoiserNone(const double& samplefp) if (m_audioBufferFill >= m_audioBuffer.size()) { - std::size_t res = m_audioFifo.write((const quint8*)&m_audioBuffer[0], m_audioBufferFill); - - if (res != m_audioBufferFill) - { - qDebug("DenoiserWorker::processSample: %lu/%lu audio samples written", res, m_audioBufferFill); - m_audioFifo.clear(); - } - - m_audioBufferFill = 0; + flushAudio(); } } @@ -428,15 +576,7 @@ void DenoiserWorker::processI16DenoiserRNNoise(const double& samplefp) if (m_audioBufferFill >= m_audioBuffer.size()) { - std::size_t res = m_audioFifo.write((const quint8*)&m_audioBuffer[0], m_audioBufferFill); - - if (res != m_audioBufferFill) - { - qDebug("DenoiserWorker::processSample: %lu/%lu audio samples written", res, m_audioBufferFill); - m_audioFifo.clear(); - } - - m_audioBufferFill = 0; + flushAudio(); } } @@ -444,6 +584,124 @@ void DenoiserWorker::processI16DenoiserRNNoise(const double& samplefp) } } +void DenoiserWorker::processNvidiaSample(const double& samplefp) +{ + if (m_nvidiaResetPending) + { + m_nvidiaDenoiser.shutdown(); + m_nvidiaResetPending = false; + } + + // NvAFX_Run uses mono, normalized floating point audio in 10 ms frames. + m_nvidiaIn[m_nvidiaFill++] = static_cast(std::max(-1.0, std::min(1.0, samplefp / 32768.0))); + + if (m_nvidiaFill < m_nvidiaFrameSize) { + return; + } + + // The model is loaded by prepareNvidia() outside m_mutex; pass through until it is ready. + bool processed = false; + + if (m_nvidiaReady) + { + QString error; + processed = m_nvidiaDenoiser.process(m_nvidiaIn, m_nvidiaOut, error); + + if (!processed) + { + m_nvidiaReady = false; + reportNvidiaError(error + QStringLiteral(" Audio is passing through.")); + } + } + + if (processed && !m_nvidiaStatusReported) + { + if (m_msgQueueToFeature) { + m_msgQueueToFeature->push(MsgReportNvidiaStatus::create(QString())); + } + m_nvidiaStatusReported = true; + } + + for (int j = 0; j < m_nvidiaFrameSize; ++j) + { + const double normalized = processed && std::isfinite(m_nvidiaOut[j]) ? m_nvidiaOut[j] : m_nvidiaIn[j]; + const double sample = std::max(-32768.0, std::min(32767.0, normalized * 32768.0)); + const int16_t audioSample = static_cast(sample); + + if (m_channelPowerAvg.asDouble() > 1e-4) { + m_sampleBuffer.push_back(Sample(static_cast(audioSample) * (SDR_RX_SAMP_SZ == 24 ? 256 : 1), 0)); + } + + m_audioBuffer[m_audioBufferFill].l = audioSample; + m_audioBuffer[m_audioBufferFill].r = audioSample; + ++m_audioBufferFill; + + if (m_audioBufferFill >= m_audioBuffer.size()) + { + flushAudio(); + } + } + + m_nvidiaFill = 0; +} + +void DenoiserWorker::reportNvidiaError(const QString& error) +{ + qWarning() << "DenoiserWorker:" << error; + m_nvidiaStatusReported = false; + if (m_msgQueueToFeature) { + m_msgQueueToFeature->push(MsgReportNvidiaStatus::create(error)); + } +} + +void DenoiserWorker::processVst3Sample(double left, double right) +{ + const int i = m_vst3Fill++; + m_vst3Input[0][i] = static_cast(std::max(-1.0, std::min(1.0, left / 32768.0))); + m_vst3Input[1][i] = static_cast(std::max(-1.0, std::min(1.0, right / 32768.0))); + if (m_vst3Fill != m_vst3BlockSize) { + return; + } + + bool processed = false; + if (m_vst3Effect) + { + QString error; + processed = m_vst3Effect->process(m_vst3Input[0], m_vst3Input[1], + m_vst3Output[0], m_vst3Output[1], m_vst3BlockSize, error); + if (!processed && !m_vst3FailureReported) + { + qWarning() << "DenoiserWorker:" << error; + if (m_msgQueueToFeature) + { + m_msgQueueToFeature->push(MsgReportVst3Status::create( + QStringLiteral("VST3: %1. Audio is passing through.").arg(error))); + } + m_vst3FailureReported = true; + } + } + for (int j = 0; j < m_vst3BlockSize; ++j) + { + const float l = processed && std::isfinite(m_vst3Output[0][j]) ? m_vst3Output[0][j] : m_vst3Input[0][j]; + const float r = processed && std::isfinite(m_vst3Output[1][j]) ? m_vst3Output[1][j] : m_vst3Input[1][j]; + const int16_t leftSample = static_cast(std::max(-32768.0f, std::min(32767.0f, l * 32768.0f))); + const int16_t rightSample = static_cast(std::max(-32768.0f, std::min(32767.0f, r * 32768.0f))); + if (m_channelPowerAvg.asDouble() > 1e-4) + { + const int scale = SDR_RX_SAMP_SZ == 24 ? 256 : 1; + m_sampleBuffer.push_back(Sample(static_cast(leftSample) * scale, + static_cast(rightSample) * scale)); + } + m_audioBuffer[m_audioBufferFill].l = leftSample; + m_audioBuffer[m_audioBufferFill].r = rightSample; + if (++m_audioBufferFill >= m_audioBuffer.size()) + { + flushAudio(); + } + } + m_vst3Fill = 0; +} + void DenoiserWorker::processCI16DenoiserNone(const double& samplefpRe, const double& samplefpIm) { if (m_channelPowerAvg.asDouble() > 1e-4) { // -40 dB threshold @@ -456,15 +714,7 @@ void DenoiserWorker::processCI16DenoiserNone(const double& samplefpRe, const dou if (m_audioBufferFill >= m_audioBuffer.size()) { - std::size_t res = m_audioFifo.write((const quint8*)&m_audioBuffer[0], m_audioBufferFill); - - if (res != m_audioBufferFill) - { - qDebug("DenoiserWorker::processSample: %lu/%lu audio samples written", res, m_audioBufferFill); - m_audioFifo.clear(); - } - - m_audioBufferFill = 0; + flushAudio(); } } @@ -497,15 +747,7 @@ void DenoiserWorker::processCI16DenoiserRNNoise(const double& samplefpRe, const if (m_audioBufferFill >= m_audioBuffer.size()) { - std::size_t res = m_audioFifo.write((const quint8*)&m_audioBuffer[0], m_audioBufferFill); - - if (res != m_audioBufferFill) - { - qDebug("DenoiserWorker::processSample: %lu/%lu audio samples written", res, m_audioBufferFill); - m_audioFifo.clear(); - } - - m_audioBufferFill = 0; + flushAudio(); } } diff --git a/plugins/feature/denoiser/denoiserworker.h b/plugins/feature/denoiser/denoiserworker.h index 40a658799..a744df559 100644 --- a/plugins/feature/denoiser/denoiserworker.h +++ b/plugins/feature/denoiser/denoiserworker.h @@ -30,8 +30,10 @@ #include "audio/audiofifo.h" #include "denoisersettings.h" +#include "nvidiaaudioeffects.h" class WavFileRecord; +class Vst3Effect; struct DenoiseState; class DenoiserWorker : public QObject { @@ -77,6 +79,33 @@ public: { } }; + class MsgReportNvidiaStatus : public Message { + MESSAGE_CLASS_DECLARATION + public: + const QString& getError() const { return m_error; } + static MsgReportNvidiaStatus* create(const QString& error) { + return new MsgReportNvidiaStatus(error); + } + private: + QString m_error; + explicit MsgReportNvidiaStatus(const QString& error) : Message(), m_error(error) {} + }; + + class MsgReportVst3Status : public Message { + MESSAGE_CLASS_DECLARATION + public: + const QString& getError() const { return m_error; } + static MsgReportVst3Status* create(const QString& error) { + return new MsgReportVst3Status(error); + } + private: + QString m_error; + explicit MsgReportVst3Status(const QString& error) : + Message(), + m_error(error) + {} + }; + explicit DenoiserWorker(QObject *parent = nullptr); ~DenoiserWorker() override; void reset(); @@ -84,8 +113,10 @@ public: void stopWork(); MessageQueue *getInputMessageQueue() { return &m_inputMessageQueue; } void setMessageQueueToFeature(MessageQueue *messageQueue) { m_msgQueueToFeature = messageQueue; } + void setDemodProducer(QObject *producer) { m_demodProducer = producer; } void applySampleRate(int sampleRate); void applySettings(const DenoiserSettings& settings, const QStringList& settingsKeys, bool force = false); + void setVst3Effect(Vst3Effect *effect); double getMagSq() const { return m_magsq; } double getMagSqAvg() const { return (double) m_channelPowerAvg; } void getLevels(qreal& rmsLevel, qreal& peakLevel, int& numSamples) const @@ -105,14 +136,17 @@ signals: void levelChanged(qreal rmsLevel, qreal peakLevel, int numSamples); private: + static constexpr int m_nvidiaFrameSize = 480; + static constexpr int m_vst3BlockSize = 512; + DataFifo *m_dataFifo; + QObject *m_demodProducer; int m_sinkSampleRate; MessageQueue m_inputMessageQueue; //!< Queue for asynchronous inbound communication MessageQueue *m_msgQueueToFeature; //!< Queue to report channel change to main feature object DenoiserSettings m_settings; double m_magsq; SampleVector m_sampleBuffer; - int m_sampleBufferSize; MovingAverageUtil m_channelPowerAvg; WavFileRecord* m_wavFileRecord; int m_recordSilenceNbSamples; @@ -126,6 +160,22 @@ private: float m_rnnoiseOut[480]; int m_rnnoiseFill; + NvidiaAudioEffects m_nvidiaDenoiser; + alignas(64) float m_nvidiaIn[m_nvidiaFrameSize]; + alignas(64) float m_nvidiaOut[m_nvidiaFrameSize]; + int m_nvidiaFill; + bool m_nvidiaInitAttempted; + bool m_nvidiaReady; + bool m_nvidiaResetPending; + bool m_nvidiaStatusReported; + quint32 m_nvidiaGeneration; //!< Incremented on any change that invalidates a model load + + Vst3Effect *m_vst3Effect; + float m_vst3Input[2][m_vst3BlockSize]; + float m_vst3Output[2][m_vst3BlockSize]; + int m_vst3Fill; + bool m_vst3FailureReported; + quint32 m_levelCalcCount = 0; qreal m_rmsLevel; qreal m_peakLevelOut; @@ -145,6 +195,7 @@ private: bool handleMessage(const Message& cmd); void writeSampleToFile(const Sample& sample); + void flushAudio(); void processSample( DataFifo::DataType dataType, const QByteArray::const_iterator& begin, @@ -154,6 +205,11 @@ private: void processI16DenoiserRNNoise(const double& samplefp); void processCI16DenoiserNone(const double& samplefpRe, const double& samplefpIm); void processCI16DenoiserRNNoise(const double& samplefpRe, const double& samplefpIm); + void processNvidiaSample(const double& samplefp); + void processVst3Sample(double left, double right); + void reportNvidiaError(const QString& error); + void resetNvidia(); + void prepareNvidia(); void calculateLevel(const Real& sample); private slots: diff --git a/plugins/feature/denoiser/nvidiaaudioeffects.cpp b/plugins/feature/denoiser/nvidiaaudioeffects.cpp new file mode 100644 index 000000000..52962f6d2 --- /dev/null +++ b/plugins/feature/denoiser/nvidiaaudioeffects.cpp @@ -0,0 +1,302 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include + +#ifdef Q_OS_WIN +#define WIN32_LEAN_AND_MEAN +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + +#include "nvidiaaudioeffects.h" + +#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) +struct NvidiaAudioEffects::Impl +{ + using CreateEffect = int (*)(const char *, void **); + using DestroyEffect = int (*)(void *); + using SetString = int (*)(void *, const char *, const char *); + using SetU32 = int (*)(void *, const char *, unsigned int); + using SetFloat = int (*)(void *, const char *, float); + using GetU32 = int (*)(void *, const char *, unsigned int *); + using Load = int (*)(void *); + using Run = int (*)(void *, const float **, float **, unsigned int, unsigned int); + + QLibrary library; + void *effect = nullptr; + QByteArray modelPath; + Qt::HANDLE threadId = nullptr; + DestroyEffect destroyEffect = nullptr; + Run run = nullptr; +}; +#else +struct NvidiaAudioEffects::Impl {}; +#endif + +NvidiaAudioEffects::NvidiaAudioEffects() : + m_impl(nullptr) +{ +} + +NvidiaAudioEffects::~NvidiaAudioEffects() +{ + shutdown(); +} + +bool NvidiaAudioEffects::initialize(QString& error, float intensityRatio, bool enableVad) +{ + shutdown(); +#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) + QString sdkDir = qEnvironmentVariable("NVAFX_SDK_DIR"); + +#ifdef Q_OS_WIN + if (sdkDir.isEmpty()) { + sdkDir = QDir(qEnvironmentVariable("ProgramFiles")).filePath("NVIDIA Corporation/NVIDIA Audio Effects SDK"); + } + + const QString libraryPath = QDir(sdkDir).filePath("NVAudioEffects.dll"); + const QString modelPath = QDir(sdkDir).filePath("models/denoiser_48k.trtpkg"); +#else + if (sdkDir.isEmpty()) { + sdkDir = qEnvironmentVariable("AFX_SDK_ROOT"); + } + if (sdkDir.isEmpty()) { + error = QStringLiteral("Set NVAFX_SDK_DIR to the Linux Audio Effects SDK root"); + return false; + } + + const QString libraryPath = QDir(sdkDir).filePath("nvafx/lib/libnv_audiofx.so"); + QString modelPath = qEnvironmentVariable("NVAFX_MODEL_PATH"); + if (modelPath.isEmpty()) + { + // Packages contain GPU-specific models. Pick one only if unambiguous. + QStringList models; + for (const QString& feature : {QStringLiteral("denoiser"), QStringLiteral("nvafxdenoiser")}) + { + const QDir modelDir(QDir(sdkDir).filePath(QStringLiteral("features/%1/models").arg(feature))); + for (const QString& gpuDir : modelDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) + { + const QString path = modelDir.filePath(gpuDir + QStringLiteral("/denoiser_48k.trtpkg")); + if (QFileInfo(path).isFile()) { + models.append(path); + } + } + } + if (models.size() == 1) { + modelPath = models.first(); + } else { + error = QStringLiteral("Set NVAFX_MODEL_PATH to this GPU's denoiser_48k.trtpkg (found %1 models)").arg(models.size()); + return false; + } + } +#endif + + if (!QFileInfo(libraryPath).isFile() || !QFileInfo(modelPath).isFile()) + { + error = QStringLiteral("NVIDIA Audio Effects library or 48 kHz model was not found: %1, %2").arg(libraryPath, modelPath); + return false; + } + + m_impl = new Impl; + m_impl->modelPath = QFile::encodeName(QDir::toNativeSeparators(modelPath)); + m_impl->library.setFileName(QFileInfo(libraryPath).absoluteFilePath()); +#ifdef Q_OS_WIN + // QLibrary's ordinary load cannot find this SDK's adjacent DLL dependencies. + // Load once with the SDK directory in the dependency search path, then let + // QLibrary acquire and own its own reference to the already loaded DLL. + HMODULE bootstrap = LoadLibraryExW(reinterpret_cast(QDir::toNativeSeparators(libraryPath).utf16()), + nullptr, LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + if (!bootstrap) + { + error = QStringLiteral("Could not load NVIDIA Audio Effects DLL (Windows error %1)").arg(GetLastError()); + shutdown(); + return false; + } +#endif + const bool loaded = m_impl->library.load(); +#ifdef Q_OS_WIN + FreeLibrary(bootstrap); +#endif + if (!loaded) + { + error = QStringLiteral("Could not load NVIDIA Audio Effects library: %1").arg(m_impl->library.errorString()); + shutdown(); + return false; + } + + m_impl->threadId = QThread::currentThreadId(); + const auto resolve = [this](const char *name) { return m_impl->library.resolve(name); }; + const auto createEffect = reinterpret_cast(resolve("NvAFX_CreateEffect")); + m_impl->destroyEffect = reinterpret_cast(resolve("NvAFX_DestroyEffect")); + const auto setString = reinterpret_cast(resolve("NvAFX_SetString")); + const auto setU32 = reinterpret_cast(resolve("NvAFX_SetU32")); + const auto setFloat = reinterpret_cast(resolve("NvAFX_SetFloat")); + const auto getU32 = reinterpret_cast(resolve("NvAFX_GetU32")); + const auto load = reinterpret_cast(resolve("NvAFX_Load")); + m_impl->run = reinterpret_cast(resolve("NvAFX_Run")); + + if (!createEffect || !m_impl->destroyEffect || !setString || !setU32 || !setFloat || !getU32 || !load || !m_impl->run) + { + error = QStringLiteral("NVIDIA Audio Effects library is missing required functions"); + shutdown(); + return false; + } + + int status = createEffect("denoiser", &m_impl->effect); + + if (status == 0) { + status = setU32(m_impl->effect, "input_sample_rate", 48000); + } + if (status == 0) { + status = setFloat(m_impl->effect, "intensity_ratio", qBound(0.0f, intensityRatio, 1.0f)); + } + if (status == 0) { + status = setU32(m_impl->effect, "enable_vad", enableVad ? 1U : 0U); + } + +#ifdef Q_OS_LINUX + if (status == 0) { + status = setU32(m_impl->effect, "num_streams", 1); + } + if (status == 0) { + status = setU32(m_impl->effect, "num_samples_per_input_frame", 480); + } +#endif + + if (status == 0) { + status = setString(m_impl->effect, "model_path", m_impl->modelPath.constData()); + } + + if (status == 0) { + status = load(m_impl->effect); + } + + unsigned int frameSize = 0; + unsigned int outputFrameSize = 0; + unsigned int inputChannels = 0; + unsigned int outputChannels = 0; + unsigned int outputSampleRate = 0; + +#ifdef Q_OS_LINUX + const char *inputFrameSelector = "num_samples_per_input_frame"; + const char *outputFrameSelector = "num_samples_per_output_frame"; +#else + const char *inputFrameSelector = "num_input_samples_per_frame"; + const char *outputFrameSelector = "num_output_samples_per_frame"; +#endif + + if (status == 0) { + status = getU32(m_impl->effect, inputFrameSelector, &frameSize); + } + + if (status == 0) { + status = getU32(m_impl->effect, outputFrameSelector, &outputFrameSize); + } + + if (status == 0) { + status = getU32(m_impl->effect, "num_input_channels", &inputChannels); + } + + if (status == 0) { + status = getU32(m_impl->effect, "num_output_channels", &outputChannels); + } + + if (status == 0) { + status = getU32(m_impl->effect, "output_sample_rate", &outputSampleRate); + } + + if (status != 0 || frameSize != 480 || outputFrameSize != 480 || inputChannels != 1 || outputChannels != 1 || outputSampleRate != 48000) + { + error = QStringLiteral("NVIDIA denoiser initialization failed (status %1, frames %2/%3, channels %4/%5, output rate %6)") + .arg(status).arg(frameSize).arg(outputFrameSize).arg(inputChannels).arg(outputChannels).arg(outputSampleRate); + shutdown(); + return false; + } + + return true; +#else + error = QStringLiteral("NVIDIA Audio Effects is available only on Windows and Linux"); + return false; +#endif +} + +void NvidiaAudioEffects::shutdown() +{ + if (!m_impl) { + return; + } +#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) + if (m_impl->effect && m_impl->destroyEffect) { + m_impl->destroyEffect(m_impl->effect); + } + if (m_impl->library.isLoaded()) { + m_impl->library.unload(); + } +#endif + delete m_impl; + m_impl = nullptr; +} + +bool NvidiaAudioEffects::process(const float *input, float *output, QString& error) +{ +#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) + if (!m_impl || !m_impl->effect) { + error = QStringLiteral("NVIDIA denoiser is not initialized"); + return false; + } + + if (QThread::currentThreadId() != m_impl->threadId) { + error = QStringLiteral("NVIDIA denoiser was called from a different thread than it was initialized on"); + return false; + } + + // Keep the caller's input intact for failure passthrough. + std::memcpy(output, input, 480 * sizeof(float)); +#ifdef Q_OS_WIN + // The installed Windows runtime processes the buffer in place, as in OBS. + const float *inputs[] = {output}; +#else + const float *inputs[] = {input}; +#endif + float *outputs[] = {output}; + const int status = m_impl->run(m_impl->effect, inputs, outputs, 480, 1); + + if (status != 0) + { + error = QStringLiteral("NVIDIA denoiser processing failed (status %1)").arg(status); + shutdown(); + return false; + } + + return true; +#else + Q_UNUSED(input) + Q_UNUSED(output) + error = QStringLiteral("NVIDIA Audio Effects is available only on Windows and Linux"); + return false; +#endif +} diff --git a/plugins/feature/denoiser/nvidiaaudioeffects.h b/plugins/feature/denoiser/nvidiaaudioeffects.h new file mode 100644 index 000000000..36bfb94dc --- /dev/null +++ b/plugins/feature/denoiser/nvidiaaudioeffects.h @@ -0,0 +1,41 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_FEATURE_DENOISER_NVIDIAAUDIOEFFECTS_H_ +#define INCLUDE_FEATURE_DENOISER_NVIDIAAUDIOEFFECTS_H_ + +#include + +// Loads the user-installed NVIDIA Audio Effects redistributable at runtime. +// No NVIDIA headers or binaries are required. +class NvidiaAudioEffects +{ +public: + NvidiaAudioEffects(); + ~NvidiaAudioEffects(); + + bool initialize(QString& error, float intensityRatio, bool enableVad); + void shutdown(); + bool process(const float *input, float *output, QString& error); + +private: + struct Impl; + Impl *m_impl; +}; + +#endif diff --git a/plugins/feature/denoiser/readme.md b/plugins/feature/denoiser/readme.md index 11dc9cc79..77a2d0a4f 100644 --- a/plugins/feature/denoiser/readme.md +++ b/plugins/feature/denoiser/readme.md @@ -1,19 +1,27 @@ -

Demoiser

+

Denoiser

Introduction

-This audio denoiser plugin can be used to reduce or remove noise from audio. For now it only implements the RNNoise noise reduction (more details next) +This feature can process demodulated audio with RNNoise, NVIDIA Noise Removal, +or an installed VST3 audio effect, such as a [denoiser](https://github.com/werman/noise-suppression-for-voice) +or [EQ](https://www.manda-audio.com/products.php). -It connects to the "demod" stream of Rx channels similarly to the Demod analyzer plugin. Hence it covers: +It connects to the "demod" stream of RX channels or features similarly to the Demod Analyzer plugin. +It also outputs its processed stereo audio on a "demod" stream, so another Denoiser or Demod Analyzer can use it as an input. + +Supported sources include: - AM demodulator - Broadcast FM demodulator + - DAB demodulator + - DSD demodulator - NFM demodulator - SSB demodulator - WFM demodulator - WDSP plugin (multimode) + - Another Denoiser feature -The following noise reduction schemes are covered. It can be selected via the (6) combo box: +The processing mode is selected with the (6) combo box:

RNNoise

@@ -23,6 +31,49 @@ The noise reduction is based on a mix of DSP functions and a recursive neural ne You will find all the details about RNnoise here: https://jmvalin.ca/demo/rnnoise/ +

NVIDIA Noise Removal

+ +On Windows, this option uses the NVIDIA Audio Effects SDK redistributable installed separately from NVIDIA Broadcast. +Install the redistributable for your RTX GPU from [NVIDIA's Broadcast SDK resources](https://www.nvidia.com/en-us/geforce/broadcasting/broadcast-sdk/resources/). +The feature looks in `NVAFX_SDK_DIR` if set, otherwise in `%ProgramFiles%\NVIDIA Corporation\NVIDIA Audio Effects SDK`. +SDRangel does not include NVIDIA binaries or models. + +On Linux, install the [NVIDIA Audio Effects SDK core and Denoiser feature package](https://docs.nvidia.com/maxine/afx/latest/LinuxAFXSDK/InstallTheAFXSDK.html). +Set `NVAFX_SDK_DIR` to the extracted SDK root (or use `AFX_SDK_ROOT`). Put the SDK's `nvafx/lib`, +Denoiser feature `lib`, and `external/cuda/lib` directories on `LD_LIBRARY_PATH` before starting SDRangel. +The feature selects `features/denoiser/models/sm_*/denoiser_48k.trtpkg` automatically when exactly one GPU-specific model is installed; otherwise set `NVAFX_MODEL_PATH` to the model for your GPU. +NVIDIA officially supports the Linux SDK for its listed server GPUs; consumer GeForce cards are outside that support list. + +NVIDIA Noise Removal is not available on macOS. + +Set the demodulated audio stream to 48 kS/s. The SDK's 48 kHz speech denoiser receives mono audio; stereo input is mixed to mono. +If the SDK, model, or supported GPU is unavailable, the feature passes audio through and reports the reason in the feature's error status and SDRangel log. +NVIDIA's model is trained for speech, so tones, music, and weak radio signals may be suppressed. + +When NVIDIA Noise Removal is selected, **Strength** controls the intensity ratio from 0% (passthrough) to 100% (strongest suppression). +If weak speech is being removed, try 30–50% and adjust by ear. **VAD** enables voice activity detection, which can mute frames classified as non-speech; leave it off when receiving weak or distorted voices. +Changes to these controls reload the NVIDIA model briefly. Neither setting can guarantee preservation of speech that the model classifies as noise. + +

VST3 Audio Effects

+ +Select **VST3 Effect** to scan automatically for effects in the standard VST3 folders on Windows, Linux, or macOS. +Denoiser also scans when the feature starts; use **Scan** to refresh the list after installing a plugin. +On macOS the folders include the user, system, and network Audio/Plug-ins/VST3 folders, plus the app's Contents/VST3 folder. +The scanner runs in a separate process so a plugin that fails during discovery cannot crash SDRangel. +The **...** button lets you select a module outside those folders. +Select an effect from the list and start the feature. +**Params** opens the effect's own editor when available, or a slider dialog for its editable parameters. +Changes to exposed parameters are saved with the Denoiser settings. +When **Params** is closed, the effect's complete state (including editor settings and presets that are not exposed as parameters) is also saved, and the running effect is reloaded with it. +The effect runs at the selected channel's sample rate when reported, and otherwise assumes 48 kS/s. + +The host accepts effects with one main mono or stereo audio input and output. +Effects that require other layouts or host services may report an error; in that case audio passes through. +**Params** tries the native editor on Windows, macOS, and Linux when Qt uses X11. If the editor cannot attach, it uses the slider dialog. +Editor changes that a plugin does not expose as parameters are only heard once **Params** is closed. + +

Notes

+ Please note the following points: - Audio sample rate must be 48 kS/s (check 4) @@ -40,17 +91,17 @@ Please note the following points: This button starts or stops the plugin -

2: Channel selection

+

2: Source selection

-Use this combo to select which channel to use for display. Channel is selected at start time and upon change. You may use button (3) to force association with the channel if necessary. +Use this combo to select an Rx channel or Feature as the audio source. The selection takes effect at start time and upon change. You may use button (3) to force association with the source if necessary. -

3: (Re)apply channel selection

+

3: (Re)apply source selection

-Applies or re-applies channel association (2) so that the channel gets effectively (re)connected to the denoiser. Normally it should not be necessary to use it. +Applies or re-applies source association (2) so that the source gets effectively (re)connected to the denoiser. Normally it should not be necessary to use it.

4: Input sample rate

-This is the input audio stream sample rate and for RNNoise it should always be 48 kS/s +This is the input audio stream sample rate. RNNoise and NVIDIA Noise Removal require 48 kS/s.

5: Input power

@@ -62,10 +113,12 @@ Selects the noise reduction scheme - **None**: No noise reduction (passthrough) - **RNnoise**: RNNoise (see introduction) + - **NVIDIA Noise Removal**: NVIDIA Audio Effects SDK speech denoiser + - **VST3 Effect**: An installed VST3 audio effect

7: Noise reduction enable

-Enable or disable noise reduction. When disabled it just passes audio through +Enable or disable noise reduction or VST3 effect. When disabled it just passes audio through.

8: Audio mute and device selection

diff --git a/plugins/feature/denoiser/vst3/LICENSE.txt b/plugins/feature/denoiser/vst3/LICENSE.txt new file mode 100644 index 000000000..075933e45 --- /dev/null +++ b/plugins/feature/denoiser/vst3/LICENSE.txt @@ -0,0 +1,27 @@ +//----------------------------------------------------------------------------- +// LICENSE +// (c) 2025, Steinberg Media Technologies GmbH, All Rights Reserved +//----------------------------------------------------------------------------- +// Redistribution and use in source and binary forms, with or without modification, +// are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// * Neither the name of the Steinberg Media Technologies nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. +//----------------------------------------------------------------------------- diff --git a/plugins/feature/denoiser/vst3/vst3_c_api.h b/plugins/feature/denoiser/vst3/vst3_c_api.h new file mode 100644 index 000000000..19e15c4d7 --- /dev/null +++ b/plugins/feature/denoiser/vst3/vst3_c_api.h @@ -0,0 +1,3777 @@ +/*----------------------------------------------------------------------------- + This file is part of a Steinberg SDK. It is subject to the license terms + in the LICENSE file found in the top-level directory of this distribution + and at www.steinberg.net/sdklicenses. + No part of the SDK, including this file, may be copied, modified, propagated, + or distributed except according to the terms contained in the LICENSE file. +-----------------------------------------------------------------------------*/ + +/* This file is the autogenerated C API of the VST3 SDK */ + +#pragma once + +#include + +#if _WIN32 +#define SMTG_STDMETHODCALLTYPE __stdcall +#define SMTG_COM_COMPATIBLE 1 +#else +#define SMTG_STDMETHODCALLTYPE +#define SMTG_COM_COMPATIBLE 0 +#endif + +#ifndef __cplusplus +typedef int16_t char16_t; +#endif + +#if SMTG_COM_COMPATIBLE +#define SMTG_INLINE_UID(l1, l2, l3, l4) \ +{ \ + (Steinberg_int8)(((Steinberg_uint32)(l1) & 0x000000FF) ), (Steinberg_int8)(((Steinberg_uint32)(l1) & 0x0000FF00) >> 8), \ + (Steinberg_int8)(((Steinberg_uint32)(l1) & 0x00FF0000) >> 16), (Steinberg_int8)(((Steinberg_uint32)(l1) & 0xFF000000) >> 24), \ + (Steinberg_int8)(((Steinberg_uint32)(l2) & 0x00FF0000) >> 16), (Steinberg_int8)(((Steinberg_uint32)(l2) & 0xFF000000) >> 24), \ + (Steinberg_int8)(((Steinberg_uint32)(l2) & 0x000000FF) ), (Steinberg_int8)(((Steinberg_uint32)(l2) & 0x0000FF00) >> 8), \ + (Steinberg_int8)(((Steinberg_uint32)(l3) & 0xFF000000) >> 24), (Steinberg_int8)(((Steinberg_uint32)(l3) & 0x00FF0000) >> 16), \ + (Steinberg_int8)(((Steinberg_uint32)(l3) & 0x0000FF00) >> 8), (Steinberg_int8)(((Steinberg_uint32)(l3) & 0x000000FF) ), \ + (Steinberg_int8)(((Steinberg_uint32)(l4) & 0xFF000000) >> 24), (Steinberg_int8)(((Steinberg_uint32)(l4) & 0x00FF0000) >> 16), \ + (Steinberg_int8)(((Steinberg_uint32)(l4) & 0x0000FF00) >> 8), (Steinberg_int8)(((Steinberg_uint32)(l4) & 0x000000FF) ) \ +} +#else +#define SMTG_INLINE_UID(l1, l2, l3, l4) \ +{ \ + (Steinberg_int8)(((Steinberg_uint32)(l1) & 0xFF000000) >> 24), (Steinberg_int8)(((Steinberg_uint32)(l1) & 0x00FF0000) >> 16), \ + (Steinberg_int8)(((Steinberg_uint32)(l1) & 0x0000FF00) >> 8), (Steinberg_int8)(((Steinberg_uint32)(l1) & 0x000000FF) ), \ + (Steinberg_int8)(((Steinberg_uint32)(l2) & 0xFF000000) >> 24), (Steinberg_int8)(((Steinberg_uint32)(l2) & 0x00FF0000) >> 16), \ + (Steinberg_int8)(((Steinberg_uint32)(l2) & 0x0000FF00) >> 8), (Steinberg_int8)(((Steinberg_uint32)(l2) & 0x000000FF) ), \ + (Steinberg_int8)(((Steinberg_uint32)(l3) & 0xFF000000) >> 24), (Steinberg_int8)(((Steinberg_uint32)(l3) & 0x00FF0000) >> 16), \ + (Steinberg_int8)(((Steinberg_uint32)(l3) & 0x0000FF00) >> 8), (Steinberg_int8)(((Steinberg_uint32)(l3) & 0x000000FF) ), \ + (Steinberg_int8)(((Steinberg_uint32)(l4) & 0xFF000000) >> 24), (Steinberg_int8)(((Steinberg_uint32)(l4) & 0x00FF0000) >> 16), \ + (Steinberg_int8)(((Steinberg_uint32)(l4) & 0x0000FF00) >> 8), (Steinberg_int8)(((Steinberg_uint32)(l4) & 0x000000FF) ) \ +} +#endif + +/*---------------------------------------------------------------------------------------------------------------------- +----- Typedefs --------------------------------------------------------------------------------------------------------- +----------------------------------------------------------------------------------------------------------------------*/ + +typedef char Steinberg_int8; +typedef uint8_t Steinberg_uint8; +typedef unsigned char Steinberg_uchar; +typedef int16_t Steinberg_int16; +typedef uint16_t Steinberg_uint16; +typedef int32_t Steinberg_int32; +typedef uint32_t Steinberg_uint32; +typedef int64_t Steinberg_int64; +typedef uint64_t Steinberg_uint64; +typedef Steinberg_int64 Steinberg_TSize; +typedef Steinberg_int32 Steinberg_tresult; +typedef Steinberg_uint64 Steinberg_TPtrInt; +typedef Steinberg_uint8 Steinberg_TBool; +typedef char Steinberg_char8; +typedef char16_t Steinberg_char16; +typedef Steinberg_char16 Steinberg_tchar; +typedef const Steinberg_char8* Steinberg_CStringA; +typedef const Steinberg_char16* Steinberg_CStringW; +typedef const Steinberg_tchar* Steinberg_CString; +typedef const Steinberg_char8* Steinberg_FIDString; +typedef Steinberg_int32 Steinberg_UCoord; +typedef Steinberg_int64 Steinberg_LARGE_INT; +typedef char Steinberg_TUID[16]; +typedef Steinberg_uint64 Steinberg_Linux_TimerInterval; +typedef int Steinberg_Linux_FileDescriptor; +typedef Steinberg_char16 Steinberg_Vst_TChar; +typedef Steinberg_Vst_TChar Steinberg_Vst_String128[128]; +typedef const Steinberg_char8* Steinberg_Vst_CString; +typedef Steinberg_int32 Steinberg_Vst_MediaType; +typedef Steinberg_int32 Steinberg_Vst_BusDirection; +typedef Steinberg_int32 Steinberg_Vst_BusType; +typedef Steinberg_int32 Steinberg_Vst_IoMode; +typedef Steinberg_int32 Steinberg_Vst_UnitID; +typedef double Steinberg_Vst_ParamValue; +typedef Steinberg_uint32 Steinberg_Vst_ParamID; +typedef Steinberg_int32 Steinberg_Vst_ProgramListID; +typedef Steinberg_int16 Steinberg_Vst_CtrlNumber; +typedef double Steinberg_Vst_TQuarterNotes; +typedef Steinberg_int64 Steinberg_Vst_TSamples; +typedef Steinberg_uint32 Steinberg_Vst_ColorSpec; +typedef float Steinberg_Vst_Sample32; +typedef double Steinberg_Vst_Sample64; +typedef double Steinberg_Vst_SampleRate; +typedef Steinberg_uint64 Steinberg_Vst_SpeakerArrangement; +typedef Steinberg_uint64 Steinberg_Vst_Speaker; +typedef Steinberg_uint32 Steinberg_Vst_NoteExpressionTypeID; +typedef double Steinberg_Vst_NoteExpressionValue; +typedef Steinberg_uint32 Steinberg_Vst_KeyswitchTypeID; +typedef Steinberg_uint32 Steinberg_Vst_PhysicalUITypeID; +typedef Steinberg_int32 Steinberg_Vst_KnobMode; +typedef Steinberg_uint32 Steinberg_Vst_ChannelContext_ColorSpec; +typedef Steinberg_uint8 Steinberg_Vst_ChannelContext_ColorComponent; +typedef Steinberg_uint32 Steinberg_Vst_PrefetchableSupport; +typedef Steinberg_uint32 Steinberg_Vst_DataExchangeQueueID; +typedef Steinberg_uint32 Steinberg_Vst_DataExchangeBlockID; +typedef Steinberg_uint32 Steinberg_Vst_DataExchangeUserContextID; +typedef Steinberg_uint8 Steinberg_Vst_MidiGroup; +typedef Steinberg_uint8 Steinberg_Vst_MidiChannel; +typedef Steinberg_int32 Steinberg_Vst_BusIndex; + + +/*---------------------------------------------------------------------------------------------------------------------- +----- Interface forward declarations ----------------------------------------------------------------------------------- +----------------------------------------------------------------------------------------------------------------------*/ + +struct Steinberg_FUnknown; +struct Steinberg_IPlugViewContentScaleSupport; +struct Steinberg_IPlugView; +struct Steinberg_IPlugFrame; +struct Steinberg_Linux_IEventHandler; +struct Steinberg_Linux_ITimerHandler; +struct Steinberg_Linux_IRunLoop; +struct Steinberg_IBStream; +struct Steinberg_ISizeableStream; +struct Steinberg_Vst_INoteExpressionController; +struct Steinberg_Vst_IKeyswitchController; +struct Steinberg_Vst_INoteExpressionPhysicalUIMapping; +struct Steinberg_IPluginBase; +struct Steinberg_IPluginFactory; +struct Steinberg_IPluginFactory2; +struct Steinberg_IPluginFactory3; +struct Steinberg_Vst_IComponent; +struct Steinberg_Vst_IAttributeList; +struct Steinberg_Vst_IStreamAttributes; +struct Steinberg_Vst_IRemapParamID; +struct Steinberg_Vst_IComponentHandler; +struct Steinberg_Vst_IComponentHandler2; +struct Steinberg_Vst_IComponentHandlerBusActivation; +struct Steinberg_Vst_IProgress; +struct Steinberg_Vst_IEditController; +struct Steinberg_Vst_IEditController2; +struct Steinberg_Vst_IMidiMapping; +struct Steinberg_Vst_IEditControllerHostEditing; +struct Steinberg_Vst_IComponentHandlerSystemTime; +struct Steinberg_Vst_IEventList; +struct Steinberg_Vst_IMessage; +struct Steinberg_Vst_IConnectionPoint; +struct Steinberg_Vst_IXmlRepresentationController; +struct Steinberg_Vst_IComponentHandler3; +struct Steinberg_Vst_IContextMenuTarget; +struct Steinberg_Vst_IContextMenu; +struct Steinberg_Vst_IMidiLearn; +struct Steinberg_Vst_ChannelContext_IInfoListener; +struct Steinberg_Vst_IPrefetchableSupport; +struct Steinberg_Vst_IDataExchangeHandler; +struct Steinberg_Vst_IDataExchangeReceiver; +struct Steinberg_Vst_IAutomationState; +struct Steinberg_Vst_IInterAppAudioHost; +struct Steinberg_Vst_IInterAppAudioConnectionNotification; +struct Steinberg_Vst_IInterAppAudioPresetManager; +struct Steinberg_Vst_IAudioProcessor; +struct Steinberg_Vst_IAudioPresentationLatency; +struct Steinberg_Vst_IProcessContextRequirements; +struct Steinberg_Vst_IMidiMapping2; +struct Steinberg_Vst_IMidiLearn2; +struct Steinberg_Vst_IHostApplication; +struct Steinberg_Vst_IVst3ToVst2Wrapper; +struct Steinberg_Vst_IVst3ToAUWrapper; +struct Steinberg_Vst_IVst3ToAAXWrapper; +struct Steinberg_Vst_IVst3WrapperMPESupport; +struct Steinberg_Vst_IParameterFinder; +struct Steinberg_Vst_NoteOnOrchestralArticulation_IInfo; +struct Steinberg_Vst_ITransportControl; +struct Steinberg_Vst_IUnitHandler; +struct Steinberg_Vst_IUnitHandler2; +struct Steinberg_Vst_IUnitInfo; +struct Steinberg_Vst_IProgramListData; +struct Steinberg_Vst_IUnitData; +struct Steinberg_Vst_IPlugInterfaceSupport; +struct Steinberg_Vst_IParameterFunctionName; +struct Steinberg_Vst_IParamValueQueue; +struct Steinberg_Vst_IParameterChanges; + + +/*---------------------------------------------------------------------------------------------------------------------- +----- Struct forward declarations -------------------------------------------------------------------------------------- +----------------------------------------------------------------------------------------------------------------------*/ + +struct Steinberg_ViewRect; +struct Steinberg_Vst_NoteExpressionValueDescription; +struct Steinberg_Vst_NoteExpressionValueEvent; +struct Steinberg_Vst_NoteExpressionIntValueEvent; +struct Steinberg_Vst_NoteExpressionTextEvent; +struct Steinberg_Vst_NoteExpressionTypeInfo; +struct Steinberg_Vst_KeyswitchInfo; +struct Steinberg_Vst_PhysicalUIMap; +struct Steinberg_Vst_PhysicalUIMapList; +struct Steinberg_PFactoryInfo; +struct Steinberg_PClassInfo; +struct Steinberg_PClassInfo2; +struct Steinberg_PClassInfoW; +struct Steinberg_Vst_BusInfo; +struct Steinberg_Vst_RoutingInfo; +struct Steinberg_Vst_ParameterInfo; +struct Steinberg_Vst_FrameRate; +struct Steinberg_Vst_Chord; +struct Steinberg_Vst_ProcessContext; +struct Steinberg_Vst_NoteOnEvent; +struct Steinberg_Vst_NoteOffEvent; +struct Steinberg_Vst_DataEvent; +struct Steinberg_Vst_PolyPressureEvent; +struct Steinberg_Vst_ChordEvent; +struct Steinberg_Vst_ScaleEvent; +struct Steinberg_Vst_LegacyMIDICCOutEvent; +struct Steinberg_Vst_Event; +struct Steinberg_Vst_RepresentationInfo; +struct Steinberg_Vst_IContextMenuItem; +struct Steinberg_Vst_DataExchangeBlock; +struct Steinberg_Vst_ProcessSetup; +struct Steinberg_Vst_AudioBusBuffers; +struct Steinberg_Vst_ProcessData; +struct Steinberg_Vst_Midi2Controller; +struct Steinberg_Vst_Midi2ControllerParamIDAssignment; +struct Steinberg_Vst_Midi2ControllerParamIDAssignmentList; +struct Steinberg_Vst_Midi1ControllerParamIDAssignment; +struct Steinberg_Vst_Midi1ControllerParamIDAssignmentList; +struct Steinberg_Vst_NoteOnOrchestralArticulation_Variations; +struct Steinberg_Vst_NoteOnOrchestralArticulation_ClassificationVariations; +struct Steinberg_Vst_TransportPosition; +struct Steinberg_Vst_UnitInfo; +struct Steinberg_Vst_ProgramListInfo; + + +/*---------------------------------------------------------------------------------------------------------------------- +----- Result value definitions ----------------------------------------------------------------------------------------- +----------------------------------------------------------------------------------------------------------------------*/ + +#if SMTG_COM_COMPATIBLE +static const Steinberg_tresult Steinberg_kNoInterface = 0x80004002L; +static const Steinberg_tresult Steinberg_kResultOk = 0x00000000L; +static const Steinberg_tresult Steinberg_kResultTrue = 0x00000000L; +static const Steinberg_tresult Steinberg_kResultFalse = 0x00000001L; +static const Steinberg_tresult Steinberg_kInvalidArgument = 0x80070057L; +static const Steinberg_tresult Steinberg_kNotImplemented = 0x80004001L; +static const Steinberg_tresult Steinberg_kInternalError = 0x80004005L; +static const Steinberg_tresult Steinberg_kNotInitialized = 0x8000FFFFL; +static const Steinberg_tresult Steinberg_kOutOfMemory = 0x8007000EL; + +#else +static const Steinberg_tresult Steinberg_kNoInterface = -1; +static const Steinberg_tresult Steinberg_kResultOk = 0; +static const Steinberg_tresult Steinberg_kResultTrue = 0; +static const Steinberg_tresult Steinberg_kResultFalse = 1; +static const Steinberg_tresult Steinberg_kInvalidArgument = 2; +static const Steinberg_tresult Steinberg_kNotImplemented = 3; +static const Steinberg_tresult Steinberg_kInternalError = 4; +static const Steinberg_tresult Steinberg_kNotInitialized = 5; +static const Steinberg_tresult Steinberg_kOutOfMemory = 6; +#endif + + +/*---------------------------------------------------------------------------------------------------------------------- +----- Interface typedefs ----------------------------------------------------------------------------------------------- +----------------------------------------------------------------------------------------------------------------------*/ + +typedef float Steinberg_IPlugViewContentScaleSupport_ScaleFactor; +typedef const char* Steinberg_Vst_IAttributeList_AttrID; +typedef Steinberg_uint64 Steinberg_Vst_IProgress_ID; +typedef struct Steinberg_Vst_IContextMenuItem Steinberg_Vst_IContextMenu_Item; + + +/*---------------------------------------------------------------------------------------------------------------------- +----- Enums ------------------------------------------------------------------------------------------------------------ +----------------------------------------------------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ibstream.h", line 32 */ + +typedef enum +{ + Steinberg_IBStream_IStreamSeekMode_kIBSeekSet = 0, + Steinberg_IBStream_IStreamSeekMode_kIBSeekCur, + Steinberg_IBStream_IStreamSeekMode_kIBSeekEnd +} Steinberg_IBStream_IStreamSeekMode; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 45 */ + +typedef enum +{ + Steinberg_Vst_NoteExpressionTypeIDs_kVolumeTypeID = 0, + Steinberg_Vst_NoteExpressionTypeIDs_kPanTypeID, + Steinberg_Vst_NoteExpressionTypeIDs_kTuningTypeID, + Steinberg_Vst_NoteExpressionTypeIDs_kVibratoTypeID, + Steinberg_Vst_NoteExpressionTypeIDs_kExpressionTypeID, + Steinberg_Vst_NoteExpressionTypeIDs_kBrightnessTypeID, + Steinberg_Vst_NoteExpressionTypeIDs_kTextTypeID, + Steinberg_Vst_NoteExpressionTypeIDs_kPhonemeTypeID, + Steinberg_Vst_NoteExpressionTypeIDs_kCustomStart = 100000, + Steinberg_Vst_NoteExpressionTypeIDs_kCustomEnd = 200000, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2AssignablePerNoteControllerStart = 201000, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2AssignablePerNoteControllerEnd = 201255, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2RegisteredPerNoteControllerStart = 202000, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2RegisteredPerNoteControllerPlayingPosition = Steinberg_Vst_NoteExpressionTypeIDs_kMidi2RegisteredPerNoteControllerStart + 0x0C, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2RegisteredPerNoteControllerEnd = 202255, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOnAttributeStart = 203000, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOnOrchestralArticulationStart = Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOnAttributeStart + 0x10, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOnOrchestralArticulationEnd = Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOnAttributeStart + 0x1F, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOnAttributeEnd = 203255, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOffAttributeStart = 204000, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOffOrchestralArticulation = Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOffAttributeStart + 0x10, + Steinberg_Vst_NoteExpressionTypeIDs_kMidi2NoteOffAttributeEnd = 204255, + Steinberg_Vst_NoteExpressionTypeIDs_kInvalidTypeID = 0xFFFFFFFF +} Steinberg_Vst_NoteExpressionTypeIDs; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 182 */ + +typedef enum +{ + Steinberg_Vst_NoteExpressionTypeInfo_NoteExpressionTypeFlags_kIsBipolar = 1 << 0, + Steinberg_Vst_NoteExpressionTypeInfo_NoteExpressionTypeFlags_kIsOneShot = 1 << 1, + Steinberg_Vst_NoteExpressionTypeInfo_NoteExpressionTypeFlags_kIsAbsolute = 1 << 2, + Steinberg_Vst_NoteExpressionTypeInfo_NoteExpressionTypeFlags_kAssociatedParameterIDValid = 1 << 3 +} Steinberg_Vst_NoteExpressionTypeInfo_NoteExpressionTypeFlags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 249 */ + +typedef enum +{ + Steinberg_Vst_KeyswitchTypeIDs_kNoteOnKeyswitchTypeID = 0, + Steinberg_Vst_KeyswitchTypeIDs_kOnTheFlyKeyswitchTypeID, + Steinberg_Vst_KeyswitchTypeIDs_kOnReleaseKeyswitchTypeID, + Steinberg_Vst_KeyswitchTypeIDs_kKeyRangeTypeID +} Steinberg_Vst_KeyswitchTypeIDs; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstphysicalui.h", line 41 */ + +typedef enum +{ + Steinberg_Vst_PhysicalUITypeIDs_kPUIXMovement = 0, + Steinberg_Vst_PhysicalUITypeIDs_kPUIYMovement, + Steinberg_Vst_PhysicalUITypeIDs_kPUIPressure, + Steinberg_Vst_PhysicalUITypeIDs_kPUITypeCount, + Steinberg_Vst_PhysicalUITypeIDs_kInvalidPUITypeID = 0xFFFFFFFF +} Steinberg_Vst_PhysicalUITypeIDs; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 65 */ + +typedef enum +{ + Steinberg_PFactoryInfo_FactoryFlags_kNoFlags = 0, + Steinberg_PFactoryInfo_FactoryFlags_kClassesDiscardable = 1 << 0, + Steinberg_PFactoryInfo_FactoryFlags_kLicenseCheck = 1 << 1, + Steinberg_PFactoryInfo_FactoryFlags_kComponentNonDiscardable = 1 << 3, + Steinberg_PFactoryInfo_FactoryFlags_kUnicode = 1 << 4 +} Steinberg_PFactoryInfo_FactoryFlags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 127 */ + +typedef enum +{ + Steinberg_PClassInfo_ClassCardinality_kManyInstances = 0x7FFFFFFF +} Steinberg_PClassInfo_ClassCardinality; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcomponent.h", line 65 */ + +typedef enum +{ + Steinberg_Vst_MediaTypes_kAudio = 0, + Steinberg_Vst_MediaTypes_kEvent, + Steinberg_Vst_MediaTypes_kNumMediaTypes +} Steinberg_Vst_MediaTypes; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcomponent.h", line 74 */ + +typedef enum +{ + Steinberg_Vst_BusDirections_kInput = 0, + Steinberg_Vst_BusDirections_kOutput +} Steinberg_Vst_BusDirections; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcomponent.h", line 82 */ + +typedef enum +{ + Steinberg_Vst_BusTypes_kMain = 0, + Steinberg_Vst_BusTypes_kAux +} Steinberg_Vst_BusTypes; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcomponent.h", line 104 */ + +typedef enum +{ + Steinberg_Vst_BusInfo_BusFlags_kDefaultActive = 1 << 0, + Steinberg_Vst_BusInfo_BusFlags_kIsControlVoltage = 1 << 1 +} Steinberg_Vst_BusInfo_BusFlags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcomponent.h", line 122 */ + +typedef enum +{ + Steinberg_Vst_IoModes_kSimple = 0, + Steinberg_Vst_IoModes_kAdvanced, + Steinberg_Vst_IoModes_kOfflineProcessing +} Steinberg_Vst_IoModes; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 67 */ + +typedef enum +{ + Steinberg_Vst_ParameterInfo_ParameterFlags_kNoFlags = 0, + Steinberg_Vst_ParameterInfo_ParameterFlags_kCanAutomate = 1 << 0, + Steinberg_Vst_ParameterInfo_ParameterFlags_kIsReadOnly = 1 << 1, + Steinberg_Vst_ParameterInfo_ParameterFlags_kIsWrapAround = 1 << 2, + Steinberg_Vst_ParameterInfo_ParameterFlags_kIsList = 1 << 3, + Steinberg_Vst_ParameterInfo_ParameterFlags_kIsHidden = 1 << 4, + Steinberg_Vst_ParameterInfo_ParameterFlags_kIsProgramChange = 1 << 15, + Steinberg_Vst_ParameterInfo_ParameterFlags_kIsBypass = 1 << 16 +} Steinberg_Vst_ParameterInfo_ParameterFlags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 116 */ + +typedef enum +{ + Steinberg_Vst_RestartFlags_kReloadComponent = 1 << 0, + Steinberg_Vst_RestartFlags_kIoChanged = 1 << 1, + Steinberg_Vst_RestartFlags_kParamValuesChanged = 1 << 2, + Steinberg_Vst_RestartFlags_kLatencyChanged = 1 << 3, + Steinberg_Vst_RestartFlags_kParamTitlesChanged = 1 << 4, + Steinberg_Vst_RestartFlags_kMidiCCAssignmentChanged = 1 << 5, + Steinberg_Vst_RestartFlags_kNoteExpressionChanged = 1 << 6, + Steinberg_Vst_RestartFlags_kIoTitlesChanged = 1 << 7, + Steinberg_Vst_RestartFlags_kPrefetchableSupportChanged = 1 << 8, + Steinberg_Vst_RestartFlags_kRoutingInfoChanged = 1 << 9, + Steinberg_Vst_RestartFlags_kKeyswitchChanged = 1 << 10, + Steinberg_Vst_RestartFlags_kParamIDMappingChanged = 1 << 11 +} Steinberg_Vst_RestartFlags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 426 */ + +typedef enum +{ + Steinberg_Vst_IProgress_ProgressType_AsyncStateRestoration = 0, + Steinberg_Vst_IProgress_ProgressType_UIBackgroundTask +} Steinberg_Vst_IProgress_ProgressType; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 555 */ + +typedef enum +{ + Steinberg_Vst_KnobModes_kCircularMode = 0, + Steinberg_Vst_KnobModes_kRelativCircularMode, + Steinberg_Vst_KnobModes_kLinearMode +} Steinberg_Vst_KnobModes; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstprocesscontext.h", line 47 */ + +typedef enum +{ + Steinberg_Vst_FrameRate_FrameRateFlags_kPullDownRate = 1 << 0, + Steinberg_Vst_FrameRate_FrameRateFlags_kDropRate = 1 << 1 +} Steinberg_Vst_FrameRate_FrameRateFlags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstprocesscontext.h", line 79 */ + +typedef enum +{ + Steinberg_Vst_Chord_Masks_kChordMask = 0x0FFF, + Steinberg_Vst_Chord_Masks_kReservedMask = 0xF000 +} Steinberg_Vst_Chord_Masks; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstprocesscontext.h", line 100 */ + +typedef enum +{ + Steinberg_Vst_ProcessContext_StatesAndFlags_kPlaying = 1 << 1, + Steinberg_Vst_ProcessContext_StatesAndFlags_kCycleActive = 1 << 2, + Steinberg_Vst_ProcessContext_StatesAndFlags_kRecording = 1 << 3, + Steinberg_Vst_ProcessContext_StatesAndFlags_kSystemTimeValid = 1 << 8, + Steinberg_Vst_ProcessContext_StatesAndFlags_kContTimeValid = 1 << 17, + Steinberg_Vst_ProcessContext_StatesAndFlags_kProjectTimeMusicValid = 1 << 9, + Steinberg_Vst_ProcessContext_StatesAndFlags_kBarPositionValid = 1 << 11, + Steinberg_Vst_ProcessContext_StatesAndFlags_kCycleValid = 1 << 12, + Steinberg_Vst_ProcessContext_StatesAndFlags_kTempoValid = 1 << 10, + Steinberg_Vst_ProcessContext_StatesAndFlags_kTimeSigValid = 1 << 13, + Steinberg_Vst_ProcessContext_StatesAndFlags_kChordValid = 1 << 18, + Steinberg_Vst_ProcessContext_StatesAndFlags_kSmpteValid = 1 << 14, + Steinberg_Vst_ProcessContext_StatesAndFlags_kClockValid = 1 << 15 +} Steinberg_Vst_ProcessContext_StatesAndFlags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 32 */ + +typedef enum +{ + Steinberg_Vst_NoteIDUserRange_kNoteIDUserRangeLowerBound = -10000, + Steinberg_Vst_NoteIDUserRange_kNoteIDUserRangeUpperBound = -1000 +} Steinberg_Vst_NoteIDUserRange; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 77 */ + +typedef enum +{ + Steinberg_Vst_DataEvent_DataTypes_kMidiSysEx = 0 +} Steinberg_Vst_DataEvent_DataTypes; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 150 */ + +typedef enum +{ + Steinberg_Vst_Event_EventFlags_kIsLive = 1 << 0, + Steinberg_Vst_Event_EventFlags_kUserReserved1 = 1 << 14, + Steinberg_Vst_Event_EventFlags_kUserReserved2 = 1 << 15 +} Steinberg_Vst_Event_EventFlags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 159 */ + +typedef enum +{ + Steinberg_Vst_Event_EventTypes_kNoteOnEvent = 0, + Steinberg_Vst_Event_EventTypes_kNoteOffEvent = 1, + Steinberg_Vst_Event_EventTypes_kDataEvent = 2, + Steinberg_Vst_Event_EventTypes_kPolyPressureEvent = 3, + Steinberg_Vst_Event_EventTypes_kNoteExpressionValueEvent = 4, + Steinberg_Vst_Event_EventTypes_kNoteExpressionTextEvent = 5, + Steinberg_Vst_Event_EventTypes_kChordEvent = 6, + Steinberg_Vst_Event_EventTypes_kScaleEvent = 7, + Steinberg_Vst_Event_EventTypes_kNoteExpressionIntValueEvent = 8, + Steinberg_Vst_Event_EventTypes_kLegacyMIDICCOutEvent = 65535 +} Steinberg_Vst_Event_EventTypes; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcontextmenu.h", line 174 */ + +typedef enum +{ + Steinberg_Vst_IContextMenuItem_Flags_kIsSeparator = 1 << 0, + Steinberg_Vst_IContextMenuItem_Flags_kIsDisabled = 1 << 1, + Steinberg_Vst_IContextMenuItem_Flags_kIsChecked = 1 << 2, + Steinberg_Vst_IContextMenuItem_Flags_kIsGroupStart = 1 << 3 | Steinberg_Vst_IContextMenuItem_Flags_kIsDisabled, + Steinberg_Vst_IContextMenuItem_Flags_kIsGroupEnd = 1 << 4 | Steinberg_Vst_IContextMenuItem_Flags_kIsSeparator +} Steinberg_Vst_IContextMenuItem_Flags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmidicontrollers.h", line 25 */ + +typedef enum +{ + Steinberg_Vst_ControllerNumbers_kCtrlBankSelectMSB = 0, + Steinberg_Vst_ControllerNumbers_kCtrlModWheel = 1, + Steinberg_Vst_ControllerNumbers_kCtrlBreath = 2, + Steinberg_Vst_ControllerNumbers_kCtrlFoot = 4, + Steinberg_Vst_ControllerNumbers_kCtrlPortaTime = 5, + Steinberg_Vst_ControllerNumbers_kCtrlDataEntryMSB = 6, + Steinberg_Vst_ControllerNumbers_kCtrlVolume = 7, + Steinberg_Vst_ControllerNumbers_kCtrlBalance = 8, + Steinberg_Vst_ControllerNumbers_kCtrlPan = 10, + Steinberg_Vst_ControllerNumbers_kCtrlExpression = 11, + Steinberg_Vst_ControllerNumbers_kCtrlEffect1 = 12, + Steinberg_Vst_ControllerNumbers_kCtrlEffect2 = 13, + Steinberg_Vst_ControllerNumbers_kCtrlGPC1 = 16, + Steinberg_Vst_ControllerNumbers_kCtrlGPC2 = 17, + Steinberg_Vst_ControllerNumbers_kCtrlGPC3 = 18, + Steinberg_Vst_ControllerNumbers_kCtrlGPC4 = 19, + Steinberg_Vst_ControllerNumbers_kCtrlBankSelectLSB = 32, + Steinberg_Vst_ControllerNumbers_kCtrlDataEntryLSB = 38, + Steinberg_Vst_ControllerNumbers_kCtrlSustainOnOff = 64, + Steinberg_Vst_ControllerNumbers_kCtrlPortaOnOff = 65, + Steinberg_Vst_ControllerNumbers_kCtrlSustenutoOnOff = 66, + Steinberg_Vst_ControllerNumbers_kCtrlSoftPedalOnOff = 67, + Steinberg_Vst_ControllerNumbers_kCtrlLegatoFootSwOnOff = 68, + Steinberg_Vst_ControllerNumbers_kCtrlHold2OnOff = 69, + Steinberg_Vst_ControllerNumbers_kCtrlSoundVariation = 70, + Steinberg_Vst_ControllerNumbers_kCtrlFilterCutoff = 71, + Steinberg_Vst_ControllerNumbers_kCtrlReleaseTime = 72, + Steinberg_Vst_ControllerNumbers_kCtrlAttackTime = 73, + Steinberg_Vst_ControllerNumbers_kCtrlFilterResonance = 74, + Steinberg_Vst_ControllerNumbers_kCtrlDecayTime = 75, + Steinberg_Vst_ControllerNumbers_kCtrlVibratoRate = 76, + Steinberg_Vst_ControllerNumbers_kCtrlVibratoDepth = 77, + Steinberg_Vst_ControllerNumbers_kCtrlVibratoDelay = 78, + Steinberg_Vst_ControllerNumbers_kCtrlSoundCtrler10 = 79, + Steinberg_Vst_ControllerNumbers_kCtrlGPC5 = 80, + Steinberg_Vst_ControllerNumbers_kCtrlGPC6 = 81, + Steinberg_Vst_ControllerNumbers_kCtrlGPC7 = 82, + Steinberg_Vst_ControllerNumbers_kCtrlGPC8 = 83, + Steinberg_Vst_ControllerNumbers_kCtrlPortaControl = 84, + Steinberg_Vst_ControllerNumbers_kCtrlEff1Depth = 91, + Steinberg_Vst_ControllerNumbers_kCtrlEff2Depth = 92, + Steinberg_Vst_ControllerNumbers_kCtrlEff3Depth = 93, + Steinberg_Vst_ControllerNumbers_kCtrlEff4Depth = 94, + Steinberg_Vst_ControllerNumbers_kCtrlEff5Depth = 95, + Steinberg_Vst_ControllerNumbers_kCtrlDataIncrement = 96, + Steinberg_Vst_ControllerNumbers_kCtrlDataDecrement = 97, + Steinberg_Vst_ControllerNumbers_kCtrlNRPNSelectLSB = 98, + Steinberg_Vst_ControllerNumbers_kCtrlNRPNSelectMSB = 99, + Steinberg_Vst_ControllerNumbers_kCtrlRPNSelectLSB = 100, + Steinberg_Vst_ControllerNumbers_kCtrlRPNSelectMSB = 101, + Steinberg_Vst_ControllerNumbers_kCtrlAllSoundsOff = 120, + Steinberg_Vst_ControllerNumbers_kCtrlResetAllCtrlers = 121, + Steinberg_Vst_ControllerNumbers_kCtrlLocalCtrlOnOff = 122, + Steinberg_Vst_ControllerNumbers_kCtrlAllNotesOff = 123, + Steinberg_Vst_ControllerNumbers_kCtrlOmniModeOff = 124, + Steinberg_Vst_ControllerNumbers_kCtrlOmniModeOn = 125, + Steinberg_Vst_ControllerNumbers_kCtrlPolyModeOnOff = 126, + Steinberg_Vst_ControllerNumbers_kCtrlPolyModeOn = 127, + Steinberg_Vst_ControllerNumbers_kAfterTouch = 128, + Steinberg_Vst_ControllerNumbers_kPitchBend = 129, + Steinberg_Vst_ControllerNumbers_kCountCtrlNumber, + Steinberg_Vst_ControllerNumbers_kCtrlProgramChange = 130, + Steinberg_Vst_ControllerNumbers_kCtrlPolyPressure = 131, + Steinberg_Vst_ControllerNumbers_kCtrlQuarterFrame = 132, + Steinberg_Vst_ControllerNumbers_kSystemSongSelect = 133, + Steinberg_Vst_ControllerNumbers_kSystemSongPointer = 134, + Steinberg_Vst_ControllerNumbers_kSystemCableSelect = 135, + Steinberg_Vst_ControllerNumbers_kSystemTuneRequest = 136, + Steinberg_Vst_ControllerNumbers_kSystemMidiClockStart = 137, + Steinberg_Vst_ControllerNumbers_kSystemMidiClockContinue = 138, + Steinberg_Vst_ControllerNumbers_kSystemMidiClockStop = 139, + Steinberg_Vst_ControllerNumbers_kSystemActiveSensing = 140 +} Steinberg_Vst_ControllerNumbers; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstchannelcontextinfo.h", line 170 */ + +typedef enum +{ + Steinberg_Vst_ChannelContext_ChannelPluginLocation_kPreVolumeFader = 0, + Steinberg_Vst_ChannelContext_ChannelPluginLocation_kPostVolumeFader, + Steinberg_Vst_ChannelContext_ChannelPluginLocation_kUsedAsPanner +} Steinberg_Vst_ChannelContext_ChannelPluginLocation; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstprefetchablesupport.h", line 38 */ + +typedef enum +{ + Steinberg_Vst_ePrefetchableSupport_kIsNeverPrefetchable = 0, + Steinberg_Vst_ePrefetchableSupport_kIsYetPrefetchable, + Steinberg_Vst_ePrefetchableSupport_kIsNotYetPrefetchable, + Steinberg_Vst_ePrefetchableSupport_kNumPrefetchableSupport +} Steinberg_Vst_ePrefetchableSupport; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstautomationstate.h", line 43 */ + +typedef enum +{ + Steinberg_Vst_IAutomationState_AutomationStates_kNoAutomation = 0, + Steinberg_Vst_IAutomationState_AutomationStates_kReadState = 1 << 0, + Steinberg_Vst_IAutomationState_AutomationStates_kWriteState = 1 << 1, + Steinberg_Vst_IAutomationState_AutomationStates_kReadWriteState = Steinberg_Vst_IAutomationState_AutomationStates_kReadState | Steinberg_Vst_IAutomationState_AutomationStates_kWriteState +} Steinberg_Vst_IAutomationState_AutomationStates; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 101 */ + +typedef enum +{ + Steinberg_Vst_ComponentFlags_kDistributable = 1 << 0, + Steinberg_Vst_ComponentFlags_kSimpleModeSupported = 1 << 1 +} Steinberg_Vst_ComponentFlags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 113 */ + +typedef enum +{ + Steinberg_Vst_SymbolicSampleSizes_kSample32, + Steinberg_Vst_SymbolicSampleSizes_kSample64 +} Steinberg_Vst_SymbolicSampleSizes; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 147 */ + +typedef enum +{ + Steinberg_Vst_ProcessModes_kRealtime, + Steinberg_Vst_ProcessModes_kPrefetch, + Steinberg_Vst_ProcessModes_kOffline +} Steinberg_Vst_ProcessModes; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 440 */ + +typedef enum +{ + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedSystemTime = 1 << 0, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedContinousTimeSamples = 1 << 1, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedProjectTimeMusic = 1 << 2, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedBarPositionMusic = 1 << 3, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedCycleMusic = 1 << 4, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedSamplesToNextClock = 1 << 5, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedTempo = 1 << 6, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedTimeSignature = 1 << 7, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedChord = 1 << 8, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedFrameRate = 1 << 9, + Steinberg_Vst_IProcessContextRequirements_Flags_kNeedTransportState = 1 << 10 +} Steinberg_Vst_IProcessContextRequirements_Flags; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteonorchestralarticulationinfo.h", line 70 */ + +typedef enum +{ + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kCoreSoundSustainAndStrikes = 0, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kStaccatosAndShorts = 1, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kSameNoteTrillsRepeats = 2, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kIntervallicTrills = 3, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kAdditionalColors = 4, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kPitchAndDynamicGestures = 5, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kScalesRunsAndArpeggios = 6, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kEffectsAndNoises = 7, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kReserved1 = 8, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kReserved2 = 9, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kCustomNoteOn1 = 10, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kCustomNoteOn2 = 11, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kCustomNoteOn3 = 12, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kCustomNoteOn4 = 13, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kCustomNoteOn5 = 14, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kCustomNoteOn6 = 15, + Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification_kReserved3 = 16 +} Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_Classification; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsttransportcontrol.h", line 32 */ + +typedef enum +{ + Steinberg_Vst_TransportPositionType_Samples, + Steinberg_Vst_TransportPositionType_QuarterNotes +} Steinberg_Vst_TransportPositionType; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsttransportcontrol.h", line 105 */ + +typedef enum +{ + Steinberg_Vst_ITransportControl_Action_Locate = 0, + Steinberg_Vst_ITransportControl_Action_PlaybackStart, + Steinberg_Vst_ITransportControl_Action_PlaybackStop, + Steinberg_Vst_ITransportControl_Action_LocateAndPlaybackStart, + Steinberg_Vst_ITransportControl_Action_PlaybackStopAndLocate, + Steinberg_Vst_ITransportControl_Action_RecordOnPlaybackStart, + Steinberg_Vst_ITransportControl_Action_LocateAndRecordOnPlaybackStart, + Steinberg_Vst_ITransportControl_Action_RecordOff, + Steinberg_Vst_ITransportControl_Action_RecordOffPlaybackStop, + Steinberg_Vst_ITransportControl_Action_RecordOffPlaybackStopAndLocate, + Steinberg_Vst_ITransportControl_Action_SetCycleStart, + Steinberg_Vst_ITransportControl_Action_SetCycleEnd, + Steinberg_Vst_ITransportControl_Action_CycleOn, + Steinberg_Vst_ITransportControl_Action_CycleOff +} Steinberg_Vst_ITransportControl_Action; + + +/*---------------------------------------------------------------------------------------------------------------------- +----- Variable declarations -------------------------------------------------------------------------------------------- +----------------------------------------------------------------------------------------------------------------------*/ + +static const Steinberg_int32 Steinberg_kMaxInt32 = INT32_MAX; +static const Steinberg_int32 Steinberg_kMinInt32 = INT32_MIN; +static const Steinberg_int32 Steinberg_kMaxLong = INT32_MAX; +static const Steinberg_int32 Steinberg_kMinLong = INT32_MIN; +static const Steinberg_uint32 Steinberg_kMaxInt32u = UINT32_MAX; +static const Steinberg_int64 Steinberg_kMaxInt64 = INT64_MAX; +static const Steinberg_int64 Steinberg_kMinInt64 = INT64_MIN; +static const Steinberg_uint64 Steinberg_kMaxInt64u = UINT64_MAX; +static const Steinberg_FIDString Steinberg_kPlatformStringWin = "WIN"; +static const Steinberg_FIDString Steinberg_kPlatformStringMac = "MAC"; +static const Steinberg_FIDString Steinberg_kPlatformStringIOS = "IOS"; +static const Steinberg_FIDString Steinberg_kPlatformStringLinux = "Linux"; +static const Steinberg_FIDString Steinberg_kPlatformString = "MAC"; +static const Steinberg_UCoord Steinberg_kMaxCoord = ((Steinberg_UCoord) 0x7FFFFFFF); +static const Steinberg_UCoord Steinberg_kMinCoord = ((Steinberg_UCoord) -0x7FFFFFFF); +static const Steinberg_FIDString Steinberg_kPlatformTypeHWND = "HWND"; +static const Steinberg_FIDString Steinberg_kPlatformTypeHIView = "HIView"; +static const Steinberg_FIDString Steinberg_kPlatformTypeNSView = "NSView"; +static const Steinberg_FIDString Steinberg_kPlatformTypeUIView = "UIView"; +static const Steinberg_FIDString Steinberg_kPlatformTypeX11EmbedWindowID = "X11EmbedWindowID"; +static const Steinberg_FIDString Steinberg_kPlatformTypeWaylandSurfaceID = "WaylandSurfaceID"; +static const Steinberg_uint32 Steinberg_kPrintfBufferSize = 4096; +static const Steinberg_Vst_ParamID Steinberg_Vst_kNoParamId = 0xFFFFFFFF; +static const Steinberg_Vst_ParamID Steinberg_Vst_kMinParamId = 0; +static const Steinberg_Vst_ParamID Steinberg_Vst_kMaxParamId = 0x7FFFFFFF; +static const Steinberg_int32 Steinberg_Vst_kStepCountContinuous = 0; +static const Steinberg_int32 Steinberg_Vst_kStepCountToggle = 1; +static const Steinberg_FIDString Steinberg_Vst_SDKVersionString = "VST 3.8.1"; +static const Steinberg_uint32 Steinberg_Vst_SDKVersionMajor = 3; +static const Steinberg_uint32 Steinberg_Vst_SDKVersionMinor = 8; +static const Steinberg_uint32 Steinberg_Vst_SDKVersionSub = 1; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion = ((3 << 16) | (8 << 8) | 1); +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_8_0 = 0x030800; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_14 = 0x03070E; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_13 = 0x03070D; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_12 = 0x03070C; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_11 = 0x03070B; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_10 = 0x03070A; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_9 = 0x030709; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_8 = 0x030708; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_7 = 0x030707; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_6 = 0x030706; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_5 = 0x030705; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_4 = 0x030704; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_3 = 0x030703; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_2 = 0x030702; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_1 = 0x030701; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_7_0 = 0x030700; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_14 = 0x03060E; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_13 = 0x03060D; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_12 = 0x03060C; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_11 = 0x03060B; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_10 = 0x03060A; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_9 = 0x030609; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_8 = 0x030608; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_7 = 0x030607; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_6 = 0x030606; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_5 = 0x030605; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_6_0 = 0x030600; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_5_0 = 0x030500; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_1_0 = 0x030100; +static const Steinberg_uint32 Steinberg_Vst_SDKVersion_3_0_0 = 0x030000; +static const Steinberg_int32 Steinberg_Vst_kDefaultFactoryFlags = 1 << 4; +static const Steinberg_Vst_CString Steinberg_Vst_PresetAttributes_kPlugInName = "PlugInName"; +static const Steinberg_Vst_CString Steinberg_Vst_PresetAttributes_kPlugInCategory = "PlugInCategory"; +static const Steinberg_Vst_CString Steinberg_Vst_PresetAttributes_kInstrument = "MusicalInstrument"; +static const Steinberg_Vst_CString Steinberg_Vst_PresetAttributes_kStyle = "MusicalStyle"; +static const Steinberg_Vst_CString Steinberg_Vst_PresetAttributes_kCharacter = "MusicalCharacter"; +static const Steinberg_Vst_CString Steinberg_Vst_PresetAttributes_kStateType = "StateType"; +static const Steinberg_Vst_CString Steinberg_Vst_PresetAttributes_kFilePathStringType = "FilePathString"; +static const Steinberg_Vst_CString Steinberg_Vst_PresetAttributes_kName = "Name"; +static const Steinberg_Vst_CString Steinberg_Vst_PresetAttributes_kFileName = "FileName"; +static const Steinberg_Vst_CString Steinberg_Vst_StateType_kProject = "Project"; +static const Steinberg_Vst_CString Steinberg_Vst_StateType_kDefault = "Default"; +static const Steinberg_Vst_CString Steinberg_Vst_StateType_kTrackPreset = "TrackPreset"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kAccordion = "Accordion"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kAccordionAccordion = "Accordion|Accordion"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kAccordionHarmonica = "Accordion|Harmonica"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kAccordionOther = "Accordion|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBass = "Bass"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBassABass = "Bass|A. Bass"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBassEBass = "Bass|E. Bass"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBassSynthBass = "Bass|Synth Bass"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBassOther = "Bass|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBrass = "Brass"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBrassFrenchHorn = "Brass|French Horn"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBrassTrumpet = "Brass|Trumpet"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBrassTrombone = "Brass|Trombone"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBrassTuba = "Brass|Tuba"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBrassSection = "Brass|Section"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBrassSynth = "Brass|Synth"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kBrassOther = "Brass|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kChromaticPerc = "Chromatic Perc"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kChromaticPercBell = "Chromatic Perc|Bell"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kChromaticPercMallett = "Chromatic Perc|Mallett"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kChromaticPercWood = "Chromatic Perc|Wood"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kChromaticPercPercussion = "Chromatic Perc|Percussion"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kChromaticPercTimpani = "Chromatic Perc|Timpani"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kChromaticPercOther = "Chromatic Perc|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPerc = "Drum&Perc"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercDrumsetGM = "Drum&Perc|Drumset GM"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercDrumset = "Drum&Perc|Drumset"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercDrumMenues = "Drum&Perc|Drum Menues"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercBeats = "Drum&Perc|Beats"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercPercussion = "Drum&Perc|Percussion"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercKickDrum = "Drum&Perc|Kick Drum"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercSnareDrum = "Drum&Perc|Snare Drum"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercToms = "Drum&Perc|Toms"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercHiHats = "Drum&Perc|HiHats"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercCymbals = "Drum&Perc|Cymbals"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kDrumPercOther = "Drum&Perc|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kEthnic = "Ethnic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kEthnicAsian = "Ethnic|Asian"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kEthnicAfrican = "Ethnic|African"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kEthnicEuropean = "Ethnic|European"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kEthnicLatin = "Ethnic|Latin"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kEthnicAmerican = "Ethnic|American"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kEthnicAlien = "Ethnic|Alien"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kEthnicOther = "Ethnic|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kGuitar = "Guitar/Plucked"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kGuitarAGuitar = "Guitar/Plucked|A. Guitar"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kGuitarEGuitar = "Guitar/Plucked|E. Guitar"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kGuitarHarp = "Guitar/Plucked|Harp"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kGuitarEthnic = "Guitar/Plucked|Ethnic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kGuitarOther = "Guitar/Plucked|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kKeyboard = "Keyboard"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kKeyboardClavi = "Keyboard|Clavi"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kKeyboardEPiano = "Keyboard|E. Piano"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kKeyboardHarpsichord = "Keyboard|Harpsichord"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kKeyboardOther = "Keyboard|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kMusicalFX = "Musical FX"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kMusicalFXHitsStabs = "Musical FX|Hits&Stabs"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kMusicalFXMotion = "Musical FX|Motion"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kMusicalFXSweeps = "Musical FX|Sweeps"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kMusicalFXBeepsBlips = "Musical FX|Beeps&Blips"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kMusicalFXScratches = "Musical FX|Scratches"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kMusicalFXOther = "Musical FX|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kOrgan = "Organ"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kOrganElectric = "Organ|Electric"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kOrganPipe = "Organ|Pipe"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kOrganOther = "Organ|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kPiano = "Piano"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kPianoAPiano = "Piano|A. Piano"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kPianoEGrand = "Piano|E. Grand"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kPianoOther = "Piano|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSoundFX = "Sound FX"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSoundFXNature = "Sound FX|Nature"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSoundFXMechanical = "Sound FX|Mechanical"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSoundFXSynthetic = "Sound FX|Synthetic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSoundFXOther = "Sound FX|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kStrings = "Strings"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kStringsViolin = "Strings|Violin"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kStringsViola = "Strings|Viola"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kStringsCello = "Strings|Cello"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kStringsBass = "Strings|Bass"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kStringsSection = "Strings|Section"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kStringsSynth = "Strings|Synth"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kStringsOther = "Strings|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthLead = "Synth Lead"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthLeadAnalog = "Synth Lead|Analog"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthLeadDigital = "Synth Lead|Digital"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthLeadArpeggio = "Synth Lead|Arpeggio"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthLeadOther = "Synth Lead|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthPad = "Synth Pad"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthPadSynthChoir = "Synth Pad|Synth Choir"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthPadAnalog = "Synth Pad|Analog"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthPadDigital = "Synth Pad|Digital"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthPadMotion = "Synth Pad|Motion"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthPadOther = "Synth Pad|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthComp = "Synth Comp"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthCompAnalog = "Synth Comp|Analog"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthCompDigital = "Synth Comp|Digital"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kSynthCompOther = "Synth Comp|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kVocal = "Vocal"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kVocalLeadVocal = "Vocal|Lead Vocal"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kVocalAdlibs = "Vocal|Adlibs"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kVocalChoir = "Vocal|Choir"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kVocalSolo = "Vocal|Solo"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kVocalFX = "Vocal|FX"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kVocalSpoken = "Vocal|Spoken"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kVocalOther = "Vocal|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kWoodwinds = "Woodwinds"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kWoodwindsEthnic = "Woodwinds|Ethnic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kWoodwindsFlute = "Woodwinds|Flute"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kWoodwindsOboe = "Woodwinds|Oboe"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kWoodwindsEnglHorn = "Woodwinds|Engl. Horn"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kWoodwindsClarinet = "Woodwinds|Clarinet"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kWoodwindsSaxophone = "Woodwinds|Saxophone"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kWoodwindsBassoon = "Woodwinds|Bassoon"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalInstrument_kWoodwindsOther = "Woodwinds|Other"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAlternativeIndie = "Alternative/Indie"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAlternativeIndieGothRock = "Alternative/Indie|Goth Rock"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAlternativeIndieGrunge = "Alternative/Indie|Grunge"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAlternativeIndieNewWave = "Alternative/Indie|New Wave"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAlternativeIndiePunk = "Alternative/Indie|Punk"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAlternativeIndieCollegeRock = "Alternative/Indie|College Rock"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAlternativeIndieDarkWave = "Alternative/Indie|Dark Wave"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAlternativeIndieHardcore = "Alternative/Indie|Hardcore"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAmbientChillOut = "Ambient/ChillOut"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAmbientChillOutNewAgeMeditation = "Ambient/ChillOut|New Age/Meditation"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAmbientChillOutDarkAmbient = "Ambient/ChillOut|Dark Ambient"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAmbientChillOutDowntempo = "Ambient/ChillOut|Downtempo"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kAmbientChillOutLounge = "Ambient/ChillOut|Lounge"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kBlues = "Blues"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kBluesAcousticBlues = "Blues|Acoustic Blues"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kBluesCountryBlues = "Blues|Country Blues"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kBluesElectricBlues = "Blues|Electric Blues"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kBluesChicagoBlues = "Blues|Chicago Blues"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassical = "Classical"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalBaroque = "Classical|Baroque"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalChamberMusic = "Classical|Chamber Music"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalMedieval = "Classical|Medieval"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalModernComposition = "Classical|Modern Composition"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalOpera = "Classical|Opera"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalGregorian = "Classical|Gregorian"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalRenaissance = "Classical|Renaissance"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalClassic = "Classical|Classic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalRomantic = "Classical|Romantic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kClassicalSoundtrack = "Classical|Soundtrack"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kCountry = "Country"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kCountryCountryWestern = "Country|Country/Western"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kCountryHonkyTonk = "Country|Honky Tonk"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kCountryUrbanCowboy = "Country|Urban Cowboy"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kCountryBluegrass = "Country|Bluegrass"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kCountryAmericana = "Country|Americana"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kCountrySquaredance = "Country|Squaredance"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kCountryNorthAmericanFolk = "Country|North American Folk"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDance = "Electronica/Dance"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceMinimal = "Electronica/Dance|Minimal"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceClassicHouse = "Electronica/Dance|Classic House"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceElektroHouse = "Electronica/Dance|Elektro House"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceFunkyHouse = "Electronica/Dance|Funky House"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceIndustrial = "Electronica/Dance|Industrial"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceElectronicBodyMusic = "Electronica/Dance|Electronic Body Music"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceTripHop = "Electronica/Dance|Trip Hop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceTechno = "Electronica/Dance|Techno"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceDrumNBassJungle = "Electronica/Dance|Drum'n'Bass/Jungle"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceElektro = "Electronica/Dance|Elektro"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceTrance = "Electronica/Dance|Trance"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceDub = "Electronica/Dance|Dub"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kElectronicaDanceBigBeats = "Electronica/Dance|Big Beats"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kExperimental = "Experimental"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kExperimentalNewMusic = "Experimental|New Music"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kExperimentalFreeImprovisation = "Experimental|Free Improvisation"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kExperimentalElectronicArtMusic = "Experimental|Electronic Art Music"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kExperimentalNoise = "Experimental|Noise"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kJazz = "Jazz"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kJazzNewOrleansJazz = "Jazz|New Orleans Jazz"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kJazzTraditionalJazz = "Jazz|Traditional Jazz"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kJazzOldtimeJazzDixiland = "Jazz|Oldtime Jazz/Dixiland"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kJazzFusion = "Jazz|Fusion"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kJazzAvantgarde = "Jazz|Avantgarde"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kJazzLatinJazz = "Jazz|Latin Jazz"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kJazzFreeJazz = "Jazz|Free Jazz"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kJazzRagtime = "Jazz|Ragtime"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kPop = "Pop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kPopBritpop = "Pop|Britpop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kPopRock = "Pop|Pop/Rock"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kPopTeenPop = "Pop|Teen Pop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kPopChartDance = "Pop|Chart Dance"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kPop80sPop = "Pop|80's Pop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kPopDancehall = "Pop|Dancehall"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kPopDisco = "Pop|Disco"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetal = "Rock/Metal"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalBluesRock = "Rock/Metal|Blues Rock"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalClassicRock = "Rock/Metal|Classic Rock"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalHardRock = "Rock/Metal|Hard Rock"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalRockRoll = "Rock/Metal|Rock & Roll"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalSingerSongwriter = "Rock/Metal|Singer/Songwriter"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalHeavyMetal = "Rock/Metal|Heavy Metal"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalDeathBlackMetal = "Rock/Metal|Death/Black Metal"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalNuMetal = "Rock/Metal|NuMetal"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalReggae = "Rock/Metal|Reggae"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalBallad = "Rock/Metal|Ballad"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalAlternativeRock = "Rock/Metal|Alternative Rock"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalRockabilly = "Rock/Metal|Rockabilly"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalThrashMetal = "Rock/Metal|Thrash Metal"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kRockMetalProgressiveRock = "Rock/Metal|Progressive Rock"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kUrbanHipHopRB = "Urban (Hip-Hop / R&B)"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kUrbanHipHopRBClassic = "Urban (Hip-Hop / R&B)|Classic R&B"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kUrbanHipHopRBModern = "Urban (Hip-Hop / R&B)|Modern R&B"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kUrbanHipHopRBPop = "Urban (Hip-Hop / R&B)|R&B Pop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kUrbanHipHopRBWestCoastHipHop = "Urban (Hip-Hop / R&B)|WestCoast Hip-Hop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kUrbanHipHopRBEastCoastHipHop = "Urban (Hip-Hop / R&B)|EastCoast Hip-Hop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kUrbanHipHopRBRapHipHop = "Urban (Hip-Hop / R&B)|Rap/Hip Hop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kUrbanHipHopRBSoul = "Urban (Hip-Hop / R&B)|Soul"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kUrbanHipHopRBFunk = "Urban (Hip-Hop / R&B)|Funk"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnic = "World/Ethnic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicAfrica = "World/Ethnic|Africa"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicAsia = "World/Ethnic|Asia"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicCeltic = "World/Ethnic|Celtic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicEurope = "World/Ethnic|Europe"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicKlezmer = "World/Ethnic|Klezmer"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicScandinavia = "World/Ethnic|Scandinavia"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicEasternEurope = "World/Ethnic|Eastern Europe"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicIndiaOriental = "World/Ethnic|India/Oriental"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicNorthAmerica = "World/Ethnic|North America"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicSouthAmerica = "World/Ethnic|South America"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalStyle_kWorldEthnicAustralia = "World/Ethnic|Australia"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kMono = "Mono"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kPoly = "Poly"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kSplit = "Split"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kLayer = "Layer"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kGlide = "Glide"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kGlissando = "Glissando"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kMajor = "Major"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kMinor = "Minor"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kSingle = "Single"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kEnsemble = "Ensemble"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kAcoustic = "Acoustic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kElectric = "Electric"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kAnalog = "Analog"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kDigital = "Digital"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kVintage = "Vintage"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kModern = "Modern"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kOld = "Old"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kNew = "New"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kClean = "Clean"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kDistorted = "Distorted"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kDry = "Dry"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kProcessed = "Processed"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kHarmonic = "Harmonic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kDissonant = "Dissonant"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kClear = "Clear"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kNoisy = "Noisy"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kThin = "Thin"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kRich = "Rich"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kDark = "Dark"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kBright = "Bright"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kCold = "Cold"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kWarm = "Warm"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kMetallic = "Metallic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kWooden = "Wooden"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kGlass = "Glass"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kPlastic = "Plastic"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kPercussive = "Percussive"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kSoft = "Soft"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kFast = "Fast"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kSlow = "Slow"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kShort = "Short"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kLong = "Long"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kAttack = "Attack"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kRelease = "Release"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kDecay = "Decay"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kSustain = "Sustain"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kFastAttack = "Fast Attack"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kSlowAttack = "Slow Attack"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kShortRelease = "Short Release"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kLongRelease = "Long Release"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kStatic = "Static"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kMoving = "Moving"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kLoop = "Loop"; +static const Steinberg_Vst_CString Steinberg_Vst_MusicalCharacter_kOneShot = "One Shot"; +static const Steinberg_Vst_CString Steinberg_Vst_ViewType_kEditor = "editor"; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerL = 1 << 0; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerR = 1 << 1; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerC = 1 << 2; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerLfe = 1 << 3; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerLs = 1 << 4; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerRs = 1 << 5; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerLc = 1 << 6; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerRc = 1 << 7; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerS = 1 << 8; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerCs = 1 << 8; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerSl = 1 << 9; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerSr = 1 << 10; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerTc = 1 << 11; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerTfl = 1 << 12; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerTfc = 1 << 13; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerTfr = 1 << 14; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerTrl = 1 << 15; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerTrc = 1 << 16; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerTrr = 1 << 17; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerLfe2 = 1 << 18; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerM = 1 << 19; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN0 = (Steinberg_Vst_Speaker) 1 << 20; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN1 = (Steinberg_Vst_Speaker) 1 << 21; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN2 = (Steinberg_Vst_Speaker) 1 << 22; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN3 = (Steinberg_Vst_Speaker) 1 << 23; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN4 = (Steinberg_Vst_Speaker) 1 << 38; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN5 = (Steinberg_Vst_Speaker) 1 << 39; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN6 = (Steinberg_Vst_Speaker) 1 << 40; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN7 = (Steinberg_Vst_Speaker) 1 << 41; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN8 = (Steinberg_Vst_Speaker) 1 << 42; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN9 = (Steinberg_Vst_Speaker) 1 << 43; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN10 = (Steinberg_Vst_Speaker) 1 << 44; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN11 = (Steinberg_Vst_Speaker) 1 << 45; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN12 = (Steinberg_Vst_Speaker) 1 << 46; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN13 = (Steinberg_Vst_Speaker) 1 << 47; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN14 = (Steinberg_Vst_Speaker) 1 << 48; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN15 = (Steinberg_Vst_Speaker) 1 << 49; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN16 = (Steinberg_Vst_Speaker) 1 << 50; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN17 = (Steinberg_Vst_Speaker) 1 << 51; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN18 = (Steinberg_Vst_Speaker) 1 << 52; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN19 = (Steinberg_Vst_Speaker) 1 << 53; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN20 = (Steinberg_Vst_Speaker) 1 << 54; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN21 = (Steinberg_Vst_Speaker) 1 << 55; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN22 = (Steinberg_Vst_Speaker) 1 << 56; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN23 = (Steinberg_Vst_Speaker) 1 << 57; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerACN24 = (Steinberg_Vst_Speaker) 1 << 58; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerTsl = (Steinberg_Vst_Speaker) 1 << 24; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerTsr = (Steinberg_Vst_Speaker) 1 << 25; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerLcs = (Steinberg_Vst_Speaker) 1 << 26; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerRcs = (Steinberg_Vst_Speaker) 1 << 27; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerBfl = (Steinberg_Vst_Speaker) 1 << 28; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerBfc = (Steinberg_Vst_Speaker) 1 << 29; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerBfr = (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerPl = (Steinberg_Vst_Speaker) 1 << 31; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerPr = (Steinberg_Vst_Speaker) 1 << 32; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerBsl = (Steinberg_Vst_Speaker) 1 << 33; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerBsr = (Steinberg_Vst_Speaker) 1 << 34; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerBrl = (Steinberg_Vst_Speaker) 1 << 35; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerBrc = (Steinberg_Vst_Speaker) 1 << 36; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerBrr = (Steinberg_Vst_Speaker) 1 << 37; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerLw = (Steinberg_Vst_Speaker) 1 << 59; +static const Steinberg_Vst_Speaker Steinberg_Vst_kSpeakerRw = (Steinberg_Vst_Speaker) 1 << 60; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kEmpty = 0; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kMono = 1 << 19; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereo = 1 << 0 | 1 << 1; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereoWide = (Steinberg_Vst_Speaker) 1 << 59 | (Steinberg_Vst_Speaker) 1 << 60; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereoSurround = 1 << 4 | 1 << 5; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereoCenter = 1 << 6 | 1 << 7; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereoSide = 1 << 9 | 1 << 10; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereoCLfe = 1 << 2 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereoTF = 1 << 12 | 1 << 14; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereoTS = (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereoTR = 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kStereoBF = (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kCineFront = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 6 | 1 << 7; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k30Cine = 1 << 0 | 1 << 1 | 1 << 2; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k31Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k30Music = 1 << 0 | 1 << 1 | 1 << 8; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k31Music = 1 << 0 | 1 << 1 | 1 << 8 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k40Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 8; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k41Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 8 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k40Music = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k41Music = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k51 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k60Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 8; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k61Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 8 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k60Music = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k61Music = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71CineFullFront = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70Music = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71Music = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71CineFullRear = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 26 | (Steinberg_Vst_Speaker) 1 << 27; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71CineSideFill = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71Proximity = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 31 | (Steinberg_Vst_Speaker) 1 << 32; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k80Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k81Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k80Music = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 8 | 1 << 9 | 1 << 10; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k81Music = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 8 | 1 << 9 | 1 << 10 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k90Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 9 | 1 << 10; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k91Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 9 | 1 << 10 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k100Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 9 | 1 << 10; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k101Cine = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 9 | 1 << 10 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kAmbi1stOrderACN = (Steinberg_Vst_Speaker) 1 << 20 | (Steinberg_Vst_Speaker) 1 << 21 | (Steinberg_Vst_Speaker) 1 << 22 | (Steinberg_Vst_Speaker) 1 << 23; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kAmbi2cdOrderACN = (Steinberg_Vst_Speaker) 1 << 20 | (Steinberg_Vst_Speaker) 1 << 21 | (Steinberg_Vst_Speaker) 1 << 22 | (Steinberg_Vst_Speaker) 1 << 23 | (Steinberg_Vst_Speaker) 1 << 38 | (Steinberg_Vst_Speaker) 1 << 39 | (Steinberg_Vst_Speaker) 1 << 40 | (Steinberg_Vst_Speaker) 1 << 41 | (Steinberg_Vst_Speaker) 1 << 42; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kAmbi3rdOrderACN = (Steinberg_Vst_Speaker) 1 << 20 | (Steinberg_Vst_Speaker) 1 << 21 | (Steinberg_Vst_Speaker) 1 << 22 | (Steinberg_Vst_Speaker) 1 << 23 | (Steinberg_Vst_Speaker) 1 << 38 | (Steinberg_Vst_Speaker) 1 << 39 | (Steinberg_Vst_Speaker) 1 << 40 | (Steinberg_Vst_Speaker) 1 << 41 | (Steinberg_Vst_Speaker) 1 << 42 | (Steinberg_Vst_Speaker) 1 << 43 | (Steinberg_Vst_Speaker) 1 << 44 | (Steinberg_Vst_Speaker) 1 << 45 | (Steinberg_Vst_Speaker) 1 << 46 | (Steinberg_Vst_Speaker) 1 << 47 | (Steinberg_Vst_Speaker) 1 << 48 | (Steinberg_Vst_Speaker) 1 << 49; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kAmbi4thOrderACN = (Steinberg_Vst_Speaker) 1 << 20 | (Steinberg_Vst_Speaker) 1 << 21 | (Steinberg_Vst_Speaker) 1 << 22 | (Steinberg_Vst_Speaker) 1 << 23 | (Steinberg_Vst_Speaker) 1 << 38 | (Steinberg_Vst_Speaker) 1 << 39 | (Steinberg_Vst_Speaker) 1 << 40 | (Steinberg_Vst_Speaker) 1 << 41 | (Steinberg_Vst_Speaker) 1 << 42 | (Steinberg_Vst_Speaker) 1 << 43 | (Steinberg_Vst_Speaker) 1 << 44 | (Steinberg_Vst_Speaker) 1 << 45 | (Steinberg_Vst_Speaker) 1 << 46 | (Steinberg_Vst_Speaker) 1 << 47 | (Steinberg_Vst_Speaker) 1 << 48 | (Steinberg_Vst_Speaker) 1 << 49 | (Steinberg_Vst_Speaker) 1 << 50 | (Steinberg_Vst_Speaker) 1 << 51 | (Steinberg_Vst_Speaker) 1 << 52 | (Steinberg_Vst_Speaker) 1 << 53 | (Steinberg_Vst_Speaker) 1 << 54 | (Steinberg_Vst_Speaker) 1 << 55 | (Steinberg_Vst_Speaker) 1 << 56 | (Steinberg_Vst_Speaker) 1 << 57 | (Steinberg_Vst_Speaker) 1 << 58; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kAmbi5thOrderACN = 0x000FFFFFFFFF; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kAmbi6thOrderACN = 0x0001FFFFFFFFFFFF; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_kAmbi7thOrderACN = 0xFFFFFFFFFFFFFFFF; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k80Cube = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k40_4 = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71CineTopCenter = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 8 | 1 << 11; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71CineCenterHigh = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 8 | 1 << 13; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70CineFrontHigh = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70MPEG3D = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_2 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71CineFrontHigh = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71MPEG3D = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k51_2 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70CineSideHigh = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_2_TS = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71CineSideHigh = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k51_2_TS = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k81MPEG3D = 1 << 0 | 1 << 1 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 13 | 1 << 14 | (Steinberg_Vst_Speaker) 1 << 29; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k41_4_1 = 1 << 0 | 1 << 1 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 13 | 1 << 14 | (Steinberg_Vst_Speaker) 1 << 29; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k90 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_4 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k91 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k51_4 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_4_1 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 29; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k51_4_1 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 29 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70_2 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71_2 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k91Atmos = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70_2_TF = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71_2_TF = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70_3 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 16; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k72_3 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 16 | 1 << 3 | 1 << 18; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70_4 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71_4 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k111MPEG3D = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70_6 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k71_6 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k90_4 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k91_4 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k90_6 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k91_6 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k90_4_W = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 59 | (Steinberg_Vst_Speaker) 1 << 60 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k91_4_W = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 59 | (Steinberg_Vst_Speaker) 1 << 60 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k90_6_W = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 59 | (Steinberg_Vst_Speaker) 1 << 60 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k91_6_W = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 59 | (Steinberg_Vst_Speaker) 1 << 60 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k100 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 11 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_5 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 11 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k101 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 11 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k101MPEG3D = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 11 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k51_5 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 11 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k102 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 18; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k52_5 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 18; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k110 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_6 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k111 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k51_6 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k122 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 18; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k72_5 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 18; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k130 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k131 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k140 = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30 | (Steinberg_Vst_Speaker) 1 << 35 | (Steinberg_Vst_Speaker) 1 << 37; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k60_4_4 = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30 | (Steinberg_Vst_Speaker) 1 << 35 | (Steinberg_Vst_Speaker) 1 << 37; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k220 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 9 | 1 << 10 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 16 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 29 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k100_9_3 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 9 | 1 << 10 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 16 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 29 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k222 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 9 | 1 << 10 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 16 | 1 << 17 | 1 << 18 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 29 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k102_9_3 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3 | 1 << 4 | 1 << 5 | 1 << 6 | 1 << 7 | 1 << 8 | 1 << 9 | 1 << 10 | 1 << 11 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 16 | 1 << 17 | 1 << 18 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 29 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_5_3 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 29 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k51_5_3 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 29 | (Steinberg_Vst_Speaker) 1 << 30 | 1 << 3; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_2_2 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_4_2 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k70_4_2 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 9 | 1 << 10 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_5_Sony = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k40_2_2 = 1 << 2 | 1 << 9 | 1 << 10 | 1 << 8 | (Steinberg_Vst_Speaker) 1 << 24 | (Steinberg_Vst_Speaker) 1 << 25 | (Steinberg_Vst_Speaker) 1 << 33 | (Steinberg_Vst_Speaker) 1 << 34; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k40_4_2 = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_3_2 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 13 | 1 << 14 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k30_5_2 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 12 | 1 << 13 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k40_4_4 = 1 << 0 | 1 << 1 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30 | (Steinberg_Vst_Speaker) 1 << 35 | (Steinberg_Vst_Speaker) 1 << 37; +static const Steinberg_Vst_SpeakerArrangement Steinberg_Vst_SpeakerArr_k50_4_4 = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 4 | 1 << 5 | 1 << 12 | 1 << 14 | 1 << 15 | 1 << 17 | (Steinberg_Vst_Speaker) 1 << 28 | (Steinberg_Vst_Speaker) 1 << 30 | (Steinberg_Vst_Speaker) 1 << 35 | (Steinberg_Vst_Speaker) 1 << 37; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringEmpty = ""; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringMono = "Mono"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereo = "Stereo"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoWide = "Stereo (Lw Rw)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoR = "Stereo (Ls Rs)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoC = "Stereo (Lc Rc)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoSide = "Stereo (Sl Sr)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoCLfe = "Stereo (C LFE)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoTF = "Stereo (Tfl Tfr)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoTS = "Stereo (Tsl Tsr)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoTR = "Stereo (Trl Trr)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoBF = "Stereo (Bfl Bfr)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringCineFront = "Cine Front"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString30Cine = "LRC"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString30Music = "LRS"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString31Cine = "LRC+LFE"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString31Music = "LRS+LFE"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40Cine = "LRCS"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40Music = "Quadro"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString41Cine = "LRCS+LFE"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString41Music = "Quadro+LFE"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50 = "5.0"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51 = "5.1"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString60Cine = "6.0 Cine"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString60Music = "6.0 Music"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString61Cine = "6.1 Cine"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString61Music = "6.1 Music"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70Cine = "7.0 SDDS"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70CineOld = "7.0 Cine (SDDS)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70Music = "7.0"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70MusicOld = "7.0 Music (Dolby)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71Cine = "7.1 SDDS"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71CineOld = "7.1 Cine (SDDS)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71Music = "7.1"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71MusicOld = "7.1 Music (Dolby)"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71CineTopCenter = "7.1 Cine Top Center"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71CineCenterHigh = "7.1 Cine Center High"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71CineFullRear = "7.1 Cine Full Rear"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_2 = "5.1.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_2 = "5.0.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_2TopSide = "5.0.2 Top Side"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_2TopSide = "5.1.2 Top Side"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71Proximity = "7.1 Proximity"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString80Cine = "8.0 Cine"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString80Music = "8.0 Music"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40_4 = "8.0 Cube"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString81Cine = "8.1 Cine"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString81Music = "8.1 Music"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90Cine = "9.0 Cine"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91Cine = "9.1 Cine"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString100Cine = "10.0 Cine"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString101Cine = "10.1 Cine"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString52_5 = "5.2.5"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString72_5 = "12.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_4 = "5.0.4"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_4 = "5.1.4"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_4_1 = "5.0.4.1"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_4_1 = "5.1.4.1"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_2 = "7.0.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71_2 = "7.1.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_2_TF = "7.0.2 Top Front"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71_2_TF = "7.1.2 Top Front"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_3 = "7.0.3"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString72_3 = "7.2.3"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_4 = "7.0.4"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71_4 = "7.1.4"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_6 = "7.0.6"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71_6 = "7.1.6"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90_4 = "9.0.4 ITU"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91_4 = "9.1.4 ITU"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90_6 = "9.0.6 ITU"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91_6 = "9.1.6 ITU"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90_4_W = "9.0.4"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91_4_W = "9.1.4"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90_6_W = "9.0.6"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91_6_W = "9.1.6"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_5 = "10.0 Auro-3D"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_5 = "10.1 Auro-3D"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_6 = "11.0 Auro-3D"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_6 = "11.1 Auro-3D"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString130 = "13.0 Auro-3D"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString131 = "13.1 Auro-3D"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString41_4_1 = "8.1 MPEG"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString60_4_4 = "14.0"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString220 = "22.0"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString222 = "22.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_5_3 = "5.0.5.3"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_5_3 = "5.1.5.3"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_2_2 = "5.0.2.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_4_2 = "5.0.4.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_4_2 = "7.0.4.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_5_Sony = "5.0.5 Sony"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40_2_2 = "4.0.3.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40_4_2 = "4.0.4.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_3_2 = "5.0.3.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString30_5_2 = "3.0.5.2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40_4_4 = "4.0.4.4"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_4_4 = "5.0.4.4"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi1stOrder = "1OA"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi2cdOrder = "2OA"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi3rdOrder = "3OA"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi4thOrder = "4OA"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi5thOrder = "5OA"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi6thOrder = "6OA"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi7thOrder = "7OA"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringMonoS = "M"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoS = "L R"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoWideS = "Lw Rw"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoRS = "Ls Rs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoCS = "Lc Rc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoSS = "Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoCLfeS = "C LFE"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoTFS = "Tfl Tfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoTSS = "Tsl Tsr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoTRS = "Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringStereoBFS = "Bfl Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringCineFrontS = "L R C Lc Rc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString30CineS = "L R C"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString30MusicS = "L R S"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString31CineS = "L R C LFE"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString31MusicS = "L R LFE S"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40CineS = "L R C S"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40MusicS = "L R Ls Rs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString41CineS = "L R C LFE S"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString41MusicS = "L R LFE Ls Rs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50S = "L R C Ls Rs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51S = "L R C LFE Ls Rs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString60CineS = "L R C Ls Rs Cs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString60MusicS = "L R Ls Rs Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString61CineS = "L R C LFE Ls Rs Cs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString61MusicS = "L R LFE Ls Rs Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70CineS = "L R C Ls Rs Lc Rc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70MusicS = "L R C Ls Rs Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71CineS = "L R C LFE Ls Rs Lc Rc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71MusicS = "L R C LFE Ls Rs Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString80CineS = "L R C Ls Rs Lc Rc Cs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString80MusicS = "L R C Ls Rs Cs Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString81CineS = "L R C LFE Ls Rs Lc Rc Cs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString81MusicS = "L R C LFE Ls Rs Cs Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40_4S = "L R Ls Rs Tfl Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71CineTopCenterS = "L R C LFE Ls Rs Cs Tc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71CineCenterHighS = "L R C LFE Ls Rs Cs Tfc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71CineFullRearS = "L R C LFE Ls Rs Lcs Rcs"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_2S = "L R C Ls Rs Tfl Tfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_2S = "L R C LFE Ls Rs Tfl Tfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_2TopSideS = "L R C Ls Rs Tsl Tsr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_2TopSideS = "L R C LFE Ls Rs Tsl Tsr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71ProximityS = "L R C LFE Ls Rs Pl Pr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90CineS = "L R C Ls Rs Lc Rc Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91CineS = "L R C LFE Ls Rs Lc Rc Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString100CineS = "L R C Ls Rs Lc Rc Cs Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString101CineS = "L R C LFE Ls Rs Lc Rc Cs Sl Sr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_4S = "L R C Ls Rs Tfl Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_4S = "L R C LFE Ls Rs Tfl Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_4_1S = "L R C Ls Rs Tfl Tfr Trl Trr Bfc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_4_1S = "L R C LFE Ls Rs Tfl Tfr Trl Trr Bfc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_2S = "L R C Ls Rs Sl Sr Tsl Tsr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71_2S = "L R C LFE Ls Rs Sl Sr Tsl Tsr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_2_TFS = "L R C Ls Rs Sl Sr Tfl Tfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71_2_TFS = "L R C LFE Ls Rs Sl Sr Tfl Tfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_3S = "L R C Ls Rs Sl Sr Tfl Tfr Trc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString72_3S = "L R C LFE Ls Rs Sl Sr Tfl Tfr Trc LFE2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_4S = "L R C Ls Rs Sl Sr Tfl Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71_4S = "L R C LFE Ls Rs Sl Sr Tfl Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_6S = "L R C Ls Rs Sl Sr Tfl Tfr Trl Trr Tsl Tsr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString71_6S = "L R C LFE Ls Rs Sl Sr Tfl Tfr Trl Trr Tsl Tsr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90_4S = "L R C Ls Rs Lc Rc Sl Sr Tfl Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91_4S = "L R C LFE Ls Rs Lc Rc Sl Sr Tfl Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90_6S = "L R C Ls Rs Lc Rc Sl Sr Tfl Tfr Trl Trr Tsl Tsr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91_6S = "L R C LFE Ls Rs Lc Rc Sl Sr Tfl Tfr Trl Trr Tsl Tsr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90_4_WS = "L R C Ls Rs Sl Sr Tfl Tfr Trl Trr Lw Rw"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91_4_WS = "L R C LFE Ls Rs Sl Sr Tfl Tfr Trl Trr Lw Rw"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString90_6_WS = "L R C Ls Rs Sl Sr Tfl Tfr Trl Trr Tsl Tsr Lw Rw"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString91_6_WS = "L R C LFE Ls Rs Sl Sr Tfl Tfr Trl Trr Tsl Tsr Lw Rw"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_5S = "L R C Ls Rs Tc Tfl Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_5S = "L R C LFE Ls Rs Tc Tfl Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_5_SonyS = "L R C Ls Rs Tfl Tfc Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_6S = "L R C Ls Rs Tc Tfl Tfc Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_6S = "L R C LFE Ls Rs Tc Tfl Tfc Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString130S = "L R C Ls Rs Sl Sr Tc Tfl Tfc Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString131S = "L R C LFE Ls Rs Sl Sr Tc Tfl Tfc Tfr Trl Trr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString52_5S = "L R C LFE Ls Rs Tfl Tfc Tfr Trl Trr LFE2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString72_5S = "L R C LFE Ls Rs Lc Rc Tfl Tfc Tfr Trl Trr LFE2"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString41_4_1S = "L R LFE Ls Rs Tfl Tfc Tfr Bfc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString30_5_2S = "L R C Tfl Tfc Tfr Trl Trr Bfl Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40_2_2S = "C Sl Sr Cs Tfc Tsl Tsr Trc"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40_4_2S = "L R Ls Rs Tfl Tfr Trl Trr Bfl Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString40_4_4S = "L R Ls Rs Tfl Tfr Trl Trr Bfl Bfr Brl Brr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_4_4S = "L R C Ls Rs Tfl Tfr Trl Trr Bfl Bfr Brl Brr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString60_4_4S = "L R Ls Rs Sl Sr Tfl Tfr Trl Trr Bfl Bfr Brl Brr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_5_3S = "L R C Ls Rs Tfl Tfc Tfr Trl Trr Bfl Bfc Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString51_5_3S = "L R C LFE Ls Rs Tfl Tfc Tfr Trl Trr Bfl Bfc Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_2_2S = "L R C Ls Rs Tsl Tsr Bfl Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_3_2S = "L R C Ls Rs Tfl Tfc Tfr Bfl Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString50_4_2S = "L R C Ls Rs Tfl Tfr Trl Trr Bfl Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString70_4_2S = "L R C Ls Rs Sl Sr Tfl Tfr Trl Trr Bfl Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString222S = "L R C LFE Ls Rs Lc Rc Cs Sl Sr Tc Tfl Tfc Tfr Trl Trc Trr LFE2 Tsl Tsr Bfl Bfc Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kString220S = "L R C Ls Rs Lc Rc Cs Sl Sr Tc Tfl Tfc Tfr Trl Trc Trr Tsl Tsr Bfl Bfc Bfr"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi1stOrderS = "0 1 2 3"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi2cdOrderS = "0 1 2 3 4 5 6 7 8"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi3rdOrderS = "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi4thOrderS = "0..24"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi5thOrderS = "0..35"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi6thOrderS = "0..48"; +static const Steinberg_Vst_CString Steinberg_Vst_SpeakerArr_kStringAmbi7thOrderS = "0..63"; +static const Steinberg_Vst_CString Steinberg_Vst_CurveType_kSegment = "segment"; +static const Steinberg_Vst_CString Steinberg_Vst_CurveType_kValueList = "valueList"; +static const Steinberg_Vst_CString Steinberg_Vst_Attributes_kStyle = "style"; +static const Steinberg_Vst_CString Steinberg_Vst_Attributes_kLEDStyle = "ledStyle"; +static const Steinberg_Vst_CString Steinberg_Vst_Attributes_kSwitchStyle = "switchStyle"; +static const Steinberg_Vst_CString Steinberg_Vst_Attributes_kKnobTurnsPerFullRange = "turnsPerFullRange"; +static const Steinberg_Vst_CString Steinberg_Vst_Attributes_kFunction = "function"; +static const Steinberg_Vst_CString Steinberg_Vst_Attributes_kFlags = "flags"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanPosCenterXFunc = "PanPosCenterX"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanPosCenterYFunc = "PanPosCenterY"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanPosFrontLeftXFunc = "PanPosFrontLeftX"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanPosFrontLeftYFunc = "PanPosFrontLeftY"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanPosFrontRightXFunc = "PanPosFrontRightX"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanPosFrontRightYFunc = "PanPosFrontRightY"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanRotationFunc = "PanRotation"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanLawFunc = "PanLaw"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanMirrorModeFunc = "PanMirrorMode"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kPanLfeGainFunc = "PanLfeGain"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kGainReductionFunc = "GainReduction"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kSoloFunc = "Solo"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kMuteFunc = "Mute"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFunction_kVolumeFunc = "Volume"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kInverseStyle = "inverse"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kLEDWrapLeftStyle = "wrapLeft"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kLEDWrapRightStyle = "wrapRight"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kLEDSpreadStyle = "spread"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kLEDBoostCutStyle = "boostCut"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kLEDSingleDotStyle = "singleDot"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kSwitchPushStyle = "push"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kSwitchPushIncLoopedStyle = "pushIncLooped"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kSwitchPushDecLoopedStyle = "pushDecLooped"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kSwitchPushIncStyle = "pushInc"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kSwitchPushDecStyle = "pushDec"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesStyle_kSwitchLatchStyle = "latch"; +static const Steinberg_Vst_CString Steinberg_Vst_AttributesFlags_kHideableFlag = "hideable"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelUIDKey = "channel uid"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelUIDLengthKey = "channel uid length"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelRuntimeIDKey = "channel runtime id"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelNameKey = "channel name"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelNameLengthKey = "channel name length"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelColorKey = "channel color"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelIndexKey = "channel index"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelIndexNamespaceOrderKey = "channel index namespace order"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelIndexNamespaceKey = "channel index namespace"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelIndexNamespaceLengthKey = "channel index namespace length"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelImageKey = "channel image"; +static const Steinberg_Vst_CString Steinberg_Vst_ChannelContext_kChannelPluginLocationKey = "channel plugin location"; +static const Steinberg_Vst_DataExchangeQueueID Steinberg_Vst_InvalidDataExchangeQueueID = INT32_MAX; +static const Steinberg_Vst_DataExchangeBlockID Steinberg_Vst_InvalidDataExchangeBlockID = INT32_MAX; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFx = "Fx"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxAnalyzer = "Fx|Analyzer"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxBass = "Fx|Bass"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxChannelStrip = "Fx|Channel Strip"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxDelay = "Fx|Delay"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxDistortion = "Fx|Distortion"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxDrums = "Fx|Drums"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxDynamics = "Fx|Dynamics"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxEQ = "Fx|EQ"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxFilter = "Fx|Filter"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxGenerator = "Fx|Generator"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxGuitar = "Fx|Guitar"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxInstrument = "Fx|Instrument"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxInstrumentExternal = "Fx|Instrument|External"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxMastering = "Fx|Mastering"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxMicrophone = "Fx|Microphone"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxModulation = "Fx|Modulation"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxNetwork = "Fx|Network"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxPitchShift = "Fx|Pitch Shift"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxRestoration = "Fx|Restoration"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxReverb = "Fx|Reverb"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxSpatial = "Fx|Spatial"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxSurround = "Fx|Surround"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxTools = "Fx|Tools"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kFxVocals = "Fx|Vocals"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kInstrument = "Instrument"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kInstrumentDrum = "Instrument|Drum"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kInstrumentExternal = "Instrument|External"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kInstrumentPiano = "Instrument|Piano"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kInstrumentSampler = "Instrument|Sampler"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kInstrumentSynth = "Instrument|Synth"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kInstrumentSynthSampler = "Instrument|Synth|Sampler"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kAmbisonics = "Ambisonics"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kAnalyzer = "Analyzer"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kNoOfflineProcess = "NoOfflineProcess"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kOnlyARA = "OnlyARA"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kOnlyOfflineProcess = "OnlyOfflineProcess"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kOnlyRealTime = "OnlyRT"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kSpatial = "Spatial"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kSpatialFx = "Spatial|Fx"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kUpDownMix = "Up-Downmix"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kMono = "Mono"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kStereo = "Stereo"; +static const Steinberg_Vst_CString Steinberg_Vst_PlugType_kSurround = "Surround"; +static const Steinberg_uint32 Steinberg_Vst_kNoTail = 0; +static const Steinberg_uint32 Steinberg_Vst_kInfiniteTail = UINT32_MAX; +static const Steinberg_Vst_UnitID Steinberg_Vst_kRootUnitId = 0; +static const Steinberg_Vst_UnitID Steinberg_Vst_kNoParentUnitId = -1; +static const Steinberg_Vst_ProgramListID Steinberg_Vst_kNoProgramListId = -1; +static const Steinberg_int32 Steinberg_Vst_kAllProgramInvalid = -1; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kCompGainReduction = "Comp:GainReduction"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kCompGainReductionMax = "Comp:GainReductionMax"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kCompGainReductionPeakHold = "Comp:GainReductionPeakHold"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kCompResetGainReductionMax = "Comp:ResetGainReductionMax"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kLowLatencyMode = "LowLatencyMode"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kDryWetMix = "DryWetMix"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kRandomize = "Randomize"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kRandomizeAroundCurrent = "RandomizeAroundCurrent"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kPanPosCenterX = "PanPosCenterX"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kPanPosCenterY = "PanPosCenterY"; +static const Steinberg_Vst_CString Steinberg_Vst_FunctionNameType_kPanPosCenterZ = "PanPosCenterZ"; + + +/*---------------------------------------------------------------------------------------------------------------------- +----- Structs ---------------------------------------------------------------------------------------------------------- +----------------------------------------------------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/gui/iplugview.h", line 34 */ + +struct Steinberg_ViewRect +{ + Steinberg_int32 left; + Steinberg_int32 top; + Steinberg_int32 right; + Steinberg_int32 bottom; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 102 */ + +struct Steinberg_Vst_NoteExpressionValueDescription +{ + Steinberg_Vst_NoteExpressionValue defaultValue; + Steinberg_Vst_NoteExpressionValue minimum; + Steinberg_Vst_NoteExpressionValue maximum; + Steinberg_int32 stepCount; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 123 */ + +struct Steinberg_Vst_NoteExpressionValueEvent +{ + Steinberg_Vst_NoteExpressionTypeID typeId; + Steinberg_int32 noteId; + Steinberg_Vst_NoteExpressionValue value; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 137 */ + +struct Steinberg_Vst_NoteExpressionIntValueEvent +{ + Steinberg_Vst_NoteExpressionTypeID typeId; + Steinberg_int32 noteId; + Steinberg_uint64 value; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 151 */ + +struct Steinberg_Vst_NoteExpressionTextEvent +{ + Steinberg_Vst_NoteExpressionTypeID typeId; + Steinberg_int32 noteId; + Steinberg_uint32 textLen; + const Steinberg_Vst_TChar* text; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 171 */ + +struct Steinberg_Vst_NoteExpressionTypeInfo +{ + Steinberg_Vst_NoteExpressionTypeID typeId; + Steinberg_Vst_String128 title; + Steinberg_Vst_String128 shortTitle; + Steinberg_Vst_String128 units; + Steinberg_int32 unitId; + struct Steinberg_Vst_NoteExpressionValueDescription valueDesc; + Steinberg_Vst_ParamID associatedParameterId; + Steinberg_int32 flags; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 265 */ + +struct Steinberg_Vst_KeyswitchInfo +{ + Steinberg_Vst_KeyswitchTypeID typeId; + Steinberg_Vst_String128 title; + Steinberg_Vst_String128 shortTitle; + Steinberg_int32 keyswitchMin; + Steinberg_int32 keyswitchMax; + Steinberg_int32 keyRemapped; + Steinberg_int32 unitId; + Steinberg_int32 flags; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstphysicalui.h", line 60 */ + +struct Steinberg_Vst_PhysicalUIMap +{ + Steinberg_Vst_PhysicalUITypeID physicalUITypeID; + Steinberg_Vst_NoteExpressionTypeID noteExpressionTypeID; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstphysicalui.h", line 76 */ + +struct Steinberg_Vst_PhysicalUIMapList +{ + Steinberg_uint32 count; + struct Steinberg_Vst_PhysicalUIMap* map; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 62 */ + +struct Steinberg_PFactoryInfo +{ + Steinberg_char8 vendor[64]; + Steinberg_char8 url[256]; + Steinberg_char8 email[128]; + Steinberg_int32 flags; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 124 */ + +struct Steinberg_PClassInfo +{ + Steinberg_TUID cid; + Steinberg_int32 cardinality; + Steinberg_char8 category[32]; + Steinberg_char8 name[64]; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 222 */ + +struct Steinberg_PClassInfo2 +{ + Steinberg_TUID cid; + Steinberg_int32 cardinality; + Steinberg_char8 category[32]; + Steinberg_char8 name[64]; + Steinberg_uint32 classFlags; + Steinberg_char8 subCategories[128]; + Steinberg_char8 vendor[64]; + Steinberg_char8 version[64]; + Steinberg_char8 sdkVersion[64]; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 337 */ + +struct Steinberg_PClassInfoW +{ + Steinberg_TUID cid; + Steinberg_int32 cardinality; + Steinberg_char8 category[32]; + Steinberg_char16 name[64]; + Steinberg_uint32 classFlags; + Steinberg_char8 subCategories[128]; + Steinberg_char16 vendor[64]; + Steinberg_char16 version[64]; + Steinberg_char16 sdkVersion[64]; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcomponent.h", line 93 */ + +struct Steinberg_Vst_BusInfo +{ + Steinberg_Vst_MediaType mediaType; + Steinberg_Vst_BusDirection direction; + Steinberg_int32 channelCount; + Steinberg_Vst_String128 name; + Steinberg_Vst_BusType busType; + Steinberg_uint32 flags; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcomponent.h", line 136 */ + +struct Steinberg_Vst_RoutingInfo +{ + Steinberg_Vst_MediaType mediaType; + Steinberg_int32 busIndex; + Steinberg_int32 channel; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 46 */ + +struct Steinberg_Vst_ParameterInfo +{ + Steinberg_Vst_ParamID id; + Steinberg_Vst_String128 title; + Steinberg_Vst_String128 shortTitle; + Steinberg_Vst_String128 units; + Steinberg_int32 stepCount; + Steinberg_Vst_ParamValue defaultNormalizedValue; + Steinberg_Vst_UnitID unitId; + Steinberg_int32 flags; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstprocesscontext.h", line 44 */ + +struct Steinberg_Vst_FrameRate +{ + Steinberg_uint32 framesPerSecond; + Steinberg_uint32 flags; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstprocesscontext.h", line 64 */ + +struct Steinberg_Vst_Chord +{ + Steinberg_uint8 keyNote; + Steinberg_uint8 rootNote; + Steinberg_int16 chordMask; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstprocesscontext.h", line 96 */ + +struct Steinberg_Vst_ProcessContext +{ + Steinberg_uint32 state; + double sampleRate; + Steinberg_Vst_TSamples projectTimeSamples; + Steinberg_int64 systemTime; + Steinberg_Vst_TSamples continousTimeSamples; + Steinberg_Vst_TQuarterNotes projectTimeMusic; + Steinberg_Vst_TQuarterNotes barPositionMusic; + Steinberg_Vst_TQuarterNotes cycleStartMusic; + Steinberg_Vst_TQuarterNotes cycleEndMusic; + double tempo; + Steinberg_int32 timeSigNumerator; + Steinberg_int32 timeSigDenominator; + struct Steinberg_Vst_Chord chord; + Steinberg_int32 smpteOffsetSubframes; + struct Steinberg_Vst_FrameRate frameRate; + Steinberg_int32 samplesToNextClock; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 43 */ + +struct Steinberg_Vst_NoteOnEvent +{ + Steinberg_int16 channel; + Steinberg_int16 pitch; + float tuning; + float velocity; + Steinberg_int32 length; + Steinberg_int32 noteId; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 57 */ + +struct Steinberg_Vst_NoteOffEvent +{ + Steinberg_int16 channel; + Steinberg_int16 pitch; + float velocity; + Steinberg_int32 noteId; + float tuning; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 70 */ + +struct Steinberg_Vst_DataEvent +{ + Steinberg_uint32 size; + Steinberg_uint32 type; + const Steinberg_uint8* bytes; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 87 */ + +struct Steinberg_Vst_PolyPressureEvent +{ + Steinberg_int16 channel; + Steinberg_int16 pitch; + float pressure; + Steinberg_int32 noteId; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 99 */ + +struct Steinberg_Vst_ChordEvent +{ + Steinberg_int16 root; + Steinberg_int16 bassNote; + Steinberg_int16 mask; + Steinberg_uint16 textLen; + const Steinberg_Vst_TChar* text; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 113 */ + +struct Steinberg_Vst_ScaleEvent +{ + Steinberg_int16 root; + Steinberg_int16 mask; + Steinberg_uint16 textLen; + const Steinberg_Vst_TChar* text; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 129 */ + +struct Steinberg_Vst_LegacyMIDICCOutEvent +{ + Steinberg_uint8 controlNumber; + Steinberg_int8 channel; + Steinberg_int8 value; + Steinberg_int8 value2; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 142 */ + +struct Steinberg_Vst_Event +{ + Steinberg_int32 busIndex; + Steinberg_int32 sampleOffset; + Steinberg_Vst_TQuarterNotes ppqPosition; + Steinberg_uint16 flags; + Steinberg_uint16 type; + union + { + struct Steinberg_Vst_NoteOnEvent Steinberg_Vst_Event_noteOn; + struct Steinberg_Vst_NoteOffEvent Steinberg_Vst_Event_noteOff; + struct Steinberg_Vst_DataEvent Steinberg_Vst_Event_data; + struct Steinberg_Vst_PolyPressureEvent Steinberg_Vst_Event_polyPressure; + struct Steinberg_Vst_NoteExpressionValueEvent Steinberg_Vst_Event_noteExpressionValue; + struct Steinberg_Vst_NoteExpressionTextEvent Steinberg_Vst_Event_noteExpressionText; + struct Steinberg_Vst_NoteExpressionIntValueEvent Steinberg_Vst_Event_noteExpressionIntValue; + struct Steinberg_Vst_ChordEvent Steinberg_Vst_Event_chord; + struct Steinberg_Vst_ScaleEvent Steinberg_Vst_Event_scale; + struct Steinberg_Vst_LegacyMIDICCOutEvent Steinberg_Vst_Event_midiCCOut; + }; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstrepresentation.h", line 37 */ + +struct Steinberg_Vst_RepresentationInfo +{ + Steinberg_char8 vendor[64]; + Steinberg_char8 name[64]; + Steinberg_char8 version[64]; + Steinberg_char8 host[64]; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcontextmenu.h", line 168 */ + +struct Steinberg_Vst_IContextMenuItem +{ + Steinberg_Vst_String128 name; + Steinberg_int32 tag; + Steinberg_int32 flags; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstdataexchange.h", line 45 */ + +struct Steinberg_Vst_DataExchangeBlock +{ + void* data; + Steinberg_uint32 size; + Steinberg_Vst_DataExchangeBlockID blockID; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 174 */ + +struct Steinberg_Vst_ProcessSetup +{ + Steinberg_int32 processMode; + Steinberg_int32 symbolicSampleSize; + Steinberg_int32 maxSamplesPerBlock; + Steinberg_Vst_SampleRate sampleRate; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 202 */ + +struct Steinberg_Vst_AudioBusBuffers +{ + Steinberg_int32 numChannels; + Steinberg_uint64 silenceFlags; + union + { + Steinberg_Vst_Sample32** Steinberg_Vst_AudioBusBuffers_channelBuffers32; + Steinberg_Vst_Sample64** Steinberg_Vst_AudioBusBuffers_channelBuffers64; + }; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 224 */ + +struct Steinberg_Vst_ProcessData +{ + Steinberg_int32 processMode; + Steinberg_int32 symbolicSampleSize; + Steinberg_int32 numSamples; + Steinberg_int32 numInputs; + Steinberg_int32 numOutputs; + struct Steinberg_Vst_AudioBusBuffers* inputs; + struct Steinberg_Vst_AudioBusBuffers* outputs; + struct Steinberg_Vst_IParameterChanges* inputParameterChanges; + struct Steinberg_Vst_IParameterChanges* outputParameterChanges; + struct Steinberg_Vst_IEventList* inputEvents; + struct Steinberg_Vst_IEventList* outputEvents; + struct Steinberg_Vst_ProcessContext* processContext; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmidimapping2.h", line 41 */ + +struct Steinberg_Vst_Midi2Controller +{ + Steinberg_uint8 byte1; + Steinberg_uint8 byte2; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmidimapping2.h", line 81 */ + +struct Steinberg_Vst_Midi2ControllerParamIDAssignment +{ + Steinberg_Vst_ParamID pId; + Steinberg_Vst_BusIndex busIndex; + Steinberg_Vst_MidiChannel channel; + struct Steinberg_Vst_Midi2Controller controller; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmidimapping2.h", line 90 */ + +struct Steinberg_Vst_Midi2ControllerParamIDAssignmentList +{ + Steinberg_uint32 count; + struct Steinberg_Vst_Midi2ControllerParamIDAssignment* map; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmidimapping2.h", line 97 */ + +struct Steinberg_Vst_Midi1ControllerParamIDAssignment +{ + Steinberg_Vst_ParamID pId; + Steinberg_Vst_BusIndex busIndex; + Steinberg_Vst_MidiChannel channel; + Steinberg_Vst_CtrlNumber controller; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmidimapping2.h", line 106 */ + +struct Steinberg_Vst_Midi1ControllerParamIDAssignmentList +{ + Steinberg_uint32 count; + struct Steinberg_Vst_Midi1ControllerParamIDAssignment* map; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteonorchestralarticulationinfo.h", line 33 */ + +struct Steinberg_Vst_NoteOnOrchestralArticulation_Variations +{ + Steinberg_uint8 variation[16]; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteonorchestralarticulationinfo.h", line 43 */ + +struct Steinberg_Vst_NoteOnOrchestralArticulation_ClassificationVariations +{ + struct Steinberg_Vst_NoteOnOrchestralArticulation_Variations classification[17]; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsttransportcontrol.h", line 51 */ + +struct Steinberg_Vst_TransportPosition +{ + Steinberg_Vst_TransportPositionType type; + union + { + Steinberg_Vst_TSamples Steinberg_Vst_TransportPosition_samples; + Steinberg_Vst_TQuarterNotes Steinberg_Vst_TransportPosition_quarterNotes; + }; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstunits.h", line 44 */ + +struct Steinberg_Vst_UnitInfo +{ + Steinberg_Vst_UnitID id; + Steinberg_Vst_UnitID parentUnitId; + Steinberg_Vst_String128 name; + Steinberg_Vst_ProgramListID programListId; +}; + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstunits.h", line 56 */ + +struct Steinberg_Vst_ProgramListInfo +{ + Steinberg_Vst_ProgramListID id; + Steinberg_Vst_String128 name; + Steinberg_int32 programCount; +}; + + +/*---------------------------------------------------------------------------------------------------------------------- +----- Interfaces ------------------------------------------------------------------------------------------------------- +----------------------------------------------------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/funknown.h", line 374 */ + +typedef struct Steinberg_FUnknownVtbl +{ + /* methods defined in "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + +} Steinberg_FUnknownVtbl; + +typedef struct Steinberg_FUnknown +{ + struct Steinberg_FUnknownVtbl* lpVtbl; +} Steinberg_FUnknown; + +static const Steinberg_TUID Steinberg_FUnknown_iid = SMTG_INLINE_UID (0x00000000, 0x00000000, 0xC0000000, 0x00000046); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/gui/iplugviewcontentscalesupport.h", line 57 */ + +typedef struct Steinberg_IPlugViewContentScaleSupportVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_IPlugViewContentScaleSupport": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setContentScaleFactor) (void* thisInterface, Steinberg_IPlugViewContentScaleSupport_ScaleFactor factor); + +} Steinberg_IPlugViewContentScaleSupportVtbl; + +typedef struct Steinberg_IPlugViewContentScaleSupport +{ + struct Steinberg_IPlugViewContentScaleSupportVtbl* lpVtbl; +} Steinberg_IPlugViewContentScaleSupport; + +static const Steinberg_TUID Steinberg_IPlugViewContentScaleSupport_iid = SMTG_INLINE_UID (0x65ED9690, 0x8AC44525, 0x8AADEF7A, 0x72EA703F); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/gui/iplugview.h", line 134 */ + +typedef struct Steinberg_IPlugViewVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_IPlugView": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* isPlatformTypeSupported) (void* thisInterface, Steinberg_FIDString type); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* attached) (void* thisInterface, void* parent, Steinberg_FIDString type); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* removed) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* onWheel) (void* thisInterface, float distance); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* onKeyDown) (void* thisInterface, Steinberg_char16 key, Steinberg_int16 keyCode, Steinberg_int16 modifiers); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* onKeyUp) (void* thisInterface, Steinberg_char16 key, Steinberg_int16 keyCode, Steinberg_int16 modifiers); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getSize) (void* thisInterface, struct Steinberg_ViewRect* size); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* onSize) (void* thisInterface, struct Steinberg_ViewRect* newSize); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* onFocus) (void* thisInterface, Steinberg_TBool state); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setFrame) (void* thisInterface, struct Steinberg_IPlugFrame* frame); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* canResize) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* checkSizeConstraint) (void* thisInterface, struct Steinberg_ViewRect* rect); + +} Steinberg_IPlugViewVtbl; + +typedef struct Steinberg_IPlugView +{ + struct Steinberg_IPlugViewVtbl* lpVtbl; +} Steinberg_IPlugView; + +static const Steinberg_TUID Steinberg_IPlugView_iid = SMTG_INLINE_UID (0x5BC32507, 0xD06049EA, 0xA6151B52, 0x2B755B29); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/gui/iplugview.h", line 208 */ + +typedef struct Steinberg_IPlugFrameVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_IPlugFrame": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* resizeView) (void* thisInterface, struct Steinberg_IPlugView* view, struct Steinberg_ViewRect* newSize); + +} Steinberg_IPlugFrameVtbl; + +typedef struct Steinberg_IPlugFrame +{ + struct Steinberg_IPlugFrameVtbl* lpVtbl; +} Steinberg_IPlugFrame; + +static const Steinberg_TUID Steinberg_IPlugFrame_iid = SMTG_INLINE_UID (0x367FAF01, 0xAFA94693, 0x8D4DA2A0, 0xED0882A3); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/gui/iplugview.h", line 234 */ + +typedef struct Steinberg_Linux_IEventHandlerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Linux_IEventHandler": */ + void (SMTG_STDMETHODCALLTYPE* onFDIsSet) (void* thisInterface, Steinberg_Linux_FileDescriptor fd); + +} Steinberg_Linux_IEventHandlerVtbl; + +typedef struct Steinberg_Linux_IEventHandler +{ + struct Steinberg_Linux_IEventHandlerVtbl* lpVtbl; +} Steinberg_Linux_IEventHandler; + +static const Steinberg_TUID Steinberg_Linux_IEventHandler_iid = SMTG_INLINE_UID (0x561E65C9, 0x13A0496F, 0x813A2C35, 0x654D7983); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/gui/iplugview.h", line 250 */ + +typedef struct Steinberg_Linux_ITimerHandlerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Linux_ITimerHandler": */ + void (SMTG_STDMETHODCALLTYPE* onTimer) (void* thisInterface); + +} Steinberg_Linux_ITimerHandlerVtbl; + +typedef struct Steinberg_Linux_ITimerHandler +{ + struct Steinberg_Linux_ITimerHandlerVtbl* lpVtbl; +} Steinberg_Linux_ITimerHandler; + +static const Steinberg_TUID Steinberg_Linux_ITimerHandler_iid = SMTG_INLINE_UID (0x10BDD94F, 0x41424774, 0x821FAD8F, 0xECA72CA9); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/gui/iplugview.h", line 278 */ + +typedef struct Steinberg_Linux_IRunLoopVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Linux_IRunLoop": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* registerEventHandler) (void* thisInterface, struct Steinberg_Linux_IEventHandler* handler, Steinberg_Linux_FileDescriptor fd); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* unregisterEventHandler) (void* thisInterface, struct Steinberg_Linux_IEventHandler* handler); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* registerTimer) (void* thisInterface, struct Steinberg_Linux_ITimerHandler* handler, Steinberg_Linux_TimerInterval milliseconds); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* unregisterTimer) (void* thisInterface, struct Steinberg_Linux_ITimerHandler* handler); + +} Steinberg_Linux_IRunLoopVtbl; + +typedef struct Steinberg_Linux_IRunLoop +{ + struct Steinberg_Linux_IRunLoopVtbl* lpVtbl; +} Steinberg_Linux_IRunLoop; + +static const Steinberg_TUID Steinberg_Linux_IRunLoop_iid = SMTG_INLINE_UID (0x18C35366, 0x97764F1A, 0x9C5B8385, 0x7A871389); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ibstream.h", line 29 */ + +typedef struct Steinberg_IBStreamVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_IBStream": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* read) (void* thisInterface, void* buffer, Steinberg_int32 numBytes, Steinberg_int32* numBytesRead); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* write) (void* thisInterface, void* buffer, Steinberg_int32 numBytes, Steinberg_int32* numBytesWritten); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* seek) (void* thisInterface, Steinberg_int64 pos, Steinberg_int32 mode, Steinberg_int64* result); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* tell) (void* thisInterface, Steinberg_int64* pos); + +} Steinberg_IBStreamVtbl; + +typedef struct Steinberg_IBStream +{ + struct Steinberg_IBStreamVtbl* lpVtbl; +} Steinberg_IBStream; + +static const Steinberg_TUID Steinberg_IBStream_iid = SMTG_INLINE_UID (0xC3BF6EA2, 0x30994752, 0x9B6BF990, 0x1EE33E9B); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ibstream.h", line 72 */ + +typedef struct Steinberg_ISizeableStreamVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_ISizeableStream": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getStreamSize) (void* thisInterface, Steinberg_int64* size); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setStreamSize) (void* thisInterface, Steinberg_int64 size); + +} Steinberg_ISizeableStreamVtbl; + +typedef struct Steinberg_ISizeableStream +{ + struct Steinberg_ISizeableStreamVtbl* lpVtbl; +} Steinberg_ISizeableStream; + +static const Steinberg_TUID Steinberg_ISizeableStream_iid = SMTG_INLINE_UID (0x04F9549E, 0xE02F4E6E, 0x87E86A87, 0x47F4E17F); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 212 */ + +typedef struct Steinberg_Vst_INoteExpressionControllerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_INoteExpressionController": */ + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getNoteExpressionCount) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getNoteExpressionInfo) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel, Steinberg_int32 noteExpressionIndex, struct Steinberg_Vst_NoteExpressionTypeInfo* info); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getNoteExpressionStringByValue) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel, Steinberg_Vst_NoteExpressionTypeID id, Steinberg_Vst_NoteExpressionValue valueNormalized, Steinberg_Vst_String128 string); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getNoteExpressionValueByString) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel, Steinberg_Vst_NoteExpressionTypeID id, const Steinberg_Vst_TChar* string, Steinberg_Vst_NoteExpressionValue* valueNormalized); + +} Steinberg_Vst_INoteExpressionControllerVtbl; + +typedef struct Steinberg_Vst_INoteExpressionController +{ + struct Steinberg_Vst_INoteExpressionControllerVtbl* lpVtbl; +} Steinberg_Vst_INoteExpressionController; + +static const Steinberg_TUID Steinberg_Vst_INoteExpressionController_iid = SMTG_INLINE_UID (0xB7F8F859, 0x41234872, 0x91169581, 0x4F3721A3); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteexpression.h", line 294 */ + +typedef struct Steinberg_Vst_IKeyswitchControllerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IKeyswitchController": */ + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getKeyswitchCount) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getKeyswitchInfo) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel, Steinberg_int32 keySwitchIndex, struct Steinberg_Vst_KeyswitchInfo* info); + +} Steinberg_Vst_IKeyswitchControllerVtbl; + +typedef struct Steinberg_Vst_IKeyswitchController +{ + struct Steinberg_Vst_IKeyswitchControllerVtbl* lpVtbl; +} Steinberg_Vst_IKeyswitchController; + +static const Steinberg_TUID Steinberg_Vst_IKeyswitchController_iid = SMTG_INLINE_UID (0x1F2F76D3, 0xBFFB4B96, 0xB99527A5, 0x5EBCCEF4); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstphysicalui.h", line 148 */ + +typedef struct Steinberg_Vst_INoteExpressionPhysicalUIMappingVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_INoteExpressionPhysicalUIMapping": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getPhysicalUIMapping) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel, struct Steinberg_Vst_PhysicalUIMapList* list); + +} Steinberg_Vst_INoteExpressionPhysicalUIMappingVtbl; + +typedef struct Steinberg_Vst_INoteExpressionPhysicalUIMapping +{ + struct Steinberg_Vst_INoteExpressionPhysicalUIMappingVtbl* lpVtbl; +} Steinberg_Vst_INoteExpressionPhysicalUIMapping; + +static const Steinberg_TUID Steinberg_Vst_INoteExpressionPhysicalUIMapping_iid = SMTG_INLINE_UID (0xB03078FF, 0x94D24AC8, 0x90CCD303, 0xD4133324); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 36 */ + +typedef struct Steinberg_IPluginBaseVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_IPluginBase": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* initialize) (void* thisInterface, struct Steinberg_FUnknown* context); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* terminate) (void* thisInterface); + +} Steinberg_IPluginBaseVtbl; + +typedef struct Steinberg_IPluginBase +{ + struct Steinberg_IPluginBaseVtbl* lpVtbl; +} Steinberg_IPluginBase; + +static const Steinberg_TUID Steinberg_IPluginBase_iid = SMTG_INLINE_UID (0x22888DDB, 0x156E45AE, 0x8358B348, 0x08190625); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 192 */ + +typedef struct Steinberg_IPluginFactoryVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_IPluginFactory": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getFactoryInfo) (void* thisInterface, struct Steinberg_PFactoryInfo* info); + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* countClasses) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getClassInfo) (void* thisInterface, Steinberg_int32 index, struct Steinberg_PClassInfo* info); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* createInstance) (void* thisInterface, Steinberg_FIDString cid, Steinberg_FIDString iid, void** obj); + +} Steinberg_IPluginFactoryVtbl; + +typedef struct Steinberg_IPluginFactory +{ + struct Steinberg_IPluginFactoryVtbl* lpVtbl; +} Steinberg_IPluginFactory; + +static const Steinberg_TUID Steinberg_IPluginFactory_iid = SMTG_INLINE_UID (0x7A4D811C, 0x52114A1F, 0xAED9D2EE, 0x0B43BF9F); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 321 */ + +typedef struct Steinberg_IPluginFactory2Vtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods derived from "Steinberg_IPluginFactory": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getFactoryInfo) (void* thisInterface, struct Steinberg_PFactoryInfo* info); + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* countClasses) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getClassInfo) (void* thisInterface, Steinberg_int32 index, struct Steinberg_PClassInfo* info); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* createInstance) (void* thisInterface, Steinberg_FIDString cid, Steinberg_FIDString iid, void** obj); + + /* methods defined in "Steinberg_IPluginFactory2": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getClassInfo2) (void* thisInterface, Steinberg_int32 index, struct Steinberg_PClassInfo2* info); + +} Steinberg_IPluginFactory2Vtbl; + +typedef struct Steinberg_IPluginFactory2 +{ + struct Steinberg_IPluginFactory2Vtbl* lpVtbl; +} Steinberg_IPluginFactory2; + +static const Steinberg_TUID Steinberg_IPluginFactory2_iid = SMTG_INLINE_UID (0x0007B650, 0xF24B4C0B, 0xA464EDB9, 0xF00B2ABB); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/base/ipluginbase.h", line 447 */ + +typedef struct Steinberg_IPluginFactory3Vtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods derived from "Steinberg_IPluginFactory": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getFactoryInfo) (void* thisInterface, struct Steinberg_PFactoryInfo* info); + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* countClasses) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getClassInfo) (void* thisInterface, Steinberg_int32 index, struct Steinberg_PClassInfo* info); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* createInstance) (void* thisInterface, Steinberg_FIDString cid, Steinberg_FIDString iid, void** obj); + + /* methods derived from "Steinberg_IPluginFactory2": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getClassInfo2) (void* thisInterface, Steinberg_int32 index, struct Steinberg_PClassInfo2* info); + + /* methods defined in "Steinberg_IPluginFactory3": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getClassInfoUnicode) (void* thisInterface, Steinberg_int32 index, struct Steinberg_PClassInfoW* info); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setHostContext) (void* thisInterface, struct Steinberg_FUnknown* context); + +} Steinberg_IPluginFactory3Vtbl; + +typedef struct Steinberg_IPluginFactory3 +{ + struct Steinberg_IPluginFactory3Vtbl* lpVtbl; +} Steinberg_IPluginFactory3; + +static const Steinberg_TUID Steinberg_IPluginFactory3_iid = SMTG_INLINE_UID (0x4555A2AB, 0xC1234E57, 0x9B122910, 0x36878931); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcomponent.h", line 158 */ + +typedef struct Steinberg_Vst_IComponentVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods derived from "Steinberg_IPluginBase": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* initialize) (void* thisInterface, struct Steinberg_FUnknown* context); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* terminate) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IComponent": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getControllerClassId) (void* thisInterface, Steinberg_TUID classId); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setIoMode) (void* thisInterface, Steinberg_Vst_IoMode mode); + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getBusCount) (void* thisInterface, Steinberg_Vst_MediaType type, Steinberg_Vst_BusDirection dir); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getBusInfo) (void* thisInterface, Steinberg_Vst_MediaType type, Steinberg_Vst_BusDirection dir, Steinberg_int32 index, struct Steinberg_Vst_BusInfo* bus); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getRoutingInfo) (void* thisInterface, struct Steinberg_Vst_RoutingInfo* inInfo, struct Steinberg_Vst_RoutingInfo* outInfo); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* activateBus) (void* thisInterface, Steinberg_Vst_MediaType type, Steinberg_Vst_BusDirection dir, Steinberg_int32 index, Steinberg_TBool state); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setActive) (void* thisInterface, Steinberg_TBool state); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setState) (void* thisInterface, struct Steinberg_IBStream* state); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getState) (void* thisInterface, struct Steinberg_IBStream* state); + +} Steinberg_Vst_IComponentVtbl; + +typedef struct Steinberg_Vst_IComponent +{ + struct Steinberg_Vst_IComponentVtbl* lpVtbl; +} Steinberg_Vst_IComponent; + +static const Steinberg_TUID Steinberg_Vst_IComponent_iid = SMTG_INLINE_UID (0xE831FF31, 0xF2D54301, 0x928EBBEE, 0x25697802); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstattributes.h", line 40 */ + +typedef struct Steinberg_Vst_IAttributeListVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IAttributeList": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setInt) (void* thisInterface, Steinberg_Vst_IAttributeList_AttrID id, Steinberg_int64 value); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getInt) (void* thisInterface, Steinberg_Vst_IAttributeList_AttrID id, Steinberg_int64* value); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setFloat) (void* thisInterface, Steinberg_Vst_IAttributeList_AttrID id, double value); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getFloat) (void* thisInterface, Steinberg_Vst_IAttributeList_AttrID id, double* value); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setString) (void* thisInterface, Steinberg_Vst_IAttributeList_AttrID id, const Steinberg_Vst_TChar* string); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getString) (void* thisInterface, Steinberg_Vst_IAttributeList_AttrID id, Steinberg_Vst_TChar* string, Steinberg_uint32 sizeInBytes); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setBinary) (void* thisInterface, Steinberg_Vst_IAttributeList_AttrID id, const void* data, Steinberg_uint32 sizeInBytes); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getBinary) (void* thisInterface, Steinberg_Vst_IAttributeList_AttrID id, const void** data, Steinberg_uint32* sizeInBytes); + +} Steinberg_Vst_IAttributeListVtbl; + +typedef struct Steinberg_Vst_IAttributeList +{ + struct Steinberg_Vst_IAttributeListVtbl* lpVtbl; +} Steinberg_Vst_IAttributeList; + +static const Steinberg_TUID Steinberg_Vst_IAttributeList_iid = SMTG_INLINE_UID (0x1E5F0AEB, 0xCC7F4533, 0xA2544011, 0x38AD5EE4); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstattributes.h", line 135 */ + +typedef struct Steinberg_Vst_IStreamAttributesVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IStreamAttributes": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getFileName) (void* thisInterface, Steinberg_Vst_String128 name); + struct Steinberg_Vst_IAttributeList* (SMTG_STDMETHODCALLTYPE* getAttributes) (void* thisInterface); + +} Steinberg_Vst_IStreamAttributesVtbl; + +typedef struct Steinberg_Vst_IStreamAttributes +{ + struct Steinberg_Vst_IStreamAttributesVtbl* lpVtbl; +} Steinberg_Vst_IStreamAttributes; + +static const Steinberg_TUID Steinberg_Vst_IStreamAttributes_iid = SMTG_INLINE_UID (0xD6CE2FFC, 0xEFAF4B8C, 0x9E74F1BB, 0x12DA44B4); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstremapparamid.h", line 46 */ + +typedef struct Steinberg_Vst_IRemapParamIDVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IRemapParamID": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getCompatibleParamID) (void* thisInterface, const Steinberg_TUID pluginToReplaceUID, Steinberg_Vst_ParamID oldParamID, Steinberg_Vst_ParamID* newParamID); + +} Steinberg_Vst_IRemapParamIDVtbl; + +typedef struct Steinberg_Vst_IRemapParamID +{ + struct Steinberg_Vst_IRemapParamIDVtbl* lpVtbl; +} Steinberg_Vst_IRemapParamID; + +static const Steinberg_TUID Steinberg_Vst_IRemapParamID_iid = SMTG_INLINE_UID (0x2B88021E, 0x6286B646, 0xB49DF76A, 0x5663061C); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 217 */ + +typedef struct Steinberg_Vst_IComponentHandlerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IComponentHandler": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* beginEdit) (void* thisInterface, Steinberg_Vst_ParamID id); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* performEdit) (void* thisInterface, Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue valueNormalized); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* endEdit) (void* thisInterface, Steinberg_Vst_ParamID id); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* restartComponent) (void* thisInterface, Steinberg_int32 flags); + +} Steinberg_Vst_IComponentHandlerVtbl; + +typedef struct Steinberg_Vst_IComponentHandler +{ + struct Steinberg_Vst_IComponentHandlerVtbl* lpVtbl; +} Steinberg_Vst_IComponentHandler; + +static const Steinberg_TUID Steinberg_Vst_IComponentHandler_iid = SMTG_INLINE_UID (0x93A0BEA3, 0x0BD045DB, 0x8E890B0C, 0xC1E46AC6); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 307 */ + +typedef struct Steinberg_Vst_IComponentHandler2Vtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IComponentHandler2": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setDirty) (void* thisInterface, Steinberg_TBool state); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* requestOpenEditor) (void* thisInterface, Steinberg_FIDString name); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* startGroupEdit) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* finishGroupEdit) (void* thisInterface); + +} Steinberg_Vst_IComponentHandler2Vtbl; + +typedef struct Steinberg_Vst_IComponentHandler2 +{ + struct Steinberg_Vst_IComponentHandler2Vtbl* lpVtbl; +} Steinberg_Vst_IComponentHandler2; + +static const Steinberg_TUID Steinberg_Vst_IComponentHandler2_iid = SMTG_INLINE_UID (0xF040B4B3, 0xA36045EC, 0xABCDC045, 0xB4D5A2CC); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 365 */ + +typedef struct Steinberg_Vst_IComponentHandlerBusActivationVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IComponentHandlerBusActivation": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* requestBusActivation) (void* thisInterface, Steinberg_Vst_MediaType type, Steinberg_Vst_BusDirection dir, Steinberg_int32 index, Steinberg_TBool state); + +} Steinberg_Vst_IComponentHandlerBusActivationVtbl; + +typedef struct Steinberg_Vst_IComponentHandlerBusActivation +{ + struct Steinberg_Vst_IComponentHandlerBusActivationVtbl* lpVtbl; +} Steinberg_Vst_IComponentHandlerBusActivation; + +static const Steinberg_TUID Steinberg_Vst_IComponentHandlerBusActivation_iid = SMTG_INLINE_UID (0x067D02C1, 0x5B4E274D, 0xA92D90FD, 0x6EAF7240); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 422 */ + +typedef struct Steinberg_Vst_IProgressVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IProgress": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* start) (void* thisInterface, Steinberg_Vst_IProgress_ProgressType type, const Steinberg_tchar* optionalDescription, Steinberg_Vst_IProgress_ID* outID); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* update) (void* thisInterface, Steinberg_Vst_IProgress_ID id, Steinberg_Vst_ParamValue normValue); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* finish) (void* thisInterface, Steinberg_Vst_IProgress_ID id); + +} Steinberg_Vst_IProgressVtbl; + +typedef struct Steinberg_Vst_IProgress +{ + struct Steinberg_Vst_IProgressVtbl* lpVtbl; +} Steinberg_Vst_IProgress; + +static const Steinberg_TUID Steinberg_Vst_IProgress_iid = SMTG_INLINE_UID (0x00C9DC5B, 0x9D904254, 0x91A388C8, 0xB4E91B69); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 468 */ + +typedef struct Steinberg_Vst_IEditControllerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods derived from "Steinberg_IPluginBase": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* initialize) (void* thisInterface, struct Steinberg_FUnknown* context); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* terminate) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IEditController": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setComponentState) (void* thisInterface, struct Steinberg_IBStream* state); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setState) (void* thisInterface, struct Steinberg_IBStream* state); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getState) (void* thisInterface, struct Steinberg_IBStream* state); + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getParameterCount) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getParameterInfo) (void* thisInterface, Steinberg_int32 paramIndex, struct Steinberg_Vst_ParameterInfo* info); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getParamStringByValue) (void* thisInterface, Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue valueNormalized, Steinberg_Vst_String128 string); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getParamValueByString) (void* thisInterface, Steinberg_Vst_ParamID id, Steinberg_Vst_TChar* string, Steinberg_Vst_ParamValue* valueNormalized); + Steinberg_Vst_ParamValue (SMTG_STDMETHODCALLTYPE* normalizedParamToPlain) (void* thisInterface, Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue valueNormalized); + Steinberg_Vst_ParamValue (SMTG_STDMETHODCALLTYPE* plainParamToNormalized) (void* thisInterface, Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue plainValue); + Steinberg_Vst_ParamValue (SMTG_STDMETHODCALLTYPE* getParamNormalized) (void* thisInterface, Steinberg_Vst_ParamID id); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setParamNormalized) (void* thisInterface, Steinberg_Vst_ParamID id, Steinberg_Vst_ParamValue value); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setComponentHandler) (void* thisInterface, struct Steinberg_Vst_IComponentHandler* handler); + struct Steinberg_IPlugView* (SMTG_STDMETHODCALLTYPE* createView) (void* thisInterface, Steinberg_FIDString name); + +} Steinberg_Vst_IEditControllerVtbl; + +typedef struct Steinberg_Vst_IEditController +{ + struct Steinberg_Vst_IEditControllerVtbl* lpVtbl; +} Steinberg_Vst_IEditController; + +static const Steinberg_TUID Steinberg_Vst_IEditController_iid = SMTG_INLINE_UID (0xDCD7BBE3, 0x7742448D, 0xA874AACC, 0x979C759E); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 575 */ + +typedef struct Steinberg_Vst_IEditController2Vtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IEditController2": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setKnobMode) (void* thisInterface, Steinberg_Vst_KnobMode mode); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* openHelp) (void* thisInterface, Steinberg_TBool onlyCheck); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* openAboutBox) (void* thisInterface, Steinberg_TBool onlyCheck); + +} Steinberg_Vst_IEditController2Vtbl; + +typedef struct Steinberg_Vst_IEditController2 +{ + struct Steinberg_Vst_IEditController2Vtbl* lpVtbl; +} Steinberg_Vst_IEditController2; + +static const Steinberg_TUID Steinberg_Vst_IEditController2_iid = SMTG_INLINE_UID (0x7F4EFE59, 0xF3204967, 0xAC27A3AE, 0xAFB63038); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 659 */ + +typedef struct Steinberg_Vst_IMidiMappingVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IMidiMapping": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getMidiControllerAssignment) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel, Steinberg_Vst_CtrlNumber midiControllerNumber, Steinberg_Vst_ParamID* id); + +} Steinberg_Vst_IMidiMappingVtbl; + +typedef struct Steinberg_Vst_IMidiMapping +{ + struct Steinberg_Vst_IMidiMappingVtbl* lpVtbl; +} Steinberg_Vst_IMidiMapping; + +static const Steinberg_TUID Steinberg_Vst_IMidiMapping_iid = SMTG_INLINE_UID (0xDF0FF9F7, 0x49B74669, 0xB63AB732, 0x7ADBF5E5); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 708 */ + +typedef struct Steinberg_Vst_IEditControllerHostEditingVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IEditControllerHostEditing": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* beginEditFromHost) (void* thisInterface, Steinberg_Vst_ParamID paramID); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* endEditFromHost) (void* thisInterface, Steinberg_Vst_ParamID paramID); + +} Steinberg_Vst_IEditControllerHostEditingVtbl; + +typedef struct Steinberg_Vst_IEditControllerHostEditing +{ + struct Steinberg_Vst_IEditControllerHostEditingVtbl* lpVtbl; +} Steinberg_Vst_IEditControllerHostEditing; + +static const Steinberg_TUID Steinberg_Vst_IEditControllerHostEditing_iid = SMTG_INLINE_UID (0xC1271208, 0x70594098, 0xB9DD34B3, 0x6BB0195E); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsteditcontroller.h", line 735 */ + +typedef struct Steinberg_Vst_IComponentHandlerSystemTimeVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IComponentHandlerSystemTime": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getSystemTime) (void* thisInterface, Steinberg_int64* systemTime); + +} Steinberg_Vst_IComponentHandlerSystemTimeVtbl; + +typedef struct Steinberg_Vst_IComponentHandlerSystemTime +{ + struct Steinberg_Vst_IComponentHandlerSystemTimeVtbl* lpVtbl; +} Steinberg_Vst_IComponentHandlerSystemTime; + +static const Steinberg_TUID Steinberg_Vst_IComponentHandlerSystemTime_iid = SMTG_INLINE_UID (0xF9E53056, 0xD1554CD5, 0xB7695E1B, 0x7B0F7745); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstevents.h", line 198 */ + +typedef struct Steinberg_Vst_IEventListVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IEventList": */ + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getEventCount) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getEvent) (void* thisInterface, Steinberg_int32 index, struct Steinberg_Vst_Event* e); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* addEvent) (void* thisInterface, struct Steinberg_Vst_Event* e); + +} Steinberg_Vst_IEventListVtbl; + +typedef struct Steinberg_Vst_IEventList +{ + struct Steinberg_Vst_IEventListVtbl* lpVtbl; +} Steinberg_Vst_IEventList; + +static const Steinberg_TUID Steinberg_Vst_IEventList_iid = SMTG_INLINE_UID (0x3A2C4214, 0x346349FE, 0xB2C4F397, 0xB9695A44); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmessage.h", line 40 */ + +typedef struct Steinberg_Vst_IMessageVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IMessage": */ + Steinberg_FIDString (SMTG_STDMETHODCALLTYPE* getMessageID) (void* thisInterface); + void (SMTG_STDMETHODCALLTYPE* setMessageID) (void* thisInterface, Steinberg_FIDString id); + struct Steinberg_Vst_IAttributeList* (SMTG_STDMETHODCALLTYPE* getAttributes) (void* thisInterface); + +} Steinberg_Vst_IMessageVtbl; + +typedef struct Steinberg_Vst_IMessage +{ + struct Steinberg_Vst_IMessageVtbl* lpVtbl; +} Steinberg_Vst_IMessage; + +static const Steinberg_TUID Steinberg_Vst_IMessage_iid = SMTG_INLINE_UID (0x936F033B, 0xC6C047DB, 0xBB0882F8, 0x13C1E613); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmessage.h", line 73 */ + +typedef struct Steinberg_Vst_IConnectionPointVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IConnectionPoint": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* connect) (void* thisInterface, struct Steinberg_Vst_IConnectionPoint* other); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* disconnect) (void* thisInterface, struct Steinberg_Vst_IConnectionPoint* other); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* notify) (void* thisInterface, struct Steinberg_Vst_IMessage* message); + +} Steinberg_Vst_IConnectionPointVtbl; + +typedef struct Steinberg_Vst_IConnectionPoint +{ + struct Steinberg_Vst_IConnectionPointVtbl* lpVtbl; +} Steinberg_Vst_IConnectionPoint; + +static const Steinberg_TUID Steinberg_Vst_IConnectionPoint_iid = SMTG_INLINE_UID (0x70A4156F, 0x6E6E4026, 0x989148BF, 0xAA60D8D1); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstrepresentation.h", line 180 */ + +typedef struct Steinberg_Vst_IXmlRepresentationControllerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IXmlRepresentationController": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getXmlRepresentationStream) (void* thisInterface, struct Steinberg_Vst_RepresentationInfo* info, struct Steinberg_IBStream* stream); + +} Steinberg_Vst_IXmlRepresentationControllerVtbl; + +typedef struct Steinberg_Vst_IXmlRepresentationController +{ + struct Steinberg_Vst_IXmlRepresentationControllerVtbl* lpVtbl; +} Steinberg_Vst_IXmlRepresentationController; + +static const Steinberg_TUID Steinberg_Vst_IXmlRepresentationController_iid = SMTG_INLINE_UID (0xA81A0471, 0x48C34DC4, 0xAC30C9E1, 0x3C8393D5); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcontextmenu.h", line 124 */ + +typedef struct Steinberg_Vst_IComponentHandler3Vtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IComponentHandler3": */ + struct Steinberg_Vst_IContextMenu* (SMTG_STDMETHODCALLTYPE* createContextMenu) (void* thisInterface, struct Steinberg_IPlugView* plugView, const Steinberg_Vst_ParamID* paramID); + +} Steinberg_Vst_IComponentHandler3Vtbl; + +typedef struct Steinberg_Vst_IComponentHandler3 +{ + struct Steinberg_Vst_IComponentHandler3Vtbl* lpVtbl; +} Steinberg_Vst_IComponentHandler3; + +static const Steinberg_TUID Steinberg_Vst_IComponentHandler3_iid = SMTG_INLINE_UID (0x69F11617, 0xD26B400D, 0xA4B6B964, 0x7B6EBBAB); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcontextmenu.h", line 154 */ + +typedef struct Steinberg_Vst_IContextMenuTargetVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IContextMenuTarget": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* executeMenuItem) (void* thisInterface, Steinberg_int32 tag); + +} Steinberg_Vst_IContextMenuTargetVtbl; + +typedef struct Steinberg_Vst_IContextMenuTarget +{ + struct Steinberg_Vst_IContextMenuTargetVtbl* lpVtbl; +} Steinberg_Vst_IContextMenuTarget; + +static const Steinberg_TUID Steinberg_Vst_IContextMenuTarget_iid = SMTG_INLINE_UID (0x3CDF2E75, 0x85D34144, 0xBF86D36B, 0xD7C4894D); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstcontextmenu.h", line 196 */ + +typedef struct Steinberg_Vst_IContextMenuVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IContextMenu": */ + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getItemCount) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getItem) (void* thisInterface, Steinberg_int32 index, Steinberg_Vst_IContextMenu_Item* item, struct Steinberg_Vst_IContextMenuTarget** target); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* addItem) (void* thisInterface, const Steinberg_Vst_IContextMenu_Item* item, struct Steinberg_Vst_IContextMenuTarget* target); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* removeItem) (void* thisInterface, const Steinberg_Vst_IContextMenu_Item* item, struct Steinberg_Vst_IContextMenuTarget* target); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* popup) (void* thisInterface, Steinberg_UCoord x, Steinberg_UCoord y); + +} Steinberg_Vst_IContextMenuVtbl; + +typedef struct Steinberg_Vst_IContextMenu +{ + struct Steinberg_Vst_IContextMenuVtbl* lpVtbl; +} Steinberg_Vst_IContextMenu; + +static const Steinberg_TUID Steinberg_Vst_IContextMenu_iid = SMTG_INLINE_UID (0x2E93C863, 0x0C9C4588, 0x97DBECF5, 0xAD17817D); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmidilearn.h", line 90 */ + +typedef struct Steinberg_Vst_IMidiLearnVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IMidiLearn": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* onLiveMIDIControllerInput) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel, Steinberg_Vst_CtrlNumber midiCC); + +} Steinberg_Vst_IMidiLearnVtbl; + +typedef struct Steinberg_Vst_IMidiLearn +{ + struct Steinberg_Vst_IMidiLearnVtbl* lpVtbl; +} Steinberg_Vst_IMidiLearn; + +static const Steinberg_TUID Steinberg_Vst_IMidiLearn_iid = SMTG_INLINE_UID (0x6B2449CC, 0x419740B5, 0xAB3C79DA, 0xC5FE5C86); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstchannelcontextinfo.h", line 155 */ + +typedef struct Steinberg_Vst_ChannelContext_IInfoListenerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_ChannelContext_IInfoListener": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setChannelContextInfos) (void* thisInterface, struct Steinberg_Vst_IAttributeList* list); + +} Steinberg_Vst_ChannelContext_IInfoListenerVtbl; + +typedef struct Steinberg_Vst_ChannelContext_IInfoListener +{ + struct Steinberg_Vst_ChannelContext_IInfoListenerVtbl* lpVtbl; +} Steinberg_Vst_ChannelContext_IInfoListener; + +static const Steinberg_TUID Steinberg_Vst_ChannelContext_IInfoListener_iid = SMTG_INLINE_UID (0x0F194781, 0x8D984ADA, 0xBBA0C1EF, 0xC011D8D0); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstprefetchablesupport.h", line 78 */ + +typedef struct Steinberg_Vst_IPrefetchableSupportVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IPrefetchableSupport": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getPrefetchableSupport) (void* thisInterface, Steinberg_Vst_PrefetchableSupport* prefetchable); + +} Steinberg_Vst_IPrefetchableSupportVtbl; + +typedef struct Steinberg_Vst_IPrefetchableSupport +{ + struct Steinberg_Vst_IPrefetchableSupportVtbl* lpVtbl; +} Steinberg_Vst_IPrefetchableSupport; + +static const Steinberg_TUID Steinberg_Vst_IPrefetchableSupport_iid = SMTG_INLINE_UID (0x8AE54FDA, 0xE93046B9, 0xA28555BC, 0xDC98E21E); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstdataexchange.h", line 96 */ + +typedef struct Steinberg_Vst_IDataExchangeHandlerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IDataExchangeHandler": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* openQueue) (void* thisInterface, struct Steinberg_Vst_IAudioProcessor* processor, Steinberg_uint32 blockSize, Steinberg_uint32 numBlocks, Steinberg_uint32 alignment, Steinberg_Vst_DataExchangeUserContextID userContextID, Steinberg_Vst_DataExchangeQueueID* outID); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* closeQueue) (void* thisInterface, Steinberg_Vst_DataExchangeQueueID queueID); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* lockBlock) (void* thisInterface, Steinberg_Vst_DataExchangeQueueID queueId, struct Steinberg_Vst_DataExchangeBlock* block); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* freeBlock) (void* thisInterface, Steinberg_Vst_DataExchangeQueueID queueId, Steinberg_Vst_DataExchangeBlockID blockID, Steinberg_TBool sendToController); + +} Steinberg_Vst_IDataExchangeHandlerVtbl; + +typedef struct Steinberg_Vst_IDataExchangeHandler +{ + struct Steinberg_Vst_IDataExchangeHandlerVtbl* lpVtbl; +} Steinberg_Vst_IDataExchangeHandler; + +static const Steinberg_TUID Steinberg_Vst_IDataExchangeHandler_iid = SMTG_INLINE_UID (0x36D551BD, 0x6FF54F08, 0xB48E830D, 0x8BD5A03B); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstdataexchange.h", line 171 */ + +typedef struct Steinberg_Vst_IDataExchangeReceiverVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IDataExchangeReceiver": */ + void (SMTG_STDMETHODCALLTYPE* queueOpened) (void* thisInterface, Steinberg_Vst_DataExchangeUserContextID userContextID, Steinberg_uint32 blockSize, Steinberg_TBool* dispatchOnBackgroundThread); + void (SMTG_STDMETHODCALLTYPE* queueClosed) (void* thisInterface, Steinberg_Vst_DataExchangeUserContextID userContextID); + void (SMTG_STDMETHODCALLTYPE* onDataExchangeBlocksReceived) (void* thisInterface, Steinberg_Vst_DataExchangeUserContextID userContextID, Steinberg_uint32 numBlocks, struct Steinberg_Vst_DataExchangeBlock* blocks, Steinberg_TBool onBackgroundThread); + +} Steinberg_Vst_IDataExchangeReceiverVtbl; + +typedef struct Steinberg_Vst_IDataExchangeReceiver +{ + struct Steinberg_Vst_IDataExchangeReceiverVtbl* lpVtbl; +} Steinberg_Vst_IDataExchangeReceiver; + +static const Steinberg_TUID Steinberg_Vst_IDataExchangeReceiver_iid = SMTG_INLINE_UID (0x45A759DC, 0x84FA4907, 0xABCB6175, 0x2FC786B6); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstautomationstate.h", line 39 */ + +typedef struct Steinberg_Vst_IAutomationStateVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IAutomationState": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setAutomationState) (void* thisInterface, Steinberg_int32 state); + +} Steinberg_Vst_IAutomationStateVtbl; + +typedef struct Steinberg_Vst_IAutomationState +{ + struct Steinberg_Vst_IAutomationStateVtbl* lpVtbl; +} Steinberg_Vst_IAutomationState; + +static const Steinberg_TUID Steinberg_Vst_IAutomationState_iid = SMTG_INLINE_UID (0xB4E8287F, 0x1BB346AA, 0x83A46667, 0x68937BAB); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstinterappaudio.h", line 38 */ + +typedef struct Steinberg_Vst_IInterAppAudioHostVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IInterAppAudioHost": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getScreenSize) (void* thisInterface, struct Steinberg_ViewRect* size, float* scale); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* connectedToHost) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* switchToHost) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* sendRemoteControlEvent) (void* thisInterface, Steinberg_uint32 event); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getHostIcon) (void* thisInterface, void** icon); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* scheduleEventFromUI) (void* thisInterface, struct Steinberg_Vst_Event* event); + struct Steinberg_Vst_IInterAppAudioPresetManager* (SMTG_STDMETHODCALLTYPE* createPresetManager) (void* thisInterface, const Steinberg_TUID* cid); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* showSettingsView) (void* thisInterface); + +} Steinberg_Vst_IInterAppAudioHostVtbl; + +typedef struct Steinberg_Vst_IInterAppAudioHost +{ + struct Steinberg_Vst_IInterAppAudioHostVtbl* lpVtbl; +} Steinberg_Vst_IInterAppAudioHost; + +static const Steinberg_TUID Steinberg_Vst_IInterAppAudioHost_iid = SMTG_INLINE_UID (0x0CE5743D, 0x68DF415E, 0xAE285BD4, 0xE2CDC8FD); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstinterappaudio.h", line 101 */ + +typedef struct Steinberg_Vst_IInterAppAudioConnectionNotificationVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IInterAppAudioConnectionNotification": */ + void (SMTG_STDMETHODCALLTYPE* onInterAppAudioConnectionStateChange) (void* thisInterface, Steinberg_TBool newState); + +} Steinberg_Vst_IInterAppAudioConnectionNotificationVtbl; + +typedef struct Steinberg_Vst_IInterAppAudioConnectionNotification +{ + struct Steinberg_Vst_IInterAppAudioConnectionNotificationVtbl* lpVtbl; +} Steinberg_Vst_IInterAppAudioConnectionNotification; + +static const Steinberg_TUID Steinberg_Vst_IInterAppAudioConnectionNotification_iid = SMTG_INLINE_UID (0x6020C72D, 0x5FC24AA1, 0xB0950DB5, 0xD7D6D5CF); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstinterappaudio.h", line 122 */ + +typedef struct Steinberg_Vst_IInterAppAudioPresetManagerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IInterAppAudioPresetManager": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* runLoadPresetBrowser) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* runSavePresetBrowser) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* loadNextPreset) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* loadPreviousPreset) (void* thisInterface); + +} Steinberg_Vst_IInterAppAudioPresetManagerVtbl; + +typedef struct Steinberg_Vst_IInterAppAudioPresetManager +{ + struct Steinberg_Vst_IInterAppAudioPresetManagerVtbl* lpVtbl; +} Steinberg_Vst_IInterAppAudioPresetManager; + +static const Steinberg_TUID Steinberg_Vst_IInterAppAudioPresetManager_iid = SMTG_INLINE_UID (0xADE6FCC4, 0x46C94E1D, 0xB3B49A80, 0xC93FEFDD); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 269 */ + +typedef struct Steinberg_Vst_IAudioProcessorVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IAudioProcessor": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setBusArrangements) (void* thisInterface, Steinberg_Vst_SpeakerArrangement* inputs, Steinberg_int32 numIns, Steinberg_Vst_SpeakerArrangement* outputs, Steinberg_int32 numOuts); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getBusArrangement) (void* thisInterface, Steinberg_Vst_BusDirection dir, Steinberg_int32 index, Steinberg_Vst_SpeakerArrangement* arr); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* canProcessSampleSize) (void* thisInterface, Steinberg_int32 symbolicSampleSize); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* getLatencySamples) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setupProcessing) (void* thisInterface, struct Steinberg_Vst_ProcessSetup* setup); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setProcessing) (void* thisInterface, Steinberg_TBool state); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* process) (void* thisInterface, struct Steinberg_Vst_ProcessData* data); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* getTailSamples) (void* thisInterface); + +} Steinberg_Vst_IAudioProcessorVtbl; + +typedef struct Steinberg_Vst_IAudioProcessor +{ + struct Steinberg_Vst_IAudioProcessorVtbl* lpVtbl; +} Steinberg_Vst_IAudioProcessor; + +static const Steinberg_TUID Steinberg_Vst_IAudioProcessor_iid = SMTG_INLINE_UID (0x42043F99, 0xB7DA453C, 0xA569E79D, 0x9AAEC33D); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 400 */ + +typedef struct Steinberg_Vst_IAudioPresentationLatencyVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IAudioPresentationLatency": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setAudioPresentationLatencySamples) (void* thisInterface, Steinberg_Vst_BusDirection dir, Steinberg_int32 busIndex, Steinberg_uint32 latencyInSamples); + +} Steinberg_Vst_IAudioPresentationLatencyVtbl; + +typedef struct Steinberg_Vst_IAudioPresentationLatency +{ + struct Steinberg_Vst_IAudioPresentationLatencyVtbl* lpVtbl; +} Steinberg_Vst_IAudioPresentationLatency; + +static const Steinberg_TUID Steinberg_Vst_IAudioPresentationLatency_iid = SMTG_INLINE_UID (0x309ECE78, 0xEB7D4fae, 0x8B2225D9, 0x09FD08B6); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstaudioprocessor.h", line 437 */ + +typedef struct Steinberg_Vst_IProcessContextRequirementsVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IProcessContextRequirements": */ + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* getProcessContextRequirements) (void* thisInterface); + +} Steinberg_Vst_IProcessContextRequirementsVtbl; + +typedef struct Steinberg_Vst_IProcessContextRequirements +{ + struct Steinberg_Vst_IProcessContextRequirementsVtbl* lpVtbl; +} Steinberg_Vst_IProcessContextRequirements; + +static const Steinberg_TUID Steinberg_Vst_IProcessContextRequirements_iid = SMTG_INLINE_UID (0x2A654303, 0xEF764E3D, 0x95B5FE83, 0x730EF6D0); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmidimapping2.h", line 128 */ + +typedef struct Steinberg_Vst_IMidiMapping2Vtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IMidiMapping2": */ + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* getNumMidi2ControllerAssignments) (void* thisInterface, Steinberg_Vst_BusDirections direction); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getMidi2ControllerAssignments) (void* thisInterface, Steinberg_Vst_BusDirections direction, const struct Steinberg_Vst_Midi2ControllerParamIDAssignmentList* list); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* getNumMidi1ControllerAssignments) (void* thisInterface, Steinberg_Vst_BusDirections direction); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getMidi1ControllerAssignments) (void* thisInterface, Steinberg_Vst_BusDirections direction, const struct Steinberg_Vst_Midi1ControllerParamIDAssignmentList* list); + +} Steinberg_Vst_IMidiMapping2Vtbl; + +typedef struct Steinberg_Vst_IMidiMapping2 +{ + struct Steinberg_Vst_IMidiMapping2Vtbl* lpVtbl; +} Steinberg_Vst_IMidiMapping2; + +static const Steinberg_TUID Steinberg_Vst_IMidiMapping2_iid = SMTG_INLINE_UID (0x6DE14B88, 0x03F94F09, 0xA2552F0F, 0x9326593E); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstmidimapping2.h", line 188 */ + +typedef struct Steinberg_Vst_IMidiLearn2Vtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IMidiLearn2": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* onLiveMidi2ControllerInput) (void* thisInterface, Steinberg_Vst_BusIndex index, Steinberg_Vst_MidiChannel channel, struct Steinberg_Vst_Midi2Controller midiCC); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* onLiveMidi1ControllerInput) (void* thisInterface, Steinberg_Vst_BusIndex index, Steinberg_Vst_MidiChannel channel, Steinberg_Vst_CtrlNumber midiCC); + +} Steinberg_Vst_IMidiLearn2Vtbl; + +typedef struct Steinberg_Vst_IMidiLearn2 +{ + struct Steinberg_Vst_IMidiLearn2Vtbl* lpVtbl; +} Steinberg_Vst_IMidiLearn2; + +static const Steinberg_TUID Steinberg_Vst_IMidiLearn2_iid = SMTG_INLINE_UID (0xF07E498A, 0x78864327, 0x8B431CED, 0xA3C553FC); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsthostapplication.h", line 35 */ + +typedef struct Steinberg_Vst_IHostApplicationVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IHostApplication": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getName) (void* thisInterface, Steinberg_Vst_String128 name); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* createInstance) (void* thisInterface, Steinberg_TUID cid, Steinberg_TUID iid, void** obj); + +} Steinberg_Vst_IHostApplicationVtbl; + +typedef struct Steinberg_Vst_IHostApplication +{ + struct Steinberg_Vst_IHostApplicationVtbl* lpVtbl; +} Steinberg_Vst_IHostApplication; + +static const Steinberg_TUID Steinberg_Vst_IHostApplication_iid = SMTG_INLINE_UID (0x58E595CC, 0xDB2D4969, 0x8B6AAF8C, 0x36A664E5); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsthostapplication.h", line 76 */ + +typedef struct Steinberg_Vst_IVst3ToVst2WrapperVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + +} Steinberg_Vst_IVst3ToVst2WrapperVtbl; + +typedef struct Steinberg_Vst_IVst3ToVst2Wrapper +{ + struct Steinberg_Vst_IVst3ToVst2WrapperVtbl* lpVtbl; +} Steinberg_Vst_IVst3ToVst2Wrapper; + +static const Steinberg_TUID Steinberg_Vst_IVst3ToVst2Wrapper_iid = SMTG_INLINE_UID (0x29633AEC, 0x1D1C47E2, 0xBB85B97B, 0xD36EAC61); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsthostapplication.h", line 96 */ + +typedef struct Steinberg_Vst_IVst3ToAUWrapperVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + +} Steinberg_Vst_IVst3ToAUWrapperVtbl; + +typedef struct Steinberg_Vst_IVst3ToAUWrapper +{ + struct Steinberg_Vst_IVst3ToAUWrapperVtbl* lpVtbl; +} Steinberg_Vst_IVst3ToAUWrapper; + +static const Steinberg_TUID Steinberg_Vst_IVst3ToAUWrapper_iid = SMTG_INLINE_UID (0xA3B8C6C5, 0xC0954688, 0xB0916F0B, 0xB697AA44); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsthostapplication.h", line 116 */ + +typedef struct Steinberg_Vst_IVst3ToAAXWrapperVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + +} Steinberg_Vst_IVst3ToAAXWrapperVtbl; + +typedef struct Steinberg_Vst_IVst3ToAAXWrapper +{ + struct Steinberg_Vst_IVst3ToAAXWrapperVtbl* lpVtbl; +} Steinberg_Vst_IVst3ToAAXWrapper; + +static const Steinberg_TUID Steinberg_Vst_IVst3ToAAXWrapper_iid = SMTG_INLINE_UID (0x6D319DC6, 0x60C56242, 0xB32C951B, 0x93BEF4C6); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsthostapplication.h", line 140 */ + +typedef struct Steinberg_Vst_IVst3WrapperMPESupportVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IVst3WrapperMPESupport": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* enableMPEInputProcessing) (void* thisInterface, Steinberg_TBool state); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setMPEInputDeviceSettings) (void* thisInterface, Steinberg_int32 masterChannel, Steinberg_int32 memberBeginChannel, Steinberg_int32 memberEndChannel); + +} Steinberg_Vst_IVst3WrapperMPESupportVtbl; + +typedef struct Steinberg_Vst_IVst3WrapperMPESupport +{ + struct Steinberg_Vst_IVst3WrapperMPESupportVtbl* lpVtbl; +} Steinberg_Vst_IVst3WrapperMPESupport; + +static const Steinberg_TUID Steinberg_Vst_IVst3WrapperMPESupport_iid = SMTG_INLINE_UID (0x44149067, 0x42CF4BF9, 0x8800B750, 0xF7359FE3); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstplugview.h", line 44 */ + +typedef struct Steinberg_Vst_IParameterFinderVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IParameterFinder": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* findParameter) (void* thisInterface, Steinberg_int32 xPos, Steinberg_int32 yPos, Steinberg_Vst_ParamID* resultTag); + +} Steinberg_Vst_IParameterFinderVtbl; + +typedef struct Steinberg_Vst_IParameterFinder +{ + struct Steinberg_Vst_IParameterFinderVtbl* lpVtbl; +} Steinberg_Vst_IParameterFinder; + +static const Steinberg_TUID Steinberg_Vst_IParameterFinder_iid = SMTG_INLINE_UID (0x0F618302, 0x215D4587, 0xA512073C, 0x77B9D383); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstnoteonorchestralarticulationinfo.h", line 65 */ + +typedef struct Steinberg_Vst_NoteOnOrchestralArticulation_IInfoVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_NoteOnOrchestralArticulation_IInfo": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getVariationsInfo) (void* thisInterface, Steinberg_int32 busIndex, Steinberg_int16 channel, struct Steinberg_Vst_NoteOnOrchestralArticulation_ClassificationVariations* info); + +} Steinberg_Vst_NoteOnOrchestralArticulation_IInfoVtbl; + +typedef struct Steinberg_Vst_NoteOnOrchestralArticulation_IInfo +{ + struct Steinberg_Vst_NoteOnOrchestralArticulation_IInfoVtbl* lpVtbl; +} Steinberg_Vst_NoteOnOrchestralArticulation_IInfo; + +static const Steinberg_TUID Steinberg_Vst_NoteOnOrchestralArticulation_IInfo_iid = SMTG_INLINE_UID (0x7D34A9B4, 0x89CA45F4, 0x9284A9FD, 0x4DD9C906); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivsttransportcontrol.h", line 100 */ + +typedef struct Steinberg_Vst_ITransportControlVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_ITransportControl": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* requestAction) (void* thisInterface, Steinberg_int32 action, struct Steinberg_Vst_TransportPosition* position); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* isActionSupported) (void* thisInterface, Steinberg_int32 action); + +} Steinberg_Vst_ITransportControlVtbl; + +typedef struct Steinberg_Vst_ITransportControl +{ + struct Steinberg_Vst_ITransportControlVtbl* lpVtbl; +} Steinberg_Vst_ITransportControl; + +static const Steinberg_TUID Steinberg_Vst_ITransportControl_iid = SMTG_INLINE_UID (0xD752F52D, 0x004348A0, 0xB431B045, 0xF0DCA49C); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstunits.h", line 80 */ + +typedef struct Steinberg_Vst_IUnitHandlerVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IUnitHandler": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* notifyUnitSelection) (void* thisInterface, Steinberg_Vst_UnitID unitId); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* notifyProgramListChange) (void* thisInterface, Steinberg_Vst_ProgramListID listId, Steinberg_int32 programIndex); + +} Steinberg_Vst_IUnitHandlerVtbl; + +typedef struct Steinberg_Vst_IUnitHandler +{ + struct Steinberg_Vst_IUnitHandlerVtbl* lpVtbl; +} Steinberg_Vst_IUnitHandler; + +static const Steinberg_TUID Steinberg_Vst_IUnitHandler_iid = SMTG_INLINE_UID (0x4B5147F8, 0x4654486B, 0x8DAB30BA, 0x163A3C56); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstunits.h", line 121 */ + +typedef struct Steinberg_Vst_IUnitHandler2Vtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IUnitHandler2": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* notifyUnitByBusChange) (void* thisInterface); + +} Steinberg_Vst_IUnitHandler2Vtbl; + +typedef struct Steinberg_Vst_IUnitHandler2 +{ + struct Steinberg_Vst_IUnitHandler2Vtbl* lpVtbl; +} Steinberg_Vst_IUnitHandler2; + +static const Steinberg_TUID Steinberg_Vst_IUnitHandler2_iid = SMTG_INLINE_UID (0xF89F8CDF, 0x699E4BA5, 0x96AAC9A4, 0x81452B01); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstunits.h", line 151 */ + +typedef struct Steinberg_Vst_IUnitInfoVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IUnitInfo": */ + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getUnitCount) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getUnitInfo) (void* thisInterface, Steinberg_int32 unitIndex, struct Steinberg_Vst_UnitInfo* info); + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getProgramListCount) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getProgramListInfo) (void* thisInterface, Steinberg_int32 listIndex, struct Steinberg_Vst_ProgramListInfo* info); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getProgramName) (void* thisInterface, Steinberg_Vst_ProgramListID listId, Steinberg_int32 programIndex, Steinberg_Vst_String128 name); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getProgramInfo) (void* thisInterface, Steinberg_Vst_ProgramListID listId, Steinberg_int32 programIndex, Steinberg_Vst_CString attributeId, Steinberg_Vst_String128 attributeValue); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* hasProgramPitchNames) (void* thisInterface, Steinberg_Vst_ProgramListID listId, Steinberg_int32 programIndex); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getProgramPitchName) (void* thisInterface, Steinberg_Vst_ProgramListID listId, Steinberg_int32 programIndex, Steinberg_int16 midiPitch, Steinberg_Vst_String128 name); + Steinberg_Vst_UnitID (SMTG_STDMETHODCALLTYPE* getSelectedUnit) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* selectUnit) (void* thisInterface, Steinberg_Vst_UnitID unitId); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getUnitByBus) (void* thisInterface, Steinberg_Vst_MediaType type, Steinberg_Vst_BusDirection dir, Steinberg_int32 busIndex, Steinberg_int32 channel, Steinberg_Vst_UnitID* unitId); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setUnitProgramData) (void* thisInterface, Steinberg_int32 listOrUnitId, Steinberg_int32 programIndex, struct Steinberg_IBStream* data); + +} Steinberg_Vst_IUnitInfoVtbl; + +typedef struct Steinberg_Vst_IUnitInfo +{ + struct Steinberg_Vst_IUnitInfoVtbl* lpVtbl; +} Steinberg_Vst_IUnitInfo; + +static const Steinberg_TUID Steinberg_Vst_IUnitInfo_iid = SMTG_INLINE_UID (0x3D4BD6B5, 0x913A4FD2, 0xA886E768, 0xA5EB92C1); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstunits.h", line 242 */ + +typedef struct Steinberg_Vst_IProgramListDataVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IProgramListData": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* programDataSupported) (void* thisInterface, Steinberg_Vst_ProgramListID listId); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getProgramData) (void* thisInterface, Steinberg_Vst_ProgramListID listId, Steinberg_int32 programIndex, struct Steinberg_IBStream* data); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setProgramData) (void* thisInterface, Steinberg_Vst_ProgramListID listId, Steinberg_int32 programIndex, struct Steinberg_IBStream* data); + +} Steinberg_Vst_IProgramListDataVtbl; + +typedef struct Steinberg_Vst_IProgramListData +{ + struct Steinberg_Vst_IProgramListDataVtbl* lpVtbl; +} Steinberg_Vst_IProgramListData; + +static const Steinberg_TUID Steinberg_Vst_IProgramListData_iid = SMTG_INLINE_UID (0x8683B01F, 0x7B354F70, 0xA2651DEC, 0x353AF4FF); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstunits.h", line 279 */ + +typedef struct Steinberg_Vst_IUnitDataVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IUnitData": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* unitDataSupported) (void* thisInterface, Steinberg_Vst_UnitID unitID); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getUnitData) (void* thisInterface, Steinberg_Vst_UnitID unitId, struct Steinberg_IBStream* data); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* setUnitData) (void* thisInterface, Steinberg_Vst_UnitID unitId, struct Steinberg_IBStream* data); + +} Steinberg_Vst_IUnitDataVtbl; + +typedef struct Steinberg_Vst_IUnitData +{ + struct Steinberg_Vst_IUnitDataVtbl* lpVtbl; +} Steinberg_Vst_IUnitData; + +static const Steinberg_TUID Steinberg_Vst_IUnitData_iid = SMTG_INLINE_UID (0x6C389611, 0xD391455D, 0xB870B833, 0x94A0EFDD); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstpluginterfacesupport.h", line 53 */ + +typedef struct Steinberg_Vst_IPlugInterfaceSupportVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IPlugInterfaceSupport": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* isPlugInterfaceSupported) (void* thisInterface, const Steinberg_TUID iid); + +} Steinberg_Vst_IPlugInterfaceSupportVtbl; + +typedef struct Steinberg_Vst_IPlugInterfaceSupport +{ + struct Steinberg_Vst_IPlugInterfaceSupportVtbl* lpVtbl; +} Steinberg_Vst_IPlugInterfaceSupport; + +static const Steinberg_TUID Steinberg_Vst_IPlugInterfaceSupport_iid = SMTG_INLINE_UID (0x4FB58B9E, 0x9EAA4E0F, 0xAB361C1C, 0xCCB56FEA); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstparameterfunctionname.h", line 141 */ + +typedef struct Steinberg_Vst_IParameterFunctionNameVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IParameterFunctionName": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getParameterIDFromFunctionName) (void* thisInterface, Steinberg_Vst_UnitID unitID, Steinberg_FIDString functionName, Steinberg_Vst_ParamID* paramID); + +} Steinberg_Vst_IParameterFunctionNameVtbl; + +typedef struct Steinberg_Vst_IParameterFunctionName +{ + struct Steinberg_Vst_IParameterFunctionNameVtbl* lpVtbl; +} Steinberg_Vst_IParameterFunctionName; + +static const Steinberg_TUID Steinberg_Vst_IParameterFunctionName_iid = SMTG_INLINE_UID (0x6D21E1DC, 0x91199D4B, 0xA2A02FEF, 0x6C1AE55C); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstparameterchanges.h", line 84 */ + +typedef struct Steinberg_Vst_IParamValueQueueVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IParamValueQueue": */ + Steinberg_Vst_ParamID (SMTG_STDMETHODCALLTYPE* getParameterId) (void* thisInterface); + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getPointCount) (void* thisInterface); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* getPoint) (void* thisInterface, Steinberg_int32 index, Steinberg_int32* sampleOffset, Steinberg_Vst_ParamValue* value); + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* addPoint) (void* thisInterface, Steinberg_int32 sampleOffset, Steinberg_Vst_ParamValue value, Steinberg_int32* index); + +} Steinberg_Vst_IParamValueQueueVtbl; + +typedef struct Steinberg_Vst_IParamValueQueue +{ + struct Steinberg_Vst_IParamValueQueueVtbl* lpVtbl; +} Steinberg_Vst_IParamValueQueue; + +static const Steinberg_TUID Steinberg_Vst_IParamValueQueue_iid = SMTG_INLINE_UID (0x01263A18, 0xED074F6F, 0x98C9D356, 0x4686F9BA); + +/*---------------------------------------------------------------------------------------------------------------------- +Source: "pluginterfaces/vst/ivstparameterchanges.h", line 121 */ + +typedef struct Steinberg_Vst_IParameterChangesVtbl +{ + /* methods derived from "Steinberg_FUnknown": */ + Steinberg_tresult (SMTG_STDMETHODCALLTYPE* queryInterface) (void* thisInterface, const Steinberg_TUID iid, void** obj); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* addRef) (void* thisInterface); + Steinberg_uint32 (SMTG_STDMETHODCALLTYPE* release) (void* thisInterface); + + /* methods defined in "Steinberg_Vst_IParameterChanges": */ + Steinberg_int32 (SMTG_STDMETHODCALLTYPE* getParameterCount) (void* thisInterface); + struct Steinberg_Vst_IParamValueQueue* (SMTG_STDMETHODCALLTYPE* getParameterData) (void* thisInterface, Steinberg_int32 index); + struct Steinberg_Vst_IParamValueQueue* (SMTG_STDMETHODCALLTYPE* addParameterData) (void* thisInterface, const Steinberg_Vst_ParamID* id, Steinberg_int32* index); + +} Steinberg_Vst_IParameterChangesVtbl; + +typedef struct Steinberg_Vst_IParameterChanges +{ + struct Steinberg_Vst_IParameterChangesVtbl* lpVtbl; +} Steinberg_Vst_IParameterChanges; + +static const Steinberg_TUID Steinberg_Vst_IParameterChanges_iid = SMTG_INLINE_UID (0xA4779663, 0x0BB64A56, 0xB44384A8, 0x466FEB9D); + diff --git a/plugins/feature/denoiser/vst3effect.cpp b/plugins/feature/denoiser/vst3effect.cpp new file mode 100644 index 000000000..e5dc23e1f --- /dev/null +++ b/plugins/feature/denoiser/vst3effect.cpp @@ -0,0 +1,1415 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef QT_WIDGETS_LIB +#include +#include +#endif +#include +#include +#include +#include +#include +#ifdef Q_OS_LINUX +#include +#endif +#ifdef Q_OS_MAC +#include +#endif + +#include "vst3effect.h" +#include "vst3/vst3_c_api.h" + +namespace +{ +constexpr int kBlockSize = 512; + +#ifndef Q_OS_MAC +QString binaryPath(const QString &path) +{ + const QFileInfo info(path); + if (info.isFile()) + { + return info.absoluteFilePath(); + } + if (!info.isDir() || !path.endsWith(QLatin1String(".vst3"), Qt::CaseInsensitive)) + { + return {}; + } + const QDir bundle(path); + const QString name = info.fileName(); +#ifdef Q_OS_WIN +#if defined(Q_PROCESSOR_X86_64) + const QString arch = QStringLiteral("x86_64-win"); +#elif defined(Q_PROCESSOR_ARM_64) + const QString arch = QStringLiteral("arm64-win"); +#else + const QString arch = QStringLiteral("x86-win"); +#endif + const QString candidate = bundle.filePath(QStringLiteral("Contents/%1/%2").arg(arch, name)); +#elif defined(Q_OS_LINUX) +#if defined(Q_PROCESSOR_X86_64) + const QString arch = QStringLiteral("x86_64-linux"); +#else + const QString arch = QStringLiteral("%1-linux").arg(QSysInfo::currentCpuArchitecture()); +#endif + QString binaryName = name; + binaryName.chop(5); // Remove the .vst3 bundle extension. + const QString candidate = bundle.filePath(QStringLiteral("Contents/%1/%2.so").arg(arch, binaryName)); +#else + return {}; +#endif + if (QFileInfo::exists(candidate)) + { + return candidate; + } + return {}; +} +#endif + +struct Module +{ +#ifdef Q_OS_MAC + CFBundleRef bundle = nullptr; +#else + QLibrary library; +#endif + Steinberg_IPluginFactory *factory = nullptr; + using Exit = bool (*)(); + Exit exit = nullptr; + bool entered = false; +#ifdef Q_OS_LINUX + void *nativeHandle = nullptr; +#endif + + bool load(const QString &path, QString &error) + { +#ifdef Q_OS_MAC + const QFileInfo info(path); + if (!info.isDir() || !path.endsWith(QLatin1String(".vst3"), Qt::CaseInsensitive)) + { + error = QStringLiteral("VST3 bundle was not found in %1").arg(path); + return false; + } + const QByteArray utf8Path = info.absoluteFilePath().toUtf8(); + CFStringRef cfPath = + CFStringCreateWithCString(kCFAllocatorDefault, utf8Path.constData(), kCFStringEncodingUTF8); + if (!cfPath) + { + error = QStringLiteral("Invalid VST3 bundle path: %1").arg(path); + return false; + } + CFURLRef url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, cfPath, kCFURLPOSIXPathStyle, true); + CFRelease(cfPath); + if (!url) + { + error = QStringLiteral("Invalid VST3 bundle URL: %1").arg(path); + return false; + } + bundle = CFBundleCreate(kCFAllocatorDefault, url); + CFRelease(url); + if (!bundle || !CFBundleLoadExecutable(bundle)) + { + error = QStringLiteral("Could not load VST3 bundle: %1").arg(path); + close(); + return false; + } + auto entry = + reinterpret_cast(CFBundleGetFunctionPointerForName(bundle, CFSTR("bundleEntry"))); + exit = reinterpret_cast(CFBundleGetFunctionPointerForName(bundle, CFSTR("bundleExit"))); + if (!entry || !exit || !entry(bundle)) + { + error = QStringLiteral("VST3 bundleEntry failed or is missing"); + close(); + return false; + } + entered = true; + auto getFactory = reinterpret_cast( + CFBundleGetFunctionPointerForName(bundle, CFSTR("GetPluginFactory"))); +#else + const QString binary = binaryPath(path); + if (binary.isEmpty()) + { + error = QStringLiteral("VST3 binary was not found in %1").arg(path); + return false; + } + library.setFileName(binary); + if (!library.load()) + { + error = library.errorString(); + return false; + } +#ifdef Q_OS_WIN + auto entry = reinterpret_cast(library.resolve("InitDll")); + exit = reinterpret_cast(library.resolve("ExitDll")); + if (entry) + { + if (!entry()) + { + error = QStringLiteral("VST3 InitDll failed"); + close(); + return false; + } + entered = true; + } +#elif defined(Q_OS_LINUX) + auto entry = reinterpret_cast(library.resolve("ModuleEntry")); + exit = reinterpret_cast(library.resolve("ModuleExit")); + // VST3 requires the dlopen handle in ModuleEntry; QLibrary does not expose it. + nativeHandle = dlopen(binary.toLocal8Bit().constData(), RTLD_NOW | RTLD_LOCAL); + if (!entry || !exit || !nativeHandle || !entry(nativeHandle)) + { + error = QStringLiteral("VST3 ModuleEntry failed or is missing"); + close(); + return false; + } + entered = true; +#endif + auto getFactory = reinterpret_cast(library.resolve("GetPluginFactory")); +#endif + factory = getFactory ? getFactory() : nullptr; + if (!factory) + { + error = QStringLiteral("VST3 GetPluginFactory failed"); + close(); + return false; + } + return true; + } + + void close() + { + if (factory) + { + factory->lpVtbl->release(factory); + factory = nullptr; + } + if (exit && entered) + { + exit(); + } + exit = nullptr; + entered = false; +#ifdef Q_OS_LINUX + if (nativeHandle) + { + dlclose(nativeHandle); + nativeHandle = nullptr; + } +#endif +#ifdef Q_OS_MAC + if (bundle) + { + CFBundleUnloadExecutable(bundle); + CFRelease(bundle); + bundle = nullptr; + } +#else + if (library.isLoaded()) + { + library.unload(); + } +#endif + } + ~Module() + { + close(); + } +}; + +Steinberg_tresult SMTG_STDMETHODCALLTYPE hostQuery(void *self, const Steinberg_TUID iid, void **obj) +{ + if (!obj) + { + return Steinberg_kInvalidArgument; + } + if (std::memcmp(iid, Steinberg_FUnknown_iid, 16) == 0 || + std::memcmp(iid, Steinberg_Vst_IHostApplication_iid, 16) == 0) + { + *obj = self; + return Steinberg_kResultOk; + } + *obj = nullptr; + return Steinberg_kNoInterface; +} + +Steinberg_uint32 SMTG_STDMETHODCALLTYPE hostAddRef(void *) +{ + return 1; +} + +Steinberg_uint32 SMTG_STDMETHODCALLTYPE hostRelease(void *) +{ + return 1; +} + +Steinberg_tresult SMTG_STDMETHODCALLTYPE hostName(void *, Steinberg_Vst_String128 name) +{ + constexpr char16_t text[] = u"SDRangel"; + std::memset(name, 0, 128 * sizeof(Steinberg_Vst_TChar)); + std::memcpy(name, text, sizeof(text)); + return Steinberg_kResultOk; +} + +Steinberg_tresult SMTG_STDMETHODCALLTYPE hostCreate(void *, Steinberg_TUID, Steinberg_TUID, void **obj) +{ + if (obj) + { + *obj = nullptr; + } + return Steinberg_kNoInterface; +} +Steinberg_Vst_IHostApplicationVtbl hostVtbl = {hostQuery, hostAddRef, hostRelease, hostName, hostCreate}; +Steinberg_Vst_IHostApplication host = {&hostVtbl}; + +struct ComponentHandler +{ + Steinberg_Vst_IComponentHandler iface; + std::function queue; // Forwards editor edits to this instance's processor. + std::function onEdit; +}; + +Steinberg_tresult SMTG_STDMETHODCALLTYPE handlerQuery(void *self, const Steinberg_TUID iid, void **obj) +{ + if (!obj) + { + return Steinberg_kInvalidArgument; + } + if (std::memcmp(iid, Steinberg_FUnknown_iid, 16) == 0 || + std::memcmp(iid, Steinberg_Vst_IComponentHandler_iid, 16) == 0) + { + *obj = self; + return Steinberg_kResultOk; + } + *obj = nullptr; + return Steinberg_kNoInterface; +} +Steinberg_tresult SMTG_STDMETHODCALLTYPE handlerEdit(void *, Steinberg_Vst_ParamID) +{ + return Steinberg_kResultOk; +} +Steinberg_tresult SMTG_STDMETHODCALLTYPE handlerPerformEdit(void *self, Steinberg_Vst_ParamID id, + Steinberg_Vst_ParamValue value) +{ + auto *componentHandler = static_cast(self); + if (!std::isfinite(value) || value < 0.0 || value > 1.0) + { + return Steinberg_kInvalidArgument; + } + if (componentHandler->queue) + { + componentHandler->queue(id, value); + } + if (componentHandler->onEdit) + { + componentHandler->onEdit(id, value); + } + return Steinberg_kResultOk; +} +Steinberg_tresult SMTG_STDMETHODCALLTYPE handlerRestart(void *, Steinberg_int32) +{ + return Steinberg_kResultOk; +} +Steinberg_Vst_IComponentHandlerVtbl handlerVtbl = {handlerQuery, hostAddRef, hostRelease, handlerEdit, + handlerPerformEdit, handlerEdit, handlerRestart}; + +#ifdef QT_WIDGETS_LIB +struct EditorFrame +{ + Steinberg_IPlugFrame iface; + std::function resize; +}; + +Steinberg_tresult SMTG_STDMETHODCALLTYPE frameQuery(void *self, const Steinberg_TUID iid, void **obj) +{ + if (!obj) + { + return Steinberg_kInvalidArgument; + } + if (std::memcmp(iid, Steinberg_FUnknown_iid, 16) == 0 || std::memcmp(iid, Steinberg_IPlugFrame_iid, 16) == 0) + { + *obj = self; + return Steinberg_kResultOk; + } + *obj = nullptr; + return Steinberg_kNoInterface; +} + +Steinberg_tresult SMTG_STDMETHODCALLTYPE frameResize(void *self, Steinberg_IPlugView *view, Steinberg_ViewRect *size) +{ + auto *frame = static_cast(self); + return frame->resize ? frame->resize(view, size) : Steinberg_kResultFalse; +} + +Steinberg_IPlugFrameVtbl frameVtbl = {frameQuery, hostAddRef, hostRelease, frameResize}; +#endif + +bool ok(Steinberg_tresult status) +{ + return status == Steinberg_kResultOk; +} + +struct ParameterPoint +{ + Steinberg_Vst_IParamValueQueue iface; + Steinberg_Vst_ParamID id; + Steinberg_Vst_ParamValue value; +}; +struct ParameterChanges +{ + Steinberg_Vst_IParameterChanges iface; + ParameterPoint points[128]; + int count = 0; +}; +Steinberg_tresult SMTG_STDMETHODCALLTYPE pointQuery(void *self, const Steinberg_TUID iid, void **obj) +{ + if (!obj) + { + return Steinberg_kInvalidArgument; + } + if (std::memcmp(iid, Steinberg_FUnknown_iid, 16) == 0 || + std::memcmp(iid, Steinberg_Vst_IParamValueQueue_iid, 16) == 0) + { + *obj = self; + return Steinberg_kResultOk; + } + *obj = nullptr; + return Steinberg_kNoInterface; +} +Steinberg_Vst_ParamID SMTG_STDMETHODCALLTYPE paramId(void *self) +{ + return static_cast(self)->id; +} +Steinberg_int32 SMTG_STDMETHODCALLTYPE pointCount(void *) +{ + return 1; +} +Steinberg_tresult SMTG_STDMETHODCALLTYPE getPoint(void *self, Steinberg_int32 index, Steinberg_int32 *offset, + Steinberg_Vst_ParamValue *value) +{ + if (index != 0 || !offset || !value) + { + return Steinberg_kInvalidArgument; + } + *offset = 0; + *value = static_cast(self)->value; + return Steinberg_kResultOk; +} +Steinberg_tresult SMTG_STDMETHODCALLTYPE addPoint(void *, Steinberg_int32, Steinberg_Vst_ParamValue, Steinberg_int32 *) +{ + return Steinberg_kNotImplemented; +} +Steinberg_Vst_IParamValueQueueVtbl pointVtbl = {pointQuery, hostAddRef, hostRelease, paramId, + pointCount, getPoint, addPoint}; +Steinberg_tresult SMTG_STDMETHODCALLTYPE changesQuery(void *self, const Steinberg_TUID iid, void **obj) +{ + if (!obj) + { + return Steinberg_kInvalidArgument; + } + if (std::memcmp(iid, Steinberg_FUnknown_iid, 16) == 0 || + std::memcmp(iid, Steinberg_Vst_IParameterChanges_iid, 16) == 0) + { + *obj = self; + return Steinberg_kResultOk; + } + *obj = nullptr; + return Steinberg_kNoInterface; +} +Steinberg_int32 SMTG_STDMETHODCALLTYPE changeCount(void *self) +{ + return static_cast(self)->count; +} +Steinberg_Vst_IParamValueQueue *SMTG_STDMETHODCALLTYPE parameterData(void *self, Steinberg_int32 index) +{ + auto *changes = static_cast(self); + return index >= 0 && index < changes->count ? &changes->points[index].iface : nullptr; +} +Steinberg_Vst_IParamValueQueue *SMTG_STDMETHODCALLTYPE addParameterData(void *, const Steinberg_Vst_ParamID *, + Steinberg_int32 *) +{ + return nullptr; +} +Steinberg_Vst_IParameterChangesVtbl changesVtbl = {changesQuery, hostAddRef, hostRelease, + changeCount, parameterData, addParameterData}; + +// In-memory IBStream used to save and restore component and controller state. +struct MemoryStream +{ + Steinberg_IBStream iface; + QByteArray data; + qint64 position = 0; +}; + +Steinberg_tresult SMTG_STDMETHODCALLTYPE streamQuery(void *self, const Steinberg_TUID iid, void **obj) +{ + if (!obj) { + return Steinberg_kInvalidArgument; + } + if (std::memcmp(iid, Steinberg_FUnknown_iid, 16) == 0 || std::memcmp(iid, Steinberg_IBStream_iid, 16) == 0) + { + *obj = self; + return Steinberg_kResultOk; + } + *obj = nullptr; + return Steinberg_kNoInterface; +} + +Steinberg_tresult SMTG_STDMETHODCALLTYPE streamRead(void *self, void *buffer, Steinberg_int32 numBytes, + Steinberg_int32 *numBytesRead) +{ + auto *stream = static_cast(self); + if (!buffer || numBytes < 0) { + return Steinberg_kInvalidArgument; + } + const qint64 available = std::max(0, stream->data.size() - stream->position); + const Steinberg_int32 count = static_cast(std::min(numBytes, available)); + if (count > 0) + { + std::memcpy(buffer, stream->data.constData() + stream->position, count); + stream->position += count; + } + if (numBytesRead) { + *numBytesRead = count; + } + return Steinberg_kResultOk; +} + +Steinberg_tresult SMTG_STDMETHODCALLTYPE streamWrite(void *self, void *buffer, Steinberg_int32 numBytes, + Steinberg_int32 *numBytesWritten) +{ + auto *stream = static_cast(self); + const qint64 end = stream->position + numBytes; + if (!buffer || numBytes < 0 || end > 0x7fffffff) { + return Steinberg_kInvalidArgument; + } + if (end > stream->data.size()) { + stream->data.resize(static_cast(end)); + } + std::memcpy(stream->data.data() + stream->position, buffer, numBytes); + stream->position = end; + if (numBytesWritten) { + *numBytesWritten = numBytes; + } + return Steinberg_kResultOk; +} + +Steinberg_tresult SMTG_STDMETHODCALLTYPE streamSeek(void *self, Steinberg_int64 pos, Steinberg_int32 mode, + Steinberg_int64 *result) +{ + auto *stream = static_cast(self); + qint64 position = pos; + if (mode == Steinberg_IBStream_IStreamSeekMode_kIBSeekCur) { + position += stream->position; + } else if (mode == Steinberg_IBStream_IStreamSeekMode_kIBSeekEnd) { + position += stream->data.size(); + } else if (mode != Steinberg_IBStream_IStreamSeekMode_kIBSeekSet) { + return Steinberg_kInvalidArgument; + } + if (position < 0) { + return Steinberg_kInvalidArgument; + } + stream->position = position; + if (result) { + *result = position; + } + return Steinberg_kResultOk; +} + +Steinberg_tresult SMTG_STDMETHODCALLTYPE streamTell(void *self, Steinberg_int64 *pos) +{ + if (!pos) { + return Steinberg_kInvalidArgument; + } + *pos = static_cast(self)->position; + return Steinberg_kResultOk; +} + +Steinberg_IBStreamVtbl streamVtbl = {streamQuery, hostAddRef, hostRelease, streamRead, + streamWrite, streamSeek, streamTell}; + +MemoryStream makeStream(const QByteArray &data = QByteArray()) +{ + MemoryStream stream; + stream.iface.lpVtbl = &streamVtbl; + stream.data = data; + return stream; +} + +// Saved state container: magic, version, class ID, component state, controller state. +constexpr quint32 kStateMagic = 0x53565354; +constexpr quint32 kStateVersion = 1; +} // namespace + +struct Vst3Effect::Impl +{ + Module module; + QByteArray classId; + ComponentHandler handler = {{&handlerVtbl}, {}}; + std::function detachEditor; + Steinberg_Vst_IComponent *component = nullptr; + Steinberg_Vst_IAudioProcessor *processor = nullptr; + Steinberg_Vst_IEditController *controller = nullptr; + Steinberg_Vst_IConnectionPoint *componentConnection = nullptr; + Steinberg_Vst_IConnectionPoint *controllerConnection = nullptr; + bool componentConnected = false; + bool controllerConnected = false; + bool controllerInitialized = false; + QVector parameterInfos; + QMutex parameterMutex; + ParameterPoint pending[128] = {}; + int pendingCount = 0; + bool initialized = false; + bool active = false; + bool processing = false; + int inputChannels = 0; + int outputChannels = 0; + int sourceChannels = 0; + int inputBusCount = 0; + int outputBusCount = 0; + bool sample64 = false; + double sampleRate = 0.0; + Steinberg_Vst_TSamples processedSamples = 0; + double input64[2][kBlockSize] = {}; + double output64[2][kBlockSize] = {}; + float monoInput[kBlockSize] = {}; + + bool queueParameter(quint32 id, double value) + { + QMutexLocker lock(¶meterMutex); + for (int i = 0; i < pendingCount; ++i) + { + if (pending[i].id == id) + { + pending[i].value = value; + return true; + } + } + if (pendingCount >= 128) + { + return false; + } + pending[pendingCount].id = id; + pending[pendingCount].value = value; + ++pendingCount; + return true; + } + + void close() + { + if (detachEditor) + { + auto detach = std::move(detachEditor); + detach(); + } + if (processor && processing) + { + processor->lpVtbl->setProcessing(processor, 0); + } + processing = false; + if (component && active) + { + component->lpVtbl->setActive(component, 0); + } + active = false; + if (processor) + { + processor->lpVtbl->release(processor); + processor = nullptr; + } + if (controllerConnection && controllerConnected) + { + controllerConnection->lpVtbl->disconnect(controllerConnection, componentConnection); + } + if (componentConnection && componentConnected) + { + componentConnection->lpVtbl->disconnect(componentConnection, controllerConnection); + } + controllerConnected = false; + componentConnected = false; + if (controllerConnection) + { + controllerConnection->lpVtbl->release(controllerConnection); + controllerConnection = nullptr; + } + if (componentConnection) + { + componentConnection->lpVtbl->release(componentConnection); + componentConnection = nullptr; + } + if (controller) + { + controller->lpVtbl->setComponentHandler(controller, nullptr); + if (controllerInitialized) + { + controller->lpVtbl->terminate(controller); + } + controller->lpVtbl->release(controller); + controller = nullptr; + } + controllerInitialized = false; + parameterInfos.clear(); + pendingCount = 0; + if (component) + { + if (initialized) + { + component->lpVtbl->terminate(component); + } + component->lpVtbl->release(component); + component = nullptr; + } + initialized = false; + classId.clear(); + module.close(); + } + ~Impl() + { + close(); + } +}; + +#ifdef QT_WIDGETS_LIB +class Vst3Effect::EditorWidget : public QWidget +{ +public: + EditorWidget(Vst3Effect *effect, QWidget *parent) : QWidget(parent), m_effect(effect) + { + setAttribute(Qt::WA_NativeWindow); + setFocusPolicy(Qt::StrongFocus); + m_frame.iface.lpVtbl = &frameVtbl; + m_frame.resize = [this](Steinberg_IPlugView *view, Steinberg_ViewRect *size) + { + return resizeFromPlugin(view, size); + }; + } + + ~EditorWidget() override + { + detach(); + m_effect->m_impl->detachEditor = {}; + } + + bool attach(QString &error) + { + auto &impl = *m_effect->m_impl; + if (!impl.controller) + { + error = QStringLiteral("VST3 effect has no editor controller"); + return false; + } + + const char *platformType = nullptr; +#ifdef Q_OS_WIN + platformType = Steinberg_kPlatformTypeHWND; +#elif defined(Q_OS_MAC) + platformType = Steinberg_kPlatformTypeNSView; +#elif defined(Q_OS_LINUX) + if (QGuiApplication::platformName() == QLatin1String("xcb")) + { + platformType = Steinberg_kPlatformTypeX11EmbedWindowID; + } +#endif + if (!platformType) + { + error = QStringLiteral("No native VST3 editor window is available on this display"); + return false; + } + + m_view = impl.controller->lpVtbl->createView(impl.controller, Steinberg_Vst_ViewType_kEditor); + if (!m_view) + { + error = QStringLiteral("This VST3 effect has no custom editor"); + return false; + } + if (!ok(m_view->lpVtbl->isPlatformTypeSupported(m_view, platformType))) + { + error = QStringLiteral("This VST3 editor does not support the current window system"); + detach(); + return false; + } + + Steinberg_IPlugViewContentScaleSupport *scaleSupport = nullptr; + if (ok(m_view->lpVtbl->queryInterface(m_view, Steinberg_IPlugViewContentScaleSupport_iid, + reinterpret_cast(&scaleSupport))) && + scaleSupport) + { + scaleSupport->lpVtbl->setContentScaleFactor(scaleSupport, static_cast(devicePixelRatioF())); + scaleSupport->lpVtbl->release(scaleSupport); + } + + Steinberg_ViewRect size = {}; + if (!ok(m_view->lpVtbl->getSize(m_view, &size)) || size.right <= size.left || size.bottom <= size.top) + { + size = {0, 0, 640, 400}; + } + const qreal scale = nativeScale(); + setFixedSize(qMax(1, qRound((size.right - size.left) / scale)), + qMax(1, qRound((size.bottom - size.top) / scale))); + if (!ok(m_view->lpVtbl->setFrame(m_view, &m_frame.iface))) + { + error = QStringLiteral("VST3 editor rejected the host window frame"); + detach(); + return false; + } + + void *nativeParent = reinterpret_cast(static_cast(winId())); + m_attached = true; // attached() may request a resize before it returns. + if (!ok(m_view->lpVtbl->attached(m_view, nativeParent, platformType))) + { + error = QStringLiteral("VST3 editor could not attach to the host window"); + detach(); + return false; + } + impl.detachEditor = [this]() + { + detach(); + }; + return true; + } + +private: + qreal nativeScale() const + { +#ifdef Q_OS_MAC + return 1.0; // NSView coordinates are logical points. +#else + return devicePixelRatioF(); // HWND and X11 coordinates are physical pixels. +#endif + } + + Steinberg_tresult resizeFromPlugin(Steinberg_IPlugView *view, Steinberg_ViewRect *size) + { + if (!m_attached || view != m_view || !size || m_resizing || size->right <= size->left || + size->bottom <= size->top) + { + return Steinberg_kResultFalse; + } + m_resizing = true; + const qreal scale = nativeScale(); + setFixedSize(qMax(1, qRound((size->right - size->left) / scale)), + qMax(1, qRound((size->bottom - size->top) / scale))); + const Steinberg_tresult result = m_view->lpVtbl->onSize(m_view, size); + updateGeometry(); + m_resizing = false; + return result; + } + + void detach() + { + if (!m_view) + { + return; + } + Steinberg_IPlugView *view = m_view; + m_view = nullptr; + m_frame.resize = {}; + if (m_attached) + { + view->lpVtbl->removed(view); + } + m_attached = false; + view->lpVtbl->setFrame(view, nullptr); + view->lpVtbl->release(view); + } + + Vst3Effect *m_effect; + EditorFrame m_frame = {}; + Steinberg_IPlugView *m_view = nullptr; + bool m_attached = false; + bool m_resizing = false; +}; +#endif + +Vst3Effect::Vst3Effect() : m_impl(new Impl) +{ + Impl *impl = m_impl.get(); + m_impl->handler.queue = [impl](quint32 id, double value) + { + impl->queueParameter(id, value); + }; +} + +Vst3Effect::~Vst3Effect() +{ + close(); +} + +QStringList Vst3Effect::modulePaths(const QStringList &extraPaths) +{ + QStringList paths = extraPaths; + if (paths.isEmpty()) + { +#ifdef Q_OS_WIN + paths << QDir(qEnvironmentVariable("ProgramFiles")).filePath(QStringLiteral("Common Files/VST3")); + paths << QDir(qEnvironmentVariable("LOCALAPPDATA")).filePath(QStringLiteral("Programs/Common/VST3")); + paths << QDir(QCoreApplication::applicationDirPath()).filePath(QStringLiteral("VST3")); +#elif defined(Q_OS_LINUX) + paths << QDir::home().filePath(QStringLiteral(".vst3")) << QStringLiteral("/usr/lib/vst3") + << QStringLiteral("/usr/lib64/vst3") << QStringLiteral("/usr/local/lib/vst3") + << QStringLiteral("/usr/local/lib64/vst3"); + paths << QDir(QCoreApplication::applicationDirPath()).filePath(QStringLiteral("vst3")); +#elif defined(Q_OS_MAC) + paths << QDir::home().filePath(QStringLiteral("Library/Audio/Plug-ins/VST3")) + << QStringLiteral("/Library/Audio/Plug-ins/VST3") + << QStringLiteral("/Network/Library/Audio/Plug-ins/VST3"); + paths << QDir(QCoreApplication::applicationDirPath()).filePath(QStringLiteral("../VST3")); +#endif + } + QStringList modules; + std::function collect = [&](const QString &path) + { + const QFileInfo info(path); + if (!info.exists()) + { + return; + } + if (path.endsWith(QLatin1String(".vst3"), Qt::CaseInsensitive) && (info.isFile() || info.isDir())) + { + modules << info.absoluteFilePath(); + return; + } + if (!info.isDir() || info.isSymLink()) + { + return; + } + const QFileInfoList entries = QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot); + for (const QFileInfo &child : entries) + { + collect(child.absoluteFilePath()); + } + }; + for (const QString &path : paths) + { + collect(path); + } + modules.removeDuplicates(); + return modules; +} + +QVector Vst3Effect::discover(const QStringList &extraPaths) +{ + QVector result; + for (const QString &path : modulePaths(extraPaths)) + { + Module module; + QString error; + if (!module.load(path, error)) + { + continue; + } + const int count = module.factory->lpVtbl->countClasses(module.factory); + for (int i = 0; i < count; ++i) + { + Steinberg_PClassInfo info = {}; + if (!ok(module.factory->lpVtbl->getClassInfo(module.factory, i, &info))) + { + continue; + } + if (QByteArray(info.category, sizeof(info.category)).split('\0').first().trimmed() != "Audio Module Class") + { + continue; + } + Vst3PluginInfo plugin; + plugin.modulePath = path; + plugin.classId = QByteArray(info.cid, 16); + plugin.name = QString::fromUtf8(QByteArray(info.name, sizeof(info.name)).split('\0').first()); + result.append(plugin); + } + } + std::sort(result.begin(), result.end(), + [](const auto &a, const auto &b) + { + return a.name < b.name; + }); + return result; +} + +bool Vst3Effect::open(const QString &modulePath, const QByteArray &classId, int sampleRate, int sourceChannels, + QString &error, const QByteArray &state) +{ + close(); + if (classId.size() != 16 || sampleRate <= 0 || (sourceChannels != 1 && sourceChannels != 2)) + { + error = QStringLiteral("Invalid VST3 selection or audio format"); + return false; + } + auto &v = *m_impl; + if (!v.module.load(modulePath, error)) + { + return false; + } + if (!ok(v.module.factory->lpVtbl->createInstance(v.module.factory, classId.constData(), + Steinberg_Vst_IComponent_iid, + reinterpret_cast(&v.component))) || + !v.component) + { + error = QStringLiteral("VST3 effect component could not be created"); + close(); + return false; + } + if (!ok(v.component->lpVtbl->initialize(v.component, reinterpret_cast(&host)))) + { + error = QStringLiteral("VST3 effect initialization failed"); + close(); + return false; + } + v.initialized = true; + v.classId = classId; + if (!ok(v.component->lpVtbl->queryInterface(v.component, Steinberg_Vst_IAudioProcessor_iid, + reinterpret_cast(&v.processor))) || + !v.processor) + { + error = QStringLiteral("Selected VST3 class has no audio processor"); + close(); + return false; + } + const auto controllerQuery = v.component->lpVtbl->queryInterface(v.component, Steinberg_Vst_IEditController_iid, + reinterpret_cast(&v.controller)); + if (!ok(controllerQuery) || !v.controller) + { + Steinberg_TUID controllerId = {}; + const auto idStatus = v.component->lpVtbl->getControllerClassId(v.component, controllerId); + const auto createStatus = ok(idStatus) ? v.module.factory->lpVtbl->createInstance( + v.module.factory, controllerId, Steinberg_Vst_IEditController_iid, + reinterpret_cast(&v.controller)) + : idStatus; + if (ok(idStatus) && ok(createStatus) && v.controller) + { + const auto initStatus = + v.controller->lpVtbl->initialize(v.controller, reinterpret_cast(&host)); + if (ok(initStatus)) + { + v.controllerInitialized = true; + } + else + { + v.controller->lpVtbl->release(v.controller); + v.controller = nullptr; + } + } + } + if (v.controller) + { + v.controller->lpVtbl->setComponentHandler(v.controller, &v.handler.iface); + if (v.controllerInitialized) + { + v.component->lpVtbl->queryInterface(v.component, Steinberg_Vst_IConnectionPoint_iid, + reinterpret_cast(&v.componentConnection)); + v.controller->lpVtbl->queryInterface(v.controller, Steinberg_Vst_IConnectionPoint_iid, + reinterpret_cast(&v.controllerConnection)); + if (v.componentConnection && v.controllerConnection) + { + const auto status1 = + v.componentConnection->lpVtbl->connect(v.componentConnection, v.controllerConnection); + const auto status2 = + v.controllerConnection->lpVtbl->connect(v.controllerConnection, v.componentConnection); + v.componentConnected = ok(status1); + v.controllerConnected = ok(status2); + } + } + } + if (!state.isEmpty()) + { + // Restore before reading parameters, so they reflect the saved state. + QString stateError; + if (!setState(state, stateError)) { + qWarning("Vst3Effect::open: %s", qPrintable(stateError)); + } + } + if (v.controller) + { + const int count = std::max(0, std::min(4096, v.controller->lpVtbl->getParameterCount(v.controller))); + for (int i = 0; i < count; ++i) + { + Steinberg_Vst_ParameterInfo info = {}; + if (!ok(v.controller->lpVtbl->getParameterInfo(v.controller, i, &info))) + { + continue; + } + Vst3ParameterInfo parameter; + parameter.id = info.id; + parameter.name = + QString::fromUtf16(reinterpret_cast(info.title), 128).split(QChar(0)).first(); + parameter.defaultValue = info.defaultNormalizedValue; + const double current = v.controller->lpVtbl->getParamNormalized(v.controller, info.id); + parameter.currentValue = + std::isfinite(current) && current >= 0.0 && current <= 1.0 ? current : parameter.defaultValue; + parameter.steps = info.stepCount; + parameter.readOnly = (info.flags & Steinberg_Vst_ParameterInfo_ParameterFlags_kIsReadOnly) != 0; + parameter.hidden = (info.flags & Steinberg_Vst_ParameterInfo_ParameterFlags_kIsHidden) != 0; + v.parameterInfos.append(parameter); + } + } + v.inputBusCount = v.component->lpVtbl->getBusCount(v.component, Steinberg_Vst_MediaTypes_kAudio, + Steinberg_Vst_BusDirections_kInput); + v.outputBusCount = v.component->lpVtbl->getBusCount(v.component, Steinberg_Vst_MediaTypes_kAudio, + Steinberg_Vst_BusDirections_kOutput); + if (v.inputBusCount < 1 || v.inputBusCount > 16 || v.outputBusCount < 1 || v.outputBusCount > 16) + { + error = QStringLiteral("VST3 effect must have a main audio input and output bus"); + close(); + return false; + } + Steinberg_Vst_SpeakerArrangement arrangement = + sourceChannels == 1 ? Steinberg_Vst_SpeakerArr_kMono : Steinberg_Vst_SpeakerArr_kStereo; + v.processor->lpVtbl->setBusArrangements(v.processor, &arrangement, 1, &arrangement, 1); + Steinberg_Vst_BusInfo input = {}, output = {}; + if (!ok(v.component->lpVtbl->getBusInfo(v.component, Steinberg_Vst_MediaTypes_kAudio, + Steinberg_Vst_BusDirections_kInput, 0, &input)) || + !ok(v.component->lpVtbl->getBusInfo(v.component, Steinberg_Vst_MediaTypes_kAudio, + Steinberg_Vst_BusDirections_kOutput, 0, &output)) || + input.channelCount < 1 || input.channelCount > 2 || output.channelCount < 1 || output.channelCount > 2) + { + error = QStringLiteral("VST3 effect requires an unsupported bus layout"); + close(); + return false; + } + v.inputChannels = input.channelCount; + v.outputChannels = output.channelCount; + v.sourceChannels = sourceChannels; + v.sampleRate = sampleRate; + v.processedSamples = 0; + v.component->lpVtbl->activateBus(v.component, Steinberg_Vst_MediaTypes_kAudio, Steinberg_Vst_BusDirections_kInput, + 0, 1); + v.component->lpVtbl->activateBus(v.component, Steinberg_Vst_MediaTypes_kAudio, Steinberg_Vst_BusDirections_kOutput, + 0, 1); + for (int i = 1; i < v.inputBusCount; ++i) + { + v.component->lpVtbl->activateBus(v.component, Steinberg_Vst_MediaTypes_kAudio, + Steinberg_Vst_BusDirections_kInput, i, 0); + } + for (int i = 1; i < v.outputBusCount; ++i) + { + v.component->lpVtbl->activateBus(v.component, Steinberg_Vst_MediaTypes_kAudio, + Steinberg_Vst_BusDirections_kOutput, i, 0); + } + if (!ok(v.processor->lpVtbl->canProcessSampleSize(v.processor, Steinberg_Vst_SymbolicSampleSizes_kSample32))) + { + if (!ok(v.processor->lpVtbl->canProcessSampleSize(v.processor, Steinberg_Vst_SymbolicSampleSizes_kSample64))) + { + error = QStringLiteral("VST3 effect supports neither 32-bit nor 64-bit floating point audio"); + close(); + return false; + } + v.sample64 = true; + } + Steinberg_Vst_ProcessSetup setup = {Steinberg_Vst_ProcessModes_kRealtime, + v.sample64 ? Steinberg_Vst_SymbolicSampleSizes_kSample64 + : Steinberg_Vst_SymbolicSampleSizes_kSample32, + kBlockSize, static_cast(sampleRate)}; + if (!ok(v.processor->lpVtbl->setupProcessing(v.processor, &setup)) || + !ok(v.component->lpVtbl->setActive(v.component, 1))) + { + error = QStringLiteral("VST3 effect processing setup failed"); + close(); + return false; + } + v.active = true; + if (!ok(v.processor->lpVtbl->setProcessing(v.processor, 1))) + { + error = QStringLiteral("VST3 effect could not start processing"); + close(); + return false; + } + v.processing = true; + return true; +} + +bool Vst3Effect::process(const float *left, const float *right, float *outLeft, float *outRight, int count, + QString &error) +{ + auto &v = *m_impl; + if (!v.processing || count < 1 || count > kBlockSize) + { + error = QStringLiteral("VST3 effect is not ready"); + return false; + } + if (v.inputChannels == 1 && v.sourceChannels == 2 && right) + { + for (int i = 0; i < count; ++i) + { + v.monoInput[i] = 0.5f * (left[i] + right[i]); + } + } + const float *firstInput = v.inputChannels == 1 && v.sourceChannels == 2 && right ? v.monoInput : left; + float *in32[] = {const_cast(firstInput), const_cast(right ? right : left)}; + float *out32[] = {outLeft, outRight}; + double *in64[] = {v.input64[0], v.input64[1]}; + double *out64[] = {v.output64[0], v.output64[1]}; + if (v.sample64) + { + for (int i = 0; i < count; ++i) + { + v.input64[0][i] = firstInput[i]; + v.input64[1][i] = right ? right[i] : left[i]; + } + } + Steinberg_Vst_AudioBusBuffers inputs[16] = {}, outputs[16] = {}; + inputs[0].numChannels = v.inputChannels; + outputs[0].numChannels = v.outputChannels; + if (v.sample64) + { + inputs[0].Steinberg_Vst_AudioBusBuffers_channelBuffers64 = in64; + outputs[0].Steinberg_Vst_AudioBusBuffers_channelBuffers64 = out64; + } + else + { + inputs[0].Steinberg_Vst_AudioBusBuffers_channelBuffers32 = in32; + outputs[0].Steinberg_Vst_AudioBusBuffers_channelBuffers32 = out32; + } + Steinberg_Vst_ProcessData data = {}; + ParameterChanges changes = {}; + changes.iface.lpVtbl = &changesVtbl; + { + QMutexLocker lock(&v.parameterMutex); + changes.count = v.pendingCount; + for (int i = 0; i < changes.count; ++i) + { + changes.points[i] = v.pending[i]; + changes.points[i].iface.lpVtbl = &pointVtbl; + } + v.pendingCount = 0; + } + data.processMode = Steinberg_Vst_ProcessModes_kRealtime; + data.symbolicSampleSize = + v.sample64 ? Steinberg_Vst_SymbolicSampleSizes_kSample64 : Steinberg_Vst_SymbolicSampleSizes_kSample32; + data.numSamples = count; + data.numInputs = v.inputBusCount; + data.numOutputs = v.outputBusCount; + data.inputs = inputs; + data.outputs = outputs; + data.inputParameterChanges = &changes.iface; + Steinberg_Vst_ProcessContext context = {}; + context.state = Steinberg_Vst_ProcessContext_StatesAndFlags_kPlaying | + Steinberg_Vst_ProcessContext_StatesAndFlags_kContTimeValid; + context.sampleRate = v.sampleRate; + context.projectTimeSamples = v.processedSamples; + context.continousTimeSamples = v.processedSamples; + context.tempo = 120.0; + context.timeSigNumerator = 4; + context.timeSigDenominator = 4; + data.processContext = &context; + if (!ok(v.processor->lpVtbl->process(v.processor, &data))) + { + error = QStringLiteral("VST3 audio processing failed"); + return false; + } + v.processedSamples += count; + if (v.sample64) + { + for (int i = 0; i < count; ++i) + { + outLeft[i] = (outputs[0].silenceFlags & 1) ? 0.0f : static_cast(v.output64[0][i]); + outRight[i] = (outputs[0].silenceFlags & (v.outputChannels == 2 ? 2 : 1)) + ? 0.0f + : static_cast(v.output64[v.outputChannels == 2 ? 1 : 0][i]); + } + } + else + { + if (outputs[0].silenceFlags & 1) + { + std::fill(outLeft, outLeft + count, 0.0f); + } + if (v.outputChannels == 2) + { + if (outputs[0].silenceFlags & 2) + { + std::fill(outRight, outRight + count, 0.0f); + } + } + else + { + std::copy(outLeft, outLeft + count, outRight); + } + } + return true; +} + +void Vst3Effect::close() +{ + m_impl->close(); +} + +void Vst3Effect::setParameterEditCallback(std::function callback) +{ + m_impl->handler.onEdit = std::move(callback); +} + +#ifdef QT_WIDGETS_LIB +QWidget *Vst3Effect::createEditorWidget(QWidget *parent, QString &error) +{ + if (m_impl->detachEditor) + { + error = QStringLiteral("The VST3 editor is already open"); + return nullptr; + } + auto *widget = new EditorWidget(this, parent); + if (!widget->attach(error)) + { + delete widget; + return nullptr; + } + return widget; +} +#endif + +unsigned int Vst3Effect::latencySamples() const +{ + return m_impl->processor ? m_impl->processor->lpVtbl->getLatencySamples(m_impl->processor) : 0; +} + +QVector Vst3Effect::parameters() const +{ + return m_impl->parameterInfos; +} + +double Vst3Effect::parameterValue(quint32 id) const +{ + auto *controller = m_impl->controller; + const double value = controller ? controller->lpVtbl->getParamNormalized(controller, id) : -1.0; + return std::isfinite(value) && value >= 0.0 && value <= 1.0 ? value : -1.0; +} + +QByteArray Vst3Effect::state(QString &error) +{ + auto &v = *m_impl; + if (!v.component) + { + error = QStringLiteral("VST3 effect is not open"); + return QByteArray(); + } + bool pending = false; + { + QMutexLocker lock(&v.parameterMutex); + pending = v.pendingCount > 0; + } + if (pending && v.processing) + { + // Parameter changes reach the component only through process(), so deliver + // any queued edits with a silent block before asking it for its state. + float silence[2][kBlockSize] = {}; + float discard[2][kBlockSize]; + QString processError; + process(silence[0], silence[1], discard[0], discard[1], kBlockSize, processError); + } + MemoryStream componentState = makeStream(); + if (!ok(v.component->lpVtbl->getState(v.component, &componentState.iface))) + { + error = QStringLiteral("VST3 effect could not save its state"); + return QByteArray(); + } + MemoryStream controllerState = makeStream(); + if (v.controller && !ok(v.controller->lpVtbl->getState(v.controller, &controllerState.iface))) { + controllerState.data.clear(); // Controller state is optional. + } + QByteArray result; + QDataStream out(&result, QIODevice::WriteOnly); + out << kStateMagic << kStateVersion << v.classId << componentState.data << controllerState.data; + return result; +} + +bool Vst3Effect::setState(const QByteArray &state, QString &error) +{ + auto &v = *m_impl; + if (!v.component) + { + error = QStringLiteral("VST3 effect is not open"); + return false; + } + QDataStream in(state); + quint32 magic = 0, version = 0; + QByteArray classId, componentData, controllerData; + in >> magic >> version >> classId >> componentData >> controllerData; + if (in.status() != QDataStream::Ok || magic != kStateMagic || version != kStateVersion) + { + error = QStringLiteral("Saved VST3 state is invalid"); + return false; + } + if (classId != v.classId) + { + error = QStringLiteral("Saved VST3 state belongs to a different effect"); + return false; + } + MemoryStream componentState = makeStream(componentData); + if (!ok(v.component->lpVtbl->setState(v.component, &componentState.iface))) + { + error = QStringLiteral("VST3 effect rejected its saved state"); + return false; + } + if (v.controller) + { + // The host must mirror the component state into the controller. + MemoryStream mirroredState = makeStream(componentData); + v.controller->lpVtbl->setComponentState(v.controller, &mirroredState.iface); + if (!controllerData.isEmpty()) + { + MemoryStream controllerState = makeStream(controllerData); + v.controller->lpVtbl->setState(v.controller, &controllerState.iface); + } + } + return true; +} + +bool Vst3Effect::setParameter(quint32 id, double value) +{ + auto &v = *m_impl; + if (!v.controller || value < 0.0 || value > 1.0) + { + return false; + } + const auto parameter = std::find_if(v.parameterInfos.cbegin(), v.parameterInfos.cend(), + [id](const Vst3ParameterInfo &info) + { + return info.id == id && !info.readOnly; + }); + if (parameter == v.parameterInfos.cend()) + { + return false; + } + v.controller->lpVtbl->setParamNormalized(v.controller, id, value); + return v.queueParameter(id, value); +} + +QString Vst3Effect::parameterText(quint32 id, double value) const +{ + auto *controller = m_impl->controller; + if (controller) + { + Steinberg_Vst_String128 text = {}; + if (ok(controller->lpVtbl->getParamStringByValue(controller, id, value, text))) + { + const QString formatted = + QString::fromUtf16(reinterpret_cast(text), 128).split(QChar(0)).first(); + if (!formatted.isEmpty()) + { + return formatted; + } + } + } + return QString::number(value, 'f', 3); +} diff --git a/plugins/feature/denoiser/vst3effect.h b/plugins/feature/denoiser/vst3effect.h new file mode 100644 index 000000000..857292c64 --- /dev/null +++ b/plugins/feature/denoiser/vst3effect.h @@ -0,0 +1,87 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_FEATURE_DENOISER_VST3EFFECT_H_ +#define INCLUDE_FEATURE_DENOISER_VST3EFFECT_H_ + +#include +#include +#include +#include +#include +#include +#include + +class QWidget; + +struct Vst3PluginInfo +{ + QString modulePath; + QByteArray classId; // The factory's 16-byte platform-specific class ID. + QString name; +}; + +struct Vst3ParameterInfo +{ + quint32 id; + QString name; + double defaultValue; + double currentValue; + int steps; + bool readOnly; + bool hidden; +}; + +// Owns one audio effect. Construct, configure and destroy on the feature thread; +// only process() is called by the audio worker while the instance is active. +class Vst3Effect +{ +public: + Vst3Effect(); + ~Vst3Effect(); + + static QVector discover(const QStringList& extraPaths = {}); + static QStringList modulePaths(const QStringList& extraPaths = {}); + // state is a blob from state(); it is ignored if it belongs to a different class. + bool open(const QString& modulePath, const QByteArray& classId, int sampleRate, + int sourceChannels, QString& error, const QByteArray& state = QByteArray()); + bool process(const float *left, const float *right, float *outLeft, float *outRight, + int count, QString& error); + void close(); + unsigned int latencySamples() const; + QVector parameters() const; + double parameterValue(quint32 id) const; + // Not safe while another thread calls process(); flushes queued parameter changes. + QByteArray state(QString& error); + bool setState(const QByteArray& state, QString& error); + bool setParameter(quint32 id, double value); + QString parameterText(quint32 id, double value) const; + void setParameterEditCallback(std::function callback); +#ifdef QT_WIDGETS_LIB + QWidget *createEditorWidget(QWidget *parent, QString& error); +#endif + +private: +#ifdef QT_WIDGETS_LIB + class EditorWidget; +#endif + struct Impl; + std::unique_ptr m_impl; +}; + +#endif diff --git a/plugins/feature/denoiser/vst3scan.cpp b/plugins/feature/denoiser/vst3scan.cpp new file mode 100644 index 000000000..1bbfa4c21 --- /dev/null +++ b/plugins/feature/denoiser/vst3scan.cpp @@ -0,0 +1,83 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include + +#include "vst3effect.h" + +int main(int argc, char **argv) +{ + QCoreApplication app(argc, argv); + QStringList paths = app.arguments().mid(1); + + const bool probe = !paths.isEmpty() && paths.first() == QStringLiteral("--probe"); + if (probe) { + paths.removeFirst(); + } + + QJsonArray plugins; + + if (probe) + { + for (const Vst3PluginInfo& plugin : Vst3Effect::discover(paths)) + { + QJsonObject object; + object.insert(QStringLiteral("path"), plugin.modulePath); + object.insert(QStringLiteral("id"), QString::fromLatin1(plugin.classId.toHex())); + object.insert(QStringLiteral("name"), plugin.name); + plugins.append(object); + + } + } + else + { + for (const QString& path : Vst3Effect::modulePaths(paths)) + { + QProcess child; + child.setProgram(app.applicationFilePath()); + child.setArguments({QStringLiteral("--probe"), path}); + child.start(); + if (!child.waitForStarted(5000)) { + continue; + } + if (!child.waitForFinished(60000)) + { + child.kill(); + child.waitForFinished(5000); + continue; + } + if (child.exitStatus() != QProcess::NormalExit || child.exitCode() != 0) + continue; + const QJsonDocument result = QJsonDocument::fromJson(child.readAllStandardOutput()); + if (!result.isArray()) { + continue; + } + for (const QJsonValue& value : result.array()) { + plugins.append(value); + } + } + } + const QByteArray json = QJsonDocument(plugins).toJson(QJsonDocument::Compact); + std::fwrite(json.constData(), 1, static_cast(json.size()), stdout); + return 0; +} diff --git a/sdrbase/maincore.cpp b/sdrbase/maincore.cpp index af5bba9bf..ea26fbe19 100644 --- a/sdrbase/maincore.cpp +++ b/sdrbase/maincore.cpp @@ -64,6 +64,7 @@ MESSAGE_CLASS_DEFINITION(MainCore::MsgDeleteFeature, Message) MESSAGE_CLASS_DEFINITION(MainCore::MsgChannelReport, Message) MESSAGE_CLASS_DEFINITION(MainCore::MsgChannelSettings, Message) MESSAGE_CLASS_DEFINITION(MainCore::MsgChannelDemodReport, Message) +MESSAGE_CLASS_DEFINITION(MainCore::MsgFeatureDemodReport, Message) MESSAGE_CLASS_DEFINITION(MainCore::MsgChannelDemodQuery, Message) MESSAGE_CLASS_DEFINITION(MainCore::MsgMoveDeviceUIToWorkspace, Message) MESSAGE_CLASS_DEFINITION(MainCore::MsgArrangeWorkspace, Message) diff --git a/sdrbase/maincore.h b/sdrbase/maincore.h index 9d459a0d5..767728fee 100644 --- a/sdrbase/maincore.h +++ b/sdrbase/maincore.h @@ -565,6 +565,28 @@ public: { } }; + class SDRBASE_API MsgFeatureDemodReport : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const QObject *getFeature() const { return m_feature; } + int getSampleRate() const { return m_sampleRate; } + + static MsgFeatureDemodReport* create(const QObject *feature, int sampleRate) { + return new MsgFeatureDemodReport(feature, sampleRate); + } + + private: + const QObject *m_feature; + int m_sampleRate; + + MsgFeatureDemodReport(const QObject *feature, int sampleRate) : + Message(), + m_feature(feature), + m_sampleRate(sampleRate) + { } + }; + class SDRBASE_API MsgChannelSettings : public Message { MESSAGE_CLASS_DECLARATION diff --git a/sdrbase/resources/webapi/doc/swagger/include/Denoiser.yaml b/sdrbase/resources/webapi/doc/swagger/include/Denoiser.yaml index aaccaca88..a144cf351 100644 --- a/sdrbase/resources/webapi/doc/swagger/include/Denoiser.yaml +++ b/sdrbase/resources/webapi/doc/swagger/include/Denoiser.yaml @@ -9,6 +9,8 @@ DenoiserSettings: Denoiser type * 0 - none * 1 - RNnoise + * 2 - NVIDIA Noise Removal + * 3 - VST3 audio effect enableDenoiser: type: integer minimum: 0 @@ -17,6 +19,29 @@ DenoiserSettings: Enable denoiser * 1 - enable * 0 - disable + nvidiaIntensity: + type: integer + minimum: 0 + maximum: 100 + description: NVIDIA Noise Removal strength in percent + nvidiaVad: + type: integer + description: > + NVIDIA voice activity detection + * 1 - enable + * 0 - disable + vst3ModulePath: + type: string + description: Absolute path to the selected VST3 module or bundle + vst3ClassId: + type: string + description: 16-byte VST3 processor class ID encoded as hexadecimal + vst3Parameters: + type: string + description: JSON object mapping numeric VST3 parameter IDs to normalized values from 0 to 1 + vst3State: + type: string + description: Opaque VST3 component and controller state, base64 encoded volumeTenths: type: integer description: > diff --git a/swagger/sdrangel/api/swagger/include/Denoiser.yaml b/swagger/sdrangel/api/swagger/include/Denoiser.yaml index 1ac503b7f..d91c92915 100644 --- a/swagger/sdrangel/api/swagger/include/Denoiser.yaml +++ b/swagger/sdrangel/api/swagger/include/Denoiser.yaml @@ -9,6 +9,8 @@ DenoiserSettings: Denoiser type * 0 - none * 1 - RNnoise + * 2 - NVIDIA Noise Removal + * 3 - VST3 audio effect enableDenoiser: type: integer minimum: 0 @@ -17,6 +19,29 @@ DenoiserSettings: Enable denoiser * 1 - enable * 0 - disable + nvidiaIntensity: + type: integer + minimum: 0 + maximum: 100 + description: NVIDIA Noise Removal strength in percent + nvidiaVad: + type: integer + description: > + NVIDIA voice activity detection + * 1 - enable + * 0 - disable + vst3ModulePath: + type: string + description: Absolute path to the selected VST3 module or bundle + vst3ClassId: + type: string + description: 16-byte VST3 processor class ID encoded as hexadecimal + vst3Parameters: + type: string + description: JSON object mapping numeric VST3 parameter IDs to normalized values from 0 to 1 + vst3State: + type: string + description: Opaque VST3 component and controller state, base64 encoded volumeTenths: type: integer description: > diff --git a/swagger/sdrangel/code/qt5/client/SWGDenoiserSettings.cpp b/swagger/sdrangel/code/qt5/client/SWGDenoiserSettings.cpp index 0c154a9d2..15e1f6c12 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDenoiserSettings.cpp +++ b/swagger/sdrangel/code/qt5/client/SWGDenoiserSettings.cpp @@ -32,6 +32,18 @@ SWGDenoiserSettings::SWGDenoiserSettings() { m_denoiser_type_isSet = false; enable_denoiser = 0; m_enable_denoiser_isSet = false; + nvidia_intensity = 0; + m_nvidia_intensity_isSet = false; + nvidia_vad = 0; + m_nvidia_vad_isSet = false; + vst3_module_path = nullptr; + m_vst3_module_path_isSet = false; + vst3_class_id = nullptr; + m_vst3_class_id_isSet = false; + vst3_parameters = nullptr; + m_vst3_parameters_isSet = false; + vst3_state = nullptr; + m_vst3_state_isSet = false; volume_tenths = 0; m_volume_tenths_isSet = false; audio_device_name = nullptr; @@ -70,6 +82,18 @@ SWGDenoiserSettings::init() { m_denoiser_type_isSet = false; enable_denoiser = 0; m_enable_denoiser_isSet = false; + nvidia_intensity = 0; + m_nvidia_intensity_isSet = false; + nvidia_vad = 0; + m_nvidia_vad_isSet = false; + vst3_module_path = new QString(""); + m_vst3_module_path_isSet = false; + vst3_class_id = new QString(""); + m_vst3_class_id_isSet = false; + vst3_parameters = new QString(""); + m_vst3_parameters_isSet = false; + vst3_state = new QString(""); + m_vst3_state_isSet = false; volume_tenths = 0; m_volume_tenths_isSet = false; audio_device_name = new QString(""); @@ -101,6 +125,11 @@ SWGDenoiserSettings::init() { void SWGDenoiserSettings::cleanup() { + if(vst3_module_path != nullptr) delete vst3_module_path; + if(vst3_class_id != nullptr) delete vst3_class_id; + if(vst3_parameters != nullptr) delete vst3_parameters; + if(vst3_state != nullptr) delete vst3_state; + if(audio_device_name != nullptr) { @@ -142,6 +171,14 @@ SWGDenoiserSettings::fromJsonObject(QJsonObject &pJson) { ::SWGSDRangel::setValue(&enable_denoiser, pJson["enableDenoiser"], "qint32", ""); + ::SWGSDRangel::setValue(&nvidia_intensity, pJson["nvidiaIntensity"], "qint32", ""); + + ::SWGSDRangel::setValue(&nvidia_vad, pJson["nvidiaVad"], "qint32", ""); + ::SWGSDRangel::setValue(&vst3_module_path, pJson["vst3ModulePath"], "QString", "QString"); + ::SWGSDRangel::setValue(&vst3_class_id, pJson["vst3ClassId"], "QString", "QString"); + ::SWGSDRangel::setValue(&vst3_parameters, pJson["vst3Parameters"], "QString", "QString"); + ::SWGSDRangel::setValue(&vst3_state, pJson["vst3State"], "QString", "QString"); + ::SWGSDRangel::setValue(&volume_tenths, pJson["volumeTenths"], "qint32", ""); ::SWGSDRangel::setValue(&audio_device_name, pJson["audioDeviceName"], "QString", "QString"); @@ -190,6 +227,24 @@ SWGDenoiserSettings::asJsonObject() { if(m_enable_denoiser_isSet){ obj->insert("enableDenoiser", QJsonValue(enable_denoiser)); } + if(m_nvidia_intensity_isSet){ + obj->insert("nvidiaIntensity", QJsonValue(nvidia_intensity)); + } + if(m_nvidia_vad_isSet){ + obj->insert("nvidiaVad", QJsonValue(nvidia_vad)); + } + if(vst3_module_path != nullptr && *vst3_module_path != QString("")){ + toJsonValue(QString("vst3ModulePath"), vst3_module_path, obj, QString("QString")); + } + if(vst3_class_id != nullptr && *vst3_class_id != QString("")){ + toJsonValue(QString("vst3ClassId"), vst3_class_id, obj, QString("QString")); + } + if(vst3_parameters != nullptr && *vst3_parameters != QString("")){ + toJsonValue(QString("vst3Parameters"), vst3_parameters, obj, QString("QString")); + } + if(vst3_state != nullptr && *vst3_state != QString("")){ + toJsonValue(QString("vst3State"), vst3_state, obj, QString("QString")); + } if(m_volume_tenths_isSet){ obj->insert("volumeTenths", QJsonValue(volume_tenths)); } @@ -253,6 +308,51 @@ SWGDenoiserSettings::setEnableDenoiser(qint32 enable_denoiser) { this->m_enable_denoiser_isSet = true; } +qint32 +SWGDenoiserSettings::getNvidiaIntensity() { + return nvidia_intensity; +} +void +SWGDenoiserSettings::setNvidiaIntensity(qint32 nvidia_intensity) { + this->nvidia_intensity = nvidia_intensity; + this->m_nvidia_intensity_isSet = true; +} + +qint32 +SWGDenoiserSettings::getNvidiaVad() { + return nvidia_vad; +} +void +SWGDenoiserSettings::setNvidiaVad(qint32 nvidia_vad) { + this->nvidia_vad = nvidia_vad; + this->m_nvidia_vad_isSet = true; +} + +QString* SWGDenoiserSettings::getVst3ModulePath() { return vst3_module_path; } +void SWGDenoiserSettings::setVst3ModulePath(QString* value) { + if (vst3_module_path != value) delete vst3_module_path; + vst3_module_path = value; + m_vst3_module_path_isSet = true; +} +QString* SWGDenoiserSettings::getVst3ClassId() { return vst3_class_id; } +void SWGDenoiserSettings::setVst3ClassId(QString* value) { + if (vst3_class_id != value) delete vst3_class_id; + vst3_class_id = value; + m_vst3_class_id_isSet = true; +} +QString* SWGDenoiserSettings::getVst3Parameters() { return vst3_parameters; } +void SWGDenoiserSettings::setVst3Parameters(QString* value) { + if (vst3_parameters != value) delete vst3_parameters; + vst3_parameters = value; + m_vst3_parameters_isSet = true; +} +QString* SWGDenoiserSettings::getVst3State() { return vst3_state; } +void SWGDenoiserSettings::setVst3State(QString* value) { + if (vst3_state != value) delete vst3_state; + vst3_state = value; + m_vst3_state_isSet = true; +} + qint32 SWGDenoiserSettings::getVolumeTenths() { return volume_tenths; @@ -394,6 +494,15 @@ SWGDenoiserSettings::isSet(){ if(m_enable_denoiser_isSet){ isObjectUpdated = true; break; } + if(m_nvidia_intensity_isSet){ + isObjectUpdated = true; break; + } + if(m_nvidia_vad_isSet){ + isObjectUpdated = true; break; + } + if(m_vst3_module_path_isSet || m_vst3_class_id_isSet || m_vst3_parameters_isSet || m_vst3_state_isSet){ + isObjectUpdated = true; break; + } if(m_volume_tenths_isSet){ isObjectUpdated = true; break; } @@ -437,4 +546,3 @@ SWGDenoiserSettings::isSet(){ return isObjectUpdated; } } - diff --git a/swagger/sdrangel/code/qt5/client/SWGDenoiserSettings.h b/swagger/sdrangel/code/qt5/client/SWGDenoiserSettings.h index 9fa837426..fbb4d7b5f 100644 --- a/swagger/sdrangel/code/qt5/client/SWGDenoiserSettings.h +++ b/swagger/sdrangel/code/qt5/client/SWGDenoiserSettings.h @@ -49,6 +49,22 @@ public: qint32 getEnableDenoiser(); void setEnableDenoiser(qint32 enable_denoiser); + qint32 getNvidiaIntensity(); + void setNvidiaIntensity(qint32 nvidia_intensity); + + qint32 getNvidiaVad(); + void setNvidiaVad(qint32 nvidia_vad); + + QString* getVst3ModulePath(); + void setVst3ModulePath(QString* vst3_module_path); + QString* getVst3ClassId(); + void setVst3ClassId(QString* vst3_class_id); + QString* getVst3Parameters(); + void setVst3Parameters(QString* vst3_parameters); + + QString* getVst3State(); + void setVst3State(QString* vst3_state); + qint32 getVolumeTenths(); void setVolumeTenths(qint32 volume_tenths); @@ -98,6 +114,22 @@ private: qint32 enable_denoiser; bool m_enable_denoiser_isSet; + qint32 nvidia_intensity; + bool m_nvidia_intensity_isSet; + + qint32 nvidia_vad; + bool m_nvidia_vad_isSet; + + QString* vst3_module_path; + bool m_vst3_module_path_isSet; + QString* vst3_class_id; + bool m_vst3_class_id_isSet; + QString* vst3_parameters; + bool m_vst3_parameters_isSet; + + QString* vst3_state; + bool m_vst3_state_isSet; + qint32 volume_tenths; bool m_volume_tenths_isSet; From 7713b06c07b58a86ffd024c83015fbdd8da8bdea Mon Sep 17 00:00:00 2001 From: Jon Beniston Date: Sun, 27 Sep 2026 10:41:29 +0100 Subject: [PATCH 03/11] Link to EQ available on all platforms. --- plugins/feature/denoiser/readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/feature/denoiser/readme.md b/plugins/feature/denoiser/readme.md index 77a2d0a4f..f8f2f4294 100644 --- a/plugins/feature/denoiser/readme.md +++ b/plugins/feature/denoiser/readme.md @@ -4,7 +4,7 @@ This feature can process demodulated audio with RNNoise, NVIDIA Noise Removal, or an installed VST3 audio effect, such as a [denoiser](https://github.com/werman/noise-suppression-for-voice) -or [EQ](https://www.manda-audio.com/products.php). +or [EQ](https://duskaudio.com/plugins/multi-q/). It connects to the "demod" stream of RX channels or features similarly to the Demod Analyzer plugin. It also outputs its processed stereo audio on a "demod" stream, so another Denoiser or Demod Analyzer can use it as an input. From 05a3510c4459bc3d319ec9a743312d9b4a0d9075 Mon Sep 17 00:00:00 2001 From: Jon Beniston Date: Sun, 27 Sep 2026 12:30:54 +0100 Subject: [PATCH 04/11] Check if NVIDIA denoiser is available --- plugins/feature/denoiser/denoiser.cpp | 44 +++++--- plugins/feature/denoiser/denoiser.h | 1 + plugins/feature/denoiser/denoisergui.cpp | 13 ++- .../feature/denoiser/nvidiaaudioeffects.cpp | 103 +++++++++++------- plugins/feature/denoiser/nvidiaaudioeffects.h | 1 + plugins/feature/denoiser/readme.md | 11 +- 6 files changed, 118 insertions(+), 55 deletions(-) diff --git a/plugins/feature/denoiser/denoiser.cpp b/plugins/feature/denoiser/denoiser.cpp index a6eb426a9..8ad878b1d 100644 --- a/plugins/feature/denoiser/denoiser.cpp +++ b/plugins/feature/denoiser/denoiser.cpp @@ -191,6 +191,17 @@ void Denoiser::start() m_running = true; configureVst3(); + if (m_settings.m_enableDenoiser && + m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Nvidia) + { + QString error; + if (!NvidiaAudioEffects::isAvailable(error)) + { + m_errorMessage = error + QStringLiteral(" Audio is passing through."); + qWarning() << "Denoiser:" << m_errorMessage; + setState(StError); + } + } } void Denoiser::stop() @@ -245,10 +256,10 @@ bool Denoiser::handleMessage(const Message& cmd) m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Nvidia) { if (report.getError().isEmpty()) { - m_state = StRunning; + setState(StRunning); } else { m_errorMessage = report.getError(); - m_state = StError; + setState(StError); } } return true; @@ -260,7 +271,7 @@ bool Denoiser::handleMessage(const Message& cmd) m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Vst3) { m_errorMessage = report.getError(); - m_state = StError; + setState(StError); } return true; } @@ -379,11 +390,23 @@ void Denoiser::applySettings(const DenoiserSettings& settings, const QList(); @@ -443,7 +466,7 @@ void Denoiser::configureVst3() if (!effect->open(m_settings.m_vst3ModulePath, m_settings.m_vst3ClassId, m_sampleRate, 2, error, m_settings.m_vst3State)) { m_errorMessage = QStringLiteral("VST3: %1. Audio is passing through.").arg(error); - m_state = StError; + setState(StError); qWarning() << m_errorMessage; return; } @@ -453,7 +476,7 @@ void Denoiser::configureVst3() m_worker->setVst3Effect(effect.get()); m_vst3Effect = std::move(effect); if (m_state == StError) { - m_state = StRunning; + setState(StRunning); } } @@ -491,11 +514,6 @@ void Denoiser::applyReportedSampleRate(int sampleRate) { m_worker->applySampleRate(m_sampleRate); configureVst3(); - if (sampleRateChanged && m_state == StError && - m_settings.m_denoiserType == DenoiserSettings::DenoiserType::DenoiserType_Nvidia) - { - m_state = StRunning; - } } if (m_dataPipe) diff --git a/plugins/feature/denoiser/denoiser.h b/plugins/feature/denoiser/denoiser.h index 7c9f2de47..a12989a81 100644 --- a/plugins/feature/denoiser/denoiser.h +++ b/plugins/feature/denoiser/denoiser.h @@ -202,6 +202,7 @@ public: void getAvailableChannelsReport(); void setLevelMeter(QObject *levelMeter) { m_levelMeter = levelMeter; } + bool isRunning() const { return m_running; } QVector vst3Parameters() const; bool hasVst3Effect() const; QString vst3ParameterText(quint32 id, double value) const; diff --git a/plugins/feature/denoiser/denoisergui.cpp b/plugins/feature/denoiser/denoisergui.cpp index a0b65894f..2263f2d00 100644 --- a/plugins/feature/denoiser/denoisergui.cpp +++ b/plugins/feature/denoiser/denoisergui.cpp @@ -47,6 +47,7 @@ #include "ui_denoisergui.h" #include "denoiser.h" #include "denoisergui.h" +#include "nvidiaaudioeffects.h" DenoiserGUI* DenoiserGUI::create(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature) { @@ -190,9 +191,10 @@ DenoiserGUI::DenoiserGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Featu ui->denoiserType->setItemData(1, static_cast(DenoiserType::DenoiserType_RNnoise)); ui->denoiserType->setItemData(2, static_cast(DenoiserType::DenoiserType_Nvidia)); ui->denoiserType->setItemData(3, static_cast(DenoiserType::DenoiserType_Vst3)); -#if !defined(Q_OS_WIN) && !defined(Q_OS_LINUX) - ui->denoiserType->removeItem(static_cast(DenoiserSettings::DenoiserType::DenoiserType_Nvidia)); -#endif + QString nvidiaError; + if (!NvidiaAudioEffects::isAvailable(nvidiaError)) { + ui->denoiserType->removeItem(ui->denoiserType->findData(static_cast(DenoiserType::DenoiserType_Nvidia))); + } rollupContents->arrangeRollups(); connect(rollupContents, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); @@ -870,6 +872,11 @@ void DenoiserGUI::tick() void DenoiserGUI::updateFeatureState() { updateStartStopButton(ui->startStop); + if (m_denoiser->getState() == Feature::StError && m_denoiser->isRunning()) + { + const QSignalBlocker blocker(ui->startStop); + ui->startStop->setChecked(true); + } if (m_denoiser->getState() == Feature::StRunning && !m_vst3ScanAttempted) { scanVst3Plugins({}, true); } diff --git a/plugins/feature/denoiser/nvidiaaudioeffects.cpp b/plugins/feature/denoiser/nvidiaaudioeffects.cpp index 52962f6d2..6c406b762 100644 --- a/plugins/feature/denoiser/nvidiaaudioeffects.cpp +++ b/plugins/feature/denoiser/nvidiaaudioeffects.cpp @@ -34,42 +34,10 @@ #include "nvidiaaudioeffects.h" -#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) -struct NvidiaAudioEffects::Impl -{ - using CreateEffect = int (*)(const char *, void **); - using DestroyEffect = int (*)(void *); - using SetString = int (*)(void *, const char *, const char *); - using SetU32 = int (*)(void *, const char *, unsigned int); - using SetFloat = int (*)(void *, const char *, float); - using GetU32 = int (*)(void *, const char *, unsigned int *); - using Load = int (*)(void *); - using Run = int (*)(void *, const float **, float **, unsigned int, unsigned int); - - QLibrary library; - void *effect = nullptr; - QByteArray modelPath; - Qt::HANDLE threadId = nullptr; - DestroyEffect destroyEffect = nullptr; - Run run = nullptr; -}; -#else -struct NvidiaAudioEffects::Impl {}; -#endif - -NvidiaAudioEffects::NvidiaAudioEffects() : - m_impl(nullptr) -{ -} - -NvidiaAudioEffects::~NvidiaAudioEffects() +namespace { - shutdown(); -} - -bool NvidiaAudioEffects::initialize(QString& error, float intensityRatio, bool enableVad) +bool findInstallation(QString& libraryPath, QString& modelPath, QString& error) { - shutdown(); #if defined(Q_OS_WIN) || defined(Q_OS_LINUX) QString sdkDir = qEnvironmentVariable("NVAFX_SDK_DIR"); @@ -78,8 +46,8 @@ bool NvidiaAudioEffects::initialize(QString& error, float intensityRatio, bool e sdkDir = QDir(qEnvironmentVariable("ProgramFiles")).filePath("NVIDIA Corporation/NVIDIA Audio Effects SDK"); } - const QString libraryPath = QDir(sdkDir).filePath("NVAudioEffects.dll"); - const QString modelPath = QDir(sdkDir).filePath("models/denoiser_48k.trtpkg"); + libraryPath = QDir(sdkDir).filePath("NVAudioEffects.dll"); + modelPath = QDir(sdkDir).filePath("models/denoiser_48k.trtpkg"); #else if (sdkDir.isEmpty()) { sdkDir = qEnvironmentVariable("AFX_SDK_ROOT"); @@ -89,8 +57,8 @@ bool NvidiaAudioEffects::initialize(QString& error, float intensityRatio, bool e return false; } - const QString libraryPath = QDir(sdkDir).filePath("nvafx/lib/libnv_audiofx.so"); - QString modelPath = qEnvironmentVariable("NVAFX_MODEL_PATH"); + libraryPath = QDir(sdkDir).filePath("nvafx/lib/libnv_audiofx.so"); + modelPath = qEnvironmentVariable("NVAFX_MODEL_PATH"); if (modelPath.isEmpty()) { // Packages contain GPU-specific models. Pick one only if unambiguous. @@ -120,6 +88,65 @@ bool NvidiaAudioEffects::initialize(QString& error, float intensityRatio, bool e error = QStringLiteral("NVIDIA Audio Effects library or 48 kHz model was not found: %1, %2").arg(libraryPath, modelPath); return false; } + return true; +#else + Q_UNUSED(libraryPath) + Q_UNUSED(modelPath) + error = QStringLiteral("NVIDIA Audio Effects is available only on Windows and Linux"); + return false; +#endif +} +} + +#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) +struct NvidiaAudioEffects::Impl +{ + using CreateEffect = int (*)(const char *, void **); + using DestroyEffect = int (*)(void *); + using SetString = int (*)(void *, const char *, const char *); + using SetU32 = int (*)(void *, const char *, unsigned int); + using SetFloat = int (*)(void *, const char *, float); + using GetU32 = int (*)(void *, const char *, unsigned int *); + using Load = int (*)(void *); + using Run = int (*)(void *, const float **, float **, unsigned int, unsigned int); + + QLibrary library; + void *effect = nullptr; + QByteArray modelPath; + Qt::HANDLE threadId = nullptr; + DestroyEffect destroyEffect = nullptr; + Run run = nullptr; +}; +#else +struct NvidiaAudioEffects::Impl {}; +#endif + +NvidiaAudioEffects::NvidiaAudioEffects() : + m_impl(nullptr) +{ +} + +NvidiaAudioEffects::~NvidiaAudioEffects() +{ + shutdown(); +} + +bool NvidiaAudioEffects::isAvailable(QString& error) +{ + QString libraryPath; + QString modelPath; + return findInstallation(libraryPath, modelPath, error); +} + +bool NvidiaAudioEffects::initialize(QString& error, float intensityRatio, bool enableVad) +{ + shutdown(); +#if defined(Q_OS_WIN) || defined(Q_OS_LINUX) + QString libraryPath; + QString modelPath; + if (!findInstallation(libraryPath, modelPath, error)) { + return false; + } m_impl = new Impl; m_impl->modelPath = QFile::encodeName(QDir::toNativeSeparators(modelPath)); diff --git a/plugins/feature/denoiser/nvidiaaudioeffects.h b/plugins/feature/denoiser/nvidiaaudioeffects.h index 36bfb94dc..58f9cb87b 100644 --- a/plugins/feature/denoiser/nvidiaaudioeffects.h +++ b/plugins/feature/denoiser/nvidiaaudioeffects.h @@ -29,6 +29,7 @@ public: NvidiaAudioEffects(); ~NvidiaAudioEffects(); + static bool isAvailable(QString& error); bool initialize(QString& error, float intensityRatio, bool enableVad); void shutdown(); bool process(const float *input, float *output, QString& error); diff --git a/plugins/feature/denoiser/readme.md b/plugins/feature/denoiser/readme.md index f8f2f4294..e1ec2ff70 100644 --- a/plugins/feature/denoiser/readme.md +++ b/plugins/feature/denoiser/readme.md @@ -45,6 +45,7 @@ The feature selects `features/denoiser/models/sm_*/denoiser_48k.trtpkg` automati NVIDIA officially supports the Linux SDK for its listed server GPUs; consumer GeForce cards are outside that support list. NVIDIA Noise Removal is not available on macOS. +The option appears in the Denoiser only when the SDK library and 48 kHz model can be found at startup. Restart SDRangel after installing the SDK or changing its environment variables. Set the demodulated audio stream to 48 kS/s. The SDK's 48 kHz speech denoiser receives mono audio; stereo input is mixed to mono. If the SDK, model, or supported GPU is unavailable, the feature passes audio through and reports the reason in the feature's error status and SDRangel log. @@ -58,7 +59,12 @@ Changes to these controls reload the NVIDIA model briefly. Neither setting can g Select **VST3 Effect** to scan automatically for effects in the standard VST3 folders on Windows, Linux, or macOS. Denoiser also scans when the feature starts; use **Scan** to refresh the list after installing a plugin. -On macOS the folders include the user, system, and network Audio/Plug-ins/VST3 folders, plus the app's Contents/VST3 folder. +**Scan** searches these folders recursively: + + - **Windows:** `%ProgramFiles%\Common Files\VST3`, `%LOCALAPPDATA%\Programs\Common\VST3`, and `VST3` beside the SDRangel executable. + - **Linux:** `~/.vst3`, `/usr/lib/vst3`, `/usr/lib64/vst3`, `/usr/local/lib/vst3`, `/usr/local/lib64/vst3`, and `vst3` beside the SDRangel executable. + - **macOS:** `~/Library/Audio/Plug-ins/VST3`, `/Library/Audio/Plug-ins/VST3`, `/Network/Library/Audio/Plug-ins/VST3`, and the app's `Contents/VST3` folder. + The scanner runs in a separate process so a plugin that fails during discovery cannot crash SDRangel. The **...** button lets you select a module outside those folders. Select an effect from the list and start the feature. @@ -69,7 +75,10 @@ The effect runs at the selected channel's sample rate when reported, and otherwi The host accepts effects with one main mono or stereo audio input and output. Effects that require other layouts or host services may report an error; in that case audio passes through. + **Params** tries the native editor on Windows, macOS, and Linux when Qt uses X11. If the editor cannot attach, it uses the slider dialog. +If using Wayland on Linux, you need to set `QT_QPA_PLATFORM=xcb` in the environment to use the native editor. For snaps, also set `DISABLE_WAYLAND=1`. + Editor changes that a plugin does not expose as parameters are only heard once **Params** is closed.

Notes

From 3a4ce89cdcb41d0ae3e107a6ce949d6dc4949bf3 Mon Sep 17 00:00:00 2001 From: Jon Beniston Date: Sun, 27 Sep 2026 12:43:05 +0100 Subject: [PATCH 05/11] Tweak docs. --- plugins/feature/denoiser/readme.md | 33 ++++++++++++------------------ 1 file changed, 13 insertions(+), 20 deletions(-) diff --git a/plugins/feature/denoiser/readme.md b/plugins/feature/denoiser/readme.md index e1ec2ff70..a8c80302c 100644 --- a/plugins/feature/denoiser/readme.md +++ b/plugins/feature/denoiser/readme.md @@ -31,6 +31,15 @@ The noise reduction is based on a mix of DSP functions and a recursive neural ne You will find all the details about RNnoise here: https://jmvalin.ca/demo/rnnoise/ +Please note the following points: + + - Audio sample rate must be 48 kS/s (check 4) + - When taking the audio source from the WDSP plugin it should be used without noise reduction + - You should have enough input level but not exceed 100% on peaks (check 9 and 10). An average level between 10 and 20% should already provide good results + - The model has been trained on human voice therefore anything else like music is considered to be noise. It may however be successful at selecting the voice from songs. + - It should have enough original spectral components therefore any noise processing before the input will only deteriorate its performance. It should also have enough bandwidth it is recommended to have at least 100-3000 Hz. It is not an issue to extend beyond 3000 Hz because any high frequency hiss will be cancelled and it may benefit from the extra bandwidth on some transmissions. + - With SSB transmisions the pitch should be as close as possible to the natural pitch of the voice. In any case prefer a higher pitch to a lower one. Note that some voices are better processed than others which may also depend on voice processing before transmission. +

NVIDIA Noise Removal

On Windows, this option uses the NVIDIA Audio Effects SDK redistributable installed separately from NVIDIA Broadcast. @@ -45,6 +54,7 @@ The feature selects `features/denoiser/models/sm_*/denoiser_48k.trtpkg` automati NVIDIA officially supports the Linux SDK for its listed server GPUs; consumer GeForce cards are outside that support list. NVIDIA Noise Removal is not available on macOS. + The option appears in the Denoiser only when the SDK library and 48 kHz model can be found at startup. Restart SDRangel after installing the SDK or changing its environment variables. Set the demodulated audio stream to 48 kS/s. The SDK's 48 kHz speech denoiser receives mono audio; stereo input is mixed to mono. @@ -65,33 +75,16 @@ Denoiser also scans when the feature starts; use **Scan** to refresh the list af - **Linux:** `~/.vst3`, `/usr/lib/vst3`, `/usr/lib64/vst3`, `/usr/local/lib/vst3`, `/usr/local/lib64/vst3`, and `vst3` beside the SDRangel executable. - **macOS:** `~/Library/Audio/Plug-ins/VST3`, `/Library/Audio/Plug-ins/VST3`, `/Network/Library/Audio/Plug-ins/VST3`, and the app's `Contents/VST3` folder. -The scanner runs in a separate process so a plugin that fails during discovery cannot crash SDRangel. The **...** button lets you select a module outside those folders. -Select an effect from the list and start the feature. + **Params** opens the effect's own editor when available, or a slider dialog for its editable parameters. Changes to exposed parameters are saved with the Denoiser settings. -When **Params** is closed, the effect's complete state (including editor settings and presets that are not exposed as parameters) is also saved, and the running effect is reloaded with it. -The effect runs at the selected channel's sample rate when reported, and otherwise assumes 48 kS/s. - -The host accepts effects with one main mono or stereo audio input and output. -Effects that require other layouts or host services may report an error; in that case audio passes through. **Params** tries the native editor on Windows, macOS, and Linux when Qt uses X11. If the editor cannot attach, it uses the slider dialog. If using Wayland on Linux, you need to set `QT_QPA_PLATFORM=xcb` in the environment to use the native editor. For snaps, also set `DISABLE_WAYLAND=1`. Editor changes that a plugin does not expose as parameters are only heard once **Params** is closed. -

Notes

- -Please note the following points: - - - Audio sample rate must be 48 kS/s (check 4) - - When taking the audio source from the WDSP plugin it should be used without noise reduction - - You should have enough input level but not exceed 100% on peaks (check 9 and 10). An average level between 10 and 20% should already provide good results - - The model has been trained on human voice therefore anything else like music is considered to be noise. It may however be successful at selecting the voice from songs. - - It should have enough original spectral components therefore any noise processing before the input will only deteriorate its performance. It should also have enough bandwidth it is recommended to have at least 100-3000 Hz. It is not an issue to extend beyond 3000 Hz because any high frequency hiss will be cancelled and it may benefit from the extra bandwidth on some transmissions. - - With SSB transmisions the pitch should be as close as possible to the natural pitch of the voice. In any case prefer a higher pitch to a lower one. Note that some voices are better processed than others which may also depend on voice processing before transmission. -

Interface

![Denoiser plugin GUI](../../../doc/img/DenoiserFeature_plugin.png) @@ -118,10 +111,10 @@ Indication of the input audio stream power

6: Noise reduction scheme

-Selects the noise reduction scheme +Selects the noise reduction scheme (see introduction for details of each) - **None**: No noise reduction (passthrough) - - **RNnoise**: RNNoise (see introduction) + - **RNnoise**: RNNoise - **NVIDIA Noise Removal**: NVIDIA Audio Effects SDK speech denoiser - **VST3 Effect**: An installed VST3 audio effect From c699e3f2a77fbbd9078b540761d6f5dec72ae69d Mon Sep 17 00:00:00 2001 From: Jon Beniston Date: Sun, 27 Sep 2026 14:00:31 +0100 Subject: [PATCH 06/11] BFDDemod: Send sample rate to demod analyzer. --- plugins/channelrx/demodbfm/bfmdemod.cpp | 19 +++++++++++++++++++ plugins/channelrx/demodbfm/bfmdemod.h | 1 + plugins/channelrx/demodbfm/bfmdemodsink.cpp | 15 +++++++++++++++ 3 files changed, 35 insertions(+) diff --git a/plugins/channelrx/demodbfm/bfmdemod.cpp b/plugins/channelrx/demodbfm/bfmdemod.cpp index 47f42ed63..71ab4520b 100644 --- a/plugins/channelrx/demodbfm/bfmdemod.cpp +++ b/plugins/channelrx/demodbfm/bfmdemod.cpp @@ -194,12 +194,31 @@ bool BFMDemod::handleMessage(const Message& cmd) return true; } + else if (MainCore::MsgChannelDemodQuery::match(cmd)) + { + sendSampleRateToDemodAnalyzer(); + return true; + } else { return false; } } +void BFMDemod::sendSampleRateToDemodAnalyzer() +{ + QList pipes; + MainCore::instance()->getMessagePipes().getMessagePipes(this, "reportdemod", pipes); + + for (const auto& pipe : pipes) + { + MessageQueue *messageQueue = qobject_cast(pipe->m_element); + if (messageQueue) { + messageQueue->push(MainCore::MsgChannelDemodReport::create(this, getAudioSampleRate())); + } + } +} + void BFMDemod::setCenterFrequency(qint64 frequency) { BFMDemodSettings settings = m_settings; diff --git a/plugins/channelrx/demodbfm/bfmdemod.h b/plugins/channelrx/demodbfm/bfmdemod.h index c4e705ebb..c1e0f1b7f 100644 --- a/plugins/channelrx/demodbfm/bfmdemod.h +++ b/plugins/channelrx/demodbfm/bfmdemod.h @@ -176,6 +176,7 @@ private: QNetworkRequest m_networkRequest; virtual bool handleMessage(const Message& cmd); + void sendSampleRateToDemodAnalyzer(); void applySettings(const QStringList& settingsKeys, const BFMDemodSettings& settings, bool force = false); void webapiFormatChannelReport(SWGSDRangel::SWGChannelReport& response); diff --git a/plugins/channelrx/demodbfm/bfmdemodsink.cpp b/plugins/channelrx/demodbfm/bfmdemodsink.cpp index 2c72a7939..75637be66 100644 --- a/plugins/channelrx/demodbfm/bfmdemodsink.cpp +++ b/plugins/channelrx/demodbfm/bfmdemodsink.cpp @@ -25,6 +25,7 @@ #include "dsp/basebandsamplesink.h" #include "dsp/datafifo.h" #include "pipes/datapipes.h" +#include "util/messagequeue.h" #include "maincore.h" #include "rdsparser.h" @@ -291,6 +292,20 @@ void BFMDemodSink::applyAudioSampleRate(int sampleRate) m_deemphasisFilterY.configure(m_settings.getDeEmphasisTimeConstant() * sampleRate); m_audioSampleRate = sampleRate; + + if (m_channel) + { + QList pipes; + MainCore::instance()->getMessagePipes().getMessagePipes(m_channel, "reportdemod", pipes); + + for (const auto& pipe : pipes) + { + MessageQueue *messageQueue = qobject_cast(pipe->m_element); + if (messageQueue) { + messageQueue->push(MainCore::MsgChannelDemodReport::create(m_channel, sampleRate)); + } + } + } } void BFMDemodSink::applyChannelSettings(int channelSampleRate, int channelFrequencyOffset, bool force) From f6f0f520e7a56dbae79c0d12e16a22187318d4c5 Mon Sep 17 00:00:00 2001 From: Jon Beniston Date: Sun, 27 Sep 2026 14:01:43 +0100 Subject: [PATCH 07/11] DAB. Pass audio to demod pipe even when muted. --- plugins/channelrx/demoddab/dabdemodsink.cpp | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/plugins/channelrx/demoddab/dabdemodsink.cpp b/plugins/channelrx/demoddab/dabdemodsink.cpp index 92d59551e..9368a0423 100644 --- a/plugins/channelrx/demoddab/dabdemodsink.cpp +++ b/plugins/channelrx/demoddab/dabdemodsink.cpp @@ -393,16 +393,8 @@ void DABDemodSink::audio(int16_t *buffer, int size, int samplerate, bool stereo) for (int i = 0; i < size; i+=2) { Complex ci, ca; - if (!m_settings.m_audioMute) - { - ci.real(buffer[i]); - ci.imag(buffer[i+1]); - } - else - { - ci.real(0.0f); - ci.imag(0.0f); - } + ci.real(buffer[i]); + ci.imag(buffer[i+1]); if (m_audioInterpolatorDistance == 1.0f) { @@ -444,8 +436,9 @@ void DABDemodSink::processOneAudioSample(Complex &ci) qint16 l = scale(ci.real(), factor); qint16 r = scale(ci.imag(), factor); - m_audioBuffer[m_audioBufferFill].l = l; - m_audioBuffer[m_audioBufferFill].r = r; + // Muting DAB's direct output must not silence consumers of the demod pipe. + m_audioBuffer[m_audioBufferFill].l = m_settings.m_audioMute ? 0 : l; + m_audioBuffer[m_audioBufferFill].r = m_settings.m_audioMute ? 0 : r; ++m_audioBufferFill; if (m_audioBufferFill >= m_audioBuffer.size()) From 4fcc4fd234f4590929d715e1705c3727ca3139d9 Mon Sep 17 00:00:00 2001 From: Robin Getz Date: Wed, 16 Sep 2026 16:29:21 -0400 Subject: [PATCH 08/11] Define repository-wide text and binary file attributes Normalize text files to LF and explicitly identify binary assets, generated, and vendor files so so Git does not apply line-ending conversion to them. Signed-off-by: Robin Getz --- .gitattributes | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/.gitattributes b/.gitattributes index a23bfa2cc..6fd6e9396 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,48 @@ -*.fits binary \ No newline at end of file +# Git attributes for SDRangel +# normalize text files to LF and identify binary files. +* text=auto eol=lf + +# Vendored Cesium content: preserve upstream line endings. +plugins/feature/map/Cesium/** -text + +# Generated Swagger UI files +sdrbase/resources/webapi/doc/swagger-ui/** -text + +# Generated Swagger documentation and client code +sdrbase/resources/webapi/doc/swagger/** -text +swagger/sdrangel/code/** -text + +# SDRangel configuration and preset files +*.cfgx binary +*.prex binary + +# Binary image files. +*.png binary +*.PNG binary +*.bmp binary +*.BMP binary +*.xcf binary +*.XCF binary +*.jpg binary +*.JPG binary +*.fits binary +*.FITS binary +*.ico binary +*.ICO binary +*.icns binary +*.icns binary +*.gif binary +*.GIF binary + +# Binary audio/media files. +*.wav binary +*.WAV binary +*.wasm binary +*.WASM binary + +# Binary fonts. +*.ttf binary +*.TTF binary + +# Binary document files. +*.odg binary From 8e96a08b17715eb6f961c43bdfb50d370aec8083 Mon Sep 17 00:00:00 2001 From: Robin Getz Date: Sun, 27 Sep 2026 17:15:43 -0400 Subject: [PATCH 09/11] repowide : Normalize text files to LF Normalize existing text files to LF to conform to the repository-wide line-ending policy defined by .gitattributes by: git add --renormalize . Signed-off-by: Robin Getz --- .github/workflows/coverity.yml | 110 +- .github/workflows/linux.yml | 152 +- android/qt6/AndroidManifest.xml | 134 +- app/crashhandler.h | 52 +- logging/bufferlogger.cpp | 100 +- logging/bufferlogger.h | 92 +- .../channelrx/demodadsb/sideviews/ReadMe.txt | 34 +- plugins/feature/map/data/README.txt | 46 +- plugins/feature/map/map/cockpit.js | 2926 ++-- plugins/feature/map/map/grid.js | 330 +- plugins/feature/map/map/map3d.html | 2696 ++-- .../feature/mcpserver/bridge/CMakeLists.txt | 258 +- .../feature/mcpserver/bridge/httpclient.cpp | 988 +- plugins/feature/mcpserver/bridge/httpclient.h | 202 +- plugins/feature/mcpserver/bridge/main.cpp | 2170 +-- plugins/feature/mcpserver/bridge/readme.md | 176 +- plugins/feature/mcpserver/mcpservergui.cpp | 680 +- plugins/feature/mcpserver/mcptools.cpp | 12368 ++++++++-------- plugins/feature/mcpserver/mcptools.h | 598 +- plugins/feature/mcpserver/readme.md | 342 +- plugins/feature/mcpserver/toolsdump.cpp | 166 +- plugins/feature/sid/icons/delta.svg | 38 +- plugins/feature/sid/icons/gamma.svg | 44 +- plugins/feature/sid/icons/proton.svg | 74 +- plugins/feature/sid/icons/xlp.svg | 90 +- plugins/feature/sid/icons/xls.svg | 106 +- plugins/feature/sid/icons/xsp.svg | 96 +- plugins/feature/sid/icons/xss.svg | 112 +- plugins/feature/skymap/html/aladin.html | 310 +- sdrgui/gui/checklist.cpp | 344 +- sdrgui/gui/checklist.h | 210 +- 31 files changed, 13022 insertions(+), 13022 deletions(-) diff --git a/.github/workflows/coverity.yml b/.github/workflows/coverity.yml index 92865c862..870e46f6d 100644 --- a/.github/workflows/coverity.yml +++ b/.github/workflows/coverity.yml @@ -1,55 +1,55 @@ -name: SDRangel Linux Coverity build - -# Run every day at 3:00am UTC -on: - schedule: - - cron: '0 3 * * *' - workflow_dispatch: - -jobs: - build_coverity: - if: github.repository == 'f4exb/sdrangel' - # run once on latest - runs-on: ubuntu-24.04 - env: - COVERITY_SCAN_PROJECT_NAME: ${{ github.repository }} - COVERITY_SCAN_PROJECT_ID : "33161" - COVERITY_SCAN_NOTIFICATION_EMAIL: ${{ secrets.COVERITY_SCAN_NOTIFICATION_EMAIL }} - COVERITY_SCAN_TOKEN: ${{ secrets.COVERITY_SCAN_TOKEN }} - steps: - - uses: actions/checkout@v4 - with: - submodules: true - fetch-depth: 0 - - name: Check Coverity - id: coverity_check - run: | - ./.github/workflows/coverity.sh --precheck - # keep dependencies synced with linux.yml - - name: Install dependencies - if: steps.coverity_check.outputs.run == 'true' - run: | - sudo apt-get update - sudo apt-get install software-properties-common - sudo add-apt-repository -y ppa:ettusresearch/uhd - sudo apt-get update - sudo apt-get -y install build-essential cmake git xxd \ - devscripts fakeroot debhelper libfftw3-dev qtbase5-dev libopengl-dev libqt5opengl5-dev \ - qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5multimedia5-plugins libqt5websockets5-dev \ - libqt5quick5 qtwebengine5-dev qtbase5-private-dev \ - qml-module-qtlocation qml-module-qtpositioning qml-module-qtquick-window2 qml-module-qtquick-dialogs \ - qml-module-qtquick-controls qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtgraphicaleffects \ - libqt5serialport5-dev qtdeclarative5-dev qtpositioning5-dev qtlocation5-dev \ - libqt5charts5-dev libqt5texttospeech5-dev libqt5gamepad5-dev libqt5svg5-dev libfaad-dev libflac-dev zlib1g-dev \ - libusb-1.0-0-dev libhidapi-dev libboost-all-dev libasound2-dev libopencv-dev libopencv-imgcodecs-dev \ - libxml2-dev bison flex ffmpeg libpostproc-dev libavcodec-dev libavformat-dev \ - libopus-dev libcodec2-dev libairspy-dev libhackrf-dev \ - libbladerf-dev libsoapysdr-dev libiio-dev libuhd-dev libhamlib-dev libunwind-dev \ - libavahi-client-dev libavahi-common-dev libaio-dev \ - python3-mako python3-cheetah python3-numpy \ - autoconf automake libtool ninja-build - bash cmake/ci/build_sdrplay.sh - - name: Build SDRangel for Coverity - if: steps.coverity_check.outputs.run == 'true' - run: | - ./.github/workflows/coverity.sh +name: SDRangel Linux Coverity build + +# Run every day at 3:00am UTC +on: + schedule: + - cron: '0 3 * * *' + workflow_dispatch: + +jobs: + build_coverity: + if: github.repository == 'f4exb/sdrangel' + # run once on latest + runs-on: ubuntu-24.04 + env: + COVERITY_SCAN_PROJECT_NAME: ${{ github.repository }} + COVERITY_SCAN_PROJECT_ID : "33161" + COVERITY_SCAN_NOTIFICATION_EMAIL: ${{ secrets.COVERITY_SCAN_NOTIFICATION_EMAIL }} + COVERITY_SCAN_TOKEN: ${{ secrets.COVERITY_SCAN_TOKEN }} + steps: + - uses: actions/checkout@v4 + with: + submodules: true + fetch-depth: 0 + - name: Check Coverity + id: coverity_check + run: | + ./.github/workflows/coverity.sh --precheck + # keep dependencies synced with linux.yml + - name: Install dependencies + if: steps.coverity_check.outputs.run == 'true' + run: | + sudo apt-get update + sudo apt-get install software-properties-common + sudo add-apt-repository -y ppa:ettusresearch/uhd + sudo apt-get update + sudo apt-get -y install build-essential cmake git xxd \ + devscripts fakeroot debhelper libfftw3-dev qtbase5-dev libopengl-dev libqt5opengl5-dev \ + qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5multimedia5-plugins libqt5websockets5-dev \ + libqt5quick5 qtwebengine5-dev qtbase5-private-dev \ + qml-module-qtlocation qml-module-qtpositioning qml-module-qtquick-window2 qml-module-qtquick-dialogs \ + qml-module-qtquick-controls qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtgraphicaleffects \ + libqt5serialport5-dev qtdeclarative5-dev qtpositioning5-dev qtlocation5-dev \ + libqt5charts5-dev libqt5texttospeech5-dev libqt5gamepad5-dev libqt5svg5-dev libfaad-dev libflac-dev zlib1g-dev \ + libusb-1.0-0-dev libhidapi-dev libboost-all-dev libasound2-dev libopencv-dev libopencv-imgcodecs-dev \ + libxml2-dev bison flex ffmpeg libpostproc-dev libavcodec-dev libavformat-dev \ + libopus-dev libcodec2-dev libairspy-dev libhackrf-dev \ + libbladerf-dev libsoapysdr-dev libiio-dev libuhd-dev libhamlib-dev libunwind-dev \ + libavahi-client-dev libavahi-common-dev libaio-dev \ + python3-mako python3-cheetah python3-numpy \ + autoconf automake libtool ninja-build + bash cmake/ci/build_sdrplay.sh + - name: Build SDRangel for Coverity + if: steps.coverity_check.outputs.run == 'true' + run: | + ./.github/workflows/coverity.sh diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 8095b2fc5..852974b39 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -1,76 +1,76 @@ -name: SDRangel Linux release build - -on: - push: - branches: - - linux_github_release - tags: - - 'v*' - workflow_dispatch: - -jobs: - build_deb: - strategy: - fail-fast: false - matrix: - os: [ubuntu-22.04, ubuntu-24.04] - runs-on: ${{ matrix.os }} - steps: - - uses: actions/checkout@v4 - with: - submodules: true - fetch-depth: 0 - - name: Install dependencies - # ensure changes in dependencies get added to coverity.yml - run: | - sudo apt-get update - sudo apt-get install software-properties-common - sudo add-apt-repository -y ppa:ettusresearch/uhd - sudo apt-get update - sudo apt-get -y install build-essential cmake git xxd \ - devscripts fakeroot debhelper libfftw3-dev qtbase5-dev libopengl-dev libqt5opengl5-dev \ - qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5multimedia5-plugins libqt5websockets5-dev \ - libqt5quick5 qtwebengine5-dev qtbase5-private-dev \ - qml-module-qtlocation qml-module-qtpositioning qml-module-qtquick-window2 qml-module-qtquick-dialogs \ - qml-module-qtquick-controls qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtgraphicaleffects \ - libqt5serialport5-dev qtdeclarative5-dev qtpositioning5-dev qtlocation5-dev \ - libqt5charts5-dev libqt5texttospeech5-dev libqt5gamepad5-dev libqt5svg5-dev libfaad-dev libflac-dev zlib1g-dev \ - libusb-1.0-0-dev libhidapi-dev libboost-all-dev libasound2-dev libopencv-dev libopencv-imgcodecs-dev \ - libxml2-dev bison flex ffmpeg libpostproc-dev libavcodec-dev libavformat-dev \ - libopus-dev libcodec2-dev libairspy-dev libhackrf-dev \ - libbladerf-dev libsoapysdr-dev libiio-dev libuhd-dev libhamlib-dev libunwind-dev \ - libavahi-client-dev libavahi-common-dev libaio-dev \ - python3-mako python3-cheetah python3-numpy \ - autoconf automake libtool ninja-build - bash cmake/ci/build_sdrplay.sh - - name: Build SDRangel - run: | - if [ "${RUNNING_IN_ACT:-}" = "true" ]; then - mkdir -p /tmp/build - rsync -a --delete . /tmp/build/sdrangel/ - cd /tmp/build/sdrangel - debuild -i -us -uc -b - cp ../sdrangel_*_amd64.deb "$GITHUB_WORKSPACE"/ - else - debuild -i -us -uc -b - fi - - name: Get version - id: get_version - run: | - if [[ "${{github.ref_name}}" == "linux_github_release" ]]; then - echo "version=$(echo ${{github.sha}} | cut -c1-7)" >> $GITHUB_OUTPUT - else - echo "version=$(echo ${{github.ref_name}} | cut -c2-)" >> $GITHUB_OUTPUT - fi - - name: Rename - run: mv ../sdrangel_*_amd64.deb sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb - path: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb - - name: Upload release - if: startsWith(github.ref, 'refs/tags/') - uses: softprops/action-gh-release@v2 - with: - files: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb +name: SDRangel Linux release build + +on: + push: + branches: + - linux_github_release + tags: + - 'v*' + workflow_dispatch: + +jobs: + build_deb: + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, ubuntu-24.04] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + with: + submodules: true + fetch-depth: 0 + - name: Install dependencies + # ensure changes in dependencies get added to coverity.yml + run: | + sudo apt-get update + sudo apt-get install software-properties-common + sudo add-apt-repository -y ppa:ettusresearch/uhd + sudo apt-get update + sudo apt-get -y install build-essential cmake git xxd \ + devscripts fakeroot debhelper libfftw3-dev qtbase5-dev libopengl-dev libqt5opengl5-dev \ + qttools5-dev qttools5-dev-tools qtmultimedia5-dev libqt5multimedia5-plugins libqt5websockets5-dev \ + libqt5quick5 qtwebengine5-dev qtbase5-private-dev \ + qml-module-qtlocation qml-module-qtpositioning qml-module-qtquick-window2 qml-module-qtquick-dialogs \ + qml-module-qtquick-controls qml-module-qtquick-controls2 qml-module-qtquick-layouts qml-module-qtgraphicaleffects \ + libqt5serialport5-dev qtdeclarative5-dev qtpositioning5-dev qtlocation5-dev \ + libqt5charts5-dev libqt5texttospeech5-dev libqt5gamepad5-dev libqt5svg5-dev libfaad-dev libflac-dev zlib1g-dev \ + libusb-1.0-0-dev libhidapi-dev libboost-all-dev libasound2-dev libopencv-dev libopencv-imgcodecs-dev \ + libxml2-dev bison flex ffmpeg libpostproc-dev libavcodec-dev libavformat-dev \ + libopus-dev libcodec2-dev libairspy-dev libhackrf-dev \ + libbladerf-dev libsoapysdr-dev libiio-dev libuhd-dev libhamlib-dev libunwind-dev \ + libavahi-client-dev libavahi-common-dev libaio-dev \ + python3-mako python3-cheetah python3-numpy \ + autoconf automake libtool ninja-build + bash cmake/ci/build_sdrplay.sh + - name: Build SDRangel + run: | + if [ "${RUNNING_IN_ACT:-}" = "true" ]; then + mkdir -p /tmp/build + rsync -a --delete . /tmp/build/sdrangel/ + cd /tmp/build/sdrangel + debuild -i -us -uc -b + cp ../sdrangel_*_amd64.deb "$GITHUB_WORKSPACE"/ + else + debuild -i -us -uc -b + fi + - name: Get version + id: get_version + run: | + if [[ "${{github.ref_name}}" == "linux_github_release" ]]; then + echo "version=$(echo ${{github.sha}} | cut -c1-7)" >> $GITHUB_OUTPUT + else + echo "version=$(echo ${{github.ref_name}} | cut -c2-)" >> $GITHUB_OUTPUT + fi + - name: Rename + run: mv ../sdrangel_*_amd64.deb sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb + - name: Upload artifact + uses: actions/upload-artifact@v4 + with: + name: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb + path: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb + - name: Upload release + if: startsWith(github.ref, 'refs/tags/') + uses: softprops/action-gh-release@v2 + with: + files: sdrangel_${{ steps.get_version.outputs.version }}_${{ matrix.os }}_amd64.deb diff --git a/android/qt6/AndroidManifest.xml b/android/qt6/AndroidManifest.xml index e7bd96b12..d90bab2ae 100644 --- a/android/qt6/AndroidManifest.xml +++ b/android/qt6/AndroidManifest.xml @@ -1,67 +1,67 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/crashhandler.h b/app/crashhandler.h index 2c857ccb7..447d06a06 100644 --- a/app/crashhandler.h +++ b/app/crashhandler.h @@ -1,26 +1,26 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2025 Jon Beniston, M7RCE // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include "loggerwithfile.h" - -void installCrashHandler(qtwebapp::LoggerWithFile *logger); - -#ifdef _WIN32 -void logWindowsStackTrace(); -#endif +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2025 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "loggerwithfile.h" + +void installCrashHandler(qtwebapp::LoggerWithFile *logger); + +#ifdef _WIN32 +void logWindowsStackTrace(); +#endif diff --git a/logging/bufferlogger.cpp b/logging/bufferlogger.cpp index 4f9b0bc6b..c0849de94 100644 --- a/logging/bufferlogger.cpp +++ b/logging/bufferlogger.cpp @@ -1,50 +1,50 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2025 Jon Beniston, M7RCE // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#include "bufferlogger.h" - -using namespace qtwebapp; - -BufferLogger::BufferLogger(int maxSize, QObject *parent) : - Logger(parent), - m_maxSize(maxSize) -{ -} - -BufferLogger::~BufferLogger() -{ -} - -void BufferLogger::write(const LogMessage* logMessage) -{ - QString text = qPrintable(logMessage->toString("{timestamp} {type} {msg}", "yyyy-MM-dd HH:mm:ss.zzz")); - m_messages.enqueue(text); - while (m_messages.size() > m_maxSize) { - m_messages.dequeue(); - } -} - -QString BufferLogger::getLog() const -{ - QString log; - - for (const auto& s : m_messages) { - log.append(s); - } - - return log; -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2025 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "bufferlogger.h" + +using namespace qtwebapp; + +BufferLogger::BufferLogger(int maxSize, QObject *parent) : + Logger(parent), + m_maxSize(maxSize) +{ +} + +BufferLogger::~BufferLogger() +{ +} + +void BufferLogger::write(const LogMessage* logMessage) +{ + QString text = qPrintable(logMessage->toString("{timestamp} {type} {msg}", "yyyy-MM-dd HH:mm:ss.zzz")); + m_messages.enqueue(text); + while (m_messages.size() > m_maxSize) { + m_messages.dequeue(); + } +} + +QString BufferLogger::getLog() const +{ + QString log; + + for (const auto& s : m_messages) { + log.append(s); + } + + return log; +} diff --git a/logging/bufferlogger.h b/logging/bufferlogger.h index fa4807e90..cce4c371a 100644 --- a/logging/bufferlogger.h +++ b/logging/bufferlogger.h @@ -1,46 +1,46 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2025 Jon Beniston, M7RCE // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#pragma once - -#include - -#include "logger.h" -#include "export.h" - -namespace qtwebapp { - -// A ring-buffer like logger for holding m_maxSize recent log messages -class LOGGING_API BufferLogger : public Logger { - Q_OBJECT - Q_DISABLE_COPY(BufferLogger) - -public: - BufferLogger(int maxSize, QObject *parent = nullptr); - virtual ~BufferLogger(); - - void write(const LogMessage* logMessage) override; - QString getLog() const; // Get last m_maxSize messages as one big string - -private: - - int m_maxSize; // Maximum number of messages to store - QQueue m_messages; // Queue containing last m_maxSize messages - -}; - -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2025 Jon Beniston, M7RCE // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#pragma once + +#include + +#include "logger.h" +#include "export.h" + +namespace qtwebapp { + +// A ring-buffer like logger for holding m_maxSize recent log messages +class LOGGING_API BufferLogger : public Logger { + Q_OBJECT + Q_DISABLE_COPY(BufferLogger) + +public: + BufferLogger(int maxSize, QObject *parent = nullptr); + virtual ~BufferLogger(); + + void write(const LogMessage* logMessage) override; + QString getLog() const; // Get last m_maxSize messages as one big string + +private: + + int m_maxSize; // Maximum number of messages to store + QQueue m_messages; // Queue containing last m_maxSize messages + +}; + +} diff --git a/plugins/channelrx/demodadsb/sideviews/ReadMe.txt b/plugins/channelrx/demodadsb/sideviews/ReadMe.txt index 5bc03889c..8f54542ed 100644 --- a/plugins/channelrx/demodadsb/sideviews/ReadMe.txt +++ b/plugins/channelrx/demodadsb/sideviews/ReadMe.txt @@ -1,18 +1,18 @@ -SECTION FROM THE MANUAL RELATING TO THE USE OF OPERATOR FLAGS - -The operator column can be used to display a graphic for each aircraft, typically to show its -operator. Operator flag graphic files must be in .bmp format and must be placed in an -OperatorFlags subdirectory. To set an aircraft to display the operator flag, enter the name of -the file minus the .bmp extension into the OperatorFlagCode of the Edit Aircraft Details dialog -box. - -For example, if you enter “BAW” into the OperatorFlagCode field of an aircraft, and you have -previously placed the file “BAW.bmp” into the directory -C:\Program Files\Kinetic\BaseStation\OperatorFlags, then the baw bitmap will be displayed in the -Operator column for that aircraft. - -Note: We do not envisage users typically entering these codes using this interface. Instead, we -have provided this feature so that those existing third party applications that use BaseStation’s -database interface to write registration data into the database can write in flag codes matching -existing flag data sets, allowing the users of those third party products to have operator flags +SECTION FROM THE MANUAL RELATING TO THE USE OF OPERATOR FLAGS + +The operator column can be used to display a graphic for each aircraft, typically to show its +operator. Operator flag graphic files must be in .bmp format and must be placed in an +OperatorFlags subdirectory. To set an aircraft to display the operator flag, enter the name of +the file minus the .bmp extension into the OperatorFlagCode of the Edit Aircraft Details dialog +box. + +For example, if you enter “BAW” into the OperatorFlagCode field of an aircraft, and you have +previously placed the file “BAW.bmp” into the directory +C:\Program Files\Kinetic\BaseStation\OperatorFlags, then the baw bitmap will be displayed in the +Operator column for that aircraft. + +Note: We do not envisage users typically entering these codes using this interface. Instead, we +have provided this feature so that those existing third party applications that use BaseStation’s +database interface to write registration data into the database can write in flag codes matching +existing flag data sets, allowing the users of those third party products to have operator flags automatically appear. \ No newline at end of file diff --git a/plugins/feature/map/data/README.txt b/plugins/feature/map/data/README.txt index e7075a745..685247222 100644 --- a/plugins/feature/map/data/README.txt +++ b/plugins/feature/map/data/README.txt @@ -1,23 +1,23 @@ -UK transmitter data: - -TxParamsAM.csv. TxParamsDAB.csv, TxParamsVHF.csv - https://www.ofcom.org.uk/spectrum/information/radio-tech-parameters - -700-plan-clearance.xlsx - https://www.ofcom.org.uk/spectrum/information/transmitter-frequency - -French transmitter data: - -sites-DAB-TII-v0.10.csv - https://extranet.arcom.fr/radio/index.php - - -WMM (World Magnetic Model): - -Download ERSI shapefiles from: https://data.ngdc.noaa.gov/geomag/wmm/wmm2025/shapefiles/ -Open D_2025.shp in QGIS: https://qgis.org/ -Layer > Open Attribute Table, Toggle Edit Mode, Delete unneeded contours (E.g. odd values). -Edit > Edit Geometry > Simplify feature, Draw box around all geometry, set tolerance to 0.1 and check reduction in number of verticies. -Layer > Save As... - -QGIS geojson export doesn't support styles (See: https://github.com/qgis/QGIS/issues/21195) so manually edit the geojson and insert: - - "stroke": "#ff0000" properties to set color. Negative blue, positive red, 0 green. - "stroke-width": 0.5, for contours that aren't multiples of 10 and 1.0 for those that are. +UK transmitter data: + +TxParamsAM.csv. TxParamsDAB.csv, TxParamsVHF.csv - https://www.ofcom.org.uk/spectrum/information/radio-tech-parameters + +700-plan-clearance.xlsx - https://www.ofcom.org.uk/spectrum/information/transmitter-frequency + +French transmitter data: + +sites-DAB-TII-v0.10.csv - https://extranet.arcom.fr/radio/index.php + + +WMM (World Magnetic Model): + +Download ERSI shapefiles from: https://data.ngdc.noaa.gov/geomag/wmm/wmm2025/shapefiles/ +Open D_2025.shp in QGIS: https://qgis.org/ +Layer > Open Attribute Table, Toggle Edit Mode, Delete unneeded contours (E.g. odd values). +Edit > Edit Geometry > Simplify feature, Draw box around all geometry, set tolerance to 0.1 and check reduction in number of verticies. +Layer > Save As... + +QGIS geojson export doesn't support styles (See: https://github.com/qgis/QGIS/issues/21195) so manually edit the geojson and insert: + + "stroke": "#ff0000" properties to set color. Negative blue, positive red, 0 green. + "stroke-width": 0.5, for contours that aren't multiples of 10 and 1.0 for those that are. diff --git a/plugins/feature/map/map/cockpit.js b/plugins/feature/map/map/cockpit.js index 1da72d86b..0214cb1a9 100644 --- a/plugins/feature/map/map/cockpit.js +++ b/plugins/feature/map/map/cockpit.js @@ -1,1463 +1,1463 @@ -// Airbus like PFD (Primary Flight Display) - -var icao; -var callsign; -var aircraftType; -var onSurface; -var wasOnSurface60SecsAgo; -var speed; -var modelSpeed; // Speed of 3D model in Cesium -var trueAirspeed; -var groundspeed; -var targetSpeed; -var altitude; -var targetAltitude; -var radioAltitude; -var verticalSpeed; // ft/m -var heading; // degrees mag -var targetHeading; -var track; // degrees true -var pressure; // mb -var mach; -var roll; -var autopilot; -var verticalMode; -var lateralMode; -var tcasMode; -var windSpeed; -var windDirection; -var staticAirTemperature; - -var mdoelSpeed; -var toga = false; -var rollOut = false; -var runwayAltitude; - -const grayColor = "#6A75AE"; -const greenColor = "#20E966"; -const cyanColor = "#2FF7FE"; -const yellowColor = "#F4F82F"; -const orangeColor = "#FEDA30"; -const skyColor = "#26C9FF"; -const groundColor = "#D35E34"; - -function setPFDData(forward, newICAO, newCallsign, newAircraftType, newOnSurface, newWasOnSurface60SecsAgo, newRunwayAltitudeEstimate, - newModelSpeed, newIndicatedAirspeed, newTrueAirspeed, newGroundspeed, newMach, newAltitude, newRadioAltitude, newQnh, newVerticalSpeed, - newHeading, newTrack, newRoll, newSelectedAltitude, newSelectedHeading, - newAutopilot, newVerticalMode, newLateralMode, newTCASMode, - newWindSpeed, newWindDirection, newStaticAirTemperature) { - - //console.log('PFD', newIndicatedAirspeed, newMach, newAltitude, newQnh, newVerticalSpeed, newHeading, newTrack, newRoll, newSelectedAltitude, newSelectedHeading); - - const newAircraft = icao !== newICAO; - - if (newAircraft) { - toga = false; - rollOut = false; - runwayAltitude = undefined; - } - - icao = newICAO; - callsign = newCallsign; - aircraftType = newAircraftType; - onSurface = newOnSurface; - wasOnSurface60SecsAgo = newWasOnSurface60SecsAgo; - modelSpeed = newModelSpeed; - if ((newIndicatedAirspeed === undefined) || (newOnSurface > 0)) { - // IAS not transmitted frequently. After landing will no longer be valid - if (newGroundspeed !== undefined) { - speed = newGroundspeed; - } else { - speed = newModelSpeed; - } - } else { - speed = newIndicatedAirspeed; - } - trueAirspeed = newTrueAirspeed; - groundspeed = newGroundspeed; - mach = newMach; - altitude = newAltitude; - radioAltitude = newRadioAltitude; - pressure = newQnh; - verticalSpeed = newVerticalSpeed; - if (newHeading === undefined) { - heading = newTrack; // Track more frequent than heading - } else { - heading = newHeading; - } - track = newTrack; - roll = newRoll; - targetAltitude = newSelectedAltitude; - targetHeading = newSelectedHeading; - if (newAutopilot === -1) { - autopilot = undefined; - } else { - autopilot = newAutopilot; - } - verticalMode = newVerticalMode; - lateralMode = newLateralMode; - tcasMode = newTCASMode; - windSpeed = newWindSpeed; - windDirection = newWindDirection; - staticAirTemperature = newStaticAirTemperature; - - // Correct altitude for QNH setting - if (pressure !== undefined) { - altitude += (pressure - 1013.25) * 30; - } - - if (!rollOut && forward && (wasOnSurface60SecsAgo === 0) && (onSurface > 0) && (modelSpeed >= 70)) { - rollOut = true; - } else if (rollOut && ((modelSpeed < 40) || (onSurface === 0))) { - rollOut = false; - } - - const accelerationHeight = 1500; - - if (!toga && !rollOut && forward && (onSurface > 0) && (modelSpeed >= 35)) { - toga = true; // Start take-off roll on surface - runwayAltitude = altitude; - } else if (!toga && !rollOut && (modelSpeed >= 35) && (runwayAltitude === undefined) && (wasOnSurface60SecsAgo > 0) && (newRunwayAltitudeEstimate !== undefined)) { - toga = true; // For when selecting an aircraft having just taken off - runwayAltitude = newRunwayAltitudeEstimate; - } else if (!toga && !rollOut && (onSurface === 0) && (wasOnSurface60SecsAgo > 0) && (altitude !== undefined) && (runwayAltitude !== undefined) && (altitude < runwayAltitude + accelerationHeight)) { - toga = true; // For when played in reverse - } else if (toga && (modelSpeed <= 20)) { - toga = false; - } else if (toga && (altitude !== undefined) && (runwayAltitude !== undefined) && (altitude >= runwayAltitude + accelerationHeight)) { - toga = false; - } - if (toga && (runwayAltitude === undefined) && (newRunwayAltitudeEstimate !== undefined)) { - runwayAltitude = newRunwayAltitudeEstimate; - } -} - -function isStd() { - return (pressure >= 1012) && (pressure < 1014); -} - -function drawAirspeedIndicator(ctx, fm20, fm30) { - // Airspeed indicator - - const speedIndWidth = 100; - const speedIndHeight = 500; - const speedIndLeft = 30; - const speedIndRight = speedIndLeft + speedIndWidth; - const speedIndTop = 250; - const speedIndBottom = speedIndTop + speedIndHeight; - const speedIndMid = speedIndTop + speedIndHeight / 2; - - // Background - ctx.fillStyle = grayColor; - ctx.fillRect(speedIndLeft, speedIndTop, speedIndWidth, speedIndHeight); - - // Clip speed tape - ctx.save(); - ctx.rect(speedIndLeft, speedIndTop, speedIndWidth, speedIndHeight); - ctx.clip(); - - // Speed tape markings every 10knts - const speedTapMinSpeed = 0; // A320 only starts drawning from 30knts, but we draw from 0 - const speedTapeLeft = speedIndRight - 20; - const speedTapeRight = speedIndRight; - const speedTapeSpacing = 60; - const speedTapeStep = 10; - const speedTextStep = 20; - const speedPerPixel = speedTapeSpacing / speedTapeStep; - const speedOffset = (speed % speedTextStep) * speedPerPixel; - ctx.beginPath(); - var speedTape = Math.round(speed - speed % speedTextStep + 6 * speedTapeStep); - for (var i = -6; i < 5; i++) { - if (speedTape >= speedTapMinSpeed) { - ctx.moveTo(speedTapeLeft, speedOffset + i * speedTapeSpacing + speedIndMid); - ctx.lineTo(speedTapeRight, speedOffset + i * speedTapeSpacing + speedIndMid); - } - speedTape -= speedTapeStep; - } - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Speeds every 20knts - var speedText = Math.round(speed - speed % speedTextStep + 3 * speedTextStep); - for (var i = -3; i < 3; i++) { - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - if (speedText >= speedTapMinSpeed) { - const speedTextString = speedText.toString().padStart(3, '0'); - ctx.fillText(speedTextString, speedIndLeft + 20, speedOffset + i * speedTapeSpacing * 2 + speedIndMid + fm30.actualBoundingBoxAscent / 2); - } - speedText -= speedTextStep; - } - - // Disable clipping - ctx.restore(); - - ctx.beginPath(); - ctx.moveTo(speedIndLeft, speedIndTop); - ctx.lineTo(speedIndRight + 30, speedIndTop); - var speedIndRightLineHeight = speed / (speedIndHeight / 2 / speedPerPixel); // White line on right only drawn down to speedTapMinSpeed - if (speedIndRightLineHeight > 1) { - speedIndRightLineHeight = 1; - ctx.moveTo(speedIndLeft, speedIndTop + speedIndHeight); - ctx.lineTo(speedIndRight + 30, speedIndTop + speedIndHeight); - } - ctx.moveTo(speedIndRight, speedIndTop); - ctx.lineTo(speedIndRight, speedIndTop + speedIndRightLineHeight * (speedIndHeight / 2) + (speedIndHeight / 2)); - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Speed indicator - ctx.beginPath(); - ctx.moveTo(speedIndLeft - 10, speedIndMid); - ctx.lineTo(speedIndLeft, speedIndMid); - ctx.moveTo(speedTapeLeft - 5, speedIndMid); - ctx.lineTo(speedTapeRight + 20, speedIndMid); - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - ctx.beginPath(); - ctx.moveTo(speedTapeRight + 10, speedIndMid); - ctx.lineTo(speedTapeRight + 35, speedIndMid - 10); - ctx.lineTo(speedTapeRight + 35, speedIndMid + 10); - ctx.lineTo(speedTapeRight + 10, speedIndMid); - ctx.fillStyle = yellowColor; - ctx.fill(); - - // Target speed - - if (targetSpeed !== undefined) { - var targetSpeedY = (speed - targetSpeed) * speedPerPixel; - targetSpeedY = targetSpeedY + speedIndMid; - if (targetSpeedY < speedIndTop) { - // Target speed as text on top - ctx.font = "20px Arial"; - ctx.fillStyle = cyanColor; - const targetSpeedMetrics = ctx.measureText(targetSpeed); - ctx.fillText(targetSpeed, speedIndRight - targetSpeedMetrics.width / 2, speedIndTop - 4); - - } else if (targetSpeedY > speedIndBottom) { - // Target speed as text underneath - ctx.font = "20px Arial"; - ctx.fillStyle = cyanColor; - const targetSpeedMetrics = ctx.measureText(targetSpeed); - ctx.fillText(targetSpeed, speedIndRight - targetSpeedMetrics.width / 2, speedIndBottom + fm20.actualBoundingBoxAscent + 4); - } else { - // Cyan triangle on right side - const targetSpeedWidth = 40; - const targetSpeedHeight = 30; - const targetSpeedLeft = speedIndRight; - const targetSpeedRight = targetSpeedLeft + targetSpeedWidth; - - ctx.beginPath(); - ctx.moveTo(targetSpeedLeft, targetSpeedY); - ctx.lineTo(targetSpeedRight, targetSpeedY - targetSpeedHeight / 2); - ctx.lineTo(targetSpeedRight, targetSpeedY + targetSpeedHeight / 2); - ctx.lineTo(targetSpeedLeft, targetSpeedY); - ctx.lineWidth = 2; - ctx.strokeStyle = cyanColor; - ctx.stroke(); - } - } -} - -function drawAltitudeIndicator(ctx, fm20, fm30) { - // Altitude indicator - - const altitudeIndWidth = 70; - const altitudeIndHeight = 500; - const altitudeIndLeft = 750; - const altitudeIndRight = altitudeIndLeft + altitudeIndWidth; - const altitudeIndTop = 250; - const altitudeIndBottom = altitudeIndTop + altitudeIndHeight; - const altitudeIndMid = altitudeIndTop + altitudeIndHeight / 2; - - // Background - ctx.fillStyle = grayColor; - ctx.fillRect(altitudeIndLeft, altitudeIndTop, altitudeIndWidth, altitudeIndHeight); - - ctx.font = "30px Arial"; - const greaterThanMetrics = ctx.measureText(">"); - - // Mid point marker (for glideslope, but always visible) - ctx.fillStyle = yellowColor; - ctx.fillRect(altitudeIndLeft - 70, altitudeIndMid - 3, 50, 6); - - // Clip altitude tape - ctx.save(); - ctx.rect(altitudeIndLeft - greaterThanMetrics.width, altitudeIndTop, altitudeIndWidth + greaterThanMetrics.width, altitudeIndHeight); - ctx.clip(); - - // Altitude tape markings every 100 ft - const altitudeTapeLeft = altitudeIndRight - 10; - const altitudeTapeRight = altitudeIndRight; - const altitudeTapeSpacing = 40; - const altitudeTapeStep = 100; - const altitudeTextStep = 500; - const altitudePerPixel = altitudeTapeSpacing / altitudeTapeStep; // reciprocal - const altitudeOffset = (altitude % altitudeTextStep) * altitudePerPixel; - ctx.beginPath(); - var altitudeTape = Math.round(altitude - altitude % altitudeTextStep + 10 * altitudeTapeStep); - for (var i = -10; i < 7; i++) { - ctx.moveTo(altitudeTapeLeft, altitudeOffset + i * altitudeTapeSpacing + altitudeIndMid); - ctx.lineTo(altitudeTapeRight, altitudeOffset + i * altitudeTapeSpacing + altitudeIndMid); - altitudeTape -= altitudeTapeStep; - } - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Flight level texts every 500ft - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - var altitudeText = Math.round(altitude - altitude % altitudeTextStep + 2 * altitudeTextStep); - for (var i = -2; i < 2; i++) { - const flightLevelText = Math.abs(altitudeText / 100); // Don't display - if negative - const flightLevelTextString = ">" + flightLevelText.toString().padStart(3, '0'); - ctx.fillText(flightLevelTextString, altitudeIndLeft - greaterThanMetrics.width, altitudeOffset + i * altitudeTapeSpacing * 5 + altitudeIndMid + fm30.actualBoundingBoxAscent / 2); - altitudeText -= altitudeTextStep; - } - - // Disable clipping - ctx.restore(); - - // White lines at top, bottom and on right - ctx.beginPath(); - ctx.moveTo(altitudeIndLeft, altitudeIndTop); - ctx.lineTo(altitudeIndRight + 30, altitudeIndTop); - ctx.moveTo(altitudeIndLeft, altitudeIndTop + altitudeIndHeight); - ctx.lineTo(altitudeIndRight + 30, altitudeIndTop + altitudeIndHeight); - ctx.moveTo(altitudeIndRight, altitudeIndTop); - ctx.lineTo(altitudeIndRight, altitudeIndTop + altitudeIndHeight); - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Target altitude - - if (targetAltitude !== undefined) { - var targetAltitudeY = (altitude - targetAltitude) * altitudePerPixel; - targetAltitudeY = targetAltitudeY + altitudeIndMid; - - if (isStd()) { - targetAltitudeText = Math.round(targetAltitude / 100); - } else { - targetAltitudeText = Math.round(targetAltitude); - } - - if (targetAltitudeY < altitudeIndTop) { - // Target altitude as text on top - ctx.font = "30px Arial"; - ctx.fillStyle = cyanColor; - const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); - if (isStd()) { - ctx.fillText("FL", altitudeIndLeft, altitudeIndTop - 4); - } - ctx.fillText(targetAltitudeText, altitudeIndRight - targetAltitudeMetrics.width / 2, altitudeIndTop - 4); - } else if (targetAltitudeY > altitudeIndBottom) { - // Target altitude as text underneath - ctx.font = "30px Arial"; - ctx.fillStyle = cyanColor; - const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); - if (isStd()) { - ctx.fillText("FL", altitudeIndLeft, altitudeIndBottom + fm30.actualBoundingBoxAscent + 4); - } - ctx.fillText(targetAltitudeText, altitudeIndRight - targetAltitudeMetrics.width / 2, altitudeIndBottom + fm30.actualBoundingBoxAscent + 4); - } else { - - // Clip - ctx.save(); - ctx.rect(altitudeIndLeft - greaterThanMetrics.width, altitudeIndTop, altitudeIndWidth + greaterThanMetrics.width, altitudeIndHeight); - ctx.clip(); - - targetAltitudeText = targetAltitudeText.toString().padStart(3, '0'); - - ctx.font = "30px Arial"; - ctx.fillStyle = cyanColor; - const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); - - // Cyan box - const targetAltitudeWidth = 30; - const targetAltitudeHeight = 3 * (fm30.actualBoundingBoxAscent + fm30.actualBoundingBoxDescent); - const targetAltitudeBoxHeight = 1.1 * (fm30.actualBoundingBoxAscent + fm30.actualBoundingBoxDescent); - const targetAltitudeLeft = altitudeIndLeft - 5; - const targetAltitudeRight = targetAltitudeLeft + targetAltitudeWidth; - - ctx.beginPath(); - ctx.moveTo(targetAltitudeLeft, targetAltitudeY - targetAltitudeHeight / 2); - ctx.lineTo(targetAltitudeLeft, targetAltitudeY - 5); - ctx.lineTo(targetAltitudeLeft + 5, targetAltitudeY); - ctx.lineTo(targetAltitudeLeft, targetAltitudeY + 5); - ctx.lineTo(targetAltitudeLeft, targetAltitudeY + targetAltitudeHeight / 2); - ctx.lineTo(targetAltitudeRight, targetAltitudeY + targetAltitudeHeight / 2); - ctx.lineTo(targetAltitudeRight, targetAltitudeY - targetAltitudeHeight / 2); - ctx.lineTo(targetAltitudeLeft, targetAltitudeY - targetAltitudeHeight / 2); - ctx.lineWidth = 2; - ctx.lineWidth = 2; - ctx.strokeStyle = cyanColor; - ctx.stroke(); - - ctx.fillStyle = 'black'; - ctx.fillRect(altitudeIndLeft, targetAltitudeY - targetAltitudeBoxHeight / 2, altitudeIndWidth - 2, targetAltitudeBoxHeight); - ctx.fillStyle = cyanColor; - ctx.fillText(targetAltitudeText, altitudeIndLeft, targetAltitudeY + fm30.actualBoundingBoxAscent / 2); - - // Disable clipping - ctx.restore(); - } - } - - // Altitude - - ctx.font = "34px Arial"; - const levelText = (altitude === undefined) || isNaN(altitude) ? "" : Math.floor(altitude / 100).toString(); - const levelTextMetrics = ctx.measureText(levelText); - const levelTextHeightMetrics = ctx.measureText("0"); - const border = 2; - const levelHeight = levelTextHeightMetrics.actualBoundingBoxAscent + levelTextHeightMetrics.actualBoundingBoxDescent + 8 * border; - - const subscaleHeight = 60; - const subscaleWidth = 30; - - // Black background box - ctx.fillStyle = 'black'; - ctx.fillRect(altitudeIndLeft, altitudeIndMid - levelHeight / 2, altitudeIndWidth + 1, levelHeight); - - // Current flight level - if (levelText !== "") { - ctx.fillStyle = greenColor; - ctx.fillText(levelText, altitudeIndRight - levelTextMetrics.width, altitudeIndMid + levelTextMetrics.actualBoundingBoxAscent / 2); - } - - // Yellow box - ctx.beginPath(); - ctx.moveTo(altitudeIndLeft, altitudeIndMid - levelHeight / 2); - ctx.lineTo(altitudeIndRight, altitudeIndMid - levelHeight / 2); - ctx.lineTo(altitudeIndRight, altitudeIndMid - subscaleHeight / 2); - ctx.lineTo(altitudeIndRight + subscaleWidth, altitudeIndMid - subscaleHeight / 2); - ctx.lineTo(altitudeIndRight + subscaleWidth, altitudeIndMid + subscaleHeight / 2); - ctx.lineTo(altitudeIndRight, altitudeIndMid + subscaleHeight / 2); - ctx.lineTo(altitudeIndRight, altitudeIndMid + levelHeight / 2); - ctx.lineTo(altitudeIndLeft, altitudeIndMid + levelHeight / 2); - ctx.lineWidth = 2; - if (Math.abs(verticalSpeed) >= 6000) { - ctx.strokeStyle = orangeColor; - } else { - ctx.strokeStyle = yellowColor; - } - ctx.stroke(); - - // Clip around subscale - ctx.save(); - ctx.rect(altitudeIndRight, altitudeIndMid - subscaleHeight / 2, subscaleWidth, subscaleHeight); - ctx.clip(); - - const subscaleStep = 20; - var subscaleText = (altitude % 100) + subscaleStep * 2; - var subscaleSpacing = fm20.actualBoundingBoxAscent + fm20.actualBoundingBoxDescent + 2; - const subscalePerPixel = subscaleSpacing / subscaleStep; // reciprocal - const subscaleOffset = (altitude % subscaleStep) * subscalePerPixel; - ctx.font = "20px Arial"; - for (var i = -2; i < 2; i++) { - const subscaleTextString = (Math.floor((subscaleText % 100) / subscaleStep) * subscaleStep).toString().padStart(2, '0'); - ctx.fillText(subscaleTextString, altitudeIndRight + 1, subscaleOffset + i * subscaleSpacing + altitudeIndMid + fm20.actualBoundingBoxAscent / 2); - subscaleText -= subscaleStep; - if (subscaleText < 0) { - subscaleText += 100; - } - } - - // Disable clipping - ctx.restore(); -} -function drawHeadingIndicator(ctx, fm20, fm30) { - - const headingIndWidth = 450; - const headingIndHeight = 60; - const headingIndLeft = 225; - const headingIndRight = headingIndLeft + headingIndWidth; - const headingIndTop = 890; - const headingIndBottom = headingIndTop + headingIndHeight; - const headingIndMid = headingIndLeft + headingIndWidth / 2; - - ctx.fillStyle = grayColor; - ctx.fillRect(headingIndLeft, headingIndTop, headingIndWidth, headingIndHeight); - - // White lines left, right and top - ctx.beginPath(); - ctx.moveTo(headingIndLeft, headingIndBottom); - ctx.lineTo(headingIndLeft, headingIndTop); - ctx.lineTo(headingIndRight, headingIndTop); - ctx.lineTo(headingIndRight, headingIndBottom); - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - // Heading indicator line - ctx.beginPath(); - ctx.moveTo(headingIndMid, headingIndTop - 30); - ctx.lineTo(headingIndMid, headingIndTop); - ctx.lineWidth = 4; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - // Clip tape - ctx.save(); - ctx.rect(headingIndLeft, headingIndTop, headingIndWidth, headingIndHeight); - ctx.clip(); - - // Tape markings every 5 degrees - const headingTapeLeft = headingIndRight - 20; - const headingTapeRight = headingIndRight; - const headingTapeSpacing = 50; - const headingTapeStep = 5; - const headingTextStep = 10; - const headingPerPixel = headingTapeSpacing / headingTapeStep; - const headingOffset = - (heading % headingTextStep) * headingPerPixel; - ctx.beginPath(); - var headingTape = Math.round(heading - heading % headingTextStep - 6 * headingTapeStep); - for (var i = -6; i < 7; i++) { - ctx.moveTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop); - if (headingTape % 10 != 0) { - ctx.lineTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop + 10); - } else { - ctx.lineTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop + 20); - } - headingTape += headingTapeStep; - } - ctx.lineWidth = 2; - ctx.strokeStyle = "white"; - ctx.stroke(); - - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - const headingMetricsBig = ctx.measureText("36"); - ctx.font = "24px Arial"; - ctx.fillStyle = "white"; - const headingMetricsSmall = ctx.measureText("36"); - - // Headings every 10 degrees - var headingText = Math.round(heading - heading % headingTextStep - 3 * headingTextStep); - for (var i = -3; i < 4; i++) { - const big = headingText % 30 == 0; - if (big) { - ctx.font = "30px Arial"; - } else { - ctx.font = "24px Arial"; - } - ctx.fillStyle = "white"; - var headingTextMod = Math.round(headingText / 10) % 36; - if (headingTextMod < 0) { - headingTextMod += 36; - } - const headingTextString = headingTextMod.toString(); - const headingMetrics = ctx.measureText(headingTextString); - - ctx.fillText(headingTextString, headingOffset + i * headingTapeSpacing * 2 + headingIndMid - headingMetrics.width / 2, headingIndTop + 30 + headingMetrics.actualBoundingBoxAscent); - headingText += headingTextStep; - } - - // Track diamond - - if (track !== undefined) { - const trackMid = headingIndMid + (track - heading) * headingPerPixel; - const trackSize = 20; - - ctx.beginPath(); - ctx.moveTo(trackMid, headingIndTop); - ctx.lineTo(trackMid - trackSize / 2, headingIndTop + trackSize / 2); - ctx.lineTo(trackMid, headingIndTop + trackSize); - ctx.lineTo(trackMid + trackSize / 2, headingIndTop + trackSize / 2); - ctx.lineTo(trackMid, headingIndTop); - ctx.lineWidth = 5; - ctx.strokeStyle = greenColor; - ctx.stroke(); - } - - // Disable clipping - ctx.restore(); - - // Target heading - - if (targetHeading !== undefined) { - var targetDiff = targetHeading - heading; - if (targetDiff > 180) { - targetDiff -= 360; - } - var targetMid = headingIndMid + targetDiff * headingPerPixel; - if (targetMid < headingIndLeft) { - - // Display target heading as text on left - ctx.font = "20px Arial"; - ctx.fillStyle = cyanColor; - const targetHeadingText = Math.round(targetHeading).toString().padStart(3, '0'); - const targetHeadingMetrics = ctx.measureText(targetHeadingText); - ctx.fillText(targetHeadingText, headingIndLeft, headingIndTop - 4); - - } else if (targetMid > headingIndRight) { - - // Display target heading as text on right - ctx.font = "20px Arial"; - ctx.fillStyle = cyanColor; - const targetHeadingText = Math.round(targetHeading).toString().padStart(3, '0'); - const targetHeadingMetrics = ctx.measureText(targetHeadingText); - ctx.fillText(targetHeadingText, headingIndRight - targetHeadingMetrics.width, headingIndTop - 4); - - } else { - // Target indicator triangle - - const targetWidth = 30; - const targetHeight = 40; - - ctx.beginPath(); - ctx.moveTo(targetMid, headingIndTop); - ctx.lineTo(targetMid - targetWidth / 2, headingIndTop - targetHeight); - ctx.lineTo(targetMid + targetWidth / 2, headingIndTop - targetHeight); - ctx.lineTo(targetMid, headingIndTop); - ctx.lineWidth = 2; - ctx.strokeStyle = cyanColor; - ctx.stroke(); - } - } -} - -function drawBankAngleBoxMarker(ctx, radius, height) { - ctx.beginPath(); - ctx.moveTo(-5, -radius); - ctx.lineTo(-5, -radius - height); - ctx.lineTo(5, -radius - height); - ctx.lineTo(5, -radius); - ctx.lineWidth = 2; - ctx.strokeStyle = 'white'; - ctx.stroke(); -} - -function drawBankAngleLineMarker(ctx, radius, height) { - ctx.beginPath(); - ctx.moveTo(0, -radius); - ctx.lineTo(0, -radius - height); - ctx.lineWidth = 2; - ctx.strokeStyle = 'white'; - ctx.stroke(); -} -function drawAttitudeIndicator(ctx, fm20, fm30) { - - if (roll === undefined) { - return; - } - - // Height the same as airspeed indicator - cropped width same as heading indicator - - const speedIndRight = 30 + 100; - const altitudeIndLeft = 750; - - const attitudeIndMidX = speedIndRight + ((altitudeIndLeft - speedIndRight) / 2); - //const attitudeIndLeft = 30 + 100; // speedIndRight - //const attitudeIndRight = 750; // altitudeIndLeft - const attitudeIndWidth = 500; // speedIndHeight = 500; // attitudeIndRight - attitudeIndLeft; - const attitudeIndTop = 250; - const attitudeIndLeft = attitudeIndMidX - attitudeIndWidth / 2; - const attitudeIndHeight = attitudeIndWidth; // It's a circle - const attitudeIndMidY = attitudeIndTop + attitudeIndHeight / 2; - const attitudeIndCrop = (attitudeIndWidth - 450) / 2; // headingIndWidth = 450 - - // Clip - ctx.save(); - //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, 0, 2 * Math.PI); - ctx.beginPath(); - ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10 + Math.PI, Math.PI - Math.PI / 10 + Math.PI); - ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10, Math.PI - Math.PI / 10); -// //ctx.rect(attitudeIndLeft + attitudeIndCrop, attitudeIndTop, attitudeIndWidth - 2 * attitudeIndCrop, attitudeIndWidth); - // ctx.rect(attitudeIndLeft + attitudeIndCrop, attitudeIndTop, attitudeIndWidth - 2 * attitudeIndCrop, attitudeIndWidth); - ctx.clip(); - - - // Background - //ctx.beginPath(); - //ctx.fillStyle = cyanColor; - //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10, Math.PI - Math.PI / 10); - //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10 + Math.PI, Math.PI - Math.PI / 10 + Math.PI); - //console.log(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, 0, 2 * Math.PI); - //ctx.fill(); - - ctx.fillStyle = skyColor; - ctx.fillRect(attitudeIndLeft, attitudeIndTop, attitudeIndWidth, attitudeIndWidth); - - const rollRad = -roll * Math.PI / 180; - const radius = attitudeIndWidth / 2; - - ctx.fillStyle = groundColor; - ctx.beginPath(); - ctx.arc(attitudeIndMidX, attitudeIndMidY, radius, 0 + rollRad, Math.PI + rollRad); - ctx.fill(); - - //const offsetX = Math.cos(rollRad) * radius; - //const offsetY = Math.sin(rollRad) * radius; - //ctx.beginPath(); - //ctx.moveTo(attitudeIndMidX - offsetX, attitudeIndMidY - offsetY); - //ctx.lineTo(attitudeIndMidX + offsetX, attitudeIndMidY + offsetY); - //ctx.lineWidth = 2; - //ctx.strokeStyle = 'white'; - //ctx.stroke(); - - // Disable clipping - //ctx.restore(); - - const twoAndHalfDegOffset = 15; - const fiveDegOffset = twoAndHalfDegOffset * 2; - const tenDegOffset = twoAndHalfDegOffset * 4; - const fifteenDegOffset = twoAndHalfDegOffset * 2.5; - const spacing = 50; - - // ctx.save(); - - ctx.translate(attitudeIndMidX, attitudeIndMidY); - ctx.rotate(rollRad); - - ctx.beginPath(); - ctx.moveTo(-radius, 0); - ctx.lineTo(radius, 0); - for (var i = -2; i < 4; i++) { - ctx.moveTo(-twoAndHalfDegOffset, -i * spacing - spacing / 2); - ctx.lineTo(twoAndHalfDegOffset, -i * spacing - spacing / 2); - } - for (var i = -1; i < 5; i++) { - ctx.moveTo(-fiveDegOffset, -i * spacing); - ctx.lineTo(fiveDegOffset, -i * spacing); - } - for (var i = -1; i < 3; i++) { - ctx.moveTo(-tenDegOffset, -i * 2 * spacing); - ctx.lineTo(tenDegOffset, -i * 2 * spacing); - } - ctx.moveTo(-fifteenDegOffset, 2.75 * spacing); - ctx.lineTo(fifteenDegOffset, 2.75 * spacing); - ctx.moveTo(-tenDegOffset, 3.5 * spacing); - ctx.lineTo(tenDegOffset, 3.5 * spacing); - ctx.lineWidth = 2; - ctx.strokeStyle = 'white'; - ctx.stroke(); - - const greenThingWidth = 20; - ctx.beginPath(); - ctx.strokeStyle = greenColor; - ctx.moveTo(-fifteenDegOffset - greenThingWidth, 2.75 * spacing - 3); - ctx.lineTo(-fifteenDegOffset, 2.75 * spacing - 3); - ctx.moveTo(-fifteenDegOffset - greenThingWidth, 2.75 * spacing + 3); - ctx.lineTo(-fifteenDegOffset, 2.75 * spacing + 3); - ctx.moveTo(fifteenDegOffset + greenThingWidth, 2.75 * spacing - 3); - ctx.lineTo(fifteenDegOffset, 2.75 * spacing - 3); - ctx.moveTo(fifteenDegOffset + greenThingWidth, 2.75 * spacing + 3); - ctx.lineTo(fifteenDegOffset, 2.75 * spacing + 3); - ctx.stroke(); - - ctx.font = "20px Arial"; - ctx.fillStyle = 'white'; - const labelMetrics = ctx.measureText("20"); - const labelCenterY = labelMetrics.actualBoundingBoxAscent / 2; - const labelOffset = tenDegOffset + 10; - - ctx.fillText("10", labelOffset, spacing * 2 + labelCenterY); - ctx.fillText("10", -labelOffset - labelMetrics.width, spacing * 2 + labelCenterY); - ctx.fillText("10", labelOffset, -spacing * 2 + labelCenterY); - ctx.fillText("10", -labelOffset - labelMetrics.width, -spacing * 2 + labelCenterY); - ctx.fillText("20", labelOffset, -spacing * 4 + labelCenterY); - ctx.fillText("20", -labelOffset - labelMetrics.width, -spacing * 4 + labelCenterY); - ctx.fillText("20", labelOffset, spacing * 3.5 + labelCenterY); - ctx.fillText("20", -labelOffset - labelMetrics.width, spacing * 3.5 + labelCenterY); - - const rollBig = 18; - const rollSmall = 10; - - const rollTriangleOffet = 4; - - ctx.beginPath(); - ctx.moveTo(0, -radius + rollTriangleOffet); - ctx.lineTo(rollBig, -radius + rollBig + rollTriangleOffet); - ctx.lineTo(-rollBig, -radius + rollBig + rollTriangleOffet); - ctx.lineTo(0, -radius + rollTriangleOffet); - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - const rollTrapX1 = 20; - const rollTrapX2 = 30; - const rollTrapY1 = -radius + rollBig + rollTriangleOffet + 5; - const rollTrapY2 = rollTrapY1 + 10; - - ctx.beginPath(); - ctx.moveTo(-rollTrapX1, rollTrapY1); - ctx.lineTo(rollTrapX1, rollTrapY1); - ctx.lineTo(rollTrapX2, rollTrapY2); - ctx.lineTo(-rollTrapX2, rollTrapY2); - ctx.lineTo(-rollTrapX1, rollTrapY1); - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - ctx.restore(); - - // Roll scale - - ctx.save(); - ctx.translate(attitudeIndMidX, attitudeIndMidY); - - ctx.beginPath(); - ctx.rect(-radius, -radius - 2 *rollBig , radius * 2, radius); - ctx.clip(); - - ctx.beginPath(); - ctx.moveTo(0, -radius); - ctx.lineTo(rollBig, -radius - rollBig); - ctx.lineTo(-rollBig, -radius - rollBig); - ctx.lineTo(0, -radius); - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - - ctx.beginPath(); - ctx.arc(0, 0, radius, (240 - 2) * Math.PI / 180, (300 + 2) * Math.PI / 180); - ctx.lineWidth = 2; - ctx.strokeStyle = 'white'; - ctx.stroke(); - - ctx.rotate(45 * Math.PI / 180); - drawBankAngleLineMarker(ctx, radius, rollBig); - ctx.rotate(-15 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, rollBig); - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, 10); - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, 10); - ctx.rotate(-10 * Math.PI / 180); - - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, 10); - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, 10); - ctx.rotate(-10 * Math.PI / 180); - drawBankAngleBoxMarker(ctx, radius, rollBig); - ctx.rotate(-15 * Math.PI / 180); - drawBankAngleLineMarker(ctx, radius, rollBig); - - - // ctx.rotate(-rollRad); - // ctx.translate(-attitudeIndMidX, -attitudeIndMidY); - - ctx.restore(); - - // Wings - const wingThickness = 14; - const wingHeight = 35; - const wingWidth = 90; - const wingOffset = 130; - - ctx.beginPath(); - ctx.moveTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY - wingThickness / 2); - ctx.lineTo(attitudeIndMidX - wingOffset, attitudeIndMidY - wingThickness / 2); - ctx.lineTo(attitudeIndMidX - wingOffset, attitudeIndMidY + wingHeight); - ctx.lineTo(attitudeIndMidX - wingOffset - wingThickness, attitudeIndMidY + wingHeight); - ctx.lineTo(attitudeIndMidX - wingOffset - wingThickness, attitudeIndMidY + wingThickness / 2); - ctx.lineTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY + wingThickness / 2); - ctx.lineTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY - wingThickness / 2); - ctx.lineWidth = 4; - ctx.fillStyle = 'black'; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - ctx.fill(); - - ctx.beginPath(); - ctx.moveTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY - wingThickness / 2); - ctx.lineTo(attitudeIndMidX + wingOffset, attitudeIndMidY - wingThickness / 2); - ctx.lineTo(attitudeIndMidX + wingOffset, attitudeIndMidY + wingHeight); - ctx.lineTo(attitudeIndMidX + wingOffset + wingThickness, attitudeIndMidY + wingHeight); - ctx.lineTo(attitudeIndMidX + wingOffset + wingThickness, attitudeIndMidY + wingThickness / 2); - ctx.lineTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY + wingThickness / 2); - ctx.lineTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY - wingThickness / 2); - ctx.lineWidth = 4; - ctx.fillStyle = 'black'; - ctx.strokeStyle = yellowColor; - ctx.stroke(); - ctx.fill(); - - ctx.strokeRect(attitudeIndMidX - wingThickness / 2, attitudeIndMidY - wingThickness / 2, wingThickness, wingThickness); - - // Radio altitude - if ((radioAltitude !== undefined) && (radioAltitude <= 2500)) { - ctx.font = "30px Arial"; - if (radioAltitude < 100) { - ctx.fillStyle = orangeColor; - } else { - ctx.fillStyle = greenColor; - } - const raText = Math.round(radioAltitude).toString(); - const raTextMetrics = ctx.measureText(raText); - ctx.fillText(raText, attitudeIndMidX - raTextMetrics.width / 2, attitudeIndTop + attitudeIndHeight - 4); - } -} - -function drawPressure(ctx, fm20, fm30) { - - if (pressure !== undefined) { - - const pressureLeft = 750; // Righthand side of altitude indicator - const pressureMidX = 750 + 80; // Lefthand side of altitude indicator - const pressureMidY = 850; - - const pressureInt = Math.round(pressure); - - if (isStd()) { - - const border = 3; - ctx.font = "30px Arial"; - ctx.fillStyle = cyanColor; - const pressureText = "STD"; - const pressureMetrics = ctx.measureText(pressureText); - const height = pressureMetrics.actualBoundingBoxAscent + pressureMetrics.actualBoundingBoxDescent + 2 * border; - ctx.fillText(pressureText, pressureMidX - pressureMetrics.width / 2, pressureMidY); - - ctx.lineWidth = 2; - ctx.strokeStyle = yellowColor; - ctx.strokeRect(pressureMidX - pressureMetrics.width / 2 - border, pressureMidY - pressureMetrics.actualBoundingBoxAscent - 2 * border, pressureMetrics.width + border * 2, height + border * 2); - - } else { - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - ctx.fillText("QNH", pressureLeft, pressureMidY); - - ctx.fillStyle = cyanColor; - const pressureText = pressureInt.toString(); - ctx.fillText(pressureText, pressureMidX, pressureMidY); - } - } -} - -function drawMachIndicator(ctx) { - if (mach !== undefined) { - if (mach >= 0.45) { // Actually comes on at .5 and goes off at 0.45 - - ctx.font = "38px Arial"; - ctx.fillStyle = greenColor; - var machString; - if (mach < 1) { - machString = mach.toFixed(3).substring(1); // No leading 0 - } else { - machString = mach.toFixed(2); - } - - ctx.fillText(machString, 40, 840); - } - } -} -function drawVerticalSpeedIndicator(ctx, fm20, fm30) { - - const verticalSpeedIndWidth = 50; - const verticalSpeedIndHeight = 620; - const verticalSpeedIndLeft = 900; - const verticalSpeedIndTop = 190; - const verticalSpeedIndBottom = verticalSpeedIndTop + verticalSpeedIndHeight; - const verticalSpeedIndMidY = verticalSpeedIndTop + + verticalSpeedIndHeight / 2; - const verticalSpeedIndMidX = verticalSpeedIndLeft + verticalSpeedIndWidth / 2; - const verticalSpeedIndRight = verticalSpeedIndLeft + verticalSpeedIndWidth; - const verticalSpeedBevel = 80; - const verticalSpeedMarkerSpacing = 35; - const verticalSpeedMarkerWidth = verticalSpeedIndWidth / 4; - const verticalSpeedMarkerLeft = verticalSpeedIndLeft + verticalSpeedMarkerWidth; - const verticalSpeedIndText = verticalSpeedIndLeft + 1; - const verticalSpeedLineRight = verticalSpeedIndRight + 30; - const verticalSpeedLineLeft = verticalSpeedIndMidX - 5; - - - // Background - ctx.beginPath(); - ctx.moveTo(verticalSpeedIndLeft, verticalSpeedIndTop); - ctx.lineTo(verticalSpeedIndMidX, verticalSpeedIndTop); - ctx.lineTo(verticalSpeedIndRight, verticalSpeedIndTop + verticalSpeedBevel); - ctx.lineTo(verticalSpeedIndRight, verticalSpeedIndBottom - verticalSpeedBevel); - ctx.lineTo(verticalSpeedIndMidX, verticalSpeedIndBottom); - ctx.lineTo(verticalSpeedIndLeft, verticalSpeedIndBottom); - ctx.lineTo(verticalSpeedIndLeft, verticalSpeedIndTop); - ctx.fillStyle = grayColor; - ctx.fill(); - - // Labels - ctx.font = "20px Arial"; - ctx.fillStyle = 'white'; - ctx.fillText("6", verticalSpeedIndText, verticalSpeedIndMidY - 8 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("2", verticalSpeedIndText, verticalSpeedIndMidY - 6 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("1", verticalSpeedIndText, verticalSpeedIndMidY - 4 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("1", verticalSpeedIndText, verticalSpeedIndMidY + 4 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("2", verticalSpeedIndText, verticalSpeedIndMidY + 6 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - ctx.fillText("6", verticalSpeedIndText, verticalSpeedIndMidY + 8 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); - - // Markers - ctx.fillStyle = 'white'; - for (var i = -8; i <= 8; i++) - { - const j = Math.abs(i); - if (!((j == 1) || (j == 3))) { - var height; - if ((j == 4) || (j == 6) || (j == 8)) { - height = 6; - } else { - height = 2; - } - ctx.fillRect(verticalSpeedMarkerLeft, verticalSpeedIndMidY - i * verticalSpeedMarkerSpacing - height / 2, verticalSpeedMarkerWidth, height); - } - } - - // 0 marker - ctx.fillStyle = yellowColor; - ctx.fillRect(verticalSpeedIndLeft, verticalSpeedIndMidY - 3, verticalSpeedIndWidth / 2, 6); - - // Indicator line - - const verticalSpeedAbsolute = Math.abs(verticalSpeed); - var verticalOffset; - var color = greenColor; - - if (verticalSpeedAbsolute <= 1000) { - verticalOffset = verticalSpeedAbsolute / 1000 * 4 * verticalSpeedMarkerSpacing; - } else if (verticalSpeedAbsolute < 2000) { - verticalOffset = (verticalSpeedAbsolute - 1000) / 1000 * 2 * verticalSpeedMarkerSpacing + 4 * verticalSpeedMarkerSpacing; - } else if (verticalSpeedAbsolute < 6000) { - verticalOffset = (verticalSpeedAbsolute - 2000) / 4000 * 2 * verticalSpeedMarkerSpacing + 6 * verticalSpeedMarkerSpacing; - } else { - verticalOffset = 8 * verticalSpeedMarkerSpacing; - color = orangeColor; - } - - const verticalSpeedLineY = verticalSpeedIndMidY - verticalOffset * Math.sign(verticalSpeed); - - ctx.beginPath(); - ctx.moveTo(verticalSpeedLineRight, verticalSpeedIndMidY); - ctx.lineTo(verticalSpeedLineLeft, verticalSpeedLineY); - ctx.lineWidth = 4; - ctx.strokeStyle = color; - ctx.stroke(); - - // Text - if (verticalSpeedAbsolute > 200) { - - const verticalSpeedTextX = verticalSpeedLineLeft + 3; - const verticalSpeedTextHeight = fm20.actualBoundingBoxAscent + fm20.actualBoundingBoxDescent + 2; - const verticalSpeedText = Math.round(verticalSpeedAbsolute / 100); - const verticalSpeedTextString = verticalSpeedText.toString().padStart(2, '0'); - - // Background - ctx.fillStyle = 'black'; - if (verticalSpeed > 0) { - ctx.fillRect(verticalSpeedTextX, verticalSpeedLineY - verticalSpeedTextHeight, verticalSpeedIndWidth / 2, verticalSpeedTextHeight); - } else { - ctx.fillRect(verticalSpeedTextX, verticalSpeedLineY, verticalSpeedIndWidth / 2, verticalSpeedTextHeight); - } - - ctx.fillStyle = color; - if (verticalSpeed > 0) { - ctx.fillText(verticalSpeedTextString, verticalSpeedTextX, verticalSpeedLineY - fm20.actualBoundingBoxDescent - 1); - } else { - ctx.fillText(verticalSpeedTextString, verticalSpeedTextX, verticalSpeedLineY + fm20.actualBoundingBoxAscent + 1); - } - - } - -} - -// For testing only -var speedInc = 0.1; -var headingInc = 0.1; -var altitudeInc = 1; -var verticalSpeedInc = 10; -var rollInc = 0.1; -function animatePFD() { - if (speed === undefined) { - speed = 0; - targetSpeed = 200; - } else if (speed <= 0) { - speedInc = 0.1; - } else if (speed >= 350) { - speedInc = -0.1; - } - if (heading === undefined) { - heading = 0; - targetHeading = 180; - } else if (heading <= 0) { - headingInc = 0.1; - } else if (heading >= 360) { - headingInc = -0.1; - } - if (altitude === undefined) { - altitude = 0; - targetAltitude = 1000; - } else if (altitude <= 0) { - altitudeInc = 1; - } else if (altitude >= 45000) { - altitudeInc = -1; - } - if (verticalSpeed === undefined) { - verticalSpeed = -7000; - } else if (verticalSpeed <= -7000) { - verticalSpeedInc = 10; - } else if (verticalSpeed >= 7000) { - verticalSpeedInc = -10; - } - if (roll === undefined) { - roll = 45; - } else if (roll <= -45) { - rollInc = 0.1; - } else if (roll >= 45) { - rollInc = -0.1; - } - speed = speed + speedInc; - groundspeed = 150; - trueAirspeed = 130; - heading = heading + headingInc; - altitude = altitude + altitudeInc; - altitude = 39; - radioAltitude = 1720; - onSurface = 0; - verticalSpeed = verticalSpeed + verticalSpeedInc; - roll = roll + rollInc; - callsign = "BAW123G"; - aircraftType = "A320"; - windDirection = 85; - windSpeed = 15; - staticAirTemperature = 7; - verticalMode = 3; - lateralMode = 2; - autopilot = 1; - tcasMode = 1; - pressure = 1013; - //pressure = 1018; -} -function drawPFD() { - - const canvas = document.getElementById("pfdCanvas"); - const ctx = canvas.getContext("2d"); - - ctx.font = "20px Arial"; - const fm20 = ctx.measureText("180"); - ctx.font = "30px Arial"; - const fm30 = ctx.measureText("180"); - - // Background - - ctx.fillStyle = "black"; - ctx.fillRect(0, 0, 1000, 1000); - - // Airspeed indicator - - drawAirspeedIndicator(ctx, fm20, fm30); - - // Attitude indicator - - drawAttitudeIndicator(ctx, fm20, fm30); - - // Altimeter - - drawAltitudeIndicator(ctx, fm20, fm30); - - // Vertical speed indicator - - drawVerticalSpeedIndicator(ctx, fm20, fm30); - - // Heading indicator - - drawHeadingIndicator(ctx, fm20, fm30); - - // Pressure setting - - drawPressure(ctx, fm20, fm30); - - // Mach indicator - - drawMachIndicator(ctx); - - // Flight mode announciators - - ctx.beginPath(); - ctx.moveTo(220, 5); - ctx.lineTo(220, 140); - ctx.lineWidth = 1; - ctx.strokeStyle = "white"; - ctx.stroke(); - if (targetSpeed !== undefined) { - ctx.font = "30px Arial"; - ctx.fillStyle = greenColor; - ctx.fillText("SPEED", 55, 50); // THR CLB is climbing? - } else if (toga) { - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - ctx.fillText("TOGA", 70, 50); - } - - // FIXME: - //ctx.font = "30px Arial"; - //ctx.fillStyle = "white"; - //ctx.fillText("toga " + toga + " roll " + rollOut + " Surf " + onSurface + " wasSurf " + wasOnSurface60SecsAgo + " MS " + modelSpeed + " r/w Alt " + runwayAltitude, 50, 150); - - var landing = false; - if (verticalMode !== undefined) { - ctx.font = "30px Arial"; - ctx.fillStyle = greenColor; - if (verticalMode == 1) { - if (verticalSpeed !== undefined) { - if (verticalSpeed > 0) { - ctx.fillText("CLB", 290, 50); - } else if (verticalSpeed < 0) { - ctx.fillText("DES", 290, 50); - } else { - ctx.fillText("ALT", 290, 50); - } - } else if (targetAltitude !== undefined && altitude !== undefined) { - if (targetAltitude > altitude) { - ctx.fillText("CLB", 290, 50); - } else if (targetAltitude < altitude) { - ctx.fillText("DES", 290, 50); - } else { - ctx.fillText("ALT", 290, 50); - } - } - } else if (verticalMode == 2) { - ctx.fillText("ALT", 290, 50); - } else if (verticalMode == 3) { - if (rollOut) { - ctx.fillText("ROLL OUT", 370, 50); - landing = true; - } else if ((onSurface === 0) && (radioAltitude < 40)) { - ctx.fillText("FLARE", 390, 50); - landing = true; - } else if ((onSurface === 0) && (radioAltitude < 400)) { - ctx.fillText("LAND", 400, 50); - landing = true; - } else { - ctx.fillText("G/S", 290, 50); - } - } - } - if (!landing) { - ctx.beginPath(); - ctx.moveTo(420, 5); - ctx.lineTo(420, 140); - ctx.lineWidth = 1; - ctx.strokeStyle = "white"; - ctx.stroke(); - } - - ctx.beginPath(); - ctx.moveTo(660, 5); - ctx.lineTo(660, 140); - ctx.lineWidth = 1; - ctx.strokeStyle = "white"; - ctx.stroke(); - if (lateralMode !== undefined) { - ctx.font = "30px Arial"; - ctx.fillStyle = greenColor; - if (lateralMode == 1) { - ctx.fillText("NAV", 510, 50); - } else if (lateralMode == 2) { - if (!landing) { - ctx.fillText("LOC", 510, 50); - } - } - } - - ctx.beginPath(); - ctx.moveTo(850, 5); - ctx.lineTo(850, 140); - ctx.lineWidth = 1; - ctx.strokeStyle = "white"; - ctx.stroke(); - ctx.font = "30px Arial"; - ctx.fillStyle = "white"; - if (autopilot !== undefined) { - if (autopilot) { - if (verticalMode == 3) { - // We can't tell whether both APs are enabled - but they typically would be - ctx.fillText("AP1+2", 870, 40); - ctx.fillText("CAT3", 720, 40); - ctx.fillText("DUAL", 720, 85); - } else { - ctx.fillText("AP1", 890, 40); - } - } - } - ctx.fillText("1 FD 2", 870, 85); - if (((targetSpeed !== undefined) || autopilot) && !rollOut) { - ctx.fillText("A/THR", 870, 130); - } - - // Aircraft callsign and type - - ctx.fillStyle = "white"; - ctx.font = "30px Arial"; - if (callsign !== undefined) { - ctx.fillText(callsign, 20, 940); - } - ctx.font = "21px Arial"; - if (aircraftType !== undefined) { - ctx.fillText(aircraftType, 20, 980); - } - - const dataLeft = 750; // Aligned with QNH - const dataTop = 890; - - // TCAS - As displayed on ND/ECAM - if (tcasMode === 1) { - ctx.fillStyle = orangeColor; - ctx.font = "21px Arial"; - ctx.fillText("TCAS STBY", dataLeft, dataTop); - } else if (tcasMode === 2) { - ctx.fillStyle = "white"; - ctx.font = "21px Arial"; - ctx.fillText("TA ONLY", dataLeft, dataTop); - } - - // Groundspeed and TAS as displayed on ND - if ((groundspeed !== undefined) || (trueAirspeed !== undefined)) { - ctx.font = "21px Arial"; - if (groundspeed !== undefined) { - ctx.fillStyle = "white"; - ctx.fillText("GS", dataLeft, dataTop + 30); - ctx.fillStyle = greenColor; - ctx.fillText(Math.round(groundspeed).toString(), dataLeft + 40, dataTop + 30); - } - if (trueAirspeed !== undefined) { - ctx.fillStyle = "white"; - ctx.fillText("TAS", dataLeft + 90, dataTop + 30); - ctx.fillStyle = greenColor; - ctx.fillText(Math.round(trueAirspeed).toString(), dataLeft + 140, dataTop + 30); - } - } - - // Wind speed and direction as displayed on ND - if ((windSpeed !== undefined) && (windDirection !== undefined)) { - const windText = pad(Math.round(windDirection), 3) + "/" + Math.round(windSpeed); - ctx.fillStyle = greenColor; - ctx.font = "21px Arial"; - ctx.fillText(windText, dataLeft, dataTop + 60); - - if (heading !== undefined) { - // An arrow showing wind direction relative to heading - var angle = (windDirection - heading) * Math.PI / 180; - - ctx.save(); - ctx.translate(dataLeft + 80, dataTop + 53); - ctx.rotate(angle); - - ctx.strokeStyle = greenColor; - ctx.beginPath(); - ctx.moveTo(0, -10); - ctx.lineTo(0, 10); - ctx.lineTo(-5, 7); - ctx.moveTo(0, 10); - ctx.lineTo(5, 7); - ctx.stroke(); - - ctx.restore(); - } - } - - // Static air temperature as displayed on lower ECAM - if (staticAirTemperature !== undefined) { - var satText; - if (staticAirTemperature > 0) { - satText = "+" + Math.round(staticAirTemperature); - } else { - satText = Math.round(staticAirTemperature).toString(); - } - - ctx.font = "21px Arial"; - ctx.fillStyle = "white"; - ctx.fillText("SAT", dataLeft, dataTop + 90); - ctx.fillStyle = greenColor; - ctx.fillText(satText, dataLeft + 60, dataTop + 90); - ctx.fillStyle = cyanColor; - ctx.fillText("\u00B0C", dataLeft + 100, dataTop + 90); - } -} - -const canvas = document.getElementById('pfdCanvas'); -canvas.onmousedown = pfdMouseDown; -canvas.onmouseup = pfdMouseUp; -canvas.onmousemove = pfdMouseMove; -canvas.onmouseleave = pfdMouseLeave; -canvas.onmouseenter = pfdMouseEnter; -var docMouseMove = null; -var docMouseUp = null; -var movePFD = false; -var scalePFD = false; -var posX = 0; -var posY = 0; -var canvasWidth = 0; -var canvasHeight = 0; - -function pad(num, size) { - num = num.toString(); - while (num.length < size) num = "0" + num; - return num; -} - -function pfdMouseDown(e) { - e.preventDefault(); - e.stopPropagation(); - const r = canvas.getBoundingClientRect(); - posX = r.left; - posY = r.top; - canvasWidth = r.width; - canvasHeight = r.height; - if ((e.offsetX > 0.95 * canvasWidth) && (e.offsetY > 0.95 * canvasHeight)) { - scalePFD = true; - } else { - movePFD = true; - } -} -function pfdMouseUp(e) { - e.preventDefault(); - e.stopPropagation(); - movePFD = false; - scalePFD = false; - pfdRestoreDocMouse(); -} -function pfdMouseMove(e) { - e.preventDefault(); - e.stopPropagation(); - if (movePFD) { - posX = posX + e.movementX; - posY = posY + e.movementY; - canvas.style.position = "absolute"; - canvas.style.left = posX + "px"; - canvas.style.top = posY + "px"; - } else if (scalePFD) { - canvasWidth = canvasWidth + e.movementX; - canvasHeight = canvasHeight + e.movementY; - const constrainedWidth = Math.max(canvasWidth, 250); - const constrainedHeight = Math.max(canvasHeight, 250); - canvas.style.width = constrainedWidth + "px"; - canvas.style.height = constrainedHeight + "px"; - } -} - -function pfdMouseLeave(e) { - //movePFD = false; - //scalePFD = false; - if (scalePFD || movePFD) { - docMouseUp = document.onmouseup; - docMouseMove = document.onmousemove; - document.onmouseup = pfdMouseUp; - document.onmousemove = pfdMouseMove; - } -} - -function pfdRestoreDocMouse() { - if (docMouseUp) { - document.onmouseup = docMouseUp; - document.onmousemove = docMouseMove; - docMouseDown = null; - docMouseMove = null; - } -} -function pfdMouseEnter(e) { - pfdRestoreDocMouse(); -} +// Airbus like PFD (Primary Flight Display) + +var icao; +var callsign; +var aircraftType; +var onSurface; +var wasOnSurface60SecsAgo; +var speed; +var modelSpeed; // Speed of 3D model in Cesium +var trueAirspeed; +var groundspeed; +var targetSpeed; +var altitude; +var targetAltitude; +var radioAltitude; +var verticalSpeed; // ft/m +var heading; // degrees mag +var targetHeading; +var track; // degrees true +var pressure; // mb +var mach; +var roll; +var autopilot; +var verticalMode; +var lateralMode; +var tcasMode; +var windSpeed; +var windDirection; +var staticAirTemperature; + +var mdoelSpeed; +var toga = false; +var rollOut = false; +var runwayAltitude; + +const grayColor = "#6A75AE"; +const greenColor = "#20E966"; +const cyanColor = "#2FF7FE"; +const yellowColor = "#F4F82F"; +const orangeColor = "#FEDA30"; +const skyColor = "#26C9FF"; +const groundColor = "#D35E34"; + +function setPFDData(forward, newICAO, newCallsign, newAircraftType, newOnSurface, newWasOnSurface60SecsAgo, newRunwayAltitudeEstimate, + newModelSpeed, newIndicatedAirspeed, newTrueAirspeed, newGroundspeed, newMach, newAltitude, newRadioAltitude, newQnh, newVerticalSpeed, + newHeading, newTrack, newRoll, newSelectedAltitude, newSelectedHeading, + newAutopilot, newVerticalMode, newLateralMode, newTCASMode, + newWindSpeed, newWindDirection, newStaticAirTemperature) { + + //console.log('PFD', newIndicatedAirspeed, newMach, newAltitude, newQnh, newVerticalSpeed, newHeading, newTrack, newRoll, newSelectedAltitude, newSelectedHeading); + + const newAircraft = icao !== newICAO; + + if (newAircraft) { + toga = false; + rollOut = false; + runwayAltitude = undefined; + } + + icao = newICAO; + callsign = newCallsign; + aircraftType = newAircraftType; + onSurface = newOnSurface; + wasOnSurface60SecsAgo = newWasOnSurface60SecsAgo; + modelSpeed = newModelSpeed; + if ((newIndicatedAirspeed === undefined) || (newOnSurface > 0)) { + // IAS not transmitted frequently. After landing will no longer be valid + if (newGroundspeed !== undefined) { + speed = newGroundspeed; + } else { + speed = newModelSpeed; + } + } else { + speed = newIndicatedAirspeed; + } + trueAirspeed = newTrueAirspeed; + groundspeed = newGroundspeed; + mach = newMach; + altitude = newAltitude; + radioAltitude = newRadioAltitude; + pressure = newQnh; + verticalSpeed = newVerticalSpeed; + if (newHeading === undefined) { + heading = newTrack; // Track more frequent than heading + } else { + heading = newHeading; + } + track = newTrack; + roll = newRoll; + targetAltitude = newSelectedAltitude; + targetHeading = newSelectedHeading; + if (newAutopilot === -1) { + autopilot = undefined; + } else { + autopilot = newAutopilot; + } + verticalMode = newVerticalMode; + lateralMode = newLateralMode; + tcasMode = newTCASMode; + windSpeed = newWindSpeed; + windDirection = newWindDirection; + staticAirTemperature = newStaticAirTemperature; + + // Correct altitude for QNH setting + if (pressure !== undefined) { + altitude += (pressure - 1013.25) * 30; + } + + if (!rollOut && forward && (wasOnSurface60SecsAgo === 0) && (onSurface > 0) && (modelSpeed >= 70)) { + rollOut = true; + } else if (rollOut && ((modelSpeed < 40) || (onSurface === 0))) { + rollOut = false; + } + + const accelerationHeight = 1500; + + if (!toga && !rollOut && forward && (onSurface > 0) && (modelSpeed >= 35)) { + toga = true; // Start take-off roll on surface + runwayAltitude = altitude; + } else if (!toga && !rollOut && (modelSpeed >= 35) && (runwayAltitude === undefined) && (wasOnSurface60SecsAgo > 0) && (newRunwayAltitudeEstimate !== undefined)) { + toga = true; // For when selecting an aircraft having just taken off + runwayAltitude = newRunwayAltitudeEstimate; + } else if (!toga && !rollOut && (onSurface === 0) && (wasOnSurface60SecsAgo > 0) && (altitude !== undefined) && (runwayAltitude !== undefined) && (altitude < runwayAltitude + accelerationHeight)) { + toga = true; // For when played in reverse + } else if (toga && (modelSpeed <= 20)) { + toga = false; + } else if (toga && (altitude !== undefined) && (runwayAltitude !== undefined) && (altitude >= runwayAltitude + accelerationHeight)) { + toga = false; + } + if (toga && (runwayAltitude === undefined) && (newRunwayAltitudeEstimate !== undefined)) { + runwayAltitude = newRunwayAltitudeEstimate; + } +} + +function isStd() { + return (pressure >= 1012) && (pressure < 1014); +} + +function drawAirspeedIndicator(ctx, fm20, fm30) { + // Airspeed indicator + + const speedIndWidth = 100; + const speedIndHeight = 500; + const speedIndLeft = 30; + const speedIndRight = speedIndLeft + speedIndWidth; + const speedIndTop = 250; + const speedIndBottom = speedIndTop + speedIndHeight; + const speedIndMid = speedIndTop + speedIndHeight / 2; + + // Background + ctx.fillStyle = grayColor; + ctx.fillRect(speedIndLeft, speedIndTop, speedIndWidth, speedIndHeight); + + // Clip speed tape + ctx.save(); + ctx.rect(speedIndLeft, speedIndTop, speedIndWidth, speedIndHeight); + ctx.clip(); + + // Speed tape markings every 10knts + const speedTapMinSpeed = 0; // A320 only starts drawning from 30knts, but we draw from 0 + const speedTapeLeft = speedIndRight - 20; + const speedTapeRight = speedIndRight; + const speedTapeSpacing = 60; + const speedTapeStep = 10; + const speedTextStep = 20; + const speedPerPixel = speedTapeSpacing / speedTapeStep; + const speedOffset = (speed % speedTextStep) * speedPerPixel; + ctx.beginPath(); + var speedTape = Math.round(speed - speed % speedTextStep + 6 * speedTapeStep); + for (var i = -6; i < 5; i++) { + if (speedTape >= speedTapMinSpeed) { + ctx.moveTo(speedTapeLeft, speedOffset + i * speedTapeSpacing + speedIndMid); + ctx.lineTo(speedTapeRight, speedOffset + i * speedTapeSpacing + speedIndMid); + } + speedTape -= speedTapeStep; + } + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Speeds every 20knts + var speedText = Math.round(speed - speed % speedTextStep + 3 * speedTextStep); + for (var i = -3; i < 3; i++) { + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + if (speedText >= speedTapMinSpeed) { + const speedTextString = speedText.toString().padStart(3, '0'); + ctx.fillText(speedTextString, speedIndLeft + 20, speedOffset + i * speedTapeSpacing * 2 + speedIndMid + fm30.actualBoundingBoxAscent / 2); + } + speedText -= speedTextStep; + } + + // Disable clipping + ctx.restore(); + + ctx.beginPath(); + ctx.moveTo(speedIndLeft, speedIndTop); + ctx.lineTo(speedIndRight + 30, speedIndTop); + var speedIndRightLineHeight = speed / (speedIndHeight / 2 / speedPerPixel); // White line on right only drawn down to speedTapMinSpeed + if (speedIndRightLineHeight > 1) { + speedIndRightLineHeight = 1; + ctx.moveTo(speedIndLeft, speedIndTop + speedIndHeight); + ctx.lineTo(speedIndRight + 30, speedIndTop + speedIndHeight); + } + ctx.moveTo(speedIndRight, speedIndTop); + ctx.lineTo(speedIndRight, speedIndTop + speedIndRightLineHeight * (speedIndHeight / 2) + (speedIndHeight / 2)); + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Speed indicator + ctx.beginPath(); + ctx.moveTo(speedIndLeft - 10, speedIndMid); + ctx.lineTo(speedIndLeft, speedIndMid); + ctx.moveTo(speedTapeLeft - 5, speedIndMid); + ctx.lineTo(speedTapeRight + 20, speedIndMid); + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(speedTapeRight + 10, speedIndMid); + ctx.lineTo(speedTapeRight + 35, speedIndMid - 10); + ctx.lineTo(speedTapeRight + 35, speedIndMid + 10); + ctx.lineTo(speedTapeRight + 10, speedIndMid); + ctx.fillStyle = yellowColor; + ctx.fill(); + + // Target speed + + if (targetSpeed !== undefined) { + var targetSpeedY = (speed - targetSpeed) * speedPerPixel; + targetSpeedY = targetSpeedY + speedIndMid; + if (targetSpeedY < speedIndTop) { + // Target speed as text on top + ctx.font = "20px Arial"; + ctx.fillStyle = cyanColor; + const targetSpeedMetrics = ctx.measureText(targetSpeed); + ctx.fillText(targetSpeed, speedIndRight - targetSpeedMetrics.width / 2, speedIndTop - 4); + + } else if (targetSpeedY > speedIndBottom) { + // Target speed as text underneath + ctx.font = "20px Arial"; + ctx.fillStyle = cyanColor; + const targetSpeedMetrics = ctx.measureText(targetSpeed); + ctx.fillText(targetSpeed, speedIndRight - targetSpeedMetrics.width / 2, speedIndBottom + fm20.actualBoundingBoxAscent + 4); + } else { + // Cyan triangle on right side + const targetSpeedWidth = 40; + const targetSpeedHeight = 30; + const targetSpeedLeft = speedIndRight; + const targetSpeedRight = targetSpeedLeft + targetSpeedWidth; + + ctx.beginPath(); + ctx.moveTo(targetSpeedLeft, targetSpeedY); + ctx.lineTo(targetSpeedRight, targetSpeedY - targetSpeedHeight / 2); + ctx.lineTo(targetSpeedRight, targetSpeedY + targetSpeedHeight / 2); + ctx.lineTo(targetSpeedLeft, targetSpeedY); + ctx.lineWidth = 2; + ctx.strokeStyle = cyanColor; + ctx.stroke(); + } + } +} + +function drawAltitudeIndicator(ctx, fm20, fm30) { + // Altitude indicator + + const altitudeIndWidth = 70; + const altitudeIndHeight = 500; + const altitudeIndLeft = 750; + const altitudeIndRight = altitudeIndLeft + altitudeIndWidth; + const altitudeIndTop = 250; + const altitudeIndBottom = altitudeIndTop + altitudeIndHeight; + const altitudeIndMid = altitudeIndTop + altitudeIndHeight / 2; + + // Background + ctx.fillStyle = grayColor; + ctx.fillRect(altitudeIndLeft, altitudeIndTop, altitudeIndWidth, altitudeIndHeight); + + ctx.font = "30px Arial"; + const greaterThanMetrics = ctx.measureText(">"); + + // Mid point marker (for glideslope, but always visible) + ctx.fillStyle = yellowColor; + ctx.fillRect(altitudeIndLeft - 70, altitudeIndMid - 3, 50, 6); + + // Clip altitude tape + ctx.save(); + ctx.rect(altitudeIndLeft - greaterThanMetrics.width, altitudeIndTop, altitudeIndWidth + greaterThanMetrics.width, altitudeIndHeight); + ctx.clip(); + + // Altitude tape markings every 100 ft + const altitudeTapeLeft = altitudeIndRight - 10; + const altitudeTapeRight = altitudeIndRight; + const altitudeTapeSpacing = 40; + const altitudeTapeStep = 100; + const altitudeTextStep = 500; + const altitudePerPixel = altitudeTapeSpacing / altitudeTapeStep; // reciprocal + const altitudeOffset = (altitude % altitudeTextStep) * altitudePerPixel; + ctx.beginPath(); + var altitudeTape = Math.round(altitude - altitude % altitudeTextStep + 10 * altitudeTapeStep); + for (var i = -10; i < 7; i++) { + ctx.moveTo(altitudeTapeLeft, altitudeOffset + i * altitudeTapeSpacing + altitudeIndMid); + ctx.lineTo(altitudeTapeRight, altitudeOffset + i * altitudeTapeSpacing + altitudeIndMid); + altitudeTape -= altitudeTapeStep; + } + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Flight level texts every 500ft + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + var altitudeText = Math.round(altitude - altitude % altitudeTextStep + 2 * altitudeTextStep); + for (var i = -2; i < 2; i++) { + const flightLevelText = Math.abs(altitudeText / 100); // Don't display - if negative + const flightLevelTextString = ">" + flightLevelText.toString().padStart(3, '0'); + ctx.fillText(flightLevelTextString, altitudeIndLeft - greaterThanMetrics.width, altitudeOffset + i * altitudeTapeSpacing * 5 + altitudeIndMid + fm30.actualBoundingBoxAscent / 2); + altitudeText -= altitudeTextStep; + } + + // Disable clipping + ctx.restore(); + + // White lines at top, bottom and on right + ctx.beginPath(); + ctx.moveTo(altitudeIndLeft, altitudeIndTop); + ctx.lineTo(altitudeIndRight + 30, altitudeIndTop); + ctx.moveTo(altitudeIndLeft, altitudeIndTop + altitudeIndHeight); + ctx.lineTo(altitudeIndRight + 30, altitudeIndTop + altitudeIndHeight); + ctx.moveTo(altitudeIndRight, altitudeIndTop); + ctx.lineTo(altitudeIndRight, altitudeIndTop + altitudeIndHeight); + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Target altitude + + if (targetAltitude !== undefined) { + var targetAltitudeY = (altitude - targetAltitude) * altitudePerPixel; + targetAltitudeY = targetAltitudeY + altitudeIndMid; + + if (isStd()) { + targetAltitudeText = Math.round(targetAltitude / 100); + } else { + targetAltitudeText = Math.round(targetAltitude); + } + + if (targetAltitudeY < altitudeIndTop) { + // Target altitude as text on top + ctx.font = "30px Arial"; + ctx.fillStyle = cyanColor; + const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); + if (isStd()) { + ctx.fillText("FL", altitudeIndLeft, altitudeIndTop - 4); + } + ctx.fillText(targetAltitudeText, altitudeIndRight - targetAltitudeMetrics.width / 2, altitudeIndTop - 4); + } else if (targetAltitudeY > altitudeIndBottom) { + // Target altitude as text underneath + ctx.font = "30px Arial"; + ctx.fillStyle = cyanColor; + const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); + if (isStd()) { + ctx.fillText("FL", altitudeIndLeft, altitudeIndBottom + fm30.actualBoundingBoxAscent + 4); + } + ctx.fillText(targetAltitudeText, altitudeIndRight - targetAltitudeMetrics.width / 2, altitudeIndBottom + fm30.actualBoundingBoxAscent + 4); + } else { + + // Clip + ctx.save(); + ctx.rect(altitudeIndLeft - greaterThanMetrics.width, altitudeIndTop, altitudeIndWidth + greaterThanMetrics.width, altitudeIndHeight); + ctx.clip(); + + targetAltitudeText = targetAltitudeText.toString().padStart(3, '0'); + + ctx.font = "30px Arial"; + ctx.fillStyle = cyanColor; + const targetAltitudeMetrics = ctx.measureText(targetAltitudeText); + + // Cyan box + const targetAltitudeWidth = 30; + const targetAltitudeHeight = 3 * (fm30.actualBoundingBoxAscent + fm30.actualBoundingBoxDescent); + const targetAltitudeBoxHeight = 1.1 * (fm30.actualBoundingBoxAscent + fm30.actualBoundingBoxDescent); + const targetAltitudeLeft = altitudeIndLeft - 5; + const targetAltitudeRight = targetAltitudeLeft + targetAltitudeWidth; + + ctx.beginPath(); + ctx.moveTo(targetAltitudeLeft, targetAltitudeY - targetAltitudeHeight / 2); + ctx.lineTo(targetAltitudeLeft, targetAltitudeY - 5); + ctx.lineTo(targetAltitudeLeft + 5, targetAltitudeY); + ctx.lineTo(targetAltitudeLeft, targetAltitudeY + 5); + ctx.lineTo(targetAltitudeLeft, targetAltitudeY + targetAltitudeHeight / 2); + ctx.lineTo(targetAltitudeRight, targetAltitudeY + targetAltitudeHeight / 2); + ctx.lineTo(targetAltitudeRight, targetAltitudeY - targetAltitudeHeight / 2); + ctx.lineTo(targetAltitudeLeft, targetAltitudeY - targetAltitudeHeight / 2); + ctx.lineWidth = 2; + ctx.lineWidth = 2; + ctx.strokeStyle = cyanColor; + ctx.stroke(); + + ctx.fillStyle = 'black'; + ctx.fillRect(altitudeIndLeft, targetAltitudeY - targetAltitudeBoxHeight / 2, altitudeIndWidth - 2, targetAltitudeBoxHeight); + ctx.fillStyle = cyanColor; + ctx.fillText(targetAltitudeText, altitudeIndLeft, targetAltitudeY + fm30.actualBoundingBoxAscent / 2); + + // Disable clipping + ctx.restore(); + } + } + + // Altitude + + ctx.font = "34px Arial"; + const levelText = (altitude === undefined) || isNaN(altitude) ? "" : Math.floor(altitude / 100).toString(); + const levelTextMetrics = ctx.measureText(levelText); + const levelTextHeightMetrics = ctx.measureText("0"); + const border = 2; + const levelHeight = levelTextHeightMetrics.actualBoundingBoxAscent + levelTextHeightMetrics.actualBoundingBoxDescent + 8 * border; + + const subscaleHeight = 60; + const subscaleWidth = 30; + + // Black background box + ctx.fillStyle = 'black'; + ctx.fillRect(altitudeIndLeft, altitudeIndMid - levelHeight / 2, altitudeIndWidth + 1, levelHeight); + + // Current flight level + if (levelText !== "") { + ctx.fillStyle = greenColor; + ctx.fillText(levelText, altitudeIndRight - levelTextMetrics.width, altitudeIndMid + levelTextMetrics.actualBoundingBoxAscent / 2); + } + + // Yellow box + ctx.beginPath(); + ctx.moveTo(altitudeIndLeft, altitudeIndMid - levelHeight / 2); + ctx.lineTo(altitudeIndRight, altitudeIndMid - levelHeight / 2); + ctx.lineTo(altitudeIndRight, altitudeIndMid - subscaleHeight / 2); + ctx.lineTo(altitudeIndRight + subscaleWidth, altitudeIndMid - subscaleHeight / 2); + ctx.lineTo(altitudeIndRight + subscaleWidth, altitudeIndMid + subscaleHeight / 2); + ctx.lineTo(altitudeIndRight, altitudeIndMid + subscaleHeight / 2); + ctx.lineTo(altitudeIndRight, altitudeIndMid + levelHeight / 2); + ctx.lineTo(altitudeIndLeft, altitudeIndMid + levelHeight / 2); + ctx.lineWidth = 2; + if (Math.abs(verticalSpeed) >= 6000) { + ctx.strokeStyle = orangeColor; + } else { + ctx.strokeStyle = yellowColor; + } + ctx.stroke(); + + // Clip around subscale + ctx.save(); + ctx.rect(altitudeIndRight, altitudeIndMid - subscaleHeight / 2, subscaleWidth, subscaleHeight); + ctx.clip(); + + const subscaleStep = 20; + var subscaleText = (altitude % 100) + subscaleStep * 2; + var subscaleSpacing = fm20.actualBoundingBoxAscent + fm20.actualBoundingBoxDescent + 2; + const subscalePerPixel = subscaleSpacing / subscaleStep; // reciprocal + const subscaleOffset = (altitude % subscaleStep) * subscalePerPixel; + ctx.font = "20px Arial"; + for (var i = -2; i < 2; i++) { + const subscaleTextString = (Math.floor((subscaleText % 100) / subscaleStep) * subscaleStep).toString().padStart(2, '0'); + ctx.fillText(subscaleTextString, altitudeIndRight + 1, subscaleOffset + i * subscaleSpacing + altitudeIndMid + fm20.actualBoundingBoxAscent / 2); + subscaleText -= subscaleStep; + if (subscaleText < 0) { + subscaleText += 100; + } + } + + // Disable clipping + ctx.restore(); +} +function drawHeadingIndicator(ctx, fm20, fm30) { + + const headingIndWidth = 450; + const headingIndHeight = 60; + const headingIndLeft = 225; + const headingIndRight = headingIndLeft + headingIndWidth; + const headingIndTop = 890; + const headingIndBottom = headingIndTop + headingIndHeight; + const headingIndMid = headingIndLeft + headingIndWidth / 2; + + ctx.fillStyle = grayColor; + ctx.fillRect(headingIndLeft, headingIndTop, headingIndWidth, headingIndHeight); + + // White lines left, right and top + ctx.beginPath(); + ctx.moveTo(headingIndLeft, headingIndBottom); + ctx.lineTo(headingIndLeft, headingIndTop); + ctx.lineTo(headingIndRight, headingIndTop); + ctx.lineTo(headingIndRight, headingIndBottom); + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + // Heading indicator line + ctx.beginPath(); + ctx.moveTo(headingIndMid, headingIndTop - 30); + ctx.lineTo(headingIndMid, headingIndTop); + ctx.lineWidth = 4; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + // Clip tape + ctx.save(); + ctx.rect(headingIndLeft, headingIndTop, headingIndWidth, headingIndHeight); + ctx.clip(); + + // Tape markings every 5 degrees + const headingTapeLeft = headingIndRight - 20; + const headingTapeRight = headingIndRight; + const headingTapeSpacing = 50; + const headingTapeStep = 5; + const headingTextStep = 10; + const headingPerPixel = headingTapeSpacing / headingTapeStep; + const headingOffset = - (heading % headingTextStep) * headingPerPixel; + ctx.beginPath(); + var headingTape = Math.round(heading - heading % headingTextStep - 6 * headingTapeStep); + for (var i = -6; i < 7; i++) { + ctx.moveTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop); + if (headingTape % 10 != 0) { + ctx.lineTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop + 10); + } else { + ctx.lineTo(headingOffset + i * headingTapeSpacing + headingIndMid, headingIndTop + 20); + } + headingTape += headingTapeStep; + } + ctx.lineWidth = 2; + ctx.strokeStyle = "white"; + ctx.stroke(); + + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + const headingMetricsBig = ctx.measureText("36"); + ctx.font = "24px Arial"; + ctx.fillStyle = "white"; + const headingMetricsSmall = ctx.measureText("36"); + + // Headings every 10 degrees + var headingText = Math.round(heading - heading % headingTextStep - 3 * headingTextStep); + for (var i = -3; i < 4; i++) { + const big = headingText % 30 == 0; + if (big) { + ctx.font = "30px Arial"; + } else { + ctx.font = "24px Arial"; + } + ctx.fillStyle = "white"; + var headingTextMod = Math.round(headingText / 10) % 36; + if (headingTextMod < 0) { + headingTextMod += 36; + } + const headingTextString = headingTextMod.toString(); + const headingMetrics = ctx.measureText(headingTextString); + + ctx.fillText(headingTextString, headingOffset + i * headingTapeSpacing * 2 + headingIndMid - headingMetrics.width / 2, headingIndTop + 30 + headingMetrics.actualBoundingBoxAscent); + headingText += headingTextStep; + } + + // Track diamond + + if (track !== undefined) { + const trackMid = headingIndMid + (track - heading) * headingPerPixel; + const trackSize = 20; + + ctx.beginPath(); + ctx.moveTo(trackMid, headingIndTop); + ctx.lineTo(trackMid - trackSize / 2, headingIndTop + trackSize / 2); + ctx.lineTo(trackMid, headingIndTop + trackSize); + ctx.lineTo(trackMid + trackSize / 2, headingIndTop + trackSize / 2); + ctx.lineTo(trackMid, headingIndTop); + ctx.lineWidth = 5; + ctx.strokeStyle = greenColor; + ctx.stroke(); + } + + // Disable clipping + ctx.restore(); + + // Target heading + + if (targetHeading !== undefined) { + var targetDiff = targetHeading - heading; + if (targetDiff > 180) { + targetDiff -= 360; + } + var targetMid = headingIndMid + targetDiff * headingPerPixel; + if (targetMid < headingIndLeft) { + + // Display target heading as text on left + ctx.font = "20px Arial"; + ctx.fillStyle = cyanColor; + const targetHeadingText = Math.round(targetHeading).toString().padStart(3, '0'); + const targetHeadingMetrics = ctx.measureText(targetHeadingText); + ctx.fillText(targetHeadingText, headingIndLeft, headingIndTop - 4); + + } else if (targetMid > headingIndRight) { + + // Display target heading as text on right + ctx.font = "20px Arial"; + ctx.fillStyle = cyanColor; + const targetHeadingText = Math.round(targetHeading).toString().padStart(3, '0'); + const targetHeadingMetrics = ctx.measureText(targetHeadingText); + ctx.fillText(targetHeadingText, headingIndRight - targetHeadingMetrics.width, headingIndTop - 4); + + } else { + // Target indicator triangle + + const targetWidth = 30; + const targetHeight = 40; + + ctx.beginPath(); + ctx.moveTo(targetMid, headingIndTop); + ctx.lineTo(targetMid - targetWidth / 2, headingIndTop - targetHeight); + ctx.lineTo(targetMid + targetWidth / 2, headingIndTop - targetHeight); + ctx.lineTo(targetMid, headingIndTop); + ctx.lineWidth = 2; + ctx.strokeStyle = cyanColor; + ctx.stroke(); + } + } +} + +function drawBankAngleBoxMarker(ctx, radius, height) { + ctx.beginPath(); + ctx.moveTo(-5, -radius); + ctx.lineTo(-5, -radius - height); + ctx.lineTo(5, -radius - height); + ctx.lineTo(5, -radius); + ctx.lineWidth = 2; + ctx.strokeStyle = 'white'; + ctx.stroke(); +} + +function drawBankAngleLineMarker(ctx, radius, height) { + ctx.beginPath(); + ctx.moveTo(0, -radius); + ctx.lineTo(0, -radius - height); + ctx.lineWidth = 2; + ctx.strokeStyle = 'white'; + ctx.stroke(); +} +function drawAttitudeIndicator(ctx, fm20, fm30) { + + if (roll === undefined) { + return; + } + + // Height the same as airspeed indicator - cropped width same as heading indicator + + const speedIndRight = 30 + 100; + const altitudeIndLeft = 750; + + const attitudeIndMidX = speedIndRight + ((altitudeIndLeft - speedIndRight) / 2); + //const attitudeIndLeft = 30 + 100; // speedIndRight + //const attitudeIndRight = 750; // altitudeIndLeft + const attitudeIndWidth = 500; // speedIndHeight = 500; // attitudeIndRight - attitudeIndLeft; + const attitudeIndTop = 250; + const attitudeIndLeft = attitudeIndMidX - attitudeIndWidth / 2; + const attitudeIndHeight = attitudeIndWidth; // It's a circle + const attitudeIndMidY = attitudeIndTop + attitudeIndHeight / 2; + const attitudeIndCrop = (attitudeIndWidth - 450) / 2; // headingIndWidth = 450 + + // Clip + ctx.save(); + //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, 0, 2 * Math.PI); + ctx.beginPath(); + ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10 + Math.PI, Math.PI - Math.PI / 10 + Math.PI); + ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10, Math.PI - Math.PI / 10); +// //ctx.rect(attitudeIndLeft + attitudeIndCrop, attitudeIndTop, attitudeIndWidth - 2 * attitudeIndCrop, attitudeIndWidth); + // ctx.rect(attitudeIndLeft + attitudeIndCrop, attitudeIndTop, attitudeIndWidth - 2 * attitudeIndCrop, attitudeIndWidth); + ctx.clip(); + + + // Background + //ctx.beginPath(); + //ctx.fillStyle = cyanColor; + //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10, Math.PI - Math.PI / 10); + //ctx.arc(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, Math.PI / 10 + Math.PI, Math.PI - Math.PI / 10 + Math.PI); + //console.log(attitudeIndMidX, attitudeIndMidY, attitudeIndWidth / 2, 0, 2 * Math.PI); + //ctx.fill(); + + ctx.fillStyle = skyColor; + ctx.fillRect(attitudeIndLeft, attitudeIndTop, attitudeIndWidth, attitudeIndWidth); + + const rollRad = -roll * Math.PI / 180; + const radius = attitudeIndWidth / 2; + + ctx.fillStyle = groundColor; + ctx.beginPath(); + ctx.arc(attitudeIndMidX, attitudeIndMidY, radius, 0 + rollRad, Math.PI + rollRad); + ctx.fill(); + + //const offsetX = Math.cos(rollRad) * radius; + //const offsetY = Math.sin(rollRad) * radius; + //ctx.beginPath(); + //ctx.moveTo(attitudeIndMidX - offsetX, attitudeIndMidY - offsetY); + //ctx.lineTo(attitudeIndMidX + offsetX, attitudeIndMidY + offsetY); + //ctx.lineWidth = 2; + //ctx.strokeStyle = 'white'; + //ctx.stroke(); + + // Disable clipping + //ctx.restore(); + + const twoAndHalfDegOffset = 15; + const fiveDegOffset = twoAndHalfDegOffset * 2; + const tenDegOffset = twoAndHalfDegOffset * 4; + const fifteenDegOffset = twoAndHalfDegOffset * 2.5; + const spacing = 50; + + // ctx.save(); + + ctx.translate(attitudeIndMidX, attitudeIndMidY); + ctx.rotate(rollRad); + + ctx.beginPath(); + ctx.moveTo(-radius, 0); + ctx.lineTo(radius, 0); + for (var i = -2; i < 4; i++) { + ctx.moveTo(-twoAndHalfDegOffset, -i * spacing - spacing / 2); + ctx.lineTo(twoAndHalfDegOffset, -i * spacing - spacing / 2); + } + for (var i = -1; i < 5; i++) { + ctx.moveTo(-fiveDegOffset, -i * spacing); + ctx.lineTo(fiveDegOffset, -i * spacing); + } + for (var i = -1; i < 3; i++) { + ctx.moveTo(-tenDegOffset, -i * 2 * spacing); + ctx.lineTo(tenDegOffset, -i * 2 * spacing); + } + ctx.moveTo(-fifteenDegOffset, 2.75 * spacing); + ctx.lineTo(fifteenDegOffset, 2.75 * spacing); + ctx.moveTo(-tenDegOffset, 3.5 * spacing); + ctx.lineTo(tenDegOffset, 3.5 * spacing); + ctx.lineWidth = 2; + ctx.strokeStyle = 'white'; + ctx.stroke(); + + const greenThingWidth = 20; + ctx.beginPath(); + ctx.strokeStyle = greenColor; + ctx.moveTo(-fifteenDegOffset - greenThingWidth, 2.75 * spacing - 3); + ctx.lineTo(-fifteenDegOffset, 2.75 * spacing - 3); + ctx.moveTo(-fifteenDegOffset - greenThingWidth, 2.75 * spacing + 3); + ctx.lineTo(-fifteenDegOffset, 2.75 * spacing + 3); + ctx.moveTo(fifteenDegOffset + greenThingWidth, 2.75 * spacing - 3); + ctx.lineTo(fifteenDegOffset, 2.75 * spacing - 3); + ctx.moveTo(fifteenDegOffset + greenThingWidth, 2.75 * spacing + 3); + ctx.lineTo(fifteenDegOffset, 2.75 * spacing + 3); + ctx.stroke(); + + ctx.font = "20px Arial"; + ctx.fillStyle = 'white'; + const labelMetrics = ctx.measureText("20"); + const labelCenterY = labelMetrics.actualBoundingBoxAscent / 2; + const labelOffset = tenDegOffset + 10; + + ctx.fillText("10", labelOffset, spacing * 2 + labelCenterY); + ctx.fillText("10", -labelOffset - labelMetrics.width, spacing * 2 + labelCenterY); + ctx.fillText("10", labelOffset, -spacing * 2 + labelCenterY); + ctx.fillText("10", -labelOffset - labelMetrics.width, -spacing * 2 + labelCenterY); + ctx.fillText("20", labelOffset, -spacing * 4 + labelCenterY); + ctx.fillText("20", -labelOffset - labelMetrics.width, -spacing * 4 + labelCenterY); + ctx.fillText("20", labelOffset, spacing * 3.5 + labelCenterY); + ctx.fillText("20", -labelOffset - labelMetrics.width, spacing * 3.5 + labelCenterY); + + const rollBig = 18; + const rollSmall = 10; + + const rollTriangleOffet = 4; + + ctx.beginPath(); + ctx.moveTo(0, -radius + rollTriangleOffet); + ctx.lineTo(rollBig, -radius + rollBig + rollTriangleOffet); + ctx.lineTo(-rollBig, -radius + rollBig + rollTriangleOffet); + ctx.lineTo(0, -radius + rollTriangleOffet); + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + const rollTrapX1 = 20; + const rollTrapX2 = 30; + const rollTrapY1 = -radius + rollBig + rollTriangleOffet + 5; + const rollTrapY2 = rollTrapY1 + 10; + + ctx.beginPath(); + ctx.moveTo(-rollTrapX1, rollTrapY1); + ctx.lineTo(rollTrapX1, rollTrapY1); + ctx.lineTo(rollTrapX2, rollTrapY2); + ctx.lineTo(-rollTrapX2, rollTrapY2); + ctx.lineTo(-rollTrapX1, rollTrapY1); + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + ctx.restore(); + + // Roll scale + + ctx.save(); + ctx.translate(attitudeIndMidX, attitudeIndMidY); + + ctx.beginPath(); + ctx.rect(-radius, -radius - 2 *rollBig , radius * 2, radius); + ctx.clip(); + + ctx.beginPath(); + ctx.moveTo(0, -radius); + ctx.lineTo(rollBig, -radius - rollBig); + ctx.lineTo(-rollBig, -radius - rollBig); + ctx.lineTo(0, -radius); + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + + ctx.beginPath(); + ctx.arc(0, 0, radius, (240 - 2) * Math.PI / 180, (300 + 2) * Math.PI / 180); + ctx.lineWidth = 2; + ctx.strokeStyle = 'white'; + ctx.stroke(); + + ctx.rotate(45 * Math.PI / 180); + drawBankAngleLineMarker(ctx, radius, rollBig); + ctx.rotate(-15 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, rollBig); + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, 10); + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, 10); + ctx.rotate(-10 * Math.PI / 180); + + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, 10); + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, 10); + ctx.rotate(-10 * Math.PI / 180); + drawBankAngleBoxMarker(ctx, radius, rollBig); + ctx.rotate(-15 * Math.PI / 180); + drawBankAngleLineMarker(ctx, radius, rollBig); + + + // ctx.rotate(-rollRad); + // ctx.translate(-attitudeIndMidX, -attitudeIndMidY); + + ctx.restore(); + + // Wings + const wingThickness = 14; + const wingHeight = 35; + const wingWidth = 90; + const wingOffset = 130; + + ctx.beginPath(); + ctx.moveTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY - wingThickness / 2); + ctx.lineTo(attitudeIndMidX - wingOffset, attitudeIndMidY - wingThickness / 2); + ctx.lineTo(attitudeIndMidX - wingOffset, attitudeIndMidY + wingHeight); + ctx.lineTo(attitudeIndMidX - wingOffset - wingThickness, attitudeIndMidY + wingHeight); + ctx.lineTo(attitudeIndMidX - wingOffset - wingThickness, attitudeIndMidY + wingThickness / 2); + ctx.lineTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY + wingThickness / 2); + ctx.lineTo(attitudeIndMidX - wingOffset - wingWidth, attitudeIndMidY - wingThickness / 2); + ctx.lineWidth = 4; + ctx.fillStyle = 'black'; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + ctx.fill(); + + ctx.beginPath(); + ctx.moveTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY - wingThickness / 2); + ctx.lineTo(attitudeIndMidX + wingOffset, attitudeIndMidY - wingThickness / 2); + ctx.lineTo(attitudeIndMidX + wingOffset, attitudeIndMidY + wingHeight); + ctx.lineTo(attitudeIndMidX + wingOffset + wingThickness, attitudeIndMidY + wingHeight); + ctx.lineTo(attitudeIndMidX + wingOffset + wingThickness, attitudeIndMidY + wingThickness / 2); + ctx.lineTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY + wingThickness / 2); + ctx.lineTo(attitudeIndMidX + wingOffset + wingWidth, attitudeIndMidY - wingThickness / 2); + ctx.lineWidth = 4; + ctx.fillStyle = 'black'; + ctx.strokeStyle = yellowColor; + ctx.stroke(); + ctx.fill(); + + ctx.strokeRect(attitudeIndMidX - wingThickness / 2, attitudeIndMidY - wingThickness / 2, wingThickness, wingThickness); + + // Radio altitude + if ((radioAltitude !== undefined) && (radioAltitude <= 2500)) { + ctx.font = "30px Arial"; + if (radioAltitude < 100) { + ctx.fillStyle = orangeColor; + } else { + ctx.fillStyle = greenColor; + } + const raText = Math.round(radioAltitude).toString(); + const raTextMetrics = ctx.measureText(raText); + ctx.fillText(raText, attitudeIndMidX - raTextMetrics.width / 2, attitudeIndTop + attitudeIndHeight - 4); + } +} + +function drawPressure(ctx, fm20, fm30) { + + if (pressure !== undefined) { + + const pressureLeft = 750; // Righthand side of altitude indicator + const pressureMidX = 750 + 80; // Lefthand side of altitude indicator + const pressureMidY = 850; + + const pressureInt = Math.round(pressure); + + if (isStd()) { + + const border = 3; + ctx.font = "30px Arial"; + ctx.fillStyle = cyanColor; + const pressureText = "STD"; + const pressureMetrics = ctx.measureText(pressureText); + const height = pressureMetrics.actualBoundingBoxAscent + pressureMetrics.actualBoundingBoxDescent + 2 * border; + ctx.fillText(pressureText, pressureMidX - pressureMetrics.width / 2, pressureMidY); + + ctx.lineWidth = 2; + ctx.strokeStyle = yellowColor; + ctx.strokeRect(pressureMidX - pressureMetrics.width / 2 - border, pressureMidY - pressureMetrics.actualBoundingBoxAscent - 2 * border, pressureMetrics.width + border * 2, height + border * 2); + + } else { + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + ctx.fillText("QNH", pressureLeft, pressureMidY); + + ctx.fillStyle = cyanColor; + const pressureText = pressureInt.toString(); + ctx.fillText(pressureText, pressureMidX, pressureMidY); + } + } +} + +function drawMachIndicator(ctx) { + if (mach !== undefined) { + if (mach >= 0.45) { // Actually comes on at .5 and goes off at 0.45 + + ctx.font = "38px Arial"; + ctx.fillStyle = greenColor; + var machString; + if (mach < 1) { + machString = mach.toFixed(3).substring(1); // No leading 0 + } else { + machString = mach.toFixed(2); + } + + ctx.fillText(machString, 40, 840); + } + } +} +function drawVerticalSpeedIndicator(ctx, fm20, fm30) { + + const verticalSpeedIndWidth = 50; + const verticalSpeedIndHeight = 620; + const verticalSpeedIndLeft = 900; + const verticalSpeedIndTop = 190; + const verticalSpeedIndBottom = verticalSpeedIndTop + verticalSpeedIndHeight; + const verticalSpeedIndMidY = verticalSpeedIndTop + + verticalSpeedIndHeight / 2; + const verticalSpeedIndMidX = verticalSpeedIndLeft + verticalSpeedIndWidth / 2; + const verticalSpeedIndRight = verticalSpeedIndLeft + verticalSpeedIndWidth; + const verticalSpeedBevel = 80; + const verticalSpeedMarkerSpacing = 35; + const verticalSpeedMarkerWidth = verticalSpeedIndWidth / 4; + const verticalSpeedMarkerLeft = verticalSpeedIndLeft + verticalSpeedMarkerWidth; + const verticalSpeedIndText = verticalSpeedIndLeft + 1; + const verticalSpeedLineRight = verticalSpeedIndRight + 30; + const verticalSpeedLineLeft = verticalSpeedIndMidX - 5; + + + // Background + ctx.beginPath(); + ctx.moveTo(verticalSpeedIndLeft, verticalSpeedIndTop); + ctx.lineTo(verticalSpeedIndMidX, verticalSpeedIndTop); + ctx.lineTo(verticalSpeedIndRight, verticalSpeedIndTop + verticalSpeedBevel); + ctx.lineTo(verticalSpeedIndRight, verticalSpeedIndBottom - verticalSpeedBevel); + ctx.lineTo(verticalSpeedIndMidX, verticalSpeedIndBottom); + ctx.lineTo(verticalSpeedIndLeft, verticalSpeedIndBottom); + ctx.lineTo(verticalSpeedIndLeft, verticalSpeedIndTop); + ctx.fillStyle = grayColor; + ctx.fill(); + + // Labels + ctx.font = "20px Arial"; + ctx.fillStyle = 'white'; + ctx.fillText("6", verticalSpeedIndText, verticalSpeedIndMidY - 8 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("2", verticalSpeedIndText, verticalSpeedIndMidY - 6 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("1", verticalSpeedIndText, verticalSpeedIndMidY - 4 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("1", verticalSpeedIndText, verticalSpeedIndMidY + 4 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("2", verticalSpeedIndText, verticalSpeedIndMidY + 6 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + ctx.fillText("6", verticalSpeedIndText, verticalSpeedIndMidY + 8 * verticalSpeedMarkerSpacing + fm20.actualBoundingBoxAscent / 2); + + // Markers + ctx.fillStyle = 'white'; + for (var i = -8; i <= 8; i++) + { + const j = Math.abs(i); + if (!((j == 1) || (j == 3))) { + var height; + if ((j == 4) || (j == 6) || (j == 8)) { + height = 6; + } else { + height = 2; + } + ctx.fillRect(verticalSpeedMarkerLeft, verticalSpeedIndMidY - i * verticalSpeedMarkerSpacing - height / 2, verticalSpeedMarkerWidth, height); + } + } + + // 0 marker + ctx.fillStyle = yellowColor; + ctx.fillRect(verticalSpeedIndLeft, verticalSpeedIndMidY - 3, verticalSpeedIndWidth / 2, 6); + + // Indicator line + + const verticalSpeedAbsolute = Math.abs(verticalSpeed); + var verticalOffset; + var color = greenColor; + + if (verticalSpeedAbsolute <= 1000) { + verticalOffset = verticalSpeedAbsolute / 1000 * 4 * verticalSpeedMarkerSpacing; + } else if (verticalSpeedAbsolute < 2000) { + verticalOffset = (verticalSpeedAbsolute - 1000) / 1000 * 2 * verticalSpeedMarkerSpacing + 4 * verticalSpeedMarkerSpacing; + } else if (verticalSpeedAbsolute < 6000) { + verticalOffset = (verticalSpeedAbsolute - 2000) / 4000 * 2 * verticalSpeedMarkerSpacing + 6 * verticalSpeedMarkerSpacing; + } else { + verticalOffset = 8 * verticalSpeedMarkerSpacing; + color = orangeColor; + } + + const verticalSpeedLineY = verticalSpeedIndMidY - verticalOffset * Math.sign(verticalSpeed); + + ctx.beginPath(); + ctx.moveTo(verticalSpeedLineRight, verticalSpeedIndMidY); + ctx.lineTo(verticalSpeedLineLeft, verticalSpeedLineY); + ctx.lineWidth = 4; + ctx.strokeStyle = color; + ctx.stroke(); + + // Text + if (verticalSpeedAbsolute > 200) { + + const verticalSpeedTextX = verticalSpeedLineLeft + 3; + const verticalSpeedTextHeight = fm20.actualBoundingBoxAscent + fm20.actualBoundingBoxDescent + 2; + const verticalSpeedText = Math.round(verticalSpeedAbsolute / 100); + const verticalSpeedTextString = verticalSpeedText.toString().padStart(2, '0'); + + // Background + ctx.fillStyle = 'black'; + if (verticalSpeed > 0) { + ctx.fillRect(verticalSpeedTextX, verticalSpeedLineY - verticalSpeedTextHeight, verticalSpeedIndWidth / 2, verticalSpeedTextHeight); + } else { + ctx.fillRect(verticalSpeedTextX, verticalSpeedLineY, verticalSpeedIndWidth / 2, verticalSpeedTextHeight); + } + + ctx.fillStyle = color; + if (verticalSpeed > 0) { + ctx.fillText(verticalSpeedTextString, verticalSpeedTextX, verticalSpeedLineY - fm20.actualBoundingBoxDescent - 1); + } else { + ctx.fillText(verticalSpeedTextString, verticalSpeedTextX, verticalSpeedLineY + fm20.actualBoundingBoxAscent + 1); + } + + } + +} + +// For testing only +var speedInc = 0.1; +var headingInc = 0.1; +var altitudeInc = 1; +var verticalSpeedInc = 10; +var rollInc = 0.1; +function animatePFD() { + if (speed === undefined) { + speed = 0; + targetSpeed = 200; + } else if (speed <= 0) { + speedInc = 0.1; + } else if (speed >= 350) { + speedInc = -0.1; + } + if (heading === undefined) { + heading = 0; + targetHeading = 180; + } else if (heading <= 0) { + headingInc = 0.1; + } else if (heading >= 360) { + headingInc = -0.1; + } + if (altitude === undefined) { + altitude = 0; + targetAltitude = 1000; + } else if (altitude <= 0) { + altitudeInc = 1; + } else if (altitude >= 45000) { + altitudeInc = -1; + } + if (verticalSpeed === undefined) { + verticalSpeed = -7000; + } else if (verticalSpeed <= -7000) { + verticalSpeedInc = 10; + } else if (verticalSpeed >= 7000) { + verticalSpeedInc = -10; + } + if (roll === undefined) { + roll = 45; + } else if (roll <= -45) { + rollInc = 0.1; + } else if (roll >= 45) { + rollInc = -0.1; + } + speed = speed + speedInc; + groundspeed = 150; + trueAirspeed = 130; + heading = heading + headingInc; + altitude = altitude + altitudeInc; + altitude = 39; + radioAltitude = 1720; + onSurface = 0; + verticalSpeed = verticalSpeed + verticalSpeedInc; + roll = roll + rollInc; + callsign = "BAW123G"; + aircraftType = "A320"; + windDirection = 85; + windSpeed = 15; + staticAirTemperature = 7; + verticalMode = 3; + lateralMode = 2; + autopilot = 1; + tcasMode = 1; + pressure = 1013; + //pressure = 1018; +} +function drawPFD() { + + const canvas = document.getElementById("pfdCanvas"); + const ctx = canvas.getContext("2d"); + + ctx.font = "20px Arial"; + const fm20 = ctx.measureText("180"); + ctx.font = "30px Arial"; + const fm30 = ctx.measureText("180"); + + // Background + + ctx.fillStyle = "black"; + ctx.fillRect(0, 0, 1000, 1000); + + // Airspeed indicator + + drawAirspeedIndicator(ctx, fm20, fm30); + + // Attitude indicator + + drawAttitudeIndicator(ctx, fm20, fm30); + + // Altimeter + + drawAltitudeIndicator(ctx, fm20, fm30); + + // Vertical speed indicator + + drawVerticalSpeedIndicator(ctx, fm20, fm30); + + // Heading indicator + + drawHeadingIndicator(ctx, fm20, fm30); + + // Pressure setting + + drawPressure(ctx, fm20, fm30); + + // Mach indicator + + drawMachIndicator(ctx); + + // Flight mode announciators + + ctx.beginPath(); + ctx.moveTo(220, 5); + ctx.lineTo(220, 140); + ctx.lineWidth = 1; + ctx.strokeStyle = "white"; + ctx.stroke(); + if (targetSpeed !== undefined) { + ctx.font = "30px Arial"; + ctx.fillStyle = greenColor; + ctx.fillText("SPEED", 55, 50); // THR CLB is climbing? + } else if (toga) { + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + ctx.fillText("TOGA", 70, 50); + } + + // FIXME: + //ctx.font = "30px Arial"; + //ctx.fillStyle = "white"; + //ctx.fillText("toga " + toga + " roll " + rollOut + " Surf " + onSurface + " wasSurf " + wasOnSurface60SecsAgo + " MS " + modelSpeed + " r/w Alt " + runwayAltitude, 50, 150); + + var landing = false; + if (verticalMode !== undefined) { + ctx.font = "30px Arial"; + ctx.fillStyle = greenColor; + if (verticalMode == 1) { + if (verticalSpeed !== undefined) { + if (verticalSpeed > 0) { + ctx.fillText("CLB", 290, 50); + } else if (verticalSpeed < 0) { + ctx.fillText("DES", 290, 50); + } else { + ctx.fillText("ALT", 290, 50); + } + } else if (targetAltitude !== undefined && altitude !== undefined) { + if (targetAltitude > altitude) { + ctx.fillText("CLB", 290, 50); + } else if (targetAltitude < altitude) { + ctx.fillText("DES", 290, 50); + } else { + ctx.fillText("ALT", 290, 50); + } + } + } else if (verticalMode == 2) { + ctx.fillText("ALT", 290, 50); + } else if (verticalMode == 3) { + if (rollOut) { + ctx.fillText("ROLL OUT", 370, 50); + landing = true; + } else if ((onSurface === 0) && (radioAltitude < 40)) { + ctx.fillText("FLARE", 390, 50); + landing = true; + } else if ((onSurface === 0) && (radioAltitude < 400)) { + ctx.fillText("LAND", 400, 50); + landing = true; + } else { + ctx.fillText("G/S", 290, 50); + } + } + } + if (!landing) { + ctx.beginPath(); + ctx.moveTo(420, 5); + ctx.lineTo(420, 140); + ctx.lineWidth = 1; + ctx.strokeStyle = "white"; + ctx.stroke(); + } + + ctx.beginPath(); + ctx.moveTo(660, 5); + ctx.lineTo(660, 140); + ctx.lineWidth = 1; + ctx.strokeStyle = "white"; + ctx.stroke(); + if (lateralMode !== undefined) { + ctx.font = "30px Arial"; + ctx.fillStyle = greenColor; + if (lateralMode == 1) { + ctx.fillText("NAV", 510, 50); + } else if (lateralMode == 2) { + if (!landing) { + ctx.fillText("LOC", 510, 50); + } + } + } + + ctx.beginPath(); + ctx.moveTo(850, 5); + ctx.lineTo(850, 140); + ctx.lineWidth = 1; + ctx.strokeStyle = "white"; + ctx.stroke(); + ctx.font = "30px Arial"; + ctx.fillStyle = "white"; + if (autopilot !== undefined) { + if (autopilot) { + if (verticalMode == 3) { + // We can't tell whether both APs are enabled - but they typically would be + ctx.fillText("AP1+2", 870, 40); + ctx.fillText("CAT3", 720, 40); + ctx.fillText("DUAL", 720, 85); + } else { + ctx.fillText("AP1", 890, 40); + } + } + } + ctx.fillText("1 FD 2", 870, 85); + if (((targetSpeed !== undefined) || autopilot) && !rollOut) { + ctx.fillText("A/THR", 870, 130); + } + + // Aircraft callsign and type + + ctx.fillStyle = "white"; + ctx.font = "30px Arial"; + if (callsign !== undefined) { + ctx.fillText(callsign, 20, 940); + } + ctx.font = "21px Arial"; + if (aircraftType !== undefined) { + ctx.fillText(aircraftType, 20, 980); + } + + const dataLeft = 750; // Aligned with QNH + const dataTop = 890; + + // TCAS - As displayed on ND/ECAM + if (tcasMode === 1) { + ctx.fillStyle = orangeColor; + ctx.font = "21px Arial"; + ctx.fillText("TCAS STBY", dataLeft, dataTop); + } else if (tcasMode === 2) { + ctx.fillStyle = "white"; + ctx.font = "21px Arial"; + ctx.fillText("TA ONLY", dataLeft, dataTop); + } + + // Groundspeed and TAS as displayed on ND + if ((groundspeed !== undefined) || (trueAirspeed !== undefined)) { + ctx.font = "21px Arial"; + if (groundspeed !== undefined) { + ctx.fillStyle = "white"; + ctx.fillText("GS", dataLeft, dataTop + 30); + ctx.fillStyle = greenColor; + ctx.fillText(Math.round(groundspeed).toString(), dataLeft + 40, dataTop + 30); + } + if (trueAirspeed !== undefined) { + ctx.fillStyle = "white"; + ctx.fillText("TAS", dataLeft + 90, dataTop + 30); + ctx.fillStyle = greenColor; + ctx.fillText(Math.round(trueAirspeed).toString(), dataLeft + 140, dataTop + 30); + } + } + + // Wind speed and direction as displayed on ND + if ((windSpeed !== undefined) && (windDirection !== undefined)) { + const windText = pad(Math.round(windDirection), 3) + "/" + Math.round(windSpeed); + ctx.fillStyle = greenColor; + ctx.font = "21px Arial"; + ctx.fillText(windText, dataLeft, dataTop + 60); + + if (heading !== undefined) { + // An arrow showing wind direction relative to heading + var angle = (windDirection - heading) * Math.PI / 180; + + ctx.save(); + ctx.translate(dataLeft + 80, dataTop + 53); + ctx.rotate(angle); + + ctx.strokeStyle = greenColor; + ctx.beginPath(); + ctx.moveTo(0, -10); + ctx.lineTo(0, 10); + ctx.lineTo(-5, 7); + ctx.moveTo(0, 10); + ctx.lineTo(5, 7); + ctx.stroke(); + + ctx.restore(); + } + } + + // Static air temperature as displayed on lower ECAM + if (staticAirTemperature !== undefined) { + var satText; + if (staticAirTemperature > 0) { + satText = "+" + Math.round(staticAirTemperature); + } else { + satText = Math.round(staticAirTemperature).toString(); + } + + ctx.font = "21px Arial"; + ctx.fillStyle = "white"; + ctx.fillText("SAT", dataLeft, dataTop + 90); + ctx.fillStyle = greenColor; + ctx.fillText(satText, dataLeft + 60, dataTop + 90); + ctx.fillStyle = cyanColor; + ctx.fillText("\u00B0C", dataLeft + 100, dataTop + 90); + } +} + +const canvas = document.getElementById('pfdCanvas'); +canvas.onmousedown = pfdMouseDown; +canvas.onmouseup = pfdMouseUp; +canvas.onmousemove = pfdMouseMove; +canvas.onmouseleave = pfdMouseLeave; +canvas.onmouseenter = pfdMouseEnter; +var docMouseMove = null; +var docMouseUp = null; +var movePFD = false; +var scalePFD = false; +var posX = 0; +var posY = 0; +var canvasWidth = 0; +var canvasHeight = 0; + +function pad(num, size) { + num = num.toString(); + while (num.length < size) num = "0" + num; + return num; +} + +function pfdMouseDown(e) { + e.preventDefault(); + e.stopPropagation(); + const r = canvas.getBoundingClientRect(); + posX = r.left; + posY = r.top; + canvasWidth = r.width; + canvasHeight = r.height; + if ((e.offsetX > 0.95 * canvasWidth) && (e.offsetY > 0.95 * canvasHeight)) { + scalePFD = true; + } else { + movePFD = true; + } +} +function pfdMouseUp(e) { + e.preventDefault(); + e.stopPropagation(); + movePFD = false; + scalePFD = false; + pfdRestoreDocMouse(); +} +function pfdMouseMove(e) { + e.preventDefault(); + e.stopPropagation(); + if (movePFD) { + posX = posX + e.movementX; + posY = posY + e.movementY; + canvas.style.position = "absolute"; + canvas.style.left = posX + "px"; + canvas.style.top = posY + "px"; + } else if (scalePFD) { + canvasWidth = canvasWidth + e.movementX; + canvasHeight = canvasHeight + e.movementY; + const constrainedWidth = Math.max(canvasWidth, 250); + const constrainedHeight = Math.max(canvasHeight, 250); + canvas.style.width = constrainedWidth + "px"; + canvas.style.height = constrainedHeight + "px"; + } +} + +function pfdMouseLeave(e) { + //movePFD = false; + //scalePFD = false; + if (scalePFD || movePFD) { + docMouseUp = document.onmouseup; + docMouseMove = document.onmousemove; + document.onmouseup = pfdMouseUp; + document.onmousemove = pfdMouseMove; + } +} + +function pfdRestoreDocMouse() { + if (docMouseUp) { + document.onmouseup = docMouseUp; + document.onmousemove = docMouseMove; + docMouseDown = null; + docMouseMove = null; + } +} +function pfdMouseEnter(e) { + pfdRestoreDocMouse(); +} diff --git a/plugins/feature/map/map/grid.js b/plugins/feature/map/map/grid.js index c9b94963b..742292390 100644 --- a/plugins/feature/map/map/grid.js +++ b/plugins/feature/map/map/grid.js @@ -1,165 +1,165 @@ -// Maidenhead grid for Cesium - -const polylines = new Cesium.PolylineCollection(); -const polylinesFine = new Cesium.PolylineCollection(); - -const labels = new Cesium.LabelCollection(); -const labelsFine = new Cesium.LabelCollection(); - -const segLen = 2; - -const gridMaterial = Cesium.Material.fromType('Color'); -gridMaterial.uniforms.color = new Cesium.Color(0.6, 0.6, 0.6, 1.0); -const gridLabelColor = new Cesium.Color(1, 1, 1, 1.0); - -function createLat() { - for (var lon = -180; lon < 180; lon += 20) { - const array = []; - for (var lat = -90; lat <= 90; lat += segLen) { - array.push(lon); - array.push(lat); - } - polylines.add({ - positions: Cesium.Cartesian3.fromDegreesArray(array), - width: 1, - material: gridMaterial - }); - - } -} - -function createLatFine() { - for (var lon = -180; lon < 180; lon += 2) { - if (lon % 20 != 0) { - const array = []; - for (var lat = -90; lat <= 90; lat += segLen) { - array.push(lon); - array.push(lat); - } - polylinesFine.add({ - positions: Cesium.Cartesian3.fromDegreesArray(array), - width: 1, - material: gridMaterial - }); - } - } -} - -function createLon() { - for (var lat = -80; lat <= 80; lat += 10) { - const array = []; - for (var lon = -180; lon <= 180; lon += segLen) { - array.push(lon); - array.push(lat); - } - polylines.add({ - positions: Cesium.Cartesian3.fromDegreesArray(array), - width: 1, - material: gridMaterial - }); - } -} - -function createLonFine() { - for (var lat = -80; lat <= 80; lat += 1) { - if (lat % 10 != 0) { - const array = []; - for (var lon = -180; lon <= 180; lon += segLen) { - array.push(lon); - array.push(lat); - } - polylinesFine.add({ - positions: Cesium.Cartesian3.fromDegreesArray(array), - width: 1, - material: gridMaterial - }); - } - } -} - -function createLabels() { - var latField = 'B'.charCodeAt(0); - for (var lat = -80; lat <= 80; lat += 10) { - var lonField = 'A'.charCodeAt(0); - for (var lon = -180; lon < 180; lon += 20) { - labels.add({ - position: Cesium.Cartesian3.fromDegrees(lon + 0.5, lat + 0.5, 0.0), - text: String.fromCharCode(lonField) + String.fromCharCode(latField), - fillColor: gridLabelColor, - font: '20px sans-serif' - }); - lonField++; - } - latField++; - } -} - -function createLabelsFine() { - var latField = 'B'.charCodeAt(0); - for (var lat = -80; lat <= 80; lat += 1) { - var latSq = '0'.charCodeAt(0) + mod(lat, 10); - var lonField = 'A'.charCodeAt(0); - for (var lon = -180; lon < 180; lon += 2) { - var lonSq = '0'.charCodeAt(0) + mod(lon, 20) / 2; - labelsFine.add({ - position: Cesium.Cartesian3.fromDegrees(lon + 0.05, lat + 0.05, 0.0), - text: String.fromCharCode(lonField) + String.fromCharCode(latField) + String.fromCharCode(lonSq) + String.fromCharCode(latSq), - fillColor: gridLabelColor, - font: '20px sans-serif' - }); - if (mod(lon, 20) == 18) { - lonField++; - } - } - if (mod(lat, 10) == 9) { - latField++; - } - } -} -function mod(n, m) { - return ((n % m) + m) % m; -} - -function showGridByDistance() { - - var cameraHeight = viewer.scene.ellipsoid.cartesianToCartographic(viewer.scene.camera.position).height; - - const showFine = cameraHeight < 1500000; - - polylinesFine.show = showFine; - labels.show = !showFine; - labelsFine.show = showFine; -} - -function createGrid(viewer) { - - createLatFine(); - createLat(); - createLonFine(); - createLon(); - polylinesFine.show = false; - viewer.scene.primitives.add(polylines); - viewer.scene.primitives.add(polylinesFine); - - createLabels(); - createLabelsFine(); - labelsFine.show = false; - viewer.scene.primitives.add(labels); - viewer.scene.primitives.add(labelsFine); -} - -function showGrid(show) { - if (show) { - if (polylines.length == 0) { - createGrid(viewer); - } - polylines.show = true; - viewer.clock.onTick.addEventListener(showGridByDistance); - } else { - viewer.clock.onTick.removeEventListener(showGridByDistance); - polylines.show = false; - polylinesFine.show = false; - labels.show = false; - labelsFine.show = false; - } -} +// Maidenhead grid for Cesium + +const polylines = new Cesium.PolylineCollection(); +const polylinesFine = new Cesium.PolylineCollection(); + +const labels = new Cesium.LabelCollection(); +const labelsFine = new Cesium.LabelCollection(); + +const segLen = 2; + +const gridMaterial = Cesium.Material.fromType('Color'); +gridMaterial.uniforms.color = new Cesium.Color(0.6, 0.6, 0.6, 1.0); +const gridLabelColor = new Cesium.Color(1, 1, 1, 1.0); + +function createLat() { + for (var lon = -180; lon < 180; lon += 20) { + const array = []; + for (var lat = -90; lat <= 90; lat += segLen) { + array.push(lon); + array.push(lat); + } + polylines.add({ + positions: Cesium.Cartesian3.fromDegreesArray(array), + width: 1, + material: gridMaterial + }); + + } +} + +function createLatFine() { + for (var lon = -180; lon < 180; lon += 2) { + if (lon % 20 != 0) { + const array = []; + for (var lat = -90; lat <= 90; lat += segLen) { + array.push(lon); + array.push(lat); + } + polylinesFine.add({ + positions: Cesium.Cartesian3.fromDegreesArray(array), + width: 1, + material: gridMaterial + }); + } + } +} + +function createLon() { + for (var lat = -80; lat <= 80; lat += 10) { + const array = []; + for (var lon = -180; lon <= 180; lon += segLen) { + array.push(lon); + array.push(lat); + } + polylines.add({ + positions: Cesium.Cartesian3.fromDegreesArray(array), + width: 1, + material: gridMaterial + }); + } +} + +function createLonFine() { + for (var lat = -80; lat <= 80; lat += 1) { + if (lat % 10 != 0) { + const array = []; + for (var lon = -180; lon <= 180; lon += segLen) { + array.push(lon); + array.push(lat); + } + polylinesFine.add({ + positions: Cesium.Cartesian3.fromDegreesArray(array), + width: 1, + material: gridMaterial + }); + } + } +} + +function createLabels() { + var latField = 'B'.charCodeAt(0); + for (var lat = -80; lat <= 80; lat += 10) { + var lonField = 'A'.charCodeAt(0); + for (var lon = -180; lon < 180; lon += 20) { + labels.add({ + position: Cesium.Cartesian3.fromDegrees(lon + 0.5, lat + 0.5, 0.0), + text: String.fromCharCode(lonField) + String.fromCharCode(latField), + fillColor: gridLabelColor, + font: '20px sans-serif' + }); + lonField++; + } + latField++; + } +} + +function createLabelsFine() { + var latField = 'B'.charCodeAt(0); + for (var lat = -80; lat <= 80; lat += 1) { + var latSq = '0'.charCodeAt(0) + mod(lat, 10); + var lonField = 'A'.charCodeAt(0); + for (var lon = -180; lon < 180; lon += 2) { + var lonSq = '0'.charCodeAt(0) + mod(lon, 20) / 2; + labelsFine.add({ + position: Cesium.Cartesian3.fromDegrees(lon + 0.05, lat + 0.05, 0.0), + text: String.fromCharCode(lonField) + String.fromCharCode(latField) + String.fromCharCode(lonSq) + String.fromCharCode(latSq), + fillColor: gridLabelColor, + font: '20px sans-serif' + }); + if (mod(lon, 20) == 18) { + lonField++; + } + } + if (mod(lat, 10) == 9) { + latField++; + } + } +} +function mod(n, m) { + return ((n % m) + m) % m; +} + +function showGridByDistance() { + + var cameraHeight = viewer.scene.ellipsoid.cartesianToCartographic(viewer.scene.camera.position).height; + + const showFine = cameraHeight < 1500000; + + polylinesFine.show = showFine; + labels.show = !showFine; + labelsFine.show = showFine; +} + +function createGrid(viewer) { + + createLatFine(); + createLat(); + createLonFine(); + createLon(); + polylinesFine.show = false; + viewer.scene.primitives.add(polylines); + viewer.scene.primitives.add(polylinesFine); + + createLabels(); + createLabelsFine(); + labelsFine.show = false; + viewer.scene.primitives.add(labels); + viewer.scene.primitives.add(labelsFine); +} + +function showGrid(show) { + if (show) { + if (polylines.length == 0) { + createGrid(viewer); + } + polylines.show = true; + viewer.clock.onTick.addEventListener(showGridByDistance); + } else { + viewer.clock.onTick.removeEventListener(showGridByDistance); + polylines.show = false; + polylinesFine.show = false; + labels.show = false; + labelsFine.show = false; + } +} diff --git a/plugins/feature/map/map/map3d.html b/plugins/feature/map/map/map3d.html index da0cda347..79d7df997 100644 --- a/plugins/feature/map/map/map3d.html +++ b/plugins/feature/map/map/map3d.html @@ -1,1348 +1,1348 @@ - - - - - - - - - -
- - - - - - - - - + + + + + + + + + +
+ + + + + + + + + diff --git a/plugins/feature/mcpserver/bridge/CMakeLists.txt b/plugins/feature/mcpserver/bridge/CMakeLists.txt index 8fa612378..7d24bdd1b 100644 --- a/plugins/feature/mcpserver/bridge/CMakeLists.txt +++ b/plugins/feature/mcpserver/bridge/CMakeLists.txt @@ -1,129 +1,129 @@ -project(sdrangelmcpbridge) - -# A standalone executable, deliberately free of Qt and of the rest of SDRangel: it is -# shipped inside a Claude Desktop extension bundle, where nothing else is on the library -# path, so it must run with only the C++ runtime. - -set(mcpbridge_SOURCES - main.cpp - httpclient.cpp - jsonscan.cpp - ssereader.cpp -) - -set(mcpbridge_HEADERS - httpclient.h - jsonscan.h - ssereader.h -) - -add_executable(sdrangel-mcp-bridge ${mcpbridge_SOURCES} ${mcpbridge_HEADERS}) - -# There is no Qt here, so the project wide automatic moc, uic and rcc have nothing to do -set_target_properties(sdrangel-mcp-bridge PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF) - -target_compile_definitions(sdrangel-mcp-bridge PRIVATE - SDRANGEL_MCP_BRIDGE_VERSION="${CPACK_PACKAGE_VERSION}" -) - -find_package(Threads REQUIRED) -target_link_libraries(sdrangel-mcp-bridge Threads::Threads) - -if(WIN32) - target_link_libraries(sdrangel-mcp-bridge ws2_32) - # Static runtime, so the bundle does not depend on the redistributable being present - set_property(TARGET sdrangel-mcp-bridge PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") -endif() - -install(TARGETS sdrangel-mcp-bridge DESTINATION ${INSTALL_BIN_DIR}) - -# A .mcpb is a zip with manifest.json at its root, so CMake can build one on its own. The -# mcpb CLI only adds validation and signing, and requiring npm to build SDRangel would be a -# poor trade for that. -if(BUILD_MCP_BUNDLE) - if(WIN32) - set(MCPBRIDGE_BUNDLE_PLATFORM "win32") - elseif(APPLE) - set(MCPBRIDGE_BUNDLE_PLATFORM "darwin") - else() - set(MCPBRIDGE_BUNDLE_PLATFORM "linux") - endif() - - # A bundle claiming a version that is already installed is not unpacked again, which - # silently leaves the previous one in place, so every build needs a version of its own. - # A release is exactly its tag; anything else carries the git describe suffix and the time - # it was configured, since rebuilds between commits would otherwise all claim the same - # version. Both are valid semantic version prereleases, and the added identifier makes a - # rebuild sort above what it replaces rather than below it - if(sdrangel_VERSION_SUFFIX STREQUAL "") - set(MCPBRIDGE_BUNDLE_VERSION "${CPACK_PACKAGE_VERSION}") - else() - string(TIMESTAMP MCPBRIDGE_BUILD_TIME "%Y%m%dT%H%M%S" UTC) - set(MCPBRIDGE_BUNDLE_VERSION "${CPACK_PACKAGE_VERSION}.${MCPBRIDGE_BUILD_TIME}") - endif() - - # The tool list the bundle carries comes from the server itself, built here by a host tool - # that constructs the real registry. Sources are named by path rather than reusing the - # plugin target, which is a Qt plugin module and cannot be linked into an executable - set(MCPTOOLSDUMP_DIR "${CMAKE_SOURCE_DIR}/plugins/feature/mcpserver") - - add_executable(sdrangel-mcp-tools-dump - "${MCPTOOLSDUMP_DIR}/toolsdump.cpp" - "${MCPTOOLSDUMP_DIR}/mcptools.cpp" - "${MCPTOOLSDUMP_DIR}/mcpdocs.cpp" - "${MCPTOOLSDUMP_DIR}/mcpdatafeed.cpp" - "${MCPTOOLSDUMP_DIR}/mcpcapture.cpp" - "${MCPTOOLSDUMP_DIR}/mcpaudiocapture.cpp" - "${MCPTOOLSDUMP_DIR}/mcpstreams.cpp" - ) - - target_include_directories(sdrangel-mcp-tools-dump PRIVATE - "${MCPTOOLSDUMP_DIR}" - "${CMAKE_SOURCE_DIR}/sdrbase" - "${CMAKE_SOURCE_DIR}/exports" - "${CMAKE_SOURCE_DIR}/httpserver" - "${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client" - ) - - target_link_libraries(sdrangel-mcp-tools-dump PRIVATE Qt::Core sdrbase httpserver) - - set(MCPBRIDGE_BUNDLE_DIR "${CMAKE_CURRENT_BINARY_DIR}/bundle") - # Alongside the built binaries, which is bin/ on Windows and the build directory itself - # elsewhere. That is also where the running application looks for it in a build tree - set(MCPBRIDGE_BUNDLE_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/sdrangel-${MCPBRIDGE_BUNDLE_VERSION}-${MCPBRIDGE_BUNDLE_PLATFORM}.mcpb") - - configure_file(manifest.json.in "${MCPBRIDGE_BUNDLE_DIR}/manifest.json" @ONLY) - - # Part of ALL, so that turning the option on is enough: the packaging step installs the - # bundle if it is there, and silently leaves it out if it is not, which would be a hard - # thing to notice in a finished installer - add_custom_target(mcpbundle ALL - COMMAND ${CMAKE_COMMAND} -E make_directory "${MCPBRIDGE_BUNDLE_DIR}/server" - COMMAND ${CMAKE_COMMAND} -E copy $ "${MCPBRIDGE_BUNDLE_DIR}/server/" - COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_SOURCE_DIR}/cmake/cpack/sdrangel_icon.png" "${MCPBRIDGE_BUNDLE_DIR}/icon.png" - # The tool list, straight from the server's own registry, beside the bridge that serves - # it when SDRangel is not up - COMMAND $ "${MCPBRIDGE_BUNDLE_DIR}/server/tools.json" - COMMAND ${CMAKE_COMMAND} -E rm -f "${MCPBRIDGE_BUNDLE_FILE}" - # Relative paths and a working directory, so that manifest.json lands at the root of - # the archive, which is where the installer looks for it - COMMAND ${CMAKE_COMMAND} -E tar cf "${MCPBRIDGE_BUNDLE_FILE}" --format=zip -- manifest.json icon.png server - WORKING_DIRECTORY "${MCPBRIDGE_BUNDLE_DIR}" - DEPENDS sdrangel-mcp-bridge sdrangel-mcp-tools-dump "${MCPBRIDGE_BUNDLE_DIR}/manifest.json" - COMMENT "Packaging ${MCPBRIDGE_BUNDLE_FILE}" - VERBATIM - ) - - # The installer needs the name, and cmake/cpack is configured after this directory - set(MCPBRIDGE_BUNDLE_NAME "sdrangel-${MCPBRIDGE_BUNDLE_VERSION}-${MCPBRIDGE_BUNDLE_PLATFORM}.mcpb" - CACHE INTERNAL "File name of the Claude Desktop extension bundle") - - # Not OPTIONAL: mcpbundle is part of ALL, so the bundle is always there by the time the - # install rules run. Should packaging ever break, failing here is far better than an - # installer that quietly ships without the extension - install(FILES "${MCPBRIDGE_BUNDLE_FILE}" DESTINATION ${INSTALL_BIN_DIR}) - - # Beside the installed bridge as well, for anyone pointing a client straight at it rather - # than installing the extension - install(FILES "${MCPBRIDGE_BUNDLE_DIR}/server/tools.json" DESTINATION ${INSTALL_BIN_DIR}) -endif() +project(sdrangelmcpbridge) + +# A standalone executable, deliberately free of Qt and of the rest of SDRangel: it is +# shipped inside a Claude Desktop extension bundle, where nothing else is on the library +# path, so it must run with only the C++ runtime. + +set(mcpbridge_SOURCES + main.cpp + httpclient.cpp + jsonscan.cpp + ssereader.cpp +) + +set(mcpbridge_HEADERS + httpclient.h + jsonscan.h + ssereader.h +) + +add_executable(sdrangel-mcp-bridge ${mcpbridge_SOURCES} ${mcpbridge_HEADERS}) + +# There is no Qt here, so the project wide automatic moc, uic and rcc have nothing to do +set_target_properties(sdrangel-mcp-bridge PROPERTIES AUTOMOC OFF AUTOUIC OFF AUTORCC OFF) + +target_compile_definitions(sdrangel-mcp-bridge PRIVATE + SDRANGEL_MCP_BRIDGE_VERSION="${CPACK_PACKAGE_VERSION}" +) + +find_package(Threads REQUIRED) +target_link_libraries(sdrangel-mcp-bridge Threads::Threads) + +if(WIN32) + target_link_libraries(sdrangel-mcp-bridge ws2_32) + # Static runtime, so the bundle does not depend on the redistributable being present + set_property(TARGET sdrangel-mcp-bridge PROPERTY MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +endif() + +install(TARGETS sdrangel-mcp-bridge DESTINATION ${INSTALL_BIN_DIR}) + +# A .mcpb is a zip with manifest.json at its root, so CMake can build one on its own. The +# mcpb CLI only adds validation and signing, and requiring npm to build SDRangel would be a +# poor trade for that. +if(BUILD_MCP_BUNDLE) + if(WIN32) + set(MCPBRIDGE_BUNDLE_PLATFORM "win32") + elseif(APPLE) + set(MCPBRIDGE_BUNDLE_PLATFORM "darwin") + else() + set(MCPBRIDGE_BUNDLE_PLATFORM "linux") + endif() + + # A bundle claiming a version that is already installed is not unpacked again, which + # silently leaves the previous one in place, so every build needs a version of its own. + # A release is exactly its tag; anything else carries the git describe suffix and the time + # it was configured, since rebuilds between commits would otherwise all claim the same + # version. Both are valid semantic version prereleases, and the added identifier makes a + # rebuild sort above what it replaces rather than below it + if(sdrangel_VERSION_SUFFIX STREQUAL "") + set(MCPBRIDGE_BUNDLE_VERSION "${CPACK_PACKAGE_VERSION}") + else() + string(TIMESTAMP MCPBRIDGE_BUILD_TIME "%Y%m%dT%H%M%S" UTC) + set(MCPBRIDGE_BUNDLE_VERSION "${CPACK_PACKAGE_VERSION}.${MCPBRIDGE_BUILD_TIME}") + endif() + + # The tool list the bundle carries comes from the server itself, built here by a host tool + # that constructs the real registry. Sources are named by path rather than reusing the + # plugin target, which is a Qt plugin module and cannot be linked into an executable + set(MCPTOOLSDUMP_DIR "${CMAKE_SOURCE_DIR}/plugins/feature/mcpserver") + + add_executable(sdrangel-mcp-tools-dump + "${MCPTOOLSDUMP_DIR}/toolsdump.cpp" + "${MCPTOOLSDUMP_DIR}/mcptools.cpp" + "${MCPTOOLSDUMP_DIR}/mcpdocs.cpp" + "${MCPTOOLSDUMP_DIR}/mcpdatafeed.cpp" + "${MCPTOOLSDUMP_DIR}/mcpcapture.cpp" + "${MCPTOOLSDUMP_DIR}/mcpaudiocapture.cpp" + "${MCPTOOLSDUMP_DIR}/mcpstreams.cpp" + ) + + target_include_directories(sdrangel-mcp-tools-dump PRIVATE + "${MCPTOOLSDUMP_DIR}" + "${CMAKE_SOURCE_DIR}/sdrbase" + "${CMAKE_SOURCE_DIR}/exports" + "${CMAKE_SOURCE_DIR}/httpserver" + "${CMAKE_SOURCE_DIR}/swagger/sdrangel/code/qt5/client" + ) + + target_link_libraries(sdrangel-mcp-tools-dump PRIVATE Qt::Core sdrbase httpserver) + + set(MCPBRIDGE_BUNDLE_DIR "${CMAKE_CURRENT_BINARY_DIR}/bundle") + # Alongside the built binaries, which is bin/ on Windows and the build directory itself + # elsewhere. That is also where the running application looks for it in a build tree + set(MCPBRIDGE_BUNDLE_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/sdrangel-${MCPBRIDGE_BUNDLE_VERSION}-${MCPBRIDGE_BUNDLE_PLATFORM}.mcpb") + + configure_file(manifest.json.in "${MCPBRIDGE_BUNDLE_DIR}/manifest.json" @ONLY) + + # Part of ALL, so that turning the option on is enough: the packaging step installs the + # bundle if it is there, and silently leaves it out if it is not, which would be a hard + # thing to notice in a finished installer + add_custom_target(mcpbundle ALL + COMMAND ${CMAKE_COMMAND} -E make_directory "${MCPBRIDGE_BUNDLE_DIR}/server" + COMMAND ${CMAKE_COMMAND} -E copy $ "${MCPBRIDGE_BUNDLE_DIR}/server/" + COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_SOURCE_DIR}/cmake/cpack/sdrangel_icon.png" "${MCPBRIDGE_BUNDLE_DIR}/icon.png" + # The tool list, straight from the server's own registry, beside the bridge that serves + # it when SDRangel is not up + COMMAND $ "${MCPBRIDGE_BUNDLE_DIR}/server/tools.json" + COMMAND ${CMAKE_COMMAND} -E rm -f "${MCPBRIDGE_BUNDLE_FILE}" + # Relative paths and a working directory, so that manifest.json lands at the root of + # the archive, which is where the installer looks for it + COMMAND ${CMAKE_COMMAND} -E tar cf "${MCPBRIDGE_BUNDLE_FILE}" --format=zip -- manifest.json icon.png server + WORKING_DIRECTORY "${MCPBRIDGE_BUNDLE_DIR}" + DEPENDS sdrangel-mcp-bridge sdrangel-mcp-tools-dump "${MCPBRIDGE_BUNDLE_DIR}/manifest.json" + COMMENT "Packaging ${MCPBRIDGE_BUNDLE_FILE}" + VERBATIM + ) + + # The installer needs the name, and cmake/cpack is configured after this directory + set(MCPBRIDGE_BUNDLE_NAME "sdrangel-${MCPBRIDGE_BUNDLE_VERSION}-${MCPBRIDGE_BUNDLE_PLATFORM}.mcpb" + CACHE INTERNAL "File name of the Claude Desktop extension bundle") + + # Not OPTIONAL: mcpbundle is part of ALL, so the bundle is always there by the time the + # install rules run. Should packaging ever break, failing here is far better than an + # installer that quietly ships without the extension + install(FILES "${MCPBRIDGE_BUNDLE_FILE}" DESTINATION ${INSTALL_BIN_DIR}) + + # Beside the installed bridge as well, for anyone pointing a client straight at it rather + # than installing the extension + install(FILES "${MCPBRIDGE_BUNDLE_DIR}/server/tools.json" DESTINATION ${INSTALL_BIN_DIR}) +endif() diff --git a/plugins/feature/mcpserver/bridge/httpclient.cpp b/plugins/feature/mcpserver/bridge/httpclient.cpp index 827c32c21..79372dca6 100644 --- a/plugins/feature/mcpserver/bridge/httpclient.cpp +++ b/plugins/feature/mcpserver/bridge/httpclient.cpp @@ -1,494 +1,494 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#include "httpclient.h" - -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#include -#else -#include -#include -#include -#include -#include -#include -#include -#include -#endif - -namespace -{ - -std::string lowered(const std::string& text) -{ - std::string result(text); - - std::transform(result.begin(), result.end(), result.begin(), - [](unsigned char c) { return static_cast(std::tolower(c)); }); - return result; -} - -std::string trimmed(const std::string& text) -{ - size_t begin = text.find_first_not_of(" \t\r\n"); - - if (begin == std::string::npos) { - return std::string(); - } - - size_t end = text.find_last_not_of(" \t\r\n"); - return text.substr(begin, end - begin + 1); -} - -std::string socketError() -{ -#ifdef _WIN32 - int code = WSAGetLastError(); - - switch (code) - { - case WSAECONNREFUSED: return "connection refused"; - case WSAETIMEDOUT: return "timed out"; - case WSAECONNRESET: return "connection reset"; - case WSAEHOSTUNREACH: return "host unreachable"; - default: return "socket error " + std::to_string(code); - } -#else - // A receive timeout set with SO_RCVTIMEO comes back as EAGAIN, whose text says nothing - // about time - if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { - return "timed out"; - } - - return std::strerror(errno); -#endif -} - -} // namespace - -HttpClient::Socket HttpClient::invalidSocket() -{ -#ifdef _WIN32 - return INVALID_SOCKET; -#else - return -1; -#endif -} - -std::string HttpClient::Head::header(const std::string& name) const -{ - std::string wanted = lowered(name); - - for (const auto& header : m_headers) - { - if (lowered(header.first) == wanted) { - return header.second; - } - } - - return std::string(); -} - -bool HttpClient::startup(std::string& error) -{ -#ifdef _WIN32 - WSADATA data; - int result = WSAStartup(MAKEWORD(2, 2), &data); - - if (result != 0) - { - error = "WSAStartup failed with " + std::to_string(result); - return false; - } -#else - (void) error; -#endif - return true; -} - -void HttpClient::cleanup() -{ -#ifdef _WIN32 - WSACleanup(); -#endif -} - -HttpClient::~HttpClient() -{ - close(); -} - -bool HttpClient::open(const std::string& host, int port, int timeoutMs, std::string& error) -{ - close(); - - addrinfo hints; - std::memset(&hints, 0, sizeof(hints)); - hints.ai_family = AF_UNSPEC; - hints.ai_socktype = SOCK_STREAM; - hints.ai_protocol = IPPROTO_TCP; - - addrinfo *addresses = nullptr; - std::string service = std::to_string(port); - - if (getaddrinfo(host.c_str(), service.c_str(), &hints, &addresses) != 0) - { - error = "cannot resolve " + host; - return false; - } - - std::string reason; - - for (addrinfo *address = addresses; address != nullptr; address = address->ai_next) - { - Socket handle = socket(address->ai_family, address->ai_socktype, address->ai_protocol); - - if (handle == invalidSocket()) { - continue; - } - - if (connect(handle, address->ai_addr, static_cast(address->ai_addrlen)) == 0) - { - m_socket = handle; - break; - } - - // Read before closing the socket and freeing the addresses, either of which - // replaces the last error with one of its own - reason = socketError(); - -#ifdef _WIN32 - closesocket(handle); -#else - ::close(handle); -#endif - } - - freeaddrinfo(addresses); - - if (m_socket == invalidSocket()) - { - error = reason.empty() ? "no usable address" : reason; - return false; - } - - // Nagle would hold small JSON-RPC messages back waiting for more to send - int flag = 1; - setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flag), sizeof(flag)); - -#ifdef SO_NOSIGPIPE - // A send on a connection the server has closed must fail, not raise SIGPIPE and end the - // process. Linux has no such option and uses MSG_NOSIGNAL on the send instead - setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(flag)); -#endif - - if (timeoutMs > 0) - { -#ifdef _WIN32 - DWORD timeout = static_cast(timeoutMs); - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); - setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); -#else - timeval timeout; - timeout.tv_sec = timeoutMs / 1000; - timeout.tv_usec = (timeoutMs % 1000) * 1000; - setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); - setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); -#endif - } - - m_buffer.clear(); - m_eof = false; - return true; -} - -void HttpClient::interrupt() -{ - if (m_socket != invalidSocket()) - { -#ifdef _WIN32 - shutdown(m_socket, SD_BOTH); -#else - shutdown(m_socket, SHUT_RDWR); -#endif - } -} - -void HttpClient::close() -{ - if (m_socket != invalidSocket()) - { -#ifdef _WIN32 - closesocket(m_socket); -#else - ::close(m_socket); -#endif - m_socket = invalidSocket(); - } - - m_buffer.clear(); - m_eof = false; -} - -bool HttpClient::sendAll(const std::string& data, std::string& error) -{ - size_t sent = 0; - - while (sent < data.size()) - { -#ifdef MSG_NOSIGNAL - const int flags = MSG_NOSIGNAL; -#else - const int flags = 0; -#endif - int count = ::send(m_socket, data.data() + sent, static_cast(data.size() - sent), flags); - - if (count <= 0) - { - error = "send failed (" + socketError() + ")"; - return false; - } - - sent += static_cast(count); - } - - return true; -} - -bool HttpClient::send(const std::string& method, const std::string& path, const std::vector
& headers, - const std::string& body, std::string& error) -{ - std::string request = method + " " + path + " HTTP/1.1\r\n"; - - for (const auto& header : headers) { - request += header.first + ": " + header.second + "\r\n"; - } - - // One request per connection keeps the response framing simple: no pipelining to unpick, - // and a body with neither Content-Length nor chunking ends at the close - request += "Connection: close\r\n"; - request += "Content-Length: " + std::to_string(body.size()) + "\r\n"; - request += "\r\n"; - request += body; - - return sendAll(request, error); -} - -bool HttpClient::fill(std::string& error) -{ - char block[8192]; - int count = recv(m_socket, block, sizeof(block), 0); - - if (count == 0) - { - m_eof = true; - return false; - } - - if (count < 0) - { - error = "read failed (" + socketError() + ")"; - m_eof = true; - return false; - } - - m_buffer.append(block, static_cast(count)); - return true; -} - -bool HttpClient::readLine(std::string& line, std::string& error) -{ - for (;;) - { - size_t end = m_buffer.find("\r\n"); - - if (end != std::string::npos) - { - line = m_buffer.substr(0, end); - m_buffer.erase(0, end + 2); - return true; - } - - if (!fill(error)) - { - if (error.empty()) { - error = "connection closed while reading a line"; - } - - return false; - } - } -} - -bool HttpClient::readExactly(size_t count, std::string& out, std::string& error) -{ - while (m_buffer.size() < count) - { - if (!fill(error)) - { - if (error.empty()) { - error = "connection closed with " + std::to_string(count - m_buffer.size()) + " bytes still to read"; - } - - return false; - } - } - - out = m_buffer.substr(0, count); - m_buffer.erase(0, count); - return true; -} - -bool HttpClient::readHead(Head& head, std::string& error) -{ - std::string line; - - if (!readLine(line, error)) { - return false; - } - - // HTTP/1.1 200 OK - size_t firstSpace = line.find(' '); - - if ((firstSpace == std::string::npos) || (line.compare(0, 5, "HTTP/") != 0)) - { - error = "not an HTTP response: " + line; - return false; - } - - size_t secondSpace = line.find(' ', firstSpace + 1); - head.m_status = std::atoi(line.substr(firstSpace + 1).c_str()); - head.m_reason = (secondSpace == std::string::npos) ? std::string() : trimmed(line.substr(secondSpace + 1)); - - for (;;) - { - if (!readLine(line, error)) { - return false; - } - - if (line.empty()) { - break; - } - - size_t colon = line.find(':'); - - if (colon == std::string::npos) { - continue; - } - - head.m_headers.emplace_back(trimmed(line.substr(0, colon)), trimmed(line.substr(colon + 1))); - } - - std::string length = head.header("Content-Length"); - - if (!length.empty()) { - head.m_contentLength = std::atoll(length.c_str()); - } - - head.m_chunked = (lowered(head.header("Transfer-Encoding")).find("chunked") != std::string::npos); - return true; -} - -bool HttpClient::readChunk(std::string& chunk, std::string& error) -{ - std::string line; - - if (!readLine(line, error)) { - return false; - } - - // The size line may carry chunk extensions after a semicolon - size_t semicolon = line.find(';'); - std::string sizeText = trimmed((semicolon == std::string::npos) ? line : line.substr(0, semicolon)); - size_t size = static_cast(std::strtoul(sizeText.c_str(), nullptr, 16)); - - if (size == 0) - { - // Trailers, then the final blank line. The body is complete, which is not an error - for (;;) - { - std::string trailer; - - if (!readLine(trailer, error) || trailer.empty()) { - break; - } - } - - error.clear(); - return false; - } - - if (!readExactly(size, chunk, error)) { - return false; - } - - std::string terminator; - return readLine(terminator, error); -} - -bool HttpClient::readSome(std::string& data, std::string& error) -{ - if (m_buffer.empty() && !fill(error)) { - return false; - } - - data.clear(); - data.swap(m_buffer); - return true; -} - -bool HttpClient::readBody(const Head& head, std::string& body, std::string& error) -{ - body.clear(); - - if (head.m_chunked) - { - std::string chunk; - - while (readChunk(chunk, error)) { - body += chunk; - } - - return error.empty(); - } - - if (head.m_contentLength >= 0) - { - if (head.m_contentLength == 0) { - return true; - } - - return readExactly(static_cast(head.m_contentLength), body, error); - } - - // Neither framing: the body runs to the close, which Connection: close guarantees - while (fill(error)) { - // keep reading - } - - body.swap(m_buffer); - m_buffer.clear(); - return error.empty(); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "httpclient.h" + +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +namespace +{ + +std::string lowered(const std::string& text) +{ + std::string result(text); + + std::transform(result.begin(), result.end(), result.begin(), + [](unsigned char c) { return static_cast(std::tolower(c)); }); + return result; +} + +std::string trimmed(const std::string& text) +{ + size_t begin = text.find_first_not_of(" \t\r\n"); + + if (begin == std::string::npos) { + return std::string(); + } + + size_t end = text.find_last_not_of(" \t\r\n"); + return text.substr(begin, end - begin + 1); +} + +std::string socketError() +{ +#ifdef _WIN32 + int code = WSAGetLastError(); + + switch (code) + { + case WSAECONNREFUSED: return "connection refused"; + case WSAETIMEDOUT: return "timed out"; + case WSAECONNRESET: return "connection reset"; + case WSAEHOSTUNREACH: return "host unreachable"; + default: return "socket error " + std::to_string(code); + } +#else + // A receive timeout set with SO_RCVTIMEO comes back as EAGAIN, whose text says nothing + // about time + if ((errno == EAGAIN) || (errno == EWOULDBLOCK)) { + return "timed out"; + } + + return std::strerror(errno); +#endif +} + +} // namespace + +HttpClient::Socket HttpClient::invalidSocket() +{ +#ifdef _WIN32 + return INVALID_SOCKET; +#else + return -1; +#endif +} + +std::string HttpClient::Head::header(const std::string& name) const +{ + std::string wanted = lowered(name); + + for (const auto& header : m_headers) + { + if (lowered(header.first) == wanted) { + return header.second; + } + } + + return std::string(); +} + +bool HttpClient::startup(std::string& error) +{ +#ifdef _WIN32 + WSADATA data; + int result = WSAStartup(MAKEWORD(2, 2), &data); + + if (result != 0) + { + error = "WSAStartup failed with " + std::to_string(result); + return false; + } +#else + (void) error; +#endif + return true; +} + +void HttpClient::cleanup() +{ +#ifdef _WIN32 + WSACleanup(); +#endif +} + +HttpClient::~HttpClient() +{ + close(); +} + +bool HttpClient::open(const std::string& host, int port, int timeoutMs, std::string& error) +{ + close(); + + addrinfo hints; + std::memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_protocol = IPPROTO_TCP; + + addrinfo *addresses = nullptr; + std::string service = std::to_string(port); + + if (getaddrinfo(host.c_str(), service.c_str(), &hints, &addresses) != 0) + { + error = "cannot resolve " + host; + return false; + } + + std::string reason; + + for (addrinfo *address = addresses; address != nullptr; address = address->ai_next) + { + Socket handle = socket(address->ai_family, address->ai_socktype, address->ai_protocol); + + if (handle == invalidSocket()) { + continue; + } + + if (connect(handle, address->ai_addr, static_cast(address->ai_addrlen)) == 0) + { + m_socket = handle; + break; + } + + // Read before closing the socket and freeing the addresses, either of which + // replaces the last error with one of its own + reason = socketError(); + +#ifdef _WIN32 + closesocket(handle); +#else + ::close(handle); +#endif + } + + freeaddrinfo(addresses); + + if (m_socket == invalidSocket()) + { + error = reason.empty() ? "no usable address" : reason; + return false; + } + + // Nagle would hold small JSON-RPC messages back waiting for more to send + int flag = 1; + setsockopt(m_socket, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flag), sizeof(flag)); + +#ifdef SO_NOSIGPIPE + // A send on a connection the server has closed must fail, not raise SIGPIPE and end the + // process. Linux has no such option and uses MSG_NOSIGNAL on the send instead + setsockopt(m_socket, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(flag)); +#endif + + if (timeoutMs > 0) + { +#ifdef _WIN32 + DWORD timeout = static_cast(timeoutMs); + setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); + setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); +#else + timeval timeout; + timeout.tv_sec = timeoutMs / 1000; + timeout.tv_usec = (timeoutMs % 1000) * 1000; + setsockopt(m_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); + setsockopt(m_socket, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)); +#endif + } + + m_buffer.clear(); + m_eof = false; + return true; +} + +void HttpClient::interrupt() +{ + if (m_socket != invalidSocket()) + { +#ifdef _WIN32 + shutdown(m_socket, SD_BOTH); +#else + shutdown(m_socket, SHUT_RDWR); +#endif + } +} + +void HttpClient::close() +{ + if (m_socket != invalidSocket()) + { +#ifdef _WIN32 + closesocket(m_socket); +#else + ::close(m_socket); +#endif + m_socket = invalidSocket(); + } + + m_buffer.clear(); + m_eof = false; +} + +bool HttpClient::sendAll(const std::string& data, std::string& error) +{ + size_t sent = 0; + + while (sent < data.size()) + { +#ifdef MSG_NOSIGNAL + const int flags = MSG_NOSIGNAL; +#else + const int flags = 0; +#endif + int count = ::send(m_socket, data.data() + sent, static_cast(data.size() - sent), flags); + + if (count <= 0) + { + error = "send failed (" + socketError() + ")"; + return false; + } + + sent += static_cast(count); + } + + return true; +} + +bool HttpClient::send(const std::string& method, const std::string& path, const std::vector
& headers, + const std::string& body, std::string& error) +{ + std::string request = method + " " + path + " HTTP/1.1\r\n"; + + for (const auto& header : headers) { + request += header.first + ": " + header.second + "\r\n"; + } + + // One request per connection keeps the response framing simple: no pipelining to unpick, + // and a body with neither Content-Length nor chunking ends at the close + request += "Connection: close\r\n"; + request += "Content-Length: " + std::to_string(body.size()) + "\r\n"; + request += "\r\n"; + request += body; + + return sendAll(request, error); +} + +bool HttpClient::fill(std::string& error) +{ + char block[8192]; + int count = recv(m_socket, block, sizeof(block), 0); + + if (count == 0) + { + m_eof = true; + return false; + } + + if (count < 0) + { + error = "read failed (" + socketError() + ")"; + m_eof = true; + return false; + } + + m_buffer.append(block, static_cast(count)); + return true; +} + +bool HttpClient::readLine(std::string& line, std::string& error) +{ + for (;;) + { + size_t end = m_buffer.find("\r\n"); + + if (end != std::string::npos) + { + line = m_buffer.substr(0, end); + m_buffer.erase(0, end + 2); + return true; + } + + if (!fill(error)) + { + if (error.empty()) { + error = "connection closed while reading a line"; + } + + return false; + } + } +} + +bool HttpClient::readExactly(size_t count, std::string& out, std::string& error) +{ + while (m_buffer.size() < count) + { + if (!fill(error)) + { + if (error.empty()) { + error = "connection closed with " + std::to_string(count - m_buffer.size()) + " bytes still to read"; + } + + return false; + } + } + + out = m_buffer.substr(0, count); + m_buffer.erase(0, count); + return true; +} + +bool HttpClient::readHead(Head& head, std::string& error) +{ + std::string line; + + if (!readLine(line, error)) { + return false; + } + + // HTTP/1.1 200 OK + size_t firstSpace = line.find(' '); + + if ((firstSpace == std::string::npos) || (line.compare(0, 5, "HTTP/") != 0)) + { + error = "not an HTTP response: " + line; + return false; + } + + size_t secondSpace = line.find(' ', firstSpace + 1); + head.m_status = std::atoi(line.substr(firstSpace + 1).c_str()); + head.m_reason = (secondSpace == std::string::npos) ? std::string() : trimmed(line.substr(secondSpace + 1)); + + for (;;) + { + if (!readLine(line, error)) { + return false; + } + + if (line.empty()) { + break; + } + + size_t colon = line.find(':'); + + if (colon == std::string::npos) { + continue; + } + + head.m_headers.emplace_back(trimmed(line.substr(0, colon)), trimmed(line.substr(colon + 1))); + } + + std::string length = head.header("Content-Length"); + + if (!length.empty()) { + head.m_contentLength = std::atoll(length.c_str()); + } + + head.m_chunked = (lowered(head.header("Transfer-Encoding")).find("chunked") != std::string::npos); + return true; +} + +bool HttpClient::readChunk(std::string& chunk, std::string& error) +{ + std::string line; + + if (!readLine(line, error)) { + return false; + } + + // The size line may carry chunk extensions after a semicolon + size_t semicolon = line.find(';'); + std::string sizeText = trimmed((semicolon == std::string::npos) ? line : line.substr(0, semicolon)); + size_t size = static_cast(std::strtoul(sizeText.c_str(), nullptr, 16)); + + if (size == 0) + { + // Trailers, then the final blank line. The body is complete, which is not an error + for (;;) + { + std::string trailer; + + if (!readLine(trailer, error) || trailer.empty()) { + break; + } + } + + error.clear(); + return false; + } + + if (!readExactly(size, chunk, error)) { + return false; + } + + std::string terminator; + return readLine(terminator, error); +} + +bool HttpClient::readSome(std::string& data, std::string& error) +{ + if (m_buffer.empty() && !fill(error)) { + return false; + } + + data.clear(); + data.swap(m_buffer); + return true; +} + +bool HttpClient::readBody(const Head& head, std::string& body, std::string& error) +{ + body.clear(); + + if (head.m_chunked) + { + std::string chunk; + + while (readChunk(chunk, error)) { + body += chunk; + } + + return error.empty(); + } + + if (head.m_contentLength >= 0) + { + if (head.m_contentLength == 0) { + return true; + } + + return readExactly(static_cast(head.m_contentLength), body, error); + } + + // Neither framing: the body runs to the close, which Connection: close guarantees + while (fill(error)) { + // keep reading + } + + body.swap(m_buffer); + m_buffer.clear(); + return error.empty(); +} diff --git a/plugins/feature/mcpserver/bridge/httpclient.h b/plugins/feature/mcpserver/bridge/httpclient.h index 38c6b6d76..f16a2c24b 100644 --- a/plugins/feature/mcpserver/bridge/httpclient.h +++ b/plugins/feature/mcpserver/bridge/httpclient.h @@ -1,101 +1,101 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#ifndef INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ -#define INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ - -#include -#include -#include - -//!< Just enough HTTP/1.1 to talk to SDRangel's MCP server: one request per connection, -//!< no TLS, no redirects, no keep alive. Bodies arrive either with a Content-Length or -//!< chunked, and a chunked body can be read incrementally so that the event stream can -//!< be followed as it arrives. -class HttpClient -{ -public: - using Header = std::pair; - - struct Head - { - int m_status = 0; - std::string m_reason; - std::vector
m_headers; - long long m_contentLength = -1; //!< -1 when there is no Content-Length - bool m_chunked = false; - - //!< Case insensitive lookup, empty when the header is absent - std::string header(const std::string& name) const; - }; - - HttpClient() = default; - ~HttpClient(); - - HttpClient(const HttpClient&) = delete; - HttpClient& operator=(const HttpClient&) = delete; - - static bool startup(std::string& error); //!< WSAStartup on Windows, nothing elsewhere - static void cleanup(); - - bool open(const std::string& host, int port, int timeoutMs, std::string& error); - void close(); - //!< Wakes a read blocked on this socket from another thread. Only the socket is touched: - //!< the buffer and the rest belong to the thread reading, which closes when its read - //!< returns. Closing from the other thread would not wake a read on Linux, and frees a - //!< descriptor number the reader still holds - void interrupt(); - bool isOpen() const { return m_socket != invalidSocket(); } - - //!< Sends the request and its body. An empty method body is fine. - bool send(const std::string& method, const std::string& path, const std::vector
& headers, - const std::string& body, std::string& error); - - bool readHead(Head& head, std::string& error); - - //!< Reads the whole body, however it is framed. Not for the event stream, which never ends. - bool readBody(const Head& head, std::string& body, std::string& error); - - //!< One piece of a chunked body, for following a stream. Returns false at the end of the - //!< body or on error, with error empty when the end was reached cleanly. - bool readChunk(std::string& chunk, std::string& error); - - //!< Whatever has arrived of a body that is delimited by the connection closing rather - //!< than chunked, which is how the event stream comes back. Same false at the end. - bool readSome(std::string& data, std::string& error); - -private: -#ifdef _WIN32 - using Socket = unsigned long long; //!< SOCKET, kept out of the header so windows.h is not needed here -#else - using Socket = int; -#endif - - static Socket invalidSocket(); - - bool fill(std::string& error); //!< One read into m_buffer - bool readLine(std::string& line, std::string& error); - bool readExactly(size_t count, std::string& out, std::string& error); - bool sendAll(const std::string& data, std::string& error); - - Socket m_socket = invalidSocket(); - std::string m_buffer; //!< Bytes read from the socket but not yet consumed - bool m_eof = false; -}; - -#endif // INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ +#define INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ + +#include +#include +#include + +//!< Just enough HTTP/1.1 to talk to SDRangel's MCP server: one request per connection, +//!< no TLS, no redirects, no keep alive. Bodies arrive either with a Content-Length or +//!< chunked, and a chunked body can be read incrementally so that the event stream can +//!< be followed as it arrives. +class HttpClient +{ +public: + using Header = std::pair; + + struct Head + { + int m_status = 0; + std::string m_reason; + std::vector
m_headers; + long long m_contentLength = -1; //!< -1 when there is no Content-Length + bool m_chunked = false; + + //!< Case insensitive lookup, empty when the header is absent + std::string header(const std::string& name) const; + }; + + HttpClient() = default; + ~HttpClient(); + + HttpClient(const HttpClient&) = delete; + HttpClient& operator=(const HttpClient&) = delete; + + static bool startup(std::string& error); //!< WSAStartup on Windows, nothing elsewhere + static void cleanup(); + + bool open(const std::string& host, int port, int timeoutMs, std::string& error); + void close(); + //!< Wakes a read blocked on this socket from another thread. Only the socket is touched: + //!< the buffer and the rest belong to the thread reading, which closes when its read + //!< returns. Closing from the other thread would not wake a read on Linux, and frees a + //!< descriptor number the reader still holds + void interrupt(); + bool isOpen() const { return m_socket != invalidSocket(); } + + //!< Sends the request and its body. An empty method body is fine. + bool send(const std::string& method, const std::string& path, const std::vector
& headers, + const std::string& body, std::string& error); + + bool readHead(Head& head, std::string& error); + + //!< Reads the whole body, however it is framed. Not for the event stream, which never ends. + bool readBody(const Head& head, std::string& body, std::string& error); + + //!< One piece of a chunked body, for following a stream. Returns false at the end of the + //!< body or on error, with error empty when the end was reached cleanly. + bool readChunk(std::string& chunk, std::string& error); + + //!< Whatever has arrived of a body that is delimited by the connection closing rather + //!< than chunked, which is how the event stream comes back. Same false at the end. + bool readSome(std::string& data, std::string& error); + +private: +#ifdef _WIN32 + using Socket = unsigned long long; //!< SOCKET, kept out of the header so windows.h is not needed here +#else + using Socket = int; +#endif + + static Socket invalidSocket(); + + bool fill(std::string& error); //!< One read into m_buffer + bool readLine(std::string& line, std::string& error); + bool readExactly(size_t count, std::string& out, std::string& error); + bool sendAll(const std::string& data, std::string& error); + + Socket m_socket = invalidSocket(); + std::string m_buffer; //!< Bytes read from the socket but not yet consumed + bool m_eof = false; +}; + +#endif // INCLUDE_MCPBRIDGE_HTTPCLIENT_H_ diff --git a/plugins/feature/mcpserver/bridge/main.cpp b/plugins/feature/mcpserver/bridge/main.cpp index a0631cb3d..6211064c1 100644 --- a/plugins/feature/mcpserver/bridge/main.cpp +++ b/plugins/feature/mcpserver/bridge/main.cpp @@ -1,1085 +1,1085 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -// Bridges the MCP stdio transport to SDRangel's Streamable HTTP MCP server, for clients -// such as Claude Desktop that can only launch a local server on stdin and stdout. -// JSON-RPC messages are passed through untouched: this program understands the transport, -// not the protocol. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#ifdef _WIN32 -#include -#include -#include -#endif - -#include "httpclient.h" -#include "jsonscan.h" -#include "ssereader.h" - -namespace -{ - -const char *versionText = "sdrangel-mcp-bridge " SDRANGEL_MCP_BRIDGE_VERSION; - -struct Options -{ - std::string m_host = "127.0.0.1"; - int m_port = 8092; - std::string m_path = "/mcp"; - std::string m_token; - bool m_verbose = false; -}; - -void note(const Options& options, const std::string& message) -{ - if (options.m_verbose) { - std::fprintf(stderr, "sdrangel-mcp-bridge: %s\n", message.c_str()); - } -} - -void warn(const std::string& message) -{ - std::fprintf(stderr, "sdrangel-mcp-bridge: %s\n", message.c_str()); -} - -//!< An extension bundle cannot leave an argument out, so a user_config value the user did not -//!< set can reach us as the placeholder text itself. Treated as "not given" rather than taken -//!< literally, which would mean a nonsense port or a token the server never issued. -bool isPlaceholder(const std::string& value) -{ - return (value.size() > 3) && (value.compare(0, 2, "${") == 0) && (value.back() == '}'); -} - -//!< The tool list this build of SDRangel provides, written beside the bridge when the -//!< extension was packaged. A client reads the tool list once when a conversation begins and -//!< does not ask again, so a conversation that starts before SDRangel is up would have no -//!< tools for its whole life if the bridge could only answer with what it had seen. Shipping -//!< the list means it is right the first time the extension is ever used, and it comes from -//!< the server's own registry, so it cannot drift from what the tools really are. -std::string toolsFile(const char *program) -{ - std::string path; - -#ifdef _WIN32 - char module[MAX_PATH]; - - if (GetModuleFileNameA(nullptr, module, MAX_PATH) > 0) { - path = module; - } -#endif - - if (path.empty() && program) { - path = program; - } - - size_t slash = path.find_last_of("/\\"); - return (slash == std::string::npos) ? std::string("tools.json") : path.substr(0, slash + 1) + "tools.json"; -} - -std::string readFile(const std::string& path) -{ - std::ifstream file(path, std::ios::binary); - - if (!file) { - return std::string(); - } - - return std::string((std::istreambuf_iterator(file)), std::istreambuf_iterator()); -} - -//!< JSON string escaping for the messages this program generates itself -std::string escaped(const std::string& text) -{ - std::string result; - - for (char c : text) - { - switch (c) - { - case '"': result += "\\\""; break; - case '\\': result += "\\\\"; break; - case '\n': result += "\\n"; break; - case '\r': result += "\\r"; break; - case '\t': result += "\\t"; break; - default: - if (static_cast(c) < 0x20) { - result += ' '; - } else { - result += c; - } - } - } - - return result; -} - -} // namespace - -class Bridge -{ -public: - Bridge(const Options& options, const std::string& shippedTools) : - m_options(options), - m_shippedTools(shippedTools) - { - } - - int run(); - -private: - void handle(const std::string& message); - void post(const std::string& message); - bool exchange(const std::string& message, HttpClient::Head& head, std::string& body, std::string& error); - void noteSession(const HttpClient::Head& head); - bool reinitialize(const std::string& staleSession); - bool answerLocally(const std::string& id, const std::string& method, const std::string& message); - bool openSession(); - //!< Subscribes again to the resources the client had subscribed to, on a session just built - void replaySubscriptions(); - void settleHandshake(); - void waitForHandshake(); - void streamLoop(); - void startStream(); - void stopStream(); - void endSession(); - - std::vector headers(bool eventStream) const; - void writeMessage(const std::string& message); - void writeError(const std::string& id, int code, const std::string& reason); - - std::string sessionId() const; - - const Options m_options; - mutable std::mutex m_stateMutex; - std::string m_sessionId; - std::string m_protocolVersion; - std::string m_initializeMessage; //!< Kept so the session can be rebuilt without the client - std::set m_subscriptions; //!< Resource URIs the client subscribed to, to carry over to a new session - std::mutex m_reinitMutex; //!< One rebuild at a time, however many calls failed at once - std::atomic m_degraded { false }; //!< Handshake answered without SDRangel: it was not up - std::string m_shippedTools; //!< tools/list result packaged with the bridge, may be empty - - // Every request but the handshake itself waits for the handshake to finish. Whether - // SDRangel was reachable decides how the listings are answered, and a request that - // overtook the handshake would be answered on a state that had not been worked out yet - std::mutex m_handshakeMutex; - std::condition_variable m_handshakeReady; - bool m_handshakeSettled { false }; - - std::mutex m_outputMutex; - - static constexpr int m_retryMinMs = 1000; //!< First wait before reopening the event stream - static constexpr int m_retryMaxMs = 60000; //!< And the longest, once it keeps failing - - // Socket timeouts, so that a SDRangel that has stopped answering cannot hold a worker - // for ever: run() joins every worker once the client closes stdin, and one that never - // returns would keep this process alive after the client has given up on it. - // A call may legitimately run for over a minute: scan watches for up to 30 s after - // measuring its threshold for up to 15 s, and listen may tune the gain first - static constexpr int m_callTimeoutMs = 180000; - // The server writes a keepalive comment every 15 s while the stream is open - static constexpr int m_streamTimeoutMs = 60000; - static constexpr int m_shutdownTimeoutMs = 5000; - - std::atomic m_running { true }; - std::atomic m_streamWanted { false }; - std::thread m_streamThread; - std::mutex m_streamMutex; - HttpClient *m_streamClient = nullptr; //!< Owned by the stream thread, closed from ours to unblock it -}; - -std::string Bridge::sessionId() const -{ - std::lock_guard lock(m_stateMutex); - return m_sessionId; -} - -std::vector Bridge::headers(bool eventStream) const -{ - std::vector result; - result.emplace_back("Host", m_options.m_host + ":" + std::to_string(m_options.m_port)); - result.emplace_back("User-Agent", versionText); - result.emplace_back("Accept", eventStream ? "text/event-stream" : "application/json, text/event-stream"); - - if (!eventStream) { - result.emplace_back("Content-Type", "application/json"); - } - - if (!m_options.m_token.empty()) { - result.emplace_back("Authorization", "Bearer " + m_options.m_token); - } - - std::string session; - std::string version; - { - std::lock_guard lock(m_stateMutex); - session = m_sessionId; - version = m_protocolVersion; - } - - if (!session.empty()) { - result.emplace_back("Mcp-Session-Id", session); - } - - // Sent on every request after initialize, as the Streamable HTTP transport requires - if (!version.empty()) { - result.emplace_back("MCP-Protocol-Version", version); - } - - return result; -} - -void Bridge::writeMessage(const std::string& message) -{ - // One JSON-RPC message per line. Compact JSON has no raw newlines in it, so nothing - // here can break the framing, but a stray carriage return would confuse a strict reader - std::string line(message); - line.erase(std::remove(line.begin(), line.end(), '\n'), line.end()); - line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); - - std::lock_guard lock(m_outputMutex); - std::fwrite(line.data(), 1, line.size(), stdout); - std::fputc('\n', stdout); - std::fflush(stdout); -} - -void Bridge::writeError(const std::string& id, int code, const std::string& reason) -{ - // An absent or unreadable id becomes null, which is what JSON-RPC asks for when the - // request could not be identified. The client cannot match it to a call, so the text - // has to stand on its own in the log - std::string identifier = id.empty() ? "null" : id; - writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + identifier - + ",\"error\":{\"code\":" + std::to_string(code) - + ",\"message\":\"" + escaped(reason) + "\"}}"); -} - -void Bridge::handle(const std::string& message) -{ - post(message); -} - -//!< One request and its whole reply. The error is ready to hand to the client as it is. -bool Bridge::exchange(const std::string& message, HttpClient::Head& head, std::string& body, std::string& error) -{ - HttpClient client; - - if (!client.open(m_options.m_host, m_options.m_port, m_callTimeoutMs, error)) - { - error = "Cannot reach SDRangel's MCP server at " + m_options.m_host + ":" - + std::to_string(m_options.m_port) + ": " + error + ". Start SDRangel, add the MCP Server " - "feature and start it, then try again."; - return false; - } - - if (!client.send("POST", m_options.m_path, headers(false), message, error)) - { - error = "Sending to SDRangel failed: " + error; - return false; - } - - if (!client.readHead(head, error)) - { - error = "No reply from SDRangel: " + error; - return false; - } - - if (!client.readBody(head, body, error)) - { - error = "Truncated reply from SDRangel: " + error; - return false; - } - - return true; -} - -void Bridge::noteSession(const HttpClient::Head& head) -{ - std::string session = head.header("Mcp-Session-Id"); - - if (session.empty() || (session == sessionId())) { - return; - } - - { - std::lock_guard lock(m_stateMutex); - m_sessionId = session; - } - - note(m_options, "session " + session); - startStream(); // no effect once it is running: it picks the new session up on its own -} - -//!< Replays the client's initialize to get a working session again. SDRangel forgets every -//!< session it has issued when it restarts, and answers 404 to the ones it used to know. The -//!< client will not initialize a second time on its own, and the bridge outlives many runs of -//!< SDRangel, so without this the connector is dead until the client restarts it. -bool Bridge::reinitialize(const std::string& staleSession) -{ - std::lock_guard lock(m_reinitMutex); - - if (sessionId() != staleSession) { - return true; // another call rebuilt it while this one waited - } - - std::string initialize; - { - std::lock_guard stateLock(m_stateMutex); - initialize = m_initializeMessage; - m_sessionId.clear(); // or the replay carries the dead id and is refused in its turn - } - - if (initialize.empty()) { - return false; - } - - HttpClient::Head head; - std::string body; - std::string error; - - if (!exchange(initialize, head, body, error)) - { - note(m_options, "could not start a new session: " + error); - return false; - } - - if ((head.m_status < 200) || (head.m_status > 299)) - { - note(m_options, "could not start a new session: HTTP " + std::to_string(head.m_status)); - return false; - } - - noteSession(head); - - std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); - - if (!version.empty()) - { - std::lock_guard stateLock(m_stateMutex); - m_protocolVersion = version; - } - - // This server does nothing with it, but a client that has initialized sends it, and the - // reply is of no interest either way - HttpClient::Head ignoredHead; - std::string ignoredBody; - std::string ignoredError; - exchange("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}", ignoredHead, ignoredBody, ignoredError); - - if (sessionId().empty()) { - return false; - } - - replaySubscriptions(); - return true; -} - -//!< A subscription lives in the session it was made in, so a session the server has forgotten -//!< took the client's subscriptions with it. The client is not told: the updates it asked for -//!< carry on arriving as before. The replies are answers to requests the client never made, so -//!< they are not passed on -void Bridge::replaySubscriptions() -{ - std::set uris; - { - std::lock_guard lock(m_stateMutex); - uris = m_subscriptions; - } - - int n = 0; - - for (const std::string& uri : uris) - { - HttpClient::Head head; - std::string body; - std::string error; - std::string message = "{\"jsonrpc\":\"2.0\",\"id\":\"bridge-subscribe-" + std::to_string(++n) - + "\",\"method\":\"resources/subscribe\",\"params\":{\"uri\":\"" + escaped(uri) + "\"}}"; - - if (!exchange(message, head, body, error) || (head.m_status < 200) || (head.m_status > 299)) { - note(m_options, "could not subscribe again to " + uri); - } - } - - if (n > 0) { - note(m_options, "subscribed again to " + std::to_string(n) + " resource(s)"); - } -} - -//!< Answers what the bridge can answer on its own. Returns true when it has replied. -//!< -//!< A stdio server's health is judged by the client from this conversation, and the bridge is -//!< healthy whether or not SDRangel happens to be running: it is a long lived process that -//!< outlives many runs of the application behind it. Letting SDRangel's absence turn into -//!< failed pings or a failed handshake makes the client give up on the bridge for good, since -//!< it will not restart it until the application itself is restarted. -bool Bridge::answerLocally(const std::string& id, const std::string& method, const std::string& message) -{ - if (!m_degraded.load()) { - return false; - } - - // SDRangel was not up for the handshake, so there is nothing to list yet. An empty list - // keeps the client working; it is told to ask again as soon as SDRangel appears - static const char *emptyListings[][2] = { - {"tools/list", "tools"}, - {"resources/list", "resources"}, - {"resources/templates/list", "resourceTemplates"}, - {"prompts/list", "prompts"}, - }; - - for (const auto& listing : emptyListings) - { - if (method == listing[0]) - { - // The tools are shipped with the bridge; resources and prompts are whatever the - // running instance happens to hold, so those stay empty until it is reachable - std::string result = (method == "tools/list") && !m_shippedTools.empty() - ? m_shippedTools - : std::string("{\"") + listing[1] + "\":[]}"; - - writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) - + ",\"result\":" + result + "}"); - return true; - } - } - - (void) message; - return false; -} - -//!< Establishes a session upstream by replaying the client's initialize. Tells the client to -//!< ask for the tools again if the handshake had to be answered without SDRangel. -bool Bridge::openSession() -{ - if (!sessionId().empty()) { - return true; - } - - // One session at a time, however many callers found none: the stream thread and every - // worker with a call in hand arrive here together when SDRangel comes back, and each - // would otherwise open a session of its own, with the stream on one and the calls on - // another. Whoever waited finds the session the first one made - std::lock_guard lock(m_reinitMutex); - - if (!sessionId().empty()) { - return true; - } - - std::string initialize; - { - std::lock_guard lock(m_stateMutex); - initialize = m_initializeMessage; - } - - if (initialize.empty()) { - return false; - } - - HttpClient::Head head; - std::string body; - std::string error; - - if (!exchange(initialize, head, body, error) || (head.m_status < 200) || (head.m_status > 299)) { - return false; - } - - noteSession(head); - - if (sessionId().empty()) { - return false; - } - - std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); - - if (!version.empty()) - { - std::lock_guard lock(m_stateMutex); - m_protocolVersion = version; - } - - replaySubscriptions(); - - if (m_degraded.exchange(false)) - { - note(m_options, "SDRangel is up, telling the client to list again"); - writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}"); - writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/resources/list_changed\"}"); - writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/prompts/list_changed\"}"); - } - - return true; -} - -void Bridge::settleHandshake() -{ - { - std::lock_guard lock(m_handshakeMutex); - m_handshakeSettled = true; - } - - m_handshakeReady.notify_all(); -} - -void Bridge::waitForHandshake() -{ - std::unique_lock lock(m_handshakeMutex); - - // Bounded, so that a client which never gets as far as initialize cannot wedge the bridge - m_handshakeReady.wait_for(lock, std::chrono::seconds(20), [this]() { return m_handshakeSettled; }); -} - -void Bridge::post(const std::string& message) -{ - std::string id = jsonMember(message, "id"); - std::string method = jsonStringMember(message, "method"); - - // Whether this process is alive has nothing to do with the handshake or with SDRangel - if (method == "ping") - { - writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) + ",\"result\":{}}"); - return; - } - - if (method == "initialize") - { - std::lock_guard lock(m_stateMutex); - m_initializeMessage = message; - } - else - { - waitForHandshake(); - } - - if (answerLocally(id, method, message)) { - return; - } - - // A call arriving while there is no session, because SDRangel was away: try to build one - // rather than failing on a stale or absent session - if ((method != "initialize") && sessionId().empty()) { - openSession(); - } - - // Releases anything waiting on the handshake however this call ends - struct Settle - { - Bridge *bridge; - bool wanted; - ~Settle() { if (wanted) { bridge->settleHandshake(); } } - } settle { this, method == "initialize" }; - - HttpClient::Head head; - std::string body; - std::string error; - - if (!exchange(message, head, body, error)) - { - // A notification has no id and takes no reply, failed or not: an error against a - // null id is a response to a call the client never made - if (id.empty() && (method != "initialize")) - { - note(m_options, "dropped " + method + ": " + error); - return; - } - - // The handshake must not fail, whatever SDRangel is doing: a client that is told the - // server is broken during initialize never comes back to it - if (method == "initialize") - { - note(m_options, "SDRangel is not up: answering the handshake without it"); - m_degraded.store(true); - startStream(); // watches for SDRangel and lists again once it is there - - std::string requested = jsonStringMember(jsonMember(message, "params"), "protocolVersion"); - - if (requested.empty()) { - requested = "2025-06-18"; - } - - writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) - + ",\"result\":{\"protocolVersion\":\"" + escaped(requested) + "\"" - ",\"capabilities\":{\"tools\":{\"listChanged\":true}" - ",\"resources\":{\"listChanged\":true,\"subscribe\":true}" - ",\"prompts\":{\"listChanged\":true}}" - ",\"serverInfo\":{\"name\":\"SDRangel\",\"version\":\"" + escaped(SDRANGEL_MCP_BRIDGE_VERSION) + "\"}" - // Written in the past tense: the client reads this once, when the - // conversation starts, and never again, so anything phrased as the state - // right now is wrong within seconds of SDRangel being started - ",\"instructions\":\"SDRangel is a software defined radio (SDR) application. This " - "server controls it.\\n\\nSDRangel was not running when this conversation started, so " - "these tools are the ones shipped with it rather than a listing from the running " - "instance. They work as soon as SDRangel is running with the MCP Server feature added " - "and started, with nothing to restart. Until then a call reports that it cannot reach " - "it.\"}}"); - return; - } - - writeError(id, -32001, error); - return; - } - - noteSession(head); - - // A session the server has never heard of: it has been restarted, or the session was - // expired. Rebuild it and send the call again, so that neither the client nor the user - // has to know anything happened - std::string session = sessionId(); - - if ((head.m_status == 404) && !session.empty() && (method != "initialize")) - { - note(m_options, "session refused, starting a new one"); - - if (reinitialize(session)) - { - HttpClient::Head retryHead; - std::string retryBody; - std::string retryError; - - if (exchange(message, retryHead, retryBody, retryError)) - { - head = retryHead; - body = retryBody; - noteSession(head); - } - } - } - - if (head.m_status == 202) { - return; // a notification or a response of our own: nothing comes back - } - - if ((head.m_status < 200) || (head.m_status > 299)) - { - // The server's own errors are {"error": "..."} rather than JSON-RPC - std::string detail = jsonStringMember(body, "error"); - - if (detail.empty()) { - detail = head.m_reason.empty() ? body : head.m_reason; - } - - writeError(id, -32001, "SDRangel returned HTTP " + std::to_string(head.m_status) + ": " + detail); - return; - } - - if (body.empty()) - { - writeError(id, -32001, "SDRangel returned an empty reply"); - return; - } - - if (method == "initialize") - { - std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); - - if (!version.empty()) - { - std::lock_guard lock(m_stateMutex); - m_protocolVersion = version; - } - } - - // Remembered only once the server has accepted it, so that a refused subscription is not - // replayed on the next session - if (((method == "resources/subscribe") || (method == "resources/unsubscribe")) && jsonMember(body, "error").empty()) - { - std::string uri = jsonStringMember(jsonMember(message, "params"), "uri"); - - if (!uri.empty()) - { - std::lock_guard lock(m_stateMutex); - - if (method == "resources/subscribe") { - m_subscriptions.insert(uri); - } else { - m_subscriptions.erase(uri); - } - } - } - - writeMessage(body); -} - -void Bridge::startStream() -{ - bool expected = false; - - if (!m_streamWanted.compare_exchange_strong(expected, true)) { - return; // already running - } - - m_streamThread = std::thread([this]() { streamLoop(); }); -} - -void Bridge::stopStream() -{ - if (!m_streamWanted.load()) { - return; - } - - { - // Shutting the socket down under the thread is what unblocks its read; the thread - // then closes it itself - std::lock_guard lock(m_streamMutex); - - if (m_streamClient) { - m_streamClient->interrupt(); - } - } - - if (m_streamThread.joinable()) { - m_streamThread.join(); - } -} - -void Bridge::streamLoop() -{ - // The server closes the stream when its lifetime backstop expires, so this reopens it - // for as long as the bridge is running. It is also what notices SDRangel coming back - // after the handshake had to be answered without it. - // - // Retries back off. A client that is sitting idle sends nothing, so nothing else here - // ever notices that something is wrong, and a fixed one second retry turns an - // unreachable or unhappy server into hundreds of log lines a minute, for hours. - int retryMs = m_retryMinMs; - - while (m_running.load()) - { - HttpClient client; - std::string error; - bool opened = false; - - if (sessionId().empty() && !openSession()) - { - // Nothing to stream from yet: wait and look again - for (int waited = 0; m_running.load() && (waited < retryMs); waited += 50) { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - } - - retryMs = std::min(retryMs * 2, m_retryMaxMs); - continue; - } - - if (!client.open(m_options.m_host, m_options.m_port, m_streamTimeoutMs, error)) - { - note(m_options, "event stream cannot connect: " + error); - } - else - { - { - std::lock_guard lock(m_streamMutex); - m_streamClient = &client; - } - - if (client.send("GET", m_options.m_path, headers(true), std::string(), error)) - { - HttpClient::Head head; - - if (!client.readHead(head, error)) - { - note(m_options, "event stream failed: " + error); - } - else if (head.m_status == 404) - { - // The session has been forgotten, which SDRangel restarting does to all of - // them. Only calls coming from the client recovered this before, so an idle - // client left the stream asking after a session that would never come back - note(m_options, "event stream session refused, starting a new one"); - - std::string stale = sessionId(); - - if (!stale.empty()) { - reinitialize(stale); - } - } - else if (head.m_status != 200) - { - note(m_options, "event stream refused with HTTP " + std::to_string(head.m_status)); - } - else - { - note(m_options, "event stream open"); - opened = true; - retryMs = m_retryMinMs; - SseReader reader; - std::string chunk; - - // The server delimits the stream by closing the connection rather than - // chunking it, but a proxy or a later server might chunk, so follow - // whichever framing the response actually used - while (head.m_chunked ? client.readChunk(chunk, error) : client.readSome(chunk, error)) - { - for (const auto& event : reader.feed(chunk)) - { - if (!event.empty()) { - writeMessage(event); - } - } - } - - if (!error.empty()) { - note(m_options, "event stream ended: " + error); - } - } - } - - { - std::lock_guard lock(m_streamMutex); - m_streamClient = nullptr; - } - } - - // Reopening immediately would spin if the server has gone away - for (int waited = 0; m_running.load() && (waited < retryMs); waited += 50) { - std::this_thread::sleep_for(std::chrono::milliseconds(50)); - } - - // A stream that opened and then ended is the normal lifetime backstop, so that starts - // again promptly; anything else waits longer each time - retryMs = opened ? m_retryMinMs : std::min(retryMs * 2, m_retryMaxMs); - } -} - -void Bridge::endSession() -{ - std::string session = sessionId(); - - if (session.empty()) { - return; - } - - HttpClient client; - std::string error; - - if (!client.open(m_options.m_host, m_options.m_port, m_shutdownTimeoutMs, error)) { - return; // going away anyway, and the server expires idle sessions - } - - if (client.send("DELETE", m_options.m_path, headers(false), std::string(), error)) - { - HttpClient::Head head; - std::string body; - - if (client.readHead(head, error)) { - client.readBody(head, body, error); - } - } - - note(m_options, "session ended"); -} - -int Bridge::run() -{ - std::string error; - - if (!HttpClient::startup(error)) - { - warn(error); - return 1; - } - - note(m_options, std::string("relaying to http://") + m_options.m_host + ":" - + std::to_string(m_options.m_port) + m_options.m_path); - - // A worker, and the flag it raises once it has run to completion. A thread that is still - // working is joinable too, so joinable() cannot tell the loop below which of them it is able - // to reap without blocking - struct Worker - { - std::thread m_thread; - std::shared_ptr> m_finished; - }; - - std::vector workers; - std::string line; - - while (std::getline(std::cin, line)) - { - if (!line.empty() && (line.back() == '\r')) { - line.pop_back(); - } - - if (line.empty()) { - continue; - } - - // A thread each, so that a long call such as record_iq does not hold up the - // messages that follow it, cancellation among them - auto finished = std::make_shared>(false); - workers.push_back(Worker{ - std::thread([this, line, finished]() { - handle(line); - finished->store(true); - }), - finished}); - - // Reap only the ones that have finished. Joining a worker that is still inside a - // record_iq, listen, scan or audio call would stop this loop reading input for as long as - // that call runs, which is exactly when a cancellation needs to get through - for (auto worker = workers.begin(); worker != workers.end(); ) - { - if (worker->m_finished->load()) - { - worker->m_thread.join(); - worker = workers.erase(worker); - } - else - { - ++worker; - } - } - } - - note(m_options, "input closed"); - m_running.store(false); - - for (auto& worker : workers) - { - if (worker.m_thread.joinable()) { - worker.m_thread.join(); - } - } - - stopStream(); - endSession(); - HttpClient::cleanup(); - return 0; -} - -int main(int argc, char *argv[]) -{ -#ifndef _WIN32 - // A write to a socket or pipe whose other end has gone must fail, not end the process - signal(SIGPIPE, SIG_IGN); -#endif - - Options options; - - for (int i = 1; i < argc; i++) - { - std::string argument(argv[i]); - auto value = [&](const char *name) -> std::string - { - if (i + 1 >= argc) - { - warn(std::string(name) + " needs a value"); - std::exit(2); - } - - return std::string(argv[++i]); - }; - - if (argument == "--host") - { - std::string host = value("--host"); - - if (!isPlaceholder(host) && !host.empty()) { - options.m_host = host; - } - } - else if (argument == "--port") - { - std::string port = value("--port"); - - if (!isPlaceholder(port) && !port.empty()) { - options.m_port = std::atoi(port.c_str()); - } - } - else if (argument == "--path") - { - std::string path = value("--path"); - - if (!isPlaceholder(path) && !path.empty()) { - options.m_path = path; - } - } - else if (argument == "--token") - { - std::string token = value("--token"); - - // "" is how a shell or a manifest spells an empty value it could not omit - if (!isPlaceholder(token) && (token != "\"\"")) { - options.m_token = token; - } - } - else if (argument == "--verbose") { - options.m_verbose = true; - } else if ((argument == "--version") || (argument == "-v")) { - std::printf("%s\n", versionText); - return 0; - } else if ((argument == "--help") || (argument == "-h")) { - std::printf("%s\n\n", versionText); - std::printf("Relays the MCP stdio transport to SDRangel's HTTP MCP server.\n\n"); - std::printf(" --host
SDRangel's MCP server address (default 127.0.0.1)\n"); - std::printf(" --port SDRangel's MCP server port (default 8092)\n"); - std::printf(" --path Endpoint path (default /mcp)\n"); - std::printf(" --token Bearer token, if the server has one set\n"); - std::printf(" --verbose Report what it is doing on stderr\n"); - return 0; - } else { - warn("unknown argument " + argument); - return 2; - } - } - - if ((options.m_port <= 0) || (options.m_port > 65535)) - { - warn("port must be between 1 and 65535"); - return 2; - } - -#ifdef _WIN32 - // Without this the C runtime turns \n into \r\n on the way out and eats \r on the way - // in, either of which corrupts the message framing - _setmode(_fileno(stdin), _O_BINARY); - _setmode(_fileno(stdout), _O_BINARY); -#endif - - std::ios::sync_with_stdio(false); - - std::string shippedTools = readFile(toolsFile(argv[0])); - - // Trim, so that a trailing newline cannot land in the middle of a JSON-RPC message - while (!shippedTools.empty() && ((shippedTools.back() == '\n') || (shippedTools.back() == '\r'))) { - shippedTools.pop_back(); - } - - if (options.m_verbose && shippedTools.empty()) { - warn("no tools.json beside the executable: no tools until SDRangel is reachable"); - } - - Bridge bridge(options, shippedTools); - return bridge.run(); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +// Bridges the MCP stdio transport to SDRangel's Streamable HTTP MCP server, for clients +// such as Claude Desktop that can only launch a local server on stdin and stdout. +// JSON-RPC messages are passed through untouched: this program understands the transport, +// not the protocol. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#include +#include +#endif + +#include "httpclient.h" +#include "jsonscan.h" +#include "ssereader.h" + +namespace +{ + +const char *versionText = "sdrangel-mcp-bridge " SDRANGEL_MCP_BRIDGE_VERSION; + +struct Options +{ + std::string m_host = "127.0.0.1"; + int m_port = 8092; + std::string m_path = "/mcp"; + std::string m_token; + bool m_verbose = false; +}; + +void note(const Options& options, const std::string& message) +{ + if (options.m_verbose) { + std::fprintf(stderr, "sdrangel-mcp-bridge: %s\n", message.c_str()); + } +} + +void warn(const std::string& message) +{ + std::fprintf(stderr, "sdrangel-mcp-bridge: %s\n", message.c_str()); +} + +//!< An extension bundle cannot leave an argument out, so a user_config value the user did not +//!< set can reach us as the placeholder text itself. Treated as "not given" rather than taken +//!< literally, which would mean a nonsense port or a token the server never issued. +bool isPlaceholder(const std::string& value) +{ + return (value.size() > 3) && (value.compare(0, 2, "${") == 0) && (value.back() == '}'); +} + +//!< The tool list this build of SDRangel provides, written beside the bridge when the +//!< extension was packaged. A client reads the tool list once when a conversation begins and +//!< does not ask again, so a conversation that starts before SDRangel is up would have no +//!< tools for its whole life if the bridge could only answer with what it had seen. Shipping +//!< the list means it is right the first time the extension is ever used, and it comes from +//!< the server's own registry, so it cannot drift from what the tools really are. +std::string toolsFile(const char *program) +{ + std::string path; + +#ifdef _WIN32 + char module[MAX_PATH]; + + if (GetModuleFileNameA(nullptr, module, MAX_PATH) > 0) { + path = module; + } +#endif + + if (path.empty() && program) { + path = program; + } + + size_t slash = path.find_last_of("/\\"); + return (slash == std::string::npos) ? std::string("tools.json") : path.substr(0, slash + 1) + "tools.json"; +} + +std::string readFile(const std::string& path) +{ + std::ifstream file(path, std::ios::binary); + + if (!file) { + return std::string(); + } + + return std::string((std::istreambuf_iterator(file)), std::istreambuf_iterator()); +} + +//!< JSON string escaping for the messages this program generates itself +std::string escaped(const std::string& text) +{ + std::string result; + + for (char c : text) + { + switch (c) + { + case '"': result += "\\\""; break; + case '\\': result += "\\\\"; break; + case '\n': result += "\\n"; break; + case '\r': result += "\\r"; break; + case '\t': result += "\\t"; break; + default: + if (static_cast(c) < 0x20) { + result += ' '; + } else { + result += c; + } + } + } + + return result; +} + +} // namespace + +class Bridge +{ +public: + Bridge(const Options& options, const std::string& shippedTools) : + m_options(options), + m_shippedTools(shippedTools) + { + } + + int run(); + +private: + void handle(const std::string& message); + void post(const std::string& message); + bool exchange(const std::string& message, HttpClient::Head& head, std::string& body, std::string& error); + void noteSession(const HttpClient::Head& head); + bool reinitialize(const std::string& staleSession); + bool answerLocally(const std::string& id, const std::string& method, const std::string& message); + bool openSession(); + //!< Subscribes again to the resources the client had subscribed to, on a session just built + void replaySubscriptions(); + void settleHandshake(); + void waitForHandshake(); + void streamLoop(); + void startStream(); + void stopStream(); + void endSession(); + + std::vector headers(bool eventStream) const; + void writeMessage(const std::string& message); + void writeError(const std::string& id, int code, const std::string& reason); + + std::string sessionId() const; + + const Options m_options; + mutable std::mutex m_stateMutex; + std::string m_sessionId; + std::string m_protocolVersion; + std::string m_initializeMessage; //!< Kept so the session can be rebuilt without the client + std::set m_subscriptions; //!< Resource URIs the client subscribed to, to carry over to a new session + std::mutex m_reinitMutex; //!< One rebuild at a time, however many calls failed at once + std::atomic m_degraded { false }; //!< Handshake answered without SDRangel: it was not up + std::string m_shippedTools; //!< tools/list result packaged with the bridge, may be empty + + // Every request but the handshake itself waits for the handshake to finish. Whether + // SDRangel was reachable decides how the listings are answered, and a request that + // overtook the handshake would be answered on a state that had not been worked out yet + std::mutex m_handshakeMutex; + std::condition_variable m_handshakeReady; + bool m_handshakeSettled { false }; + + std::mutex m_outputMutex; + + static constexpr int m_retryMinMs = 1000; //!< First wait before reopening the event stream + static constexpr int m_retryMaxMs = 60000; //!< And the longest, once it keeps failing + + // Socket timeouts, so that a SDRangel that has stopped answering cannot hold a worker + // for ever: run() joins every worker once the client closes stdin, and one that never + // returns would keep this process alive after the client has given up on it. + // A call may legitimately run for over a minute: scan watches for up to 30 s after + // measuring its threshold for up to 15 s, and listen may tune the gain first + static constexpr int m_callTimeoutMs = 180000; + // The server writes a keepalive comment every 15 s while the stream is open + static constexpr int m_streamTimeoutMs = 60000; + static constexpr int m_shutdownTimeoutMs = 5000; + + std::atomic m_running { true }; + std::atomic m_streamWanted { false }; + std::thread m_streamThread; + std::mutex m_streamMutex; + HttpClient *m_streamClient = nullptr; //!< Owned by the stream thread, closed from ours to unblock it +}; + +std::string Bridge::sessionId() const +{ + std::lock_guard lock(m_stateMutex); + return m_sessionId; +} + +std::vector Bridge::headers(bool eventStream) const +{ + std::vector result; + result.emplace_back("Host", m_options.m_host + ":" + std::to_string(m_options.m_port)); + result.emplace_back("User-Agent", versionText); + result.emplace_back("Accept", eventStream ? "text/event-stream" : "application/json, text/event-stream"); + + if (!eventStream) { + result.emplace_back("Content-Type", "application/json"); + } + + if (!m_options.m_token.empty()) { + result.emplace_back("Authorization", "Bearer " + m_options.m_token); + } + + std::string session; + std::string version; + { + std::lock_guard lock(m_stateMutex); + session = m_sessionId; + version = m_protocolVersion; + } + + if (!session.empty()) { + result.emplace_back("Mcp-Session-Id", session); + } + + // Sent on every request after initialize, as the Streamable HTTP transport requires + if (!version.empty()) { + result.emplace_back("MCP-Protocol-Version", version); + } + + return result; +} + +void Bridge::writeMessage(const std::string& message) +{ + // One JSON-RPC message per line. Compact JSON has no raw newlines in it, so nothing + // here can break the framing, but a stray carriage return would confuse a strict reader + std::string line(message); + line.erase(std::remove(line.begin(), line.end(), '\n'), line.end()); + line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); + + std::lock_guard lock(m_outputMutex); + std::fwrite(line.data(), 1, line.size(), stdout); + std::fputc('\n', stdout); + std::fflush(stdout); +} + +void Bridge::writeError(const std::string& id, int code, const std::string& reason) +{ + // An absent or unreadable id becomes null, which is what JSON-RPC asks for when the + // request could not be identified. The client cannot match it to a call, so the text + // has to stand on its own in the log + std::string identifier = id.empty() ? "null" : id; + writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + identifier + + ",\"error\":{\"code\":" + std::to_string(code) + + ",\"message\":\"" + escaped(reason) + "\"}}"); +} + +void Bridge::handle(const std::string& message) +{ + post(message); +} + +//!< One request and its whole reply. The error is ready to hand to the client as it is. +bool Bridge::exchange(const std::string& message, HttpClient::Head& head, std::string& body, std::string& error) +{ + HttpClient client; + + if (!client.open(m_options.m_host, m_options.m_port, m_callTimeoutMs, error)) + { + error = "Cannot reach SDRangel's MCP server at " + m_options.m_host + ":" + + std::to_string(m_options.m_port) + ": " + error + ". Start SDRangel, add the MCP Server " + "feature and start it, then try again."; + return false; + } + + if (!client.send("POST", m_options.m_path, headers(false), message, error)) + { + error = "Sending to SDRangel failed: " + error; + return false; + } + + if (!client.readHead(head, error)) + { + error = "No reply from SDRangel: " + error; + return false; + } + + if (!client.readBody(head, body, error)) + { + error = "Truncated reply from SDRangel: " + error; + return false; + } + + return true; +} + +void Bridge::noteSession(const HttpClient::Head& head) +{ + std::string session = head.header("Mcp-Session-Id"); + + if (session.empty() || (session == sessionId())) { + return; + } + + { + std::lock_guard lock(m_stateMutex); + m_sessionId = session; + } + + note(m_options, "session " + session); + startStream(); // no effect once it is running: it picks the new session up on its own +} + +//!< Replays the client's initialize to get a working session again. SDRangel forgets every +//!< session it has issued when it restarts, and answers 404 to the ones it used to know. The +//!< client will not initialize a second time on its own, and the bridge outlives many runs of +//!< SDRangel, so without this the connector is dead until the client restarts it. +bool Bridge::reinitialize(const std::string& staleSession) +{ + std::lock_guard lock(m_reinitMutex); + + if (sessionId() != staleSession) { + return true; // another call rebuilt it while this one waited + } + + std::string initialize; + { + std::lock_guard stateLock(m_stateMutex); + initialize = m_initializeMessage; + m_sessionId.clear(); // or the replay carries the dead id and is refused in its turn + } + + if (initialize.empty()) { + return false; + } + + HttpClient::Head head; + std::string body; + std::string error; + + if (!exchange(initialize, head, body, error)) + { + note(m_options, "could not start a new session: " + error); + return false; + } + + if ((head.m_status < 200) || (head.m_status > 299)) + { + note(m_options, "could not start a new session: HTTP " + std::to_string(head.m_status)); + return false; + } + + noteSession(head); + + std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); + + if (!version.empty()) + { + std::lock_guard stateLock(m_stateMutex); + m_protocolVersion = version; + } + + // This server does nothing with it, but a client that has initialized sends it, and the + // reply is of no interest either way + HttpClient::Head ignoredHead; + std::string ignoredBody; + std::string ignoredError; + exchange("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}", ignoredHead, ignoredBody, ignoredError); + + if (sessionId().empty()) { + return false; + } + + replaySubscriptions(); + return true; +} + +//!< A subscription lives in the session it was made in, so a session the server has forgotten +//!< took the client's subscriptions with it. The client is not told: the updates it asked for +//!< carry on arriving as before. The replies are answers to requests the client never made, so +//!< they are not passed on +void Bridge::replaySubscriptions() +{ + std::set uris; + { + std::lock_guard lock(m_stateMutex); + uris = m_subscriptions; + } + + int n = 0; + + for (const std::string& uri : uris) + { + HttpClient::Head head; + std::string body; + std::string error; + std::string message = "{\"jsonrpc\":\"2.0\",\"id\":\"bridge-subscribe-" + std::to_string(++n) + + "\",\"method\":\"resources/subscribe\",\"params\":{\"uri\":\"" + escaped(uri) + "\"}}"; + + if (!exchange(message, head, body, error) || (head.m_status < 200) || (head.m_status > 299)) { + note(m_options, "could not subscribe again to " + uri); + } + } + + if (n > 0) { + note(m_options, "subscribed again to " + std::to_string(n) + " resource(s)"); + } +} + +//!< Answers what the bridge can answer on its own. Returns true when it has replied. +//!< +//!< A stdio server's health is judged by the client from this conversation, and the bridge is +//!< healthy whether or not SDRangel happens to be running: it is a long lived process that +//!< outlives many runs of the application behind it. Letting SDRangel's absence turn into +//!< failed pings or a failed handshake makes the client give up on the bridge for good, since +//!< it will not restart it until the application itself is restarted. +bool Bridge::answerLocally(const std::string& id, const std::string& method, const std::string& message) +{ + if (!m_degraded.load()) { + return false; + } + + // SDRangel was not up for the handshake, so there is nothing to list yet. An empty list + // keeps the client working; it is told to ask again as soon as SDRangel appears + static const char *emptyListings[][2] = { + {"tools/list", "tools"}, + {"resources/list", "resources"}, + {"resources/templates/list", "resourceTemplates"}, + {"prompts/list", "prompts"}, + }; + + for (const auto& listing : emptyListings) + { + if (method == listing[0]) + { + // The tools are shipped with the bridge; resources and prompts are whatever the + // running instance happens to hold, so those stay empty until it is reachable + std::string result = (method == "tools/list") && !m_shippedTools.empty() + ? m_shippedTools + : std::string("{\"") + listing[1] + "\":[]}"; + + writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) + + ",\"result\":" + result + "}"); + return true; + } + } + + (void) message; + return false; +} + +//!< Establishes a session upstream by replaying the client's initialize. Tells the client to +//!< ask for the tools again if the handshake had to be answered without SDRangel. +bool Bridge::openSession() +{ + if (!sessionId().empty()) { + return true; + } + + // One session at a time, however many callers found none: the stream thread and every + // worker with a call in hand arrive here together when SDRangel comes back, and each + // would otherwise open a session of its own, with the stream on one and the calls on + // another. Whoever waited finds the session the first one made + std::lock_guard lock(m_reinitMutex); + + if (!sessionId().empty()) { + return true; + } + + std::string initialize; + { + std::lock_guard lock(m_stateMutex); + initialize = m_initializeMessage; + } + + if (initialize.empty()) { + return false; + } + + HttpClient::Head head; + std::string body; + std::string error; + + if (!exchange(initialize, head, body, error) || (head.m_status < 200) || (head.m_status > 299)) { + return false; + } + + noteSession(head); + + if (sessionId().empty()) { + return false; + } + + std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); + + if (!version.empty()) + { + std::lock_guard lock(m_stateMutex); + m_protocolVersion = version; + } + + replaySubscriptions(); + + if (m_degraded.exchange(false)) + { + note(m_options, "SDRangel is up, telling the client to list again"); + writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/tools/list_changed\"}"); + writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/resources/list_changed\"}"); + writeMessage("{\"jsonrpc\":\"2.0\",\"method\":\"notifications/prompts/list_changed\"}"); + } + + return true; +} + +void Bridge::settleHandshake() +{ + { + std::lock_guard lock(m_handshakeMutex); + m_handshakeSettled = true; + } + + m_handshakeReady.notify_all(); +} + +void Bridge::waitForHandshake() +{ + std::unique_lock lock(m_handshakeMutex); + + // Bounded, so that a client which never gets as far as initialize cannot wedge the bridge + m_handshakeReady.wait_for(lock, std::chrono::seconds(20), [this]() { return m_handshakeSettled; }); +} + +void Bridge::post(const std::string& message) +{ + std::string id = jsonMember(message, "id"); + std::string method = jsonStringMember(message, "method"); + + // Whether this process is alive has nothing to do with the handshake or with SDRangel + if (method == "ping") + { + writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) + ",\"result\":{}}"); + return; + } + + if (method == "initialize") + { + std::lock_guard lock(m_stateMutex); + m_initializeMessage = message; + } + else + { + waitForHandshake(); + } + + if (answerLocally(id, method, message)) { + return; + } + + // A call arriving while there is no session, because SDRangel was away: try to build one + // rather than failing on a stale or absent session + if ((method != "initialize") && sessionId().empty()) { + openSession(); + } + + // Releases anything waiting on the handshake however this call ends + struct Settle + { + Bridge *bridge; + bool wanted; + ~Settle() { if (wanted) { bridge->settleHandshake(); } } + } settle { this, method == "initialize" }; + + HttpClient::Head head; + std::string body; + std::string error; + + if (!exchange(message, head, body, error)) + { + // A notification has no id and takes no reply, failed or not: an error against a + // null id is a response to a call the client never made + if (id.empty() && (method != "initialize")) + { + note(m_options, "dropped " + method + ": " + error); + return; + } + + // The handshake must not fail, whatever SDRangel is doing: a client that is told the + // server is broken during initialize never comes back to it + if (method == "initialize") + { + note(m_options, "SDRangel is not up: answering the handshake without it"); + m_degraded.store(true); + startStream(); // watches for SDRangel and lists again once it is there + + std::string requested = jsonStringMember(jsonMember(message, "params"), "protocolVersion"); + + if (requested.empty()) { + requested = "2025-06-18"; + } + + writeMessage("{\"jsonrpc\":\"2.0\",\"id\":" + (id.empty() ? "null" : id) + + ",\"result\":{\"protocolVersion\":\"" + escaped(requested) + "\"" + ",\"capabilities\":{\"tools\":{\"listChanged\":true}" + ",\"resources\":{\"listChanged\":true,\"subscribe\":true}" + ",\"prompts\":{\"listChanged\":true}}" + ",\"serverInfo\":{\"name\":\"SDRangel\",\"version\":\"" + escaped(SDRANGEL_MCP_BRIDGE_VERSION) + "\"}" + // Written in the past tense: the client reads this once, when the + // conversation starts, and never again, so anything phrased as the state + // right now is wrong within seconds of SDRangel being started + ",\"instructions\":\"SDRangel is a software defined radio (SDR) application. This " + "server controls it.\\n\\nSDRangel was not running when this conversation started, so " + "these tools are the ones shipped with it rather than a listing from the running " + "instance. They work as soon as SDRangel is running with the MCP Server feature added " + "and started, with nothing to restart. Until then a call reports that it cannot reach " + "it.\"}}"); + return; + } + + writeError(id, -32001, error); + return; + } + + noteSession(head); + + // A session the server has never heard of: it has been restarted, or the session was + // expired. Rebuild it and send the call again, so that neither the client nor the user + // has to know anything happened + std::string session = sessionId(); + + if ((head.m_status == 404) && !session.empty() && (method != "initialize")) + { + note(m_options, "session refused, starting a new one"); + + if (reinitialize(session)) + { + HttpClient::Head retryHead; + std::string retryBody; + std::string retryError; + + if (exchange(message, retryHead, retryBody, retryError)) + { + head = retryHead; + body = retryBody; + noteSession(head); + } + } + } + + if (head.m_status == 202) { + return; // a notification or a response of our own: nothing comes back + } + + if ((head.m_status < 200) || (head.m_status > 299)) + { + // The server's own errors are {"error": "..."} rather than JSON-RPC + std::string detail = jsonStringMember(body, "error"); + + if (detail.empty()) { + detail = head.m_reason.empty() ? body : head.m_reason; + } + + writeError(id, -32001, "SDRangel returned HTTP " + std::to_string(head.m_status) + ": " + detail); + return; + } + + if (body.empty()) + { + writeError(id, -32001, "SDRangel returned an empty reply"); + return; + } + + if (method == "initialize") + { + std::string version = jsonStringMember(jsonMember(body, "result"), "protocolVersion"); + + if (!version.empty()) + { + std::lock_guard lock(m_stateMutex); + m_protocolVersion = version; + } + } + + // Remembered only once the server has accepted it, so that a refused subscription is not + // replayed on the next session + if (((method == "resources/subscribe") || (method == "resources/unsubscribe")) && jsonMember(body, "error").empty()) + { + std::string uri = jsonStringMember(jsonMember(message, "params"), "uri"); + + if (!uri.empty()) + { + std::lock_guard lock(m_stateMutex); + + if (method == "resources/subscribe") { + m_subscriptions.insert(uri); + } else { + m_subscriptions.erase(uri); + } + } + } + + writeMessage(body); +} + +void Bridge::startStream() +{ + bool expected = false; + + if (!m_streamWanted.compare_exchange_strong(expected, true)) { + return; // already running + } + + m_streamThread = std::thread([this]() { streamLoop(); }); +} + +void Bridge::stopStream() +{ + if (!m_streamWanted.load()) { + return; + } + + { + // Shutting the socket down under the thread is what unblocks its read; the thread + // then closes it itself + std::lock_guard lock(m_streamMutex); + + if (m_streamClient) { + m_streamClient->interrupt(); + } + } + + if (m_streamThread.joinable()) { + m_streamThread.join(); + } +} + +void Bridge::streamLoop() +{ + // The server closes the stream when its lifetime backstop expires, so this reopens it + // for as long as the bridge is running. It is also what notices SDRangel coming back + // after the handshake had to be answered without it. + // + // Retries back off. A client that is sitting idle sends nothing, so nothing else here + // ever notices that something is wrong, and a fixed one second retry turns an + // unreachable or unhappy server into hundreds of log lines a minute, for hours. + int retryMs = m_retryMinMs; + + while (m_running.load()) + { + HttpClient client; + std::string error; + bool opened = false; + + if (sessionId().empty() && !openSession()) + { + // Nothing to stream from yet: wait and look again + for (int waited = 0; m_running.load() && (waited < retryMs); waited += 50) { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + + retryMs = std::min(retryMs * 2, m_retryMaxMs); + continue; + } + + if (!client.open(m_options.m_host, m_options.m_port, m_streamTimeoutMs, error)) + { + note(m_options, "event stream cannot connect: " + error); + } + else + { + { + std::lock_guard lock(m_streamMutex); + m_streamClient = &client; + } + + if (client.send("GET", m_options.m_path, headers(true), std::string(), error)) + { + HttpClient::Head head; + + if (!client.readHead(head, error)) + { + note(m_options, "event stream failed: " + error); + } + else if (head.m_status == 404) + { + // The session has been forgotten, which SDRangel restarting does to all of + // them. Only calls coming from the client recovered this before, so an idle + // client left the stream asking after a session that would never come back + note(m_options, "event stream session refused, starting a new one"); + + std::string stale = sessionId(); + + if (!stale.empty()) { + reinitialize(stale); + } + } + else if (head.m_status != 200) + { + note(m_options, "event stream refused with HTTP " + std::to_string(head.m_status)); + } + else + { + note(m_options, "event stream open"); + opened = true; + retryMs = m_retryMinMs; + SseReader reader; + std::string chunk; + + // The server delimits the stream by closing the connection rather than + // chunking it, but a proxy or a later server might chunk, so follow + // whichever framing the response actually used + while (head.m_chunked ? client.readChunk(chunk, error) : client.readSome(chunk, error)) + { + for (const auto& event : reader.feed(chunk)) + { + if (!event.empty()) { + writeMessage(event); + } + } + } + + if (!error.empty()) { + note(m_options, "event stream ended: " + error); + } + } + } + + { + std::lock_guard lock(m_streamMutex); + m_streamClient = nullptr; + } + } + + // Reopening immediately would spin if the server has gone away + for (int waited = 0; m_running.load() && (waited < retryMs); waited += 50) { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + + // A stream that opened and then ended is the normal lifetime backstop, so that starts + // again promptly; anything else waits longer each time + retryMs = opened ? m_retryMinMs : std::min(retryMs * 2, m_retryMaxMs); + } +} + +void Bridge::endSession() +{ + std::string session = sessionId(); + + if (session.empty()) { + return; + } + + HttpClient client; + std::string error; + + if (!client.open(m_options.m_host, m_options.m_port, m_shutdownTimeoutMs, error)) { + return; // going away anyway, and the server expires idle sessions + } + + if (client.send("DELETE", m_options.m_path, headers(false), std::string(), error)) + { + HttpClient::Head head; + std::string body; + + if (client.readHead(head, error)) { + client.readBody(head, body, error); + } + } + + note(m_options, "session ended"); +} + +int Bridge::run() +{ + std::string error; + + if (!HttpClient::startup(error)) + { + warn(error); + return 1; + } + + note(m_options, std::string("relaying to http://") + m_options.m_host + ":" + + std::to_string(m_options.m_port) + m_options.m_path); + + // A worker, and the flag it raises once it has run to completion. A thread that is still + // working is joinable too, so joinable() cannot tell the loop below which of them it is able + // to reap without blocking + struct Worker + { + std::thread m_thread; + std::shared_ptr> m_finished; + }; + + std::vector workers; + std::string line; + + while (std::getline(std::cin, line)) + { + if (!line.empty() && (line.back() == '\r')) { + line.pop_back(); + } + + if (line.empty()) { + continue; + } + + // A thread each, so that a long call such as record_iq does not hold up the + // messages that follow it, cancellation among them + auto finished = std::make_shared>(false); + workers.push_back(Worker{ + std::thread([this, line, finished]() { + handle(line); + finished->store(true); + }), + finished}); + + // Reap only the ones that have finished. Joining a worker that is still inside a + // record_iq, listen, scan or audio call would stop this loop reading input for as long as + // that call runs, which is exactly when a cancellation needs to get through + for (auto worker = workers.begin(); worker != workers.end(); ) + { + if (worker->m_finished->load()) + { + worker->m_thread.join(); + worker = workers.erase(worker); + } + else + { + ++worker; + } + } + } + + note(m_options, "input closed"); + m_running.store(false); + + for (auto& worker : workers) + { + if (worker.m_thread.joinable()) { + worker.m_thread.join(); + } + } + + stopStream(); + endSession(); + HttpClient::cleanup(); + return 0; +} + +int main(int argc, char *argv[]) +{ +#ifndef _WIN32 + // A write to a socket or pipe whose other end has gone must fail, not end the process + signal(SIGPIPE, SIG_IGN); +#endif + + Options options; + + for (int i = 1; i < argc; i++) + { + std::string argument(argv[i]); + auto value = [&](const char *name) -> std::string + { + if (i + 1 >= argc) + { + warn(std::string(name) + " needs a value"); + std::exit(2); + } + + return std::string(argv[++i]); + }; + + if (argument == "--host") + { + std::string host = value("--host"); + + if (!isPlaceholder(host) && !host.empty()) { + options.m_host = host; + } + } + else if (argument == "--port") + { + std::string port = value("--port"); + + if (!isPlaceholder(port) && !port.empty()) { + options.m_port = std::atoi(port.c_str()); + } + } + else if (argument == "--path") + { + std::string path = value("--path"); + + if (!isPlaceholder(path) && !path.empty()) { + options.m_path = path; + } + } + else if (argument == "--token") + { + std::string token = value("--token"); + + // "" is how a shell or a manifest spells an empty value it could not omit + if (!isPlaceholder(token) && (token != "\"\"")) { + options.m_token = token; + } + } + else if (argument == "--verbose") { + options.m_verbose = true; + } else if ((argument == "--version") || (argument == "-v")) { + std::printf("%s\n", versionText); + return 0; + } else if ((argument == "--help") || (argument == "-h")) { + std::printf("%s\n\n", versionText); + std::printf("Relays the MCP stdio transport to SDRangel's HTTP MCP server.\n\n"); + std::printf(" --host
SDRangel's MCP server address (default 127.0.0.1)\n"); + std::printf(" --port SDRangel's MCP server port (default 8092)\n"); + std::printf(" --path Endpoint path (default /mcp)\n"); + std::printf(" --token Bearer token, if the server has one set\n"); + std::printf(" --verbose Report what it is doing on stderr\n"); + return 0; + } else { + warn("unknown argument " + argument); + return 2; + } + } + + if ((options.m_port <= 0) || (options.m_port > 65535)) + { + warn("port must be between 1 and 65535"); + return 2; + } + +#ifdef _WIN32 + // Without this the C runtime turns \n into \r\n on the way out and eats \r on the way + // in, either of which corrupts the message framing + _setmode(_fileno(stdin), _O_BINARY); + _setmode(_fileno(stdout), _O_BINARY); +#endif + + std::ios::sync_with_stdio(false); + + std::string shippedTools = readFile(toolsFile(argv[0])); + + // Trim, so that a trailing newline cannot land in the middle of a JSON-RPC message + while (!shippedTools.empty() && ((shippedTools.back() == '\n') || (shippedTools.back() == '\r'))) { + shippedTools.pop_back(); + } + + if (options.m_verbose && shippedTools.empty()) { + warn("no tools.json beside the executable: no tools until SDRangel is reachable"); + } + + Bridge bridge(options, shippedTools); + return bridge.run(); +} diff --git a/plugins/feature/mcpserver/bridge/readme.md b/plugins/feature/mcpserver/bridge/readme.md index a8ecb025e..bed9d79ae 100644 --- a/plugins/feature/mcpserver/bridge/readme.md +++ b/plugins/feature/mcpserver/bridge/readme.md @@ -1,88 +1,88 @@ -

SDRangel MCP stdio bridge

- -

Introduction

- -Relays the MCP stdio transport to the HTTP transport of the [MCP Server feature](../readme.md), for -clients that can only launch a local server on stdin and stdout. Claude Desktop is the one that -matters: it has no way to connect to an MCP server on `http://127.0.0.1`, since its custom connectors -are fetched from Anthropic's cloud, which cannot reach your machine. - -Without it, those clients need `npx mcp-remote`, which means installing Node.js and hand editing a -JSON configuration file. The bridge is a single executable with no dependencies beyond the C++ -runtime, so it can be shipped inside a Claude Desktop extension bundle (`.mcpb`) and installed with -a double click. - -JSON-RPC messages pass through untouched. This program understands the transport, not the protocol, -so it needs no changes when tools are added or the schema changes. - -

Building

- -It is not built by default, as only a release that ships an extension bundle needs it: - - cmake -S . -B build -DBUILD_MCP_BRIDGE=ON - cmake --build build --target sdrangel-mcp-bridge - -There is no Qt and no SDRangel library in it, and on Windows it links the static runtime, so the -executable stands alone. - -

Packaging

- - cmake -S . -B build -DBUILD_MCP_BUNDLE=ON - cmake --build build --target mcpbundle - -produces `bin/sdrangel--.mcpb`, a Claude Desktop extension holding this -executable, the manifest and an icon. A `.mcpb` is a zip with `manifest.json` at its root, so -CMake builds one on its own; the `mcpb` CLI only adds validation and signing, and requiring -npm to build SDRangel would be a poor trade for that. The bundle is not signed, so Claude -warns that the publisher is unverified when it is installed. - -Both options default to off, so a normal build is untouched. With `BUILD_MCP_BUNDLE=ON` the -bundle is part of `all`, so building the Windows installer picks it up with nothing else to -remember: - - cmake --build build --target package - -

Running

- - sdrangel-mcp-bridge [--host
] [--port ] [--path ] [--token ] [--verbose] - -The defaults match the MCP Server feature's own: `127.0.0.1`, port 8092, path `/mcp` and no token. -`--verbose` reports what it is doing on stderr, which Claude Desktop collects in its logs. - -To use it without an extension bundle, in `%APPDATA%\Claude\claude_desktop_config.json`: - - "mcpServers": { - "sdrangel": { - "command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", - "args": ["--port", "8092"] - } - } - -

How it works

- -Each line arriving on stdin is one JSON-RPC message, and is POSTed to the server on its own -connection and its own thread, so that a long call such as `record_iq` does not hold up the messages -that follow it. Replies are written back to stdout, one line each. - -The server's session id, returned as a header on the reply to `initialize`, is sent on every request -after it, and the negotiated protocol version with it. Once there is a session, a GET is held open -for the server to client event stream, which is where `notifications/resources/updated` arrives for -anything subscribed to with `resources/subscribe`. The server closes that stream when its lifetime -backstop expires, so it is reopened for as long as the bridge runs. When stdin closes, the session is -ended with a DELETE. SDRangel forgets every session when it restarts: the bridge then replays the -client's `initialize` to get a new one, and subscribes again to every resource the client had -subscribed to, so the client sees neither the restart nor a gap in its updates. - -Anything that goes wrong with the transport becomes a JSON-RPC error against the id of the request -that provoked it, rather than a dropped message. The one users will meet is SDRangel not running, -which says so in as many words. - -

Testing

- -The bridge can be driven by hand, which is the quickest way to check it against a running SDRangel: - - echo {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}} | sdrangel-mcp-bridge --verbose - -Worth covering when changing it: a tool call that takes tens of seconds arriving before a quick one, -a `resources/subscribe` followed by a change in SDRangel, and starting the bridge with nothing -listening on the port. +

SDRangel MCP stdio bridge

+ +

Introduction

+ +Relays the MCP stdio transport to the HTTP transport of the [MCP Server feature](../readme.md), for +clients that can only launch a local server on stdin and stdout. Claude Desktop is the one that +matters: it has no way to connect to an MCP server on `http://127.0.0.1`, since its custom connectors +are fetched from Anthropic's cloud, which cannot reach your machine. + +Without it, those clients need `npx mcp-remote`, which means installing Node.js and hand editing a +JSON configuration file. The bridge is a single executable with no dependencies beyond the C++ +runtime, so it can be shipped inside a Claude Desktop extension bundle (`.mcpb`) and installed with +a double click. + +JSON-RPC messages pass through untouched. This program understands the transport, not the protocol, +so it needs no changes when tools are added or the schema changes. + +

Building

+ +It is not built by default, as only a release that ships an extension bundle needs it: + + cmake -S . -B build -DBUILD_MCP_BRIDGE=ON + cmake --build build --target sdrangel-mcp-bridge + +There is no Qt and no SDRangel library in it, and on Windows it links the static runtime, so the +executable stands alone. + +

Packaging

+ + cmake -S . -B build -DBUILD_MCP_BUNDLE=ON + cmake --build build --target mcpbundle + +produces `bin/sdrangel--.mcpb`, a Claude Desktop extension holding this +executable, the manifest and an icon. A `.mcpb` is a zip with `manifest.json` at its root, so +CMake builds one on its own; the `mcpb` CLI only adds validation and signing, and requiring +npm to build SDRangel would be a poor trade for that. The bundle is not signed, so Claude +warns that the publisher is unverified when it is installed. + +Both options default to off, so a normal build is untouched. With `BUILD_MCP_BUNDLE=ON` the +bundle is part of `all`, so building the Windows installer picks it up with nothing else to +remember: + + cmake --build build --target package + +

Running

+ + sdrangel-mcp-bridge [--host
] [--port ] [--path ] [--token ] [--verbose] + +The defaults match the MCP Server feature's own: `127.0.0.1`, port 8092, path `/mcp` and no token. +`--verbose` reports what it is doing on stderr, which Claude Desktop collects in its logs. + +To use it without an extension bundle, in `%APPDATA%\Claude\claude_desktop_config.json`: + + "mcpServers": { + "sdrangel": { + "command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", + "args": ["--port", "8092"] + } + } + +

How it works

+ +Each line arriving on stdin is one JSON-RPC message, and is POSTed to the server on its own +connection and its own thread, so that a long call such as `record_iq` does not hold up the messages +that follow it. Replies are written back to stdout, one line each. + +The server's session id, returned as a header on the reply to `initialize`, is sent on every request +after it, and the negotiated protocol version with it. Once there is a session, a GET is held open +for the server to client event stream, which is where `notifications/resources/updated` arrives for +anything subscribed to with `resources/subscribe`. The server closes that stream when its lifetime +backstop expires, so it is reopened for as long as the bridge runs. When stdin closes, the session is +ended with a DELETE. SDRangel forgets every session when it restarts: the bridge then replays the +client's `initialize` to get a new one, and subscribes again to every resource the client had +subscribed to, so the client sees neither the restart nor a gap in its updates. + +Anything that goes wrong with the transport becomes a JSON-RPC error against the id of the request +that provoked it, rather than a dropped message. The one users will meet is SDRangel not running, +which says so in as many words. + +

Testing

+ +The bridge can be driven by hand, which is the quickest way to check it against a running SDRangel: + + echo {"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}} | sdrangel-mcp-bridge --verbose + +Worth covering when changing it: a tool call that takes tens of seconds arriving before a quick one, +a `resources/subscribe` followed by a change in SDRangel, and starting the bridge with nothing +listening on the port. diff --git a/plugins/feature/mcpserver/mcpservergui.cpp b/plugins/feature/mcpserver/mcpservergui.cpp index 9f1b08e5e..3a4d437d4 100644 --- a/plugins/feature/mcpserver/mcpservergui.cpp +++ b/plugins/feature/mcpserver/mcpservergui.cpp @@ -1,340 +1,340 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#include -#include - -#include "feature/featureuiset.h" -#include "gui/basicfeaturesettingsdialog.h" -#include "gui/dialogpositioner.h" - -#include "ui_mcpservergui.h" -#include "mcpserver.h" -#include "mcpservergui.h" -#include "mcpcodexconfig.h" -#include "mcpclaudeextension.h" - -MCPServerGUI* MCPServerGUI::create(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature) -{ - MCPServerGUI* gui = new MCPServerGUI(pluginAPI, featureUISet, feature); - return gui; -} - -void MCPServerGUI::destroy() -{ - delete this; -} - -void MCPServerGUI::resetToDefaults() -{ - m_settings.resetToDefaults(); - displaySettings(); - applySettings(true); -} - -QByteArray MCPServerGUI::serialize() const -{ - return m_settings.serialize(); -} - -bool MCPServerGUI::deserialize(const QByteArray& data) -{ - if (m_settings.deserialize(data)) - { - m_feature->setWorkspaceIndex(m_settings.m_workspaceIndex); - displaySettings(); - applySettings(true); - return true; - } - else - { - resetToDefaults(); - return false; - } -} - -bool MCPServerGUI::handleMessage(const Message& message) -{ - if (MCPServer::MsgConfigureMCPServer::match(message)) - { - qDebug("MCPServerGUI::handleMessage: MCPServer::MsgConfigureMCPServer"); - const MCPServer::MsgConfigureMCPServer& cfg = (MCPServer::MsgConfigureMCPServer&) message; - - if (cfg.getForce()) { - m_settings = cfg.getSettings(); - } else { - m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings()); - } - - blockApplySettings(true); - displaySettings(); - blockApplySettings(false); - - return true; - } - - return false; -} - -void MCPServerGUI::handleInputMessages() -{ - Message* message; - - while ((message = getInputMessageQueue()->pop())) - { - if (handleMessage(*message)) { - delete message; - } - } -} - -void MCPServerGUI::onWidgetRolled(QWidget* widget, bool rollDown) -{ - (void) widget; - (void) rollDown; - - getRollupContents()->saveState(m_rollupState); -} - -MCPServerGUI::MCPServerGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature, QWidget* parent) : - FeatureGUI(parent), - ui(new Ui::MCPServerGUI), - m_pluginAPI(pluginAPI), - m_featureUISet(featureUISet), - m_doApplySettings(true) -{ - m_feature = feature; - setAttribute(Qt::WA_DeleteOnClose, true); - m_helpURL = "plugins/feature/mcpserver/readme.md"; - RollupContents *rollupContents = getRollupContents(); - ui->setupUi(rollupContents); - rollupContents->arrangeRollups(); - connect(rollupContents, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); - - m_mcpServer = reinterpret_cast(feature); - m_mcpServer->setMessageQueueToGUI(&m_inputMessageQueue); - - m_settings.setRollupState(&m_rollupState); - - connect(this, &MCPServerGUI::customContextMenuRequested, this, &MCPServerGUI::onMenuDialogCalled); - connect(getInputMessageQueue(), &MessageQueue::messageEnqueued, this, &MCPServerGUI::handleInputMessages); - connect(m_mcpServer, &Feature::stateChanged, this, &MCPServerGUI::updateFeatureState); - - connect(&m_statisticsTimer, &QTimer::timeout, this, &MCPServerGUI::updateStatistics); - m_statisticsTimer.start(1000); - - displaySettings(); - applySettings(true); - makeUIConnections(); - updateFeatureState(); - updateStatistics(); - m_resizer.enableChildMouseTracking(); -} - -MCPServerGUI::~MCPServerGUI() -{ - delete ui; -} - -void MCPServerGUI::setWorkspaceIndex(int index) -{ - m_settings.m_workspaceIndex = index; - m_settingsKeys.append("workspaceIndex"); - m_feature->setWorkspaceIndex(index); -} - -void MCPServerGUI::blockApplySettings(bool block) -{ - m_doApplySettings = !block; -} - -void MCPServerGUI::displaySettings() -{ - setTitleColor(m_settings.m_rgbColor); - setWindowTitle(m_settings.m_title); - setTitle(m_settings.m_title); - blockApplySettings(true); - ui->address->setText(m_settings.m_address); - ui->port->setValue(m_settings.m_port); - ui->token->setText(m_settings.m_token); - ui->captureDir->setText(m_settings.m_captureDir); - ui->url->setText(m_mcpServer->getServerURL()); - getRollupContents()->restoreState(m_rollupState); - blockApplySettings(false); -} - -void MCPServerGUI::onMenuDialogCalled(const QPoint &p) -{ - if (m_contextMenuType == ContextMenuType::ContextMenuChannelSettings) - { - BasicFeatureSettingsDialog dialog(this); - dialog.setTitle(m_settings.m_title); - dialog.setUseReverseAPI(m_settings.m_useReverseAPI); - dialog.setReverseAPIAddress(m_settings.m_reverseAPIAddress); - dialog.setReverseAPIPort(m_settings.m_reverseAPIPort); - dialog.setReverseAPIFeatureSetIndex(m_settings.m_reverseAPIFeatureSetIndex); - dialog.setReverseAPIFeatureIndex(m_settings.m_reverseAPIFeatureIndex); - dialog.setDefaultTitle(m_displayedName); - - dialog.move(p); - new DialogPositioner(&dialog, false); - dialog.exec(); - - m_settings.m_title = dialog.getTitle(); - m_settings.m_useReverseAPI = dialog.useReverseAPI(); - m_settings.m_reverseAPIAddress = dialog.getReverseAPIAddress(); - m_settings.m_reverseAPIPort = dialog.getReverseAPIPort(); - m_settings.m_reverseAPIFeatureSetIndex = dialog.getReverseAPIFeatureSetIndex(); - m_settings.m_reverseAPIFeatureIndex = dialog.getReverseAPIFeatureIndex(); - - setTitle(m_settings.m_title); - setTitleColor(m_settings.m_rgbColor); - - m_settingsKeys.append("title"); - m_settingsKeys.append("rgbColor"); - m_settingsKeys.append("useReverseAPI"); - m_settingsKeys.append("reverseAPIAddress"); - m_settingsKeys.append("reverseAPIPort"); - m_settingsKeys.append("reverseAPIFeatureSetIndex"); - m_settingsKeys.append("reverseAPIFeatureIndex"); - - applySettings(); - } - - resetContextMenuType(); -} - -void MCPServerGUI::on_startStop_toggled(bool checked) -{ - if (m_doApplySettings) - { - MCPServer::MsgStartStop *message = MCPServer::MsgStartStop::create(checked); - m_mcpServer->getInputMessageQueue()->push(message); - } -} - -void MCPServerGUI::on_address_editingFinished() -{ - m_settings.m_address = ui->address->text().trimmed(); - m_settingsKeys.append("address"); - ui->url->setText(QString("http://%1:%2/mcp").arg(m_settings.m_address.isEmpty() ? "0.0.0.0" : m_settings.m_address).arg(m_settings.m_port)); - applySettings(); -} - -void MCPServerGUI::on_port_valueChanged(int value) -{ - m_settings.m_port = value; - m_settingsKeys.append("port"); - ui->url->setText(QString("http://%1:%2/mcp").arg(m_settings.m_address.isEmpty() ? "0.0.0.0" : m_settings.m_address).arg(m_settings.m_port)); - applySettings(); -} - -void MCPServerGUI::on_token_editingFinished() -{ - m_settings.m_token = ui->token->text().trimmed(); - m_settingsKeys.append("token"); - applySettings(); -} - -void MCPServerGUI::on_captureDir_editingFinished() -{ - m_settings.m_captureDir = ui->captureDir->text().trimmed(); - m_settingsKeys.append("captureDir"); - applySettings(); -} - -void MCPServerGUI::on_captureDirBrowse_clicked() -{ - QString dir = QFileDialog::getExistingDirectory(this, tr("Capture directory"), m_settings.m_captureDir); - - if (!dir.isEmpty()) - { - m_settings.m_captureDir = dir; - ui->captureDir->setText(dir); - m_settingsKeys.append("captureDir"); - applySettings(); - } -} - -void MCPServerGUI::on_addToCodex_clicked() -{ - // The settings hold what the server is configured with, which is what a client has to use - const QString url = MCPCodexConfig::serverUrl(m_settings.m_address, m_settings.m_port); - QString message; - MCPCodexConfig::Result result = MCPCodexConfig::addServer("sdrangel", url, m_settings.m_token, message); - - if (result == MCPCodexConfig::Failed) - { - QMessageBox::critical(this, tr("Add to Codex"), message); - } - else - { - // Codex reads its configuration once, at startup - QMessageBox::information(this, tr("Add to Codex"), - tr("%1\n\nRestart Codex for it to see the server.").arg(message)); - } -} - -void MCPServerGUI::on_addToClaude_clicked() -{ - QString message; - MCPClaudeExtension::Result result = MCPClaudeExtension::install(message); - - if (result == MCPClaudeExtension::Launched) { - QMessageBox::information(this, tr("Add to Claude Desktop"), message); - } else { - QMessageBox::warning(this, tr("Add to Claude Desktop"), message); - } -} - -void MCPServerGUI::updateFeatureState() -{ - updateStartStopButton(ui->startStop); -} - -void MCPServerGUI::updateStatistics() -{ - int streams = m_mcpServer->getStreamCount(); - ui->requests->setText(streams > 0 - ? QString("Requests: %1 Streams: %2").arg(m_mcpServer->getRequestCount()).arg(streams) - : QString("Requests: %1").arg(m_mcpServer->getRequestCount())); - ui->lastRequest->setText(m_mcpServer->getLastRequest()); -} - -void MCPServerGUI::applySettings(bool force) -{ - if (m_doApplySettings) - { - MCPServer::MsgConfigureMCPServer* message = MCPServer::MsgConfigureMCPServer::create(m_settings, m_settingsKeys, force); - m_mcpServer->getInputMessageQueue()->push(message); - } - - m_settingsKeys.clear(); -} - -void MCPServerGUI::makeUIConnections() -{ - QObject::connect(ui->startStop, &ButtonSwitch::toggled, this, &MCPServerGUI::on_startStop_toggled); - QObject::connect(ui->address, &QLineEdit::editingFinished, this, &MCPServerGUI::on_address_editingFinished); - QObject::connect(ui->port, qOverload(&QSpinBox::valueChanged), this, &MCPServerGUI::on_port_valueChanged); - QObject::connect(ui->token, &QLineEdit::editingFinished, this, &MCPServerGUI::on_token_editingFinished); - QObject::connect(ui->captureDir, &QLineEdit::editingFinished, this, &MCPServerGUI::on_captureDir_editingFinished); - QObject::connect(ui->captureDirBrowse, &QToolButton::clicked, this, &MCPServerGUI::on_captureDirBrowse_clicked); - QObject::connect(ui->addToCodex, &QPushButton::clicked, this, &MCPServerGUI::on_addToCodex_clicked); - QObject::connect(ui->addToClaude, &QPushButton::clicked, this, &MCPServerGUI::on_addToClaude_clicked); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "feature/featureuiset.h" +#include "gui/basicfeaturesettingsdialog.h" +#include "gui/dialogpositioner.h" + +#include "ui_mcpservergui.h" +#include "mcpserver.h" +#include "mcpservergui.h" +#include "mcpcodexconfig.h" +#include "mcpclaudeextension.h" + +MCPServerGUI* MCPServerGUI::create(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature) +{ + MCPServerGUI* gui = new MCPServerGUI(pluginAPI, featureUISet, feature); + return gui; +} + +void MCPServerGUI::destroy() +{ + delete this; +} + +void MCPServerGUI::resetToDefaults() +{ + m_settings.resetToDefaults(); + displaySettings(); + applySettings(true); +} + +QByteArray MCPServerGUI::serialize() const +{ + return m_settings.serialize(); +} + +bool MCPServerGUI::deserialize(const QByteArray& data) +{ + if (m_settings.deserialize(data)) + { + m_feature->setWorkspaceIndex(m_settings.m_workspaceIndex); + displaySettings(); + applySettings(true); + return true; + } + else + { + resetToDefaults(); + return false; + } +} + +bool MCPServerGUI::handleMessage(const Message& message) +{ + if (MCPServer::MsgConfigureMCPServer::match(message)) + { + qDebug("MCPServerGUI::handleMessage: MCPServer::MsgConfigureMCPServer"); + const MCPServer::MsgConfigureMCPServer& cfg = (MCPServer::MsgConfigureMCPServer&) message; + + if (cfg.getForce()) { + m_settings = cfg.getSettings(); + } else { + m_settings.applySettings(cfg.getSettingsKeys(), cfg.getSettings()); + } + + blockApplySettings(true); + displaySettings(); + blockApplySettings(false); + + return true; + } + + return false; +} + +void MCPServerGUI::handleInputMessages() +{ + Message* message; + + while ((message = getInputMessageQueue()->pop())) + { + if (handleMessage(*message)) { + delete message; + } + } +} + +void MCPServerGUI::onWidgetRolled(QWidget* widget, bool rollDown) +{ + (void) widget; + (void) rollDown; + + getRollupContents()->saveState(m_rollupState); +} + +MCPServerGUI::MCPServerGUI(PluginAPI* pluginAPI, FeatureUISet *featureUISet, Feature *feature, QWidget* parent) : + FeatureGUI(parent), + ui(new Ui::MCPServerGUI), + m_pluginAPI(pluginAPI), + m_featureUISet(featureUISet), + m_doApplySettings(true) +{ + m_feature = feature; + setAttribute(Qt::WA_DeleteOnClose, true); + m_helpURL = "plugins/feature/mcpserver/readme.md"; + RollupContents *rollupContents = getRollupContents(); + ui->setupUi(rollupContents); + rollupContents->arrangeRollups(); + connect(rollupContents, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); + + m_mcpServer = reinterpret_cast(feature); + m_mcpServer->setMessageQueueToGUI(&m_inputMessageQueue); + + m_settings.setRollupState(&m_rollupState); + + connect(this, &MCPServerGUI::customContextMenuRequested, this, &MCPServerGUI::onMenuDialogCalled); + connect(getInputMessageQueue(), &MessageQueue::messageEnqueued, this, &MCPServerGUI::handleInputMessages); + connect(m_mcpServer, &Feature::stateChanged, this, &MCPServerGUI::updateFeatureState); + + connect(&m_statisticsTimer, &QTimer::timeout, this, &MCPServerGUI::updateStatistics); + m_statisticsTimer.start(1000); + + displaySettings(); + applySettings(true); + makeUIConnections(); + updateFeatureState(); + updateStatistics(); + m_resizer.enableChildMouseTracking(); +} + +MCPServerGUI::~MCPServerGUI() +{ + delete ui; +} + +void MCPServerGUI::setWorkspaceIndex(int index) +{ + m_settings.m_workspaceIndex = index; + m_settingsKeys.append("workspaceIndex"); + m_feature->setWorkspaceIndex(index); +} + +void MCPServerGUI::blockApplySettings(bool block) +{ + m_doApplySettings = !block; +} + +void MCPServerGUI::displaySettings() +{ + setTitleColor(m_settings.m_rgbColor); + setWindowTitle(m_settings.m_title); + setTitle(m_settings.m_title); + blockApplySettings(true); + ui->address->setText(m_settings.m_address); + ui->port->setValue(m_settings.m_port); + ui->token->setText(m_settings.m_token); + ui->captureDir->setText(m_settings.m_captureDir); + ui->url->setText(m_mcpServer->getServerURL()); + getRollupContents()->restoreState(m_rollupState); + blockApplySettings(false); +} + +void MCPServerGUI::onMenuDialogCalled(const QPoint &p) +{ + if (m_contextMenuType == ContextMenuType::ContextMenuChannelSettings) + { + BasicFeatureSettingsDialog dialog(this); + dialog.setTitle(m_settings.m_title); + dialog.setUseReverseAPI(m_settings.m_useReverseAPI); + dialog.setReverseAPIAddress(m_settings.m_reverseAPIAddress); + dialog.setReverseAPIPort(m_settings.m_reverseAPIPort); + dialog.setReverseAPIFeatureSetIndex(m_settings.m_reverseAPIFeatureSetIndex); + dialog.setReverseAPIFeatureIndex(m_settings.m_reverseAPIFeatureIndex); + dialog.setDefaultTitle(m_displayedName); + + dialog.move(p); + new DialogPositioner(&dialog, false); + dialog.exec(); + + m_settings.m_title = dialog.getTitle(); + m_settings.m_useReverseAPI = dialog.useReverseAPI(); + m_settings.m_reverseAPIAddress = dialog.getReverseAPIAddress(); + m_settings.m_reverseAPIPort = dialog.getReverseAPIPort(); + m_settings.m_reverseAPIFeatureSetIndex = dialog.getReverseAPIFeatureSetIndex(); + m_settings.m_reverseAPIFeatureIndex = dialog.getReverseAPIFeatureIndex(); + + setTitle(m_settings.m_title); + setTitleColor(m_settings.m_rgbColor); + + m_settingsKeys.append("title"); + m_settingsKeys.append("rgbColor"); + m_settingsKeys.append("useReverseAPI"); + m_settingsKeys.append("reverseAPIAddress"); + m_settingsKeys.append("reverseAPIPort"); + m_settingsKeys.append("reverseAPIFeatureSetIndex"); + m_settingsKeys.append("reverseAPIFeatureIndex"); + + applySettings(); + } + + resetContextMenuType(); +} + +void MCPServerGUI::on_startStop_toggled(bool checked) +{ + if (m_doApplySettings) + { + MCPServer::MsgStartStop *message = MCPServer::MsgStartStop::create(checked); + m_mcpServer->getInputMessageQueue()->push(message); + } +} + +void MCPServerGUI::on_address_editingFinished() +{ + m_settings.m_address = ui->address->text().trimmed(); + m_settingsKeys.append("address"); + ui->url->setText(QString("http://%1:%2/mcp").arg(m_settings.m_address.isEmpty() ? "0.0.0.0" : m_settings.m_address).arg(m_settings.m_port)); + applySettings(); +} + +void MCPServerGUI::on_port_valueChanged(int value) +{ + m_settings.m_port = value; + m_settingsKeys.append("port"); + ui->url->setText(QString("http://%1:%2/mcp").arg(m_settings.m_address.isEmpty() ? "0.0.0.0" : m_settings.m_address).arg(m_settings.m_port)); + applySettings(); +} + +void MCPServerGUI::on_token_editingFinished() +{ + m_settings.m_token = ui->token->text().trimmed(); + m_settingsKeys.append("token"); + applySettings(); +} + +void MCPServerGUI::on_captureDir_editingFinished() +{ + m_settings.m_captureDir = ui->captureDir->text().trimmed(); + m_settingsKeys.append("captureDir"); + applySettings(); +} + +void MCPServerGUI::on_captureDirBrowse_clicked() +{ + QString dir = QFileDialog::getExistingDirectory(this, tr("Capture directory"), m_settings.m_captureDir); + + if (!dir.isEmpty()) + { + m_settings.m_captureDir = dir; + ui->captureDir->setText(dir); + m_settingsKeys.append("captureDir"); + applySettings(); + } +} + +void MCPServerGUI::on_addToCodex_clicked() +{ + // The settings hold what the server is configured with, which is what a client has to use + const QString url = MCPCodexConfig::serverUrl(m_settings.m_address, m_settings.m_port); + QString message; + MCPCodexConfig::Result result = MCPCodexConfig::addServer("sdrangel", url, m_settings.m_token, message); + + if (result == MCPCodexConfig::Failed) + { + QMessageBox::critical(this, tr("Add to Codex"), message); + } + else + { + // Codex reads its configuration once, at startup + QMessageBox::information(this, tr("Add to Codex"), + tr("%1\n\nRestart Codex for it to see the server.").arg(message)); + } +} + +void MCPServerGUI::on_addToClaude_clicked() +{ + QString message; + MCPClaudeExtension::Result result = MCPClaudeExtension::install(message); + + if (result == MCPClaudeExtension::Launched) { + QMessageBox::information(this, tr("Add to Claude Desktop"), message); + } else { + QMessageBox::warning(this, tr("Add to Claude Desktop"), message); + } +} + +void MCPServerGUI::updateFeatureState() +{ + updateStartStopButton(ui->startStop); +} + +void MCPServerGUI::updateStatistics() +{ + int streams = m_mcpServer->getStreamCount(); + ui->requests->setText(streams > 0 + ? QString("Requests: %1 Streams: %2").arg(m_mcpServer->getRequestCount()).arg(streams) + : QString("Requests: %1").arg(m_mcpServer->getRequestCount())); + ui->lastRequest->setText(m_mcpServer->getLastRequest()); +} + +void MCPServerGUI::applySettings(bool force) +{ + if (m_doApplySettings) + { + MCPServer::MsgConfigureMCPServer* message = MCPServer::MsgConfigureMCPServer::create(m_settings, m_settingsKeys, force); + m_mcpServer->getInputMessageQueue()->push(message); + } + + m_settingsKeys.clear(); +} + +void MCPServerGUI::makeUIConnections() +{ + QObject::connect(ui->startStop, &ButtonSwitch::toggled, this, &MCPServerGUI::on_startStop_toggled); + QObject::connect(ui->address, &QLineEdit::editingFinished, this, &MCPServerGUI::on_address_editingFinished); + QObject::connect(ui->port, qOverload(&QSpinBox::valueChanged), this, &MCPServerGUI::on_port_valueChanged); + QObject::connect(ui->token, &QLineEdit::editingFinished, this, &MCPServerGUI::on_token_editingFinished); + QObject::connect(ui->captureDir, &QLineEdit::editingFinished, this, &MCPServerGUI::on_captureDir_editingFinished); + QObject::connect(ui->captureDirBrowse, &QToolButton::clicked, this, &MCPServerGUI::on_captureDirBrowse_clicked); + QObject::connect(ui->addToCodex, &QPushButton::clicked, this, &MCPServerGUI::on_addToCodex_clicked); + QObject::connect(ui->addToClaude, &QPushButton::clicked, this, &MCPServerGUI::on_addToClaude_clicked); +} diff --git a/plugins/feature/mcpserver/mcptools.cpp b/plugins/feature/mcpserver/mcptools.cpp index 8d30765f0..1c838bc2f 100644 --- a/plugins/feature/mcpserver/mcptools.cpp +++ b/plugins/feature/mcpserver/mcptools.cpp @@ -1,6184 +1,6184 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "SWGErrorResponse.h" -#include "SWGSuccessResponse.h" -#include "SWGInstanceSummaryResponse.h" -#include "SWGInstanceDevicesResponse.h" -#include "SWGInstanceChannelsResponse.h" -#include "SWGInstanceFeaturesResponse.h" -#include "SWGDeviceSetList.h" -#include "SWGDeviceSet.h" -#include "SWGDeviceListItem.h" -#include "SWGDeviceSettings.h" -#include "SWGDeviceState.h" -#include "SWGDeviceReport.h" -#include "SWGDeviceActions.h" -#include "SWGChannelSettings.h" -#include "SWGChannelReport.h" -#include "SWGChannelActions.h" -#include "SWGChannelsDetail.h" -#include "SWGFeatureSet.h" -#include "SWGFeatureSettings.h" -#include "SWGFeatureReport.h" -#include "SWGFeatureActions.h" -#include "SWGPresets.h" -#include "SWGPresetGroup.h" -#include "SWGPresetItem.h" -#include "SWGPresetTransfer.h" -#include "SWGPresetIdentifier.h" -#include "SWGConfigurations.h" -#include "SWGConfigurationIdentifier.h" -#include "SWGWorkspaceInfo.h" -#include "SWGWorkspaceActions.h" -#include "SWGWindowList.h" -#include "SWGGLSpectrum.h" -#include "SWGGLSpectrumReport.h" -#include "SWGSpectrumActions.h" -#include "SWGGLSpectrumData.h" -#include "SWGGLSpectrumHistory.h" -#include "SWGSpectrumHistorySignal.h" -#include "SWGAudioDevices.h" -#include "SWGLocationInformation.h" - -#include "maincore.h" -#include "device/deviceset.h" -#include "channel/channelapi.h" -#include "device/deviceapi.h" -#include "feature/feature.h" -#include "feature/featureset.h" -#include "webapi/webapiadapterinterface.h" -#include "webapi/webapiutils.h" - -#include "mcpstreams.h" -#include "mcptools.h" - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -namespace { - -QJsonObject toJson(SWGSDRangel::SWGObject& object) -{ - QJsonObject *obj = object.asJsonObject(); - QJsonObject result = *obj; - delete obj; - return result; -} - -QString compact(const QJsonValue& value) -{ - if (value.isObject()) { - return QString(QJsonDocument(value.toObject()).toJson(QJsonDocument::Compact)); - } else if (value.isArray()) { - return QString(QJsonDocument(value.toArray()).toJson(QJsonDocument::Compact)); - } else if (value.isString()) { - return value.toString(); - } else { - return QString(QJsonDocument(QJsonArray({value})).toJson(QJsonDocument::Compact)); - } -} - -// Throws if the Web API call failed -void check(int httpRC, SWGSDRangel::SWGErrorResponse& error, const QString& what) -{ - if (httpRC / 100 != 2) - { - QString message = error.getMessage() ? *error.getMessage() : QString(); - throw MCPToolError(QString("%1 failed (HTTP %2)%3").arg(what).arg(httpRC).arg(message.isEmpty() ? "" : ": " + message)); - } -} - -// Argument access. Accepts numbers given as strings, as models sometimes do. -bool hasArg(const QJsonObject& args, const QString& key) -{ - return args.contains(key) && !args[key].isNull() && !args[key].isUndefined(); -} - -// Models write booleans as JSON booleans mostly, but also as "true"/"false" strings and as 0/1, -// and QJsonValue::toBool answers its default for anything but a JSON boolean, which turned -// replace "false" into true. Absent, null and anything unreadable give the default -bool argBool(const QJsonObject& args, const QString& key, bool defaultValue) -{ - if (!hasArg(args, key)) { - return defaultValue; - } - - const QJsonValue value = args.value(key); - - if (value.isBool()) { - return value.toBool(); - } - - if (value.isDouble()) { - return value.toDouble() != 0.0; - } - - if (value.isString()) - { - const QString text = value.toString().trimmed().toLower(); - - if ((text == "true") || (text == "1") || (text == "yes") || (text == "on")) { - return true; - } - - if ((text == "false") || (text == "0") || (text == "no") || (text == "off") || text.isEmpty()) { - return false; - } - } - - return defaultValue; -} - -int argInt(const QJsonObject& args, const QString& key, bool required = true, int defaultValue = 0) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isDouble()) { - return (int) value.toDouble(); - } - - bool ok; - int result = value.toString().trimmed().toInt(&ok); - - if (!ok) - { - double d = value.toString().trimmed().toDouble(&ok); - - if (ok) { - return (int) d; - } - - throw MCPToolError(QString("Argument %1 must be an integer").arg(key)); - } - - return result; -} - -qint64 argInt64(const QJsonObject& args, const QString& key, bool required = true, qint64 defaultValue = 0) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isDouble()) { - return (qint64) value.toDouble(); - } - - bool ok; - double d = value.toString().trimmed().toDouble(&ok); - - if (!ok) { - throw MCPToolError(QString("Argument %1 must be a number").arg(key)); - } - - return (qint64) d; -} - -double argDouble(const QJsonObject& args, const QString& key, bool required = true, double defaultValue = 0.0) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isDouble()) { - return value.toDouble(); - } - - bool ok; - double d = value.toString().trimmed().toDouble(&ok); - - if (!ok) { - throw MCPToolError(QString("Argument %1 must be a number").arg(key)); - } - - return d; -} - -QString argString(const QJsonObject& args, const QString& key, bool required = true, const QString& defaultValue = QString()) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isString()) { - return value.toString(); - } else if (value.isDouble()) { - return QString::number(value.toDouble(), 'g', 15); - } else { - return compact(value); - } -} - -QJsonObject argObject(const QJsonObject& args, const QString& key, bool required = true) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return QJsonObject(); - } - - QJsonValue value = args[key]; - - if (value.isObject()) { - return value.toObject(); - } - - // Tolerate an object passed as a JSON string - if (value.isString()) - { - QJsonDocument doc = QJsonDocument::fromJson(value.toString().toUtf8()); - - if (doc.isObject()) { - return doc.object(); - } - } - - throw MCPToolError(QString("Argument %1 must be a JSON object").arg(key)); -} - -// direction: "rx" / "tx" / "mimo" or 0 / 1 / 2 -int argDirection(const QJsonObject& args, const QString& key = "direction", bool required = false, int defaultValue = 0) -{ - if (!hasArg(args, key)) - { - if (required) { - throw MCPToolError(QString("Missing required argument: %1").arg(key)); - } - - return defaultValue; - } - - QJsonValue value = args[key]; - - if (value.isDouble()) { - return (int) value.toDouble(); - } - - QString s = value.toString().trimmed().toLower(); - - if ((s == "rx") || (s == "0") || (s == "receive") || (s == "source")) { - return 0; - } else if ((s == "tx") || (s == "1") || (s == "transmit") || (s == "sink")) { - return 1; - } else if ((s == "mimo") || (s == "2")) { - return 2; - } - - throw MCPToolError(QString("Argument %1 must be \"rx\", \"tx\" or \"mimo\"").arg(key)); -} - -QString directionName(int direction) -{ - switch (direction) - { - case 0: return "rx"; - case 1: return "tx"; - case 2: return "mimo"; - default: return QString::number(direction); - } -} - -// JSON schema builders -QJsonObject prop(const QString& type, const QString& description) -{ - QJsonObject p; - p["type"] = type; - p["description"] = description; - return p; -} - -QJsonObject intProp(const QString& description) { return prop("integer", description); } -QJsonObject numProp(const QString& description) { return prop("number", description); } -QJsonObject strProp(const QString& description) { return prop("string", description); } -QJsonObject objProp(const QString& description) { return prop("object", description); } - -QJsonObject enumProp(const QString& description, const QStringList& values) -{ - QJsonObject p = strProp(description); - p["enum"] = QJsonArray::fromStringList(values); - return p; -} - -QJsonObject directionProp(const QString& description) -{ - return enumProp(description, {"rx", "tx", "mimo"}); -} - -// Adds the bounds a handler enforces at runtime to the schema, so a client can see them -QJsonObject bounded(QJsonObject property, double minimum, double maximum) -{ - property["minimum"] = minimum; - property["maximum"] = maximum; - return property; -} - -QJsonObject schema(const QJsonObject& properties, const QStringList& required = QStringList()) -{ - QJsonObject s; - s["type"] = "object"; - s["properties"] = properties; - s["required"] = QJsonArray::fromStringList(required); - s["additionalProperties"] = false; - return s; -} - -const QJsonObject deviceSetIndexProp = intProp("Index of the device set (0 for R0, the first device set)"); -const QJsonObject channelIndexProp = intProp("Index of the channel within the device set"); -const QJsonObject featureIndexProp = intProp("Index of the feature within the feature set"); - -// Settings keys in the form used by the Web API PATCH: nested keys are dotted, array elements indexed -void extractKeys(const QJsonObject& json, QStringList& keys, const QString& prefix = QString()) -{ - for (const QString& key : json.keys()) - { - QString full = prefix.isEmpty() ? key : prefix + "." + key; - keys.append(full); - - if (json[key].isObject()) - { - extractKeys(json[key].toObject(), keys, full); - } - else if (json[key].isArray()) - { - QJsonArray array = json[key].toArray(); - - for (int i = 0; i < array.count(); i++) - { - QString element = QString("%1[%2]").arg(full).arg(i); - keys.append(element); - - if (array.at(i).isObject()) { - extractKeys(array.at(i).toObject(), keys, element); - } - } - } - } -} - -// Applies patch on top of target. Objects are merged recursively, everything else replaced. -// Keys absent from target are reported (they may still be valid: empty strings are not serialized). -void mergeInto(QJsonObject& target, const QJsonObject& patch, QStringList& unknownKeys, const QString& prefix = QString()) -{ - for (const QString& key : patch.keys()) - { - QString full = prefix.isEmpty() ? key : prefix + "." + key; - - if (!target.contains(key)) { - unknownKeys.append(full); - } - - if (patch[key].isObject() && target[key].isObject()) - { - QJsonObject sub = target[key].toObject(); - mergeInto(sub, patch[key].toObject(), unknownKeys, full); - target[key] = sub; - } - else - { - target[key] = patch[key]; - } - } -} - -int leadingSpaces(const QString& line) -{ - int count = 0; - - while ((count < line.length()) && (line.at(count) == ' ')) { - count++; - } - - return count; -} - -// Reads the property names and types out of one swagger definition. Only the properties of the -// definition itself are taken: the attributes of a property sit two spaces further in, so an -// items: block of an array cannot be mistaken for the array's own type. -SettingsSchema parseSettingsSchema(const QString& yaml) -{ - SettingsSchema schema; - int propertiesIndent = -1; - int nameIndent = -1; - QString property; - - for (const QString& line : yaml.split('\n')) - { - QString text = line.trimmed(); - - if (text.isEmpty() || text.startsWith('#')) { - continue; - } - - int indent = leadingSpaces(line); - - if (propertiesIndent < 0) - { - if (text == "properties:") { - propertiesIndent = indent; - } - - continue; - } - - if (indent <= propertiesIndent) { - break; // out of the properties block and into the next section of the definition - } - - if (nameIndent < 0) { - nameIndent = indent; - } - - if (indent == nameIndent) - { - if (text.endsWith(':')) - { - property = text.left(text.length() - 1); - schema.m_types.insert(property, QString()); - } - else - { - property.clear(); - } - } - else if ((indent == nameIndent + 2) && !property.isEmpty()) - { - if (text.startsWith("type:")) { - schema.m_types[property] = text.mid(5).trimmed(); - } else if (text.startsWith("$ref:") && schema.m_types.value(property).isEmpty()) { - schema.m_types[property] = "object"; - } - } - } - - schema.m_known = !schema.m_types.isEmpty(); - return schema; -} - -// Checks a patch against the schema and returns it with the one conversion worth making. Values -// are checked here rather than left to the SWG object, whose setValue() turns a string into zero -// without complaint: "rfBandwidth": "wide" would otherwise stop the channel demodulating and be -// reported as a successful change. -QJsonObject checkAgainstSchema(const QJsonObject& patch, const SettingsSchema& schema, - QStringList& unknownKeys, QStringList& typeErrors) -{ - QJsonObject checked; - - for (const QString& key : patch.keys()) - { - QJsonValue value = patch[key]; - - if (!schema.m_types.contains(key)) - { - unknownKeys.append(key); - checked[key] = value; - continue; - } - - QString type = schema.m_types[key]; - bool numeric = (type == "integer") || (type == "number"); - - if (numeric && value.isBool()) - { - // Unambiguous and lossless, and the natural way to write a 0/1 flag - checked[key] = value.toBool() ? 1 : 0; - continue; - } - - bool ok = true; - - if (numeric) { - ok = value.isDouble(); - } else if (type == "string") { - ok = value.isString(); - } else if (type == "array") { - ok = value.isArray(); - } else if (type == "object") { - ok = value.isObject(); - } - - if (!ok) - { - QString got = value.isString() ? "string" : - value.isDouble() ? "number" : - value.isBool() ? "boolean" : - value.isArray() ? "array" : - value.isObject() ? "object" : "null"; - typeErrors.append(QString("%1 expects %2 but was given a %3 (%4)") - .arg(key).arg(type).arg(got).arg(compact(QJsonObject{{key, value}}))); - } - - checked[key] = value; - } - - return checked; -} - -// The key holding the type specific settings, e.g. "rtlSdrSettings" or "ADSBDemodSettings" -QString findSettingsKey(const QJsonObject& json) -{ - for (const QString& key : json.keys()) - { - if (key.endsWith("Settings") && json[key].isObject()) { - return key; - } - } - - return QString(); -} - -// Generic settings patch: read current settings, merge the partial object given by the model -// into the type specific sub-object, then PATCH with the list of changed keys. -template -QJsonObject applySettingsPatch( - const std::function& get, - const std::function& put, - const QJsonObject& partial, - const QString& what, - const std::function& schemaFor) -{ - SWGSDRangel::SWGErrorResponse error; - error.init(); - SWG current; - check(get(current, error), error, "Get " + what); - QJsonObject json = toJson(current); - QString settingsKey = findSettingsKey(json); - - if (settingsKey.isEmpty()) { - throw MCPToolError(QString("Cannot find settings object in current %1: %2").arg(what).arg(compact(json))); - } - - QJsonObject subPartial; - - if (partial.contains(settingsKey)) - { - subPartial = partial[settingsKey].toObject(); - } - else - { - for (const QString& key : partial.keys()) - { - if (key.endsWith("Settings") && partial[key].isObject()) { - throw MCPToolError(QString("Settings object key %1 does not match the current type. Expected %2 or the bare settings object").arg(key).arg(settingsKey)); - } - } - - subPartial = partial; - } - - if (subPartial.isEmpty()) { - throw MCPToolError("No settings given"); - } - - QStringList unknownKeys; - SettingsSchema schema = schemaFor(settingsKey); - - if (schema.m_known) - { - QStringList typeErrors; - subPartial = checkAgainstSchema(subPartial, schema, unknownKeys, typeErrors); - - if (!typeErrors.isEmpty()) - { - throw MCPToolError(QString("Wrong value type for %1: %2. Numbers must be given as JSON " - "numbers, not strings. Nothing was changed.").arg(settingsKey).arg(typeErrors.join("; "))); - } - } - - QJsonObject sub = json[settingsKey].toObject(); - QStringList merged; - mergeInto(sub, subPartial, merged); - json[settingsKey] = sub; - - if (!schema.m_known) - { - // Without a schema the only test left is whether the key is in the current settings, which - // misses any string setting that is currently empty. Better than nothing, but not by much - unknownKeys = merged; - } - - QStringList keys; - extractKeys(subPartial, keys); - - SWG request; - request.fromJsonObject(json); - error.init(); - check(put(keys, request, error), error, "Set " + what); - - // Reply with only what was asked for, read back from the object that was sent. Echoing - // the whole settings block cost a client about 500 tokens per call, carried for the rest - // of the conversation, to confirm a one key change. - QJsonObject after = toJson(request)[settingsKey].toObject(); - QJsonObject changed; - - for (const QString& key : subPartial.keys()) - { - if (after.contains(key)) { - changed[key] = after[key]; - } - } - - QJsonObject result; - result["changed"] = changed; - - if (!unknownKeys.isEmpty()) { - result["warning"] = QString("Ignored unknown keys: %1. describe_settings lists the valid ones.").arg(unknownKeys.join(", ")); - } - - return result; -} - -QString capitalize(const QString& s) -{ - return s.isEmpty() ? s : s.at(0).toUpper() + s.mid(1); -} - -// The plugin lists carry a URI, a version and an index per entry that no caller needs. Each -// becomes one string: the id the other tools take, with the display name in brackets when it -// says something the id does not. -// Features with no run state: they work from the moment they are configured. Some answer the run -// request with 501 and the rest accept it and stay idle, so neither the request nor the state that -// follows it tells them apart from a feature that is slow to start -const QStringList passiveFeatureTypes = { - "AIS", "AMBE", "AntennaTools", "APRS", "FreqDisplay", "LimeRFE", "Map", "Radiosonde", - "RemoteControl", "SkyMap" -}; - -bool isPassiveFeature(const QString& featureType) -{ - return passiveFeatureTypes.contains(featureType); -} - -QJsonArray idsAndNames(const QJsonArray& plugins) -{ - QJsonArray out; - - for (const QJsonValue& v : plugins) - { - QJsonObject p = v.toObject(); - QString id = p["id"].toString(); - QString name = p["name"].toString(); - - if (!name.isEmpty() && (name.compare(id, Qt::CaseInsensitive) != 0)) { - out.append(QString("%1 (%2)").arg(id).arg(name)); - } else { - out.append(id); - } - } - - return out; -} - -} // namespace - -// --------------------------------------------------------------------------- -// Event counter -// --------------------------------------------------------------------------- - -MCPEventCounter::MCPEventCounter() : - m_deviceSetAdded(0), - m_deviceSetRemoved(0), - m_deviceChanged(0), - m_channelAdded(0), - m_channelRemoved(0), - m_featureAdded(0), - m_featureRemoved(0) -{ - MainCore *mainCore = MainCore::instance(); - connect(mainCore, &MainCore::deviceSetAdded, this, &MCPEventCounter::onDeviceSetAdded); - connect(mainCore, &MainCore::deviceSetRemoved, this, &MCPEventCounter::onDeviceSetRemoved); - connect(mainCore, &MainCore::deviceChanged, this, &MCPEventCounter::onDeviceChanged); - connect(mainCore, &MainCore::channelAdded, this, &MCPEventCounter::onChannelAdded); - connect(mainCore, &MainCore::channelRemoved, this, &MCPEventCounter::onChannelRemoved); - connect(mainCore, &MainCore::featureAdded, this, &MCPEventCounter::onFeatureAdded); - connect(mainCore, &MainCore::featureRemoved, this, &MCPEventCounter::onFeatureRemoved); -} - -void MCPEventCounter::onDeviceSetAdded(int index, DeviceAPI *device) -{ - (void) index; - (void) device; - m_deviceSetAdded.fetchAndAddRelease(1); -} - -void MCPEventCounter::onDeviceSetRemoved(int index) -{ - (void) index; - m_deviceSetRemoved.fetchAndAddRelease(1); -} - -void MCPEventCounter::onDeviceChanged(int index) -{ - (void) index; - m_deviceChanged.fetchAndAddRelease(1); -} - -void MCPEventCounter::onChannelAdded(int deviceSetIndex, ChannelAPI *channel) -{ - (void) deviceSetIndex; - (void) channel; - m_channelAdded.fetchAndAddRelease(1); -} - -void MCPEventCounter::onChannelRemoved(int deviceSetIndex, ChannelAPI *channel) -{ - (void) deviceSetIndex; - (void) channel; - m_channelRemoved.fetchAndAddRelease(1); -} - -void MCPEventCounter::onFeatureAdded(int featureSetIndex, Feature *feature) -{ - (void) featureSetIndex; - (void) feature; - m_featureAdded.fetchAndAddRelease(1); -} - -void MCPEventCounter::onFeatureRemoved(int featureSetIndex, Feature *feature) -{ - (void) featureSetIndex; - (void) feature; - m_featureRemoved.fetchAndAddRelease(1); -} - -// --------------------------------------------------------------------------- -// Registry -// --------------------------------------------------------------------------- - -MCPTools::MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface) : - m_adapter(webAPIAdapterInterface), - m_capture(webAPIAdapterInterface), - m_streams(nullptr), - m_ownerFeature(nullptr), - m_stopping(0), - m_yamlLoaded(false) -{ - registerInstanceTools(); - registerDeviceSetTools(); - registerChannelTools(); - registerFeatureTools(); - registerPresetTools(); - registerWorkspaceTools(); - registerCaptureTools(); - registerIntentTools(); -} - -void MCPTools::setStopping(bool stopping) -{ - m_stopping.storeRelease(stopping ? 1 : 0); - m_capture.setStopping(stopping); -} - -// The tools run on HTTP threads and wait for work that completes on the main thread. When the -// server stops, the main thread waits for the HTTP threads instead, so a wait that carried on -// would hold it for its whole timeout, or for ever where the main thread itself is what is -// waited for. Every wait therefore gives up at once when a stop is under way -bool MCPTools::waitFor(const std::function& condition, int timeoutMs) const -{ - QElapsedTimer timer; - timer.start(); - - while (!condition()) - { - if (m_stopping.loadAcquire()) { - throw MCPToolError("The MCP server is stopping, so this call was abandoned"); - } - - if (timer.elapsed() > timeoutMs) { - return false; - } - - QThread::msleep(20); - } - - return true; -} - -void MCPTools::pause(int ms) const -{ - QElapsedTimer timer; - timer.start(); - - for (;;) - { - if (m_stopping.loadAcquire()) { - throw MCPToolError("The MCP server is stopping, so this call was abandoned"); - } - - // Read once: read again for the sleep, the limit could pass in between and a negative - // remainder become an unsigned sleep of weeks - const qint64 remaining = ms - timer.elapsed(); - - if (remaining <= 0) { - return; - } - - QThread::msleep((unsigned long) std::min(50, remaining)); - } -} - -// Per tool behaviour. The MCP hints are narrower than they look: destructiveHint false means -// the tool is additive only, so anything that overwrites existing state is destructive, and -// openWorldHint true means the tool can reach beyond this application, which covers commanding -// the radio, features that talk to network services, and data arriving from unknown transmitters. -struct ToolBehaviour -{ - bool m_readOnly; - bool m_destructive; - bool m_idempotent; - bool m_openWorld; -}; - -static ToolBehaviour behaviourFor(const QString& name) -{ - // Reads of this instance's own configuration and of documentation compiled into the plugin - static const QStringList localReads = { - "get_instance_summary", "list_available_devices", "list_channel_types", "list_feature_types", - "describe_settings", "get_receiving_guide", "list_docs", "get_docs", "list_audio_devices", - "get_location", "get_deviceset", "get_device_settings", - "get_spectrum_settings", "get_spectrum_report", "get_spectrum_data", "get_channel_settings", "get_feature_settings", - "list_presets", "list_configurations", "get_server_status", "get_status" - }; - - // Reads that return data received off the air, from transmitters this instance does not - // control, or from the network services some features talk to. Reports carry it as well as - // the dedicated data feeds do: an ADS-B report, for instance, lists the aircraft heard. - static const QStringList offAirReads = { - "get_packets", "get_map_items", "get_channel_report", - "get_device_report", "get_feature_report" - }; - - // Purely additive: they create something new and overwrite nothing - static const QStringList additive = { - "add_deviceset", "add_channel", "add_feature", "add_workspace", "add_annotation" - }; - - if (localReads.contains(name)) { - return {true, false, true, false}; - } - - if (offAirReads.contains(name)) { - return {true, false, true, true}; - } - - if (additive.contains(name)) { - return {false, false, false, true}; - } - - // Everything else changes or removes state. Only the workspace moves and the settings writes - // land in the same place when repeated; captures, actions and creation do not. - bool idempotent = name.startsWith("set_") || name.startsWith("stop_") || (name == "clear_packets"); - return {false, true, idempotent, true}; -} - -void MCPTools::add(const QString& name, const QString& description, const QJsonObject& inputSchema, - std::function handler) -{ - Tool tool; - tool.name = name; - tool.description = description; - tool.inputSchema = inputSchema; - tool.handler = handler; - m_tools.append(tool); -} - -QJsonArray MCPTools::listTools() const -{ - QJsonArray tools; - - for (const Tool& tool : m_tools) - { - QJsonObject t; - t["name"] = tool.name; - t["description"] = tool.description; - t["inputSchema"] = tool.inputSchema; - ToolBehaviour behaviour = behaviourFor(tool.name); - // Clients carry the whole tool list on every turn, so only say what differs from the - // defaults the MCP schema gives an absent hint (read-write, destructive, not - // idempotent, open world), and no title, which would repeat the description - QJsonObject annotations; - if (behaviour.m_readOnly) { annotations["readOnlyHint"] = true; } - if (!behaviour.m_destructive) { annotations["destructiveHint"] = false; } - if (behaviour.m_idempotent) { annotations["idempotentHint"] = true; } - if (!behaviour.m_openWorld) { annotations["openWorldHint"] = false; } - if (!annotations.isEmpty()) { t["annotations"] = annotations; } - tools.append(t); - } - - return tools; -} - -QJsonObject MCPTools::callTool(const QString& name, const QJsonObject& arguments) -{ - const Tool *tool = nullptr; - - for (const Tool& t : m_tools) - { - if (t.name == name) - { - tool = &t; - break; - } - } - - if (!tool) { - throw MCPError(-32602, QString("Unknown tool: %1").arg(name)); - } - - QJsonObject result; - QJsonArray content; - - try - { - // Every input schema says additionalProperties: false, so an argument a tool does not - // define is a mistake worth reporting. Dropping it silently turns a wrong call into a - // plausible wrong answer: get_packets, which filters on source and type, looks as though - // it is ignoring a deviceSetIndex and channelIndex filter it never had - QJsonObject properties = tool->inputSchema.value("properties").toObject(); - QStringList unknown; - - for (const QString& key : arguments.keys()) - { - if (!properties.contains(key)) { - unknown.append(key); - } - } - - if (!unknown.isEmpty()) - { - QStringList accepted = properties.keys(); - throw MCPToolError(QString("%1 does not take %2. It accepts: %3") - .arg(name) - .arg(unknown.join(", ")) - .arg(accepted.isEmpty() ? QString("no arguments") : accepted.join(", "))); - } - - QJsonValue value = tool->handler(arguments); - - // A handler that has a picture to show puts it under _image, which becomes an image - // content item beside the text rather than a base64 blob in it - QJsonObject image; - - if (value.isObject() && value.toObject().contains("_image")) - { - QJsonObject object = value.toObject(); - image = object.take("_image").toObject(); - value = object; - } - - QJsonObject text; - text["type"] = "text"; - text["text"] = compact(value); - content.append(text); - - if (!image.isEmpty()) - { - QJsonObject item; - item["type"] = "image"; - item["data"] = image["data"]; - item["mimeType"] = image["mimeType"]; - content.append(item); - } - - if (value.isObject()) { - result["structuredContent"] = value; - } - - result["isError"] = false; - } - catch (const MCPToolError& e) - { - qDebug() << "MCPTools::callTool:" << name << "error:" << e.message; - QJsonObject text; - text["type"] = "text"; - text["text"] = "Error: " + e.message; - content.append(text); - result["isError"] = true; - } - - result["content"] = content; - return result; -} - -// --------------------------------------------------------------------------- -// Instance level data -// --------------------------------------------------------------------------- - -QJsonObject MCPTools::getInstanceSummary() -{ - SWGSDRangel::SWGInstanceSummaryResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceSummary(response, error), error, "Get instance summary"); - return toJson(response); -} - -QJsonObject MCPTools::getAvailableDevices(int direction) -{ - QJsonObject result; - - for (int dir = 0; dir < 3; dir++) - { - if ((direction >= 0) && (direction != dir)) { - continue; - } - - SWGSDRangel::SWGInstanceDevicesResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDevices(dir, response, error), error, "List devices"); - result[directionName(dir)] = toJson(response)["devices"].toArray(); - } - - return result; -} - -QJsonObject MCPTools::getAvailableChannels(int direction) -{ - QJsonObject result; - - for (int dir = 0; dir < 3; dir++) - { - if ((direction >= 0) && (direction != dir)) { - continue; - } - - SWGSDRangel::SWGInstanceChannelsResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceChannels(dir, response, error), error, "List channel types"); - result[directionName(dir)] = idsAndNames(toJson(response)["channels"].toArray()); - } - - return result; -} - -QJsonObject MCPTools::getAvailableFeatures() -{ - SWGSDRangel::SWGInstanceFeaturesResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceFeatures(response, error), error, "List feature types"); - QJsonObject result; - QJsonArray features; - - for (const QJsonValue& v : toJson(response)["features"].toArray()) - { - QString entry = v.toObject()["id"].toString(); - features.append(isPassiveFeature(entry) - ? QString("%1 [passive: no run state, do not start it]").arg(idsAndNames(QJsonArray{v}).first().toString()) - : idsAndNames(QJsonArray{v}).first().toString()); - } - - result["features"] = features; - return result; -} - -QJsonObject MCPTools::getPresets() -{ - SWGSDRangel::SWGPresets response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instancePresetsGet(response, error), error, "List presets"); - return toJson(response); -} - -QJsonObject MCPTools::getConfigurations() -{ - SWGSDRangel::SWGConfigurations response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceConfigurationsGet(response, error), error, "List configurations"); - return toJson(response); -} - -QJsonObject MCPTools::getDeviceSet(int deviceSetIndex) -{ - SWGSDRangel::SWGDeviceSet response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetGet(deviceSetIndex, response, error), error, QString("Get device set %1").arg(deviceSetIndex)); - return toJson(response); -} - -void MCPTools::loadYamlDefinitions() -{ - if (m_yamlLoaded) { - return; - } - - m_yamlLoaded = true; - QDir dir(":/webapi/doc/swagger/include"); - QRegularExpression definitionStart("^([A-Za-z0-9_]+):\\s*$"); - - for (const QString& fileName : dir.entryList(QStringList("*.yaml"), QDir::Files)) - { - QFile file(dir.filePath(fileName)); - - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - continue; - } - - QString name; - QStringList block; - - for (const QString& line : QString::fromUtf8(file.readAll()).split('\n')) - { - QRegularExpressionMatch match = definitionStart.match(line); - - if (match.hasMatch()) - { - if (!name.isEmpty()) { - m_yamlDefinitions[name] = block.join('\n').trimmed(); - } - - name = match.captured(1); - block.clear(); - } - - block.append(line); - } - - if (!name.isEmpty()) { - m_yamlDefinitions[name] = block.join('\n').trimmed(); - } - } - - for (auto name = m_yamlDefinitions.keyBegin(); name != m_yamlDefinitions.keyEnd(); ++name) { - m_yamlDefinitionsByLower.insert(name->toLower(), *name); - } - - qDebug("MCPTools::loadYamlDefinitions: %d definitions", (int) m_yamlDefinitions.size()); -} - -// The JSON settings key does not always capitalise the way its swagger definition does: -// testSourceSettings comes from TestSourceSettings, and sdrPlayV3Settings from SDRPlayV3Settings. -// Only the case ever differs, so a name that does not match exactly is looked up without it. -// Returns an empty string when there is no such definition -QString MCPTools::resolveDefinition(const QString& name) -{ - loadYamlDefinitions(); - - if (m_yamlDefinitions.contains(name)) { - return name; - } - - return m_yamlDefinitionsByLower.value(name.toLower()); -} - -QString MCPTools::describeType(const QString& typeIn, const QString& kindIn) -{ - QMutexLocker schemaLock(&m_schemaMutex); - loadYamlDefinitions(); - QString type = typeIn.trimmed(); - QString kind = kindIn.trimmed().toLower(); - // (settings JSON key, description of what matched) - QList> matches; - - // The spectrum display is not a type: its definitions are named after it directly - const QString lower = type.toLower(); - - if ((kind == "spectrum") || (lower == "spectrum") || (lower == "glspectrum")) - { - QStringList out; - out.append("# main spectrum display of a device set\n# get_spectrum_settings / set_spectrum_settings, get_spectrum_report, spectrum_action\n" - "# get_docs spectrum explains the display and its controls\n"); - - for (const QString& definition : {"GLSpectrum", "GLSpectrumReport", "SpectrumActions"}) - { - if (m_yamlDefinitions.contains(definition)) - { - out.append(m_yamlDefinitions[definition]); - out.append(""); - } - } - - return out.join('\n'); - } - - if (kind.isEmpty() || (kind == "channel")) - { - if (WebAPIUtils::m_channelTypeToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_channelTypeToSettingsKey[type], "channel type " + type}); - } - } - - if (kind.isEmpty() || (kind == "device")) - { - if (WebAPIUtils::m_sourceDeviceHwIdToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_sourceDeviceHwIdToSettingsKey[type], "rx device " + type}); - } - if (WebAPIUtils::m_sinkDeviceHwIdToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_sinkDeviceHwIdToSettingsKey[type], "tx device " + type}); - } - if (WebAPIUtils::m_mimoDeviceHwIdToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_mimoDeviceHwIdToSettingsKey[type], "mimo device " + type}); - } - } - - if (kind.isEmpty() || (kind == "feature")) - { - if (WebAPIUtils::m_featureTypeToSettingsKey.contains(type)) { - matches.append({WebAPIUtils::m_featureTypeToSettingsKey[type], "feature type " + type}); - } - } - - // Also accept a definition name given directly, e.g. "RtlSdrSettings" or "RtlSdr" - if (matches.isEmpty()) - { - if (!resolveDefinition(type + "Settings").isEmpty()) { - matches.append({type + "Settings", type}); - } else if (!resolveDefinition(type).isEmpty()) { - matches.append({type, type}); - } - } - - if (matches.isEmpty()) - { - throw MCPToolError(QString("Unknown type %1. Use the id values returned by list_channel_types, list_feature_types " - "or the hwType values returned by list_available_devices").arg(type)); - } - - QStringList out; - - for (const auto& match : matches) - { - QString settingsKey = match.first; - QString base = capitalize(settingsKey); - - if (base.endsWith("Settings")) { - base.chop(QString("Settings").size()); - } - - out.append(QString("# %1\n# Settings JSON key: %2\n").arg(match.second).arg(settingsKey)); - bool found = false; - - // A definition given by its own name that is not a Settings one, such as a Report or a - // marker, is what was asked for and is not reached by the suffixes below - if (!settingsKey.endsWith("Settings") && m_yamlDefinitions.contains(resolveDefinition(settingsKey))) - { - out.append(m_yamlDefinitions[resolveDefinition(settingsKey)]); - out.append(""); - found = true; - } - - for (const QString suffix : {"Settings", "Report", "Actions"}) - { - QString definition = resolveDefinition(base + suffix); - - if (!definition.isEmpty()) - { - out.append(m_yamlDefinitions[definition]); - out.append(""); - found = true; - } - } - - if (!found) { - out.append(QString("No documentation found for %1").arg(base)); - } - } - - return out.join('\n'); -} - -// --------------------------------------------------------------------------- -// Device set helpers -// --------------------------------------------------------------------------- - -int MCPTools::deviceSetCount() const -{ - return (int) MainCore::instance()->getDeviceSets().size(); -} - -int MCPTools::channelCount(int deviceSetIndex) const -{ - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { - return -1; - } - - return deviceSets[deviceSetIndex]->getNumberOfChannels(); -} - -int MCPTools::featureCount() const -{ - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty()) { - return -1; - } - - return featureSets[0]->getNumberOfFeatures(); -} - -int MCPTools::deviceSetDirection(int deviceSetIndex) -{ - QJsonObject deviceSet = getDeviceSet(deviceSetIndex); - return deviceSet["samplingDevice"].toObject()["direction"].toInt(0); -} - -// Selects the sampling device of a device set from hwType / serial / sequence / displayedName / deviceIndex -// and waits for SDRangel to switch to it. -QJsonObject MCPTools::selectDevice(int deviceSetIndex, const QJsonObject& args) -{ - int direction = deviceSetDirection(deviceSetIndex); - QString hwType = argString(args, "hwType", false); - QString serial = argString(args, "serial", false); - QString displayedName = argString(args, "displayedName", false); - int sequence = argInt(args, "sequence", false, -1); - int streamIndex = argInt(args, "deviceStreamIndex", false, -1); - - if (hasArg(args, "deviceIndex")) - { - // Resolve the index in the available devices list to concrete identifiers - int deviceIndex = argInt(args, "deviceIndex"); - QJsonArray devices = getAvailableDevices(direction)[directionName(direction)].toArray(); - bool found = false; - - for (const auto& value : devices) - { - QJsonObject device = value.toObject(); - - if (device["index"].toInt(-1) == deviceIndex) - { - hwType = device["hwType"].toString(); - serial = device["serial"].toString(); - sequence = device["sequence"].toInt(-1); - streamIndex = device["deviceStreamIndex"].toInt(-1); - displayedName = device["displayedName"].toString(); - found = true; - break; - } - } - - if (!found) { - throw MCPToolError(QString("No %1 device with index %2 in the available devices list").arg(directionName(direction)).arg(deviceIndex)); - } - } - - if (hwType.isEmpty() && serial.isEmpty() && displayedName.isEmpty()) { - throw MCPToolError("Specify at least one of hwType, serial, displayedName or deviceIndex to select a device"); - } - - SWGSDRangel::SWGDeviceListItem query; - query.setDirection(direction); - query.setIndex(-1); - query.setSequence(sequence); - query.setDeviceStreamIndex(streamIndex); - - if (!hwType.isEmpty()) { - query.setHwType(new QString(hwType)); - } - if (!serial.isEmpty()) { - query.setSerial(new QString(serial)); - } - if (!displayedName.isEmpty()) { - query.setDisplayedName(new QString(displayedName)); - } - - SWGSDRangel::SWGDeviceListItem response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - int changedBefore = m_events.m_deviceChanged.loadAcquire(); - check(m_adapter->devicesetDevicePut(deviceSetIndex, query, response, error), error, "Select device"); - - QJsonObject selected = toJson(response); - QString wantHwType = selected["hwType"].toString(); - QString wantSerial = selected["serial"].toString(); - int wantSequence = selected["sequence"].toInt(-1); - - // The change completes on the main thread and is signalled by MainCore::deviceChanged - QJsonObject deviceSet; - bool done = waitFor([&]() - { - if (m_events.m_deviceChanged.loadAcquire() == changedBefore) { - return false; - } - - deviceSet = getDeviceSet(deviceSetIndex); - QJsonObject sampling = deviceSet["samplingDevice"].toObject(); - return (sampling["hwType"].toString() == wantHwType) - && (wantSerial.isEmpty() || (sampling["serial"].toString() == wantSerial)) - && ((wantSequence < 0) || (sampling["sequence"].toInt(-1) == wantSequence)); - }); - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["selectedDevice"] = selected; - result["deviceSet"] = deviceSet; - - if (!done) { - result["warning"] = "Timed out waiting for the device change to complete. Call get_deviceset to check."; - } - - return result; -} - -QJsonObject MCPTools::getDeviceSettings(int deviceSetIndex) -{ - SWGSDRangel::SWGDeviceSettings response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetDeviceSettingsGet(deviceSetIndex, response, error), error, "Get device settings"); - return toJson(response); -} - -QJsonObject MCPTools::patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial) -{ - return applySettingsPatch( - [&](SWGSDRangel::SWGDeviceSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->devicesetDeviceSettingsGet(deviceSetIndex, r, e); - }, - [&](const QStringList& keys, SWGSDRangel::SWGDeviceSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->devicesetDeviceSettingsPutPatch(deviceSetIndex, false, keys, r, e); - }, - partial, QString("device settings of device set %1").arg(deviceSetIndex), - [this](const QString& definition) { return settingsSchema(definition); }); -} - -QSet MCPTools::channelUids(int deviceSetIndex) const -{ - QSet result; - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { - return result; - } - - DeviceSet *deviceSet = deviceSets[deviceSetIndex]; - - for (int i = 0; i < deviceSet->getNumberOfChannels(); i++) - { - const ChannelAPI *channel = deviceSet->getChannelAt(i); - - if (channel) { - result.insert(channel->getUID()); - } - } - - return result; -} - -QSet MCPTools::featureUids() const -{ - QSet result; - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty()) { - return result; - } - - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - const Feature *feature = featureSets[0]->getFeatureAt(i); - - if (feature) { - result.insert(feature->getUID()); - } - } - - return result; -} - -QSet MCPTools::deviceSetPointers() const -{ - QSet result; - - for (DeviceSet *deviceSet : MainCore::instance()->getDeviceSets()) { - result.insert(deviceSet); - } - - return result; -} - -// Adds a channel and waits for SDRangel to create it (which happens on the main thread), -// returning its index. The channel is ready to accept settings when this returns. -// -// The new channel is found by identity rather than by taking the last index: the GUI or -// another request can create a channel at the same time, and picking the highest index would -// then configure or delete somebody else's channel. -int MCPTools::addChannelAndWait(int deviceSetIndex, const QString& channelType) -{ - QMutexLocker creationLock(&m_creationMutex); - int direction = deviceSetDirection(deviceSetIndex); - int before = channelCount(deviceSetIndex); - - // A MIMO device set takes receive and transmit channels as well as MIMO ones, and the - // adapter looks the type up in the list the direction names, so the direction has to be - // the channel's rather than the device set's - if (direction == 2) - { - if (channelTypeIds(0).contains(channelType)) { - direction = 0; - } else if (channelTypeIds(1).contains(channelType)) { - direction = 1; - } - } - - if (before < 0) { - throw MCPToolError(QString("No device set with index %1").arg(deviceSetIndex)); - } - - QSet existing = channelUids(deviceSetIndex); - SWGSDRangel::SWGChannelSettings query; - query.setDirection(direction); - query.setChannelType(new QString(channelType)); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - int addedBefore = m_events.m_channelAdded.loadAcquire(); - check(m_adapter->devicesetChannelPost(deviceSetIndex, query, response, error), error, QString("Add channel %1").arg(channelType)); - - int channelIndex = -1; - bool created = waitFor([&]() - { - if (m_events.m_channelAdded.loadAcquire() <= addedBefore) { - return false; - } - - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { - return false; - } - - DeviceSet *deviceSet = deviceSets[deviceSetIndex]; - - for (int i = 0; i < deviceSet->getNumberOfChannels(); i++) - { - ChannelAPI *channel = deviceSet->getChannelAt(i); - - if (!channel || existing.contains(channel->getUID())) { - continue; - } - - QString id; - channel->getIdentifier(id); - - if (id == channelType) - { - channelIndex = i; - return true; - } - } - - return false; - }); - - if (!created || (channelIndex < 0)) { - throw MCPToolError(QString("Timed out waiting for the %1 channel to be created").arg(channelType)); - } - - // The channel needs a moment before it can accept settings - waitFor([&]() - { - SWGSDRangel::SWGChannelSettings s; - SWGSDRangel::SWGErrorResponse e; - e.init(); - return m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, s, e) / 100 == 2; - }, 2000); - - return channelIndex; -} - -// As for channels, the new feature is found by identity so that a feature created at the same -// time by the GUI or another request is never mistaken for this one. -int MCPTools::addFeatureAndWait(const QString& featureType) -{ - QMutexLocker creationLock(&m_creationMutex); - if (featureCount() < 0) { - throw MCPToolError("No feature set available"); - } - - QSet existing = featureUids(); - SWGSDRangel::SWGFeatureSettings query; - query.setFeatureType(new QString(featureType)); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - int addedBefore = m_events.m_featureAdded.loadAcquire(); - check(m_adapter->featuresetFeaturePost(0, query, response, error), error, QString("Add feature %1").arg(featureType)); - - int featureIndex = -1; - auto findNew = [&]() - { - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty()) { - return -1; - } - - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - Feature *feature = featureSets[0]->getFeatureAt(i); - - if (!feature || existing.contains(feature->getUID())) { - continue; - } - - if (feature->getIdentifier() == featureType) { - return i; - } - } - - return -1; - }; - - // The wait ends as soon as the feature appears, so a longer limit only costs time when one - // genuinely fails to be created. The Map takes a while: it brings up a web engine - waitFor([&]() - { - if (m_events.m_featureAdded.loadAcquire() <= addedBefore) { - return false; - } - - featureIndex = findNew(); - return featureIndex >= 0; - }, 15000); - - if (featureIndex < 0) - { - // Look once more before reporting a failure. A caller told that creation failed when it - // did not will retry, and every retry builds another one - featureIndex = findNew(); - } - - if (featureIndex < 0) { - throw MCPToolError(QString("Timed out waiting for the %1 feature to be created").arg(featureType)); - } - - // The feature needs a moment before it can accept settings - waitFor([&]() - { - SWGSDRangel::SWGFeatureSettings s; - SWGSDRangel::SWGErrorResponse e; - e.init(); - return m_adapter->featuresetFeatureSettingsGet(0, featureIndex, s, e) / 100 == 2; - }, 2000); - - return featureIndex; -} - -// Device set creation runs as a state machine on the main thread; MainCore::deviceSetAdded -// marks the end. The new set is identified by pointer for the same reason as above. -int MCPTools::addDeviceSetAndWait(int direction) -{ - QMutexLocker creationLock(&m_creationMutex); - QSet existing = deviceSetPointers(); - int before = m_events.m_deviceSetAdded.loadAcquire(); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDeviceSetPost(direction, response, error), error, "Add device set"); - - int deviceSetIndex = -1; - bool created = waitFor([&]() - { - if (m_events.m_deviceSetAdded.loadAcquire() <= before) { - return false; - } - - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - for (int i = 0; i < (int) deviceSets.size(); i++) - { - if (!existing.contains(deviceSets[i])) - { - deviceSetIndex = i; - return true; - } - } - - return false; - }); - - if (!created || (deviceSetIndex < 0)) { - throw MCPToolError("Timed out waiting for the device set to be created"); - } - - return deviceSetIndex; -} - -// Deletes a channel and waits for SDRangel to remove it -// Watches the channel itself disappear rather than the removed signal, which is not emitted -// for the last channel of a device set -void MCPTools::deleteChannelAndWait(int deviceSetIndex, int channelIndex) -{ - QMutexLocker deletionLock(&m_deletionMutex); - deleteChannelLocked(deviceSetIndex, channelIndex); -} - -void MCPTools::deleteChannelLocked(int deviceSetIndex, int channelIndex) -{ - const uint64_t target = channelUidAt(deviceSetIndex, channelIndex); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelDelete(deviceSetIndex, channelIndex, response, error), error, "Delete channel"); - - if (!waitFor([&]() { return !channelUids(deviceSetIndex).contains(target); })) { - throw MCPToolError(QString("Timed out waiting for channel %1:%2 to be removed").arg(deviceSetIndex).arg(channelIndex)); - } - - m_capture.forgetRecording(target); -} - -// Deletes a channel identified by its UID. A caller that waited, for instance for a -// recording to finish, cannot rely on the index it started with: deleting a lower numbered -// channel meanwhile renumbers everything above it. -void MCPTools::deleteChannelObjectAndWait(uint64_t channelUid) -{ - // The lookup and the delete under one lock, or another call's delete in between renumbers - // the index just found - QMutexLocker deletionLock(&m_deletionMutex); - int deviceSetIndex = -1; - int channelIndex = -1; - - if (!MCPCapture::locateChannel(channelUid, deviceSetIndex, channelIndex)) - { - m_capture.forgetRecording(channelUid); - return; // already gone, which is what was asked for - } - - deleteChannelLocked(deviceSetIndex, channelIndex); -} - -uint64_t MCPTools::deviceSetIdentity(int deviceSetIndex) const -{ - const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); - - if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size()) || !deviceSets[deviceSetIndex]) { - return 0; - } - - const DeviceSet *deviceSet = deviceSets[deviceSetIndex]; - const uint64_t engine = deviceSet->m_deviceAPI ? deviceSet->m_deviceAPI->getDeviceUID() : 0; - return (engine << 32) ^ reinterpret_cast(deviceSet); -} - -void MCPTools::discardNewDeviceSet(int deviceSetIndex, uint64_t identity) -{ - try - { - QMutexLocker deletionLock(&m_deletionMutex); - - // Only the last device set can be removed, and only when it is still the one made - // here: another call may have added one since, or removed this one and put another - // at the same index while this call slept, and then what is there is left for the user - if ((deviceSetIndex < 0) || (deviceSetIndex != deviceSetCount() - 1) - || (identity == 0) || (deviceSetIdentity(deviceSetIndex) != identity)) { - return; - } - - int before = m_events.m_deviceSetRemoved.loadAcquire(); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDeviceSetDelete(response, error), error, "Remove device set"); - waitFor([&]() { return m_events.m_deviceSetRemoved.loadAcquire() > before; }); - } - catch (const MCPToolError&) {} -} - -const void *MCPTools::featureAt(int featureIndex) const -{ - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty() || (featureIndex < 0) || (featureIndex >= featureSets[0]->getNumberOfFeatures())) { - return nullptr; - } - - return featureSets[0]->getFeatureAt(featureIndex); -} - -uint64_t MCPTools::featureUidAt(int featureIndex) const -{ - const Feature *feature = static_cast(featureAt(featureIndex)); - return feature ? feature->getUID() : 0; -} - -uint64_t MCPTools::channelUidAt(int deviceSetIndex, int channelIndex) const -{ - return MCPCapture::channelUidAt(deviceSetIndex, channelIndex); -} - -// Deleting or stopping the feature that is serving this request would tear down the HTTP -// listener from inside its own handler, so it is refused rather than attempted. -void MCPTools::requireNotSelf(int featureIndex, const QString& action) const -{ - if (m_ownerFeature && (featureAt(featureIndex) == m_ownerFeature)) - { - throw MCPToolError(QString("Feature %1 is the MCP Server serving this request and cannot be %2 through it. " - "Use the SDRangel GUI or the REST API instead.").arg(featureIndex).arg(action)); - } -} - -QJsonObject MCPTools::getChannelSettings(int deviceSetIndex, int channelIndex) -{ - SWGSDRangel::SWGChannelSettings response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, response, error), error, "Get channel settings"); - return toJson(response); -} - -SettingsSchema MCPTools::settingsSchema(const QString& definition) -{ - QMutexLocker schemaLock(&m_schemaMutex); - - if (m_schemaCache.contains(definition)) { - return m_schemaCache[definition]; - } - - SettingsSchema schema; - // Without this no device setting found its schema and none of them were type checked - QString name = resolveDefinition(definition); - - if (!name.isEmpty()) { - schema = parseSettingsSchema(m_yamlDefinitions[name]); - } - - m_schemaCache.insert(definition, schema); - return schema; -} - -QJsonObject MCPTools::getSpectrumSettings(int deviceSetIndex) -{ - SWGSDRangel::SWGGLSpectrum response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, response, error), error, "Get spectrum settings"); - return toJson(response); -} - -QJsonObject MCPTools::patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys) -{ - SWGSDRangel::SWGGLSpectrum current; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, current, error), error, "Get spectrum settings"); - QJsonObject json = toJson(current); - QStringList unknown; - QJsonObject checked = partial; - SettingsSchema schema = settingsSchema("GLSpectrum"); - - if (schema.m_known) - { - QStringList typeErrors; - checked = checkAgainstSchema(partial, schema, unknown, typeErrors); - - if (!typeErrors.isEmpty()) - { - throw MCPToolError(QString("Wrong value type for spectrum settings: %1. Numbers must be " - "given as JSON numbers, not strings. Nothing was changed.").arg(typeErrors.join("; "))); - } - } - - QStringList merged; - mergeInto(json, checked, merged); - - if (!schema.m_known) { - unknown = merged; - } - - if (unknownKeys) { - *unknownKeys = unknown; - } - - QStringList keys; - extractKeys(checked, keys); - SWGSDRangel::SWGGLSpectrum request; - request.init(); - request.fromJsonObject(json); - error.init(); - check(m_adapter->devicesetSpectrumSettingsPutPatch(deviceSetIndex, false, keys, request, error), error, "Set spectrum settings"); - return toJson(request); -} - -void MCPTools::addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex) -{ - if (channelType != "BFMDemod") { - return; - } - - if (report.value("BFMDemodReport").toObject().contains("rdsReport")) { - return; - } - - // The report is empty for a channel that is not running as well, where saying anything about - // RDS would only mislead, so the hint is tied to the setting that actually suppresses it - QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex).value("BFMDemodSettings").toObject(); - - if (settings.value("rdsActive").toInt(0) == 0) - { - report["rdsHint"] = "RDS is not being decoded, which is why this report has no rdsReport. Set rdsActive to 1 with " - "set_channel_settings to get the programme service name (the station name), radio text, programme " - "type and PI code."; - } -} - -QJsonObject MCPTools::patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial) -{ - return applySettingsPatch( - [&](SWGSDRangel::SWGChannelSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, r, e); - }, - [&](const QStringList& keys, SWGSDRangel::SWGChannelSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->devicesetChannelSettingsPutPatch(deviceSetIndex, channelIndex, false, keys, r, e); - }, - partial, QString("channel settings of channel %1:%2").arg(deviceSetIndex).arg(channelIndex), - [this](const QString& definition) { return settingsSchema(definition); }); -} - -QJsonObject MCPTools::getFeatureSettings(int featureIndex) -{ - SWGSDRangel::SWGFeatureSettings response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureSettingsGet(0, featureIndex, response, error), error, "Get feature settings"); - return toJson(response); -} - -QJsonObject MCPTools::patchFeatureSettings(int featureIndex, const QJsonObject& partial) -{ - return applySettingsPatch( - [&](SWGSDRangel::SWGFeatureSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->featuresetFeatureSettingsGet(0, featureIndex, r, e); - }, - [&](const QStringList& keys, SWGSDRangel::SWGFeatureSettings& r, SWGSDRangel::SWGErrorResponse& e) { - return m_adapter->featuresetFeatureSettingsPutPatch(0, featureIndex, false, keys, r, e); - }, - partial, QString("feature settings of feature %1").arg(featureIndex), - [this](const QString& definition) { return settingsSchema(definition); }); -} - -QJsonObject MCPTools::deviceState(int deviceSetIndex, int subsystemIndex, int run) -{ - SWGSDRangel::SWGDeviceState response; - response.init(); - SWGSDRangel::SWGErrorResponse error; - error.init(); - int rc; - - // The subsystem variants only apply to MIMO devices; single stream devices use the plain calls - bool mimo = deviceSetDirection(deviceSetIndex) == 2; - - auto runGet = [&](SWGSDRangel::SWGDeviceState& s, SWGSDRangel::SWGErrorResponse& e) { - return mimo ? m_adapter->devicesetDeviceSubsystemRunGet(deviceSetIndex, subsystemIndex, s, e) - : m_adapter->devicesetDeviceRunGet(deviceSetIndex, s, e); - }; - - if (run == 1) { - rc = mimo ? m_adapter->devicesetDeviceSubsystemRunPost(deviceSetIndex, subsystemIndex, response, error) - : m_adapter->devicesetDeviceRunPost(deviceSetIndex, response, error); - } else if (run == 0) { - rc = mimo ? m_adapter->devicesetDeviceSubsystemRunDelete(deviceSetIndex, subsystemIndex, response, error) - : m_adapter->devicesetDeviceRunDelete(deviceSetIndex, response, error); - } else { - rc = runGet(response, error); - } - - check(rc, error, run == 1 ? "Start device" : (run == 0 ? "Stop device" : "Get device state")); - - // The state returned by POST/DELETE is the state before the change. Give the device a moment - // and report the state actually reached. - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - - if (run >= 0) - { - QString want = run == 1 ? "running" : "idle"; - QString readError; - - bool reached = waitFor([&]() - { - SWGSDRangel::SWGDeviceState state; - state.init(); - SWGSDRangel::SWGErrorResponse e; - e.init(); - int getRC = runGet(state, e); - - if (getRC / 100 != 2) - { - readError = QString("HTTP %1 %2").arg(getRC).arg(e.getMessage() ? *e.getMessage() : QString()); - return true; // stop polling, reported below - } - - response.init(); - *response.getState() = *state.getState(); - return *state.getState() == want || *state.getState() == "error"; - }, 3000); - - if (!readError.isEmpty()) { - throw MCPToolError(QString("%1 was requested but the device state could not be read back: %2").arg(run == 1 ? "Start" : "Stop").arg(readError)); - } - - if (!reached) { - result["warning"] = QString("The device did not reach the %1 state within 3 seconds. The state reported here is the last one observed").arg(want); - } - } - - result["state"] = *response.getState(); - return result; -} - -QJsonObject MCPTools::featureState(int featureIndex, int run) -{ - // Asking a passive feature to run waits three seconds for a state it never reports, or fails - // outright on the ones that answer 501, so say what it is instead of doing either - if (run >= 0) - { - QString featureType = getFeatureSettings(featureIndex)["featureType"].toString(); - - if (isPassiveFeature(featureType)) - { - QJsonObject passive; - passive["featureIndex"] = featureIndex; - passive["featureType"] = featureType; - passive["state"] = "idle"; - passive["passive"] = true; - passive["note"] = QString("%1 has no run state and does not need starting: it works as soon as it " - "is configured, and reports idle whether or not it is doing anything.").arg(featureType); - return passive; - } - } - - SWGSDRangel::SWGDeviceState response; - response.init(); - SWGSDRangel::SWGErrorResponse error; - error.init(); - int rc; - - if (run == 1) { - rc = m_adapter->featuresetFeatureRunPost(0, featureIndex, response, error); - } else if (run == 0) { - rc = m_adapter->featuresetFeatureRunDelete(0, featureIndex, response, error); - } else { - rc = m_adapter->featuresetFeatureRunGet(0, featureIndex, response, error); - } - - check(rc, error, run == 1 ? "Start feature" : (run == 0 ? "Stop feature" : "Get feature state")); - - QJsonObject result; - result["featureIndex"] = featureIndex; - - if (run >= 0) - { - QString want = run == 1 ? "running" : "idle"; - QString readError; - - bool reached = waitFor([&]() - { - SWGSDRangel::SWGDeviceState state; - state.init(); - SWGSDRangel::SWGErrorResponse e; - e.init(); - int getRC = m_adapter->featuresetFeatureRunGet(0, featureIndex, state, e); - - if (getRC / 100 != 2) - { - readError = QString("HTTP %1 %2").arg(getRC).arg(e.getMessage() ? *e.getMessage() : QString()); - return true; // stop polling, reported below - } - - response.init(); - *response.getState() = *state.getState(); - return *state.getState() == want || *state.getState() == "error"; - }, 3000); - - if (!readError.isEmpty()) { - throw MCPToolError(QString("%1 was requested but the feature state could not be read back: %2").arg(run == 1 ? "Start" : "Stop").arg(readError)); - } - - if (!reached) { - result["warning"] = QString("The feature did not reach the %1 state within 3 seconds. The state reported here is the last one observed").arg(want); - } - } - - result["state"] = *response.getState(); - return result; -} - -// Resolves group name + name (and optionally centre frequency and type) to the full preset identifier -// SDRangel needs. For a save, the identifier of the current device is used when no matching preset exists. -QJsonObject MCPTools::presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave) -{ - QString groupName = argString(args, "groupName"); - QString name = argString(args, "name"); - QString type = argString(args, "type", false); - bool hasFrequency = hasArg(args, "centerFrequency"); - qint64 centerFrequency = argInt64(args, "centerFrequency", false, 0); - - QJsonObject deviceSet; - QString deviceType; - qint64 deviceFrequency = 0; - - if (forSave) - { - deviceSet = getDeviceSet(deviceSetIndex); - QJsonObject sampling = deviceSet["samplingDevice"].toObject(); - deviceFrequency = (qint64) sampling["centerFrequency"].toDouble(); - int direction = sampling["direction"].toInt(0); - deviceType = direction == 0 ? "R" : (direction == 1 ? "T" : "M"); - } - - QJsonArray candidates; - - for (const auto& groupValue : getPresets()["groups"].toArray()) - { - QJsonObject group = groupValue.toObject(); - - if (group["groupName"].toString() != groupName) { - continue; - } - - for (const auto& presetValue : group["presets"].toArray()) - { - QJsonObject preset = presetValue.toObject(); - - if (preset["name"].toString() != name) { - continue; - } - if (!type.isEmpty() && (preset["type"].toString() != type)) { - continue; - } - if (hasFrequency && ((qint64) preset["centerFrequency"].toDouble() != centerFrequency)) { - continue; - } - if (forSave && (preset["type"].toString() != deviceType)) { - continue; - } - - candidates.append(preset); - } - } - - QJsonObject identifier; - identifier["groupName"] = groupName; - identifier["name"] = name; - - if (candidates.count() == 1) - { - QJsonObject preset = candidates.first().toObject(); - identifier["type"] = preset["type"].toString(); - identifier["centerFrequency"] = preset["centerFrequency"].toDouble(); - identifier["exists"] = true; - } - else if (candidates.count() > 1) - { - throw MCPToolError(QString("Several presets match group %1 name %2. Specify centerFrequency and type to choose one of: %3") - .arg(groupName).arg(name).arg(compact(candidates))); - } - else if (forSave) - { - identifier["type"] = deviceType; - identifier["centerFrequency"] = (double) deviceFrequency; - identifier["exists"] = false; - } - else - { - throw MCPToolError(QString("No preset with group %1 and name %2. Call list_presets to see what exists").arg(groupName).arg(name)); - } - - return identifier; -} - -// --------------------------------------------------------------------------- -// Tool registration -// --------------------------------------------------------------------------- - -void MCPTools::registerInstanceTools() -{ - add("get_instance_summary", - "Get an overview of the SDRangel instance: version, all device sets with their sampling device and channels, and all features. " - "Call this first to learn the current state and the indexes to use with other tools.", - schema(QJsonObject()), - [this](const QJsonObject&) { return getInstanceSummary(); }); - - add("list_available_devices", - "List the SDR hardware and software sources/sinks that can be selected in a device set. Each entry gives hwType (used by " - "set_device and describe_settings), serial, sequence and index. Physical devices must be plugged in before SDRangel starts.", - schema({{"direction", directionProp("Only list devices for this direction (rx, tx or mimo). Default: all directions")}}), - [this](const QJsonObject& args) { return getAvailableDevices(argDirection(args, "direction", false, -1)); }); - - add("list_channel_types", - "List the channel plugins (demodulators for rx, modulators for tx) that can be added to a device set. The id is the channelType " - "to pass to add_channel and describe_settings.", - schema({{"direction", directionProp("Only list channels for this direction (rx, tx or mimo). Default: all directions")}}), - [this](const QJsonObject& args) { return getAvailableChannels(argDirection(args, "direction", false, -1)); }); - - add("list_feature_types", - "List the feature plugins that can be added with add_feature. The id is the featureType.", - schema(QJsonObject()), - [this](const QJsonObject&) { return getAvailableFeatures(); }); - - add("describe_settings", - "Get the documentation (OpenAPI YAML) of the settings, report and actions keys of a device, channel or feature type, " - "or of the spectrum display: what each key means, its units, range and enumeration values. Not needed for common keys; " - "call it when a set_* tool reports an unknown key, or before setting a key whose values are codes, such as a style or " - "mode. The output can run to a few thousand tokens.", - schema({ - {"type", strProp("Type identifier: a device hwType such as RTLSDR or TestSource, a channelType such as ADSBDemod or NFMDemod, " - "a featureType such as Map, or spectrum for the spectrum display")}, - {"kind", strProp("Optional: device, channel, feature or spectrum, to disambiguate when the same id exists for several kinds")} - }, {"type"}), - [this](const QJsonObject& args) { return QJsonValue(describeType(argString(args, "type"), argString(args, "kind", false))); }); - - add("get_receiving_guide", - "Read the receiving guide: which demodulator and frequency to use for a given signal or protocol (ADS-B, AIS, APRS, " - "radiosondes, weather satellites, broadcast FM, LoRa, pagers and more), the minimum device sample rate some modes need, " - "and the usual reasons nothing is received. Read this before setting up a receiver for a named signal, rather than " - "guessing frequencies.", - schema(QJsonObject()), - [this](const QJsonObject&) { return QJsonValue(m_docs.guide()); }); - - add("list_docs", - "List the user documentation (readme) available for the device, channel and feature plugins registered in this instance, " - "and for the GUI's own pages such as the spectrum display, with the section headings of each. Use get_docs to read one.", - schema({{"kind", strProp("Optional: only list device, channel, feature or gui docs")}}), - [this](const QJsonObject& args) - { - QString kind = argString(args, "kind", false).trimmed().toLower(); - QJsonObject index = m_docs.index(); - - if (kind.isEmpty()) { - return index; - } - - QJsonArray filtered; - - for (const auto& value : index["docs"].toArray()) - { - if (value.toObject()["kind"].toString() == kind) { - filtered.append(value); - } - } - - QJsonObject result; - result["count"] = filtered.count(); - result["docs"] = filtered; - return result; - }); - - add("get_docs", - "Read the user documentation (readme, as markdown) of a device, channel or feature plugin, or of a GUI page such as the " - "spectrum display: what it does, what each setting means, frequencies and sample rates it needs, and how to use it. Pass " - "section to get just one section (matched against the headings listed by list_docs) as the full documents can be long.", - schema({ - {"type", strProp("Plugin id (e.g. ADSBDemod, RTLSDR, Map), its displayed name (e.g. \"ADS-B Demodulator\"), or a GUI page: " - "spectrum, spectrummarkers, spectrummeasurements, spectrumcalibration, mainspectrum, audio, configurations, deviceuserargs, transverter")}, - {"kind", strProp("Optional: device, channel, feature or gui, to disambiguate")}, - {"section", strProp("Optional: text of a heading; only that section is returned")} - }, {"type"}), - [this](const QJsonObject& args) - { - QString type = argString(args, "type"); - QString kind = argString(args, "kind", false); - const MCPDocs::Doc *doc = m_docs.find(type, kind); - - if (!doc) { - throw MCPToolError(QString("No documentation found for %1. Call list_docs to see what is available").arg(type)); - } - - QString section = argString(args, "section", false); - QString text = m_docs.text(*doc, section); - - if (text.isEmpty()) { - throw MCPToolError(QString("No section matching \"%1\" in the %2 documentation. Sections: %3").arg(section).arg(doc->id).arg(doc->headings.join(" | "))); - } - - return QJsonValue(text); - }); - - add("get_packets", - "Get recently decoded packets from packet-oriented demodulators (AIS, APRS/AX.25 packet, LoRa/ChirpChat, M17, Meshtastic, " - "MeshCore, Inmarsat, radiosonde). Each packet has the raw bytes (hex and printable text) and, where SDRangel can decode it, " - "a decoded object: AIS message type, MMSI, position, course and speed; AX.25 from/to/via and data with APRS position and " - "comment; RS41 radiosonde serial, position and height. Packets are kept in a buffer of the last 1000; use sinceSequence " - "with the lastSequence of a previous call to read only new packets.", - schema({ - {"source", strProp("Only packets from this channel, e.g. \"R0:1\" (device set 0, channel 1)")}, - {"type", strProp("Only packets from channels of this type, e.g. AISDemod, PacketDemod, RadiosondeDemod")}, - {"limit", bounded(intProp("Maximum number of packets to return, most recent first. Default 50"), 1, MCPDataFeed::m_maxPackets)}, - {"sinceSequence", intProp("Only packets with a sequence number greater than this")} - }), - [this](const QJsonObject& args) - { - return m_dataFeed.getPackets(argString(args, "source", false), argString(args, "type", false), - argInt(args, "limit", false, 50), argInt64(args, "sinceSequence", false, 0)); - }); - - add("clear_packets", - "Discard all buffered packets.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - m_dataFeed.clearPackets(); - QJsonObject result; - result["cleared"] = true; - return result; - }); - - add("get_map_items", - "Get the objects currently plotted on the map by the running plugins: aircraft from ADS-B, ships from AIS, APRS stations, " - "radiosondes, satellites, the Sun and Moon from the star tracker, VOR/ILS beacons and so on. Each item has a name, position, " - "altitude, heading, the label and text shown on the map, and for aircraft the full ADS-B state. Only sources that are " - "running produce items; items disappear when their source removes them.", - schema({ - {"source", strProp("Only items from this channel or feature id (e.g. \"R0:0\", \"F:1\") or plugin type (e.g. ADSBDemod, AIS)")}, - {"name", strProp("Only items whose name contains this text, e.g. an ICAO address, MMSI or callsign")}, - {"limit", bounded(intProp("Maximum number of items to return. Default 200"), 1, 5000)}, - {"includeTrack", prop("boolean", "Include the position history of each item. Default false, as tracks can be long")} - }), - [this](const QJsonObject& args) - { - bool includeTrack = argBool(args, "includeTrack", false); - return m_dataFeed.getMapItems(argString(args, "source", false), argString(args, "name", false), - argInt(args, "limit", false, 200), includeTrack); - }); - - add("list_audio_devices", - "List the audio input and output devices available to SDRangel.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - SWGSDRangel::SWGAudioDevices response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceAudioGet(response, error), error, "List audio devices"); - return toJson(response); - }); - - add("get_location", - "Get the station location (latitude and longitude in degrees) used by features such as the Map and satellite tracker.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - SWGSDRangel::SWGLocationInformation response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceLocationGet(response, error), error, "Get location"); - return toJson(response); - }); - - add("set_location", - "Set the station location.", - schema({ - {"latitude", bounded(numProp("Latitude in degrees, positive north"), -90.0, 90.0)}, - {"longitude", bounded(numProp("Longitude in degrees, positive east"), -180.0, 180.0)} - }, {"latitude", "longitude"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGLocationInformation response; - response.setLatitude((float) argDouble(args, "latitude")); - response.setLongitude((float) argDouble(args, "longitude")); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceLocationPut(response, error), error, "Set location"); - return toJson(response); - }); -} - -void MCPTools::registerDeviceSetTools() -{ - add("add_deviceset", - "Create a new device set and optionally select its sampling device in one go. Returns the index of the new device set. " - "Identify the device with hwType and/or serial (from list_available_devices), or deviceIndex (its index in that list). " - "Without a device the new device set uses the first available device of that direction.", - schema({ - {"direction", directionProp("rx for a receiver (default), tx for a transmitter, mimo for a MIMO device")}, - {"hwType", strProp("Hardware type of the device to select, e.g. RTLSDR, HackRF, TestSource")}, - {"serial", strProp("Serial number of the device to select")}, - {"sequence", intProp("Sequence number of the device, to distinguish identical devices")}, - {"displayedName", strProp("Displayed name of the device, as listed by list_available_devices")}, - {"deviceIndex", intProp("Index of the device in the list_available_devices list for this direction")} - }), - [this](const QJsonObject& args) - { - int direction = argDirection(args, "direction", false, 0); - int deviceSetIndex = addDeviceSetAndWait(direction); - - if (hasArg(args, "hwType") || hasArg(args, "serial") || hasArg(args, "displayedName") || hasArg(args, "deviceIndex")) - { - try - { - return selectDevice(deviceSetIndex, args); - } - catch (const MCPToolError& e) - { - throw MCPToolError(QString("Device set %1 was created but the requested device could not be selected: %2. " - "Use set_device on that device set, or remove_last_deviceset. Do not call add_deviceset again.") - .arg(deviceSetIndex).arg(e.message)); - } - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["deviceSet"] = getDeviceSet(deviceSetIndex); - return result; - }); - - add("remove_last_deviceset", - "Remove the device set with the highest index. In the GUI the first device set (R0) cannot be removed.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - int before = m_events.m_deviceSetRemoved.loadAcquire(); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDeviceSetDelete(response, error), error, "Remove device set"); - - if (!waitFor([&]() { return m_events.m_deviceSetRemoved.loadAcquire() > before; })) { - throw MCPToolError("Timed out waiting for the device set to be removed; get_instance_summary shows whether it went"); - } - - QJsonObject result; - result["deviceSetCount"] = deviceSetCount(); - return result; - }); - - add("get_deviceset", - "Get a device set: its sampling device (hwType, serial, centre frequency, state) and the list of its channels with their reports.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return getDeviceSet(argInt(args, "deviceSetIndex")); }); - - add("set_device", - "Change the sampling device of an existing device set. Identify the device with hwType and/or serial (from list_available_devices), " - "or deviceIndex. Waits for the change to complete.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"hwType", strProp("Hardware type of the device to select, e.g. RTLSDR")}, - {"serial", strProp("Serial number of the device to select")}, - {"sequence", intProp("Sequence number of the device, to distinguish identical devices")}, - {"displayedName", strProp("Displayed name of the device")}, - {"deviceIndex", intProp("Index of the device in the list_available_devices list for the device set direction")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return selectDevice(argInt(args, "deviceSetIndex"), args); }); - - add("get_device_settings", - "Get the settings of the sampling device of a device set (centre frequency, sample rate, gain...). The keys depend on the device type.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return getDeviceSettings(argInt(args, "deviceSetIndex")); }); - - add("set_device_settings", - "Change some settings of the sampling device of a device set. Give only the keys to change, e.g. {\"centerFrequency\": 1090000000, \"gain\": 400}. " - "Use describe_settings with the device hwType to learn the valid keys, units and value ranges. Returns the keys changed with their applied values.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"settings", objProp("Object with the settings keys to change and their new values")} - }, {"deviceSetIndex", "settings"}), - [this](const QJsonObject& args) { return patchDeviceSettings(argInt(args, "deviceSetIndex"), argObject(args, "settings")); }); - - add("set_center_frequency", - "Tune the sampling device of a device set to a centre frequency in Hz. Channels keep their inputFrequencyOffset relative to it.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"frequency", numProp("Centre frequency in Hz")} - }, {"deviceSetIndex", "frequency"}), - [this](const QJsonObject& args) - { - QJsonObject settings; - settings["centerFrequency"] = (double) argInt64(args, "frequency"); - return patchDeviceSettings(argInt(args, "deviceSetIndex"), settings); - }); - - add("start_device", - "Start the sampling device of a device set so that it streams samples and its channels run. Returns the resulting state.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"subsystemIndex", bounded(intProp("MIMO devices only: 0 for the rx subsystem, 1 for tx. Default 0"), 0, 1)} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject state = deviceState(deviceSetIndex, argInt(args, "subsystemIndex", false, 0), 1); - QStringList warnings = basebandWarnings(deviceSetIndex); - - if (!warnings.isEmpty()) { - state["warning"] = warnings.join(" "); - } - - return QJsonValue(state); - }); - - add("stop_device", - "Stop the sampling device of a device set.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"subsystemIndex", bounded(intProp("MIMO devices only: 0 for the rx subsystem, 1 for tx. Default 0"), 0, 1)} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return deviceState(argInt(args, "deviceSetIndex"), argInt(args, "subsystemIndex", false, 0), 0); }); - - add("get_device_report", - "Get the live report of the sampling device of a device set (for example the actual sample rate, gain values, " - "or for file inputs the playback position). Keys depend on the device type.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGDeviceReport response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetDeviceReportGet(argInt(args, "deviceSetIndex"), response, error), error, "Get device report"); - return toJson(response); - }); - - add("device_action", - "Trigger an action on the sampling device of a device set. Only some device types have actions. Use describe_settings to find " - "the actions keys of the device type; pass them as the actions object, e.g. {\"record\": 1}.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"actions", objProp("Object with the action keys and values for this device type")} - }, {"deviceSetIndex", "actions"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject actions = argObject(args, "actions"); - QJsonObject settings = getDeviceSettings(deviceSetIndex); - QString hwType = settings["deviceHwType"].toString(); - int direction = settings["direction"].toInt(0); - const QMap& map = direction == 0 ? WebAPIUtils::m_sourceDeviceHwIdToActionsKey - : (direction == 1 ? WebAPIUtils::m_sinkDeviceHwIdToActionsKey : WebAPIUtils::m_mimoDeviceHwIdToActionsKey); - - if (!map.contains(hwType)) { - throw MCPToolError(QString("Device type %1 has no actions").arg(hwType)); - } - - QJsonObject json; - json["deviceHwType"] = hwType; - json["direction"] = direction; - json[map[hwType]] = actions.contains(map[hwType]) ? actions[map[hwType]].toObject() : actions; - QStringList keys; - extractKeys(json[map[hwType]].toObject(), keys); - - SWGSDRangel::SWGDeviceActions query; - query.init(); - query.fromJsonObject(json); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetDeviceActionsPost(deviceSetIndex, keys, query, response, error), error, "Device action"); - return toJson(response); - }); - - add("get_spectrum_settings", - "Get the settings of the main spectrum display of a device set, including FFT and scale, 2D/3D spectrum display, waterfall history, measurements and statistics, math, and saved-memory display settings.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGGLSpectrum response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumSettingsGet(argInt(args, "deviceSetIndex"), response, error), error, "Get spectrum settings"); - return toJson(response); - }); - - add("set_spectrum_settings", - "Change selected settings of the main spectrum display of a device set. Supports FFT and scale, 2D/3D spectrum display, waterfall history, measurements and statistics, math, and saved-memory display settings. Give only the keys to change (see get_spectrum_settings for the keys). " - "Keys whose values are codes are documented by describe_settings with type spectrum: for instance spectrumStyle is 0 line, 1 filled solid colour, 2 filled colour gradient, and colorMap names the gradient. " - "To smooth the trace set both averagingMode (1 moving) and averagingValue (the number of FFTs, e.g. 10): a mode with the value left at 1 averages nothing.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"settings", objProp("Object with the spectrum settings keys to change")} - }, {"deviceSetIndex", "settings"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject partial = argObject(args, "settings"); - QStringList unknownKeys; - - auto read = [&]() - { - SWGSDRangel::SWGGLSpectrum current; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, current, error), error, "Get spectrum settings"); - return toJson(current); - }; - - const QJsonObject before = read(); - patchSpectrumSettings(deviceSetIndex, partial, &unknownKeys); - - // Read back rather than echo the request: some values are rounded to what the - // display offers, and the caller should see what it got. The patch is applied by - // message, so give it a moment to land: until every key given has either moved or - // was already where it was asked to be - QJsonObject after = read(); - - for (int attempt = 0; attempt < 10; attempt++) - { - bool landed = true; - - for (const QString& key : partial.keys()) - { - if (after.contains(key) && (after[key] == before[key]) && (after[key] != partial[key])) { - landed = false; - } - } - - if (landed) { - break; - } - - QThread::msleep(50); - after = read(); - } - - QJsonObject changed; - QStringList notes; - - for (const QString& key : partial.keys()) - { - if (after.contains(key)) - { - changed[key] = after[key]; - - if (after[key].isDouble() && partial[key].isDouble() && (after[key].toDouble() != partial[key].toDouble())) { - notes.append(QString("%1 was rounded to %2, one of the values the display offers.").arg(key).arg(after[key].toDouble())); - } - } - } - - // A mode with a count of one averages nothing, which is easy to leave that way - if ((after["averagingMode"].toInt() != 0) && (after["averagingValue"].toInt() <= 1)) { - notes.append("averagingMode is set but averagingValue is 1, so no averaging is happening: set averagingValue as well, " - "10 to smooth a trace or 50 to measure a floor. The values available are 1, 2, 5, 10, 20, 50, 100 and so on."); - } - - QJsonObject result; - result["changed"] = changed; - - if (!unknownKeys.isEmpty()) { - result["warning"] = QString("Ignored unknown keys: %1. describe_settings lists the valid ones.").arg(unknownKeys.join(", ")); - } - - if (!notes.isEmpty()) { - result["note"] = notes.join(" "); - } - - return result; - }); - - - add("get_spectrum_report", - "Get the latest spectrum measurement results of a device set: peaks, channel power, adjacent channel power, occupied " - "bandwidth, 3 dB bandwidth, or SNR with THD and SINAD, depending on which measurement is selected with " - "set_spectrum_settings. Only the fields the selected measurement produces are returned, so an absent field was not " - "measured rather than measured as zero. With no measurement selected only measurement 0 comes back. The figures are " - "those of the spectrum as displayed, so they follow the zoom.", - schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGGLSpectrumReport response; - SWGSDRangel::SWGErrorResponse error; - response.init(); - error.init(); - check(m_adapter->devicesetSpectrumReportGet(argInt(args, "deviceSetIndex"), response, error), error, "Get spectrum report"); - return toJson(response); - }); - - - add("get_spectrum_data", - "Get the current power spectrum of a device set, reduced to the number of bins asked for. Use it to see what is on a band " - "without looking at the screen: which parts are occupied, how strong, and where the edges are. Each value covers " - "binBandwidth Hz starting at startFrequency. Reduction is by max, which keeps a narrow carrier that averaging would bury " - "in its neighbours; mean is better for measuring a noise floor. Every value costs tokens, so ask for the coarsest that " - "answers the question and narrow the frequency range instead of asking for more bins.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"bins", bounded(intProp("Number of values to return, most recent spectrum. Default 64"), 1, 512)}, - {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, - {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")}, - {"reduce", strProp("max to keep peaks, the default, or mean to average")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGGLSpectrumData response; - SWGSDRangel::SWGErrorResponse error; - response.init(); - error.init(); - check(m_adapter->devicesetSpectrumDataGet( - argInt(args, "deviceSetIndex"), - argInt(args, "bins", false, 64), - argInt64(args, "startFrequency", false, 0), - argInt64(args, "stopFrequency", false, 0), - argString(args, "reduce", false, "max"), - response, error), - error, "Get spectrum data"); - QJsonObject json = toJson(response); - - // The generated serialiser drops a list of plain floats, so the values go in by hand - QJsonArray power; - - if (response.getPower()) - { - for (float v : *response.getPower()) { - power.append(std::round((double) v * 10.0) / 10.0); - } - } - - json["power"] = power; - return json; - }); - - add("get_spectrum_history", - "What has been on a band over the last while, from the spectrum history the GUI keeps for scrolling: per bin " - "maximum, mean and occupancy (the fraction of the time the bin was above the noise floor by threshold dB), and a " - "signalList of every run of bins that rose above it, each with its frequency, width, peak, dutyCycle (1 for a " - "continuous carrier, small for bursts) and when it was first and last seen. This is the way to tell a continuous " - "signal from an intermittent one, find where transmissions are without stepping a scanner over them, and measure " - "a floor over time rather than from one snapshot. Only rows taken with the device tuned and sampling as it is now " - "count; after a retune, wait for new history. Scrolling is switched on if it is off, and then there is nothing to " - "report until some has accumulated, so call again after a few seconds. Every bin costs tokens: ask for the coarsest " - "that answers the question.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"seconds", numProp("How far back to look, in seconds. Default 60")}, - {"bins", bounded(intProp("Number of bins to reduce the spectrum to. Default 64"), 1, 512)}, - {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, - {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")}, - {"threshold", numProp("dB above the measured floor for a bin to count as occupied. Default 6")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - const int deviceSetIndex = argInt(args, "deviceSetIndex"); - const double seconds = argDouble(args, "seconds", false, 60.0); - const QString enabled = ensureSpectrumHistory(deviceSetIndex, seconds); - SWGSDRangel::SWGGLSpectrumHistory response; - SWGSDRangel::SWGErrorResponse error; - response.init(); - error.init(); - const int status = m_adapter->devicesetSpectrumHistoryGet(deviceSetIndex, seconds, - argInt(args, "bins", false, 64), argInt64(args, "startFrequency", false, 0), argInt64(args, "stopFrequency", false, 0), - argDouble(args, "threshold", false, 6.0), response, error); - - if (!enabled.isEmpty() && (status == 404)) - { - QJsonObject result; - result["rows"] = 0; - result["note"] = enabled + " Call again in a few seconds, once some has accumulated."; - return result; - } - - check(status, error, "Get spectrum history"); - QJsonObject json = toJson(response); - QJsonArray maxDb, meanDb, occupancy; - - for (float v : *response.getMaxDb()) { - maxDb.append(std::round((double) v * 10.0) / 10.0); - } - - for (float v : *response.getMeanDb()) { - meanDb.append(std::round((double) v * 10.0) / 10.0); - } - - for (float v : *response.getOccupancy()) { - occupancy.append(std::round((double) v * 100.0) / 100.0); - } - - json["maxDb"] = maxDb; - json["meanDb"] = meanDb; - json["occupancy"] = occupancy; - - if (!enabled.isEmpty()) { - json["note"] = enabled; - } - - return json; - }); - - add("get_waterfall_image", - "A picture of the spectrum history, the waterfall, as a greyscale image: frequency across, time down with the newest " - "row at the bottom, black a little below the noise floor and white at the strongest signal. Use it when the shape of " - "activity matters more than the numbers: a hopping signal, a drifting carrier, a burst pattern, or to see a whole band " - "at once. The reply's text gives the frequency and time extents so the picture can be read. get_spectrum_history " - "gives the same history as numbers. Scrolling is switched on if it is off, and then there is nothing to show until " - "some has accumulated.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"seconds", numProp("How far back to look, in seconds. Default 60")}, - {"width", bounded(intProp("Width in pixels, one per bin. Default 512"), 16, 2048)}, - {"height", bounded(intProp("At most this many rows, the most recent. Default 512"), 16, 2000)}, - {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, - {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - const int deviceSetIndex = argInt(args, "deviceSetIndex"); - const double seconds = argDouble(args, "seconds", false, 60.0); - const QString enabled = ensureSpectrumHistory(deviceSetIndex, seconds); - QByteArray png; - QJsonObject description; - SWGSDRangel::SWGErrorResponse error; - error.init(); - const int status = m_adapter->devicesetSpectrumHistoryImageGet(deviceSetIndex, seconds, - argInt(args, "width", false, 512), argInt64(args, "startFrequency", false, 0), argInt64(args, "stopFrequency", false, 0), - argInt(args, "height", false, 512), png, description, error); - - if (!enabled.isEmpty() && (status == 404)) - { - QJsonObject result; - result["note"] = enabled + " Call again in a few seconds, once some has accumulated."; - return result; - } - - check(status, error, "Get waterfall image"); - QJsonObject image; - image["data"] = QString(png.toBase64()); - image["mimeType"] = "image/png"; - description["_image"] = image; - description["note"] = QString("Frequency runs left to right from %1 to %2 MHz, time top to bottom from %3 to %4 with the newest row at the bottom; black is %5 dB and white %6 dB.%7") - .arg(description["startFrequency"].toDouble() / 1e6, 0, 'f', 4).arg(description["stopFrequency"].toDouble() / 1e6, 0, 'f', 4) - .arg(description["firstTime"].toString()).arg(description["lastTime"].toString()) - .arg(description["blackDb"].toDouble(), 0, 'f', 1).arg(description["whiteDb"].toDouble(), 0, 'f', 1) - .arg(enabled.isEmpty() ? QString() : " " + enabled); - return description; - }); - - add("spectrum_action", - "Act on the main spectrum of a device set. autoscale sets the reference level and range from what is on screen, " - "clearSpectrum discards the histogram and max hold traces, resetMeasurements starts the measurement statistics again, " - "freeze stops spectrum processing and unfreezing resumes it, and gotoMarker retunes to one of the annotations. " - "Everything except freeze acts on the display and so needs the GUI.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"autoscale", prop("boolean", "Set the reference level and range from the spectrum currently displayed")}, - {"clearSpectrum", prop("boolean", "Discard the accumulated histogram and max hold traces")}, - {"resetMeasurements", prop("boolean", "Discard the accumulated measurement statistics")}, - {"freeze", prop("boolean", "True to stop spectrum processing, false to resume it")}, - {"gotoMarker", intProp("Retune to the annotation at this index, counting from 0")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject actions; - - for (const QString& key : {QString("autoscale"), QString("clearSpectrum"), QString("resetMeasurements"), QString("freeze")}) - { - if (hasArg(args, key)) { - actions[key] = argBool(args, key, false) ? 1 : 0; - } - } - - if (hasArg(args, "gotoMarker")) { - actions["gotoMarker"] = argInt(args, "gotoMarker"); - } - - if (actions.isEmpty()) { - throw MCPToolError("Give at least one of autoscale, clearSpectrum, resetMeasurements, freeze or gotoMarker"); - } - - QStringList keys; - extractKeys(actions, keys); - - // fromJsonObject takes its argument by non-const reference and looks every field up - // with operator[], which inserts a null for each one that is absent, so what is echoed - // back is taken before the call rather than after it - QJsonObject applied = actions; - SWGSDRangel::SWGSpectrumActions query; - query.init(); - query.fromJsonObject(actions); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumActionsPost(deviceSetIndex, keys, query, error), error, "Spectrum action"); - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["applied"] = applied; - return result; - }); - - add("add_annotation", - "Add a labelled annotation to the main spectrum of a device set, for instance the name of the station a channel is tuned to. " - "Appends to the annotations already there instead of replacing them, and turns annotation display on if it is off. " - "Give centerFrequency, which is usually what you want as the bandwidth is then centred on it, or startFrequency.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"text", strProp("Label shown against the annotation, e.g. the RDS programme service name of a broadcast station")}, - {"centerFrequency", numProp("Centre frequency of the annotation in Hz. Give this or startFrequency")}, - {"startFrequency", numProp("Start frequency of the annotation in Hz. Give this or centerFrequency")}, - {"bandwidth", intProp("Width of the annotation in Hz. Default 0, which marks a single frequency")}, - {"color", intProp("Colour packed as blue*65536 + green*256 + red, each component 0 to 255. Default yellow")}, - {"show", bounded(intProp("0 hidden, 1 top marker only, 2 full with text and limits, 3 text only. Default 2"), 0, 3)} - }, {"deviceSetIndex", "text"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - int bandwidth = argInt(args, "bandwidth", false, 0); - - if (bandwidth < 0) { - throw MCPToolError("bandwidth cannot be negative"); - } - - qint64 startFrequency; - - if (hasArg(args, "startFrequency")) { - startFrequency = argInt64(args, "startFrequency"); - } else if (hasArg(args, "centerFrequency")) { - startFrequency = argInt64(args, "centerFrequency") - bandwidth / 2; - } else { - throw MCPToolError("Give either centerFrequency or startFrequency"); - } - - QJsonObject marker; - marker["startFrequency"] = startFrequency; - marker["bandwidth"] = bandwidth; - marker["markerColor"] = argInt(args, "color", false, 65535); // Yellow - marker["show"] = argInt(args, "show", false, 2); - marker["text"] = argString(args, "text"); - - QJsonObject current = getSpectrumSettings(deviceSetIndex); - - // Appended by the settings themselves rather than by reading the list, adding to it and - // writing it back, which would lose an annotation added by anything else in between - QJsonArray markers; - markers.append(marker); - - QJsonObject patch; - patch["annotationMarkers"] = markers; - patch["annotationMarkersMode"] = 1; - // Annotations are drawn only when their bit of markersDisplay is set, so an annotation - // added while it is clear would otherwise be invisible with nothing to say why - patch["markersDisplay"] = current.value("markersDisplay").toInt(0) | 0x2; - - QJsonObject after = patchSpectrumSettings(deviceSetIndex, patch); - QJsonObject result; - result["added"] = marker; - result["annotationMarkers"] = after.value("annotationMarkers").toArray(); - return result; - }); - - add("remove_annotation", - "Remove annotations from the main spectrum of a device set. Give text to remove the annotations carrying that label, " - "frequency to remove those whose span covers it, or all to remove every annotation. Returns what was removed and what is left.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"text", strProp("Remove annotations whose label is exactly this")}, - {"frequency", numProp("Remove annotations whose span covers this frequency in Hz")}, - {"all", prop("boolean", "Remove every annotation. Default false")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - bool all = argBool(args, "all", false); - bool byText = hasArg(args, "text"); - bool byFrequency = hasArg(args, "frequency"); - - // Without a criterion the intent is ambiguous, and either reading of it, removing - // nothing or removing everything, would be wrong often enough to be worth refusing - if (!all && !byText && !byFrequency) { - throw MCPToolError("Give text, frequency or all to say which annotations to remove"); - } - - QString text = argString(args, "text", false); - qint64 frequency = argInt64(args, "frequency", false); - QJsonArray markers = getSpectrumSettings(deviceSetIndex).value("annotationMarkers").toArray(); - QJsonArray kept; - QJsonArray removed; - - for (const QJsonValue& value : markers) - { - QJsonObject marker = value.toObject(); - qint64 start = (qint64) marker.value("startFrequency").toDouble(); - qint64 stop = start + (qint64) marker.value("bandwidth").toDouble(); - bool matches = all - || (byText && (marker.value("text").toString() == text)) - || (byFrequency && (frequency >= start) && (frequency <= stop)); - - if (matches) { - removed.append(marker); - } else { - kept.append(marker); - } - } - - QJsonObject result; - result["removed"] = removed; - - if (removed.isEmpty()) - { - result["annotationMarkers"] = markers; - result["warning"] = "No annotation matched, so nothing was removed"; - return result; - } - - QJsonObject patch; - patch["annotationMarkers"] = kept; - QJsonObject after = patchSpectrumSettings(deviceSetIndex, patch); - result["annotationMarkers"] = after.value("annotationMarkers").toArray(); - return result; - }); -} - -void MCPTools::registerChannelTools() -{ - add("add_channel", - "Add a channel (demodulator or modulator) to a device set and optionally apply initial settings. Returns the index of the new channel. " - "channelType is an id from list_channel_types, e.g. ADSBDemod, NFMDemod, AMDemod, BFMDemod, SSBDemod, AISDemod, PacketDemod, FileSink.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelType", strProp("Channel type id from list_channel_types")}, - {"settings", objProp("Optional initial settings for the channel, e.g. {\"inputFrequencyOffset\": 0}. Use describe_settings for the keys")} - }, {"deviceSetIndex", "channelType"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QString channelType = argString(args, "channelType"); - int channelIndex = addChannelAndWait(deviceSetIndex, channelType); - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["channelIndex"] = channelIndex; - QString warning = basebandWarning(deviceSetIndex, channelType); - - if (!warning.isEmpty()) { - result["warning"] = warning; - } - QJsonObject settings = argObject(args, "settings", false); - - if (!settings.isEmpty()) - { - QJsonObject patched; - - try - { - patched = patchChannelSettings(deviceSetIndex, channelIndex, settings); - } - catch (const MCPToolError& e) - { - // The channel exists even though its settings were refused. Say so and give - // its index, otherwise a retry would leave a second one behind. - throw MCPToolError(QString("The %1 channel was created as channel %2 of device set %3, but its initial " - "settings were refused, so it is left with defaults: %4. Use set_channel_settings to correct it, " - "or delete_channel to remove it. Do not call add_channel again.") - .arg(channelType).arg(channelIndex).arg(deviceSetIndex).arg(e.message)); - } - - result["changed"] = patched["changed"]; - - if (patched.contains("warning")) { - result["warning"] = patched["warning"]; - } - } - - return result; - }); - - add("delete_channel", - "Remove a channel from a device set. Channels with a higher index are renumbered down by one.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp} - }, {"deviceSetIndex", "channelIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - - // Waits for the channel itself to disappear. Waiting for the removed signal would - // sit out the whole timeout for the last channel of a device set, which the device - // set drops from its list before MainCore can look it up to signal it. - deleteChannelAndWait(deviceSetIndex, argInt(args, "channelIndex")); - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["channelCount"] = channelCount(deviceSetIndex); - return result; - }); - - add("get_channel_settings", - "Get the settings of a channel. The keys depend on the channel type. inputFrequencyOffset is the channel frequency relative to the device centre frequency in Hz.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp} - }, {"deviceSetIndex", "channelIndex"}), - [this](const QJsonObject& args) { return getChannelSettings(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex")); }); - - add("set_channel_settings", - "Change some settings of a channel. Give only the keys to change, e.g. {\"inputFrequencyOffset\": 25000, \"squelch\": -40}. " - "Use describe_settings with the channel type to learn the valid keys. Returns the keys changed with their applied values.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp}, - {"settings", objProp("Object with the settings keys to change and their new values")} - }, {"deviceSetIndex", "channelIndex", "settings"}), - [this](const QJsonObject& args) - { - return patchChannelSettings(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex"), argObject(args, "settings")); - }); - - add("get_channel_report", - "Get the live report of a channel: signal level, squelch state, decoder statistics and so on, depending on the channel type. " - "Omit channelIndex for the reports of every channel of the device set. " - "For DAB, wait briefly after selecting a programme or changing receiver gain and then read the report again. Do not accept " - "sync or audioActive alone as proof of clean reception: if synchronized audio has SNR at or below 0 dB, RTL-SDR overload " - "is likely, so reduce gain through its supported values and keep the setting that gives the best positive SNR.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", intProp("Index of the channel within the device set; omit for all channels")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - SWGSDRangel::SWGErrorResponse error; - error.init(); - - if (hasArg(args, "channelIndex")) - { - int channelIndex = argInt(args, "channelIndex"); - SWGSDRangel::SWGChannelReport response; - check(m_adapter->devicesetChannelReportGet(deviceSetIndex, channelIndex, response, error), error, "Get channel report"); - QJsonObject report = toJson(response); - addRdsHint(report, report.value("channelType").toString(), deviceSetIndex, channelIndex); - return report; - } - - SWGSDRangel::SWGChannelsDetail response; - check(m_adapter->devicesetChannelsReportGet(deviceSetIndex, response, error), error, "Get channels report"); - QJsonObject json = toJson(response); - QJsonArray channels = json.value("channels").toArray(); - - for (int i = 0; i < channels.size(); i++) - { - QJsonObject channel = channels.at(i).toObject(); - QJsonObject report = channel.value("report").toObject(); - // The channel type is on the entry here rather than on the report it carries - addRdsHint(report, channel.value("id").toString(), deviceSetIndex, channel.value("index").toInt()); - channel["report"] = report; - channels[i] = channel; - } - - json["channels"] = channels; - return json; - }); - - add("channel_action", - "Trigger an action on a channel. Only some channel types have actions. Use describe_settings to find the actions keys of the " - "channel type; pass them as the actions object.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp}, - {"actions", objProp("Object with the action keys and values for this channel type")} - }, {"deviceSetIndex", "channelIndex", "actions"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - int channelIndex = argInt(args, "channelIndex"); - QJsonObject actions = argObject(args, "actions"); - QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex); - QString channelType = settings["channelType"].toString(); - - if (!WebAPIUtils::m_channelTypeToActionsKey.contains(channelType)) { - throw MCPToolError(QString("Channel type %1 has no actions").arg(channelType)); - } - - QString actionsKey = WebAPIUtils::m_channelTypeToActionsKey[channelType]; - QJsonObject json; - json["channelType"] = channelType; - json["direction"] = settings["direction"].toInt(0); - json[actionsKey] = actions.contains(actionsKey) ? actions[actionsKey].toObject() : actions; - QStringList keys; - extractKeys(json[actionsKey].toObject(), keys); - - SWGSDRangel::SWGChannelActions query; - query.init(); - query.fromJsonObject(json); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelActionsPost(deviceSetIndex, channelIndex, keys, query, response, error), error, "Channel action"); - return toJson(response); - }); -} - -void MCPTools::registerFeatureTools() -{ - add("add_feature", - "Add a feature (device independent plugin such as Map, AIS, APRS, SatelliteTracker) and optionally apply initial settings. " - "Returns the index of the new feature. featureType is an id from list_feature_types.", - schema({ - {"featureType", strProp("Feature type id from list_feature_types")}, - {"settings", objProp("Optional initial settings for the feature. Use describe_settings for the keys")} - }, {"featureType"}), - [this](const QJsonObject& args) - { - QString featureType = argString(args, "featureType"); - int featureIndex = addFeatureAndWait(featureType); - QJsonObject result; - result["featureIndex"] = featureIndex; - QJsonObject settings = argObject(args, "settings", false); - - if (!settings.isEmpty()) - { - QJsonObject patched; - - try - { - patched = patchFeatureSettings(featureIndex, settings); - } - catch (const MCPToolError& e) - { - throw MCPToolError(QString("The %1 feature was created as feature %2, but its initial settings were " - "refused, so it is left with defaults: %3. Use set_feature_settings to correct it, or " - "delete_feature to remove it. Do not call add_feature again.") - .arg(featureType).arg(featureIndex).arg(e.message)); - } - - result["changed"] = patched["changed"]; - - if (patched.contains("warning")) { - result["warning"] = patched["warning"]; - } - } - - return result; - }); - - add("delete_feature", - "Remove a feature. Features with a higher index are renumbered down by one.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) - { - int featureIndex = argInt(args, "featureIndex"); - QMutexLocker deletionLock(&m_deletionMutex); - requireNotSelf(featureIndex, "deleted"); - const uint64_t target = featureUidAt(featureIndex); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureDelete(0, featureIndex, response, error), error, "Delete feature"); - - // FeatureSet drops the feature from its own list before MainCore looks it up, so - // removing the last feature emits no featureRemoved. Watch the feature itself go. - if (!waitFor([&]() { return !featureUids().contains(target); })) { - throw MCPToolError(QString("Timed out waiting for feature %1 to be removed").arg(featureIndex)); - } - - QJsonObject result; - result["featureCount"] = featureCount(); - return result; - }); - - add("get_feature_settings", - "Get the settings of a feature. The keys depend on the feature type.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) { return getFeatureSettings(argInt(args, "featureIndex")); }); - - add("set_feature_settings", - "Change some settings of a feature. Give only the keys to change. Use describe_settings with the feature type to learn the valid keys.", - schema({ - {"featureIndex", featureIndexProp}, - {"settings", objProp("Object with the settings keys to change and their new values")} - }, {"featureIndex", "settings"}), - [this](const QJsonObject& args) { return patchFeatureSettings(argInt(args, "featureIndex"), argObject(args, "settings")); }); - - add("get_feature_report", - "Get the live report of a feature, depending on the feature type.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGFeatureReport response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureReportGet(0, argInt(args, "featureIndex"), response, error), error, "Get feature report"); - return toJson(response); - }); - - add("start_feature", - "Start a feature. Most features must be started to do anything, but the passive ones - AIS, AMBE, AntennaTools, " - "APRS, FreqDisplay, LimeRFE, Map, Radiosonde, RemoteControl and SkyMap - have no run state, work as soon as they " - "are configured and always report idle. Starting one of those is answered without doing anything.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) { return featureState(argInt(args, "featureIndex"), 1); }); - - add("stop_feature", - "Stop a feature.", - schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), - [this](const QJsonObject& args) - { - int featureIndex = argInt(args, "featureIndex"); - requireNotSelf(featureIndex, "stopped"); - return featureState(featureIndex, 0); - }); - - add("feature_action", - "Trigger an action on a feature. Use describe_settings to find the actions keys of the feature type; pass them as the actions object.", - schema({ - {"featureIndex", featureIndexProp}, - {"actions", objProp("Object with the action keys and values for this feature type")} - }, {"featureIndex", "actions"}), - [this](const QJsonObject& args) - { - int featureIndex = argInt(args, "featureIndex"); - QJsonObject actions = argObject(args, "actions"); - QJsonObject settings = getFeatureSettings(featureIndex); - QString featureType = settings["featureType"].toString(); - - if (!WebAPIUtils::m_featureTypeToActionsKey.contains(featureType)) { - throw MCPToolError(QString("Feature type %1 has no actions").arg(featureType)); - } - - QString actionsKey = WebAPIUtils::m_featureTypeToActionsKey[featureType]; - QJsonObject json; - json["featureType"] = featureType; - json[actionsKey] = actions.contains(actionsKey) ? actions[actionsKey].toObject() : actions; - QStringList keys; - extractKeys(json[actionsKey].toObject(), keys); - - SWGSDRangel::SWGFeatureActions query; - query.init(); - query.fromJsonObject(json); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureActionsPost(0, featureIndex, keys, query, response, error), error, "Feature action"); - return toJson(response); - }); -} - -void MCPTools::registerPresetTools() -{ - add("list_presets", - "List the saved device set presets. A preset stores a device set's device and channel settings and is identified by group name, " - "name, centre frequency and type (R for rx, T for tx, M for MIMO).", - schema(QJsonObject()), - [this](const QJsonObject&) { return getPresets(); }); - - add("load_preset", - "Load a preset into a device set, replacing its device settings and channels. The preset type must match the device set direction.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"groupName", strProp("Preset group name")}, - {"name", strProp("Preset name")}, - {"centerFrequency", numProp("Preset centre frequency in Hz. Only needed when several presets share the group and name")}, - {"type", strProp("Preset type R, T or M. Only needed when several presets share the group and name")} - }, {"deviceSetIndex", "groupName", "name"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject identifier = presetIdentifier(args, deviceSetIndex, false); - SWGSDRangel::SWGPresetTransfer query; - query.setDeviceSetIndex(deviceSetIndex); - SWGSDRangel::SWGPresetIdentifier *preset = new SWGSDRangel::SWGPresetIdentifier(); - preset->setGroupName(new QString(identifier["groupName"].toString())); - preset->setName(new QString(identifier["name"].toString())); - preset->setType(new QString(identifier["type"].toString())); - preset->setCenterFrequency((qint64) identifier["centerFrequency"].toDouble()); - query.setPreset(preset); - SWGSDRangel::SWGPresetIdentifier response; - response.init(); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instancePresetPatch(query, response, error), error, "Load preset"); - pause(500); // Loading replaces the channels; give it a moment before the caller looks - QJsonObject result; - result["loaded"] = toJson(response); - result["deviceSet"] = getDeviceSet(deviceSetIndex); - return result; - }); - - add("save_preset", - "Save the current device settings and channels of a device set as a preset. Updates the preset if one with the same group, name, " - "centre frequency and type exists, otherwise creates it.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"groupName", strProp("Preset group name")}, - {"name", strProp("Preset name")} - }, {"deviceSetIndex", "groupName", "name"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject identifier = presetIdentifier(args, deviceSetIndex, true); - SWGSDRangel::SWGPresetTransfer query; - query.setDeviceSetIndex(deviceSetIndex); - SWGSDRangel::SWGPresetIdentifier *preset = new SWGSDRangel::SWGPresetIdentifier(); - preset->setGroupName(new QString(identifier["groupName"].toString())); - preset->setName(new QString(identifier["name"].toString())); - preset->setType(new QString(identifier["type"].toString())); - preset->setCenterFrequency((qint64) identifier["centerFrequency"].toDouble()); - query.setPreset(preset); - SWGSDRangel::SWGPresetIdentifier response; - response.init(); - SWGSDRangel::SWGErrorResponse error; - error.init(); - bool exists = identifier["exists"].toBool(); - - if (exists) { - check(m_adapter->instancePresetPut(query, response, error), error, "Update preset"); - } else { - check(m_adapter->instancePresetPost(query, response, error), error, "Create preset"); - } - - QJsonObject result; - result["preset"] = toJson(response); - result["created"] = !exists; - return result; - }); - - add("list_configurations", - "List the saved configurations. A configuration stores the whole instance: all device sets, features and workspaces.", - schema(QJsonObject()), - [this](const QJsonObject&) { return getConfigurations(); }); - - add("load_configuration", - "Load a saved configuration, replacing all current device sets and features.", - schema({ - {"groupName", strProp("Configuration group name")}, - {"name", strProp("Configuration name")} - }, {"groupName", "name"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGConfigurationIdentifier response; - response.setGroupName(new QString(argString(args, "groupName"))); - response.setName(new QString(argString(args, "name"))); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceConfigurationPatch(response, error), error, "Load configuration"); - pause(1000); // Loading rebuilds everything - QJsonObject result; - result["configuration"] = toJson(response); - result["instance"] = getInstanceSummary(); - return result; - }); - - add("save_configuration", - "Save the whole current instance as a configuration. Updates the configuration if one with the same group and name exists, otherwise creates it.", - schema({ - {"groupName", strProp("Configuration group name")}, - {"name", strProp("Configuration name")} - }, {"groupName", "name"}), - [this](const QJsonObject& args) - { - QString groupName = argString(args, "groupName"); - QString name = argString(args, "name"); - bool exists = false; - - for (const auto& groupValue : getConfigurations()["groups"].toArray()) - { - QJsonObject group = groupValue.toObject(); - - if (group["groupName"].toString() != groupName) { - continue; - } - - for (const auto& item : group["configurations"].toArray()) - { - if (item.toObject()["name"].toString() == name) { - exists = true; - } - } - } - - SWGSDRangel::SWGConfigurationIdentifier response; - response.setGroupName(new QString(groupName)); - response.setName(new QString(name)); - SWGSDRangel::SWGErrorResponse error; - error.init(); - - if (exists) { - check(m_adapter->instanceConfigurationPut(response, error), error, "Update configuration"); - } else { - check(m_adapter->instanceConfigurationPost(response, error), error, "Create configuration"); - } - - QJsonObject result; - result["configuration"] = toJson(response); - result["created"] = !exists; - return result; - }); -} - -void MCPTools::registerWorkspaceTools() -{ - add("add_workspace", - "GUI only: add a new workspace (a tabbed area holding device, channel and feature windows). Workspaces are numbered from 0.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceWorkspacePost(response, error), error, "Add workspace"); - return toJson(response); - }); - - add("delete_empty_workspaces", - "GUI only: remove all workspaces that contain no windows.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceWorkspaceDelete(response, error), error, "Delete empty workspaces"); - return toJson(response); - }); - - add("arrange_workspace", - "GUI only: arrange the windows of a workspace, as its title bar buttons do. cascade, tile, stackVertical and stack " - "rearrange them once and turn auto stacking and tabs off; autostack stacks them now and again whenever a window is " - "added or resized, until another arrangement is asked for; tab shows one window at a time with a tab for each. " - "stack is the usual choice: devices, spectra and channels in columns.", - schema({ - {"workspaceIndex", intProp("Index of the workspace, from 0")}, - {"arrange", enumProp("cascade, tile, stackVertical, stack, autostack or tab", {"cascade", "tile", "stackVertical", "stack", "autostack", "tab"})} - }, {"workspaceIndex", "arrange"}), - [this](const QJsonObject& args) - { - SWGSDRangel::SWGWorkspaceActions query; - query.init(); - query.setArrange(new QString(argString(args, "arrange"))); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->workspaceActionsPost(argInt(args, "workspaceIndex"), query, response, error), error, "Arrange workspace"); - return toJson(response); - }); - - add("list_windows", - "GUI only: every window, with its kind (device, spectrum, channel or feature), indices, title, workspace and whether it " - "is hidden. A hidden window is still running; set_workspace with hidden false shows it again.", - schema({}), - [this](const QJsonObject&) - { - SWGSDRangel::SWGWindowList response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceWindowsGet(response, error), error, "List windows"); - return toJson(response); - }); - - add("set_workspace", - "GUI only: move a window to a workspace, hide it, or show it again. kind is device, spectrum or channel (with " - "deviceSetIndex, plus channelIndex for a channel) or feature (with featureIndex). Give workspaceIndex to move, hidden " - "to hide (true) or show (false), or both. Showing a window raises it and shows the workspace holding it. Hiding a " - "window does not stop it: a hidden demodulator still plays audio. list_windows shows what is hidden.", - schema({ - {"kind", strProp("device, spectrum, channel or feature")}, - {"workspaceIndex", intProp("Workspace to move the window to. Optional")}, - {"hidden", prop("boolean", "true hides the window, false shows it. Optional")}, - {"deviceSetIndex", intProp("For device, spectrum and channel")}, - {"channelIndex", intProp("For channel")}, - {"featureIndex", intProp("For feature")} - }, {"kind"}), - [this](const QJsonObject& args) - { - QString kind = argString(args, "kind").trimmed().toLower(); - - if (!hasArg(args, "workspaceIndex") && !hasArg(args, "hidden")) { - throw MCPToolError("Give workspaceIndex to move the window, hidden to hide or show it, or both"); - } - - // -1 for what was not asked for, as the Web API's own validator passes it - SWGSDRangel::SWGWorkspaceInfo query; - query.setIndex(hasArg(args, "workspaceIndex") ? argInt(args, "workspaceIndex") : -1); - query.setHidden(hasArg(args, "hidden") ? (argBool(args, "hidden", false) ? 1 : 0) : -1); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - - if (kind == "device") { - check(m_adapter->devicesetDeviceWorkspacePut(argInt(args, "deviceSetIndex"), query, response, error), error, "Set device workspace"); - } else if (kind == "spectrum") { - check(m_adapter->devicesetSpectrumWorkspacePut(argInt(args, "deviceSetIndex"), query, response, error), error, "Set spectrum workspace"); - } else if (kind == "channel") { - check(m_adapter->devicesetChannelWorkspacePut(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex"), query, response, error), error, "Set channel workspace"); - } else if (kind == "feature") { - check(m_adapter->featuresetFeatureWorkspacePut(argInt(args, "featureIndex"), query, response, error), error, "Set feature workspace"); - } else { - throw MCPToolError("kind must be device, spectrum, channel or feature"); - } - - return toJson(response); - }); -} - -void MCPTools::registerCaptureTools() -{ - - add("get_server_status", - "This server's own state, in one call: the capture directory and any recordings running; which channels and features " - "feed packets and map items and how much has arrived; and the client event streams (open streams, subscriptions, " - "notifications sent). Open a stream with an HTTP GET on the MCP endpoint with Accept: text/event-stream, then " - "resources/subscribe.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - QJsonObject result; - result["capture"] = m_capture.status(); - result["dataFeed"] = m_dataFeed.getStatus(); - result["streams"] = m_streams ? m_streams->status() : QJsonObject(); - return result; - }); - - add("capture_audio", - QString("Record the demodulated audio of a channel to a WAV file and report where it went, how loud it was and whether it " - "was silent. Works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod, " - "BFMDemod, DSDDemod and M17Demod. The device must be running. This call blocks for the duration, so it is limited " - "to %1 seconds. Set inline to true (up to %2 seconds) to also get the audio back as base64 for playing directly: " - "a mono 16 kHz copy, small enough for a tool result, while the file keeps the full rate.") - .arg(MCPCapture::m_maxBlockingSeconds).arg(MCPCapture::m_maxInlineSeconds), - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", channelIndexProp}, - {"seconds", bounded(numProp(QString("How long to record for, up to %1").arg(MCPCapture::m_maxBlockingSeconds)), 0.1, MCPCapture::m_maxBlockingSeconds)}, - {"fileName", strProp("File name relative to the capture directory. The .wav extension is added. Default: audio_")}, - {"inline", prop("boolean", QString("Also return the audio as base64 in audioBase64, as a mono 16 kHz WAV. Only for clips of %1 seconds or less. Default false").arg(MCPCapture::m_maxInlineSeconds))} - }, {"deviceSetIndex", "channelIndex", "seconds"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - int channelIndex = argInt(args, "channelIndex"); - double seconds = argDouble(args, "seconds"); - bool inlineAudio = argBool(args, "inline", false); - - if ((seconds <= 0) || (seconds > MCPCapture::m_maxBlockingSeconds)) { - throw MCPToolError(QString("seconds must be between 0 and %1").arg(MCPCapture::m_maxBlockingSeconds)); - } - - if (inlineAudio && (seconds > MCPCapture::m_maxInlineSeconds)) { - throw MCPToolError(QString("inline audio is only available for %1 seconds or less").arg(MCPCapture::m_maxInlineSeconds)); - } - - QJsonObject state = deviceState(deviceSetIndex, 0, -1); - - if (state["state"].toString() != "running") { - throw MCPToolError("The device is not running, so there is no audio to record. Call start_device first."); - } - - return m_capture.captureAudio(deviceSetIndex, channelIndex, seconds, - argString(args, "fileName", false), inlineAudio); - }); - - add("start_iq_recording", - "Start recording baseband IQ samples to a file. Adds a FileSink channel to the device set unless channelIndex names an " - "existing one, and starts it recording. The device must be running for samples to be written. Recording continues until " - "stop_iq_recording, so use this for long captures and record_iq for short ones. Files are written under the capture " - "directory shown by get_server_status; fileName is relative to it.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"fileName", strProp("File name relative to the capture directory. A timestamp and the .sdriq extension are added. Default: iq_")}, - {"frequencyOffset", intProp("Channel frequency offset from the device centre frequency in Hz. Default 0, which records the full baseband centred on the device frequency")}, - {"log2Decim", bounded(intProp("Decimation as a power of two: 0 records at the device sample rate, 1 halves it, and so on. Default 0"), 0, 6)}, - {"channelIndex", intProp("Use this existing FileSink channel instead of adding one")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - bool created = !hasArg(args, "channelIndex"); - - // A bad file name is refused before a channel is added for it - m_capture.checkFileName(argString(args, "fileName", false), "iq"); - - int channelIndex = created ? addChannelAndWait(deviceSetIndex, "FileSink") : argInt(args, "channelIndex"); - const uint64_t channel = created ? channelUidAt(deviceSetIndex, channelIndex) : 0; - - try - { - QJsonObject result = m_capture.startIQRecording(deviceSetIndex, channelIndex, - argString(args, "fileName", false), argInt(args, "frequencyOffset", false, 0), - argInt(args, "log2Decim", false, 0)); - result["channelCreated"] = created; - QJsonObject state = deviceState(deviceSetIndex, 0, -1); - - if (state["state"].toString() != "running") { - result["warning"] = "The device is not running, so no samples will be recorded. Call start_device."; - } - - return result; - } - catch (const MCPToolError&) - { - // Do not leave a channel behind when the recording could not be set up. By - // identity: a concurrent listen or scan may have renumbered it meanwhile - if (created) { - try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} - } - - throw; - } - }); - - add("stop_iq_recording", - "Stop an IQ recording started with start_iq_recording and report the files written, with their size and duration.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"channelIndex", intProp("Index of the FileSink channel that is recording")}, - {"deleteChannel", prop("boolean", "Delete the FileSink channel afterwards. Default false")} - }, {"deviceSetIndex", "channelIndex"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - int channelIndex = argInt(args, "channelIndex"); - const uint64_t channel = channelUidAt(deviceSetIndex, channelIndex); - QJsonObject result = m_capture.stopIQRecording(deviceSetIndex, channelIndex); - bool deleteChannel = argBool(args, "deleteChannel", false); - - if (deleteChannel) - { - deleteChannelObjectAndWait(channel); - result["channelDeleted"] = true; - } - - return result; - }); - - add("record_iq", - QString("Record baseband IQ samples for a fixed number of seconds and return the files written. Adds a FileSink channel, " - "records, stops and removes the channel again. This call blocks for the duration, so it is limited to %1 seconds; " - "for longer captures use start_iq_recording and stop_iq_recording. The device must already be running. " - "Note that IQ files are large: roughly 4 bytes per sample per second of the device sample rate.") - .arg(MCPCapture::m_maxBlockingSeconds), - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"seconds", bounded(numProp(QString("How long to record for, up to %1").arg(MCPCapture::m_maxBlockingSeconds)), 0.1, MCPCapture::m_maxBlockingSeconds)}, - {"fileName", strProp("File name relative to the capture directory. A timestamp and the .sdriq extension are added")}, - {"frequencyOffset", intProp("Channel frequency offset from the device centre frequency in Hz. Default 0")}, - {"log2Decim", bounded(intProp("Decimation as a power of two. Default 0"), 0, 6)} - }, {"deviceSetIndex", "seconds"}), - [this](const QJsonObject& args) - { - int deviceSetIndex = argInt(args, "deviceSetIndex"); - double seconds = argDouble(args, "seconds"); - - if ((seconds <= 0) || (seconds > MCPCapture::m_maxBlockingSeconds)) - { - throw MCPToolError(QString("seconds must be between 0 and %1. For a longer capture use start_iq_recording and stop_iq_recording") - .arg(MCPCapture::m_maxBlockingSeconds)); - } - - QJsonObject state = deviceState(deviceSetIndex, 0, -1); - - if (state["state"].toString() != "running") { - throw MCPToolError("The device is not running, so there is nothing to record. Call start_device first."); - } - - // A bad file name is refused before a channel is added for it - m_capture.checkFileName(argString(args, "fileName", false), "iq"); - - int channelIndex = addChannelAndWait(deviceSetIndex, "FileSink"); - - // This call sleeps for up to half a minute and is not serialised against the other - // tools, so another request can delete a channel and renumber this one meanwhile. - // Everything after the sleep therefore works from the channel's UID, not its index. - const uint64_t channel = channelUidAt(deviceSetIndex, channelIndex); - - if (channel == 0) // cannot happen, but do not leave the channel behind if it does - { - try { deleteChannelAndWait(deviceSetIndex, channelIndex); } catch (const MCPToolError&) {} - - throw MCPToolError("The FileSink channel went away as soon as it was added"); - } - - QJsonObject result; - - try - { - QJsonObject started = m_capture.startIQRecording(deviceSetIndex, channelIndex, - argString(args, "fileName", false), argInt(args, "frequencyOffset", false, 0), - argInt(args, "log2Decim", false, 0)); - pause((int) (seconds * 1000.0)); - result = m_capture.stopIQRecording(channel); - result["fileBase"] = started["fileBase"]; - result["requestedSeconds"] = seconds; - } - catch (const MCPToolError&) - { - try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} - throw; - } - - deleteChannelObjectAndWait(channel); - - if (result["files"].toArray().isEmpty()) { - result["warning"] = "No files were written. Check that the device is running and producing samples."; - } - - return result; - }); -} - -// --------------------------------------------------------------------------- -// Intent level tools: a whole task in one call -// -// Setting up a receiver with the object level tools takes an agent around ten round trips, -// each one a model turn. These do the common tasks in one, using the same helpers, and reply -// with a short summary rather than the objects they created. -// --------------------------------------------------------------------------- - -namespace { - -// What "listen to X in mode Y" needs: the demodulator, its initial settings and the smallest -// baseband that carries it. Values are the ones the receiving guide and readmes give. -struct ListenMode -{ - const char *m_alias; - const char *m_channelType; - int m_rfBandwidth; //!< Hz. Negative selects the lower sideband, as the SSB demodulator does - int m_minBaseband; //!< Hz - const char *m_settings; //!< JSON of further initial settings - int m_scanStep; //!< Hz. The channel spacing scan steps by unless told otherwise; 0 for a mode on fixed frequencies, which is not scanned for - const char *m_feature; //!< A feature the mode's output goes to, added if absent; null for none - int m_pairOffset; //!< Hz. Non-zero for a mode on two channels this far either side of the frequency, one demodulator each -}; - -const char *const bfmSettings = "{\"afBandwidth\":15000,\"audioStereo\":1,\"rdsActive\":1,\"volume\":4,\"squelch\":-60}"; -const char *const amSettings = "{\"afBandwidth\":3000,\"bandpassEnable\":1,\"volume\":4,\"squelch\":-60}"; - -const ListenMode listenModes[] = { - // Broadcast FM asks for twice the baseband its channel needs: a 180 kHz channel in a 256 kS/s - // baseband sits against the edge of the decimation filters, and RDS suffers first; it also - // leaves room to put the channel clear of the device's DC spike - {"bfm", "BFMDemod", 180000, 512000, bfmSettings, 100000, nullptr, 0}, - {"fm", "BFMDemod", 180000, 512000, bfmSettings, 100000, nullptr, 0}, - {"wfm", "WFMDemod", 150000, 512000, "{\"volume\":2,\"squelch\":-60}", 100000, nullptr, 0}, - {"nfm", "NFMDemod", 12500, 48000, "{\"afBandwidth\":3000,\"volume\":2}", 12500, nullptr, 0}, - {"am", "AMDemod", 8000, 48000, amSettings, 25000, nullptr, 0}, - {"airband", "AMDemod", 8000, 48000, amSettings, 25000, nullptr, 0}, - {"ssb", "SSBDemod", 3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, - {"usb", "SSBDemod", 3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, - {"lsb", "SSBDemod", -3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, - {"dab", "DABDemod", 0, 2048000, "{}", 0, nullptr, 0}, - {"adsb", "ADSBDemod", 0, 2400000, "{}", 0, nullptr, 0}, - {"ais", "AISDemod", 0, 128000, "{}", 0, "AIS", 25000}, - {"dsc", "DSCDemod", 450, 48000, "{}", 0, nullptr, 0}, - // Digital voice: the DSD demodulator decides the standard from the baud rate, and its - // discriminator wants the maximum deviation of the standard, the readme's table: DMR 5.4, - // dPMR 2.7, D-Star 3.5, YSF 7.0, NXDN 2.7 kHz. dsd alone is the plugin's defaults, which - // are D-Star's, set explicitly so that a retuned demodulator gets them too. DMR carries - // two time slots, so both are switched on - {"dsd", "DSDDemod", 12500, 48000, "{\"fmDeviation\":3500,\"baudRate\":4800}", 12500, nullptr, 0}, - {"dmr", "DSDDemod", 12500, 48000, "{\"fmDeviation\":5400,\"baudRate\":4800,\"slot1On\":1,\"slot2On\":1}", 12500, nullptr, 0}, - {"dpmr", "DSDDemod", 6250, 48000, "{\"fmDeviation\":2700,\"baudRate\":2400}", 6250, nullptr, 0}, - {"dstar", "DSDDemod", 12500, 48000, "{\"fmDeviation\":3500,\"baudRate\":4800}", 12500, nullptr, 0}, - {"ysf", "DSDDemod", 12500, 48000, "{\"fmDeviation\":7000,\"baudRate\":4800}", 12500, nullptr, 0}, - {"nxdn", "DSDDemod", 12500, 48000, "{\"fmDeviation\":2700,\"baudRate\":4800}", 12500, nullptr, 0}, - {"nxdn24", "DSDDemod", 6250, 48000, "{\"fmDeviation\":2700,\"baudRate\":2400}", 6250, nullptr, 0}, - {"pager", "PagerDemod", 20000, 48000, "{}", 12500, nullptr, 0}, - {"pocsag", "PagerDemod", 20000, 48000, "{}", 12500, nullptr, 0}, - {"sonde", "RadiosondeDemod", 9600, 48000, "{}", 10000, "Radiosonde", 0}, - {"radiosonde", "RadiosondeDemod", 9600, 48000, "{}", 10000, "Radiosonde", 0}, - // AX.25 packet at 1200 baud AFSK. APRS is the same signal on a fixed regional frequency, - // with the APRS feature to plot the stations - {"packet", "PacketDemod", 12500, 48000, "{}", 0, nullptr, 0}, - {"aprs", "PacketDemod", 12500, 48000, "{}", 0, "APRS", 0}, -}; - -const char *const listenModeList = "bfm, wfm, nfm, am, ssb, usb, lsb, dab, adsb, ais, dsc, dsd, dmr, dpmr, dstar, ysf, nxdn, pager, sonde, packet, aprs"; - -// The feature a demodulator of this type feeds, by the modes that add one; null for none -const char *featureForChannelType(const QString& channelType) -{ - for (const ListenMode& mode : listenModes) - { - if (mode.m_feature && (channelType == QLatin1String(mode.m_channelType))) { - return mode.m_feature; - } - } - - return nullptr; -} - -// What listen and scan say about the features a reclaim took away -QStringList featureNotes(const QStringList& reclaimedFeatures) -{ - if (reclaimedFeatures.isEmpty()) { - return QStringList(); - } - - return QStringList(QString("Removed the %1 feature%2 an earlier listen added, as nothing feeds %3 now.") - .arg(reclaimedFeatures.join(" and ")).arg(reclaimedFeatures.size() == 1 ? "" : "s") - .arg(reclaimedFeatures.size() == 1 ? "it" : "them")); -} - -const ListenMode *findListenMode(const QString& alias) -{ - for (const ListenMode& mode : listenModes) - { - if (alias.compare(QLatin1String(mode.m_alias), Qt::CaseInsensitive) == 0) { - return &mode; - } - } - - return nullptr; -} - -// The device rate and decimation that give at least the wanted baseband. These are the rates -// an RTL-SDR runs reliably; DAB needs exactly 2.048 MS/s. -void rateFor(int minBaseband, int& devSampleRate, int& log2Decim) -{ - if (minBaseband <= 256000) { devSampleRate = 1024000; log2Decim = 2; } - else if (minBaseband <= 512000) { devSampleRate = 1024000; log2Decim = 1; } - else if (minBaseband <= 1024000) { devSampleRate = 1024000; log2Decim = 0; } - else if (minBaseband <= 2048000) { devSampleRate = 2048000; log2Decim = 0; } - else { devSampleRate = 2400000; log2Decim = 0; } -} - -// The baseband a channel type needs, from the table listen uses, so that there is one set of -// numbers rather than two that can disagree. 0 when the type is not in it. -int minimumBasebandFor(const QString& channelType) -{ - for (const ListenMode& mode : listenModes) - { - if (channelType.compare(QLatin1String(mode.m_channelType), Qt::CaseInsensitive) == 0) { - return mode.m_minBaseband; - } - } - - return 0; -} - -// Devices that are not radios attached to this machine, skipped when choosing one automatically -const QStringList virtualDeviceTypes = { - "TestSource", "FileInput", "SigMFFileInput", "LocalInput", "RemoteInput", "RemoteTCPInput", - "KiwiSDR", "AudioInput", "AaroniaRTSA", "AndroidSdrDriverInput" -}; - -// The type specific sub-object of a settings reply, e.g. the rtlSdrSettings of a device -QJsonObject settingsOf(const QJsonObject& reply) -{ - return reply[findSettingsKey(reply)].toObject(); -} - -// A signal level from a channel report, whatever the plugin calls it -bool signalLevel(const QJsonObject& report, double& db) -{ - for (const QString& key : report.keys()) - { - if (!key.endsWith("Report") || !report[key].isObject()) { - continue; - } - - QJsonObject sub = report[key].toObject(); - - for (const QString& k : sub.keys()) - { - if ((k.contains("PowerDB", Qt::CaseInsensitive) || (k == "rssi")) && sub[k].isDouble()) - { - db = sub[k].toDouble(); - return true; - } - } - } - - return false; -} - -} // namespace - -// A channel whose baseband is too narrow produces nothing, or silence, with no error anywhere: -// the demodulator simply never sees the signal. The rule is in this server's instructions, but -// it is read once at the start of a conversation and needed much later, so it is repeated here, -// where the numbers are known and the fix can be named. -QString MCPTools::basebandWarning(int deviceSetIndex, const QString& channelType) -{ - int needed = minimumBasebandFor(channelType); - - if (needed <= 0) { - return QString(); // nothing known about what this type needs - } - - QJsonObject settings; - - try - { - settings = settingsOf(getDeviceSettings(deviceSetIndex)); - } - catch (const MCPToolError&) - { - return QString(); // no device, or it cannot be read: not this call's problem to report - } - - // Only devices that express their rate this way can be checked. Saying nothing is better - // than guessing at a device whose keys are not these - if (!settings.contains("devSampleRate") || !settings.contains("log2Decim")) { - return QString(); - } - - int baseband = settings["devSampleRate"].toInt() >> settings["log2Decim"].toInt(); - - if (baseband >= needed) { - return QString(); - } - - int wantedRate = 0; - int wantedDecim = 0; - rateFor(needed, wantedRate, wantedDecim); - - return QString("%1 needs a baseband of at least %2 Hz, but device set %3 provides %4 Hz, so the channel " - "cannot work as it stands. Call set_device_settings with devSampleRate %5 and log2Decim %6.") - .arg(channelType).arg(needed).arg(deviceSetIndex).arg(baseband).arg(wantedRate).arg(wantedDecim); -} - -QStringList MCPTools::basebandWarnings(int deviceSetIndex) -{ - QStringList warnings; - QJsonObject deviceSet; - - try - { - deviceSet = getDeviceSet(deviceSetIndex); - } - catch (const MCPToolError&) - { - return warnings; - } - - QSet seen; - - for (const QJsonValue& value : deviceSet["channels"].toArray()) - { - QString channelType = value.toObject()["id"].toString(); - - if (channelType.isEmpty() || seen.contains(channelType)) { - continue; // several of a type would repeat the same sentence - } - - seen.insert(channelType); - QString warning = basebandWarning(deviceSetIndex, channelType); - - if (!warning.isEmpty()) { - warnings.append(warning); - } - } - - return warnings; -} - -QStringList MCPTools::channelTypeIds(int direction) -{ - SWGSDRangel::SWGInstanceChannelsResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceChannels(direction, response, error), error, "List channel types"); - QStringList ids; - - for (const QJsonValue& v : toJson(response)["channels"].toArray()) { - ids.append(v.toObject()["id"].toString()); - } - - return ids; -} - -void MCPTools::relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what) -{ - if (!MCPCapture::locateChannel(channelUid, deviceSetIndex, channelIndex)) { - throw MCPToolError(QString("The %1 channel no longer exists: another request removed it, or its device set, " - "while this call was running").arg(what)); - } -} - -void MCPTools::trackIntentChannel(uint64_t channelUid) -{ - if (channelUid == 0) { - return; - } - - QMutexLocker locker(&m_intentMutex); - m_intentChannels.insert(channelUid); -} - -void MCPTools::untrackIntentChannel(uint64_t channelUid) -{ - QMutexLocker locker(&m_intentMutex); - m_intentChannels.remove(channelUid); -} - -QSet MCPTools::intentChannels() -{ - QMutexLocker locker(&m_intentMutex); - return m_intentChannels; -} - -// What a device set carries besides one channel, and which of it listen or scan put there. -// Read from the live device set rather than any earlier snapshot, as a reclaim in between -// changes both the indices and the answer -QList MCPTools::channelNotes(int deviceSetIndex, const QSet& except) -{ - const QSet intent = intentChannels(); - QList notes; - - for (const QJsonValue& v : getDeviceSet(deviceSetIndex)["channels"].toArray()) - { - QJsonObject channel = v.toObject(); - int index = channel["index"].toInt(); - const uint64_t uid = channelUidAt(deviceSetIndex, index); - - if ((uid != 0) && !except.contains(uid)) { - notes.append({uid, index, channel["id"].toString(), intent.contains(uid)}); - } - } - - return notes; -} - -QStringList MCPTools::reclaimIntentChannels(int deviceSetIndex, const QSet& keep) -{ - QStringList removed; - - // Each is deleted by identity, wherever it has been renumbered to by then, and highest - // index first so that the ids come out in the order the device set listed them - QList notes = channelNotes(deviceSetIndex); - - for (int i = notes.size() - 1; i >= 0; i--) - { - if (!notes[i].m_intent || keep.contains(notes[i].m_uid)) { - continue; - } - - try - { - deleteChannelObjectAndWait(notes[i].m_uid); - removed.prepend(notes[i].m_id); - } - catch (const MCPToolError&) {} - - // Tracked no longer either way: if it could not be deleted now it will not be later - untrackIntentChannel(notes[i].m_uid); - } - - return removed; -} - -// Retuning the demodulator a previous listen added is what a person would do, and spares the -// audio device and the GUI a close and reopen. Only when the intent channels of that type are -// exactly the count the mode uses (one, or two for a paired mode such as AIS), and no scan's -// FreqScanner is there to be driving them. The first is returned; a paired mode finds the -// other among the intent channels of the type -uint64_t MCPTools::reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted) -{ - uint64_t candidate = 0; - int candidates = 0; - - for (const ChannelNote& note : channelNotes(deviceSetIndex)) - { - if (!note.m_intent) { - continue; - } - - if (note.m_id == "FreqScanner") { - return 0; - } - - if (note.m_id == channelType) - { - if (candidate == 0) - { - candidate = note.m_uid; - channelIndex = note.m_index; - } - - candidates++; - } - } - - return (candidates == wanted) ? candidate : 0; -} - -// A retune moves every channel on the device set, since each is an offset from the centre. A -// channel the user added is kept on the frequency it had when the new baseband holds it; an -// audio demodulator it cannot hold is removed, as all it could do is play noise; anything else -// is left, with a note, since a file sink or an analyser may be wanted regardless -MCPTools::RetuneOutcome MCPTools::retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband) -{ - RetuneOutcome outcome; - - if ((qint64) previousCentre == (qint64) centre) { - return outcome; - } - - static const QStringList audioDemods = { - "AMDemod", "BFMDemod", "DABDemod", "DATVDemod", "DSDDemod", "FreeDVDemod", "ILSDemod", "M17Demod", - "NFMDemod", "SSBDemod", "VORDemod", "VORDemodMC", "WFMDemod", "WDSPRx" - }; - - const QSet intent = intentChannels(); - QJsonObject set = getDeviceSet(deviceSetIndex); - - if (baseband <= 0) { - baseband = set["samplingDevice"].toObject()["bandwidth"].toInt(); - } - - struct Item { int m_index; QString m_id; uint64_t m_uid; qint64 m_offset; }; - QList items; - - for (const QJsonValue& v : set["channels"].toArray()) - { - QJsonObject channel = v.toObject(); - const int index = channel["index"].toInt(); - const uint64_t uid = channelUidAt(deviceSetIndex, index); - - if ((uid != 0) && !intent.contains(uid)) { - items.append({index, channel["id"].toString(), uid, (qint64) channel["deltaFrequency"].toDouble()}); - } - } - - // Highest index first, so that a removal does not renumber one still to be visited - for (int i = items.size() - 1; i >= 0; i--) - { - const Item& item = items[i]; - const qint64 wanted = (qint64) previousCentre + item.m_offset; // where it was listening - const qint64 offset = wanted - (qint64) centre; - const QString where = QString("%1 at %2 MHz").arg(item.m_id).arg(wanted / 1e6, 0, 'f', 3); - - // The offset key differs by type: most have inputFrequencyOffset, the Channel Analyzer - // frequency, ATV intFrequencyOffset, DATV centerFrequency; a sink or a scanner has none - // and is left alone. Read the live settings to find which, rather than guess - QString offsetKey; - - if ((baseband > 0) && (qAbs(offset) <= baseband * 0.45)) // a tenth kept clear at each edge - { - try - { - QJsonObject current = settingsOf(getChannelSettings(deviceSetIndex, item.m_index)); - - for (const char *key : {"inputFrequencyOffset", "frequency", "intFrequencyOffset", "centerFrequency"}) - { - if (current.contains(key)) - { - offsetKey = key; - break; - } - } - } - catch (const MCPToolError&) {} - } - - if (!offsetKey.isEmpty()) - { - try - { - QJsonObject partial; - partial[offsetKey] = (double) offset; - patchChannelSettings(deviceSetIndex, item.m_index, partial); - outcome.m_kept.append(where); - } - catch (const MCPToolError&) - { - outcome.m_stranded.append(where); - } - } - else if ((baseband > 0) && audioDemods.contains(item.m_id)) - { - try - { - deleteChannelObjectAndWait(item.m_uid); - outcome.m_removed.append(where); - } - catch (const MCPToolError&) - { - outcome.m_stranded.append(where); - } - } - else - { - outcome.m_stranded.append(where); - } - } - - return outcome; -} - -QStringList MCPTools::intentNotes(int deviceSetIndex, const QSet& added, const QStringList& reclaimed, - bool reused, double previousCentre, double centre, const RetuneOutcome& outcome) -{ - QStringList notes; - - if (!reclaimed.isEmpty()) - { - notes.append(QString("Removed %1 channel%2 (%3) that earlier listen or scan calls added to device set %4; pass replace false to keep them.") - .arg(reclaimed.size()).arg(reclaimed.size() == 1 ? "" : "s").arg(reclaimed.join(", ")).arg(deviceSetIndex)); - } - - // Read from the live device set rather than the snapshot pickReceiver made, which still - // lists whatever the reclaim has since removed - QStringList leftovers; - QStringList others; - - for (const ChannelNote& note : channelNotes(deviceSetIndex, added)) { - (note.m_intent ? leftovers : others).append(note.m_id); - } - - // Only possible with replace false, and then it is the caller's own trail - if (!leftovers.isEmpty()) - { - notes.append(QString("Device set %1 still has %2 channel%3 (%4) from earlier listen or scan calls, any audio ones still playing; cleanup removes them.") - .arg(deviceSetIndex).arg(leftovers.size()).arg(leftovers.size() == 1 ? "" : "s").arg(leftovers.join(", "))); - } - - // What the retune did to the channels the user added, and how to put back what it took - if (reused && ((qint64) previousCentre != (qint64) centre) - && !(outcome.m_kept.isEmpty() && outcome.m_removed.isEmpty() && outcome.m_stranded.isEmpty())) - { - QString note = QString("Retuned device set %1 from %2 to %3 MHz.").arg(deviceSetIndex) - .arg(previousCentre / 1e6, 0, 'f', 3).arg(centre / 1e6, 0, 'f', 3); - - if (!outcome.m_kept.isEmpty()) { - note += QString(" Kept %1 other channel%2 on frequency by moving the offset: %3.") - .arg(outcome.m_kept.size()).arg(outcome.m_kept.size() == 1 ? "" : "s").arg(outcome.m_kept.join(", ")); - } - - if (!outcome.m_removed.isEmpty()) { - note += QString(" Removed %1 audio demodulator%2 the new baseband could not hold, which would only have played noise: %3. " - "They were not added by listen or scan; add_channel puts one back.") - .arg(outcome.m_removed.size()).arg(outcome.m_removed.size() == 1 ? "" : "s").arg(outcome.m_removed.join(", ")); - } - - if (!outcome.m_stranded.isEmpty()) { - note += QString(" Left %1 other channel%2 that the new baseband does not hold, not being audio: %3. " - "set_channel_settings inputFrequencyOffset retunes one, delete_channel removes it.") - .arg(outcome.m_stranded.size()).arg(outcome.m_stranded.size() == 1 ? "" : "s").arg(outcome.m_stranded.join(", ")); - } - - notes.append(note); - } - - (void) others; - return notes; -} - -QJsonObject MCPTools::channelReport(int deviceSetIndex, int channelIndex) -{ - SWGSDRangel::SWGChannelReport response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelReportGet(deviceSetIndex, channelIndex, response, error), error, "Get channel report"); - return toJson(response); -} - -void MCPTools::postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions) -{ - QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex); - QString channelType = settings["channelType"].toString(); - - if (!WebAPIUtils::m_channelTypeToActionsKey.contains(channelType)) { - throw MCPToolError(QString("Channel type %1 has no actions").arg(channelType)); - } - - QJsonObject json; - json["channelType"] = channelType; - json["direction"] = settings["direction"].toInt(0); - json[WebAPIUtils::m_channelTypeToActionsKey[channelType]] = actions; - QStringList keys; - extractKeys(actions, keys); - - SWGSDRangel::SWGChannelActions query; - query.init(); - query.fromJsonObject(json); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetChannelActionsPost(deviceSetIndex, channelIndex, keys, query, response, error), error, "Channel action"); -} - -// Finds or creates a receive device set holding a suitable device and sets its sample rate. -// An existing set holding the same device is reused rather than fought for the hardware; the -// caller tunes the centre frequency and is told what else that set carries. -// Takes away the device set listen or scan created when the call fails before it is done -// with it, so a retry does not build another beside a half made one. Cleared on success -class NewDeviceSetGuard -{ -public: - NewDeviceSetGuard(MCPTools *tools, int deviceSetIndex) : - m_tools(tools), - m_deviceSetIndex(deviceSetIndex), - m_identity(deviceSetIndex >= 0 ? tools->deviceSetIdentity(deviceSetIndex) : 0) - {} - ~NewDeviceSetGuard() - { - if (m_deviceSetIndex >= 0) { - m_tools->discardNewDeviceSet(m_deviceSetIndex, m_identity); - } - } - void keep() { m_deviceSetIndex = -1; } - -private: - MCPTools *m_tools; - int m_deviceSetIndex; - uint64_t m_identity; //!< Of the set as it was when this call made it -}; - -QJsonObject MCPTools::pickReceiver(const QJsonObject& args, int minBaseband, const QSet& doomed, bool profileGain) -{ - SWGSDRangel::SWGInstanceDevicesResponse devicesResponse; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->instanceDevices(0, devicesResponse, error), error, "List devices"); - QJsonArray devices = toJson(devicesResponse)["devices"].toArray(); - - // Which device: the one the caller named; else the first real radio that was actually - // enumerated, which is the one with a serial number - some plugins list a placeholder - // entry for hardware that is not attached, and it has none; else anything - QJsonObject chosen; - QJsonObject fallback; - QString wanted = argString(args, "device", false).trimmed(); - - for (const QJsonValue& v : devices) - { - QJsonObject d = v.toObject(); - - if (!wanted.isEmpty()) - { - if ((d["serial"].toString().compare(wanted, Qt::CaseInsensitive) == 0) - || (d["displayedName"].toString().compare(wanted, Qt::CaseInsensitive) == 0) - || (d["hwType"].toString().compare(wanted, Qt::CaseInsensitive) == 0)) - { - chosen = d; - break; - } - } - else if (!virtualDeviceTypes.contains(d["hwType"].toString())) - { - if (!d["serial"].toString().isEmpty()) { chosen = d; break; } - if (fallback.isEmpty()) { fallback = d; } - } - } - - if (chosen.isEmpty() && wanted.isEmpty()) { - chosen = fallback.isEmpty() && !devices.isEmpty() ? devices.first().toObject() : fallback; - } - - if (chosen.isEmpty()) { - throw MCPToolError(QString("No receive device matches %1. list_available_devices shows what there is.").arg(wanted.isEmpty() ? "anything" : wanted)); - } - - QString hwType = chosen["hwType"].toString(); - QString serial = chosen["serial"].toString(); - - // Reuse a device set that already holds this device - int deviceSetIndex = -1; - QJsonArray otherChannels; - QJsonArray deviceSets = getInstanceSummary()["devicesetlist"].toObject()["deviceSets"].toArray(); - - for (const QJsonValue& v : deviceSets) - { - QJsonObject ds = v.toObject(); - QJsonObject sd = ds["samplingDevice"].toObject(); - - if (sd["direction"].toInt() != 0) { - continue; - } - - bool same = serial.isEmpty() ? (sd["hwType"].toString() == hwType) : (sd["serial"].toString() == serial); - - if (same) - { - deviceSetIndex = sd["index"].toInt(); - - // Channels the caller is about to remove are not ones the set has to go on - // serving, so they neither hold the baseband width up nor count as carried - for (const QJsonValue& c : ds["channels"].toArray()) - { - QJsonObject channel = c.toObject(); - - if (!doomed.contains(channelUidAt(deviceSetIndex, channel["index"].toInt()))) { - otherChannels.append(channel["id"].toString()); - } - } - - break; - } - } - - bool reused = deviceSetIndex >= 0; - - if (!reused) { - deviceSetIndex = addDeviceSetAndWait(0); - } - - // Until the caller has it, a set made here that cannot be finished is this function's to - // take away again - NewDeviceSetGuard newDeviceSet(this, reused ? -1 : deviceSetIndex); - - if (!reused) - { - QJsonObject select; - select["hwType"] = hwType; - - if (!serial.isEmpty()) { - select["serial"] = serial; - } - - selectDevice(deviceSetIndex, select); - } - - QJsonObject before = settingsOf(getDeviceSettings(deviceSetIndex)); - - // Only the devices whose rate keys and supported rates are known are set; others keep - // their configured rate and the caller is told to check it - QString rateKey; - - if (hwType == "RTLSDR") { - rateKey = "devSampleRate"; - } else if (hwType == "TestSource") { - rateKey = "sampleRate"; - } - - // A reused device set is already feeding its other channels the width it has. Widening it for - // the new channel leaves them working, narrowing it to what only the new one needs takes their - // signal away, so the width already configured is a floor rather than something to overwrite - int existingBaseband = 0; - - if (reused && !otherChannels.isEmpty() && !rateKey.isEmpty()) - { - int rate = before[rateKey].toInt(); - - if (rate > 0) { - existingBaseband = rate >> before["log2Decim"].toInt(); - } - } - - int devSampleRate = 0; - int log2Decim = 0; - rateFor(qMax(minBaseband, existingBaseband), devSampleRate, log2Decim); - QJsonObject partial; - QString rateNote; - int baseband = 0; - - if (!rateKey.isEmpty()) - { - baseband = devSampleRate >> log2Decim; - - if (baseband < existingBaseband) - { - // Wider than rateFor is able to ask for, so leave the rate alone altogether - baseband = existingBaseband; - rateNote = QString("Device set %1 was left at %2 S/s of baseband, which its other channels need.") - .arg(deviceSetIndex).arg(existingBaseband); - } - else - { - partial[rateKey] = devSampleRate; - partial["log2Decim"] = log2Decim; - - if (existingBaseband > minBaseband) { - rateNote = QString("Device set %1 was kept at %2 S/s of baseband rather than the %3 this channel needs, for its other channels.") - .arg(deviceSetIndex).arg(baseband).arg(minBaseband); - } - } - } - - // Only a device set this call created gets the receiver profile: one that was found is the - // user's, and its gain stays whatever they set - if (!reused && (hwType == "RTLSDR")) - { - partial["dcBlock"] = 1; - partial["iqImbalance"] = 1; - - // A fixed 40 dB when the caller is not about to measure one: the tuner's own AGC is - // unreliable on weak signals, and the default gain left the airband 35 dB down on what - // a hand-set receiver saw - if (profileGain) - { - partial["agc"] = 0; - partial["gain"] = 402; - rateNote = (rateNote.isEmpty() ? QString() : rateNote + " ") - + QString("Device set %1 is new, so its RTL-SDR was set to 40 dB gain with AGC off; set_device_settings changes it.") - .arg(deviceSetIndex); - } - } - - if (!partial.isEmpty()) { - patchDeviceSettings(deviceSetIndex, partial); - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["hwType"] = hwType; - result["device"] = chosen["displayedName"].toString(); - result["reused"] = reused; - result["previousCentre"] = before["centerFrequency"].toDouble(); - result["otherChannels"] = otherChannels; - result["baseband"] = baseband; - result["rateNote"] = rateNote; - newDeviceSet.keep(); - return result; -} - -// The tune_gain tool, also run by listen and scan when they set up a receiver on a new -// device set or move one to another band -QJsonObject MCPTools::tuneGain(const QJsonObject& args) -{ - int deviceSetIndex = argInt(args, "deviceSetIndex"); - QJsonObject reply = getDeviceSettings(deviceSetIndex); - const QString hwType = reply["deviceHwType"].toString(); - QJsonObject settings = settingsOf(reply); - - if (deviceState(deviceSetIndex, 0, -1)["state"].toString() != "running") { - throw MCPToolError("The device is not running, so there is nothing to measure. start_device first."); - } - - // What this knows about each device's gain: the key, its manual AGC setting, and the - // values to try. Where a device has several gain stages the one before the mixer is - // tuned, as that is where overload happens; the rest keep their settings - struct Knob { QString key; QString agcKey; int agcOff; QList values; QString unit; QString note; }; - Knob knob; - const bool custom = hasArg(args, "gainKey"); - - if (custom) - { - knob.key = argString(args, "gainKey"); - knob.agcKey = argString(args, "agcKey", false); - knob.agcOff = 0; - knob.unit = "the key's own units"; - - for (const QJsonValue& v : args["values"].toArray()) { - knob.values.append(v.toDouble()); - } - - if (knob.values.size() < 2) { - throw MCPToolError("Give at least two values to try with gainKey"); - } - } - else if (hwType == "RTLSDR") - { - // The tuner takes only the values it lists, in tenths of a decibel - knob = {"gain", "agc", 0, {}, "tenths of a dB", "The tuner's AGC is off, as it must be for the gain to hold"}; - SWGSDRangel::SWGDeviceReport report; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetDeviceReportGet(deviceSetIndex, report, error), error, "Get device report"); - QJsonObject json = toJson(report); - - for (const QString& key : json.keys()) - { - for (const QJsonValue& g : json[key].toObject()["gains"].toArray()) { - knob.values.append(g.toObject()["gainCB"].toDouble()); - } - } - - if (knob.values.isEmpty()) { - throw MCPToolError("The RTL-SDR reported no supported gain values; is the device open?"); - } - } - else if (hwType == "HackRF") { - knob = {"lnaGain", "", 0, {0, 8, 16, 24, 32, 40}, "dB", "Only the LNA is stepped; vgaGain is left as it is"}; - } - else if (hwType == "Airspy") { - knob = {"lnaGain", "lnaAGC", 0, {0, 2, 4, 6, 8, 10, 12, 14}, "steps", "Only the LNA is stepped; mixerGain and vgaGain are left as they are, with the LNA AGC off"}; - } - else if (hwType == "LimeSDR") { - knob = {"gain", "gainMode", 1, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; - } - else if (hwType == "PlutoSDR") { - knob = {"gain", "gainMode", 0, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; - } - else if (hwType == "USRP") { - knob = {"gain", "gainMode", 1, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; - } - else - { - throw MCPToolError(QString("tune_gain does not know the gain settings of a %1. Read them with describe_settings and " - "give gainKey, values and, if it has one, agcKey.").arg(hwType)); - } - - std::sort(knob.values.begin(), knob.values.end()); - knob.values.erase(std::unique(knob.values.begin(), knob.values.end()), knob.values.end()); - - // Spread the steps over the range rather than trying every value a tuner offers - const int steps = qBound(3, argInt(args, "steps", false, 8), 16); - QList candidates; - - if (knob.values.size() <= steps) { - candidates = knob.values; - } - else - { - for (int i = 0; i < steps; i++) { - candidates.append(knob.values[(int) std::round(i * (knob.values.size() - 1) / (double) (steps - 1))]); - } - } - - const bool apply = argBool(args, "apply", true); - - // A key the device does not have would be patched away as unknown at every step, and the - // sweep would then measure the same gain six times and report a choice it never made - if (!settings.contains(knob.key)) { - throw MCPToolError(QString("%1 has no %2 setting; describe_settings shows its keys").arg(hwType).arg(knob.key)); - } - - if (!knob.agcKey.isEmpty() && !settings.contains(knob.agcKey)) { - throw MCPToolError(QString("%1 has no %2 setting; describe_settings shows its keys").arg(hwType).arg(knob.agcKey)); - } - - const double previous = settings[knob.key].toDouble(); - const double previousAgc = knob.agcKey.isEmpty() ? 0 : settings[knob.agcKey].toDouble(); - const qint64 frequency = (qint64) argDouble(args, "frequency", false, 0); - const qint64 bandwidth = (qint64) argDouble(args, "bandwidth", false, 200000); - - // One reading: the floor is the median over the baseband, the signal the strongest bin, - // in the window asked for or anywhere. Max reduction keeps a narrow carrier - auto measure = [&](double& floorDb, double& peakDb) - { - SWGSDRangel::SWGGLSpectrumData response; - SWGSDRangel::SWGErrorResponse error; - response.init(); - error.init(); - check(m_adapter->devicesetSpectrumDataGet(deviceSetIndex, 256, 0, 0, "max", response, error), error, "Get spectrum data"); - // Read from the object: the generated JSON serialiser drops a list of plain floats - const bool linear = response.getLinear() != 0; - QList powers; - - if (response.getPower()) - { - for (float v : *response.getPower()) { - powers.append(linear ? 10.0 * std::log10(std::max((double) v, 1e-20)) : (double) v); - } - } - - if (powers.isEmpty()) { - throw MCPToolError("The spectrum returned no data"); - } - - QList sorted = powers; - std::sort(sorted.begin(), sorted.end()); - floorDb = sorted[sorted.size() / 2]; - - if (frequency > 0) - { - // The data call clamps to the baseband, which would silently measure noise at - // its edge for a frequency outside it - const qint64 low = response.getCenterFrequency() - response.getBandwidth() / 2; - const qint64 high = response.getCenterFrequency() + response.getBandwidth() / 2; - - if ((frequency < low) || (frequency > high)) - { - throw MCPToolError(QString("%1 MHz is outside the baseband, which covers %2 to %3 MHz; tune the device so that it is inside, or leave frequency out") - .arg(frequency / 1e6, 0, 'f', 3).arg(low / 1e6, 0, 'f', 3).arg(high / 1e6, 0, 'f', 3)); - } - - SWGSDRangel::SWGGLSpectrumData window; - SWGSDRangel::SWGErrorResponse windowError; - window.init(); - windowError.init(); - check(m_adapter->devicesetSpectrumDataGet(deviceSetIndex, 32, frequency - bandwidth / 2, frequency + bandwidth / 2, "max", window, windowError), - windowError, "Get spectrum data"); - peakDb = -1e9; - - if (window.getPower()) - { - for (float v : *window.getPower()) { - peakDb = std::max(peakDb, linear ? 10.0 * std::log10(std::max((double) v, 1e-20)) : (double) v); - } - } - - if (peakDb < -1e8) { - throw MCPToolError("The spectrum has no bins at that frequency; it must be inside the baseband"); - } - } - else - { - peakDb = sorted.last(); - } - }; - - struct Row { double gain; double floorDb; double peakDb; double snrDb; }; - QList rows; - - auto setGain = [&](double gain, bool agcOff) - { - QJsonObject partial; - partial[knob.key] = gain; - - if (!knob.agcKey.isEmpty()) { - partial[knob.agcKey] = agcOff ? knob.agcOff : previousAgc; - } - - patchDeviceSettings(deviceSetIndex, partial); - }; - - try - { - for (double gain : candidates) - { - setGain(gain, true); - pause(700); // the tuner, the spectrum averaging and a stale FFT - double floorSum = 0.0; - double peakSum = 0.0; - const int samples = 3; - - for (int i = 0; i < samples; i++) - { - if (i > 0) { - pause(250); - } - - double floorDb, peakDb; - measure(floorDb, peakDb); - floorSum += floorDb; - peakSum += peakDb; - } - - rows.append({gain, floorSum / samples, peakSum / samples, (peakSum - floorSum) / samples}); - } - } - catch (const MCPToolError&) - { - setGain(previous, false); // as it was, AGC included - throw; - } - - auto toDb = [&](double gain) { return (knob.unit == "tenths of a dB") ? gain / 10.0 : gain; }; - - // Overload shows as the floor climbing faster than the gain did. The first step - // where it does bounds the usable range from above - QStringList notes; - int compressed = 0; - int overloadFrom = rows.size(); // index of the first row that is overloaded - - for (int i = 1; i < rows.size(); i++) - { - const double gainStep = toDb(rows[i].gain) - toDb(rows[i - 1].gain); - - if ((gainStep > 0) && (rows[i].floorDb - rows[i - 1].floorDb > gainStep + 3.0)) - { - compressed++; - overloadFrom = std::min(overloadFrom, i); - } - } - - if (compressed > 0) { - notes.append(QString("The noise floor rose faster than the gain over %1 step%2, which is the front end overloading; the higher gains are not usable here.") - .arg(compressed).arg(compressed == 1 ? "" : "s")); - } - - // Best SNR, then the lowest gain within a decibel of it - double best = -1e9; - for (const Row& r : rows) { best = std::max(best, r.snrDb); } - const Row *chosen = nullptr; - QString judgedBy = frequency > 0 ? QString("the signal at %1 MHz").arg(frequency / 1e6, 0, 'f', 3) : QString("the strongest signal in the baseband"); - - if (best >= 6.0) - { - for (const Row& r : rows) { if ((r.snrDb >= best - 1.0) && !chosen) { chosen = &r; } } - } - else - { - // Nothing stood clear of the floor, so the floor itself has to decide: at low gain - // it is the converter's own noise and does not move; as gain rises the antenna's - // noise comes through and lifts it, which is when weak signals become receivable; - // and past overload it lifts faster than the gain. Take the lowest gain that puts - // the floor 8 dB above the converter's, which is the antenna's noise dominating - // by the usual 10 dB rule with a little allowance for the steps being coarse, or - // the last gain before overload if none does - double adcFloor = 1e9; - for (const Row& r : rows) { adcFloor = std::min(adcFloor, r.floorDb); } - const int lastUsable = std::max(0, overloadFrom - 1); - static const double antennaDominates = 8.0; - - for (int i = 0; (i <= lastUsable) && !chosen; i++) - { - if (rows[i].floorDb >= adcFloor + antennaDominates) { - chosen = &rows[i]; - } - } - - if (!chosen) { - chosen = &rows[lastUsable]; - } - - judgedBy = "the noise floor alone, as no signal stood clear of it"; - notes.append(QString("No signal stood more than 6 dB above the floor, so the gain is set from the floor instead: %1.") - .arg((rows[lastUsable].floorDb < adcFloor + antennaDominates) - ? "the floor never rose 8 dB above the converter's own noise before overload, so the last gain before overload is taken; check the antenna if that seems low" - : "the lowest gain at which the antenna's noise, not the converter's, sets the floor")); - } - - if (chosen == &rows.last()) { - notes.append("The best was the highest gain tried: the signal is weak or the site quiet, and more gain would not overload yet."); - } else if (chosen == &rows.first()) { - notes.append("The best was the lowest gain tried: a strong-signal site. Consider an attenuator if the floor still rises with the lowest gain."); - } - - bool autoscaled = false; - - if (apply) - { - setGain(chosen->gain, true); - - // The spectrum was scaled for the gain it had, and a change of tens of decibels - // leaves the trace off the top or along the bottom of the display. Once the new gain - // has reached the trace, the range is set from it, as the GUI's autoscale button does - if (argBool(args, "autoscale", true)) - { - try - { - pause(700); - autoscaleSpectrum(deviceSetIndex); - autoscaled = true; - } - catch (const MCPToolError& e) - { - notes.append(QString("The spectrum could not be autoscaled: %1").arg(e.message)); - } - } - } - else - { - setGain(previous, false); - notes.append("Not applied: the gain is back as it was."); - } - - if (!knob.note.isEmpty()) { - notes.append(knob.note + "."); - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["hwType"] = hwType; - result["autoscaled"] = autoscaled; - result["gainKey"] = knob.key; - result["unit"] = knob.unit; - result["previous"] = previous; - result["chosen"] = chosen->gain; - result["applied"] = apply; - result["bestSnrDb"] = chosen->snrDb; - result["judgedBy"] = judgedBy; - QJsonArray table; - - for (const Row& r : rows) - { - QJsonObject o; - o["gain"] = r.gain; - o["floorDb"] = std::round(r.floorDb * 10) / 10; - o["signalDb"] = std::round(r.peakDb * 10) / 10; - o["snrDb"] = std::round(r.snrDb * 10) / 10; - table.append(o); - } - - result["table"] = table; - - if (!notes.isEmpty()) { - result["note"] = notes.join(" "); - } - - return result; -} - -// A mode whose output is only useful through a feature, such as AIS to the AIS feature's ship -// list and the map, gets that feature added with the demodulator. One that is there already is -// left alone, whatever it is set to -int MCPTools::ensureFeature(const QString& featureType, int& featureIndex) -{ - for (const QJsonValue& v : getInstanceSummary()["featureset"].toObject()["features"].toArray()) - { - QJsonObject f = v.toObject(); - - if (f["id"].toString() == featureType) - { - featureIndex = f["index"].toInt(); - return 0; - } - } - - featureIndex = addFeatureAndWait(featureType); - trackIntentFeature(featureUidAt(featureIndex)); - return 1; -} - -void MCPTools::trackIntentFeature(uint64_t featureUid) -{ - if (featureUid == 0) { - return; - } - - QMutexLocker locker(&m_intentMutex); - m_intentFeatures.insert(featureUid); -} - -// A feature listen added goes with the demodulators that fed it: once the last of those is -// reclaimed, on whichever device set, it would only show stale data. One the next mode -// needs, or that a demodulator anywhere still feeds, stays: the user may have added their own -// decoder since and be reading the feature through it -QStringList MCPTools::reclaimIntentFeatures(const QString& keepType) -{ - QSet tracked; - { - QMutexLocker locker(&m_intentMutex); - tracked = m_intentFeatures; - } - - if (tracked.isEmpty()) { - return QStringList(); - } - - // The feature types the remaining channels feed, whoever added them - QSet needed; - - if (!keepType.isEmpty()) { - needed.insert(keepType); - } - - for (int deviceSetIndex = 0; deviceSetIndex < deviceSetCount(); deviceSetIndex++) - { - for (const ChannelNote& note : channelNotes(deviceSetIndex)) - { - const char *feature = featureForChannelType(note.m_id); - - if (feature) { - needed.insert(QString(feature)); - } - } - } - - QStringList removed; - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (featureSets.empty()) { - return removed; - } - - // Collected first: deleting renumbers the rest, and by UID, as each deletion waits - QList> doomed; - - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - const Feature *feature = featureSets[0]->getFeatureAt(i); - - if (feature && tracked.contains(feature->getUID()) && !needed.contains(feature->getIdentifier())) { - doomed.append(qMakePair(feature->getUID(), feature->getIdentifier())); - } - } - - for (const auto& feature : doomed) - { - try - { - deleteFeatureObjectAndWait(feature.first); - removed.append(feature.second); - } - catch (const MCPToolError&) {} - } - - // Tracked no longer: those removed, and any the user had already deleted - QMutexLocker locker(&m_intentMutex); - - for (uint64_t uid : tracked) - { - bool present = false; - - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - const Feature *feature = featureSets[0]->getFeatureAt(i); - - if (feature && (feature->getUID() == uid)) - { - present = true; - break; - } - } - - if (!present) { - m_intentFeatures.remove(uid); - } - } - - return removed; -} - -void MCPTools::deleteFeatureObjectAndWait(uint64_t featureUid) -{ - QMutexLocker deletionLock(&m_deletionMutex); - int featureIndex = -1; - const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); - - if (!featureSets.empty() && (featureUid != 0)) - { - for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) - { - const Feature *feature = featureSets[0]->getFeatureAt(i); - - if (feature && (feature->getUID() == featureUid)) - { - featureIndex = i; - break; - } - } - } - - if (featureIndex < 0) { - return; // Already gone - } - - requireNotSelf(featureIndex, "deleted"); - SWGSDRangel::SWGSuccessResponse response; - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->featuresetFeatureDelete(0, featureIndex, response, error), error, "Delete feature"); - - if (!waitFor([&]() { return !featureUids().contains(featureUid); })) { - throw MCPToolError(QString("Timed out waiting for feature %1 to be removed").arg(featureIndex)); - } -} - -void MCPTools::autoscaleSpectrum(int deviceSetIndex) -{ - QJsonObject actions; - actions["autoscale"] = 1; - QStringList keys; - extractKeys(actions, keys); - SWGSDRangel::SWGSpectrumActions query; - query.init(); - query.fromJsonObject(actions); - SWGSDRangel::SWGErrorResponse error; - error.init(); - check(m_adapter->devicesetSpectrumActionsPost(deviceSetIndex, keys, query, error), error, "Autoscale spectrum"); -} - -// The history the spectrum tools read is the display's scroll buffer, which fills only while -// scrolling is on. Switched on here with a length that covers what was asked for at a -// typical refresh rate, and at least a couple of minutes; a longer length the user has set -// is left alone -QString MCPTools::ensureSpectrumHistory(int deviceSetIndex, double seconds) -{ - QJsonObject settings = getSpectrumSettings(deviceSetIndex); - const bool scrolling = settings["scrollBar"].toInt() != 0; - const int length = settings["scrollLength"].toInt(); - const int wanted = qBound(1200, (int) (seconds * 20.0), 4000); - - if (scrolling && (length >= wanted)) { - return QString(); - } - - QJsonObject partial; - partial["scrollBar"] = 1; - partial["scrollLength"] = qMax(length, wanted); - patchSpectrumSettings(deviceSetIndex, partial); - return scrolling - ? QString("The spectrum history was lengthened to %1 rows to cover %2 seconds.").arg(qMax(length, wanted)).arg(seconds) - : QString("Spectrum scrolling was switched on, as the history the spectrum keeps for it is what this reads; it starts now."); -} - -// The gain suits a band and an antenna, not a mode: a device set that was just created has -// whatever gain it came with, and one moved to another band has the gain of the last one. A -// move within a band, or a change of mode on the same frequency, needs no new measurement -bool MCPTools::gainWorthTuning(bool reused, double previousCentre, double centre) -{ - if (!reused) { - return true; - } - - return std::abs(centre - previousCentre) > 0.1 * std::max(centre, previousCentre); -} - -void MCPTools::registerIntentTools() -{ - static const QString deviceHint = "Optional: which device, by serial, displayed name or type (e.g. RTLSDR) as shown by " - "list_available_devices. Default: the first radio attached to this machine"; - - add("listen", - "Receive a frequency in one call: picks a device, creates or reuses its device set, sets the sample rate, adds the " - "demodulator with sensible settings, starts the device and reports the signal level. Audio plays on the default output. " - "Use the individual tools afterwards to adjust, e.g. set_channel_settings for squelch or volume. Modes whose output " - "goes to a feature add it too: ais adds the AIS feature, sonde the Radiosonde feature and aprs the APRS feature, whose " - "reports and map items carry what was decoded; a later listen or scan removes the feature again once nothing it added " - "feeds it. ais is received on two channels, so give 162000000 and it puts a demodulator on each of 161.975 and " - "162.025 MHz.", - schema({ - {"frequency", numProp("Frequency to receive in Hz, e.g. 97300000 for 97.3 MHz")}, - {"mode", strProp("bfm (broadcast FM with stereo and RDS), wfm, nfm, am or airband, ssb/usb, lsb, dab, adsb, ais, dsc, dsd/dmr, " - "dmr, dpmr, dstar, ysf, nxdn or nxdn24 (digital voice through the DSD demodulator with the deviation and baud rate of that standard), " - "pager (POCSAG), sonde (RS41 radiosondes), packet (AX.25), aprs (APRS with its feature), or any channel type id from list_channel_types. Default nfm")}, - {"device", strProp(deviceHint)}, - {"replace", prop("boolean", "Retune the demodulator a previous listen added to this device set when it is of the same type, and remove every other channel earlier listen and scan calls added there, so that exploring a band does not leave a trail of demodulators all playing audio and mis-tuned for the current centre frequency. Channels added any other way are kept on their frequency where the baseband still holds them; audio demodulators it cannot hold are removed, anything else is left and named. Default true")}, - {"tuneGain", prop("boolean", "Measure and set the receiver gain, as tune_gain does, when the device set is new or the retune is to another band (more than a tenth of the frequency away). Adds several seconds in those cases and none otherwise. false leaves the gain as it is. Default true")} - }, {"frequency"}), - [this](const QJsonObject& args) - { - qint64 frequency = (qint64) argDouble(args, "frequency"); - QString modeName = argString(args, "mode", false, "nfm").trimmed(); - const ListenMode *mode = findListenMode(modeName); - QString channelType; - int rfBandwidth = 0; - int minBaseband = 256000; - QJsonObject initial; - QString companionFeature; - int pairOffset = 0; - - if (mode) - { - channelType = mode->m_channelType; - rfBandwidth = mode->m_rfBandwidth; - minBaseband = mode->m_minBaseband; - initial = QJsonDocument::fromJson(mode->m_settings).object(); - companionFeature = mode->m_feature ? QString(mode->m_feature) : QString(); - pairOffset = mode->m_pairOffset; - } - else - { - for (const QString& id : channelTypeIds(0)) - { - if (id.compare(modeName, Qt::CaseInsensitive) == 0) { - channelType = id; - } - } - - if (channelType.isEmpty()) { - throw MCPToolError(QString("Unknown mode %1. Use one of %2, or a channel type from list_channel_types").arg(modeName).arg(listenModeList)); - } - } - - const bool replace = argBool(args, "replace", true); - const bool wantTuneGain = argBool(args, "tuneGain", true); - QJsonObject receiver = pickReceiver(args, minBaseband, replace ? intentChannels() : QSet(), !wantTuneGain); - int deviceSetIndex = receiver["deviceSetIndex"].toInt(); - - // A device set this call created and cannot finish is taken away again, or a retry - // would build another beside it - NewDeviceSetGuard newDeviceSet(this, receiver["reused"].toBool() ? -1 : deviceSetIndex); - int baseband = receiver["baseband"].toInt(); - - // Keep the channel off the device's DC spike when the baseband has room for it: far - // enough that the spike falls outside the channel, or not at all. A spike inside a - // wide FM channel is an interferer 25 kHz from the carrier, which is worse than one - // on the carrier itself - int offset = 0; - - if ((pairOffset == 0) && (rfBandwidth != 0) && (baseband > 0)) - { - const int clear = qAbs(rfBandwidth) / 2 + 25000; // spike 25 kHz beyond the channel edge - - if (baseband / 2 >= clear + qAbs(rfBandwidth) / 2) { - offset = -clear; - } - } - - // A paired mode, such as AIS on 161.975 and 162.025 MHz, centres the device on the - // frequency asked for and puts a demodulator either side of it - const qint64 centre = (pairOffset != 0) ? frequency : frequency - offset; - - if (pairOffset != 0) { - offset = -pairOffset; - } - - // A demodulator of the right type that a previous listen added is retuned rather - // than replaced; anything else the intent tools added goes as before - int channelIndex = -1; - uint64_t channel = replace ? reusableIntentChannel(deviceSetIndex, channelType, channelIndex, pairOffset != 0 ? 2 : 1) : 0; - const bool retuned = channel != 0; - - // A paired mode keeps its other demodulator through the reclaim as well - QSet kept; - - if (retuned) - { - kept.insert(channel); - - if (pairOffset != 0) - { - for (const ChannelNote& note : channelNotes(deviceSetIndex, {channel})) - { - if (note.m_intent && (note.m_id == channelType)) - { - kept.insert(note.m_uid); - break; - } - } - } - } - - const QStringList reclaimed = replace ? reclaimIntentChannels(deviceSetIndex, kept) : QStringList(); - const QStringList reclaimedFeatures = replace ? reclaimIntentFeatures(companionFeature) : QStringList(); - - // The device is retuned only once the reclaim is done: a scanner an earlier scan - // left running would otherwise step the device on again between the two, and the - // demodulator would be added against a centre the scanner chose - QJsonObject tune; - tune["centerFrequency"] = (double) centre; - patchDeviceSettings(deviceSetIndex, tune); - const RetuneOutcome outcome = receiver["reused"].toBool() - ? retuneOtherChannels(deviceSetIndex, receiver["previousCentre"].toDouble(), (double) centre, baseband) - : RetuneOutcome(); - - if (retuned) - { - // The reclaim may have renumbered it - relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); - } - else - { - channelIndex = addChannelAndWait(deviceSetIndex, channelType); - channel = channelUidAt(deviceSetIndex, channelIndex); - trackIntentChannel(channel); - } - - initial["inputFrequencyOffset"] = offset; - - if (rfBandwidth != 0) { - initial["rfBandwidth"] = rfBandwidth; - } - - QJsonObject patched; - QString state; - - // Do not leave a half configured channel behind if setting it up fails. One that was - // there already stays, as the previous listen left it - try - { - patched = patchChannelSettings(deviceSetIndex, channelIndex, initial); - state = deviceState(deviceSetIndex, 0, 1)["state"].toString(); - } - catch (const MCPToolError&) - { - if (!retuned) - { - try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} - untrackIntentChannel(channel); - } - - throw; - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["channelIndex"] = channelIndex; - result["device"] = receiver["device"]; - result["frequency"] = (double) frequency; - result["mode"] = modeName; - result["channelType"] = channelType; - result["state"] = state; - QStringList notes; - - if (retuned) - { - result["retuned"] = true; - notes.append(QString("Retuned the %1 a previous listen added to device set %2 rather than adding another; its other settings are as they were.") - .arg(channelType).arg(deviceSetIndex)); - } - - // The second demodulator of a paired mode, on the other channel. A retuned first - // one may already have its partner from the previous listen; a fresh one needs it - uint64_t partner = 0; - - if (pairOffset != 0) - { - int partnerIndex = -1; - - for (const ChannelNote& note : channelNotes(deviceSetIndex, {channel})) - { - if (note.m_intent && (note.m_id == channelType)) - { - partnerIndex = note.m_index; - partner = note.m_uid; - break; - } - } - - if (partner == 0) - { - partnerIndex = addChannelAndWait(deviceSetIndex, channelType); - partner = channelUidAt(deviceSetIndex, partnerIndex); - trackIntentChannel(partner); - } - - QJsonObject partnerSettings = initial; - partnerSettings["inputFrequencyOffset"] = pairOffset; - - try - { - patchChannelSettings(deviceSetIndex, partnerIndex, partnerSettings); - } - catch (const MCPToolError& e) - { - notes.append(QString("The second %1 could not be configured: %2").arg(channelType).arg(e.message)); - } - - relocateChannel(partner, deviceSetIndex, partnerIndex, "second demodulator"); - relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); - result["channelIndex"] = channelIndex; - result["secondChannelIndex"] = partnerIndex; - QJsonArray frequencies; - frequencies.append((double) (frequency - pairOffset)); - frequencies.append((double) (frequency + pairOffset)); - result["frequencies"] = frequencies; - notes.append(QString("%1 is received on two channels, so there are two %2: channel %3 on %4 MHz and channel %5 on %6 MHz, with the device centred between them.") - .arg(modeName.toUpper()).arg(channelType).arg(channelIndex).arg((frequency - pairOffset) / 1e6, 0, 'f', 3) - .arg(partnerIndex).arg((frequency + pairOffset) / 1e6, 0, 'f', 3)); - } - - // The feature the mode's output goes to, so that the decoded data has somewhere to be - // read from and shown - if (!companionFeature.isEmpty()) - { - try - { - int featureIndex = -1; - const int added = ensureFeature(companionFeature, featureIndex); - result["featureIndex"] = featureIndex; - result["featureType"] = companionFeature; - notes.append(added - ? QString("Added the %1 feature (F%2), which collects what the demodulator decodes; get_feature_report reads it, and it feeds the map.").arg(companionFeature).arg(featureIndex) - : QString("The %1 feature (F%2) is already there and collects what the demodulator decodes.").arg(companionFeature).arg(featureIndex)); - } - catch (const MCPToolError& e) - { - notes.append(QString("The %1 feature could not be added: %2").arg(companionFeature).arg(e.message)); - } - } - - if (state == "running") - { - // A new device set, or one moved to another band, has no gain to speak of yet - if (wantTuneGain && gainWorthTuning(receiver["reused"].toBool(), receiver["previousCentre"].toDouble(), (double) centre)) - { - QJsonObject gainArgs; - gainArgs["deviceSetIndex"] = deviceSetIndex; - gainArgs["frequency"] = (double) frequency; - gainArgs["bandwidth"] = (double) (rfBandwidth != 0 ? qAbs(rfBandwidth) : 2000000); - gainArgs["steps"] = 6; - - try - { - QJsonObject tuned = tuneGain(gainArgs); - QJsonObject gain; - gain["key"] = tuned["gainKey"]; - gain["value"] = tuned["chosen"]; - gain["unit"] = tuned["unit"]; - gain["snrDb"] = tuned["bestSnrDb"]; - result["gain"] = gain; - notes.append(QString("Gain measured and set to %1 (%2), judged by %3, as %4%5; tune_gain shows the table, and tuneGain false leaves the gain alone.") - .arg(tuned["chosen"].toDouble()).arg(tuned["unit"].toString()).arg(tuned["judgedBy"].toString()) - .arg(receiver["reused"].toBool() ? "the retune was to another band" : "the device set is new") - .arg(tuned["autoscaled"].toBool() ? ", and the spectrum autoscaled to suit it" : "")); - } - catch (const MCPToolError& e) - { - notes.append(QString("The gain was not measured: %1").arg(e.message)); - } - } - - pause(1500); - // The channel may have been renumbered while we waited - relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); - result["deviceSetIndex"] = deviceSetIndex; - result["channelIndex"] = channelIndex; - - // The power measurement sits at the channel's floor until the demodulator has run - // for a moment, and a floor reading looks exactly like an empty band. Wait for a - // real one: reporting the floor has sent callers away from a signal that was - // decoding perfectly well. CalcDb::dbPower returns 10*log10(floor) while there is - // nothing to measure, which is -100 dB or below for every floor in use here - double db = 0.0; - bool measured = false; - bool noReport = false; - QElapsedTimer settling; - settling.start(); - - while (true) - { - QJsonObject report; - - // A demodulator with no report at all (APT, ATV) is not a failure of the - // receiver that was just built - try - { - report = channelReport(deviceSetIndex, channelIndex); - } - catch (const MCPToolError&) - { - noReport = true; - break; - } - - if (signalLevel(report, db)) - { - measured = true; - - if (db > -100.0) { - break; - } - } - - if (settling.elapsed() > 4000) { - break; - } - - pause(250); - } - - if (noReport) - { - notes.append(QString("%1 has no channel report, so there is no signal level to give; %2.") - .arg(channelType) - .arg(companionFeature.isEmpty() ? QString("get_spectrum_data shows whether there is a signal") - : QString("what it decodes appears in the %1 feature's report and in get_packets").arg(companionFeature))); - } - else if (measured) - { - result["signalDb"] = db; - - if (db <= -100.0) { - notes.append("signalDb is still at the measurement floor, which usually means the channel " - "has not settled rather than that the band is empty. Read get_channel_report again in " - "a few seconds before concluding nothing is there."); - } - } - } - else - { - notes.append("The device did not start. If another device set holds the same hardware, stop it first, or pass a different device."); - } - - if (baseband > 0) { - result["basebandSampleRate"] = baseband; - } else { - notes.append(QString("The sample rate of a %1 was left as configured; check it exceeds %2 S/s with get_device_settings.").arg(receiver["hwType"].toString()).arg(minBaseband)); - } - - if (!receiver["rateNote"].toString().isEmpty()) { - notes.append(receiver["rateNote"].toString()); - } - - notes.append(intentNotes(deviceSetIndex, partner ? QSet({channel, partner}) : QSet({channel}), - reclaimed, receiver["reused"].toBool(), - receiver["previousCentre"].toDouble(), (double) centre, outcome)); - notes.append(featureNotes(reclaimedFeatures)); - - if (patched.contains("warning")) { - notes.append(patched["warning"].toString()); - } - - if (!notes.isEmpty()) { - result["note"] = notes.join(" "); - } - - newDeviceSet.keep(); - return result; - }); - - QJsonObject frequencyList = prop("array", "Frequencies to scan in Hz. Alternatively give startFrequency, stopFrequency and stepFrequency"); - QJsonObject items; - items["type"] = "number"; - frequencyList["items"] = items; - - add("scan", - "Scan a set of frequencies for activity and listen to whichever is active, in one call: sets up a receiver, a demodulator " - "and a Frequency Scanner, starts scanning, watches for a while and reports what it found. active lists every frequency " - "above the threshold with its level, strongest first; that is the list to use for stations and other continuous " - "signals. heard lists where the scanner parked and for how long, which only tells intermittent signals apart, since " - "on a continuous carrier it parks on the first and stays. " - "The scanner keeps running afterwards; get_channel_report on the scanner channel shows its state (2 scanning, 3 receiving, " - "4 holding), channel_action {\"run\": 0} stops it. The demodulator and scanner it added stay on the device set until the " - "next listen or scan there replaces them, or cleanup removes them; they are not removed when this call returns. " - "Blocks for the watch period, so it is capped at 30 seconds.", - schema({ - {"frequencies", frequencyList}, - {"startFrequency", numProp("Start of a range in Hz, with stopFrequency and stepFrequency")}, - {"stopFrequency", numProp("End of the range in Hz, inclusive")}, - {"stepFrequency", numProp("Channel spacing in Hz. Optional: without it the spacing usual for the mode is used (bfm 100 kHz, am 25 kHz, " - "nfm/dsd/pager 12.5 kHz, sonde 10 kHz, ssb 3 kHz), which is the right choice unless the band is known to differ, " - "e.g. 8333 for airband 8.33 kHz channels in Europe. Broadcast FM stations sit on a 100 kHz raster everywhere; only " - "the Americas confine them to the odd tenths, so bfm/wfm ranges are scanned at 100 kHz whatever step is given")}, - {"mode", strProp("Demodulator, as for listen: bfm, wfm, nfm, am, ssb/usb/lsb, dsd, pager, sonde. Modes on fixed frequencies (adsb, ais, " - "dab, dsc) cannot be scanned for; listen to those directly. Default am")}, - {"threshold", numProp("Power in dB above which a frequency counts as active. Leave it out unless you have a reason: the scale " - "depends on the device and its gain, so by default the noise floor is measured first and the threshold set " - "12 dB above it. Both are reported, so a second scan can adjust")}, - {"seconds", bounded(numProp("How long to watch before replying, 3 to 30. Default 10"), 3, 30)}, - {"device", strProp(deviceHint)}, - {"replace", prop("boolean", "Remove every channel earlier listen and scan calls added to this device set first, as listen does. Channels added any other way are kept on their frequency where the baseband still holds them; audio demodulators it cannot hold are removed, anything else is left and named. Default true")}, - {"tuneGain", prop("boolean", "Measure and set the receiver gain first, as tune_gain does, when the device set is new or the retune is to another band. Adds several seconds in those cases and none otherwise. false leaves the gain as it is. Default true")} - }), - [this](const QJsonObject& args) - { - QList frequencies; - const bool fromRange = !hasArg(args, "frequencies"); - qint64 rangeStart = 0; - qint64 rangeStop = 0; - qint64 rangeStep = 0; // as given; zero to step by the mode's usual channel spacing - - if (fromRange) - { - rangeStart = (qint64) argDouble(args, "startFrequency"); - rangeStop = (qint64) argDouble(args, "stopFrequency"); - rangeStep = hasArg(args, "stepFrequency") ? (qint64) argDouble(args, "stepFrequency") : 0; - - if ((rangeStep < 0) || (rangeStop < rangeStart)) { - throw MCPToolError("stepFrequency must be positive and stopFrequency at least startFrequency"); - } - } - else - { - for (const QJsonValue& v : args["frequencies"].toArray()) { - frequencies.append((qint64) v.toDouble()); - } - - if (frequencies.isEmpty()) { - throw MCPToolError("Give frequencies, or startFrequency and stopFrequency"); - } - } - - QString modeName = argString(args, "mode", false, "am").trimmed(); - const ListenMode *mode = findListenMode(modeName); - - if (!mode) { - throw MCPToolError(QString("Unknown mode %1. Use one of %2").arg(modeName).arg(listenModeList)); - } - - // A mode on fixed frequencies has nothing to be found by stepping - if (mode->m_scanStep == 0) - { - throw MCPToolError(QString("%1 is received on fixed frequencies, so there is nothing to scan for: listen to them directly. " - "get_receiving_guide lists them (ADS-B 1090 MHz; AIS 161.975 and 162.025 MHz; DSC 2187.5 kHz, 8414.5 kHz, " - "16804.5 kHz and 156.525 MHz; DAB on the Band III blocks, one dab channel per block).").arg(mode->m_channelType)); - } - - // Without a threshold, measure the noise floor first and sit 12 dB above it: the - // level scale depends on the device and its gain, so no fixed number suits all - bool autoThreshold = !hasArg(args, "threshold"); - double threshold = autoThreshold ? -100.0 : argDouble(args, "threshold"); - int seconds = qBound(3, (int) argDouble(args, "seconds", false, 10.0), 30); - int channelBandwidth = qAbs(mode->m_rfBandwidth) > 0 ? qAbs(mode->m_rfBandwidth) : 8000; - - // Broadcast FM stations sit on a 100 kHz raster everywhere but the Americas, where - // they keep to the odd tenths. A 200 kHz step from 87.5 MHz, the usual assumption, - // lands beside every even-tenth station: with a channel this wide the station still - // shows up, 100 kHz off and weaker, and then nothing decodes. So a coarser step on - // a broadcast range is scanned at 100 kHz, which loses nothing where the odd tenths - // are the rule - const bool broadcast = (mode->m_channelType == "BFMDemod") || (mode->m_channelType == "WFMDemod"); - QString rasterNote; - - if (fromRange) - { - qint64 step = (rangeStep > 0) ? rangeStep : mode->m_scanStep; - - if (broadcast && (step > 100000)) - { - step = 100000; - rasterNote = QString("Scanned at 100 kHz rather than the %1 kHz step given: broadcast FM stations are on a 100 kHz raster " - "outside the Americas, and a coarser step lands beside them rather than on them.").arg(rangeStep / 1000.0, 0, 'g', 4); - } - else if (rangeStep > mode->m_scanStep) - { - rasterNote = QString("The %1 kHz step given is coarser than the %2 kHz channel spacing usual for %3, so channels between the steps were not seen.") - .arg(rangeStep / 1000.0, 0, 'g', 4).arg(mode->m_scanStep / 1000.0, 0, 'g', 4).arg(modeName); - } - else if (rangeStep == 0) - { - rasterNote = QString("Stepped by %1 kHz, the channel spacing usual for %2; give stepFrequency for another.") - .arg(step / 1000.0, 0, 'g', 4).arg(modeName); - } - - // Counted before it is built: a step given in kHz by mistake, 12 Hz for 12.5, - // would otherwise fill millions of entries before the limit was looked at - const qint64 count = (rangeStop - rangeStart) / step + 1; - - if (count > 2000) { - throw MCPToolError(QString("%1 frequencies is too many; use a coarser step or a narrower range (2000 at most)").arg(count)); - } - - for (qint64 f = rangeStart; f <= rangeStop; f += step) { - frequencies.append(f); - } - } - - if (frequencies.size() > 2000) { - throw MCPToolError(QString("%1 frequencies is too many; use a coarser step or a narrower range (2000 at most)").arg(frequencies.size())); - } - - std::sort(frequencies.begin(), frequencies.end()); - - // A wide baseband means fewer retunes per sweep - const bool replace = argBool(args, "replace", true); - const bool wantTuneGain = argBool(args, "tuneGain", true); - QJsonObject receiver = pickReceiver(args, 2400000, replace ? intentChannels() : QSet(), !wantTuneGain); - int deviceSetIndex = receiver["deviceSetIndex"].toInt(); - NewDeviceSetGuard newDeviceSet(this, receiver["reused"].toBool() ? -1 : deviceSetIndex); - - // The reclaim comes before the retune: a scanner an earlier scan left running would - // otherwise move the device again between the two - const QStringList reclaimed = replace ? reclaimIntentChannels(deviceSetIndex) : QStringList(); - const QStringList reclaimedFeatures = replace ? reclaimIntentFeatures() : QStringList(); - QJsonObject tune; - tune["centerFrequency"] = (double) ((frequencies.first() + frequencies.last()) / 2); - patchDeviceSettings(deviceSetIndex, tune); - const RetuneOutcome outcome = receiver["reused"].toBool() - ? retuneOtherChannels(deviceSetIndex, receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble(), receiver["baseband"].toInt()) - : RetuneOutcome(); - - int demod = addChannelAndWait(deviceSetIndex, mode->m_channelType); - const uint64_t demodChannel = channelUidAt(deviceSetIndex, demod); - trackIntentChannel(demodChannel); - int scanner = -1; - uint64_t scannerChannel = 0; - - // Anything that fails from here on removes both channels rather than leaving a - // half built scanner running on the user's radio - auto discard = [&]() - { - if (scannerChannel != 0) - { - try { deleteChannelObjectAndWait(scannerChannel); } catch (const MCPToolError&) {} - untrackIntentChannel(scannerChannel); - } - - try { deleteChannelObjectAndWait(demodChannel); } catch (const MCPToolError&) {} - untrackIntentChannel(demodChannel); - }; - - try - { - QJsonObject initial = QJsonDocument::fromJson(mode->m_settings).object(); - initial["inputFrequencyOffset"] = 0; - - if (mode->m_rfBandwidth != 0) { - initial["rfBandwidth"] = mode->m_rfBandwidth; - } - - patchChannelSettings(deviceSetIndex, demod, initial); - scanner = addChannelAndWait(deviceSetIndex, "FreqScanner"); - scannerChannel = channelUidAt(deviceSetIndex, scanner); - trackIntentChannel(scannerChannel); - } - catch (const MCPToolError&) - { - discard(); - throw; - } - - // Everything up to the scanner running with its threshold is set up, and a failure - // anywhere in it, the device not starting, the scanner refusing its settings or - // its run action, or measuring nothing, removes both channels the same way - QString gainNote; - double measuredFloor = 0.0; - bool haveFloor = false; - - try - { - QString state = deviceState(deviceSetIndex, 0, 1)["state"].toString(); - - if (state != "running") { - throw MCPToolError(QString("The device did not start (state %1), so the demodulator and scanner were removed again.").arg(state)); - } - - // Before the scanner measures anything: the gain sets the floor it measures against - if (wantTuneGain && gainWorthTuning(receiver["reused"].toBool(), receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble())) - { - QJsonObject gainArgs; - gainArgs["deviceSetIndex"] = deviceSetIndex; - gainArgs["steps"] = 6; - - try - { - QJsonObject tuned = tuneGain(gainArgs); - gainNote = QString("Gain measured and set to %1 (%2) first, as %3%4; tuneGain false leaves it alone.") - .arg(tuned["chosen"].toDouble()).arg(tuned["unit"].toString()) - .arg(receiver["reused"].toBool() ? "the retune was to another band" : "the device set is new") - .arg(tuned["autoscaled"].toBool() ? ", and the spectrum autoscaled to suit it" : ""); - } - catch (const MCPToolError& e) - { - gainNote = QString("The gain was not measured: %1").arg(e.message); - } - } - - // The scanner's baseband only takes settings while it is running, so configure it - // after the device has started - pause(1500); - relocateChannel(demodChannel, deviceSetIndex, demod, "demodulator"); - relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); - QJsonArray list; - - for (qint64 f : frequencies) - { - QJsonObject entry; - entry["frequency"] = (double) f; - entry["enabled"] = 1; - list.append(entry); - } - - QJsonObject scannerSettings; - scannerSettings["channel"] = QString("R%1:%2").arg(deviceSetIndex).arg(demod); - scannerSettings["channelBandwidth"] = channelBandwidth; - scannerSettings["channelFrequencyOffset"] = 25000; - scannerSettings["threshold"] = threshold; - scannerSettings["scanTime"] = 0.1; - scannerSettings["tuneTime"] = 250; - scannerSettings["retransmitTime"] = 2.5; - scannerSettings["priority"] = 0; - scannerSettings["measurement"] = 0; - scannerSettings["mode"] = autoThreshold ? 2 : 1; // scan only while measuring, else continuous - scannerSettings["frequencies"] = list; - patchChannelSettings(deviceSetIndex, scanner, scannerSettings); - QJsonObject run; - run["run"] = 1; - postChannelAction(deviceSetIndex, scanner, run); - - if (autoThreshold) - { - // The power scale depends on the device and its gain, so the only threshold that - // is right everywhere is one measured here: the median over the frequencies is - // the floor, as most of any band is empty. Wait for the first sweep to have - // measured every frequency rather than guess after a fixed time; a long list - // at a low sample rate takes a while - QList powers; - - for (int attempt = 0; (attempt < 30) && (powers.size() < frequencies.size()); attempt++) - { - pause(500); - relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); - powers.clear(); - - for (const QJsonValue& v : channelReport(deviceSetIndex, scanner)["FreqScannerReport"].toObject()["channelState"].toArray()) - { - QJsonObject s = v.toObject(); - - if (s.contains("power")) { - powers.append(s["power"].toDouble()); - } - } - } - - if (powers.isEmpty()) { - throw MCPToolError("The scanner measured nothing in 15 seconds, so no threshold could be set. " - "Check the device is running and producing samples, or give threshold explicitly."); - } - - std::sort(powers.begin(), powers.end()); - measuredFloor = powers[powers.size() / 2]; - haveFloor = true; - threshold = measuredFloor + 12.0; - - // Changing the mode restarts the scan with the new threshold - QJsonObject arm; - arm["threshold"] = threshold; - arm["mode"] = 1; - patchChannelSettings(deviceSetIndex, scanner, arm); - } - } - catch (const MCPToolError&) - { - discard(); - throw; - } - - // Watch: where it parks, and how strong each channel got - QMap heard; - QMap strongest; - - for (int i = 0; i < seconds; i++) - { - pause(1000); - relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); - relocateChannel(demodChannel, deviceSetIndex, demod, "demodulator"); - QJsonObject report = channelReport(deviceSetIndex, scanner)["FreqScannerReport"].toObject(); - int scanState = report["scanState"].toInt(); - - for (const QJsonValue& v : report["channelState"].toArray()) - { - QJsonObject s = v.toObject(); - qint64 f = (qint64) s["frequency"].toDouble(); - strongest[f] = qMax(strongest.value(f, -999.0), s["power"].toDouble()); - } - - if ((scanState == 3) || (scanState == 4)) - { - // One snapshot for both halves of the sum: read separately, a retune - // between them would pair a new centre with an old offset - QJsonObject set = getDeviceSet(deviceSetIndex); - qint64 centre = (qint64) set["samplingDevice"].toObject()["centerFrequency"].toDouble(); - - for (const QJsonValue& v : set["channels"].toArray()) - { - QJsonObject ch = v.toObject(); - - if (ch["index"].toInt() == demod) { - heard[centre + (qint64) ch["deltaFrequency"].toDouble()] += 1; - } - } - } - } - - QJsonObject result; - result["deviceSetIndex"] = deviceSetIndex; - result["demodChannelIndex"] = demod; - result["scannerChannelIndex"] = scanner; - result["device"] = receiver["device"]; - result["frequencies"] = frequencies.size(); - result["threshold"] = threshold; - result["secondsWatched"] = seconds; - - // A channel this wide takes in a station on the neighbouring raster steps as well, - // weaker and off frequency, so of the neighbours within a channel of each other - // only the strongest is a station; the rest are its skirts - auto isLocalPeak = [&](qint64 f) - { - const double power = strongest.value(f, -999.0); - - for (auto it = strongest.lowerBound(f - channelBandwidth); (it != strongest.end()) && (it.key() <= f + channelBandwidth); ++it) - { - if ((it.key() != f) && ((it.value() > power) || ((it.value() == power) && (it.key() < f)))) { - return false; - } - } - - return true; - }; - - QList> byTime; - for (auto it = heard.begin(); it != heard.end(); ++it) { if (isLocalPeak(it.key())) { byTime.append(qMakePair(it.value(), it.key())); } } - std::sort(byTime.begin(), byTime.end(), [](const QPair& a, const QPair& b) { return a.first > b.first; }); - QJsonArray heardArray; - - for (const auto& p : byTime) - { - QJsonObject h; - h["frequency"] = (double) p.second; - h["seconds"] = p.first; - heardArray.append(h); - } - - result["heard"] = heardArray; - - QList> byPower; - QList allPowers; // every frequency, for the floor estimate - for (auto it = strongest.begin(); it != strongest.end(); ++it) { allPowers.append(it.value()); if (isLocalPeak(it.key())) { byPower.append(qMakePair(it.value(), it.key())); } } - std::sort(byPower.begin(), byPower.end(), [](const QPair& a, const QPair& b) { return a.first > b.first; }); - std::sort(allPowers.begin(), allPowers.end()); - // Everything above the threshold, strongest first: for a band of continuous carriers - // this is the answer, as the scanner parks on the first one it finds and never gets - // to the rest. Capped well above any real band's station count, so that a threshold - // set too low on a long list cannot flood the reply - QJsonArray activeArray; - QJsonArray strongestArray; - static const int activeCap = 100; - - for (int i = 0; i < byPower.size(); i++) - { - QJsonObject s; - s["frequency"] = (double) byPower[i].second; - s["dB"] = byPower[i].first; - - if (i < 5) { - strongestArray.append(s); - } - - if ((byPower[i].first >= threshold) && (activeArray.size() < activeCap)) { - activeArray.append(s); - } - } - - result["active"] = activeArray; - result["activeCount"] = activeArray.size(); - result["strongest"] = strongestArray; - - if (haveFloor) { - result["noiseFloorDb"] = measuredFloor; - } else if (!allPowers.isEmpty()) { - result["noiseFloorDb"] = allPowers[allPowers.size() / 2]; - } - - if (autoThreshold) { - result["thresholdAuto"] = true; - } - - QStringList notes; - - if (!rasterNote.isEmpty()) { - notes.append(rasterNote); - } - - if (!gainNote.isEmpty()) { - notes.append(gainNote); - } - - if (!receiver["rateNote"].toString().isEmpty()) { - notes.append(receiver["rateNote"].toString()); - } - - if (activeArray.isEmpty()) { - notes.append("Nothing exceeded the threshold. Compare threshold with noiseFloorDb and the strongest channels; a second scan with threshold given lowers it."); - } else if (heardArray.isEmpty()) { - notes.append("The scanner did not park on any of the active frequencies while watching; active is still the list of what was found."); - } - - notes.append(intentNotes(deviceSetIndex, {demodChannel, scannerChannel}, reclaimed, receiver["reused"].toBool(), - receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble(), outcome)); - notes.append(featureNotes(reclaimedFeatures)); - - if (!notes.isEmpty()) { - result["note"] = notes.join(" "); - } - - newDeviceSet.keep(); - return result; - }); - - add("cleanup", - "Remove the channels that listen and scan added, on one device set or all of them, and the features listen added " - "for them (AIS, Radiosonde, APRS) once nothing feeds them. Each is otherwise left running, every demodulator playing " - "audio, until the next listen or scan on the same device set replaces it. Channels and features added any other way " - "are left alone; delete_channel and delete_feature remove those.", - schema({ - {"deviceSetIndex", intProp("Only this device set. Default: every device set")} - }), - [this](const QJsonObject& args) - { - QList deviceSetIndices; - - if (hasArg(args, "deviceSetIndex")) - { - deviceSetIndices.append(argInt(args, "deviceSetIndex")); - } - else - { - for (const QJsonValue& v : getInstanceSummary()["devicesetlist"].toObject()["deviceSets"].toArray()) { - deviceSetIndices.append(v.toObject()["samplingDevice"].toObject()["index"].toInt()); - } - } - - QJsonArray removed; - int count = 0; - - for (int deviceSetIndex : deviceSetIndices) - { - for (const QString& id : reclaimIntentChannels(deviceSetIndex)) - { - removed.append(QString("R%1:%2").arg(deviceSetIndex).arg(id)); - count++; - } - } - - QJsonArray features; - - for (const QString& id : reclaimIntentFeatures()) - { - features.append(id); - count++; - } - - QJsonObject result; - result["removed"] = count; - result["channels"] = removed; - result["features"] = features; - - if (count == 0) { - result["note"] = "Nothing to remove: no channel or feature added by listen or scan is still there."; - } - - return result; - }); - - add("tune_gain", - "Find the receiver gain that gives the best signal to noise ratio and apply it: steps the device through its gain range " - "and at each step measures the noise floor and the strongest signal on the main spectrum. Too little gain leaves weak " - "signals under the converter's own noise; too much overloads the front end, which raises the floor faster than the " - "signal and adds spurious products, so the best gain is where the difference between them peaks, and of gains within a " - "decibel of that the lowest is taken, for headroom. On a quiet band, where no signal stands clear of the floor, the " - "floor alone decides: the lowest gain at which the antenna's noise rather than the converter's sets it, short of " - "overload. Turns the device's AGC off, as it has to for a manual gain to mean " - "anything. The device must be running. Blocks for a few seconds per step; the reply carries the whole table so the " - "choice can be judged. Give frequency to judge by a particular signal rather than the strongest one. Once the gain " - "is applied the main spectrum is autoscaled to suit it, unless autoscale is false.", - schema({ - {"deviceSetIndex", deviceSetIndexProp}, - {"frequency", numProp("Judge by the signal at this frequency in Hz rather than the strongest in the baseband. It must be inside the baseband")}, - {"bandwidth", numProp("Width in Hz around frequency to look for the signal in. Default 200000")}, - {"steps", bounded(intProp("How many gain values to try, spread over the range. Default 8"), 3, 16)}, - {"apply", prop("boolean", "Apply the chosen gain. false measures and reports but puts the gain back as it was. Default true")}, - {"autoscale", prop("boolean", "Once the chosen gain is applied, set the main spectrum's reference level and range from what it then shows, as spectrum_action autoscale does, so the display suits the new gain. Default true")}, - {"gainKey", strProp("For a device type this does not know: the settings key of its gain, from describe_settings. Then give values too")}, - {"values", prop("array", "For a device type this does not know: the gain values to try, in the key's own units, lowest first")}, - {"agcKey", strProp("For a device type this does not know: the settings key that turns its AGC off when set to 0")} - }, {"deviceSetIndex"}), - [this](const QJsonObject& args) { return tuneGain(args); }); - - add("get_status", - "One line per device set and feature: device, frequency, run state and channels. The cheapest way to see what is going on.", - schema(QJsonObject()), - [this](const QJsonObject&) - { - QJsonObject summary = getInstanceSummary(); - QStringList lines; - - for (const QJsonValue& v : summary["devicesetlist"].toObject()["deviceSets"].toArray()) - { - QJsonObject ds = v.toObject(); - QJsonObject sd = ds["samplingDevice"].toObject(); - QStringList channels; - - for (const QJsonValue& c : ds["channels"].toArray()) - { - QJsonObject ch = c.toObject(); - channels.append(QString("%1 %2%3k").arg(ch["id"].toString()) - .arg(ch["deltaFrequency"].toDouble() >= 0 ? "+" : "").arg(ch["deltaFrequency"].toDouble() / 1000.0, 0, 'f', 1)); - } - - static const char *const prefixes[] = {"R", "T", "M"}; - lines.append(QString("%1%2 %3 %4 %5 MHz %6%7") - .arg(prefixes[qBound(0, sd["direction"].toInt(), 2)]).arg(sd["index"].toInt()) - .arg(sd["hwType"].toString()).arg(sd["serial"].toString()) - .arg(sd["centerFrequency"].toDouble() / 1e6, 0, 'f', 3).arg(sd["state"].toString()) - .arg(channels.isEmpty() ? QString() : ": " + channels.join(", "))); - } - - for (const QJsonValue& v : summary["featureset"].toObject()["features"].toArray()) - { - QJsonObject f = v.toObject(); - int index = f["index"].toInt(); - lines.append(QString("F%1 %2 %3").arg(index).arg(f["id"].toString()).arg(featureState(index, -1)["state"].toString())); - } - - return QJsonValue(lines.isEmpty() ? QString("Nothing configured") : lines.join("\n")); - }); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "SWGErrorResponse.h" +#include "SWGSuccessResponse.h" +#include "SWGInstanceSummaryResponse.h" +#include "SWGInstanceDevicesResponse.h" +#include "SWGInstanceChannelsResponse.h" +#include "SWGInstanceFeaturesResponse.h" +#include "SWGDeviceSetList.h" +#include "SWGDeviceSet.h" +#include "SWGDeviceListItem.h" +#include "SWGDeviceSettings.h" +#include "SWGDeviceState.h" +#include "SWGDeviceReport.h" +#include "SWGDeviceActions.h" +#include "SWGChannelSettings.h" +#include "SWGChannelReport.h" +#include "SWGChannelActions.h" +#include "SWGChannelsDetail.h" +#include "SWGFeatureSet.h" +#include "SWGFeatureSettings.h" +#include "SWGFeatureReport.h" +#include "SWGFeatureActions.h" +#include "SWGPresets.h" +#include "SWGPresetGroup.h" +#include "SWGPresetItem.h" +#include "SWGPresetTransfer.h" +#include "SWGPresetIdentifier.h" +#include "SWGConfigurations.h" +#include "SWGConfigurationIdentifier.h" +#include "SWGWorkspaceInfo.h" +#include "SWGWorkspaceActions.h" +#include "SWGWindowList.h" +#include "SWGGLSpectrum.h" +#include "SWGGLSpectrumReport.h" +#include "SWGSpectrumActions.h" +#include "SWGGLSpectrumData.h" +#include "SWGGLSpectrumHistory.h" +#include "SWGSpectrumHistorySignal.h" +#include "SWGAudioDevices.h" +#include "SWGLocationInformation.h" + +#include "maincore.h" +#include "device/deviceset.h" +#include "channel/channelapi.h" +#include "device/deviceapi.h" +#include "feature/feature.h" +#include "feature/featureset.h" +#include "webapi/webapiadapterinterface.h" +#include "webapi/webapiutils.h" + +#include "mcpstreams.h" +#include "mcptools.h" + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +namespace { + +QJsonObject toJson(SWGSDRangel::SWGObject& object) +{ + QJsonObject *obj = object.asJsonObject(); + QJsonObject result = *obj; + delete obj; + return result; +} + +QString compact(const QJsonValue& value) +{ + if (value.isObject()) { + return QString(QJsonDocument(value.toObject()).toJson(QJsonDocument::Compact)); + } else if (value.isArray()) { + return QString(QJsonDocument(value.toArray()).toJson(QJsonDocument::Compact)); + } else if (value.isString()) { + return value.toString(); + } else { + return QString(QJsonDocument(QJsonArray({value})).toJson(QJsonDocument::Compact)); + } +} + +// Throws if the Web API call failed +void check(int httpRC, SWGSDRangel::SWGErrorResponse& error, const QString& what) +{ + if (httpRC / 100 != 2) + { + QString message = error.getMessage() ? *error.getMessage() : QString(); + throw MCPToolError(QString("%1 failed (HTTP %2)%3").arg(what).arg(httpRC).arg(message.isEmpty() ? "" : ": " + message)); + } +} + +// Argument access. Accepts numbers given as strings, as models sometimes do. +bool hasArg(const QJsonObject& args, const QString& key) +{ + return args.contains(key) && !args[key].isNull() && !args[key].isUndefined(); +} + +// Models write booleans as JSON booleans mostly, but also as "true"/"false" strings and as 0/1, +// and QJsonValue::toBool answers its default for anything but a JSON boolean, which turned +// replace "false" into true. Absent, null and anything unreadable give the default +bool argBool(const QJsonObject& args, const QString& key, bool defaultValue) +{ + if (!hasArg(args, key)) { + return defaultValue; + } + + const QJsonValue value = args.value(key); + + if (value.isBool()) { + return value.toBool(); + } + + if (value.isDouble()) { + return value.toDouble() != 0.0; + } + + if (value.isString()) + { + const QString text = value.toString().trimmed().toLower(); + + if ((text == "true") || (text == "1") || (text == "yes") || (text == "on")) { + return true; + } + + if ((text == "false") || (text == "0") || (text == "no") || (text == "off") || text.isEmpty()) { + return false; + } + } + + return defaultValue; +} + +int argInt(const QJsonObject& args, const QString& key, bool required = true, int defaultValue = 0) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isDouble()) { + return (int) value.toDouble(); + } + + bool ok; + int result = value.toString().trimmed().toInt(&ok); + + if (!ok) + { + double d = value.toString().trimmed().toDouble(&ok); + + if (ok) { + return (int) d; + } + + throw MCPToolError(QString("Argument %1 must be an integer").arg(key)); + } + + return result; +} + +qint64 argInt64(const QJsonObject& args, const QString& key, bool required = true, qint64 defaultValue = 0) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isDouble()) { + return (qint64) value.toDouble(); + } + + bool ok; + double d = value.toString().trimmed().toDouble(&ok); + + if (!ok) { + throw MCPToolError(QString("Argument %1 must be a number").arg(key)); + } + + return (qint64) d; +} + +double argDouble(const QJsonObject& args, const QString& key, bool required = true, double defaultValue = 0.0) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isDouble()) { + return value.toDouble(); + } + + bool ok; + double d = value.toString().trimmed().toDouble(&ok); + + if (!ok) { + throw MCPToolError(QString("Argument %1 must be a number").arg(key)); + } + + return d; +} + +QString argString(const QJsonObject& args, const QString& key, bool required = true, const QString& defaultValue = QString()) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isString()) { + return value.toString(); + } else if (value.isDouble()) { + return QString::number(value.toDouble(), 'g', 15); + } else { + return compact(value); + } +} + +QJsonObject argObject(const QJsonObject& args, const QString& key, bool required = true) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return QJsonObject(); + } + + QJsonValue value = args[key]; + + if (value.isObject()) { + return value.toObject(); + } + + // Tolerate an object passed as a JSON string + if (value.isString()) + { + QJsonDocument doc = QJsonDocument::fromJson(value.toString().toUtf8()); + + if (doc.isObject()) { + return doc.object(); + } + } + + throw MCPToolError(QString("Argument %1 must be a JSON object").arg(key)); +} + +// direction: "rx" / "tx" / "mimo" or 0 / 1 / 2 +int argDirection(const QJsonObject& args, const QString& key = "direction", bool required = false, int defaultValue = 0) +{ + if (!hasArg(args, key)) + { + if (required) { + throw MCPToolError(QString("Missing required argument: %1").arg(key)); + } + + return defaultValue; + } + + QJsonValue value = args[key]; + + if (value.isDouble()) { + return (int) value.toDouble(); + } + + QString s = value.toString().trimmed().toLower(); + + if ((s == "rx") || (s == "0") || (s == "receive") || (s == "source")) { + return 0; + } else if ((s == "tx") || (s == "1") || (s == "transmit") || (s == "sink")) { + return 1; + } else if ((s == "mimo") || (s == "2")) { + return 2; + } + + throw MCPToolError(QString("Argument %1 must be \"rx\", \"tx\" or \"mimo\"").arg(key)); +} + +QString directionName(int direction) +{ + switch (direction) + { + case 0: return "rx"; + case 1: return "tx"; + case 2: return "mimo"; + default: return QString::number(direction); + } +} + +// JSON schema builders +QJsonObject prop(const QString& type, const QString& description) +{ + QJsonObject p; + p["type"] = type; + p["description"] = description; + return p; +} + +QJsonObject intProp(const QString& description) { return prop("integer", description); } +QJsonObject numProp(const QString& description) { return prop("number", description); } +QJsonObject strProp(const QString& description) { return prop("string", description); } +QJsonObject objProp(const QString& description) { return prop("object", description); } + +QJsonObject enumProp(const QString& description, const QStringList& values) +{ + QJsonObject p = strProp(description); + p["enum"] = QJsonArray::fromStringList(values); + return p; +} + +QJsonObject directionProp(const QString& description) +{ + return enumProp(description, {"rx", "tx", "mimo"}); +} + +// Adds the bounds a handler enforces at runtime to the schema, so a client can see them +QJsonObject bounded(QJsonObject property, double minimum, double maximum) +{ + property["minimum"] = minimum; + property["maximum"] = maximum; + return property; +} + +QJsonObject schema(const QJsonObject& properties, const QStringList& required = QStringList()) +{ + QJsonObject s; + s["type"] = "object"; + s["properties"] = properties; + s["required"] = QJsonArray::fromStringList(required); + s["additionalProperties"] = false; + return s; +} + +const QJsonObject deviceSetIndexProp = intProp("Index of the device set (0 for R0, the first device set)"); +const QJsonObject channelIndexProp = intProp("Index of the channel within the device set"); +const QJsonObject featureIndexProp = intProp("Index of the feature within the feature set"); + +// Settings keys in the form used by the Web API PATCH: nested keys are dotted, array elements indexed +void extractKeys(const QJsonObject& json, QStringList& keys, const QString& prefix = QString()) +{ + for (const QString& key : json.keys()) + { + QString full = prefix.isEmpty() ? key : prefix + "." + key; + keys.append(full); + + if (json[key].isObject()) + { + extractKeys(json[key].toObject(), keys, full); + } + else if (json[key].isArray()) + { + QJsonArray array = json[key].toArray(); + + for (int i = 0; i < array.count(); i++) + { + QString element = QString("%1[%2]").arg(full).arg(i); + keys.append(element); + + if (array.at(i).isObject()) { + extractKeys(array.at(i).toObject(), keys, element); + } + } + } + } +} + +// Applies patch on top of target. Objects are merged recursively, everything else replaced. +// Keys absent from target are reported (they may still be valid: empty strings are not serialized). +void mergeInto(QJsonObject& target, const QJsonObject& patch, QStringList& unknownKeys, const QString& prefix = QString()) +{ + for (const QString& key : patch.keys()) + { + QString full = prefix.isEmpty() ? key : prefix + "." + key; + + if (!target.contains(key)) { + unknownKeys.append(full); + } + + if (patch[key].isObject() && target[key].isObject()) + { + QJsonObject sub = target[key].toObject(); + mergeInto(sub, patch[key].toObject(), unknownKeys, full); + target[key] = sub; + } + else + { + target[key] = patch[key]; + } + } +} + +int leadingSpaces(const QString& line) +{ + int count = 0; + + while ((count < line.length()) && (line.at(count) == ' ')) { + count++; + } + + return count; +} + +// Reads the property names and types out of one swagger definition. Only the properties of the +// definition itself are taken: the attributes of a property sit two spaces further in, so an +// items: block of an array cannot be mistaken for the array's own type. +SettingsSchema parseSettingsSchema(const QString& yaml) +{ + SettingsSchema schema; + int propertiesIndent = -1; + int nameIndent = -1; + QString property; + + for (const QString& line : yaml.split('\n')) + { + QString text = line.trimmed(); + + if (text.isEmpty() || text.startsWith('#')) { + continue; + } + + int indent = leadingSpaces(line); + + if (propertiesIndent < 0) + { + if (text == "properties:") { + propertiesIndent = indent; + } + + continue; + } + + if (indent <= propertiesIndent) { + break; // out of the properties block and into the next section of the definition + } + + if (nameIndent < 0) { + nameIndent = indent; + } + + if (indent == nameIndent) + { + if (text.endsWith(':')) + { + property = text.left(text.length() - 1); + schema.m_types.insert(property, QString()); + } + else + { + property.clear(); + } + } + else if ((indent == nameIndent + 2) && !property.isEmpty()) + { + if (text.startsWith("type:")) { + schema.m_types[property] = text.mid(5).trimmed(); + } else if (text.startsWith("$ref:") && schema.m_types.value(property).isEmpty()) { + schema.m_types[property] = "object"; + } + } + } + + schema.m_known = !schema.m_types.isEmpty(); + return schema; +} + +// Checks a patch against the schema and returns it with the one conversion worth making. Values +// are checked here rather than left to the SWG object, whose setValue() turns a string into zero +// without complaint: "rfBandwidth": "wide" would otherwise stop the channel demodulating and be +// reported as a successful change. +QJsonObject checkAgainstSchema(const QJsonObject& patch, const SettingsSchema& schema, + QStringList& unknownKeys, QStringList& typeErrors) +{ + QJsonObject checked; + + for (const QString& key : patch.keys()) + { + QJsonValue value = patch[key]; + + if (!schema.m_types.contains(key)) + { + unknownKeys.append(key); + checked[key] = value; + continue; + } + + QString type = schema.m_types[key]; + bool numeric = (type == "integer") || (type == "number"); + + if (numeric && value.isBool()) + { + // Unambiguous and lossless, and the natural way to write a 0/1 flag + checked[key] = value.toBool() ? 1 : 0; + continue; + } + + bool ok = true; + + if (numeric) { + ok = value.isDouble(); + } else if (type == "string") { + ok = value.isString(); + } else if (type == "array") { + ok = value.isArray(); + } else if (type == "object") { + ok = value.isObject(); + } + + if (!ok) + { + QString got = value.isString() ? "string" : + value.isDouble() ? "number" : + value.isBool() ? "boolean" : + value.isArray() ? "array" : + value.isObject() ? "object" : "null"; + typeErrors.append(QString("%1 expects %2 but was given a %3 (%4)") + .arg(key).arg(type).arg(got).arg(compact(QJsonObject{{key, value}}))); + } + + checked[key] = value; + } + + return checked; +} + +// The key holding the type specific settings, e.g. "rtlSdrSettings" or "ADSBDemodSettings" +QString findSettingsKey(const QJsonObject& json) +{ + for (const QString& key : json.keys()) + { + if (key.endsWith("Settings") && json[key].isObject()) { + return key; + } + } + + return QString(); +} + +// Generic settings patch: read current settings, merge the partial object given by the model +// into the type specific sub-object, then PATCH with the list of changed keys. +template +QJsonObject applySettingsPatch( + const std::function& get, + const std::function& put, + const QJsonObject& partial, + const QString& what, + const std::function& schemaFor) +{ + SWGSDRangel::SWGErrorResponse error; + error.init(); + SWG current; + check(get(current, error), error, "Get " + what); + QJsonObject json = toJson(current); + QString settingsKey = findSettingsKey(json); + + if (settingsKey.isEmpty()) { + throw MCPToolError(QString("Cannot find settings object in current %1: %2").arg(what).arg(compact(json))); + } + + QJsonObject subPartial; + + if (partial.contains(settingsKey)) + { + subPartial = partial[settingsKey].toObject(); + } + else + { + for (const QString& key : partial.keys()) + { + if (key.endsWith("Settings") && partial[key].isObject()) { + throw MCPToolError(QString("Settings object key %1 does not match the current type. Expected %2 or the bare settings object").arg(key).arg(settingsKey)); + } + } + + subPartial = partial; + } + + if (subPartial.isEmpty()) { + throw MCPToolError("No settings given"); + } + + QStringList unknownKeys; + SettingsSchema schema = schemaFor(settingsKey); + + if (schema.m_known) + { + QStringList typeErrors; + subPartial = checkAgainstSchema(subPartial, schema, unknownKeys, typeErrors); + + if (!typeErrors.isEmpty()) + { + throw MCPToolError(QString("Wrong value type for %1: %2. Numbers must be given as JSON " + "numbers, not strings. Nothing was changed.").arg(settingsKey).arg(typeErrors.join("; "))); + } + } + + QJsonObject sub = json[settingsKey].toObject(); + QStringList merged; + mergeInto(sub, subPartial, merged); + json[settingsKey] = sub; + + if (!schema.m_known) + { + // Without a schema the only test left is whether the key is in the current settings, which + // misses any string setting that is currently empty. Better than nothing, but not by much + unknownKeys = merged; + } + + QStringList keys; + extractKeys(subPartial, keys); + + SWG request; + request.fromJsonObject(json); + error.init(); + check(put(keys, request, error), error, "Set " + what); + + // Reply with only what was asked for, read back from the object that was sent. Echoing + // the whole settings block cost a client about 500 tokens per call, carried for the rest + // of the conversation, to confirm a one key change. + QJsonObject after = toJson(request)[settingsKey].toObject(); + QJsonObject changed; + + for (const QString& key : subPartial.keys()) + { + if (after.contains(key)) { + changed[key] = after[key]; + } + } + + QJsonObject result; + result["changed"] = changed; + + if (!unknownKeys.isEmpty()) { + result["warning"] = QString("Ignored unknown keys: %1. describe_settings lists the valid ones.").arg(unknownKeys.join(", ")); + } + + return result; +} + +QString capitalize(const QString& s) +{ + return s.isEmpty() ? s : s.at(0).toUpper() + s.mid(1); +} + +// The plugin lists carry a URI, a version and an index per entry that no caller needs. Each +// becomes one string: the id the other tools take, with the display name in brackets when it +// says something the id does not. +// Features with no run state: they work from the moment they are configured. Some answer the run +// request with 501 and the rest accept it and stay idle, so neither the request nor the state that +// follows it tells them apart from a feature that is slow to start +const QStringList passiveFeatureTypes = { + "AIS", "AMBE", "AntennaTools", "APRS", "FreqDisplay", "LimeRFE", "Map", "Radiosonde", + "RemoteControl", "SkyMap" +}; + +bool isPassiveFeature(const QString& featureType) +{ + return passiveFeatureTypes.contains(featureType); +} + +QJsonArray idsAndNames(const QJsonArray& plugins) +{ + QJsonArray out; + + for (const QJsonValue& v : plugins) + { + QJsonObject p = v.toObject(); + QString id = p["id"].toString(); + QString name = p["name"].toString(); + + if (!name.isEmpty() && (name.compare(id, Qt::CaseInsensitive) != 0)) { + out.append(QString("%1 (%2)").arg(id).arg(name)); + } else { + out.append(id); + } + } + + return out; +} + +} // namespace + +// --------------------------------------------------------------------------- +// Event counter +// --------------------------------------------------------------------------- + +MCPEventCounter::MCPEventCounter() : + m_deviceSetAdded(0), + m_deviceSetRemoved(0), + m_deviceChanged(0), + m_channelAdded(0), + m_channelRemoved(0), + m_featureAdded(0), + m_featureRemoved(0) +{ + MainCore *mainCore = MainCore::instance(); + connect(mainCore, &MainCore::deviceSetAdded, this, &MCPEventCounter::onDeviceSetAdded); + connect(mainCore, &MainCore::deviceSetRemoved, this, &MCPEventCounter::onDeviceSetRemoved); + connect(mainCore, &MainCore::deviceChanged, this, &MCPEventCounter::onDeviceChanged); + connect(mainCore, &MainCore::channelAdded, this, &MCPEventCounter::onChannelAdded); + connect(mainCore, &MainCore::channelRemoved, this, &MCPEventCounter::onChannelRemoved); + connect(mainCore, &MainCore::featureAdded, this, &MCPEventCounter::onFeatureAdded); + connect(mainCore, &MainCore::featureRemoved, this, &MCPEventCounter::onFeatureRemoved); +} + +void MCPEventCounter::onDeviceSetAdded(int index, DeviceAPI *device) +{ + (void) index; + (void) device; + m_deviceSetAdded.fetchAndAddRelease(1); +} + +void MCPEventCounter::onDeviceSetRemoved(int index) +{ + (void) index; + m_deviceSetRemoved.fetchAndAddRelease(1); +} + +void MCPEventCounter::onDeviceChanged(int index) +{ + (void) index; + m_deviceChanged.fetchAndAddRelease(1); +} + +void MCPEventCounter::onChannelAdded(int deviceSetIndex, ChannelAPI *channel) +{ + (void) deviceSetIndex; + (void) channel; + m_channelAdded.fetchAndAddRelease(1); +} + +void MCPEventCounter::onChannelRemoved(int deviceSetIndex, ChannelAPI *channel) +{ + (void) deviceSetIndex; + (void) channel; + m_channelRemoved.fetchAndAddRelease(1); +} + +void MCPEventCounter::onFeatureAdded(int featureSetIndex, Feature *feature) +{ + (void) featureSetIndex; + (void) feature; + m_featureAdded.fetchAndAddRelease(1); +} + +void MCPEventCounter::onFeatureRemoved(int featureSetIndex, Feature *feature) +{ + (void) featureSetIndex; + (void) feature; + m_featureRemoved.fetchAndAddRelease(1); +} + +// --------------------------------------------------------------------------- +// Registry +// --------------------------------------------------------------------------- + +MCPTools::MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface) : + m_adapter(webAPIAdapterInterface), + m_capture(webAPIAdapterInterface), + m_streams(nullptr), + m_ownerFeature(nullptr), + m_stopping(0), + m_yamlLoaded(false) +{ + registerInstanceTools(); + registerDeviceSetTools(); + registerChannelTools(); + registerFeatureTools(); + registerPresetTools(); + registerWorkspaceTools(); + registerCaptureTools(); + registerIntentTools(); +} + +void MCPTools::setStopping(bool stopping) +{ + m_stopping.storeRelease(stopping ? 1 : 0); + m_capture.setStopping(stopping); +} + +// The tools run on HTTP threads and wait for work that completes on the main thread. When the +// server stops, the main thread waits for the HTTP threads instead, so a wait that carried on +// would hold it for its whole timeout, or for ever where the main thread itself is what is +// waited for. Every wait therefore gives up at once when a stop is under way +bool MCPTools::waitFor(const std::function& condition, int timeoutMs) const +{ + QElapsedTimer timer; + timer.start(); + + while (!condition()) + { + if (m_stopping.loadAcquire()) { + throw MCPToolError("The MCP server is stopping, so this call was abandoned"); + } + + if (timer.elapsed() > timeoutMs) { + return false; + } + + QThread::msleep(20); + } + + return true; +} + +void MCPTools::pause(int ms) const +{ + QElapsedTimer timer; + timer.start(); + + for (;;) + { + if (m_stopping.loadAcquire()) { + throw MCPToolError("The MCP server is stopping, so this call was abandoned"); + } + + // Read once: read again for the sleep, the limit could pass in between and a negative + // remainder become an unsigned sleep of weeks + const qint64 remaining = ms - timer.elapsed(); + + if (remaining <= 0) { + return; + } + + QThread::msleep((unsigned long) std::min(50, remaining)); + } +} + +// Per tool behaviour. The MCP hints are narrower than they look: destructiveHint false means +// the tool is additive only, so anything that overwrites existing state is destructive, and +// openWorldHint true means the tool can reach beyond this application, which covers commanding +// the radio, features that talk to network services, and data arriving from unknown transmitters. +struct ToolBehaviour +{ + bool m_readOnly; + bool m_destructive; + bool m_idempotent; + bool m_openWorld; +}; + +static ToolBehaviour behaviourFor(const QString& name) +{ + // Reads of this instance's own configuration and of documentation compiled into the plugin + static const QStringList localReads = { + "get_instance_summary", "list_available_devices", "list_channel_types", "list_feature_types", + "describe_settings", "get_receiving_guide", "list_docs", "get_docs", "list_audio_devices", + "get_location", "get_deviceset", "get_device_settings", + "get_spectrum_settings", "get_spectrum_report", "get_spectrum_data", "get_channel_settings", "get_feature_settings", + "list_presets", "list_configurations", "get_server_status", "get_status" + }; + + // Reads that return data received off the air, from transmitters this instance does not + // control, or from the network services some features talk to. Reports carry it as well as + // the dedicated data feeds do: an ADS-B report, for instance, lists the aircraft heard. + static const QStringList offAirReads = { + "get_packets", "get_map_items", "get_channel_report", + "get_device_report", "get_feature_report" + }; + + // Purely additive: they create something new and overwrite nothing + static const QStringList additive = { + "add_deviceset", "add_channel", "add_feature", "add_workspace", "add_annotation" + }; + + if (localReads.contains(name)) { + return {true, false, true, false}; + } + + if (offAirReads.contains(name)) { + return {true, false, true, true}; + } + + if (additive.contains(name)) { + return {false, false, false, true}; + } + + // Everything else changes or removes state. Only the workspace moves and the settings writes + // land in the same place when repeated; captures, actions and creation do not. + bool idempotent = name.startsWith("set_") || name.startsWith("stop_") || (name == "clear_packets"); + return {false, true, idempotent, true}; +} + +void MCPTools::add(const QString& name, const QString& description, const QJsonObject& inputSchema, + std::function handler) +{ + Tool tool; + tool.name = name; + tool.description = description; + tool.inputSchema = inputSchema; + tool.handler = handler; + m_tools.append(tool); +} + +QJsonArray MCPTools::listTools() const +{ + QJsonArray tools; + + for (const Tool& tool : m_tools) + { + QJsonObject t; + t["name"] = tool.name; + t["description"] = tool.description; + t["inputSchema"] = tool.inputSchema; + ToolBehaviour behaviour = behaviourFor(tool.name); + // Clients carry the whole tool list on every turn, so only say what differs from the + // defaults the MCP schema gives an absent hint (read-write, destructive, not + // idempotent, open world), and no title, which would repeat the description + QJsonObject annotations; + if (behaviour.m_readOnly) { annotations["readOnlyHint"] = true; } + if (!behaviour.m_destructive) { annotations["destructiveHint"] = false; } + if (behaviour.m_idempotent) { annotations["idempotentHint"] = true; } + if (!behaviour.m_openWorld) { annotations["openWorldHint"] = false; } + if (!annotations.isEmpty()) { t["annotations"] = annotations; } + tools.append(t); + } + + return tools; +} + +QJsonObject MCPTools::callTool(const QString& name, const QJsonObject& arguments) +{ + const Tool *tool = nullptr; + + for (const Tool& t : m_tools) + { + if (t.name == name) + { + tool = &t; + break; + } + } + + if (!tool) { + throw MCPError(-32602, QString("Unknown tool: %1").arg(name)); + } + + QJsonObject result; + QJsonArray content; + + try + { + // Every input schema says additionalProperties: false, so an argument a tool does not + // define is a mistake worth reporting. Dropping it silently turns a wrong call into a + // plausible wrong answer: get_packets, which filters on source and type, looks as though + // it is ignoring a deviceSetIndex and channelIndex filter it never had + QJsonObject properties = tool->inputSchema.value("properties").toObject(); + QStringList unknown; + + for (const QString& key : arguments.keys()) + { + if (!properties.contains(key)) { + unknown.append(key); + } + } + + if (!unknown.isEmpty()) + { + QStringList accepted = properties.keys(); + throw MCPToolError(QString("%1 does not take %2. It accepts: %3") + .arg(name) + .arg(unknown.join(", ")) + .arg(accepted.isEmpty() ? QString("no arguments") : accepted.join(", "))); + } + + QJsonValue value = tool->handler(arguments); + + // A handler that has a picture to show puts it under _image, which becomes an image + // content item beside the text rather than a base64 blob in it + QJsonObject image; + + if (value.isObject() && value.toObject().contains("_image")) + { + QJsonObject object = value.toObject(); + image = object.take("_image").toObject(); + value = object; + } + + QJsonObject text; + text["type"] = "text"; + text["text"] = compact(value); + content.append(text); + + if (!image.isEmpty()) + { + QJsonObject item; + item["type"] = "image"; + item["data"] = image["data"]; + item["mimeType"] = image["mimeType"]; + content.append(item); + } + + if (value.isObject()) { + result["structuredContent"] = value; + } + + result["isError"] = false; + } + catch (const MCPToolError& e) + { + qDebug() << "MCPTools::callTool:" << name << "error:" << e.message; + QJsonObject text; + text["type"] = "text"; + text["text"] = "Error: " + e.message; + content.append(text); + result["isError"] = true; + } + + result["content"] = content; + return result; +} + +// --------------------------------------------------------------------------- +// Instance level data +// --------------------------------------------------------------------------- + +QJsonObject MCPTools::getInstanceSummary() +{ + SWGSDRangel::SWGInstanceSummaryResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceSummary(response, error), error, "Get instance summary"); + return toJson(response); +} + +QJsonObject MCPTools::getAvailableDevices(int direction) +{ + QJsonObject result; + + for (int dir = 0; dir < 3; dir++) + { + if ((direction >= 0) && (direction != dir)) { + continue; + } + + SWGSDRangel::SWGInstanceDevicesResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDevices(dir, response, error), error, "List devices"); + result[directionName(dir)] = toJson(response)["devices"].toArray(); + } + + return result; +} + +QJsonObject MCPTools::getAvailableChannels(int direction) +{ + QJsonObject result; + + for (int dir = 0; dir < 3; dir++) + { + if ((direction >= 0) && (direction != dir)) { + continue; + } + + SWGSDRangel::SWGInstanceChannelsResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceChannels(dir, response, error), error, "List channel types"); + result[directionName(dir)] = idsAndNames(toJson(response)["channels"].toArray()); + } + + return result; +} + +QJsonObject MCPTools::getAvailableFeatures() +{ + SWGSDRangel::SWGInstanceFeaturesResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceFeatures(response, error), error, "List feature types"); + QJsonObject result; + QJsonArray features; + + for (const QJsonValue& v : toJson(response)["features"].toArray()) + { + QString entry = v.toObject()["id"].toString(); + features.append(isPassiveFeature(entry) + ? QString("%1 [passive: no run state, do not start it]").arg(idsAndNames(QJsonArray{v}).first().toString()) + : idsAndNames(QJsonArray{v}).first().toString()); + } + + result["features"] = features; + return result; +} + +QJsonObject MCPTools::getPresets() +{ + SWGSDRangel::SWGPresets response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instancePresetsGet(response, error), error, "List presets"); + return toJson(response); +} + +QJsonObject MCPTools::getConfigurations() +{ + SWGSDRangel::SWGConfigurations response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceConfigurationsGet(response, error), error, "List configurations"); + return toJson(response); +} + +QJsonObject MCPTools::getDeviceSet(int deviceSetIndex) +{ + SWGSDRangel::SWGDeviceSet response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetGet(deviceSetIndex, response, error), error, QString("Get device set %1").arg(deviceSetIndex)); + return toJson(response); +} + +void MCPTools::loadYamlDefinitions() +{ + if (m_yamlLoaded) { + return; + } + + m_yamlLoaded = true; + QDir dir(":/webapi/doc/swagger/include"); + QRegularExpression definitionStart("^([A-Za-z0-9_]+):\\s*$"); + + for (const QString& fileName : dir.entryList(QStringList("*.yaml"), QDir::Files)) + { + QFile file(dir.filePath(fileName)); + + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + continue; + } + + QString name; + QStringList block; + + for (const QString& line : QString::fromUtf8(file.readAll()).split('\n')) + { + QRegularExpressionMatch match = definitionStart.match(line); + + if (match.hasMatch()) + { + if (!name.isEmpty()) { + m_yamlDefinitions[name] = block.join('\n').trimmed(); + } + + name = match.captured(1); + block.clear(); + } + + block.append(line); + } + + if (!name.isEmpty()) { + m_yamlDefinitions[name] = block.join('\n').trimmed(); + } + } + + for (auto name = m_yamlDefinitions.keyBegin(); name != m_yamlDefinitions.keyEnd(); ++name) { + m_yamlDefinitionsByLower.insert(name->toLower(), *name); + } + + qDebug("MCPTools::loadYamlDefinitions: %d definitions", (int) m_yamlDefinitions.size()); +} + +// The JSON settings key does not always capitalise the way its swagger definition does: +// testSourceSettings comes from TestSourceSettings, and sdrPlayV3Settings from SDRPlayV3Settings. +// Only the case ever differs, so a name that does not match exactly is looked up without it. +// Returns an empty string when there is no such definition +QString MCPTools::resolveDefinition(const QString& name) +{ + loadYamlDefinitions(); + + if (m_yamlDefinitions.contains(name)) { + return name; + } + + return m_yamlDefinitionsByLower.value(name.toLower()); +} + +QString MCPTools::describeType(const QString& typeIn, const QString& kindIn) +{ + QMutexLocker schemaLock(&m_schemaMutex); + loadYamlDefinitions(); + QString type = typeIn.trimmed(); + QString kind = kindIn.trimmed().toLower(); + // (settings JSON key, description of what matched) + QList> matches; + + // The spectrum display is not a type: its definitions are named after it directly + const QString lower = type.toLower(); + + if ((kind == "spectrum") || (lower == "spectrum") || (lower == "glspectrum")) + { + QStringList out; + out.append("# main spectrum display of a device set\n# get_spectrum_settings / set_spectrum_settings, get_spectrum_report, spectrum_action\n" + "# get_docs spectrum explains the display and its controls\n"); + + for (const QString& definition : {"GLSpectrum", "GLSpectrumReport", "SpectrumActions"}) + { + if (m_yamlDefinitions.contains(definition)) + { + out.append(m_yamlDefinitions[definition]); + out.append(""); + } + } + + return out.join('\n'); + } + + if (kind.isEmpty() || (kind == "channel")) + { + if (WebAPIUtils::m_channelTypeToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_channelTypeToSettingsKey[type], "channel type " + type}); + } + } + + if (kind.isEmpty() || (kind == "device")) + { + if (WebAPIUtils::m_sourceDeviceHwIdToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_sourceDeviceHwIdToSettingsKey[type], "rx device " + type}); + } + if (WebAPIUtils::m_sinkDeviceHwIdToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_sinkDeviceHwIdToSettingsKey[type], "tx device " + type}); + } + if (WebAPIUtils::m_mimoDeviceHwIdToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_mimoDeviceHwIdToSettingsKey[type], "mimo device " + type}); + } + } + + if (kind.isEmpty() || (kind == "feature")) + { + if (WebAPIUtils::m_featureTypeToSettingsKey.contains(type)) { + matches.append({WebAPIUtils::m_featureTypeToSettingsKey[type], "feature type " + type}); + } + } + + // Also accept a definition name given directly, e.g. "RtlSdrSettings" or "RtlSdr" + if (matches.isEmpty()) + { + if (!resolveDefinition(type + "Settings").isEmpty()) { + matches.append({type + "Settings", type}); + } else if (!resolveDefinition(type).isEmpty()) { + matches.append({type, type}); + } + } + + if (matches.isEmpty()) + { + throw MCPToolError(QString("Unknown type %1. Use the id values returned by list_channel_types, list_feature_types " + "or the hwType values returned by list_available_devices").arg(type)); + } + + QStringList out; + + for (const auto& match : matches) + { + QString settingsKey = match.first; + QString base = capitalize(settingsKey); + + if (base.endsWith("Settings")) { + base.chop(QString("Settings").size()); + } + + out.append(QString("# %1\n# Settings JSON key: %2\n").arg(match.second).arg(settingsKey)); + bool found = false; + + // A definition given by its own name that is not a Settings one, such as a Report or a + // marker, is what was asked for and is not reached by the suffixes below + if (!settingsKey.endsWith("Settings") && m_yamlDefinitions.contains(resolveDefinition(settingsKey))) + { + out.append(m_yamlDefinitions[resolveDefinition(settingsKey)]); + out.append(""); + found = true; + } + + for (const QString suffix : {"Settings", "Report", "Actions"}) + { + QString definition = resolveDefinition(base + suffix); + + if (!definition.isEmpty()) + { + out.append(m_yamlDefinitions[definition]); + out.append(""); + found = true; + } + } + + if (!found) { + out.append(QString("No documentation found for %1").arg(base)); + } + } + + return out.join('\n'); +} + +// --------------------------------------------------------------------------- +// Device set helpers +// --------------------------------------------------------------------------- + +int MCPTools::deviceSetCount() const +{ + return (int) MainCore::instance()->getDeviceSets().size(); +} + +int MCPTools::channelCount(int deviceSetIndex) const +{ + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { + return -1; + } + + return deviceSets[deviceSetIndex]->getNumberOfChannels(); +} + +int MCPTools::featureCount() const +{ + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty()) { + return -1; + } + + return featureSets[0]->getNumberOfFeatures(); +} + +int MCPTools::deviceSetDirection(int deviceSetIndex) +{ + QJsonObject deviceSet = getDeviceSet(deviceSetIndex); + return deviceSet["samplingDevice"].toObject()["direction"].toInt(0); +} + +// Selects the sampling device of a device set from hwType / serial / sequence / displayedName / deviceIndex +// and waits for SDRangel to switch to it. +QJsonObject MCPTools::selectDevice(int deviceSetIndex, const QJsonObject& args) +{ + int direction = deviceSetDirection(deviceSetIndex); + QString hwType = argString(args, "hwType", false); + QString serial = argString(args, "serial", false); + QString displayedName = argString(args, "displayedName", false); + int sequence = argInt(args, "sequence", false, -1); + int streamIndex = argInt(args, "deviceStreamIndex", false, -1); + + if (hasArg(args, "deviceIndex")) + { + // Resolve the index in the available devices list to concrete identifiers + int deviceIndex = argInt(args, "deviceIndex"); + QJsonArray devices = getAvailableDevices(direction)[directionName(direction)].toArray(); + bool found = false; + + for (const auto& value : devices) + { + QJsonObject device = value.toObject(); + + if (device["index"].toInt(-1) == deviceIndex) + { + hwType = device["hwType"].toString(); + serial = device["serial"].toString(); + sequence = device["sequence"].toInt(-1); + streamIndex = device["deviceStreamIndex"].toInt(-1); + displayedName = device["displayedName"].toString(); + found = true; + break; + } + } + + if (!found) { + throw MCPToolError(QString("No %1 device with index %2 in the available devices list").arg(directionName(direction)).arg(deviceIndex)); + } + } + + if (hwType.isEmpty() && serial.isEmpty() && displayedName.isEmpty()) { + throw MCPToolError("Specify at least one of hwType, serial, displayedName or deviceIndex to select a device"); + } + + SWGSDRangel::SWGDeviceListItem query; + query.setDirection(direction); + query.setIndex(-1); + query.setSequence(sequence); + query.setDeviceStreamIndex(streamIndex); + + if (!hwType.isEmpty()) { + query.setHwType(new QString(hwType)); + } + if (!serial.isEmpty()) { + query.setSerial(new QString(serial)); + } + if (!displayedName.isEmpty()) { + query.setDisplayedName(new QString(displayedName)); + } + + SWGSDRangel::SWGDeviceListItem response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + int changedBefore = m_events.m_deviceChanged.loadAcquire(); + check(m_adapter->devicesetDevicePut(deviceSetIndex, query, response, error), error, "Select device"); + + QJsonObject selected = toJson(response); + QString wantHwType = selected["hwType"].toString(); + QString wantSerial = selected["serial"].toString(); + int wantSequence = selected["sequence"].toInt(-1); + + // The change completes on the main thread and is signalled by MainCore::deviceChanged + QJsonObject deviceSet; + bool done = waitFor([&]() + { + if (m_events.m_deviceChanged.loadAcquire() == changedBefore) { + return false; + } + + deviceSet = getDeviceSet(deviceSetIndex); + QJsonObject sampling = deviceSet["samplingDevice"].toObject(); + return (sampling["hwType"].toString() == wantHwType) + && (wantSerial.isEmpty() || (sampling["serial"].toString() == wantSerial)) + && ((wantSequence < 0) || (sampling["sequence"].toInt(-1) == wantSequence)); + }); + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["selectedDevice"] = selected; + result["deviceSet"] = deviceSet; + + if (!done) { + result["warning"] = "Timed out waiting for the device change to complete. Call get_deviceset to check."; + } + + return result; +} + +QJsonObject MCPTools::getDeviceSettings(int deviceSetIndex) +{ + SWGSDRangel::SWGDeviceSettings response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetDeviceSettingsGet(deviceSetIndex, response, error), error, "Get device settings"); + return toJson(response); +} + +QJsonObject MCPTools::patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial) +{ + return applySettingsPatch( + [&](SWGSDRangel::SWGDeviceSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->devicesetDeviceSettingsGet(deviceSetIndex, r, e); + }, + [&](const QStringList& keys, SWGSDRangel::SWGDeviceSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->devicesetDeviceSettingsPutPatch(deviceSetIndex, false, keys, r, e); + }, + partial, QString("device settings of device set %1").arg(deviceSetIndex), + [this](const QString& definition) { return settingsSchema(definition); }); +} + +QSet MCPTools::channelUids(int deviceSetIndex) const +{ + QSet result; + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { + return result; + } + + DeviceSet *deviceSet = deviceSets[deviceSetIndex]; + + for (int i = 0; i < deviceSet->getNumberOfChannels(); i++) + { + const ChannelAPI *channel = deviceSet->getChannelAt(i); + + if (channel) { + result.insert(channel->getUID()); + } + } + + return result; +} + +QSet MCPTools::featureUids() const +{ + QSet result; + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty()) { + return result; + } + + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + const Feature *feature = featureSets[0]->getFeatureAt(i); + + if (feature) { + result.insert(feature->getUID()); + } + } + + return result; +} + +QSet MCPTools::deviceSetPointers() const +{ + QSet result; + + for (DeviceSet *deviceSet : MainCore::instance()->getDeviceSets()) { + result.insert(deviceSet); + } + + return result; +} + +// Adds a channel and waits for SDRangel to create it (which happens on the main thread), +// returning its index. The channel is ready to accept settings when this returns. +// +// The new channel is found by identity rather than by taking the last index: the GUI or +// another request can create a channel at the same time, and picking the highest index would +// then configure or delete somebody else's channel. +int MCPTools::addChannelAndWait(int deviceSetIndex, const QString& channelType) +{ + QMutexLocker creationLock(&m_creationMutex); + int direction = deviceSetDirection(deviceSetIndex); + int before = channelCount(deviceSetIndex); + + // A MIMO device set takes receive and transmit channels as well as MIMO ones, and the + // adapter looks the type up in the list the direction names, so the direction has to be + // the channel's rather than the device set's + if (direction == 2) + { + if (channelTypeIds(0).contains(channelType)) { + direction = 0; + } else if (channelTypeIds(1).contains(channelType)) { + direction = 1; + } + } + + if (before < 0) { + throw MCPToolError(QString("No device set with index %1").arg(deviceSetIndex)); + } + + QSet existing = channelUids(deviceSetIndex); + SWGSDRangel::SWGChannelSettings query; + query.setDirection(direction); + query.setChannelType(new QString(channelType)); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + int addedBefore = m_events.m_channelAdded.loadAcquire(); + check(m_adapter->devicesetChannelPost(deviceSetIndex, query, response, error), error, QString("Add channel %1").arg(channelType)); + + int channelIndex = -1; + bool created = waitFor([&]() + { + if (m_events.m_channelAdded.loadAcquire() <= addedBefore) { + return false; + } + + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size())) { + return false; + } + + DeviceSet *deviceSet = deviceSets[deviceSetIndex]; + + for (int i = 0; i < deviceSet->getNumberOfChannels(); i++) + { + ChannelAPI *channel = deviceSet->getChannelAt(i); + + if (!channel || existing.contains(channel->getUID())) { + continue; + } + + QString id; + channel->getIdentifier(id); + + if (id == channelType) + { + channelIndex = i; + return true; + } + } + + return false; + }); + + if (!created || (channelIndex < 0)) { + throw MCPToolError(QString("Timed out waiting for the %1 channel to be created").arg(channelType)); + } + + // The channel needs a moment before it can accept settings + waitFor([&]() + { + SWGSDRangel::SWGChannelSettings s; + SWGSDRangel::SWGErrorResponse e; + e.init(); + return m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, s, e) / 100 == 2; + }, 2000); + + return channelIndex; +} + +// As for channels, the new feature is found by identity so that a feature created at the same +// time by the GUI or another request is never mistaken for this one. +int MCPTools::addFeatureAndWait(const QString& featureType) +{ + QMutexLocker creationLock(&m_creationMutex); + if (featureCount() < 0) { + throw MCPToolError("No feature set available"); + } + + QSet existing = featureUids(); + SWGSDRangel::SWGFeatureSettings query; + query.setFeatureType(new QString(featureType)); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + int addedBefore = m_events.m_featureAdded.loadAcquire(); + check(m_adapter->featuresetFeaturePost(0, query, response, error), error, QString("Add feature %1").arg(featureType)); + + int featureIndex = -1; + auto findNew = [&]() + { + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty()) { + return -1; + } + + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + Feature *feature = featureSets[0]->getFeatureAt(i); + + if (!feature || existing.contains(feature->getUID())) { + continue; + } + + if (feature->getIdentifier() == featureType) { + return i; + } + } + + return -1; + }; + + // The wait ends as soon as the feature appears, so a longer limit only costs time when one + // genuinely fails to be created. The Map takes a while: it brings up a web engine + waitFor([&]() + { + if (m_events.m_featureAdded.loadAcquire() <= addedBefore) { + return false; + } + + featureIndex = findNew(); + return featureIndex >= 0; + }, 15000); + + if (featureIndex < 0) + { + // Look once more before reporting a failure. A caller told that creation failed when it + // did not will retry, and every retry builds another one + featureIndex = findNew(); + } + + if (featureIndex < 0) { + throw MCPToolError(QString("Timed out waiting for the %1 feature to be created").arg(featureType)); + } + + // The feature needs a moment before it can accept settings + waitFor([&]() + { + SWGSDRangel::SWGFeatureSettings s; + SWGSDRangel::SWGErrorResponse e; + e.init(); + return m_adapter->featuresetFeatureSettingsGet(0, featureIndex, s, e) / 100 == 2; + }, 2000); + + return featureIndex; +} + +// Device set creation runs as a state machine on the main thread; MainCore::deviceSetAdded +// marks the end. The new set is identified by pointer for the same reason as above. +int MCPTools::addDeviceSetAndWait(int direction) +{ + QMutexLocker creationLock(&m_creationMutex); + QSet existing = deviceSetPointers(); + int before = m_events.m_deviceSetAdded.loadAcquire(); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDeviceSetPost(direction, response, error), error, "Add device set"); + + int deviceSetIndex = -1; + bool created = waitFor([&]() + { + if (m_events.m_deviceSetAdded.loadAcquire() <= before) { + return false; + } + + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + for (int i = 0; i < (int) deviceSets.size(); i++) + { + if (!existing.contains(deviceSets[i])) + { + deviceSetIndex = i; + return true; + } + } + + return false; + }); + + if (!created || (deviceSetIndex < 0)) { + throw MCPToolError("Timed out waiting for the device set to be created"); + } + + return deviceSetIndex; +} + +// Deletes a channel and waits for SDRangel to remove it +// Watches the channel itself disappear rather than the removed signal, which is not emitted +// for the last channel of a device set +void MCPTools::deleteChannelAndWait(int deviceSetIndex, int channelIndex) +{ + QMutexLocker deletionLock(&m_deletionMutex); + deleteChannelLocked(deviceSetIndex, channelIndex); +} + +void MCPTools::deleteChannelLocked(int deviceSetIndex, int channelIndex) +{ + const uint64_t target = channelUidAt(deviceSetIndex, channelIndex); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelDelete(deviceSetIndex, channelIndex, response, error), error, "Delete channel"); + + if (!waitFor([&]() { return !channelUids(deviceSetIndex).contains(target); })) { + throw MCPToolError(QString("Timed out waiting for channel %1:%2 to be removed").arg(deviceSetIndex).arg(channelIndex)); + } + + m_capture.forgetRecording(target); +} + +// Deletes a channel identified by its UID. A caller that waited, for instance for a +// recording to finish, cannot rely on the index it started with: deleting a lower numbered +// channel meanwhile renumbers everything above it. +void MCPTools::deleteChannelObjectAndWait(uint64_t channelUid) +{ + // The lookup and the delete under one lock, or another call's delete in between renumbers + // the index just found + QMutexLocker deletionLock(&m_deletionMutex); + int deviceSetIndex = -1; + int channelIndex = -1; + + if (!MCPCapture::locateChannel(channelUid, deviceSetIndex, channelIndex)) + { + m_capture.forgetRecording(channelUid); + return; // already gone, which is what was asked for + } + + deleteChannelLocked(deviceSetIndex, channelIndex); +} + +uint64_t MCPTools::deviceSetIdentity(int deviceSetIndex) const +{ + const std::vector& deviceSets = MainCore::instance()->getDeviceSets(); + + if ((deviceSetIndex < 0) || (deviceSetIndex >= (int) deviceSets.size()) || !deviceSets[deviceSetIndex]) { + return 0; + } + + const DeviceSet *deviceSet = deviceSets[deviceSetIndex]; + const uint64_t engine = deviceSet->m_deviceAPI ? deviceSet->m_deviceAPI->getDeviceUID() : 0; + return (engine << 32) ^ reinterpret_cast(deviceSet); +} + +void MCPTools::discardNewDeviceSet(int deviceSetIndex, uint64_t identity) +{ + try + { + QMutexLocker deletionLock(&m_deletionMutex); + + // Only the last device set can be removed, and only when it is still the one made + // here: another call may have added one since, or removed this one and put another + // at the same index while this call slept, and then what is there is left for the user + if ((deviceSetIndex < 0) || (deviceSetIndex != deviceSetCount() - 1) + || (identity == 0) || (deviceSetIdentity(deviceSetIndex) != identity)) { + return; + } + + int before = m_events.m_deviceSetRemoved.loadAcquire(); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDeviceSetDelete(response, error), error, "Remove device set"); + waitFor([&]() { return m_events.m_deviceSetRemoved.loadAcquire() > before; }); + } + catch (const MCPToolError&) {} +} + +const void *MCPTools::featureAt(int featureIndex) const +{ + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty() || (featureIndex < 0) || (featureIndex >= featureSets[0]->getNumberOfFeatures())) { + return nullptr; + } + + return featureSets[0]->getFeatureAt(featureIndex); +} + +uint64_t MCPTools::featureUidAt(int featureIndex) const +{ + const Feature *feature = static_cast(featureAt(featureIndex)); + return feature ? feature->getUID() : 0; +} + +uint64_t MCPTools::channelUidAt(int deviceSetIndex, int channelIndex) const +{ + return MCPCapture::channelUidAt(deviceSetIndex, channelIndex); +} + +// Deleting or stopping the feature that is serving this request would tear down the HTTP +// listener from inside its own handler, so it is refused rather than attempted. +void MCPTools::requireNotSelf(int featureIndex, const QString& action) const +{ + if (m_ownerFeature && (featureAt(featureIndex) == m_ownerFeature)) + { + throw MCPToolError(QString("Feature %1 is the MCP Server serving this request and cannot be %2 through it. " + "Use the SDRangel GUI or the REST API instead.").arg(featureIndex).arg(action)); + } +} + +QJsonObject MCPTools::getChannelSettings(int deviceSetIndex, int channelIndex) +{ + SWGSDRangel::SWGChannelSettings response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, response, error), error, "Get channel settings"); + return toJson(response); +} + +SettingsSchema MCPTools::settingsSchema(const QString& definition) +{ + QMutexLocker schemaLock(&m_schemaMutex); + + if (m_schemaCache.contains(definition)) { + return m_schemaCache[definition]; + } + + SettingsSchema schema; + // Without this no device setting found its schema and none of them were type checked + QString name = resolveDefinition(definition); + + if (!name.isEmpty()) { + schema = parseSettingsSchema(m_yamlDefinitions[name]); + } + + m_schemaCache.insert(definition, schema); + return schema; +} + +QJsonObject MCPTools::getSpectrumSettings(int deviceSetIndex) +{ + SWGSDRangel::SWGGLSpectrum response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, response, error), error, "Get spectrum settings"); + return toJson(response); +} + +QJsonObject MCPTools::patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys) +{ + SWGSDRangel::SWGGLSpectrum current; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, current, error), error, "Get spectrum settings"); + QJsonObject json = toJson(current); + QStringList unknown; + QJsonObject checked = partial; + SettingsSchema schema = settingsSchema("GLSpectrum"); + + if (schema.m_known) + { + QStringList typeErrors; + checked = checkAgainstSchema(partial, schema, unknown, typeErrors); + + if (!typeErrors.isEmpty()) + { + throw MCPToolError(QString("Wrong value type for spectrum settings: %1. Numbers must be " + "given as JSON numbers, not strings. Nothing was changed.").arg(typeErrors.join("; "))); + } + } + + QStringList merged; + mergeInto(json, checked, merged); + + if (!schema.m_known) { + unknown = merged; + } + + if (unknownKeys) { + *unknownKeys = unknown; + } + + QStringList keys; + extractKeys(checked, keys); + SWGSDRangel::SWGGLSpectrum request; + request.init(); + request.fromJsonObject(json); + error.init(); + check(m_adapter->devicesetSpectrumSettingsPutPatch(deviceSetIndex, false, keys, request, error), error, "Set spectrum settings"); + return toJson(request); +} + +void MCPTools::addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex) +{ + if (channelType != "BFMDemod") { + return; + } + + if (report.value("BFMDemodReport").toObject().contains("rdsReport")) { + return; + } + + // The report is empty for a channel that is not running as well, where saying anything about + // RDS would only mislead, so the hint is tied to the setting that actually suppresses it + QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex).value("BFMDemodSettings").toObject(); + + if (settings.value("rdsActive").toInt(0) == 0) + { + report["rdsHint"] = "RDS is not being decoded, which is why this report has no rdsReport. Set rdsActive to 1 with " + "set_channel_settings to get the programme service name (the station name), radio text, programme " + "type and PI code."; + } +} + +QJsonObject MCPTools::patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial) +{ + return applySettingsPatch( + [&](SWGSDRangel::SWGChannelSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->devicesetChannelSettingsGet(deviceSetIndex, channelIndex, r, e); + }, + [&](const QStringList& keys, SWGSDRangel::SWGChannelSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->devicesetChannelSettingsPutPatch(deviceSetIndex, channelIndex, false, keys, r, e); + }, + partial, QString("channel settings of channel %1:%2").arg(deviceSetIndex).arg(channelIndex), + [this](const QString& definition) { return settingsSchema(definition); }); +} + +QJsonObject MCPTools::getFeatureSettings(int featureIndex) +{ + SWGSDRangel::SWGFeatureSettings response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureSettingsGet(0, featureIndex, response, error), error, "Get feature settings"); + return toJson(response); +} + +QJsonObject MCPTools::patchFeatureSettings(int featureIndex, const QJsonObject& partial) +{ + return applySettingsPatch( + [&](SWGSDRangel::SWGFeatureSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->featuresetFeatureSettingsGet(0, featureIndex, r, e); + }, + [&](const QStringList& keys, SWGSDRangel::SWGFeatureSettings& r, SWGSDRangel::SWGErrorResponse& e) { + return m_adapter->featuresetFeatureSettingsPutPatch(0, featureIndex, false, keys, r, e); + }, + partial, QString("feature settings of feature %1").arg(featureIndex), + [this](const QString& definition) { return settingsSchema(definition); }); +} + +QJsonObject MCPTools::deviceState(int deviceSetIndex, int subsystemIndex, int run) +{ + SWGSDRangel::SWGDeviceState response; + response.init(); + SWGSDRangel::SWGErrorResponse error; + error.init(); + int rc; + + // The subsystem variants only apply to MIMO devices; single stream devices use the plain calls + bool mimo = deviceSetDirection(deviceSetIndex) == 2; + + auto runGet = [&](SWGSDRangel::SWGDeviceState& s, SWGSDRangel::SWGErrorResponse& e) { + return mimo ? m_adapter->devicesetDeviceSubsystemRunGet(deviceSetIndex, subsystemIndex, s, e) + : m_adapter->devicesetDeviceRunGet(deviceSetIndex, s, e); + }; + + if (run == 1) { + rc = mimo ? m_adapter->devicesetDeviceSubsystemRunPost(deviceSetIndex, subsystemIndex, response, error) + : m_adapter->devicesetDeviceRunPost(deviceSetIndex, response, error); + } else if (run == 0) { + rc = mimo ? m_adapter->devicesetDeviceSubsystemRunDelete(deviceSetIndex, subsystemIndex, response, error) + : m_adapter->devicesetDeviceRunDelete(deviceSetIndex, response, error); + } else { + rc = runGet(response, error); + } + + check(rc, error, run == 1 ? "Start device" : (run == 0 ? "Stop device" : "Get device state")); + + // The state returned by POST/DELETE is the state before the change. Give the device a moment + // and report the state actually reached. + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + + if (run >= 0) + { + QString want = run == 1 ? "running" : "idle"; + QString readError; + + bool reached = waitFor([&]() + { + SWGSDRangel::SWGDeviceState state; + state.init(); + SWGSDRangel::SWGErrorResponse e; + e.init(); + int getRC = runGet(state, e); + + if (getRC / 100 != 2) + { + readError = QString("HTTP %1 %2").arg(getRC).arg(e.getMessage() ? *e.getMessage() : QString()); + return true; // stop polling, reported below + } + + response.init(); + *response.getState() = *state.getState(); + return *state.getState() == want || *state.getState() == "error"; + }, 3000); + + if (!readError.isEmpty()) { + throw MCPToolError(QString("%1 was requested but the device state could not be read back: %2").arg(run == 1 ? "Start" : "Stop").arg(readError)); + } + + if (!reached) { + result["warning"] = QString("The device did not reach the %1 state within 3 seconds. The state reported here is the last one observed").arg(want); + } + } + + result["state"] = *response.getState(); + return result; +} + +QJsonObject MCPTools::featureState(int featureIndex, int run) +{ + // Asking a passive feature to run waits three seconds for a state it never reports, or fails + // outright on the ones that answer 501, so say what it is instead of doing either + if (run >= 0) + { + QString featureType = getFeatureSettings(featureIndex)["featureType"].toString(); + + if (isPassiveFeature(featureType)) + { + QJsonObject passive; + passive["featureIndex"] = featureIndex; + passive["featureType"] = featureType; + passive["state"] = "idle"; + passive["passive"] = true; + passive["note"] = QString("%1 has no run state and does not need starting: it works as soon as it " + "is configured, and reports idle whether or not it is doing anything.").arg(featureType); + return passive; + } + } + + SWGSDRangel::SWGDeviceState response; + response.init(); + SWGSDRangel::SWGErrorResponse error; + error.init(); + int rc; + + if (run == 1) { + rc = m_adapter->featuresetFeatureRunPost(0, featureIndex, response, error); + } else if (run == 0) { + rc = m_adapter->featuresetFeatureRunDelete(0, featureIndex, response, error); + } else { + rc = m_adapter->featuresetFeatureRunGet(0, featureIndex, response, error); + } + + check(rc, error, run == 1 ? "Start feature" : (run == 0 ? "Stop feature" : "Get feature state")); + + QJsonObject result; + result["featureIndex"] = featureIndex; + + if (run >= 0) + { + QString want = run == 1 ? "running" : "idle"; + QString readError; + + bool reached = waitFor([&]() + { + SWGSDRangel::SWGDeviceState state; + state.init(); + SWGSDRangel::SWGErrorResponse e; + e.init(); + int getRC = m_adapter->featuresetFeatureRunGet(0, featureIndex, state, e); + + if (getRC / 100 != 2) + { + readError = QString("HTTP %1 %2").arg(getRC).arg(e.getMessage() ? *e.getMessage() : QString()); + return true; // stop polling, reported below + } + + response.init(); + *response.getState() = *state.getState(); + return *state.getState() == want || *state.getState() == "error"; + }, 3000); + + if (!readError.isEmpty()) { + throw MCPToolError(QString("%1 was requested but the feature state could not be read back: %2").arg(run == 1 ? "Start" : "Stop").arg(readError)); + } + + if (!reached) { + result["warning"] = QString("The feature did not reach the %1 state within 3 seconds. The state reported here is the last one observed").arg(want); + } + } + + result["state"] = *response.getState(); + return result; +} + +// Resolves group name + name (and optionally centre frequency and type) to the full preset identifier +// SDRangel needs. For a save, the identifier of the current device is used when no matching preset exists. +QJsonObject MCPTools::presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave) +{ + QString groupName = argString(args, "groupName"); + QString name = argString(args, "name"); + QString type = argString(args, "type", false); + bool hasFrequency = hasArg(args, "centerFrequency"); + qint64 centerFrequency = argInt64(args, "centerFrequency", false, 0); + + QJsonObject deviceSet; + QString deviceType; + qint64 deviceFrequency = 0; + + if (forSave) + { + deviceSet = getDeviceSet(deviceSetIndex); + QJsonObject sampling = deviceSet["samplingDevice"].toObject(); + deviceFrequency = (qint64) sampling["centerFrequency"].toDouble(); + int direction = sampling["direction"].toInt(0); + deviceType = direction == 0 ? "R" : (direction == 1 ? "T" : "M"); + } + + QJsonArray candidates; + + for (const auto& groupValue : getPresets()["groups"].toArray()) + { + QJsonObject group = groupValue.toObject(); + + if (group["groupName"].toString() != groupName) { + continue; + } + + for (const auto& presetValue : group["presets"].toArray()) + { + QJsonObject preset = presetValue.toObject(); + + if (preset["name"].toString() != name) { + continue; + } + if (!type.isEmpty() && (preset["type"].toString() != type)) { + continue; + } + if (hasFrequency && ((qint64) preset["centerFrequency"].toDouble() != centerFrequency)) { + continue; + } + if (forSave && (preset["type"].toString() != deviceType)) { + continue; + } + + candidates.append(preset); + } + } + + QJsonObject identifier; + identifier["groupName"] = groupName; + identifier["name"] = name; + + if (candidates.count() == 1) + { + QJsonObject preset = candidates.first().toObject(); + identifier["type"] = preset["type"].toString(); + identifier["centerFrequency"] = preset["centerFrequency"].toDouble(); + identifier["exists"] = true; + } + else if (candidates.count() > 1) + { + throw MCPToolError(QString("Several presets match group %1 name %2. Specify centerFrequency and type to choose one of: %3") + .arg(groupName).arg(name).arg(compact(candidates))); + } + else if (forSave) + { + identifier["type"] = deviceType; + identifier["centerFrequency"] = (double) deviceFrequency; + identifier["exists"] = false; + } + else + { + throw MCPToolError(QString("No preset with group %1 and name %2. Call list_presets to see what exists").arg(groupName).arg(name)); + } + + return identifier; +} + +// --------------------------------------------------------------------------- +// Tool registration +// --------------------------------------------------------------------------- + +void MCPTools::registerInstanceTools() +{ + add("get_instance_summary", + "Get an overview of the SDRangel instance: version, all device sets with their sampling device and channels, and all features. " + "Call this first to learn the current state and the indexes to use with other tools.", + schema(QJsonObject()), + [this](const QJsonObject&) { return getInstanceSummary(); }); + + add("list_available_devices", + "List the SDR hardware and software sources/sinks that can be selected in a device set. Each entry gives hwType (used by " + "set_device and describe_settings), serial, sequence and index. Physical devices must be plugged in before SDRangel starts.", + schema({{"direction", directionProp("Only list devices for this direction (rx, tx or mimo). Default: all directions")}}), + [this](const QJsonObject& args) { return getAvailableDevices(argDirection(args, "direction", false, -1)); }); + + add("list_channel_types", + "List the channel plugins (demodulators for rx, modulators for tx) that can be added to a device set. The id is the channelType " + "to pass to add_channel and describe_settings.", + schema({{"direction", directionProp("Only list channels for this direction (rx, tx or mimo). Default: all directions")}}), + [this](const QJsonObject& args) { return getAvailableChannels(argDirection(args, "direction", false, -1)); }); + + add("list_feature_types", + "List the feature plugins that can be added with add_feature. The id is the featureType.", + schema(QJsonObject()), + [this](const QJsonObject&) { return getAvailableFeatures(); }); + + add("describe_settings", + "Get the documentation (OpenAPI YAML) of the settings, report and actions keys of a device, channel or feature type, " + "or of the spectrum display: what each key means, its units, range and enumeration values. Not needed for common keys; " + "call it when a set_* tool reports an unknown key, or before setting a key whose values are codes, such as a style or " + "mode. The output can run to a few thousand tokens.", + schema({ + {"type", strProp("Type identifier: a device hwType such as RTLSDR or TestSource, a channelType such as ADSBDemod or NFMDemod, " + "a featureType such as Map, or spectrum for the spectrum display")}, + {"kind", strProp("Optional: device, channel, feature or spectrum, to disambiguate when the same id exists for several kinds")} + }, {"type"}), + [this](const QJsonObject& args) { return QJsonValue(describeType(argString(args, "type"), argString(args, "kind", false))); }); + + add("get_receiving_guide", + "Read the receiving guide: which demodulator and frequency to use for a given signal or protocol (ADS-B, AIS, APRS, " + "radiosondes, weather satellites, broadcast FM, LoRa, pagers and more), the minimum device sample rate some modes need, " + "and the usual reasons nothing is received. Read this before setting up a receiver for a named signal, rather than " + "guessing frequencies.", + schema(QJsonObject()), + [this](const QJsonObject&) { return QJsonValue(m_docs.guide()); }); + + add("list_docs", + "List the user documentation (readme) available for the device, channel and feature plugins registered in this instance, " + "and for the GUI's own pages such as the spectrum display, with the section headings of each. Use get_docs to read one.", + schema({{"kind", strProp("Optional: only list device, channel, feature or gui docs")}}), + [this](const QJsonObject& args) + { + QString kind = argString(args, "kind", false).trimmed().toLower(); + QJsonObject index = m_docs.index(); + + if (kind.isEmpty()) { + return index; + } + + QJsonArray filtered; + + for (const auto& value : index["docs"].toArray()) + { + if (value.toObject()["kind"].toString() == kind) { + filtered.append(value); + } + } + + QJsonObject result; + result["count"] = filtered.count(); + result["docs"] = filtered; + return result; + }); + + add("get_docs", + "Read the user documentation (readme, as markdown) of a device, channel or feature plugin, or of a GUI page such as the " + "spectrum display: what it does, what each setting means, frequencies and sample rates it needs, and how to use it. Pass " + "section to get just one section (matched against the headings listed by list_docs) as the full documents can be long.", + schema({ + {"type", strProp("Plugin id (e.g. ADSBDemod, RTLSDR, Map), its displayed name (e.g. \"ADS-B Demodulator\"), or a GUI page: " + "spectrum, spectrummarkers, spectrummeasurements, spectrumcalibration, mainspectrum, audio, configurations, deviceuserargs, transverter")}, + {"kind", strProp("Optional: device, channel, feature or gui, to disambiguate")}, + {"section", strProp("Optional: text of a heading; only that section is returned")} + }, {"type"}), + [this](const QJsonObject& args) + { + QString type = argString(args, "type"); + QString kind = argString(args, "kind", false); + const MCPDocs::Doc *doc = m_docs.find(type, kind); + + if (!doc) { + throw MCPToolError(QString("No documentation found for %1. Call list_docs to see what is available").arg(type)); + } + + QString section = argString(args, "section", false); + QString text = m_docs.text(*doc, section); + + if (text.isEmpty()) { + throw MCPToolError(QString("No section matching \"%1\" in the %2 documentation. Sections: %3").arg(section).arg(doc->id).arg(doc->headings.join(" | "))); + } + + return QJsonValue(text); + }); + + add("get_packets", + "Get recently decoded packets from packet-oriented demodulators (AIS, APRS/AX.25 packet, LoRa/ChirpChat, M17, Meshtastic, " + "MeshCore, Inmarsat, radiosonde). Each packet has the raw bytes (hex and printable text) and, where SDRangel can decode it, " + "a decoded object: AIS message type, MMSI, position, course and speed; AX.25 from/to/via and data with APRS position and " + "comment; RS41 radiosonde serial, position and height. Packets are kept in a buffer of the last 1000; use sinceSequence " + "with the lastSequence of a previous call to read only new packets.", + schema({ + {"source", strProp("Only packets from this channel, e.g. \"R0:1\" (device set 0, channel 1)")}, + {"type", strProp("Only packets from channels of this type, e.g. AISDemod, PacketDemod, RadiosondeDemod")}, + {"limit", bounded(intProp("Maximum number of packets to return, most recent first. Default 50"), 1, MCPDataFeed::m_maxPackets)}, + {"sinceSequence", intProp("Only packets with a sequence number greater than this")} + }), + [this](const QJsonObject& args) + { + return m_dataFeed.getPackets(argString(args, "source", false), argString(args, "type", false), + argInt(args, "limit", false, 50), argInt64(args, "sinceSequence", false, 0)); + }); + + add("clear_packets", + "Discard all buffered packets.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + m_dataFeed.clearPackets(); + QJsonObject result; + result["cleared"] = true; + return result; + }); + + add("get_map_items", + "Get the objects currently plotted on the map by the running plugins: aircraft from ADS-B, ships from AIS, APRS stations, " + "radiosondes, satellites, the Sun and Moon from the star tracker, VOR/ILS beacons and so on. Each item has a name, position, " + "altitude, heading, the label and text shown on the map, and for aircraft the full ADS-B state. Only sources that are " + "running produce items; items disappear when their source removes them.", + schema({ + {"source", strProp("Only items from this channel or feature id (e.g. \"R0:0\", \"F:1\") or plugin type (e.g. ADSBDemod, AIS)")}, + {"name", strProp("Only items whose name contains this text, e.g. an ICAO address, MMSI or callsign")}, + {"limit", bounded(intProp("Maximum number of items to return. Default 200"), 1, 5000)}, + {"includeTrack", prop("boolean", "Include the position history of each item. Default false, as tracks can be long")} + }), + [this](const QJsonObject& args) + { + bool includeTrack = argBool(args, "includeTrack", false); + return m_dataFeed.getMapItems(argString(args, "source", false), argString(args, "name", false), + argInt(args, "limit", false, 200), includeTrack); + }); + + add("list_audio_devices", + "List the audio input and output devices available to SDRangel.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + SWGSDRangel::SWGAudioDevices response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceAudioGet(response, error), error, "List audio devices"); + return toJson(response); + }); + + add("get_location", + "Get the station location (latitude and longitude in degrees) used by features such as the Map and satellite tracker.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + SWGSDRangel::SWGLocationInformation response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceLocationGet(response, error), error, "Get location"); + return toJson(response); + }); + + add("set_location", + "Set the station location.", + schema({ + {"latitude", bounded(numProp("Latitude in degrees, positive north"), -90.0, 90.0)}, + {"longitude", bounded(numProp("Longitude in degrees, positive east"), -180.0, 180.0)} + }, {"latitude", "longitude"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGLocationInformation response; + response.setLatitude((float) argDouble(args, "latitude")); + response.setLongitude((float) argDouble(args, "longitude")); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceLocationPut(response, error), error, "Set location"); + return toJson(response); + }); +} + +void MCPTools::registerDeviceSetTools() +{ + add("add_deviceset", + "Create a new device set and optionally select its sampling device in one go. Returns the index of the new device set. " + "Identify the device with hwType and/or serial (from list_available_devices), or deviceIndex (its index in that list). " + "Without a device the new device set uses the first available device of that direction.", + schema({ + {"direction", directionProp("rx for a receiver (default), tx for a transmitter, mimo for a MIMO device")}, + {"hwType", strProp("Hardware type of the device to select, e.g. RTLSDR, HackRF, TestSource")}, + {"serial", strProp("Serial number of the device to select")}, + {"sequence", intProp("Sequence number of the device, to distinguish identical devices")}, + {"displayedName", strProp("Displayed name of the device, as listed by list_available_devices")}, + {"deviceIndex", intProp("Index of the device in the list_available_devices list for this direction")} + }), + [this](const QJsonObject& args) + { + int direction = argDirection(args, "direction", false, 0); + int deviceSetIndex = addDeviceSetAndWait(direction); + + if (hasArg(args, "hwType") || hasArg(args, "serial") || hasArg(args, "displayedName") || hasArg(args, "deviceIndex")) + { + try + { + return selectDevice(deviceSetIndex, args); + } + catch (const MCPToolError& e) + { + throw MCPToolError(QString("Device set %1 was created but the requested device could not be selected: %2. " + "Use set_device on that device set, or remove_last_deviceset. Do not call add_deviceset again.") + .arg(deviceSetIndex).arg(e.message)); + } + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["deviceSet"] = getDeviceSet(deviceSetIndex); + return result; + }); + + add("remove_last_deviceset", + "Remove the device set with the highest index. In the GUI the first device set (R0) cannot be removed.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + int before = m_events.m_deviceSetRemoved.loadAcquire(); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDeviceSetDelete(response, error), error, "Remove device set"); + + if (!waitFor([&]() { return m_events.m_deviceSetRemoved.loadAcquire() > before; })) { + throw MCPToolError("Timed out waiting for the device set to be removed; get_instance_summary shows whether it went"); + } + + QJsonObject result; + result["deviceSetCount"] = deviceSetCount(); + return result; + }); + + add("get_deviceset", + "Get a device set: its sampling device (hwType, serial, centre frequency, state) and the list of its channels with their reports.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return getDeviceSet(argInt(args, "deviceSetIndex")); }); + + add("set_device", + "Change the sampling device of an existing device set. Identify the device with hwType and/or serial (from list_available_devices), " + "or deviceIndex. Waits for the change to complete.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"hwType", strProp("Hardware type of the device to select, e.g. RTLSDR")}, + {"serial", strProp("Serial number of the device to select")}, + {"sequence", intProp("Sequence number of the device, to distinguish identical devices")}, + {"displayedName", strProp("Displayed name of the device")}, + {"deviceIndex", intProp("Index of the device in the list_available_devices list for the device set direction")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return selectDevice(argInt(args, "deviceSetIndex"), args); }); + + add("get_device_settings", + "Get the settings of the sampling device of a device set (centre frequency, sample rate, gain...). The keys depend on the device type.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return getDeviceSettings(argInt(args, "deviceSetIndex")); }); + + add("set_device_settings", + "Change some settings of the sampling device of a device set. Give only the keys to change, e.g. {\"centerFrequency\": 1090000000, \"gain\": 400}. " + "Use describe_settings with the device hwType to learn the valid keys, units and value ranges. Returns the keys changed with their applied values.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"settings", objProp("Object with the settings keys to change and their new values")} + }, {"deviceSetIndex", "settings"}), + [this](const QJsonObject& args) { return patchDeviceSettings(argInt(args, "deviceSetIndex"), argObject(args, "settings")); }); + + add("set_center_frequency", + "Tune the sampling device of a device set to a centre frequency in Hz. Channels keep their inputFrequencyOffset relative to it.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"frequency", numProp("Centre frequency in Hz")} + }, {"deviceSetIndex", "frequency"}), + [this](const QJsonObject& args) + { + QJsonObject settings; + settings["centerFrequency"] = (double) argInt64(args, "frequency"); + return patchDeviceSettings(argInt(args, "deviceSetIndex"), settings); + }); + + add("start_device", + "Start the sampling device of a device set so that it streams samples and its channels run. Returns the resulting state.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"subsystemIndex", bounded(intProp("MIMO devices only: 0 for the rx subsystem, 1 for tx. Default 0"), 0, 1)} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject state = deviceState(deviceSetIndex, argInt(args, "subsystemIndex", false, 0), 1); + QStringList warnings = basebandWarnings(deviceSetIndex); + + if (!warnings.isEmpty()) { + state["warning"] = warnings.join(" "); + } + + return QJsonValue(state); + }); + + add("stop_device", + "Stop the sampling device of a device set.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"subsystemIndex", bounded(intProp("MIMO devices only: 0 for the rx subsystem, 1 for tx. Default 0"), 0, 1)} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return deviceState(argInt(args, "deviceSetIndex"), argInt(args, "subsystemIndex", false, 0), 0); }); + + add("get_device_report", + "Get the live report of the sampling device of a device set (for example the actual sample rate, gain values, " + "or for file inputs the playback position). Keys depend on the device type.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGDeviceReport response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetDeviceReportGet(argInt(args, "deviceSetIndex"), response, error), error, "Get device report"); + return toJson(response); + }); + + add("device_action", + "Trigger an action on the sampling device of a device set. Only some device types have actions. Use describe_settings to find " + "the actions keys of the device type; pass them as the actions object, e.g. {\"record\": 1}.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"actions", objProp("Object with the action keys and values for this device type")} + }, {"deviceSetIndex", "actions"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject actions = argObject(args, "actions"); + QJsonObject settings = getDeviceSettings(deviceSetIndex); + QString hwType = settings["deviceHwType"].toString(); + int direction = settings["direction"].toInt(0); + const QMap& map = direction == 0 ? WebAPIUtils::m_sourceDeviceHwIdToActionsKey + : (direction == 1 ? WebAPIUtils::m_sinkDeviceHwIdToActionsKey : WebAPIUtils::m_mimoDeviceHwIdToActionsKey); + + if (!map.contains(hwType)) { + throw MCPToolError(QString("Device type %1 has no actions").arg(hwType)); + } + + QJsonObject json; + json["deviceHwType"] = hwType; + json["direction"] = direction; + json[map[hwType]] = actions.contains(map[hwType]) ? actions[map[hwType]].toObject() : actions; + QStringList keys; + extractKeys(json[map[hwType]].toObject(), keys); + + SWGSDRangel::SWGDeviceActions query; + query.init(); + query.fromJsonObject(json); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetDeviceActionsPost(deviceSetIndex, keys, query, response, error), error, "Device action"); + return toJson(response); + }); + + add("get_spectrum_settings", + "Get the settings of the main spectrum display of a device set, including FFT and scale, 2D/3D spectrum display, waterfall history, measurements and statistics, math, and saved-memory display settings.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGGLSpectrum response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumSettingsGet(argInt(args, "deviceSetIndex"), response, error), error, "Get spectrum settings"); + return toJson(response); + }); + + add("set_spectrum_settings", + "Change selected settings of the main spectrum display of a device set. Supports FFT and scale, 2D/3D spectrum display, waterfall history, measurements and statistics, math, and saved-memory display settings. Give only the keys to change (see get_spectrum_settings for the keys). " + "Keys whose values are codes are documented by describe_settings with type spectrum: for instance spectrumStyle is 0 line, 1 filled solid colour, 2 filled colour gradient, and colorMap names the gradient. " + "To smooth the trace set both averagingMode (1 moving) and averagingValue (the number of FFTs, e.g. 10): a mode with the value left at 1 averages nothing.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"settings", objProp("Object with the spectrum settings keys to change")} + }, {"deviceSetIndex", "settings"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject partial = argObject(args, "settings"); + QStringList unknownKeys; + + auto read = [&]() + { + SWGSDRangel::SWGGLSpectrum current; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumSettingsGet(deviceSetIndex, current, error), error, "Get spectrum settings"); + return toJson(current); + }; + + const QJsonObject before = read(); + patchSpectrumSettings(deviceSetIndex, partial, &unknownKeys); + + // Read back rather than echo the request: some values are rounded to what the + // display offers, and the caller should see what it got. The patch is applied by + // message, so give it a moment to land: until every key given has either moved or + // was already where it was asked to be + QJsonObject after = read(); + + for (int attempt = 0; attempt < 10; attempt++) + { + bool landed = true; + + for (const QString& key : partial.keys()) + { + if (after.contains(key) && (after[key] == before[key]) && (after[key] != partial[key])) { + landed = false; + } + } + + if (landed) { + break; + } + + QThread::msleep(50); + after = read(); + } + + QJsonObject changed; + QStringList notes; + + for (const QString& key : partial.keys()) + { + if (after.contains(key)) + { + changed[key] = after[key]; + + if (after[key].isDouble() && partial[key].isDouble() && (after[key].toDouble() != partial[key].toDouble())) { + notes.append(QString("%1 was rounded to %2, one of the values the display offers.").arg(key).arg(after[key].toDouble())); + } + } + } + + // A mode with a count of one averages nothing, which is easy to leave that way + if ((after["averagingMode"].toInt() != 0) && (after["averagingValue"].toInt() <= 1)) { + notes.append("averagingMode is set but averagingValue is 1, so no averaging is happening: set averagingValue as well, " + "10 to smooth a trace or 50 to measure a floor. The values available are 1, 2, 5, 10, 20, 50, 100 and so on."); + } + + QJsonObject result; + result["changed"] = changed; + + if (!unknownKeys.isEmpty()) { + result["warning"] = QString("Ignored unknown keys: %1. describe_settings lists the valid ones.").arg(unknownKeys.join(", ")); + } + + if (!notes.isEmpty()) { + result["note"] = notes.join(" "); + } + + return result; + }); + + + add("get_spectrum_report", + "Get the latest spectrum measurement results of a device set: peaks, channel power, adjacent channel power, occupied " + "bandwidth, 3 dB bandwidth, or SNR with THD and SINAD, depending on which measurement is selected with " + "set_spectrum_settings. Only the fields the selected measurement produces are returned, so an absent field was not " + "measured rather than measured as zero. With no measurement selected only measurement 0 comes back. The figures are " + "those of the spectrum as displayed, so they follow the zoom.", + schema({{"deviceSetIndex", deviceSetIndexProp}}, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGGLSpectrumReport response; + SWGSDRangel::SWGErrorResponse error; + response.init(); + error.init(); + check(m_adapter->devicesetSpectrumReportGet(argInt(args, "deviceSetIndex"), response, error), error, "Get spectrum report"); + return toJson(response); + }); + + + add("get_spectrum_data", + "Get the current power spectrum of a device set, reduced to the number of bins asked for. Use it to see what is on a band " + "without looking at the screen: which parts are occupied, how strong, and where the edges are. Each value covers " + "binBandwidth Hz starting at startFrequency. Reduction is by max, which keeps a narrow carrier that averaging would bury " + "in its neighbours; mean is better for measuring a noise floor. Every value costs tokens, so ask for the coarsest that " + "answers the question and narrow the frequency range instead of asking for more bins.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"bins", bounded(intProp("Number of values to return, most recent spectrum. Default 64"), 1, 512)}, + {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, + {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")}, + {"reduce", strProp("max to keep peaks, the default, or mean to average")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGGLSpectrumData response; + SWGSDRangel::SWGErrorResponse error; + response.init(); + error.init(); + check(m_adapter->devicesetSpectrumDataGet( + argInt(args, "deviceSetIndex"), + argInt(args, "bins", false, 64), + argInt64(args, "startFrequency", false, 0), + argInt64(args, "stopFrequency", false, 0), + argString(args, "reduce", false, "max"), + response, error), + error, "Get spectrum data"); + QJsonObject json = toJson(response); + + // The generated serialiser drops a list of plain floats, so the values go in by hand + QJsonArray power; + + if (response.getPower()) + { + for (float v : *response.getPower()) { + power.append(std::round((double) v * 10.0) / 10.0); + } + } + + json["power"] = power; + return json; + }); + + add("get_spectrum_history", + "What has been on a band over the last while, from the spectrum history the GUI keeps for scrolling: per bin " + "maximum, mean and occupancy (the fraction of the time the bin was above the noise floor by threshold dB), and a " + "signalList of every run of bins that rose above it, each with its frequency, width, peak, dutyCycle (1 for a " + "continuous carrier, small for bursts) and when it was first and last seen. This is the way to tell a continuous " + "signal from an intermittent one, find where transmissions are without stepping a scanner over them, and measure " + "a floor over time rather than from one snapshot. Only rows taken with the device tuned and sampling as it is now " + "count; after a retune, wait for new history. Scrolling is switched on if it is off, and then there is nothing to " + "report until some has accumulated, so call again after a few seconds. Every bin costs tokens: ask for the coarsest " + "that answers the question.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"seconds", numProp("How far back to look, in seconds. Default 60")}, + {"bins", bounded(intProp("Number of bins to reduce the spectrum to. Default 64"), 1, 512)}, + {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, + {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")}, + {"threshold", numProp("dB above the measured floor for a bin to count as occupied. Default 6")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + const int deviceSetIndex = argInt(args, "deviceSetIndex"); + const double seconds = argDouble(args, "seconds", false, 60.0); + const QString enabled = ensureSpectrumHistory(deviceSetIndex, seconds); + SWGSDRangel::SWGGLSpectrumHistory response; + SWGSDRangel::SWGErrorResponse error; + response.init(); + error.init(); + const int status = m_adapter->devicesetSpectrumHistoryGet(deviceSetIndex, seconds, + argInt(args, "bins", false, 64), argInt64(args, "startFrequency", false, 0), argInt64(args, "stopFrequency", false, 0), + argDouble(args, "threshold", false, 6.0), response, error); + + if (!enabled.isEmpty() && (status == 404)) + { + QJsonObject result; + result["rows"] = 0; + result["note"] = enabled + " Call again in a few seconds, once some has accumulated."; + return result; + } + + check(status, error, "Get spectrum history"); + QJsonObject json = toJson(response); + QJsonArray maxDb, meanDb, occupancy; + + for (float v : *response.getMaxDb()) { + maxDb.append(std::round((double) v * 10.0) / 10.0); + } + + for (float v : *response.getMeanDb()) { + meanDb.append(std::round((double) v * 10.0) / 10.0); + } + + for (float v : *response.getOccupancy()) { + occupancy.append(std::round((double) v * 100.0) / 100.0); + } + + json["maxDb"] = maxDb; + json["meanDb"] = meanDb; + json["occupancy"] = occupancy; + + if (!enabled.isEmpty()) { + json["note"] = enabled; + } + + return json; + }); + + add("get_waterfall_image", + "A picture of the spectrum history, the waterfall, as a greyscale image: frequency across, time down with the newest " + "row at the bottom, black a little below the noise floor and white at the strongest signal. Use it when the shape of " + "activity matters more than the numbers: a hopping signal, a drifting carrier, a burst pattern, or to see a whole band " + "at once. The reply's text gives the frequency and time extents so the picture can be read. get_spectrum_history " + "gives the same history as numbers. Scrolling is switched on if it is off, and then there is nothing to show until " + "some has accumulated.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"seconds", numProp("How far back to look, in seconds. Default 60")}, + {"width", bounded(intProp("Width in pixels, one per bin. Default 512"), 16, 2048)}, + {"height", bounded(intProp("At most this many rows, the most recent. Default 512"), 16, 2000)}, + {"startFrequency", numProp("Only from this frequency in Hz. Default the start of the spectrum")}, + {"stopFrequency", numProp("Only up to this frequency in Hz. Default the end of the spectrum")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + const int deviceSetIndex = argInt(args, "deviceSetIndex"); + const double seconds = argDouble(args, "seconds", false, 60.0); + const QString enabled = ensureSpectrumHistory(deviceSetIndex, seconds); + QByteArray png; + QJsonObject description; + SWGSDRangel::SWGErrorResponse error; + error.init(); + const int status = m_adapter->devicesetSpectrumHistoryImageGet(deviceSetIndex, seconds, + argInt(args, "width", false, 512), argInt64(args, "startFrequency", false, 0), argInt64(args, "stopFrequency", false, 0), + argInt(args, "height", false, 512), png, description, error); + + if (!enabled.isEmpty() && (status == 404)) + { + QJsonObject result; + result["note"] = enabled + " Call again in a few seconds, once some has accumulated."; + return result; + } + + check(status, error, "Get waterfall image"); + QJsonObject image; + image["data"] = QString(png.toBase64()); + image["mimeType"] = "image/png"; + description["_image"] = image; + description["note"] = QString("Frequency runs left to right from %1 to %2 MHz, time top to bottom from %3 to %4 with the newest row at the bottom; black is %5 dB and white %6 dB.%7") + .arg(description["startFrequency"].toDouble() / 1e6, 0, 'f', 4).arg(description["stopFrequency"].toDouble() / 1e6, 0, 'f', 4) + .arg(description["firstTime"].toString()).arg(description["lastTime"].toString()) + .arg(description["blackDb"].toDouble(), 0, 'f', 1).arg(description["whiteDb"].toDouble(), 0, 'f', 1) + .arg(enabled.isEmpty() ? QString() : " " + enabled); + return description; + }); + + add("spectrum_action", + "Act on the main spectrum of a device set. autoscale sets the reference level and range from what is on screen, " + "clearSpectrum discards the histogram and max hold traces, resetMeasurements starts the measurement statistics again, " + "freeze stops spectrum processing and unfreezing resumes it, and gotoMarker retunes to one of the annotations. " + "Everything except freeze acts on the display and so needs the GUI.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"autoscale", prop("boolean", "Set the reference level and range from the spectrum currently displayed")}, + {"clearSpectrum", prop("boolean", "Discard the accumulated histogram and max hold traces")}, + {"resetMeasurements", prop("boolean", "Discard the accumulated measurement statistics")}, + {"freeze", prop("boolean", "True to stop spectrum processing, false to resume it")}, + {"gotoMarker", intProp("Retune to the annotation at this index, counting from 0")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject actions; + + for (const QString& key : {QString("autoscale"), QString("clearSpectrum"), QString("resetMeasurements"), QString("freeze")}) + { + if (hasArg(args, key)) { + actions[key] = argBool(args, key, false) ? 1 : 0; + } + } + + if (hasArg(args, "gotoMarker")) { + actions["gotoMarker"] = argInt(args, "gotoMarker"); + } + + if (actions.isEmpty()) { + throw MCPToolError("Give at least one of autoscale, clearSpectrum, resetMeasurements, freeze or gotoMarker"); + } + + QStringList keys; + extractKeys(actions, keys); + + // fromJsonObject takes its argument by non-const reference and looks every field up + // with operator[], which inserts a null for each one that is absent, so what is echoed + // back is taken before the call rather than after it + QJsonObject applied = actions; + SWGSDRangel::SWGSpectrumActions query; + query.init(); + query.fromJsonObject(actions); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumActionsPost(deviceSetIndex, keys, query, error), error, "Spectrum action"); + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["applied"] = applied; + return result; + }); + + add("add_annotation", + "Add a labelled annotation to the main spectrum of a device set, for instance the name of the station a channel is tuned to. " + "Appends to the annotations already there instead of replacing them, and turns annotation display on if it is off. " + "Give centerFrequency, which is usually what you want as the bandwidth is then centred on it, or startFrequency.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"text", strProp("Label shown against the annotation, e.g. the RDS programme service name of a broadcast station")}, + {"centerFrequency", numProp("Centre frequency of the annotation in Hz. Give this or startFrequency")}, + {"startFrequency", numProp("Start frequency of the annotation in Hz. Give this or centerFrequency")}, + {"bandwidth", intProp("Width of the annotation in Hz. Default 0, which marks a single frequency")}, + {"color", intProp("Colour packed as blue*65536 + green*256 + red, each component 0 to 255. Default yellow")}, + {"show", bounded(intProp("0 hidden, 1 top marker only, 2 full with text and limits, 3 text only. Default 2"), 0, 3)} + }, {"deviceSetIndex", "text"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + int bandwidth = argInt(args, "bandwidth", false, 0); + + if (bandwidth < 0) { + throw MCPToolError("bandwidth cannot be negative"); + } + + qint64 startFrequency; + + if (hasArg(args, "startFrequency")) { + startFrequency = argInt64(args, "startFrequency"); + } else if (hasArg(args, "centerFrequency")) { + startFrequency = argInt64(args, "centerFrequency") - bandwidth / 2; + } else { + throw MCPToolError("Give either centerFrequency or startFrequency"); + } + + QJsonObject marker; + marker["startFrequency"] = startFrequency; + marker["bandwidth"] = bandwidth; + marker["markerColor"] = argInt(args, "color", false, 65535); // Yellow + marker["show"] = argInt(args, "show", false, 2); + marker["text"] = argString(args, "text"); + + QJsonObject current = getSpectrumSettings(deviceSetIndex); + + // Appended by the settings themselves rather than by reading the list, adding to it and + // writing it back, which would lose an annotation added by anything else in between + QJsonArray markers; + markers.append(marker); + + QJsonObject patch; + patch["annotationMarkers"] = markers; + patch["annotationMarkersMode"] = 1; + // Annotations are drawn only when their bit of markersDisplay is set, so an annotation + // added while it is clear would otherwise be invisible with nothing to say why + patch["markersDisplay"] = current.value("markersDisplay").toInt(0) | 0x2; + + QJsonObject after = patchSpectrumSettings(deviceSetIndex, patch); + QJsonObject result; + result["added"] = marker; + result["annotationMarkers"] = after.value("annotationMarkers").toArray(); + return result; + }); + + add("remove_annotation", + "Remove annotations from the main spectrum of a device set. Give text to remove the annotations carrying that label, " + "frequency to remove those whose span covers it, or all to remove every annotation. Returns what was removed and what is left.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"text", strProp("Remove annotations whose label is exactly this")}, + {"frequency", numProp("Remove annotations whose span covers this frequency in Hz")}, + {"all", prop("boolean", "Remove every annotation. Default false")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + bool all = argBool(args, "all", false); + bool byText = hasArg(args, "text"); + bool byFrequency = hasArg(args, "frequency"); + + // Without a criterion the intent is ambiguous, and either reading of it, removing + // nothing or removing everything, would be wrong often enough to be worth refusing + if (!all && !byText && !byFrequency) { + throw MCPToolError("Give text, frequency or all to say which annotations to remove"); + } + + QString text = argString(args, "text", false); + qint64 frequency = argInt64(args, "frequency", false); + QJsonArray markers = getSpectrumSettings(deviceSetIndex).value("annotationMarkers").toArray(); + QJsonArray kept; + QJsonArray removed; + + for (const QJsonValue& value : markers) + { + QJsonObject marker = value.toObject(); + qint64 start = (qint64) marker.value("startFrequency").toDouble(); + qint64 stop = start + (qint64) marker.value("bandwidth").toDouble(); + bool matches = all + || (byText && (marker.value("text").toString() == text)) + || (byFrequency && (frequency >= start) && (frequency <= stop)); + + if (matches) { + removed.append(marker); + } else { + kept.append(marker); + } + } + + QJsonObject result; + result["removed"] = removed; + + if (removed.isEmpty()) + { + result["annotationMarkers"] = markers; + result["warning"] = "No annotation matched, so nothing was removed"; + return result; + } + + QJsonObject patch; + patch["annotationMarkers"] = kept; + QJsonObject after = patchSpectrumSettings(deviceSetIndex, patch); + result["annotationMarkers"] = after.value("annotationMarkers").toArray(); + return result; + }); +} + +void MCPTools::registerChannelTools() +{ + add("add_channel", + "Add a channel (demodulator or modulator) to a device set and optionally apply initial settings. Returns the index of the new channel. " + "channelType is an id from list_channel_types, e.g. ADSBDemod, NFMDemod, AMDemod, BFMDemod, SSBDemod, AISDemod, PacketDemod, FileSink.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelType", strProp("Channel type id from list_channel_types")}, + {"settings", objProp("Optional initial settings for the channel, e.g. {\"inputFrequencyOffset\": 0}. Use describe_settings for the keys")} + }, {"deviceSetIndex", "channelType"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QString channelType = argString(args, "channelType"); + int channelIndex = addChannelAndWait(deviceSetIndex, channelType); + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["channelIndex"] = channelIndex; + QString warning = basebandWarning(deviceSetIndex, channelType); + + if (!warning.isEmpty()) { + result["warning"] = warning; + } + QJsonObject settings = argObject(args, "settings", false); + + if (!settings.isEmpty()) + { + QJsonObject patched; + + try + { + patched = patchChannelSettings(deviceSetIndex, channelIndex, settings); + } + catch (const MCPToolError& e) + { + // The channel exists even though its settings were refused. Say so and give + // its index, otherwise a retry would leave a second one behind. + throw MCPToolError(QString("The %1 channel was created as channel %2 of device set %3, but its initial " + "settings were refused, so it is left with defaults: %4. Use set_channel_settings to correct it, " + "or delete_channel to remove it. Do not call add_channel again.") + .arg(channelType).arg(channelIndex).arg(deviceSetIndex).arg(e.message)); + } + + result["changed"] = patched["changed"]; + + if (patched.contains("warning")) { + result["warning"] = patched["warning"]; + } + } + + return result; + }); + + add("delete_channel", + "Remove a channel from a device set. Channels with a higher index are renumbered down by one.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp} + }, {"deviceSetIndex", "channelIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + + // Waits for the channel itself to disappear. Waiting for the removed signal would + // sit out the whole timeout for the last channel of a device set, which the device + // set drops from its list before MainCore can look it up to signal it. + deleteChannelAndWait(deviceSetIndex, argInt(args, "channelIndex")); + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["channelCount"] = channelCount(deviceSetIndex); + return result; + }); + + add("get_channel_settings", + "Get the settings of a channel. The keys depend on the channel type. inputFrequencyOffset is the channel frequency relative to the device centre frequency in Hz.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp} + }, {"deviceSetIndex", "channelIndex"}), + [this](const QJsonObject& args) { return getChannelSettings(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex")); }); + + add("set_channel_settings", + "Change some settings of a channel. Give only the keys to change, e.g. {\"inputFrequencyOffset\": 25000, \"squelch\": -40}. " + "Use describe_settings with the channel type to learn the valid keys. Returns the keys changed with their applied values.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp}, + {"settings", objProp("Object with the settings keys to change and their new values")} + }, {"deviceSetIndex", "channelIndex", "settings"}), + [this](const QJsonObject& args) + { + return patchChannelSettings(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex"), argObject(args, "settings")); + }); + + add("get_channel_report", + "Get the live report of a channel: signal level, squelch state, decoder statistics and so on, depending on the channel type. " + "Omit channelIndex for the reports of every channel of the device set. " + "For DAB, wait briefly after selecting a programme or changing receiver gain and then read the report again. Do not accept " + "sync or audioActive alone as proof of clean reception: if synchronized audio has SNR at or below 0 dB, RTL-SDR overload " + "is likely, so reduce gain through its supported values and keep the setting that gives the best positive SNR.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", intProp("Index of the channel within the device set; omit for all channels")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + SWGSDRangel::SWGErrorResponse error; + error.init(); + + if (hasArg(args, "channelIndex")) + { + int channelIndex = argInt(args, "channelIndex"); + SWGSDRangel::SWGChannelReport response; + check(m_adapter->devicesetChannelReportGet(deviceSetIndex, channelIndex, response, error), error, "Get channel report"); + QJsonObject report = toJson(response); + addRdsHint(report, report.value("channelType").toString(), deviceSetIndex, channelIndex); + return report; + } + + SWGSDRangel::SWGChannelsDetail response; + check(m_adapter->devicesetChannelsReportGet(deviceSetIndex, response, error), error, "Get channels report"); + QJsonObject json = toJson(response); + QJsonArray channels = json.value("channels").toArray(); + + for (int i = 0; i < channels.size(); i++) + { + QJsonObject channel = channels.at(i).toObject(); + QJsonObject report = channel.value("report").toObject(); + // The channel type is on the entry here rather than on the report it carries + addRdsHint(report, channel.value("id").toString(), deviceSetIndex, channel.value("index").toInt()); + channel["report"] = report; + channels[i] = channel; + } + + json["channels"] = channels; + return json; + }); + + add("channel_action", + "Trigger an action on a channel. Only some channel types have actions. Use describe_settings to find the actions keys of the " + "channel type; pass them as the actions object.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp}, + {"actions", objProp("Object with the action keys and values for this channel type")} + }, {"deviceSetIndex", "channelIndex", "actions"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + int channelIndex = argInt(args, "channelIndex"); + QJsonObject actions = argObject(args, "actions"); + QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex); + QString channelType = settings["channelType"].toString(); + + if (!WebAPIUtils::m_channelTypeToActionsKey.contains(channelType)) { + throw MCPToolError(QString("Channel type %1 has no actions").arg(channelType)); + } + + QString actionsKey = WebAPIUtils::m_channelTypeToActionsKey[channelType]; + QJsonObject json; + json["channelType"] = channelType; + json["direction"] = settings["direction"].toInt(0); + json[actionsKey] = actions.contains(actionsKey) ? actions[actionsKey].toObject() : actions; + QStringList keys; + extractKeys(json[actionsKey].toObject(), keys); + + SWGSDRangel::SWGChannelActions query; + query.init(); + query.fromJsonObject(json); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelActionsPost(deviceSetIndex, channelIndex, keys, query, response, error), error, "Channel action"); + return toJson(response); + }); +} + +void MCPTools::registerFeatureTools() +{ + add("add_feature", + "Add a feature (device independent plugin such as Map, AIS, APRS, SatelliteTracker) and optionally apply initial settings. " + "Returns the index of the new feature. featureType is an id from list_feature_types.", + schema({ + {"featureType", strProp("Feature type id from list_feature_types")}, + {"settings", objProp("Optional initial settings for the feature. Use describe_settings for the keys")} + }, {"featureType"}), + [this](const QJsonObject& args) + { + QString featureType = argString(args, "featureType"); + int featureIndex = addFeatureAndWait(featureType); + QJsonObject result; + result["featureIndex"] = featureIndex; + QJsonObject settings = argObject(args, "settings", false); + + if (!settings.isEmpty()) + { + QJsonObject patched; + + try + { + patched = patchFeatureSettings(featureIndex, settings); + } + catch (const MCPToolError& e) + { + throw MCPToolError(QString("The %1 feature was created as feature %2, but its initial settings were " + "refused, so it is left with defaults: %3. Use set_feature_settings to correct it, or " + "delete_feature to remove it. Do not call add_feature again.") + .arg(featureType).arg(featureIndex).arg(e.message)); + } + + result["changed"] = patched["changed"]; + + if (patched.contains("warning")) { + result["warning"] = patched["warning"]; + } + } + + return result; + }); + + add("delete_feature", + "Remove a feature. Features with a higher index are renumbered down by one.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) + { + int featureIndex = argInt(args, "featureIndex"); + QMutexLocker deletionLock(&m_deletionMutex); + requireNotSelf(featureIndex, "deleted"); + const uint64_t target = featureUidAt(featureIndex); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureDelete(0, featureIndex, response, error), error, "Delete feature"); + + // FeatureSet drops the feature from its own list before MainCore looks it up, so + // removing the last feature emits no featureRemoved. Watch the feature itself go. + if (!waitFor([&]() { return !featureUids().contains(target); })) { + throw MCPToolError(QString("Timed out waiting for feature %1 to be removed").arg(featureIndex)); + } + + QJsonObject result; + result["featureCount"] = featureCount(); + return result; + }); + + add("get_feature_settings", + "Get the settings of a feature. The keys depend on the feature type.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) { return getFeatureSettings(argInt(args, "featureIndex")); }); + + add("set_feature_settings", + "Change some settings of a feature. Give only the keys to change. Use describe_settings with the feature type to learn the valid keys.", + schema({ + {"featureIndex", featureIndexProp}, + {"settings", objProp("Object with the settings keys to change and their new values")} + }, {"featureIndex", "settings"}), + [this](const QJsonObject& args) { return patchFeatureSettings(argInt(args, "featureIndex"), argObject(args, "settings")); }); + + add("get_feature_report", + "Get the live report of a feature, depending on the feature type.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGFeatureReport response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureReportGet(0, argInt(args, "featureIndex"), response, error), error, "Get feature report"); + return toJson(response); + }); + + add("start_feature", + "Start a feature. Most features must be started to do anything, but the passive ones - AIS, AMBE, AntennaTools, " + "APRS, FreqDisplay, LimeRFE, Map, Radiosonde, RemoteControl and SkyMap - have no run state, work as soon as they " + "are configured and always report idle. Starting one of those is answered without doing anything.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) { return featureState(argInt(args, "featureIndex"), 1); }); + + add("stop_feature", + "Stop a feature.", + schema({{"featureIndex", featureIndexProp}}, {"featureIndex"}), + [this](const QJsonObject& args) + { + int featureIndex = argInt(args, "featureIndex"); + requireNotSelf(featureIndex, "stopped"); + return featureState(featureIndex, 0); + }); + + add("feature_action", + "Trigger an action on a feature. Use describe_settings to find the actions keys of the feature type; pass them as the actions object.", + schema({ + {"featureIndex", featureIndexProp}, + {"actions", objProp("Object with the action keys and values for this feature type")} + }, {"featureIndex", "actions"}), + [this](const QJsonObject& args) + { + int featureIndex = argInt(args, "featureIndex"); + QJsonObject actions = argObject(args, "actions"); + QJsonObject settings = getFeatureSettings(featureIndex); + QString featureType = settings["featureType"].toString(); + + if (!WebAPIUtils::m_featureTypeToActionsKey.contains(featureType)) { + throw MCPToolError(QString("Feature type %1 has no actions").arg(featureType)); + } + + QString actionsKey = WebAPIUtils::m_featureTypeToActionsKey[featureType]; + QJsonObject json; + json["featureType"] = featureType; + json[actionsKey] = actions.contains(actionsKey) ? actions[actionsKey].toObject() : actions; + QStringList keys; + extractKeys(json[actionsKey].toObject(), keys); + + SWGSDRangel::SWGFeatureActions query; + query.init(); + query.fromJsonObject(json); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureActionsPost(0, featureIndex, keys, query, response, error), error, "Feature action"); + return toJson(response); + }); +} + +void MCPTools::registerPresetTools() +{ + add("list_presets", + "List the saved device set presets. A preset stores a device set's device and channel settings and is identified by group name, " + "name, centre frequency and type (R for rx, T for tx, M for MIMO).", + schema(QJsonObject()), + [this](const QJsonObject&) { return getPresets(); }); + + add("load_preset", + "Load a preset into a device set, replacing its device settings and channels. The preset type must match the device set direction.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"groupName", strProp("Preset group name")}, + {"name", strProp("Preset name")}, + {"centerFrequency", numProp("Preset centre frequency in Hz. Only needed when several presets share the group and name")}, + {"type", strProp("Preset type R, T or M. Only needed when several presets share the group and name")} + }, {"deviceSetIndex", "groupName", "name"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject identifier = presetIdentifier(args, deviceSetIndex, false); + SWGSDRangel::SWGPresetTransfer query; + query.setDeviceSetIndex(deviceSetIndex); + SWGSDRangel::SWGPresetIdentifier *preset = new SWGSDRangel::SWGPresetIdentifier(); + preset->setGroupName(new QString(identifier["groupName"].toString())); + preset->setName(new QString(identifier["name"].toString())); + preset->setType(new QString(identifier["type"].toString())); + preset->setCenterFrequency((qint64) identifier["centerFrequency"].toDouble()); + query.setPreset(preset); + SWGSDRangel::SWGPresetIdentifier response; + response.init(); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instancePresetPatch(query, response, error), error, "Load preset"); + pause(500); // Loading replaces the channels; give it a moment before the caller looks + QJsonObject result; + result["loaded"] = toJson(response); + result["deviceSet"] = getDeviceSet(deviceSetIndex); + return result; + }); + + add("save_preset", + "Save the current device settings and channels of a device set as a preset. Updates the preset if one with the same group, name, " + "centre frequency and type exists, otherwise creates it.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"groupName", strProp("Preset group name")}, + {"name", strProp("Preset name")} + }, {"deviceSetIndex", "groupName", "name"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject identifier = presetIdentifier(args, deviceSetIndex, true); + SWGSDRangel::SWGPresetTransfer query; + query.setDeviceSetIndex(deviceSetIndex); + SWGSDRangel::SWGPresetIdentifier *preset = new SWGSDRangel::SWGPresetIdentifier(); + preset->setGroupName(new QString(identifier["groupName"].toString())); + preset->setName(new QString(identifier["name"].toString())); + preset->setType(new QString(identifier["type"].toString())); + preset->setCenterFrequency((qint64) identifier["centerFrequency"].toDouble()); + query.setPreset(preset); + SWGSDRangel::SWGPresetIdentifier response; + response.init(); + SWGSDRangel::SWGErrorResponse error; + error.init(); + bool exists = identifier["exists"].toBool(); + + if (exists) { + check(m_adapter->instancePresetPut(query, response, error), error, "Update preset"); + } else { + check(m_adapter->instancePresetPost(query, response, error), error, "Create preset"); + } + + QJsonObject result; + result["preset"] = toJson(response); + result["created"] = !exists; + return result; + }); + + add("list_configurations", + "List the saved configurations. A configuration stores the whole instance: all device sets, features and workspaces.", + schema(QJsonObject()), + [this](const QJsonObject&) { return getConfigurations(); }); + + add("load_configuration", + "Load a saved configuration, replacing all current device sets and features.", + schema({ + {"groupName", strProp("Configuration group name")}, + {"name", strProp("Configuration name")} + }, {"groupName", "name"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGConfigurationIdentifier response; + response.setGroupName(new QString(argString(args, "groupName"))); + response.setName(new QString(argString(args, "name"))); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceConfigurationPatch(response, error), error, "Load configuration"); + pause(1000); // Loading rebuilds everything + QJsonObject result; + result["configuration"] = toJson(response); + result["instance"] = getInstanceSummary(); + return result; + }); + + add("save_configuration", + "Save the whole current instance as a configuration. Updates the configuration if one with the same group and name exists, otherwise creates it.", + schema({ + {"groupName", strProp("Configuration group name")}, + {"name", strProp("Configuration name")} + }, {"groupName", "name"}), + [this](const QJsonObject& args) + { + QString groupName = argString(args, "groupName"); + QString name = argString(args, "name"); + bool exists = false; + + for (const auto& groupValue : getConfigurations()["groups"].toArray()) + { + QJsonObject group = groupValue.toObject(); + + if (group["groupName"].toString() != groupName) { + continue; + } + + for (const auto& item : group["configurations"].toArray()) + { + if (item.toObject()["name"].toString() == name) { + exists = true; + } + } + } + + SWGSDRangel::SWGConfigurationIdentifier response; + response.setGroupName(new QString(groupName)); + response.setName(new QString(name)); + SWGSDRangel::SWGErrorResponse error; + error.init(); + + if (exists) { + check(m_adapter->instanceConfigurationPut(response, error), error, "Update configuration"); + } else { + check(m_adapter->instanceConfigurationPost(response, error), error, "Create configuration"); + } + + QJsonObject result; + result["configuration"] = toJson(response); + result["created"] = !exists; + return result; + }); +} + +void MCPTools::registerWorkspaceTools() +{ + add("add_workspace", + "GUI only: add a new workspace (a tabbed area holding device, channel and feature windows). Workspaces are numbered from 0.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceWorkspacePost(response, error), error, "Add workspace"); + return toJson(response); + }); + + add("delete_empty_workspaces", + "GUI only: remove all workspaces that contain no windows.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceWorkspaceDelete(response, error), error, "Delete empty workspaces"); + return toJson(response); + }); + + add("arrange_workspace", + "GUI only: arrange the windows of a workspace, as its title bar buttons do. cascade, tile, stackVertical and stack " + "rearrange them once and turn auto stacking and tabs off; autostack stacks them now and again whenever a window is " + "added or resized, until another arrangement is asked for; tab shows one window at a time with a tab for each. " + "stack is the usual choice: devices, spectra and channels in columns.", + schema({ + {"workspaceIndex", intProp("Index of the workspace, from 0")}, + {"arrange", enumProp("cascade, tile, stackVertical, stack, autostack or tab", {"cascade", "tile", "stackVertical", "stack", "autostack", "tab"})} + }, {"workspaceIndex", "arrange"}), + [this](const QJsonObject& args) + { + SWGSDRangel::SWGWorkspaceActions query; + query.init(); + query.setArrange(new QString(argString(args, "arrange"))); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->workspaceActionsPost(argInt(args, "workspaceIndex"), query, response, error), error, "Arrange workspace"); + return toJson(response); + }); + + add("list_windows", + "GUI only: every window, with its kind (device, spectrum, channel or feature), indices, title, workspace and whether it " + "is hidden. A hidden window is still running; set_workspace with hidden false shows it again.", + schema({}), + [this](const QJsonObject&) + { + SWGSDRangel::SWGWindowList response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceWindowsGet(response, error), error, "List windows"); + return toJson(response); + }); + + add("set_workspace", + "GUI only: move a window to a workspace, hide it, or show it again. kind is device, spectrum or channel (with " + "deviceSetIndex, plus channelIndex for a channel) or feature (with featureIndex). Give workspaceIndex to move, hidden " + "to hide (true) or show (false), or both. Showing a window raises it and shows the workspace holding it. Hiding a " + "window does not stop it: a hidden demodulator still plays audio. list_windows shows what is hidden.", + schema({ + {"kind", strProp("device, spectrum, channel or feature")}, + {"workspaceIndex", intProp("Workspace to move the window to. Optional")}, + {"hidden", prop("boolean", "true hides the window, false shows it. Optional")}, + {"deviceSetIndex", intProp("For device, spectrum and channel")}, + {"channelIndex", intProp("For channel")}, + {"featureIndex", intProp("For feature")} + }, {"kind"}), + [this](const QJsonObject& args) + { + QString kind = argString(args, "kind").trimmed().toLower(); + + if (!hasArg(args, "workspaceIndex") && !hasArg(args, "hidden")) { + throw MCPToolError("Give workspaceIndex to move the window, hidden to hide or show it, or both"); + } + + // -1 for what was not asked for, as the Web API's own validator passes it + SWGSDRangel::SWGWorkspaceInfo query; + query.setIndex(hasArg(args, "workspaceIndex") ? argInt(args, "workspaceIndex") : -1); + query.setHidden(hasArg(args, "hidden") ? (argBool(args, "hidden", false) ? 1 : 0) : -1); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + + if (kind == "device") { + check(m_adapter->devicesetDeviceWorkspacePut(argInt(args, "deviceSetIndex"), query, response, error), error, "Set device workspace"); + } else if (kind == "spectrum") { + check(m_adapter->devicesetSpectrumWorkspacePut(argInt(args, "deviceSetIndex"), query, response, error), error, "Set spectrum workspace"); + } else if (kind == "channel") { + check(m_adapter->devicesetChannelWorkspacePut(argInt(args, "deviceSetIndex"), argInt(args, "channelIndex"), query, response, error), error, "Set channel workspace"); + } else if (kind == "feature") { + check(m_adapter->featuresetFeatureWorkspacePut(argInt(args, "featureIndex"), query, response, error), error, "Set feature workspace"); + } else { + throw MCPToolError("kind must be device, spectrum, channel or feature"); + } + + return toJson(response); + }); +} + +void MCPTools::registerCaptureTools() +{ + + add("get_server_status", + "This server's own state, in one call: the capture directory and any recordings running; which channels and features " + "feed packets and map items and how much has arrived; and the client event streams (open streams, subscriptions, " + "notifications sent). Open a stream with an HTTP GET on the MCP endpoint with Accept: text/event-stream, then " + "resources/subscribe.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + QJsonObject result; + result["capture"] = m_capture.status(); + result["dataFeed"] = m_dataFeed.getStatus(); + result["streams"] = m_streams ? m_streams->status() : QJsonObject(); + return result; + }); + + add("capture_audio", + QString("Record the demodulated audio of a channel to a WAV file and report where it went, how loud it was and whether it " + "was silent. Works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod, " + "BFMDemod, DSDDemod and M17Demod. The device must be running. This call blocks for the duration, so it is limited " + "to %1 seconds. Set inline to true (up to %2 seconds) to also get the audio back as base64 for playing directly: " + "a mono 16 kHz copy, small enough for a tool result, while the file keeps the full rate.") + .arg(MCPCapture::m_maxBlockingSeconds).arg(MCPCapture::m_maxInlineSeconds), + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", channelIndexProp}, + {"seconds", bounded(numProp(QString("How long to record for, up to %1").arg(MCPCapture::m_maxBlockingSeconds)), 0.1, MCPCapture::m_maxBlockingSeconds)}, + {"fileName", strProp("File name relative to the capture directory. The .wav extension is added. Default: audio_")}, + {"inline", prop("boolean", QString("Also return the audio as base64 in audioBase64, as a mono 16 kHz WAV. Only for clips of %1 seconds or less. Default false").arg(MCPCapture::m_maxInlineSeconds))} + }, {"deviceSetIndex", "channelIndex", "seconds"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + int channelIndex = argInt(args, "channelIndex"); + double seconds = argDouble(args, "seconds"); + bool inlineAudio = argBool(args, "inline", false); + + if ((seconds <= 0) || (seconds > MCPCapture::m_maxBlockingSeconds)) { + throw MCPToolError(QString("seconds must be between 0 and %1").arg(MCPCapture::m_maxBlockingSeconds)); + } + + if (inlineAudio && (seconds > MCPCapture::m_maxInlineSeconds)) { + throw MCPToolError(QString("inline audio is only available for %1 seconds or less").arg(MCPCapture::m_maxInlineSeconds)); + } + + QJsonObject state = deviceState(deviceSetIndex, 0, -1); + + if (state["state"].toString() != "running") { + throw MCPToolError("The device is not running, so there is no audio to record. Call start_device first."); + } + + return m_capture.captureAudio(deviceSetIndex, channelIndex, seconds, + argString(args, "fileName", false), inlineAudio); + }); + + add("start_iq_recording", + "Start recording baseband IQ samples to a file. Adds a FileSink channel to the device set unless channelIndex names an " + "existing one, and starts it recording. The device must be running for samples to be written. Recording continues until " + "stop_iq_recording, so use this for long captures and record_iq for short ones. Files are written under the capture " + "directory shown by get_server_status; fileName is relative to it.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"fileName", strProp("File name relative to the capture directory. A timestamp and the .sdriq extension are added. Default: iq_")}, + {"frequencyOffset", intProp("Channel frequency offset from the device centre frequency in Hz. Default 0, which records the full baseband centred on the device frequency")}, + {"log2Decim", bounded(intProp("Decimation as a power of two: 0 records at the device sample rate, 1 halves it, and so on. Default 0"), 0, 6)}, + {"channelIndex", intProp("Use this existing FileSink channel instead of adding one")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + bool created = !hasArg(args, "channelIndex"); + + // A bad file name is refused before a channel is added for it + m_capture.checkFileName(argString(args, "fileName", false), "iq"); + + int channelIndex = created ? addChannelAndWait(deviceSetIndex, "FileSink") : argInt(args, "channelIndex"); + const uint64_t channel = created ? channelUidAt(deviceSetIndex, channelIndex) : 0; + + try + { + QJsonObject result = m_capture.startIQRecording(deviceSetIndex, channelIndex, + argString(args, "fileName", false), argInt(args, "frequencyOffset", false, 0), + argInt(args, "log2Decim", false, 0)); + result["channelCreated"] = created; + QJsonObject state = deviceState(deviceSetIndex, 0, -1); + + if (state["state"].toString() != "running") { + result["warning"] = "The device is not running, so no samples will be recorded. Call start_device."; + } + + return result; + } + catch (const MCPToolError&) + { + // Do not leave a channel behind when the recording could not be set up. By + // identity: a concurrent listen or scan may have renumbered it meanwhile + if (created) { + try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} + } + + throw; + } + }); + + add("stop_iq_recording", + "Stop an IQ recording started with start_iq_recording and report the files written, with their size and duration.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"channelIndex", intProp("Index of the FileSink channel that is recording")}, + {"deleteChannel", prop("boolean", "Delete the FileSink channel afterwards. Default false")} + }, {"deviceSetIndex", "channelIndex"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + int channelIndex = argInt(args, "channelIndex"); + const uint64_t channel = channelUidAt(deviceSetIndex, channelIndex); + QJsonObject result = m_capture.stopIQRecording(deviceSetIndex, channelIndex); + bool deleteChannel = argBool(args, "deleteChannel", false); + + if (deleteChannel) + { + deleteChannelObjectAndWait(channel); + result["channelDeleted"] = true; + } + + return result; + }); + + add("record_iq", + QString("Record baseband IQ samples for a fixed number of seconds and return the files written. Adds a FileSink channel, " + "records, stops and removes the channel again. This call blocks for the duration, so it is limited to %1 seconds; " + "for longer captures use start_iq_recording and stop_iq_recording. The device must already be running. " + "Note that IQ files are large: roughly 4 bytes per sample per second of the device sample rate.") + .arg(MCPCapture::m_maxBlockingSeconds), + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"seconds", bounded(numProp(QString("How long to record for, up to %1").arg(MCPCapture::m_maxBlockingSeconds)), 0.1, MCPCapture::m_maxBlockingSeconds)}, + {"fileName", strProp("File name relative to the capture directory. A timestamp and the .sdriq extension are added")}, + {"frequencyOffset", intProp("Channel frequency offset from the device centre frequency in Hz. Default 0")}, + {"log2Decim", bounded(intProp("Decimation as a power of two. Default 0"), 0, 6)} + }, {"deviceSetIndex", "seconds"}), + [this](const QJsonObject& args) + { + int deviceSetIndex = argInt(args, "deviceSetIndex"); + double seconds = argDouble(args, "seconds"); + + if ((seconds <= 0) || (seconds > MCPCapture::m_maxBlockingSeconds)) + { + throw MCPToolError(QString("seconds must be between 0 and %1. For a longer capture use start_iq_recording and stop_iq_recording") + .arg(MCPCapture::m_maxBlockingSeconds)); + } + + QJsonObject state = deviceState(deviceSetIndex, 0, -1); + + if (state["state"].toString() != "running") { + throw MCPToolError("The device is not running, so there is nothing to record. Call start_device first."); + } + + // A bad file name is refused before a channel is added for it + m_capture.checkFileName(argString(args, "fileName", false), "iq"); + + int channelIndex = addChannelAndWait(deviceSetIndex, "FileSink"); + + // This call sleeps for up to half a minute and is not serialised against the other + // tools, so another request can delete a channel and renumber this one meanwhile. + // Everything after the sleep therefore works from the channel's UID, not its index. + const uint64_t channel = channelUidAt(deviceSetIndex, channelIndex); + + if (channel == 0) // cannot happen, but do not leave the channel behind if it does + { + try { deleteChannelAndWait(deviceSetIndex, channelIndex); } catch (const MCPToolError&) {} + + throw MCPToolError("The FileSink channel went away as soon as it was added"); + } + + QJsonObject result; + + try + { + QJsonObject started = m_capture.startIQRecording(deviceSetIndex, channelIndex, + argString(args, "fileName", false), argInt(args, "frequencyOffset", false, 0), + argInt(args, "log2Decim", false, 0)); + pause((int) (seconds * 1000.0)); + result = m_capture.stopIQRecording(channel); + result["fileBase"] = started["fileBase"]; + result["requestedSeconds"] = seconds; + } + catch (const MCPToolError&) + { + try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} + throw; + } + + deleteChannelObjectAndWait(channel); + + if (result["files"].toArray().isEmpty()) { + result["warning"] = "No files were written. Check that the device is running and producing samples."; + } + + return result; + }); +} + +// --------------------------------------------------------------------------- +// Intent level tools: a whole task in one call +// +// Setting up a receiver with the object level tools takes an agent around ten round trips, +// each one a model turn. These do the common tasks in one, using the same helpers, and reply +// with a short summary rather than the objects they created. +// --------------------------------------------------------------------------- + +namespace { + +// What "listen to X in mode Y" needs: the demodulator, its initial settings and the smallest +// baseband that carries it. Values are the ones the receiving guide and readmes give. +struct ListenMode +{ + const char *m_alias; + const char *m_channelType; + int m_rfBandwidth; //!< Hz. Negative selects the lower sideband, as the SSB demodulator does + int m_minBaseband; //!< Hz + const char *m_settings; //!< JSON of further initial settings + int m_scanStep; //!< Hz. The channel spacing scan steps by unless told otherwise; 0 for a mode on fixed frequencies, which is not scanned for + const char *m_feature; //!< A feature the mode's output goes to, added if absent; null for none + int m_pairOffset; //!< Hz. Non-zero for a mode on two channels this far either side of the frequency, one demodulator each +}; + +const char *const bfmSettings = "{\"afBandwidth\":15000,\"audioStereo\":1,\"rdsActive\":1,\"volume\":4,\"squelch\":-60}"; +const char *const amSettings = "{\"afBandwidth\":3000,\"bandpassEnable\":1,\"volume\":4,\"squelch\":-60}"; + +const ListenMode listenModes[] = { + // Broadcast FM asks for twice the baseband its channel needs: a 180 kHz channel in a 256 kS/s + // baseband sits against the edge of the decimation filters, and RDS suffers first; it also + // leaves room to put the channel clear of the device's DC spike + {"bfm", "BFMDemod", 180000, 512000, bfmSettings, 100000, nullptr, 0}, + {"fm", "BFMDemod", 180000, 512000, bfmSettings, 100000, nullptr, 0}, + {"wfm", "WFMDemod", 150000, 512000, "{\"volume\":2,\"squelch\":-60}", 100000, nullptr, 0}, + {"nfm", "NFMDemod", 12500, 48000, "{\"afBandwidth\":3000,\"volume\":2}", 12500, nullptr, 0}, + {"am", "AMDemod", 8000, 48000, amSettings, 25000, nullptr, 0}, + {"airband", "AMDemod", 8000, 48000, amSettings, 25000, nullptr, 0}, + {"ssb", "SSBDemod", 3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, + {"usb", "SSBDemod", 3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, + {"lsb", "SSBDemod", -3000, 48000, "{\"volume\":2}", 3000, nullptr, 0}, + {"dab", "DABDemod", 0, 2048000, "{}", 0, nullptr, 0}, + {"adsb", "ADSBDemod", 0, 2400000, "{}", 0, nullptr, 0}, + {"ais", "AISDemod", 0, 128000, "{}", 0, "AIS", 25000}, + {"dsc", "DSCDemod", 450, 48000, "{}", 0, nullptr, 0}, + // Digital voice: the DSD demodulator decides the standard from the baud rate, and its + // discriminator wants the maximum deviation of the standard, the readme's table: DMR 5.4, + // dPMR 2.7, D-Star 3.5, YSF 7.0, NXDN 2.7 kHz. dsd alone is the plugin's defaults, which + // are D-Star's, set explicitly so that a retuned demodulator gets them too. DMR carries + // two time slots, so both are switched on + {"dsd", "DSDDemod", 12500, 48000, "{\"fmDeviation\":3500,\"baudRate\":4800}", 12500, nullptr, 0}, + {"dmr", "DSDDemod", 12500, 48000, "{\"fmDeviation\":5400,\"baudRate\":4800,\"slot1On\":1,\"slot2On\":1}", 12500, nullptr, 0}, + {"dpmr", "DSDDemod", 6250, 48000, "{\"fmDeviation\":2700,\"baudRate\":2400}", 6250, nullptr, 0}, + {"dstar", "DSDDemod", 12500, 48000, "{\"fmDeviation\":3500,\"baudRate\":4800}", 12500, nullptr, 0}, + {"ysf", "DSDDemod", 12500, 48000, "{\"fmDeviation\":7000,\"baudRate\":4800}", 12500, nullptr, 0}, + {"nxdn", "DSDDemod", 12500, 48000, "{\"fmDeviation\":2700,\"baudRate\":4800}", 12500, nullptr, 0}, + {"nxdn24", "DSDDemod", 6250, 48000, "{\"fmDeviation\":2700,\"baudRate\":2400}", 6250, nullptr, 0}, + {"pager", "PagerDemod", 20000, 48000, "{}", 12500, nullptr, 0}, + {"pocsag", "PagerDemod", 20000, 48000, "{}", 12500, nullptr, 0}, + {"sonde", "RadiosondeDemod", 9600, 48000, "{}", 10000, "Radiosonde", 0}, + {"radiosonde", "RadiosondeDemod", 9600, 48000, "{}", 10000, "Radiosonde", 0}, + // AX.25 packet at 1200 baud AFSK. APRS is the same signal on a fixed regional frequency, + // with the APRS feature to plot the stations + {"packet", "PacketDemod", 12500, 48000, "{}", 0, nullptr, 0}, + {"aprs", "PacketDemod", 12500, 48000, "{}", 0, "APRS", 0}, +}; + +const char *const listenModeList = "bfm, wfm, nfm, am, ssb, usb, lsb, dab, adsb, ais, dsc, dsd, dmr, dpmr, dstar, ysf, nxdn, pager, sonde, packet, aprs"; + +// The feature a demodulator of this type feeds, by the modes that add one; null for none +const char *featureForChannelType(const QString& channelType) +{ + for (const ListenMode& mode : listenModes) + { + if (mode.m_feature && (channelType == QLatin1String(mode.m_channelType))) { + return mode.m_feature; + } + } + + return nullptr; +} + +// What listen and scan say about the features a reclaim took away +QStringList featureNotes(const QStringList& reclaimedFeatures) +{ + if (reclaimedFeatures.isEmpty()) { + return QStringList(); + } + + return QStringList(QString("Removed the %1 feature%2 an earlier listen added, as nothing feeds %3 now.") + .arg(reclaimedFeatures.join(" and ")).arg(reclaimedFeatures.size() == 1 ? "" : "s") + .arg(reclaimedFeatures.size() == 1 ? "it" : "them")); +} + +const ListenMode *findListenMode(const QString& alias) +{ + for (const ListenMode& mode : listenModes) + { + if (alias.compare(QLatin1String(mode.m_alias), Qt::CaseInsensitive) == 0) { + return &mode; + } + } + + return nullptr; +} + +// The device rate and decimation that give at least the wanted baseband. These are the rates +// an RTL-SDR runs reliably; DAB needs exactly 2.048 MS/s. +void rateFor(int minBaseband, int& devSampleRate, int& log2Decim) +{ + if (minBaseband <= 256000) { devSampleRate = 1024000; log2Decim = 2; } + else if (minBaseband <= 512000) { devSampleRate = 1024000; log2Decim = 1; } + else if (minBaseband <= 1024000) { devSampleRate = 1024000; log2Decim = 0; } + else if (minBaseband <= 2048000) { devSampleRate = 2048000; log2Decim = 0; } + else { devSampleRate = 2400000; log2Decim = 0; } +} + +// The baseband a channel type needs, from the table listen uses, so that there is one set of +// numbers rather than two that can disagree. 0 when the type is not in it. +int minimumBasebandFor(const QString& channelType) +{ + for (const ListenMode& mode : listenModes) + { + if (channelType.compare(QLatin1String(mode.m_channelType), Qt::CaseInsensitive) == 0) { + return mode.m_minBaseband; + } + } + + return 0; +} + +// Devices that are not radios attached to this machine, skipped when choosing one automatically +const QStringList virtualDeviceTypes = { + "TestSource", "FileInput", "SigMFFileInput", "LocalInput", "RemoteInput", "RemoteTCPInput", + "KiwiSDR", "AudioInput", "AaroniaRTSA", "AndroidSdrDriverInput" +}; + +// The type specific sub-object of a settings reply, e.g. the rtlSdrSettings of a device +QJsonObject settingsOf(const QJsonObject& reply) +{ + return reply[findSettingsKey(reply)].toObject(); +} + +// A signal level from a channel report, whatever the plugin calls it +bool signalLevel(const QJsonObject& report, double& db) +{ + for (const QString& key : report.keys()) + { + if (!key.endsWith("Report") || !report[key].isObject()) { + continue; + } + + QJsonObject sub = report[key].toObject(); + + for (const QString& k : sub.keys()) + { + if ((k.contains("PowerDB", Qt::CaseInsensitive) || (k == "rssi")) && sub[k].isDouble()) + { + db = sub[k].toDouble(); + return true; + } + } + } + + return false; +} + +} // namespace + +// A channel whose baseband is too narrow produces nothing, or silence, with no error anywhere: +// the demodulator simply never sees the signal. The rule is in this server's instructions, but +// it is read once at the start of a conversation and needed much later, so it is repeated here, +// where the numbers are known and the fix can be named. +QString MCPTools::basebandWarning(int deviceSetIndex, const QString& channelType) +{ + int needed = minimumBasebandFor(channelType); + + if (needed <= 0) { + return QString(); // nothing known about what this type needs + } + + QJsonObject settings; + + try + { + settings = settingsOf(getDeviceSettings(deviceSetIndex)); + } + catch (const MCPToolError&) + { + return QString(); // no device, or it cannot be read: not this call's problem to report + } + + // Only devices that express their rate this way can be checked. Saying nothing is better + // than guessing at a device whose keys are not these + if (!settings.contains("devSampleRate") || !settings.contains("log2Decim")) { + return QString(); + } + + int baseband = settings["devSampleRate"].toInt() >> settings["log2Decim"].toInt(); + + if (baseband >= needed) { + return QString(); + } + + int wantedRate = 0; + int wantedDecim = 0; + rateFor(needed, wantedRate, wantedDecim); + + return QString("%1 needs a baseband of at least %2 Hz, but device set %3 provides %4 Hz, so the channel " + "cannot work as it stands. Call set_device_settings with devSampleRate %5 and log2Decim %6.") + .arg(channelType).arg(needed).arg(deviceSetIndex).arg(baseband).arg(wantedRate).arg(wantedDecim); +} + +QStringList MCPTools::basebandWarnings(int deviceSetIndex) +{ + QStringList warnings; + QJsonObject deviceSet; + + try + { + deviceSet = getDeviceSet(deviceSetIndex); + } + catch (const MCPToolError&) + { + return warnings; + } + + QSet seen; + + for (const QJsonValue& value : deviceSet["channels"].toArray()) + { + QString channelType = value.toObject()["id"].toString(); + + if (channelType.isEmpty() || seen.contains(channelType)) { + continue; // several of a type would repeat the same sentence + } + + seen.insert(channelType); + QString warning = basebandWarning(deviceSetIndex, channelType); + + if (!warning.isEmpty()) { + warnings.append(warning); + } + } + + return warnings; +} + +QStringList MCPTools::channelTypeIds(int direction) +{ + SWGSDRangel::SWGInstanceChannelsResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceChannels(direction, response, error), error, "List channel types"); + QStringList ids; + + for (const QJsonValue& v : toJson(response)["channels"].toArray()) { + ids.append(v.toObject()["id"].toString()); + } + + return ids; +} + +void MCPTools::relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what) +{ + if (!MCPCapture::locateChannel(channelUid, deviceSetIndex, channelIndex)) { + throw MCPToolError(QString("The %1 channel no longer exists: another request removed it, or its device set, " + "while this call was running").arg(what)); + } +} + +void MCPTools::trackIntentChannel(uint64_t channelUid) +{ + if (channelUid == 0) { + return; + } + + QMutexLocker locker(&m_intentMutex); + m_intentChannels.insert(channelUid); +} + +void MCPTools::untrackIntentChannel(uint64_t channelUid) +{ + QMutexLocker locker(&m_intentMutex); + m_intentChannels.remove(channelUid); +} + +QSet MCPTools::intentChannels() +{ + QMutexLocker locker(&m_intentMutex); + return m_intentChannels; +} + +// What a device set carries besides one channel, and which of it listen or scan put there. +// Read from the live device set rather than any earlier snapshot, as a reclaim in between +// changes both the indices and the answer +QList MCPTools::channelNotes(int deviceSetIndex, const QSet& except) +{ + const QSet intent = intentChannels(); + QList notes; + + for (const QJsonValue& v : getDeviceSet(deviceSetIndex)["channels"].toArray()) + { + QJsonObject channel = v.toObject(); + int index = channel["index"].toInt(); + const uint64_t uid = channelUidAt(deviceSetIndex, index); + + if ((uid != 0) && !except.contains(uid)) { + notes.append({uid, index, channel["id"].toString(), intent.contains(uid)}); + } + } + + return notes; +} + +QStringList MCPTools::reclaimIntentChannels(int deviceSetIndex, const QSet& keep) +{ + QStringList removed; + + // Each is deleted by identity, wherever it has been renumbered to by then, and highest + // index first so that the ids come out in the order the device set listed them + QList notes = channelNotes(deviceSetIndex); + + for (int i = notes.size() - 1; i >= 0; i--) + { + if (!notes[i].m_intent || keep.contains(notes[i].m_uid)) { + continue; + } + + try + { + deleteChannelObjectAndWait(notes[i].m_uid); + removed.prepend(notes[i].m_id); + } + catch (const MCPToolError&) {} + + // Tracked no longer either way: if it could not be deleted now it will not be later + untrackIntentChannel(notes[i].m_uid); + } + + return removed; +} + +// Retuning the demodulator a previous listen added is what a person would do, and spares the +// audio device and the GUI a close and reopen. Only when the intent channels of that type are +// exactly the count the mode uses (one, or two for a paired mode such as AIS), and no scan's +// FreqScanner is there to be driving them. The first is returned; a paired mode finds the +// other among the intent channels of the type +uint64_t MCPTools::reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted) +{ + uint64_t candidate = 0; + int candidates = 0; + + for (const ChannelNote& note : channelNotes(deviceSetIndex)) + { + if (!note.m_intent) { + continue; + } + + if (note.m_id == "FreqScanner") { + return 0; + } + + if (note.m_id == channelType) + { + if (candidate == 0) + { + candidate = note.m_uid; + channelIndex = note.m_index; + } + + candidates++; + } + } + + return (candidates == wanted) ? candidate : 0; +} + +// A retune moves every channel on the device set, since each is an offset from the centre. A +// channel the user added is kept on the frequency it had when the new baseband holds it; an +// audio demodulator it cannot hold is removed, as all it could do is play noise; anything else +// is left, with a note, since a file sink or an analyser may be wanted regardless +MCPTools::RetuneOutcome MCPTools::retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband) +{ + RetuneOutcome outcome; + + if ((qint64) previousCentre == (qint64) centre) { + return outcome; + } + + static const QStringList audioDemods = { + "AMDemod", "BFMDemod", "DABDemod", "DATVDemod", "DSDDemod", "FreeDVDemod", "ILSDemod", "M17Demod", + "NFMDemod", "SSBDemod", "VORDemod", "VORDemodMC", "WFMDemod", "WDSPRx" + }; + + const QSet intent = intentChannels(); + QJsonObject set = getDeviceSet(deviceSetIndex); + + if (baseband <= 0) { + baseband = set["samplingDevice"].toObject()["bandwidth"].toInt(); + } + + struct Item { int m_index; QString m_id; uint64_t m_uid; qint64 m_offset; }; + QList items; + + for (const QJsonValue& v : set["channels"].toArray()) + { + QJsonObject channel = v.toObject(); + const int index = channel["index"].toInt(); + const uint64_t uid = channelUidAt(deviceSetIndex, index); + + if ((uid != 0) && !intent.contains(uid)) { + items.append({index, channel["id"].toString(), uid, (qint64) channel["deltaFrequency"].toDouble()}); + } + } + + // Highest index first, so that a removal does not renumber one still to be visited + for (int i = items.size() - 1; i >= 0; i--) + { + const Item& item = items[i]; + const qint64 wanted = (qint64) previousCentre + item.m_offset; // where it was listening + const qint64 offset = wanted - (qint64) centre; + const QString where = QString("%1 at %2 MHz").arg(item.m_id).arg(wanted / 1e6, 0, 'f', 3); + + // The offset key differs by type: most have inputFrequencyOffset, the Channel Analyzer + // frequency, ATV intFrequencyOffset, DATV centerFrequency; a sink or a scanner has none + // and is left alone. Read the live settings to find which, rather than guess + QString offsetKey; + + if ((baseband > 0) && (qAbs(offset) <= baseband * 0.45)) // a tenth kept clear at each edge + { + try + { + QJsonObject current = settingsOf(getChannelSettings(deviceSetIndex, item.m_index)); + + for (const char *key : {"inputFrequencyOffset", "frequency", "intFrequencyOffset", "centerFrequency"}) + { + if (current.contains(key)) + { + offsetKey = key; + break; + } + } + } + catch (const MCPToolError&) {} + } + + if (!offsetKey.isEmpty()) + { + try + { + QJsonObject partial; + partial[offsetKey] = (double) offset; + patchChannelSettings(deviceSetIndex, item.m_index, partial); + outcome.m_kept.append(where); + } + catch (const MCPToolError&) + { + outcome.m_stranded.append(where); + } + } + else if ((baseband > 0) && audioDemods.contains(item.m_id)) + { + try + { + deleteChannelObjectAndWait(item.m_uid); + outcome.m_removed.append(where); + } + catch (const MCPToolError&) + { + outcome.m_stranded.append(where); + } + } + else + { + outcome.m_stranded.append(where); + } + } + + return outcome; +} + +QStringList MCPTools::intentNotes(int deviceSetIndex, const QSet& added, const QStringList& reclaimed, + bool reused, double previousCentre, double centre, const RetuneOutcome& outcome) +{ + QStringList notes; + + if (!reclaimed.isEmpty()) + { + notes.append(QString("Removed %1 channel%2 (%3) that earlier listen or scan calls added to device set %4; pass replace false to keep them.") + .arg(reclaimed.size()).arg(reclaimed.size() == 1 ? "" : "s").arg(reclaimed.join(", ")).arg(deviceSetIndex)); + } + + // Read from the live device set rather than the snapshot pickReceiver made, which still + // lists whatever the reclaim has since removed + QStringList leftovers; + QStringList others; + + for (const ChannelNote& note : channelNotes(deviceSetIndex, added)) { + (note.m_intent ? leftovers : others).append(note.m_id); + } + + // Only possible with replace false, and then it is the caller's own trail + if (!leftovers.isEmpty()) + { + notes.append(QString("Device set %1 still has %2 channel%3 (%4) from earlier listen or scan calls, any audio ones still playing; cleanup removes them.") + .arg(deviceSetIndex).arg(leftovers.size()).arg(leftovers.size() == 1 ? "" : "s").arg(leftovers.join(", "))); + } + + // What the retune did to the channels the user added, and how to put back what it took + if (reused && ((qint64) previousCentre != (qint64) centre) + && !(outcome.m_kept.isEmpty() && outcome.m_removed.isEmpty() && outcome.m_stranded.isEmpty())) + { + QString note = QString("Retuned device set %1 from %2 to %3 MHz.").arg(deviceSetIndex) + .arg(previousCentre / 1e6, 0, 'f', 3).arg(centre / 1e6, 0, 'f', 3); + + if (!outcome.m_kept.isEmpty()) { + note += QString(" Kept %1 other channel%2 on frequency by moving the offset: %3.") + .arg(outcome.m_kept.size()).arg(outcome.m_kept.size() == 1 ? "" : "s").arg(outcome.m_kept.join(", ")); + } + + if (!outcome.m_removed.isEmpty()) { + note += QString(" Removed %1 audio demodulator%2 the new baseband could not hold, which would only have played noise: %3. " + "They were not added by listen or scan; add_channel puts one back.") + .arg(outcome.m_removed.size()).arg(outcome.m_removed.size() == 1 ? "" : "s").arg(outcome.m_removed.join(", ")); + } + + if (!outcome.m_stranded.isEmpty()) { + note += QString(" Left %1 other channel%2 that the new baseband does not hold, not being audio: %3. " + "set_channel_settings inputFrequencyOffset retunes one, delete_channel removes it.") + .arg(outcome.m_stranded.size()).arg(outcome.m_stranded.size() == 1 ? "" : "s").arg(outcome.m_stranded.join(", ")); + } + + notes.append(note); + } + + (void) others; + return notes; +} + +QJsonObject MCPTools::channelReport(int deviceSetIndex, int channelIndex) +{ + SWGSDRangel::SWGChannelReport response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelReportGet(deviceSetIndex, channelIndex, response, error), error, "Get channel report"); + return toJson(response); +} + +void MCPTools::postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions) +{ + QJsonObject settings = getChannelSettings(deviceSetIndex, channelIndex); + QString channelType = settings["channelType"].toString(); + + if (!WebAPIUtils::m_channelTypeToActionsKey.contains(channelType)) { + throw MCPToolError(QString("Channel type %1 has no actions").arg(channelType)); + } + + QJsonObject json; + json["channelType"] = channelType; + json["direction"] = settings["direction"].toInt(0); + json[WebAPIUtils::m_channelTypeToActionsKey[channelType]] = actions; + QStringList keys; + extractKeys(actions, keys); + + SWGSDRangel::SWGChannelActions query; + query.init(); + query.fromJsonObject(json); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetChannelActionsPost(deviceSetIndex, channelIndex, keys, query, response, error), error, "Channel action"); +} + +// Finds or creates a receive device set holding a suitable device and sets its sample rate. +// An existing set holding the same device is reused rather than fought for the hardware; the +// caller tunes the centre frequency and is told what else that set carries. +// Takes away the device set listen or scan created when the call fails before it is done +// with it, so a retry does not build another beside a half made one. Cleared on success +class NewDeviceSetGuard +{ +public: + NewDeviceSetGuard(MCPTools *tools, int deviceSetIndex) : + m_tools(tools), + m_deviceSetIndex(deviceSetIndex), + m_identity(deviceSetIndex >= 0 ? tools->deviceSetIdentity(deviceSetIndex) : 0) + {} + ~NewDeviceSetGuard() + { + if (m_deviceSetIndex >= 0) { + m_tools->discardNewDeviceSet(m_deviceSetIndex, m_identity); + } + } + void keep() { m_deviceSetIndex = -1; } + +private: + MCPTools *m_tools; + int m_deviceSetIndex; + uint64_t m_identity; //!< Of the set as it was when this call made it +}; + +QJsonObject MCPTools::pickReceiver(const QJsonObject& args, int minBaseband, const QSet& doomed, bool profileGain) +{ + SWGSDRangel::SWGInstanceDevicesResponse devicesResponse; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->instanceDevices(0, devicesResponse, error), error, "List devices"); + QJsonArray devices = toJson(devicesResponse)["devices"].toArray(); + + // Which device: the one the caller named; else the first real radio that was actually + // enumerated, which is the one with a serial number - some plugins list a placeholder + // entry for hardware that is not attached, and it has none; else anything + QJsonObject chosen; + QJsonObject fallback; + QString wanted = argString(args, "device", false).trimmed(); + + for (const QJsonValue& v : devices) + { + QJsonObject d = v.toObject(); + + if (!wanted.isEmpty()) + { + if ((d["serial"].toString().compare(wanted, Qt::CaseInsensitive) == 0) + || (d["displayedName"].toString().compare(wanted, Qt::CaseInsensitive) == 0) + || (d["hwType"].toString().compare(wanted, Qt::CaseInsensitive) == 0)) + { + chosen = d; + break; + } + } + else if (!virtualDeviceTypes.contains(d["hwType"].toString())) + { + if (!d["serial"].toString().isEmpty()) { chosen = d; break; } + if (fallback.isEmpty()) { fallback = d; } + } + } + + if (chosen.isEmpty() && wanted.isEmpty()) { + chosen = fallback.isEmpty() && !devices.isEmpty() ? devices.first().toObject() : fallback; + } + + if (chosen.isEmpty()) { + throw MCPToolError(QString("No receive device matches %1. list_available_devices shows what there is.").arg(wanted.isEmpty() ? "anything" : wanted)); + } + + QString hwType = chosen["hwType"].toString(); + QString serial = chosen["serial"].toString(); + + // Reuse a device set that already holds this device + int deviceSetIndex = -1; + QJsonArray otherChannels; + QJsonArray deviceSets = getInstanceSummary()["devicesetlist"].toObject()["deviceSets"].toArray(); + + for (const QJsonValue& v : deviceSets) + { + QJsonObject ds = v.toObject(); + QJsonObject sd = ds["samplingDevice"].toObject(); + + if (sd["direction"].toInt() != 0) { + continue; + } + + bool same = serial.isEmpty() ? (sd["hwType"].toString() == hwType) : (sd["serial"].toString() == serial); + + if (same) + { + deviceSetIndex = sd["index"].toInt(); + + // Channels the caller is about to remove are not ones the set has to go on + // serving, so they neither hold the baseband width up nor count as carried + for (const QJsonValue& c : ds["channels"].toArray()) + { + QJsonObject channel = c.toObject(); + + if (!doomed.contains(channelUidAt(deviceSetIndex, channel["index"].toInt()))) { + otherChannels.append(channel["id"].toString()); + } + } + + break; + } + } + + bool reused = deviceSetIndex >= 0; + + if (!reused) { + deviceSetIndex = addDeviceSetAndWait(0); + } + + // Until the caller has it, a set made here that cannot be finished is this function's to + // take away again + NewDeviceSetGuard newDeviceSet(this, reused ? -1 : deviceSetIndex); + + if (!reused) + { + QJsonObject select; + select["hwType"] = hwType; + + if (!serial.isEmpty()) { + select["serial"] = serial; + } + + selectDevice(deviceSetIndex, select); + } + + QJsonObject before = settingsOf(getDeviceSettings(deviceSetIndex)); + + // Only the devices whose rate keys and supported rates are known are set; others keep + // their configured rate and the caller is told to check it + QString rateKey; + + if (hwType == "RTLSDR") { + rateKey = "devSampleRate"; + } else if (hwType == "TestSource") { + rateKey = "sampleRate"; + } + + // A reused device set is already feeding its other channels the width it has. Widening it for + // the new channel leaves them working, narrowing it to what only the new one needs takes their + // signal away, so the width already configured is a floor rather than something to overwrite + int existingBaseband = 0; + + if (reused && !otherChannels.isEmpty() && !rateKey.isEmpty()) + { + int rate = before[rateKey].toInt(); + + if (rate > 0) { + existingBaseband = rate >> before["log2Decim"].toInt(); + } + } + + int devSampleRate = 0; + int log2Decim = 0; + rateFor(qMax(minBaseband, existingBaseband), devSampleRate, log2Decim); + QJsonObject partial; + QString rateNote; + int baseband = 0; + + if (!rateKey.isEmpty()) + { + baseband = devSampleRate >> log2Decim; + + if (baseband < existingBaseband) + { + // Wider than rateFor is able to ask for, so leave the rate alone altogether + baseband = existingBaseband; + rateNote = QString("Device set %1 was left at %2 S/s of baseband, which its other channels need.") + .arg(deviceSetIndex).arg(existingBaseband); + } + else + { + partial[rateKey] = devSampleRate; + partial["log2Decim"] = log2Decim; + + if (existingBaseband > minBaseband) { + rateNote = QString("Device set %1 was kept at %2 S/s of baseband rather than the %3 this channel needs, for its other channels.") + .arg(deviceSetIndex).arg(baseband).arg(minBaseband); + } + } + } + + // Only a device set this call created gets the receiver profile: one that was found is the + // user's, and its gain stays whatever they set + if (!reused && (hwType == "RTLSDR")) + { + partial["dcBlock"] = 1; + partial["iqImbalance"] = 1; + + // A fixed 40 dB when the caller is not about to measure one: the tuner's own AGC is + // unreliable on weak signals, and the default gain left the airband 35 dB down on what + // a hand-set receiver saw + if (profileGain) + { + partial["agc"] = 0; + partial["gain"] = 402; + rateNote = (rateNote.isEmpty() ? QString() : rateNote + " ") + + QString("Device set %1 is new, so its RTL-SDR was set to 40 dB gain with AGC off; set_device_settings changes it.") + .arg(deviceSetIndex); + } + } + + if (!partial.isEmpty()) { + patchDeviceSettings(deviceSetIndex, partial); + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["hwType"] = hwType; + result["device"] = chosen["displayedName"].toString(); + result["reused"] = reused; + result["previousCentre"] = before["centerFrequency"].toDouble(); + result["otherChannels"] = otherChannels; + result["baseband"] = baseband; + result["rateNote"] = rateNote; + newDeviceSet.keep(); + return result; +} + +// The tune_gain tool, also run by listen and scan when they set up a receiver on a new +// device set or move one to another band +QJsonObject MCPTools::tuneGain(const QJsonObject& args) +{ + int deviceSetIndex = argInt(args, "deviceSetIndex"); + QJsonObject reply = getDeviceSettings(deviceSetIndex); + const QString hwType = reply["deviceHwType"].toString(); + QJsonObject settings = settingsOf(reply); + + if (deviceState(deviceSetIndex, 0, -1)["state"].toString() != "running") { + throw MCPToolError("The device is not running, so there is nothing to measure. start_device first."); + } + + // What this knows about each device's gain: the key, its manual AGC setting, and the + // values to try. Where a device has several gain stages the one before the mixer is + // tuned, as that is where overload happens; the rest keep their settings + struct Knob { QString key; QString agcKey; int agcOff; QList values; QString unit; QString note; }; + Knob knob; + const bool custom = hasArg(args, "gainKey"); + + if (custom) + { + knob.key = argString(args, "gainKey"); + knob.agcKey = argString(args, "agcKey", false); + knob.agcOff = 0; + knob.unit = "the key's own units"; + + for (const QJsonValue& v : args["values"].toArray()) { + knob.values.append(v.toDouble()); + } + + if (knob.values.size() < 2) { + throw MCPToolError("Give at least two values to try with gainKey"); + } + } + else if (hwType == "RTLSDR") + { + // The tuner takes only the values it lists, in tenths of a decibel + knob = {"gain", "agc", 0, {}, "tenths of a dB", "The tuner's AGC is off, as it must be for the gain to hold"}; + SWGSDRangel::SWGDeviceReport report; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetDeviceReportGet(deviceSetIndex, report, error), error, "Get device report"); + QJsonObject json = toJson(report); + + for (const QString& key : json.keys()) + { + for (const QJsonValue& g : json[key].toObject()["gains"].toArray()) { + knob.values.append(g.toObject()["gainCB"].toDouble()); + } + } + + if (knob.values.isEmpty()) { + throw MCPToolError("The RTL-SDR reported no supported gain values; is the device open?"); + } + } + else if (hwType == "HackRF") { + knob = {"lnaGain", "", 0, {0, 8, 16, 24, 32, 40}, "dB", "Only the LNA is stepped; vgaGain is left as it is"}; + } + else if (hwType == "Airspy") { + knob = {"lnaGain", "lnaAGC", 0, {0, 2, 4, 6, 8, 10, 12, 14}, "steps", "Only the LNA is stepped; mixerGain and vgaGain are left as they are, with the LNA AGC off"}; + } + else if (hwType == "LimeSDR") { + knob = {"gain", "gainMode", 1, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; + } + else if (hwType == "PlutoSDR") { + knob = {"gain", "gainMode", 0, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; + } + else if (hwType == "USRP") { + knob = {"gain", "gainMode", 1, {0, 10, 20, 30, 40, 50, 60, 70}, "dB", "gainMode set to manual"}; + } + else + { + throw MCPToolError(QString("tune_gain does not know the gain settings of a %1. Read them with describe_settings and " + "give gainKey, values and, if it has one, agcKey.").arg(hwType)); + } + + std::sort(knob.values.begin(), knob.values.end()); + knob.values.erase(std::unique(knob.values.begin(), knob.values.end()), knob.values.end()); + + // Spread the steps over the range rather than trying every value a tuner offers + const int steps = qBound(3, argInt(args, "steps", false, 8), 16); + QList candidates; + + if (knob.values.size() <= steps) { + candidates = knob.values; + } + else + { + for (int i = 0; i < steps; i++) { + candidates.append(knob.values[(int) std::round(i * (knob.values.size() - 1) / (double) (steps - 1))]); + } + } + + const bool apply = argBool(args, "apply", true); + + // A key the device does not have would be patched away as unknown at every step, and the + // sweep would then measure the same gain six times and report a choice it never made + if (!settings.contains(knob.key)) { + throw MCPToolError(QString("%1 has no %2 setting; describe_settings shows its keys").arg(hwType).arg(knob.key)); + } + + if (!knob.agcKey.isEmpty() && !settings.contains(knob.agcKey)) { + throw MCPToolError(QString("%1 has no %2 setting; describe_settings shows its keys").arg(hwType).arg(knob.agcKey)); + } + + const double previous = settings[knob.key].toDouble(); + const double previousAgc = knob.agcKey.isEmpty() ? 0 : settings[knob.agcKey].toDouble(); + const qint64 frequency = (qint64) argDouble(args, "frequency", false, 0); + const qint64 bandwidth = (qint64) argDouble(args, "bandwidth", false, 200000); + + // One reading: the floor is the median over the baseband, the signal the strongest bin, + // in the window asked for or anywhere. Max reduction keeps a narrow carrier + auto measure = [&](double& floorDb, double& peakDb) + { + SWGSDRangel::SWGGLSpectrumData response; + SWGSDRangel::SWGErrorResponse error; + response.init(); + error.init(); + check(m_adapter->devicesetSpectrumDataGet(deviceSetIndex, 256, 0, 0, "max", response, error), error, "Get spectrum data"); + // Read from the object: the generated JSON serialiser drops a list of plain floats + const bool linear = response.getLinear() != 0; + QList powers; + + if (response.getPower()) + { + for (float v : *response.getPower()) { + powers.append(linear ? 10.0 * std::log10(std::max((double) v, 1e-20)) : (double) v); + } + } + + if (powers.isEmpty()) { + throw MCPToolError("The spectrum returned no data"); + } + + QList sorted = powers; + std::sort(sorted.begin(), sorted.end()); + floorDb = sorted[sorted.size() / 2]; + + if (frequency > 0) + { + // The data call clamps to the baseband, which would silently measure noise at + // its edge for a frequency outside it + const qint64 low = response.getCenterFrequency() - response.getBandwidth() / 2; + const qint64 high = response.getCenterFrequency() + response.getBandwidth() / 2; + + if ((frequency < low) || (frequency > high)) + { + throw MCPToolError(QString("%1 MHz is outside the baseband, which covers %2 to %3 MHz; tune the device so that it is inside, or leave frequency out") + .arg(frequency / 1e6, 0, 'f', 3).arg(low / 1e6, 0, 'f', 3).arg(high / 1e6, 0, 'f', 3)); + } + + SWGSDRangel::SWGGLSpectrumData window; + SWGSDRangel::SWGErrorResponse windowError; + window.init(); + windowError.init(); + check(m_adapter->devicesetSpectrumDataGet(deviceSetIndex, 32, frequency - bandwidth / 2, frequency + bandwidth / 2, "max", window, windowError), + windowError, "Get spectrum data"); + peakDb = -1e9; + + if (window.getPower()) + { + for (float v : *window.getPower()) { + peakDb = std::max(peakDb, linear ? 10.0 * std::log10(std::max((double) v, 1e-20)) : (double) v); + } + } + + if (peakDb < -1e8) { + throw MCPToolError("The spectrum has no bins at that frequency; it must be inside the baseband"); + } + } + else + { + peakDb = sorted.last(); + } + }; + + struct Row { double gain; double floorDb; double peakDb; double snrDb; }; + QList rows; + + auto setGain = [&](double gain, bool agcOff) + { + QJsonObject partial; + partial[knob.key] = gain; + + if (!knob.agcKey.isEmpty()) { + partial[knob.agcKey] = agcOff ? knob.agcOff : previousAgc; + } + + patchDeviceSettings(deviceSetIndex, partial); + }; + + try + { + for (double gain : candidates) + { + setGain(gain, true); + pause(700); // the tuner, the spectrum averaging and a stale FFT + double floorSum = 0.0; + double peakSum = 0.0; + const int samples = 3; + + for (int i = 0; i < samples; i++) + { + if (i > 0) { + pause(250); + } + + double floorDb, peakDb; + measure(floorDb, peakDb); + floorSum += floorDb; + peakSum += peakDb; + } + + rows.append({gain, floorSum / samples, peakSum / samples, (peakSum - floorSum) / samples}); + } + } + catch (const MCPToolError&) + { + setGain(previous, false); // as it was, AGC included + throw; + } + + auto toDb = [&](double gain) { return (knob.unit == "tenths of a dB") ? gain / 10.0 : gain; }; + + // Overload shows as the floor climbing faster than the gain did. The first step + // where it does bounds the usable range from above + QStringList notes; + int compressed = 0; + int overloadFrom = rows.size(); // index of the first row that is overloaded + + for (int i = 1; i < rows.size(); i++) + { + const double gainStep = toDb(rows[i].gain) - toDb(rows[i - 1].gain); + + if ((gainStep > 0) && (rows[i].floorDb - rows[i - 1].floorDb > gainStep + 3.0)) + { + compressed++; + overloadFrom = std::min(overloadFrom, i); + } + } + + if (compressed > 0) { + notes.append(QString("The noise floor rose faster than the gain over %1 step%2, which is the front end overloading; the higher gains are not usable here.") + .arg(compressed).arg(compressed == 1 ? "" : "s")); + } + + // Best SNR, then the lowest gain within a decibel of it + double best = -1e9; + for (const Row& r : rows) { best = std::max(best, r.snrDb); } + const Row *chosen = nullptr; + QString judgedBy = frequency > 0 ? QString("the signal at %1 MHz").arg(frequency / 1e6, 0, 'f', 3) : QString("the strongest signal in the baseband"); + + if (best >= 6.0) + { + for (const Row& r : rows) { if ((r.snrDb >= best - 1.0) && !chosen) { chosen = &r; } } + } + else + { + // Nothing stood clear of the floor, so the floor itself has to decide: at low gain + // it is the converter's own noise and does not move; as gain rises the antenna's + // noise comes through and lifts it, which is when weak signals become receivable; + // and past overload it lifts faster than the gain. Take the lowest gain that puts + // the floor 8 dB above the converter's, which is the antenna's noise dominating + // by the usual 10 dB rule with a little allowance for the steps being coarse, or + // the last gain before overload if none does + double adcFloor = 1e9; + for (const Row& r : rows) { adcFloor = std::min(adcFloor, r.floorDb); } + const int lastUsable = std::max(0, overloadFrom - 1); + static const double antennaDominates = 8.0; + + for (int i = 0; (i <= lastUsable) && !chosen; i++) + { + if (rows[i].floorDb >= adcFloor + antennaDominates) { + chosen = &rows[i]; + } + } + + if (!chosen) { + chosen = &rows[lastUsable]; + } + + judgedBy = "the noise floor alone, as no signal stood clear of it"; + notes.append(QString("No signal stood more than 6 dB above the floor, so the gain is set from the floor instead: %1.") + .arg((rows[lastUsable].floorDb < adcFloor + antennaDominates) + ? "the floor never rose 8 dB above the converter's own noise before overload, so the last gain before overload is taken; check the antenna if that seems low" + : "the lowest gain at which the antenna's noise, not the converter's, sets the floor")); + } + + if (chosen == &rows.last()) { + notes.append("The best was the highest gain tried: the signal is weak or the site quiet, and more gain would not overload yet."); + } else if (chosen == &rows.first()) { + notes.append("The best was the lowest gain tried: a strong-signal site. Consider an attenuator if the floor still rises with the lowest gain."); + } + + bool autoscaled = false; + + if (apply) + { + setGain(chosen->gain, true); + + // The spectrum was scaled for the gain it had, and a change of tens of decibels + // leaves the trace off the top or along the bottom of the display. Once the new gain + // has reached the trace, the range is set from it, as the GUI's autoscale button does + if (argBool(args, "autoscale", true)) + { + try + { + pause(700); + autoscaleSpectrum(deviceSetIndex); + autoscaled = true; + } + catch (const MCPToolError& e) + { + notes.append(QString("The spectrum could not be autoscaled: %1").arg(e.message)); + } + } + } + else + { + setGain(previous, false); + notes.append("Not applied: the gain is back as it was."); + } + + if (!knob.note.isEmpty()) { + notes.append(knob.note + "."); + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["hwType"] = hwType; + result["autoscaled"] = autoscaled; + result["gainKey"] = knob.key; + result["unit"] = knob.unit; + result["previous"] = previous; + result["chosen"] = chosen->gain; + result["applied"] = apply; + result["bestSnrDb"] = chosen->snrDb; + result["judgedBy"] = judgedBy; + QJsonArray table; + + for (const Row& r : rows) + { + QJsonObject o; + o["gain"] = r.gain; + o["floorDb"] = std::round(r.floorDb * 10) / 10; + o["signalDb"] = std::round(r.peakDb * 10) / 10; + o["snrDb"] = std::round(r.snrDb * 10) / 10; + table.append(o); + } + + result["table"] = table; + + if (!notes.isEmpty()) { + result["note"] = notes.join(" "); + } + + return result; +} + +// A mode whose output is only useful through a feature, such as AIS to the AIS feature's ship +// list and the map, gets that feature added with the demodulator. One that is there already is +// left alone, whatever it is set to +int MCPTools::ensureFeature(const QString& featureType, int& featureIndex) +{ + for (const QJsonValue& v : getInstanceSummary()["featureset"].toObject()["features"].toArray()) + { + QJsonObject f = v.toObject(); + + if (f["id"].toString() == featureType) + { + featureIndex = f["index"].toInt(); + return 0; + } + } + + featureIndex = addFeatureAndWait(featureType); + trackIntentFeature(featureUidAt(featureIndex)); + return 1; +} + +void MCPTools::trackIntentFeature(uint64_t featureUid) +{ + if (featureUid == 0) { + return; + } + + QMutexLocker locker(&m_intentMutex); + m_intentFeatures.insert(featureUid); +} + +// A feature listen added goes with the demodulators that fed it: once the last of those is +// reclaimed, on whichever device set, it would only show stale data. One the next mode +// needs, or that a demodulator anywhere still feeds, stays: the user may have added their own +// decoder since and be reading the feature through it +QStringList MCPTools::reclaimIntentFeatures(const QString& keepType) +{ + QSet tracked; + { + QMutexLocker locker(&m_intentMutex); + tracked = m_intentFeatures; + } + + if (tracked.isEmpty()) { + return QStringList(); + } + + // The feature types the remaining channels feed, whoever added them + QSet needed; + + if (!keepType.isEmpty()) { + needed.insert(keepType); + } + + for (int deviceSetIndex = 0; deviceSetIndex < deviceSetCount(); deviceSetIndex++) + { + for (const ChannelNote& note : channelNotes(deviceSetIndex)) + { + const char *feature = featureForChannelType(note.m_id); + + if (feature) { + needed.insert(QString(feature)); + } + } + } + + QStringList removed; + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (featureSets.empty()) { + return removed; + } + + // Collected first: deleting renumbers the rest, and by UID, as each deletion waits + QList> doomed; + + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + const Feature *feature = featureSets[0]->getFeatureAt(i); + + if (feature && tracked.contains(feature->getUID()) && !needed.contains(feature->getIdentifier())) { + doomed.append(qMakePair(feature->getUID(), feature->getIdentifier())); + } + } + + for (const auto& feature : doomed) + { + try + { + deleteFeatureObjectAndWait(feature.first); + removed.append(feature.second); + } + catch (const MCPToolError&) {} + } + + // Tracked no longer: those removed, and any the user had already deleted + QMutexLocker locker(&m_intentMutex); + + for (uint64_t uid : tracked) + { + bool present = false; + + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + const Feature *feature = featureSets[0]->getFeatureAt(i); + + if (feature && (feature->getUID() == uid)) + { + present = true; + break; + } + } + + if (!present) { + m_intentFeatures.remove(uid); + } + } + + return removed; +} + +void MCPTools::deleteFeatureObjectAndWait(uint64_t featureUid) +{ + QMutexLocker deletionLock(&m_deletionMutex); + int featureIndex = -1; + const std::vector& featureSets = MainCore::instance()->getFeatureeSets(); + + if (!featureSets.empty() && (featureUid != 0)) + { + for (int i = 0; i < featureSets[0]->getNumberOfFeatures(); i++) + { + const Feature *feature = featureSets[0]->getFeatureAt(i); + + if (feature && (feature->getUID() == featureUid)) + { + featureIndex = i; + break; + } + } + } + + if (featureIndex < 0) { + return; // Already gone + } + + requireNotSelf(featureIndex, "deleted"); + SWGSDRangel::SWGSuccessResponse response; + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->featuresetFeatureDelete(0, featureIndex, response, error), error, "Delete feature"); + + if (!waitFor([&]() { return !featureUids().contains(featureUid); })) { + throw MCPToolError(QString("Timed out waiting for feature %1 to be removed").arg(featureIndex)); + } +} + +void MCPTools::autoscaleSpectrum(int deviceSetIndex) +{ + QJsonObject actions; + actions["autoscale"] = 1; + QStringList keys; + extractKeys(actions, keys); + SWGSDRangel::SWGSpectrumActions query; + query.init(); + query.fromJsonObject(actions); + SWGSDRangel::SWGErrorResponse error; + error.init(); + check(m_adapter->devicesetSpectrumActionsPost(deviceSetIndex, keys, query, error), error, "Autoscale spectrum"); +} + +// The history the spectrum tools read is the display's scroll buffer, which fills only while +// scrolling is on. Switched on here with a length that covers what was asked for at a +// typical refresh rate, and at least a couple of minutes; a longer length the user has set +// is left alone +QString MCPTools::ensureSpectrumHistory(int deviceSetIndex, double seconds) +{ + QJsonObject settings = getSpectrumSettings(deviceSetIndex); + const bool scrolling = settings["scrollBar"].toInt() != 0; + const int length = settings["scrollLength"].toInt(); + const int wanted = qBound(1200, (int) (seconds * 20.0), 4000); + + if (scrolling && (length >= wanted)) { + return QString(); + } + + QJsonObject partial; + partial["scrollBar"] = 1; + partial["scrollLength"] = qMax(length, wanted); + patchSpectrumSettings(deviceSetIndex, partial); + return scrolling + ? QString("The spectrum history was lengthened to %1 rows to cover %2 seconds.").arg(qMax(length, wanted)).arg(seconds) + : QString("Spectrum scrolling was switched on, as the history the spectrum keeps for it is what this reads; it starts now."); +} + +// The gain suits a band and an antenna, not a mode: a device set that was just created has +// whatever gain it came with, and one moved to another band has the gain of the last one. A +// move within a band, or a change of mode on the same frequency, needs no new measurement +bool MCPTools::gainWorthTuning(bool reused, double previousCentre, double centre) +{ + if (!reused) { + return true; + } + + return std::abs(centre - previousCentre) > 0.1 * std::max(centre, previousCentre); +} + +void MCPTools::registerIntentTools() +{ + static const QString deviceHint = "Optional: which device, by serial, displayed name or type (e.g. RTLSDR) as shown by " + "list_available_devices. Default: the first radio attached to this machine"; + + add("listen", + "Receive a frequency in one call: picks a device, creates or reuses its device set, sets the sample rate, adds the " + "demodulator with sensible settings, starts the device and reports the signal level. Audio plays on the default output. " + "Use the individual tools afterwards to adjust, e.g. set_channel_settings for squelch or volume. Modes whose output " + "goes to a feature add it too: ais adds the AIS feature, sonde the Radiosonde feature and aprs the APRS feature, whose " + "reports and map items carry what was decoded; a later listen or scan removes the feature again once nothing it added " + "feeds it. ais is received on two channels, so give 162000000 and it puts a demodulator on each of 161.975 and " + "162.025 MHz.", + schema({ + {"frequency", numProp("Frequency to receive in Hz, e.g. 97300000 for 97.3 MHz")}, + {"mode", strProp("bfm (broadcast FM with stereo and RDS), wfm, nfm, am or airband, ssb/usb, lsb, dab, adsb, ais, dsc, dsd/dmr, " + "dmr, dpmr, dstar, ysf, nxdn or nxdn24 (digital voice through the DSD demodulator with the deviation and baud rate of that standard), " + "pager (POCSAG), sonde (RS41 radiosondes), packet (AX.25), aprs (APRS with its feature), or any channel type id from list_channel_types. Default nfm")}, + {"device", strProp(deviceHint)}, + {"replace", prop("boolean", "Retune the demodulator a previous listen added to this device set when it is of the same type, and remove every other channel earlier listen and scan calls added there, so that exploring a band does not leave a trail of demodulators all playing audio and mis-tuned for the current centre frequency. Channels added any other way are kept on their frequency where the baseband still holds them; audio demodulators it cannot hold are removed, anything else is left and named. Default true")}, + {"tuneGain", prop("boolean", "Measure and set the receiver gain, as tune_gain does, when the device set is new or the retune is to another band (more than a tenth of the frequency away). Adds several seconds in those cases and none otherwise. false leaves the gain as it is. Default true")} + }, {"frequency"}), + [this](const QJsonObject& args) + { + qint64 frequency = (qint64) argDouble(args, "frequency"); + QString modeName = argString(args, "mode", false, "nfm").trimmed(); + const ListenMode *mode = findListenMode(modeName); + QString channelType; + int rfBandwidth = 0; + int minBaseband = 256000; + QJsonObject initial; + QString companionFeature; + int pairOffset = 0; + + if (mode) + { + channelType = mode->m_channelType; + rfBandwidth = mode->m_rfBandwidth; + minBaseband = mode->m_minBaseband; + initial = QJsonDocument::fromJson(mode->m_settings).object(); + companionFeature = mode->m_feature ? QString(mode->m_feature) : QString(); + pairOffset = mode->m_pairOffset; + } + else + { + for (const QString& id : channelTypeIds(0)) + { + if (id.compare(modeName, Qt::CaseInsensitive) == 0) { + channelType = id; + } + } + + if (channelType.isEmpty()) { + throw MCPToolError(QString("Unknown mode %1. Use one of %2, or a channel type from list_channel_types").arg(modeName).arg(listenModeList)); + } + } + + const bool replace = argBool(args, "replace", true); + const bool wantTuneGain = argBool(args, "tuneGain", true); + QJsonObject receiver = pickReceiver(args, minBaseband, replace ? intentChannels() : QSet(), !wantTuneGain); + int deviceSetIndex = receiver["deviceSetIndex"].toInt(); + + // A device set this call created and cannot finish is taken away again, or a retry + // would build another beside it + NewDeviceSetGuard newDeviceSet(this, receiver["reused"].toBool() ? -1 : deviceSetIndex); + int baseband = receiver["baseband"].toInt(); + + // Keep the channel off the device's DC spike when the baseband has room for it: far + // enough that the spike falls outside the channel, or not at all. A spike inside a + // wide FM channel is an interferer 25 kHz from the carrier, which is worse than one + // on the carrier itself + int offset = 0; + + if ((pairOffset == 0) && (rfBandwidth != 0) && (baseband > 0)) + { + const int clear = qAbs(rfBandwidth) / 2 + 25000; // spike 25 kHz beyond the channel edge + + if (baseband / 2 >= clear + qAbs(rfBandwidth) / 2) { + offset = -clear; + } + } + + // A paired mode, such as AIS on 161.975 and 162.025 MHz, centres the device on the + // frequency asked for and puts a demodulator either side of it + const qint64 centre = (pairOffset != 0) ? frequency : frequency - offset; + + if (pairOffset != 0) { + offset = -pairOffset; + } + + // A demodulator of the right type that a previous listen added is retuned rather + // than replaced; anything else the intent tools added goes as before + int channelIndex = -1; + uint64_t channel = replace ? reusableIntentChannel(deviceSetIndex, channelType, channelIndex, pairOffset != 0 ? 2 : 1) : 0; + const bool retuned = channel != 0; + + // A paired mode keeps its other demodulator through the reclaim as well + QSet kept; + + if (retuned) + { + kept.insert(channel); + + if (pairOffset != 0) + { + for (const ChannelNote& note : channelNotes(deviceSetIndex, {channel})) + { + if (note.m_intent && (note.m_id == channelType)) + { + kept.insert(note.m_uid); + break; + } + } + } + } + + const QStringList reclaimed = replace ? reclaimIntentChannels(deviceSetIndex, kept) : QStringList(); + const QStringList reclaimedFeatures = replace ? reclaimIntentFeatures(companionFeature) : QStringList(); + + // The device is retuned only once the reclaim is done: a scanner an earlier scan + // left running would otherwise step the device on again between the two, and the + // demodulator would be added against a centre the scanner chose + QJsonObject tune; + tune["centerFrequency"] = (double) centre; + patchDeviceSettings(deviceSetIndex, tune); + const RetuneOutcome outcome = receiver["reused"].toBool() + ? retuneOtherChannels(deviceSetIndex, receiver["previousCentre"].toDouble(), (double) centre, baseband) + : RetuneOutcome(); + + if (retuned) + { + // The reclaim may have renumbered it + relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); + } + else + { + channelIndex = addChannelAndWait(deviceSetIndex, channelType); + channel = channelUidAt(deviceSetIndex, channelIndex); + trackIntentChannel(channel); + } + + initial["inputFrequencyOffset"] = offset; + + if (rfBandwidth != 0) { + initial["rfBandwidth"] = rfBandwidth; + } + + QJsonObject patched; + QString state; + + // Do not leave a half configured channel behind if setting it up fails. One that was + // there already stays, as the previous listen left it + try + { + patched = patchChannelSettings(deviceSetIndex, channelIndex, initial); + state = deviceState(deviceSetIndex, 0, 1)["state"].toString(); + } + catch (const MCPToolError&) + { + if (!retuned) + { + try { deleteChannelObjectAndWait(channel); } catch (const MCPToolError&) {} + untrackIntentChannel(channel); + } + + throw; + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["channelIndex"] = channelIndex; + result["device"] = receiver["device"]; + result["frequency"] = (double) frequency; + result["mode"] = modeName; + result["channelType"] = channelType; + result["state"] = state; + QStringList notes; + + if (retuned) + { + result["retuned"] = true; + notes.append(QString("Retuned the %1 a previous listen added to device set %2 rather than adding another; its other settings are as they were.") + .arg(channelType).arg(deviceSetIndex)); + } + + // The second demodulator of a paired mode, on the other channel. A retuned first + // one may already have its partner from the previous listen; a fresh one needs it + uint64_t partner = 0; + + if (pairOffset != 0) + { + int partnerIndex = -1; + + for (const ChannelNote& note : channelNotes(deviceSetIndex, {channel})) + { + if (note.m_intent && (note.m_id == channelType)) + { + partnerIndex = note.m_index; + partner = note.m_uid; + break; + } + } + + if (partner == 0) + { + partnerIndex = addChannelAndWait(deviceSetIndex, channelType); + partner = channelUidAt(deviceSetIndex, partnerIndex); + trackIntentChannel(partner); + } + + QJsonObject partnerSettings = initial; + partnerSettings["inputFrequencyOffset"] = pairOffset; + + try + { + patchChannelSettings(deviceSetIndex, partnerIndex, partnerSettings); + } + catch (const MCPToolError& e) + { + notes.append(QString("The second %1 could not be configured: %2").arg(channelType).arg(e.message)); + } + + relocateChannel(partner, deviceSetIndex, partnerIndex, "second demodulator"); + relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); + result["channelIndex"] = channelIndex; + result["secondChannelIndex"] = partnerIndex; + QJsonArray frequencies; + frequencies.append((double) (frequency - pairOffset)); + frequencies.append((double) (frequency + pairOffset)); + result["frequencies"] = frequencies; + notes.append(QString("%1 is received on two channels, so there are two %2: channel %3 on %4 MHz and channel %5 on %6 MHz, with the device centred between them.") + .arg(modeName.toUpper()).arg(channelType).arg(channelIndex).arg((frequency - pairOffset) / 1e6, 0, 'f', 3) + .arg(partnerIndex).arg((frequency + pairOffset) / 1e6, 0, 'f', 3)); + } + + // The feature the mode's output goes to, so that the decoded data has somewhere to be + // read from and shown + if (!companionFeature.isEmpty()) + { + try + { + int featureIndex = -1; + const int added = ensureFeature(companionFeature, featureIndex); + result["featureIndex"] = featureIndex; + result["featureType"] = companionFeature; + notes.append(added + ? QString("Added the %1 feature (F%2), which collects what the demodulator decodes; get_feature_report reads it, and it feeds the map.").arg(companionFeature).arg(featureIndex) + : QString("The %1 feature (F%2) is already there and collects what the demodulator decodes.").arg(companionFeature).arg(featureIndex)); + } + catch (const MCPToolError& e) + { + notes.append(QString("The %1 feature could not be added: %2").arg(companionFeature).arg(e.message)); + } + } + + if (state == "running") + { + // A new device set, or one moved to another band, has no gain to speak of yet + if (wantTuneGain && gainWorthTuning(receiver["reused"].toBool(), receiver["previousCentre"].toDouble(), (double) centre)) + { + QJsonObject gainArgs; + gainArgs["deviceSetIndex"] = deviceSetIndex; + gainArgs["frequency"] = (double) frequency; + gainArgs["bandwidth"] = (double) (rfBandwidth != 0 ? qAbs(rfBandwidth) : 2000000); + gainArgs["steps"] = 6; + + try + { + QJsonObject tuned = tuneGain(gainArgs); + QJsonObject gain; + gain["key"] = tuned["gainKey"]; + gain["value"] = tuned["chosen"]; + gain["unit"] = tuned["unit"]; + gain["snrDb"] = tuned["bestSnrDb"]; + result["gain"] = gain; + notes.append(QString("Gain measured and set to %1 (%2), judged by %3, as %4%5; tune_gain shows the table, and tuneGain false leaves the gain alone.") + .arg(tuned["chosen"].toDouble()).arg(tuned["unit"].toString()).arg(tuned["judgedBy"].toString()) + .arg(receiver["reused"].toBool() ? "the retune was to another band" : "the device set is new") + .arg(tuned["autoscaled"].toBool() ? ", and the spectrum autoscaled to suit it" : "")); + } + catch (const MCPToolError& e) + { + notes.append(QString("The gain was not measured: %1").arg(e.message)); + } + } + + pause(1500); + // The channel may have been renumbered while we waited + relocateChannel(channel, deviceSetIndex, channelIndex, "demodulator"); + result["deviceSetIndex"] = deviceSetIndex; + result["channelIndex"] = channelIndex; + + // The power measurement sits at the channel's floor until the demodulator has run + // for a moment, and a floor reading looks exactly like an empty band. Wait for a + // real one: reporting the floor has sent callers away from a signal that was + // decoding perfectly well. CalcDb::dbPower returns 10*log10(floor) while there is + // nothing to measure, which is -100 dB or below for every floor in use here + double db = 0.0; + bool measured = false; + bool noReport = false; + QElapsedTimer settling; + settling.start(); + + while (true) + { + QJsonObject report; + + // A demodulator with no report at all (APT, ATV) is not a failure of the + // receiver that was just built + try + { + report = channelReport(deviceSetIndex, channelIndex); + } + catch (const MCPToolError&) + { + noReport = true; + break; + } + + if (signalLevel(report, db)) + { + measured = true; + + if (db > -100.0) { + break; + } + } + + if (settling.elapsed() > 4000) { + break; + } + + pause(250); + } + + if (noReport) + { + notes.append(QString("%1 has no channel report, so there is no signal level to give; %2.") + .arg(channelType) + .arg(companionFeature.isEmpty() ? QString("get_spectrum_data shows whether there is a signal") + : QString("what it decodes appears in the %1 feature's report and in get_packets").arg(companionFeature))); + } + else if (measured) + { + result["signalDb"] = db; + + if (db <= -100.0) { + notes.append("signalDb is still at the measurement floor, which usually means the channel " + "has not settled rather than that the band is empty. Read get_channel_report again in " + "a few seconds before concluding nothing is there."); + } + } + } + else + { + notes.append("The device did not start. If another device set holds the same hardware, stop it first, or pass a different device."); + } + + if (baseband > 0) { + result["basebandSampleRate"] = baseband; + } else { + notes.append(QString("The sample rate of a %1 was left as configured; check it exceeds %2 S/s with get_device_settings.").arg(receiver["hwType"].toString()).arg(minBaseband)); + } + + if (!receiver["rateNote"].toString().isEmpty()) { + notes.append(receiver["rateNote"].toString()); + } + + notes.append(intentNotes(deviceSetIndex, partner ? QSet({channel, partner}) : QSet({channel}), + reclaimed, receiver["reused"].toBool(), + receiver["previousCentre"].toDouble(), (double) centre, outcome)); + notes.append(featureNotes(reclaimedFeatures)); + + if (patched.contains("warning")) { + notes.append(patched["warning"].toString()); + } + + if (!notes.isEmpty()) { + result["note"] = notes.join(" "); + } + + newDeviceSet.keep(); + return result; + }); + + QJsonObject frequencyList = prop("array", "Frequencies to scan in Hz. Alternatively give startFrequency, stopFrequency and stepFrequency"); + QJsonObject items; + items["type"] = "number"; + frequencyList["items"] = items; + + add("scan", + "Scan a set of frequencies for activity and listen to whichever is active, in one call: sets up a receiver, a demodulator " + "and a Frequency Scanner, starts scanning, watches for a while and reports what it found. active lists every frequency " + "above the threshold with its level, strongest first; that is the list to use for stations and other continuous " + "signals. heard lists where the scanner parked and for how long, which only tells intermittent signals apart, since " + "on a continuous carrier it parks on the first and stays. " + "The scanner keeps running afterwards; get_channel_report on the scanner channel shows its state (2 scanning, 3 receiving, " + "4 holding), channel_action {\"run\": 0} stops it. The demodulator and scanner it added stay on the device set until the " + "next listen or scan there replaces them, or cleanup removes them; they are not removed when this call returns. " + "Blocks for the watch period, so it is capped at 30 seconds.", + schema({ + {"frequencies", frequencyList}, + {"startFrequency", numProp("Start of a range in Hz, with stopFrequency and stepFrequency")}, + {"stopFrequency", numProp("End of the range in Hz, inclusive")}, + {"stepFrequency", numProp("Channel spacing in Hz. Optional: without it the spacing usual for the mode is used (bfm 100 kHz, am 25 kHz, " + "nfm/dsd/pager 12.5 kHz, sonde 10 kHz, ssb 3 kHz), which is the right choice unless the band is known to differ, " + "e.g. 8333 for airband 8.33 kHz channels in Europe. Broadcast FM stations sit on a 100 kHz raster everywhere; only " + "the Americas confine them to the odd tenths, so bfm/wfm ranges are scanned at 100 kHz whatever step is given")}, + {"mode", strProp("Demodulator, as for listen: bfm, wfm, nfm, am, ssb/usb/lsb, dsd, pager, sonde. Modes on fixed frequencies (adsb, ais, " + "dab, dsc) cannot be scanned for; listen to those directly. Default am")}, + {"threshold", numProp("Power in dB above which a frequency counts as active. Leave it out unless you have a reason: the scale " + "depends on the device and its gain, so by default the noise floor is measured first and the threshold set " + "12 dB above it. Both are reported, so a second scan can adjust")}, + {"seconds", bounded(numProp("How long to watch before replying, 3 to 30. Default 10"), 3, 30)}, + {"device", strProp(deviceHint)}, + {"replace", prop("boolean", "Remove every channel earlier listen and scan calls added to this device set first, as listen does. Channels added any other way are kept on their frequency where the baseband still holds them; audio demodulators it cannot hold are removed, anything else is left and named. Default true")}, + {"tuneGain", prop("boolean", "Measure and set the receiver gain first, as tune_gain does, when the device set is new or the retune is to another band. Adds several seconds in those cases and none otherwise. false leaves the gain as it is. Default true")} + }), + [this](const QJsonObject& args) + { + QList frequencies; + const bool fromRange = !hasArg(args, "frequencies"); + qint64 rangeStart = 0; + qint64 rangeStop = 0; + qint64 rangeStep = 0; // as given; zero to step by the mode's usual channel spacing + + if (fromRange) + { + rangeStart = (qint64) argDouble(args, "startFrequency"); + rangeStop = (qint64) argDouble(args, "stopFrequency"); + rangeStep = hasArg(args, "stepFrequency") ? (qint64) argDouble(args, "stepFrequency") : 0; + + if ((rangeStep < 0) || (rangeStop < rangeStart)) { + throw MCPToolError("stepFrequency must be positive and stopFrequency at least startFrequency"); + } + } + else + { + for (const QJsonValue& v : args["frequencies"].toArray()) { + frequencies.append((qint64) v.toDouble()); + } + + if (frequencies.isEmpty()) { + throw MCPToolError("Give frequencies, or startFrequency and stopFrequency"); + } + } + + QString modeName = argString(args, "mode", false, "am").trimmed(); + const ListenMode *mode = findListenMode(modeName); + + if (!mode) { + throw MCPToolError(QString("Unknown mode %1. Use one of %2").arg(modeName).arg(listenModeList)); + } + + // A mode on fixed frequencies has nothing to be found by stepping + if (mode->m_scanStep == 0) + { + throw MCPToolError(QString("%1 is received on fixed frequencies, so there is nothing to scan for: listen to them directly. " + "get_receiving_guide lists them (ADS-B 1090 MHz; AIS 161.975 and 162.025 MHz; DSC 2187.5 kHz, 8414.5 kHz, " + "16804.5 kHz and 156.525 MHz; DAB on the Band III blocks, one dab channel per block).").arg(mode->m_channelType)); + } + + // Without a threshold, measure the noise floor first and sit 12 dB above it: the + // level scale depends on the device and its gain, so no fixed number suits all + bool autoThreshold = !hasArg(args, "threshold"); + double threshold = autoThreshold ? -100.0 : argDouble(args, "threshold"); + int seconds = qBound(3, (int) argDouble(args, "seconds", false, 10.0), 30); + int channelBandwidth = qAbs(mode->m_rfBandwidth) > 0 ? qAbs(mode->m_rfBandwidth) : 8000; + + // Broadcast FM stations sit on a 100 kHz raster everywhere but the Americas, where + // they keep to the odd tenths. A 200 kHz step from 87.5 MHz, the usual assumption, + // lands beside every even-tenth station: with a channel this wide the station still + // shows up, 100 kHz off and weaker, and then nothing decodes. So a coarser step on + // a broadcast range is scanned at 100 kHz, which loses nothing where the odd tenths + // are the rule + const bool broadcast = (mode->m_channelType == "BFMDemod") || (mode->m_channelType == "WFMDemod"); + QString rasterNote; + + if (fromRange) + { + qint64 step = (rangeStep > 0) ? rangeStep : mode->m_scanStep; + + if (broadcast && (step > 100000)) + { + step = 100000; + rasterNote = QString("Scanned at 100 kHz rather than the %1 kHz step given: broadcast FM stations are on a 100 kHz raster " + "outside the Americas, and a coarser step lands beside them rather than on them.").arg(rangeStep / 1000.0, 0, 'g', 4); + } + else if (rangeStep > mode->m_scanStep) + { + rasterNote = QString("The %1 kHz step given is coarser than the %2 kHz channel spacing usual for %3, so channels between the steps were not seen.") + .arg(rangeStep / 1000.0, 0, 'g', 4).arg(mode->m_scanStep / 1000.0, 0, 'g', 4).arg(modeName); + } + else if (rangeStep == 0) + { + rasterNote = QString("Stepped by %1 kHz, the channel spacing usual for %2; give stepFrequency for another.") + .arg(step / 1000.0, 0, 'g', 4).arg(modeName); + } + + // Counted before it is built: a step given in kHz by mistake, 12 Hz for 12.5, + // would otherwise fill millions of entries before the limit was looked at + const qint64 count = (rangeStop - rangeStart) / step + 1; + + if (count > 2000) { + throw MCPToolError(QString("%1 frequencies is too many; use a coarser step or a narrower range (2000 at most)").arg(count)); + } + + for (qint64 f = rangeStart; f <= rangeStop; f += step) { + frequencies.append(f); + } + } + + if (frequencies.size() > 2000) { + throw MCPToolError(QString("%1 frequencies is too many; use a coarser step or a narrower range (2000 at most)").arg(frequencies.size())); + } + + std::sort(frequencies.begin(), frequencies.end()); + + // A wide baseband means fewer retunes per sweep + const bool replace = argBool(args, "replace", true); + const bool wantTuneGain = argBool(args, "tuneGain", true); + QJsonObject receiver = pickReceiver(args, 2400000, replace ? intentChannels() : QSet(), !wantTuneGain); + int deviceSetIndex = receiver["deviceSetIndex"].toInt(); + NewDeviceSetGuard newDeviceSet(this, receiver["reused"].toBool() ? -1 : deviceSetIndex); + + // The reclaim comes before the retune: a scanner an earlier scan left running would + // otherwise move the device again between the two + const QStringList reclaimed = replace ? reclaimIntentChannels(deviceSetIndex) : QStringList(); + const QStringList reclaimedFeatures = replace ? reclaimIntentFeatures() : QStringList(); + QJsonObject tune; + tune["centerFrequency"] = (double) ((frequencies.first() + frequencies.last()) / 2); + patchDeviceSettings(deviceSetIndex, tune); + const RetuneOutcome outcome = receiver["reused"].toBool() + ? retuneOtherChannels(deviceSetIndex, receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble(), receiver["baseband"].toInt()) + : RetuneOutcome(); + + int demod = addChannelAndWait(deviceSetIndex, mode->m_channelType); + const uint64_t demodChannel = channelUidAt(deviceSetIndex, demod); + trackIntentChannel(demodChannel); + int scanner = -1; + uint64_t scannerChannel = 0; + + // Anything that fails from here on removes both channels rather than leaving a + // half built scanner running on the user's radio + auto discard = [&]() + { + if (scannerChannel != 0) + { + try { deleteChannelObjectAndWait(scannerChannel); } catch (const MCPToolError&) {} + untrackIntentChannel(scannerChannel); + } + + try { deleteChannelObjectAndWait(demodChannel); } catch (const MCPToolError&) {} + untrackIntentChannel(demodChannel); + }; + + try + { + QJsonObject initial = QJsonDocument::fromJson(mode->m_settings).object(); + initial["inputFrequencyOffset"] = 0; + + if (mode->m_rfBandwidth != 0) { + initial["rfBandwidth"] = mode->m_rfBandwidth; + } + + patchChannelSettings(deviceSetIndex, demod, initial); + scanner = addChannelAndWait(deviceSetIndex, "FreqScanner"); + scannerChannel = channelUidAt(deviceSetIndex, scanner); + trackIntentChannel(scannerChannel); + } + catch (const MCPToolError&) + { + discard(); + throw; + } + + // Everything up to the scanner running with its threshold is set up, and a failure + // anywhere in it, the device not starting, the scanner refusing its settings or + // its run action, or measuring nothing, removes both channels the same way + QString gainNote; + double measuredFloor = 0.0; + bool haveFloor = false; + + try + { + QString state = deviceState(deviceSetIndex, 0, 1)["state"].toString(); + + if (state != "running") { + throw MCPToolError(QString("The device did not start (state %1), so the demodulator and scanner were removed again.").arg(state)); + } + + // Before the scanner measures anything: the gain sets the floor it measures against + if (wantTuneGain && gainWorthTuning(receiver["reused"].toBool(), receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble())) + { + QJsonObject gainArgs; + gainArgs["deviceSetIndex"] = deviceSetIndex; + gainArgs["steps"] = 6; + + try + { + QJsonObject tuned = tuneGain(gainArgs); + gainNote = QString("Gain measured and set to %1 (%2) first, as %3%4; tuneGain false leaves it alone.") + .arg(tuned["chosen"].toDouble()).arg(tuned["unit"].toString()) + .arg(receiver["reused"].toBool() ? "the retune was to another band" : "the device set is new") + .arg(tuned["autoscaled"].toBool() ? ", and the spectrum autoscaled to suit it" : ""); + } + catch (const MCPToolError& e) + { + gainNote = QString("The gain was not measured: %1").arg(e.message); + } + } + + // The scanner's baseband only takes settings while it is running, so configure it + // after the device has started + pause(1500); + relocateChannel(demodChannel, deviceSetIndex, demod, "demodulator"); + relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); + QJsonArray list; + + for (qint64 f : frequencies) + { + QJsonObject entry; + entry["frequency"] = (double) f; + entry["enabled"] = 1; + list.append(entry); + } + + QJsonObject scannerSettings; + scannerSettings["channel"] = QString("R%1:%2").arg(deviceSetIndex).arg(demod); + scannerSettings["channelBandwidth"] = channelBandwidth; + scannerSettings["channelFrequencyOffset"] = 25000; + scannerSettings["threshold"] = threshold; + scannerSettings["scanTime"] = 0.1; + scannerSettings["tuneTime"] = 250; + scannerSettings["retransmitTime"] = 2.5; + scannerSettings["priority"] = 0; + scannerSettings["measurement"] = 0; + scannerSettings["mode"] = autoThreshold ? 2 : 1; // scan only while measuring, else continuous + scannerSettings["frequencies"] = list; + patchChannelSettings(deviceSetIndex, scanner, scannerSettings); + QJsonObject run; + run["run"] = 1; + postChannelAction(deviceSetIndex, scanner, run); + + if (autoThreshold) + { + // The power scale depends on the device and its gain, so the only threshold that + // is right everywhere is one measured here: the median over the frequencies is + // the floor, as most of any band is empty. Wait for the first sweep to have + // measured every frequency rather than guess after a fixed time; a long list + // at a low sample rate takes a while + QList powers; + + for (int attempt = 0; (attempt < 30) && (powers.size() < frequencies.size()); attempt++) + { + pause(500); + relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); + powers.clear(); + + for (const QJsonValue& v : channelReport(deviceSetIndex, scanner)["FreqScannerReport"].toObject()["channelState"].toArray()) + { + QJsonObject s = v.toObject(); + + if (s.contains("power")) { + powers.append(s["power"].toDouble()); + } + } + } + + if (powers.isEmpty()) { + throw MCPToolError("The scanner measured nothing in 15 seconds, so no threshold could be set. " + "Check the device is running and producing samples, or give threshold explicitly."); + } + + std::sort(powers.begin(), powers.end()); + measuredFloor = powers[powers.size() / 2]; + haveFloor = true; + threshold = measuredFloor + 12.0; + + // Changing the mode restarts the scan with the new threshold + QJsonObject arm; + arm["threshold"] = threshold; + arm["mode"] = 1; + patchChannelSettings(deviceSetIndex, scanner, arm); + } + } + catch (const MCPToolError&) + { + discard(); + throw; + } + + // Watch: where it parks, and how strong each channel got + QMap heard; + QMap strongest; + + for (int i = 0; i < seconds; i++) + { + pause(1000); + relocateChannel(scannerChannel, deviceSetIndex, scanner, "scanner"); + relocateChannel(demodChannel, deviceSetIndex, demod, "demodulator"); + QJsonObject report = channelReport(deviceSetIndex, scanner)["FreqScannerReport"].toObject(); + int scanState = report["scanState"].toInt(); + + for (const QJsonValue& v : report["channelState"].toArray()) + { + QJsonObject s = v.toObject(); + qint64 f = (qint64) s["frequency"].toDouble(); + strongest[f] = qMax(strongest.value(f, -999.0), s["power"].toDouble()); + } + + if ((scanState == 3) || (scanState == 4)) + { + // One snapshot for both halves of the sum: read separately, a retune + // between them would pair a new centre with an old offset + QJsonObject set = getDeviceSet(deviceSetIndex); + qint64 centre = (qint64) set["samplingDevice"].toObject()["centerFrequency"].toDouble(); + + for (const QJsonValue& v : set["channels"].toArray()) + { + QJsonObject ch = v.toObject(); + + if (ch["index"].toInt() == demod) { + heard[centre + (qint64) ch["deltaFrequency"].toDouble()] += 1; + } + } + } + } + + QJsonObject result; + result["deviceSetIndex"] = deviceSetIndex; + result["demodChannelIndex"] = demod; + result["scannerChannelIndex"] = scanner; + result["device"] = receiver["device"]; + result["frequencies"] = frequencies.size(); + result["threshold"] = threshold; + result["secondsWatched"] = seconds; + + // A channel this wide takes in a station on the neighbouring raster steps as well, + // weaker and off frequency, so of the neighbours within a channel of each other + // only the strongest is a station; the rest are its skirts + auto isLocalPeak = [&](qint64 f) + { + const double power = strongest.value(f, -999.0); + + for (auto it = strongest.lowerBound(f - channelBandwidth); (it != strongest.end()) && (it.key() <= f + channelBandwidth); ++it) + { + if ((it.key() != f) && ((it.value() > power) || ((it.value() == power) && (it.key() < f)))) { + return false; + } + } + + return true; + }; + + QList> byTime; + for (auto it = heard.begin(); it != heard.end(); ++it) { if (isLocalPeak(it.key())) { byTime.append(qMakePair(it.value(), it.key())); } } + std::sort(byTime.begin(), byTime.end(), [](const QPair& a, const QPair& b) { return a.first > b.first; }); + QJsonArray heardArray; + + for (const auto& p : byTime) + { + QJsonObject h; + h["frequency"] = (double) p.second; + h["seconds"] = p.first; + heardArray.append(h); + } + + result["heard"] = heardArray; + + QList> byPower; + QList allPowers; // every frequency, for the floor estimate + for (auto it = strongest.begin(); it != strongest.end(); ++it) { allPowers.append(it.value()); if (isLocalPeak(it.key())) { byPower.append(qMakePair(it.value(), it.key())); } } + std::sort(byPower.begin(), byPower.end(), [](const QPair& a, const QPair& b) { return a.first > b.first; }); + std::sort(allPowers.begin(), allPowers.end()); + // Everything above the threshold, strongest first: for a band of continuous carriers + // this is the answer, as the scanner parks on the first one it finds and never gets + // to the rest. Capped well above any real band's station count, so that a threshold + // set too low on a long list cannot flood the reply + QJsonArray activeArray; + QJsonArray strongestArray; + static const int activeCap = 100; + + for (int i = 0; i < byPower.size(); i++) + { + QJsonObject s; + s["frequency"] = (double) byPower[i].second; + s["dB"] = byPower[i].first; + + if (i < 5) { + strongestArray.append(s); + } + + if ((byPower[i].first >= threshold) && (activeArray.size() < activeCap)) { + activeArray.append(s); + } + } + + result["active"] = activeArray; + result["activeCount"] = activeArray.size(); + result["strongest"] = strongestArray; + + if (haveFloor) { + result["noiseFloorDb"] = measuredFloor; + } else if (!allPowers.isEmpty()) { + result["noiseFloorDb"] = allPowers[allPowers.size() / 2]; + } + + if (autoThreshold) { + result["thresholdAuto"] = true; + } + + QStringList notes; + + if (!rasterNote.isEmpty()) { + notes.append(rasterNote); + } + + if (!gainNote.isEmpty()) { + notes.append(gainNote); + } + + if (!receiver["rateNote"].toString().isEmpty()) { + notes.append(receiver["rateNote"].toString()); + } + + if (activeArray.isEmpty()) { + notes.append("Nothing exceeded the threshold. Compare threshold with noiseFloorDb and the strongest channels; a second scan with threshold given lowers it."); + } else if (heardArray.isEmpty()) { + notes.append("The scanner did not park on any of the active frequencies while watching; active is still the list of what was found."); + } + + notes.append(intentNotes(deviceSetIndex, {demodChannel, scannerChannel}, reclaimed, receiver["reused"].toBool(), + receiver["previousCentre"].toDouble(), tune["centerFrequency"].toDouble(), outcome)); + notes.append(featureNotes(reclaimedFeatures)); + + if (!notes.isEmpty()) { + result["note"] = notes.join(" "); + } + + newDeviceSet.keep(); + return result; + }); + + add("cleanup", + "Remove the channels that listen and scan added, on one device set or all of them, and the features listen added " + "for them (AIS, Radiosonde, APRS) once nothing feeds them. Each is otherwise left running, every demodulator playing " + "audio, until the next listen or scan on the same device set replaces it. Channels and features added any other way " + "are left alone; delete_channel and delete_feature remove those.", + schema({ + {"deviceSetIndex", intProp("Only this device set. Default: every device set")} + }), + [this](const QJsonObject& args) + { + QList deviceSetIndices; + + if (hasArg(args, "deviceSetIndex")) + { + deviceSetIndices.append(argInt(args, "deviceSetIndex")); + } + else + { + for (const QJsonValue& v : getInstanceSummary()["devicesetlist"].toObject()["deviceSets"].toArray()) { + deviceSetIndices.append(v.toObject()["samplingDevice"].toObject()["index"].toInt()); + } + } + + QJsonArray removed; + int count = 0; + + for (int deviceSetIndex : deviceSetIndices) + { + for (const QString& id : reclaimIntentChannels(deviceSetIndex)) + { + removed.append(QString("R%1:%2").arg(deviceSetIndex).arg(id)); + count++; + } + } + + QJsonArray features; + + for (const QString& id : reclaimIntentFeatures()) + { + features.append(id); + count++; + } + + QJsonObject result; + result["removed"] = count; + result["channels"] = removed; + result["features"] = features; + + if (count == 0) { + result["note"] = "Nothing to remove: no channel or feature added by listen or scan is still there."; + } + + return result; + }); + + add("tune_gain", + "Find the receiver gain that gives the best signal to noise ratio and apply it: steps the device through its gain range " + "and at each step measures the noise floor and the strongest signal on the main spectrum. Too little gain leaves weak " + "signals under the converter's own noise; too much overloads the front end, which raises the floor faster than the " + "signal and adds spurious products, so the best gain is where the difference between them peaks, and of gains within a " + "decibel of that the lowest is taken, for headroom. On a quiet band, where no signal stands clear of the floor, the " + "floor alone decides: the lowest gain at which the antenna's noise rather than the converter's sets it, short of " + "overload. Turns the device's AGC off, as it has to for a manual gain to mean " + "anything. The device must be running. Blocks for a few seconds per step; the reply carries the whole table so the " + "choice can be judged. Give frequency to judge by a particular signal rather than the strongest one. Once the gain " + "is applied the main spectrum is autoscaled to suit it, unless autoscale is false.", + schema({ + {"deviceSetIndex", deviceSetIndexProp}, + {"frequency", numProp("Judge by the signal at this frequency in Hz rather than the strongest in the baseband. It must be inside the baseband")}, + {"bandwidth", numProp("Width in Hz around frequency to look for the signal in. Default 200000")}, + {"steps", bounded(intProp("How many gain values to try, spread over the range. Default 8"), 3, 16)}, + {"apply", prop("boolean", "Apply the chosen gain. false measures and reports but puts the gain back as it was. Default true")}, + {"autoscale", prop("boolean", "Once the chosen gain is applied, set the main spectrum's reference level and range from what it then shows, as spectrum_action autoscale does, so the display suits the new gain. Default true")}, + {"gainKey", strProp("For a device type this does not know: the settings key of its gain, from describe_settings. Then give values too")}, + {"values", prop("array", "For a device type this does not know: the gain values to try, in the key's own units, lowest first")}, + {"agcKey", strProp("For a device type this does not know: the settings key that turns its AGC off when set to 0")} + }, {"deviceSetIndex"}), + [this](const QJsonObject& args) { return tuneGain(args); }); + + add("get_status", + "One line per device set and feature: device, frequency, run state and channels. The cheapest way to see what is going on.", + schema(QJsonObject()), + [this](const QJsonObject&) + { + QJsonObject summary = getInstanceSummary(); + QStringList lines; + + for (const QJsonValue& v : summary["devicesetlist"].toObject()["deviceSets"].toArray()) + { + QJsonObject ds = v.toObject(); + QJsonObject sd = ds["samplingDevice"].toObject(); + QStringList channels; + + for (const QJsonValue& c : ds["channels"].toArray()) + { + QJsonObject ch = c.toObject(); + channels.append(QString("%1 %2%3k").arg(ch["id"].toString()) + .arg(ch["deltaFrequency"].toDouble() >= 0 ? "+" : "").arg(ch["deltaFrequency"].toDouble() / 1000.0, 0, 'f', 1)); + } + + static const char *const prefixes[] = {"R", "T", "M"}; + lines.append(QString("%1%2 %3 %4 %5 MHz %6%7") + .arg(prefixes[qBound(0, sd["direction"].toInt(), 2)]).arg(sd["index"].toInt()) + .arg(sd["hwType"].toString()).arg(sd["serial"].toString()) + .arg(sd["centerFrequency"].toDouble() / 1e6, 0, 'f', 3).arg(sd["state"].toString()) + .arg(channels.isEmpty() ? QString() : ": " + channels.join(", "))); + } + + for (const QJsonValue& v : summary["featureset"].toObject()["features"].toArray()) + { + QJsonObject f = v.toObject(); + int index = f["index"].toInt(); + lines.append(QString("F%1 %2 %3").arg(index).arg(f["id"].toString()).arg(featureState(index, -1)["state"].toString())); + } + + return QJsonValue(lines.isEmpty() ? QString("Nothing configured") : lines.join("\n")); + }); +} diff --git a/plugins/feature/mcpserver/mcptools.h b/plugins/feature/mcpserver/mcptools.h index db2f6bdb8..29cd49bd5 100644 --- a/plugins/feature/mcpserver/mcptools.h +++ b/plugins/feature/mcpserver/mcptools.h @@ -1,299 +1,299 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -#ifndef INCLUDE_FEATURE_MCPTOOLS_H_ -#define INCLUDE_FEATURE_MCPTOOLS_H_ - -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#include "mcperror.h" -#include "mcpdocs.h" -#include "mcpdatafeed.h" -#include "mcpcapture.h" - -//!< A settings definition's properties, read from the swagger YAML that describe_settings serves. -//!< The current value of a setting cannot serve this purpose: generated SWG objects omit empty -//!< strings, so a blank setting is indistinguishable from a key that does not exist -struct SettingsSchema -{ - bool m_known = false; //!< False when the definition was not found, so nothing can be judged - QMap m_types; //!< Property name -> YAML type: integer, number, string, array or object -}; - -class WebAPIAdapterInterface; -class MCPStreams; -class DeviceAPI; -class ChannelAPI; -class Feature; - -namespace SWGSDRangel { - class SWGObject; - class SWGErrorResponse; -} - -// Counts MainCore structural change signals so that tool handlers running on HTTP threads -// can wait for asynchronous operations (which complete on the main thread) to finish. -// Lives in the main thread; the counters are read from other threads. -class MCPEventCounter : public QObject -{ - Q_OBJECT -public: - MCPEventCounter(); - - QAtomicInt m_deviceSetAdded; - QAtomicInt m_deviceSetRemoved; - QAtomicInt m_deviceChanged; - QAtomicInt m_channelAdded; - QAtomicInt m_channelRemoved; - QAtomicInt m_featureAdded; - QAtomicInt m_featureRemoved; - -private slots: - void onDeviceSetAdded(int index, DeviceAPI *device); - void onDeviceSetRemoved(int index); - void onDeviceChanged(int index); - void onChannelAdded(int deviceSetIndex, ChannelAPI *channel); - void onChannelRemoved(int deviceSetIndex, ChannelAPI *channel); - void onFeatureAdded(int featureSetIndex, Feature *feature); - void onFeatureRemoved(int featureSetIndex, Feature *feature); -}; - -// The set of MCP tools that control SDRangel. Everything goes through the -// in-process Web API adapter, so what the tools can do matches the REST API, -// plus waiting for asynchronous operations to complete. -class MCPTools -{ -public: - struct Tool - { - QString name; - QString description; - QJsonObject inputSchema; - std::function handler; - }; - - explicit MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface); - - QJsonArray listTools() const; - QJsonObject callTool(const QString& name, const QJsonObject& arguments); - - // Data also served as resources - QJsonObject getInstanceSummary(); - QJsonObject getAvailableDevices(int direction = -1); //!< -1 for all directions - QJsonObject getAvailableChannels(int direction = -1); - QJsonObject getAvailableFeatures(); - QJsonObject getPresets(); - QJsonObject getConfigurations(); - QJsonObject getDeviceSet(int deviceSetIndex); - int deviceSetCount() const; - QString describeType(const QString& type, const QString& kind); - MCPDocs& docs() { return m_docs; } - MCPDataFeed& dataFeed() { return m_dataFeed; } - MCPCapture& capture() { return m_capture; } - void setStreams(MCPStreams *streams) { m_streams = streams; } - //!< The feature that owns this server, so it can refuse to delete or stop itself - void setOwnerFeature(const QObject *feature) { m_ownerFeature = feature; } - //!< Set by the server, on the main thread, before it waits for the HTTP threads to finish. - //!< Every wait and sleep in the tools then ends at once with a tool error, since the main - //!< thread they would otherwise be waiting on is the one waiting for them - void setStopping(bool stopping); - -private: - WebAPIAdapterInterface *m_adapter; - MCPEventCounter m_events; - MCPDocs m_docs; - MCPDataFeed m_dataFeed; - MCPCapture m_capture; - MCPStreams *m_streams; - - // Creating an object and working out which one is new must not overlap with another - // creation, or two callers snapshot the same state and both claim the same object. - // The capture tools run without the dispatch lock, so this is reachable. - QMutex m_creationMutex; - // Deletion is by index, and the index is resolved just before the delete is posted for - // the main thread to do later. Two calls deleting on one device set unserialised can post - // two indices that were right when read and wrong once the first delete has renumbered - // the rest, taking a channel neither meant. Held from the lookup to the object being gone - QMutex m_deletionMutex; - // The channels listen and scan have added, so that the next of either on the same device - // set can take them away again and cleanup can remove them all. Held by uid rather than - // pointer: a channel removed from the GUI frees its address for the next one created, - // which must not then be taken for one of these. They run without the dispatch lock, so - // this has a lock of its own, which is never held across addChannelAndWait or a delete: - // those take m_creationMutex or wait - QMutex m_intentMutex; - QSet m_intentChannels; - // The features listen added for a mode's output (AIS, Radiosonde, APRS), removed again once no - // channel it added still feeds them. A feature that was already there is never among these - QSet m_intentFeatures; - const QObject *m_ownerFeature; - QAtomicInt m_stopping; - QList m_tools; - // The definitions are loaded on first use and the parsed schemas cached as they are asked - // for, from whichever thread asks. The settings tools run under the dispatch lock but - // listen and scan do not, and they patch settings too, so these have a lock of their own, - // taken by describeType and settingsSchema; the helpers they call expect it held - QMutex m_schemaMutex; - QMap m_yamlDefinitions; //!< Swagger definition name -> YAML text - QMap m_yamlDefinitionsByLower; //!< Lower cased name -> the name as written - QMap m_schemaCache; //!< Parsed form of the above, by definition name - bool m_yamlLoaded; - - void add(const QString& name, const QString& description, const QJsonObject& inputSchema, - std::function handler); - - void registerInstanceTools(); - void registerDeviceSetTools(); - void registerChannelTools(); - void registerFeatureTools(); - void registerPresetTools(); - void registerWorkspaceTools(); - void registerCaptureTools(); - void registerIntentTools(); - - //!< Polls until the condition holds, at most timeoutMs. False on timeout; throws when the - //!< server is stopping, as nothing waited for on the main thread will happen then - bool waitFor(const std::function& condition, int timeoutMs = m_waitTimeoutMs) const; - //!< A sleep that a stop cuts short, with the same tool error - void pause(int ms) const; - static const int m_waitTimeoutMs = 5000; - - // Device set helpers - int channelCount(int deviceSetIndex) const; - int featureCount() const; - int deviceSetDirection(int deviceSetIndex); - QJsonObject selectDevice(int deviceSetIndex, const QJsonObject& args); - QJsonObject getDeviceSettings(int deviceSetIndex); - QJsonObject patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial); - int addChannelAndWait(int deviceSetIndex, const QString& channelType); - int addFeatureAndWait(const QString& featureType); - int addDeviceSetAndWait(int direction); - //!< Identity of the current channels, features or device sets, to spot which one is new. - //!< Channels and features are identified by UID throughout: a pointer to one is only ever - //!< good until the next wait, since a deleted object's address is reused by the next one - //!< created, and every tool here waits - QSet channelUids(int deviceSetIndex) const; - QSet featureUids() const; - QSet deviceSetPointers() const; - void deleteChannelAndWait(int deviceSetIndex, int channelIndex); - void deleteChannelLocked(int deviceSetIndex, int channelIndex); //!< With m_deletionMutex held - //!< Removes a device set that listen or scan created and could not finish setting up, if it - //!< is still the last one, which is the only one the API can remove - void discardNewDeviceSet(int deviceSetIndex, uint64_t identity); - //!< What tells one device set from another that has since taken its index: the engine's UID - //!< together with the object's address. Zero when there is no such device set - uint64_t deviceSetIdentity(int deviceSetIndex) const; - friend class NewDeviceSetGuard; - //!< Deletes a channel wherever it has moved to, for callers that held on to it across a wait - void deleteChannelObjectAndWait(uint64_t channelUid); - const void *featureAt(int featureIndex) const; - //!< The UID of the feature or channel at an index, 0 when there is none - uint64_t featureUidAt(int featureIndex) const; - uint64_t channelUidAt(int deviceSetIndex, int channelIndex) const; - void requireNotSelf(int featureIndex, const QString& action) const; - QJsonObject getChannelSettings(int deviceSetIndex, int channelIndex); - QJsonObject patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial); - //!< The property names and types of one settings definition. Used to tell a misspelled key from - //!< a valid one, and to reject a value of the wrong type before it reaches the SWG object - SettingsSchema settingsSchema(const QString& definition); - QString resolveDefinition(const QString& name); //!< Call with m_schemaMutex held - QJsonObject getSpectrumSettings(int deviceSetIndex); - //!< unknownKeys, when given, receives the patch keys the schema does not define - QJsonObject patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys = nullptr); - //!< Explains an rdsReport that is absent because RDS decoding is switched off, rather than - //!< because nothing has been decoded yet - void addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex); - QJsonObject getFeatureSettings(int featureIndex); - QJsonObject patchFeatureSettings(int featureIndex, const QJsonObject& partial); - QJsonObject deviceState(int deviceSetIndex, int subsystemIndex, int run); //!< run: 1 start, 0 stop, -1 query - //!< Empty unless the device set's baseband is too narrow for this channel type - QString basebandWarning(int deviceSetIndex, const QString& channelType); - //!< The same for every channel a device set holds - QStringList basebandWarnings(int deviceSetIndex); - QJsonObject featureState(int featureIndex, int run); - QJsonObject presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave); - - // Shared by the intent level tools - QJsonObject channelReport(int deviceSetIndex, int channelIndex); - void postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions); - //!< doomed: uids of channels the caller is about to remove, which the reused set is not counted as carrying. - //!< profileGain: give a device set this creates the fixed receiver gain profile; false when the gain is about to be measured - QJsonObject pickReceiver(const QJsonObject& args, int minBaseband, const QSet& doomed = QSet(), bool profileGain = true); - //!< The tune_gain tool: sweeps the gain and applies the best, with the table it measured - QJsonObject tuneGain(const QJsonObject& args); - //!< Sets the main spectrum's reference level and range from what it shows, as the GUI's autoscale button does - void autoscaleSpectrum(int deviceSetIndex); - //!< Turns spectrum scrolling on if it is off, which is what keeps the history the spectrum - //!< history tools read. Returns a note when it did, empty otherwise - QString ensureSpectrumHistory(int deviceSetIndex, double seconds); - //!< The index of a feature of this type, adding one if there is none. Returns whether it was added - int ensureFeature(const QString& featureType, int& featureIndex); - void trackIntentFeature(uint64_t featureUid); - //!< Removes the features listen added that no channel it added still feeds, except one of keepType. - //!< Returns the types of those removed - QStringList reclaimIntentFeatures(const QString& keepType = QString()); - //!< Deletes a feature wherever it has been renumbered to - void deleteFeatureObjectAndWait(uint64_t featureUid); - //!< Whether listen or scan should measure the gain: a device set they created, or a retune to another band - static bool gainWorthTuning(bool reused, double previousCentre, double centre); - void trackIntentChannel(uint64_t channelUid); - void untrackIntentChannel(uint64_t channelUid); - QSet intentChannels(); - //!< A channel's type id and whether listen or scan added it, for the notes the intent tools leave - struct ChannelNote { uint64_t m_uid; int m_index; QString m_id; bool m_intent; }; - QList channelNotes(int deviceSetIndex, const QSet& except = QSet()); - //!< Removes the channels listen and scan added to a device set, except keep. Returns the ids of those removed - QStringList reclaimIntentChannels(int deviceSetIndex, const QSet& keep = QSet()); - //!< The channel a previous listen added that a new one of this type can retune instead of replacing, or 0. - //!< wanted: how many of the type the mode uses, 2 for a paired mode - uint64_t reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted = 1); - //!< What a retune of a reused device set did to the channels listen and scan did not add - struct RetuneOutcome - { - QStringList m_kept; //!< Re-offset so that they stay on the frequency they had - QStringList m_removed; //!< Audio demodulators the new baseband could not hold, which would only have made noise - QStringList m_stranded; //!< Left where they were: not audio, or the baseband unknown - }; - RetuneOutcome retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband); - //!< What listen and scan tell the caller about the rest of the device set once their own channels are in - QStringList intentNotes(int deviceSetIndex, const QSet& added, const QStringList& reclaimed, - bool reused, double previousCentre, double centre, const RetuneOutcome& outcome); - //!< Channel type ids for a direction, independent of how list_channel_types formats them - QStringList channelTypeIds(int direction); - //!< Where a channel is now. The intent tools sleep for many seconds without holding the - //!< protocol mutex, and a concurrent request that deletes a lower numbered channel - //!< renumbers everything above it, so their indices have to be resolved again before use. - void relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what); - - void loadYamlDefinitions(); //!< Call with m_schemaMutex held -}; - -#endif // INCLUDE_FEATURE_MCPTOOLS_H_ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_FEATURE_MCPTOOLS_H_ +#define INCLUDE_FEATURE_MCPTOOLS_H_ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "mcperror.h" +#include "mcpdocs.h" +#include "mcpdatafeed.h" +#include "mcpcapture.h" + +//!< A settings definition's properties, read from the swagger YAML that describe_settings serves. +//!< The current value of a setting cannot serve this purpose: generated SWG objects omit empty +//!< strings, so a blank setting is indistinguishable from a key that does not exist +struct SettingsSchema +{ + bool m_known = false; //!< False when the definition was not found, so nothing can be judged + QMap m_types; //!< Property name -> YAML type: integer, number, string, array or object +}; + +class WebAPIAdapterInterface; +class MCPStreams; +class DeviceAPI; +class ChannelAPI; +class Feature; + +namespace SWGSDRangel { + class SWGObject; + class SWGErrorResponse; +} + +// Counts MainCore structural change signals so that tool handlers running on HTTP threads +// can wait for asynchronous operations (which complete on the main thread) to finish. +// Lives in the main thread; the counters are read from other threads. +class MCPEventCounter : public QObject +{ + Q_OBJECT +public: + MCPEventCounter(); + + QAtomicInt m_deviceSetAdded; + QAtomicInt m_deviceSetRemoved; + QAtomicInt m_deviceChanged; + QAtomicInt m_channelAdded; + QAtomicInt m_channelRemoved; + QAtomicInt m_featureAdded; + QAtomicInt m_featureRemoved; + +private slots: + void onDeviceSetAdded(int index, DeviceAPI *device); + void onDeviceSetRemoved(int index); + void onDeviceChanged(int index); + void onChannelAdded(int deviceSetIndex, ChannelAPI *channel); + void onChannelRemoved(int deviceSetIndex, ChannelAPI *channel); + void onFeatureAdded(int featureSetIndex, Feature *feature); + void onFeatureRemoved(int featureSetIndex, Feature *feature); +}; + +// The set of MCP tools that control SDRangel. Everything goes through the +// in-process Web API adapter, so what the tools can do matches the REST API, +// plus waiting for asynchronous operations to complete. +class MCPTools +{ +public: + struct Tool + { + QString name; + QString description; + QJsonObject inputSchema; + std::function handler; + }; + + explicit MCPTools(WebAPIAdapterInterface *webAPIAdapterInterface); + + QJsonArray listTools() const; + QJsonObject callTool(const QString& name, const QJsonObject& arguments); + + // Data also served as resources + QJsonObject getInstanceSummary(); + QJsonObject getAvailableDevices(int direction = -1); //!< -1 for all directions + QJsonObject getAvailableChannels(int direction = -1); + QJsonObject getAvailableFeatures(); + QJsonObject getPresets(); + QJsonObject getConfigurations(); + QJsonObject getDeviceSet(int deviceSetIndex); + int deviceSetCount() const; + QString describeType(const QString& type, const QString& kind); + MCPDocs& docs() { return m_docs; } + MCPDataFeed& dataFeed() { return m_dataFeed; } + MCPCapture& capture() { return m_capture; } + void setStreams(MCPStreams *streams) { m_streams = streams; } + //!< The feature that owns this server, so it can refuse to delete or stop itself + void setOwnerFeature(const QObject *feature) { m_ownerFeature = feature; } + //!< Set by the server, on the main thread, before it waits for the HTTP threads to finish. + //!< Every wait and sleep in the tools then ends at once with a tool error, since the main + //!< thread they would otherwise be waiting on is the one waiting for them + void setStopping(bool stopping); + +private: + WebAPIAdapterInterface *m_adapter; + MCPEventCounter m_events; + MCPDocs m_docs; + MCPDataFeed m_dataFeed; + MCPCapture m_capture; + MCPStreams *m_streams; + + // Creating an object and working out which one is new must not overlap with another + // creation, or two callers snapshot the same state and both claim the same object. + // The capture tools run without the dispatch lock, so this is reachable. + QMutex m_creationMutex; + // Deletion is by index, and the index is resolved just before the delete is posted for + // the main thread to do later. Two calls deleting on one device set unserialised can post + // two indices that were right when read and wrong once the first delete has renumbered + // the rest, taking a channel neither meant. Held from the lookup to the object being gone + QMutex m_deletionMutex; + // The channels listen and scan have added, so that the next of either on the same device + // set can take them away again and cleanup can remove them all. Held by uid rather than + // pointer: a channel removed from the GUI frees its address for the next one created, + // which must not then be taken for one of these. They run without the dispatch lock, so + // this has a lock of its own, which is never held across addChannelAndWait or a delete: + // those take m_creationMutex or wait + QMutex m_intentMutex; + QSet m_intentChannels; + // The features listen added for a mode's output (AIS, Radiosonde, APRS), removed again once no + // channel it added still feeds them. A feature that was already there is never among these + QSet m_intentFeatures; + const QObject *m_ownerFeature; + QAtomicInt m_stopping; + QList m_tools; + // The definitions are loaded on first use and the parsed schemas cached as they are asked + // for, from whichever thread asks. The settings tools run under the dispatch lock but + // listen and scan do not, and they patch settings too, so these have a lock of their own, + // taken by describeType and settingsSchema; the helpers they call expect it held + QMutex m_schemaMutex; + QMap m_yamlDefinitions; //!< Swagger definition name -> YAML text + QMap m_yamlDefinitionsByLower; //!< Lower cased name -> the name as written + QMap m_schemaCache; //!< Parsed form of the above, by definition name + bool m_yamlLoaded; + + void add(const QString& name, const QString& description, const QJsonObject& inputSchema, + std::function handler); + + void registerInstanceTools(); + void registerDeviceSetTools(); + void registerChannelTools(); + void registerFeatureTools(); + void registerPresetTools(); + void registerWorkspaceTools(); + void registerCaptureTools(); + void registerIntentTools(); + + //!< Polls until the condition holds, at most timeoutMs. False on timeout; throws when the + //!< server is stopping, as nothing waited for on the main thread will happen then + bool waitFor(const std::function& condition, int timeoutMs = m_waitTimeoutMs) const; + //!< A sleep that a stop cuts short, with the same tool error + void pause(int ms) const; + static const int m_waitTimeoutMs = 5000; + + // Device set helpers + int channelCount(int deviceSetIndex) const; + int featureCount() const; + int deviceSetDirection(int deviceSetIndex); + QJsonObject selectDevice(int deviceSetIndex, const QJsonObject& args); + QJsonObject getDeviceSettings(int deviceSetIndex); + QJsonObject patchDeviceSettings(int deviceSetIndex, const QJsonObject& partial); + int addChannelAndWait(int deviceSetIndex, const QString& channelType); + int addFeatureAndWait(const QString& featureType); + int addDeviceSetAndWait(int direction); + //!< Identity of the current channels, features or device sets, to spot which one is new. + //!< Channels and features are identified by UID throughout: a pointer to one is only ever + //!< good until the next wait, since a deleted object's address is reused by the next one + //!< created, and every tool here waits + QSet channelUids(int deviceSetIndex) const; + QSet featureUids() const; + QSet deviceSetPointers() const; + void deleteChannelAndWait(int deviceSetIndex, int channelIndex); + void deleteChannelLocked(int deviceSetIndex, int channelIndex); //!< With m_deletionMutex held + //!< Removes a device set that listen or scan created and could not finish setting up, if it + //!< is still the last one, which is the only one the API can remove + void discardNewDeviceSet(int deviceSetIndex, uint64_t identity); + //!< What tells one device set from another that has since taken its index: the engine's UID + //!< together with the object's address. Zero when there is no such device set + uint64_t deviceSetIdentity(int deviceSetIndex) const; + friend class NewDeviceSetGuard; + //!< Deletes a channel wherever it has moved to, for callers that held on to it across a wait + void deleteChannelObjectAndWait(uint64_t channelUid); + const void *featureAt(int featureIndex) const; + //!< The UID of the feature or channel at an index, 0 when there is none + uint64_t featureUidAt(int featureIndex) const; + uint64_t channelUidAt(int deviceSetIndex, int channelIndex) const; + void requireNotSelf(int featureIndex, const QString& action) const; + QJsonObject getChannelSettings(int deviceSetIndex, int channelIndex); + QJsonObject patchChannelSettings(int deviceSetIndex, int channelIndex, const QJsonObject& partial); + //!< The property names and types of one settings definition. Used to tell a misspelled key from + //!< a valid one, and to reject a value of the wrong type before it reaches the SWG object + SettingsSchema settingsSchema(const QString& definition); + QString resolveDefinition(const QString& name); //!< Call with m_schemaMutex held + QJsonObject getSpectrumSettings(int deviceSetIndex); + //!< unknownKeys, when given, receives the patch keys the schema does not define + QJsonObject patchSpectrumSettings(int deviceSetIndex, const QJsonObject& partial, QStringList *unknownKeys = nullptr); + //!< Explains an rdsReport that is absent because RDS decoding is switched off, rather than + //!< because nothing has been decoded yet + void addRdsHint(QJsonObject& report, const QString& channelType, int deviceSetIndex, int channelIndex); + QJsonObject getFeatureSettings(int featureIndex); + QJsonObject patchFeatureSettings(int featureIndex, const QJsonObject& partial); + QJsonObject deviceState(int deviceSetIndex, int subsystemIndex, int run); //!< run: 1 start, 0 stop, -1 query + //!< Empty unless the device set's baseband is too narrow for this channel type + QString basebandWarning(int deviceSetIndex, const QString& channelType); + //!< The same for every channel a device set holds + QStringList basebandWarnings(int deviceSetIndex); + QJsonObject featureState(int featureIndex, int run); + QJsonObject presetIdentifier(const QJsonObject& args, int deviceSetIndex, bool forSave); + + // Shared by the intent level tools + QJsonObject channelReport(int deviceSetIndex, int channelIndex); + void postChannelAction(int deviceSetIndex, int channelIndex, const QJsonObject& actions); + //!< doomed: uids of channels the caller is about to remove, which the reused set is not counted as carrying. + //!< profileGain: give a device set this creates the fixed receiver gain profile; false when the gain is about to be measured + QJsonObject pickReceiver(const QJsonObject& args, int minBaseband, const QSet& doomed = QSet(), bool profileGain = true); + //!< The tune_gain tool: sweeps the gain and applies the best, with the table it measured + QJsonObject tuneGain(const QJsonObject& args); + //!< Sets the main spectrum's reference level and range from what it shows, as the GUI's autoscale button does + void autoscaleSpectrum(int deviceSetIndex); + //!< Turns spectrum scrolling on if it is off, which is what keeps the history the spectrum + //!< history tools read. Returns a note when it did, empty otherwise + QString ensureSpectrumHistory(int deviceSetIndex, double seconds); + //!< The index of a feature of this type, adding one if there is none. Returns whether it was added + int ensureFeature(const QString& featureType, int& featureIndex); + void trackIntentFeature(uint64_t featureUid); + //!< Removes the features listen added that no channel it added still feeds, except one of keepType. + //!< Returns the types of those removed + QStringList reclaimIntentFeatures(const QString& keepType = QString()); + //!< Deletes a feature wherever it has been renumbered to + void deleteFeatureObjectAndWait(uint64_t featureUid); + //!< Whether listen or scan should measure the gain: a device set they created, or a retune to another band + static bool gainWorthTuning(bool reused, double previousCentre, double centre); + void trackIntentChannel(uint64_t channelUid); + void untrackIntentChannel(uint64_t channelUid); + QSet intentChannels(); + //!< A channel's type id and whether listen or scan added it, for the notes the intent tools leave + struct ChannelNote { uint64_t m_uid; int m_index; QString m_id; bool m_intent; }; + QList channelNotes(int deviceSetIndex, const QSet& except = QSet()); + //!< Removes the channels listen and scan added to a device set, except keep. Returns the ids of those removed + QStringList reclaimIntentChannels(int deviceSetIndex, const QSet& keep = QSet()); + //!< The channel a previous listen added that a new one of this type can retune instead of replacing, or 0. + //!< wanted: how many of the type the mode uses, 2 for a paired mode + uint64_t reusableIntentChannel(int deviceSetIndex, const QString& channelType, int& channelIndex, int wanted = 1); + //!< What a retune of a reused device set did to the channels listen and scan did not add + struct RetuneOutcome + { + QStringList m_kept; //!< Re-offset so that they stay on the frequency they had + QStringList m_removed; //!< Audio demodulators the new baseband could not hold, which would only have made noise + QStringList m_stranded; //!< Left where they were: not audio, or the baseband unknown + }; + RetuneOutcome retuneOtherChannels(int deviceSetIndex, double previousCentre, double centre, int baseband); + //!< What listen and scan tell the caller about the rest of the device set once their own channels are in + QStringList intentNotes(int deviceSetIndex, const QSet& added, const QStringList& reclaimed, + bool reused, double previousCentre, double centre, const RetuneOutcome& outcome); + //!< Channel type ids for a direction, independent of how list_channel_types formats them + QStringList channelTypeIds(int direction); + //!< Where a channel is now. The intent tools sleep for many seconds without holding the + //!< protocol mutex, and a concurrent request that deletes a lower numbered channel + //!< renumbers everything above it, so their indices have to be resolved again before use. + void relocateChannel(uint64_t channelUid, int& deviceSetIndex, int& channelIndex, const QString& what); + + void loadYamlDefinitions(); //!< Call with m_schemaMutex held +}; + +#endif // INCLUDE_FEATURE_MCPTOOLS_H_ diff --git a/plugins/feature/mcpserver/readme.md b/plugins/feature/mcpserver/readme.md index 7dc8ba3c6..5e6fe9d0c 100644 --- a/plugins/feature/mcpserver/readme.md +++ b/plugins/feature/mcpserver/readme.md @@ -1,171 +1,171 @@ -

MCP Server Feature Plugin

- -

Introduction

- -This feature exposes SDRangel to AI agents through the [Model Context Protocol](https://modelcontextprotocol.io/) (MCP), so that an assistant such as Claude or ChatGPT/Codex can inspect and control SDRangel: create device sets, select SDR hardware, tune, add demodulators, change settings, read reports, load presets and so on. - -The plugin runs an MCP server using the Streamable HTTP transport. MCP clients connect to `http://address:port/mcp`. - -[Tutorial Video](https://youtu.be/G0FmiX7zwb8) - -

Interface

- -![MCP Server feature plugin GUI](../../../doc/img/MCPServer_plugin.png) - -

1: Start/Stop

- -Starts or stops the MCP server. The button is green when the server is listening and red if it could not listen on the requested address and port. - -

2: Endpoint URL

- -The URL to give to MCP clients. - -

3: Address

- -IP address to listen on. The default of 127.0.0.1 only accepts connections from the local computer. Use 0.0.0.0 to accept connections from any network interface, in which case a token should be set. - -

4: Port

- -TCP port to listen on. The default is 8092. - -

5: Capture directory

- -Directory that the capture tools write IQ and audio files to. It defaults to `SDRangel/captures` under your documents folder. File names given to the capture tools are relative to it, and names that would write outside it are refused, so a connected agent cannot write anywhere else on the machine. - -

6: Token

- -Optional bearer token. When set, clients must send an `Authorization: Bearer ` HTTP header. Leave empty for no authentication. - -

7: Add to Codex

- -Writes this server into Codex's `config.toml`. -Codex reads its configuration at startup, so restart it afterwards. - -

8: Add to Claude Desktop

- -Opens the extension bundle with Claude Desktop, which then shows its own dialog asking whether to install it. - -

9: Status

- -Number of MCP requests served since the server was started and the last request received. - -

Connecting a client

- -

Claude Code

- -For clients that support remote (HTTP) MCP servers, add the endpoint URL directly: - - claude mcp add --transport http sdrangel http://127.0.0.1:8092/mcp - -

Claude Desktop

- -Claude Desktop cannot connect directly to a HTTP server. -Install the SDRangel extension, which carries a small [bridge](bridge/readme.md) that relays the stdio -transport Claude Desktop does support to this server. Press Add to Claude Desktop (8) to hand -it the bundle; on Windows the installer also offers to do this at the end of a fresh install. -Failing either, take `sdrangel--.mcpb` from the release and open it with -Claude Desktop, or drag it onto Settings > Extensions. Set the port in the extension's -settings if it is not the default 8092. - -For other clients that only support local stdio servers, run the same bridge directly, in: - -- Windows: %APPDATA%\Claude\claude_desktop_config.json -- Linux: ~/.config/Claude/claude_desktop_config.json -- macOS: ~/Library/Application Support/Claude/claude_desktop_config.json - -``` - "mcpServers": { - "sdrangel": { - "command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", - "args": ["--port", "8092"] - } - } -``` - -`npx -y mcp-remote http://127.0.0.1:8092/mcp` does the same job for a client that has no -bridge built for its platform, at the cost of needing Node.js installed. - -

ChatGPT/Codex

- -Codex supports the HTTP transport, so does not need a bridge. Press Add to Codex (7) to have the -server's address written to its configuration file, or add the following by hand to: - -- Windows: %USERPROFILE%\.codex\config.toml -- macOS/Linux: ~/.codex/config.toml - -``` - [mcp_servers.sdrangel] - url = "http://127.0.0.1:8092/mcp" -``` - -With a token set, the header goes alongside it: - -``` - [mcp_servers.sdrangel] - url = "http://127.0.0.1:8092/mcp" - http_headers = { "Authorization" = "Bearer " } -``` - -

Tools

- -The intent tools do a whole task in one call: `listen` sets up a receiver on a frequency in a given mode, `scan` sets up a Frequency Scanner over a list or range of frequencies and reports every frequency above the threshold with its level (and, for intermittent signals, where the scanner parked), stepping by the channel spacing usual for the mode unless told otherwise and refusing modes that live on fixed frequencies, and `get_status` returns one line per device set and feature. Both `listen` and `scan` keep track of the channels they add: by default the next of either on the same device set removes them first, so that exploring a band does not leave a trail of demodulators all playing audio, and `cleanup` removes them all. A `listen` that finds a demodulator of the type it needs among them retunes it instead, as a person would, so stepping through a band in one mode keeps one channel open throughout. Both measure and set the receiver gain, as `tune_gain` does, when they create a device set or move one to another band, and leave it alone otherwise or when told `tuneGain` false. A mode whose output goes to a feature (AIS, radiosondes, APRS) has `listen` add that feature when it is absent, and remove it again, along with the channels, once nothing it added feeds it; a feature that was already there is left alone. AIS gets a demodulator on each of its two channels with the device centred between them. Channels added any other way are kept on the frequency they had, by moving their offset, when the retuned baseband still holds them; an audio demodulator it cannot hold is removed, since all it could do is play noise, while anything else (a file sink, an analyser) is left in place and named in the reply. The rest mirror the Web API. Creation tools wait for SDRangel to complete the operation and return the index of the new object; the `set_*` tools reply with only the keys that were changed, since a client carries every reply in its context for the rest of the conversation. - -| Area | Tools | -|------|-------| -| Intent | `listen`, `scan`, `cleanup`, `tune_gain`, `get_status` | -| Discovery | `get_instance_summary`, `list_available_devices`, `list_channel_types`, `list_feature_types`, `describe_settings`, `get_receiving_guide`, `list_docs`, `get_docs`, `list_audio_devices`, `get_location`, `set_location` | -| Device sets | `add_deviceset`, `remove_last_deviceset`, `get_deviceset`, `set_device`, `get_device_settings`, `set_device_settings`, `set_center_frequency`, `start_device`, `stop_device`, `get_device_report`, `device_action`, `get_spectrum_settings`, `set_spectrum_settings`, `get_spectrum_data`, `get_spectrum_history`, `get_waterfall_image`, `spectrum_action` | -| Channels | `add_channel`, `delete_channel`, `get_channel_settings`, `set_channel_settings`, `get_channel_report`, `channel_action` | -| Features | `add_feature`, `delete_feature`, `get_feature_settings`, `set_feature_settings`, `get_feature_report`, `start_feature`, `stop_feature`, `feature_action` | -| Presets | `list_presets`, `load_preset`, `save_preset`, `list_configurations`, `load_configuration`, `save_configuration` | -| Workspaces (GUI only) | `add_workspace`, `delete_empty_workspaces`, `list_windows`, `set_workspace` (move, hide or show a window), `arrange_workspace` | -| Live data | `get_packets`, `clear_packets`, `get_map_items` | -| Capture | `capture_audio`, `record_iq`, `start_iq_recording`, `stop_iq_recording` | -| Server | `get_server_status` (open streams, capture directory and active recordings, data feed sources) | - -Each tool carries MCP annotations: whether it only reads, whether it overwrites state rather than only adding to it, whether repeating it lands in the same place, and whether it reaches beyond this application, which covers commanding the radio and data received from transmitters SDRangel does not control. - -`describe_settings` returns the OpenAPI documentation of the settings, report and actions keys of a device, channel or feature type, so that an agent can learn the valid keys rather than guess them. The `set_*_settings` tools accept a partial settings object containing only the keys to change. - -`get_packets` returns the packets received on the `packets`, `ais` and `radiosonde` message pipes of the packet, ChirpChat, M17, Meshtastic, MeshCore, Inmarsat, AIS and radiosonde demodulators, kept in a buffer of the last 1000. Each packet carries the raw bytes and, where possible, a decode: AIS message type, MMSI, position, course and speed; AX.25 addresses and data with the APRS position and comment; RS41 serial, position and height. `get_map_items` returns the objects that the same channels and features that feed the Map send on the `mapitems` pipe (aircraft, ships, APRS stations, radiosondes, satellites, Sun and Moon, beacons), with the image, text and, on request, the track. Items are removed when their source removes them or is deleted. Both work whether or not a Map or AIS/APRS feature is present. - -`record_iq` records baseband IQ to an `.sdriq` file for a fixed number of seconds and returns the files written; `start_iq_recording` and `stop_iq_recording` do the same without a time limit for longer captures. Both work by adding a File Sink channel to the device set, so the recording has the offset and decimation the tools are given. `capture_audio` records the demodulated audio of a channel to a WAV file, and reports the sample rate, the peak level and whether the audio was silent, which tells an agent that a squelch is closed rather than that nothing is wrong. It works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod and BFMDemod. With `inline` true it also returns the audio as base64, as a mono 16 kHz copy, since MCP clients refuse a tool result over about a megabyte and ten seconds at 48 kHz would exceed that once encoded; the file keeps the full rate. Both blocking tools are capped at 30 seconds so they cannot hold an MCP client's connection open indefinitely. - -`get_receiving_guide` serves a hand written guide in `bandguide.md`: which demodulator and frequency to use for each signal SDRangel can receive, the minimum device sample rate that ADS-B, DAB and broadcast FM need, and the usual reasons nothing is received. Its frequencies come from the plugin readmes, and a test checks that every channel id it names is registered in the build. Edit that file to correct or extend it; it is compiled into the plugin, so re-run cmake after changing it. - -`list_docs` and `get_docs` serve the readme of every plugin registered in the running instance, and the GUI's own pages for what no plugin owns: the spectrum display (`spectrum`, with `spectrummarkers`, `spectrummeasurements` and `spectrumcalibration`), the main spectrum window, audio management, configurations, device user arguments and the transverter dialog. The readmes are compiled into this plugin at build time (re-run cmake after adding a plugin), converted to plain markdown with images removed, and matched to plugin ids by name; the GUI pages are listed in `CMakeLists.txt` and given their ids in `MCPDocs::addGuiDocs`. `get_docs` accepts a plugin id or its displayed name and an optional section heading, so an agent can read just the part it needs from a long document. - -

Event stream

- -A client can be told when a resource changes instead of polling for it. An HTTP GET on the endpoint with `Accept: text/event-stream` opens a Server-Sent Events stream, and `resources/subscribe` asks for a resource on it. Updates arrive as `notifications/resources/updated`, at most once a second per resource so that a busy decoder cannot flood the stream. `sdrangel://instance`, `sdrangel://packets`, `sdrangel://map/items` and `sdrangel://deviceset/{index}` can be subscribed to; the other resources never change. - -`initialize` returns an `Mcp-Session-Id` header. A client that sends it back keeps its own subscriptions and stream, and can end them with an HTTP DELETE. Clients that ignore it share an anonymous session, which works fully for one client at a time. A client keeps one stream: opening a second replaces the first, so a notification is never delivered twice. That applies to clients that send no session id as well, since they already share the anonymous subscriptions. Sessions with no stream are dropped after a day idle, and at most 32 are kept, each with at most 32 subscriptions. Up to eight streams may be open at once, and a stream is closed after ten minutes so that a client which vanished without closing its connection cannot hold a thread forever; clients reconnect. - -

Resources

- -| URI | Content | -|-----|---------| -| `sdrangel://instance` | Instance summary | -| `sdrangel://plugins/devices` | Available sampling devices | -| `sdrangel://plugins/channels` | Available channel types | -| `sdrangel://plugins/features` | Available feature types | -| `sdrangel://presets` | Saved presets | -| `sdrangel://configurations` | Saved configurations | -| `sdrangel://deviceset/{index}` | A device set | -| `sdrangel://schema/{type}` | Settings documentation for a type | -| `sdrangel://packets` | The 100 most recent decoded packets, from a buffer of the last 1000 | -| `sdrangel://map/items` | Objects currently plotted on the map | -| `sdrangel://guide` | The receiving guide | -| `sdrangel://docs` | Index of plugin and GUI documentation with section headings | -| `sdrangel://docs/{kind}/{id}` | A document as markdown, e.g. `sdrangel://docs/channel/ADSBDemod` or `sdrangel://docs/gui/spectrum` | - -

Prompts

- -`setup_receiver`, `record_iq` and `explain_configuration` are prompt templates that guide an agent through common tasks. - -

Security

- -The server has no access control beyond the optional bearer token, and an agent connected to it can change anything in SDRangel. Keep the address at 127.0.0.1 unless a token is set. - -To keep web pages from driving the server through a browser, requests carrying an `Origin` header are only accepted from an `http` or `https` localhost origin (the opaque `null` origin is rejected), and the request body must be declared as `application/json`. - +

MCP Server Feature Plugin

+ +

Introduction

+ +This feature exposes SDRangel to AI agents through the [Model Context Protocol](https://modelcontextprotocol.io/) (MCP), so that an assistant such as Claude or ChatGPT/Codex can inspect and control SDRangel: create device sets, select SDR hardware, tune, add demodulators, change settings, read reports, load presets and so on. + +The plugin runs an MCP server using the Streamable HTTP transport. MCP clients connect to `http://address:port/mcp`. + +[Tutorial Video](https://youtu.be/G0FmiX7zwb8) + +

Interface

+ +![MCP Server feature plugin GUI](../../../doc/img/MCPServer_plugin.png) + +

1: Start/Stop

+ +Starts or stops the MCP server. The button is green when the server is listening and red if it could not listen on the requested address and port. + +

2: Endpoint URL

+ +The URL to give to MCP clients. + +

3: Address

+ +IP address to listen on. The default of 127.0.0.1 only accepts connections from the local computer. Use 0.0.0.0 to accept connections from any network interface, in which case a token should be set. + +

4: Port

+ +TCP port to listen on. The default is 8092. + +

5: Capture directory

+ +Directory that the capture tools write IQ and audio files to. It defaults to `SDRangel/captures` under your documents folder. File names given to the capture tools are relative to it, and names that would write outside it are refused, so a connected agent cannot write anywhere else on the machine. + +

6: Token

+ +Optional bearer token. When set, clients must send an `Authorization: Bearer ` HTTP header. Leave empty for no authentication. + +

7: Add to Codex

+ +Writes this server into Codex's `config.toml`. +Codex reads its configuration at startup, so restart it afterwards. + +

8: Add to Claude Desktop

+ +Opens the extension bundle with Claude Desktop, which then shows its own dialog asking whether to install it. + +

9: Status

+ +Number of MCP requests served since the server was started and the last request received. + +

Connecting a client

+ +

Claude Code

+ +For clients that support remote (HTTP) MCP servers, add the endpoint URL directly: + + claude mcp add --transport http sdrangel http://127.0.0.1:8092/mcp + +

Claude Desktop

+ +Claude Desktop cannot connect directly to a HTTP server. +Install the SDRangel extension, which carries a small [bridge](bridge/readme.md) that relays the stdio +transport Claude Desktop does support to this server. Press Add to Claude Desktop (8) to hand +it the bundle; on Windows the installer also offers to do this at the end of a fresh install. +Failing either, take `sdrangel--.mcpb` from the release and open it with +Claude Desktop, or drag it onto Settings > Extensions. Set the port in the extension's +settings if it is not the default 8092. + +For other clients that only support local stdio servers, run the same bridge directly, in: + +- Windows: %APPDATA%\Claude\claude_desktop_config.json +- Linux: ~/.config/Claude/claude_desktop_config.json +- macOS: ~/Library/Application Support/Claude/claude_desktop_config.json + +``` + "mcpServers": { + "sdrangel": { + "command": "C:\\Program Files\\SDRangel\\sdrangel-mcp-bridge.exe", + "args": ["--port", "8092"] + } + } +``` + +`npx -y mcp-remote http://127.0.0.1:8092/mcp` does the same job for a client that has no +bridge built for its platform, at the cost of needing Node.js installed. + +

ChatGPT/Codex

+ +Codex supports the HTTP transport, so does not need a bridge. Press Add to Codex (7) to have the +server's address written to its configuration file, or add the following by hand to: + +- Windows: %USERPROFILE%\.codex\config.toml +- macOS/Linux: ~/.codex/config.toml + +``` + [mcp_servers.sdrangel] + url = "http://127.0.0.1:8092/mcp" +``` + +With a token set, the header goes alongside it: + +``` + [mcp_servers.sdrangel] + url = "http://127.0.0.1:8092/mcp" + http_headers = { "Authorization" = "Bearer " } +``` + +

Tools

+ +The intent tools do a whole task in one call: `listen` sets up a receiver on a frequency in a given mode, `scan` sets up a Frequency Scanner over a list or range of frequencies and reports every frequency above the threshold with its level (and, for intermittent signals, where the scanner parked), stepping by the channel spacing usual for the mode unless told otherwise and refusing modes that live on fixed frequencies, and `get_status` returns one line per device set and feature. Both `listen` and `scan` keep track of the channels they add: by default the next of either on the same device set removes them first, so that exploring a band does not leave a trail of demodulators all playing audio, and `cleanup` removes them all. A `listen` that finds a demodulator of the type it needs among them retunes it instead, as a person would, so stepping through a band in one mode keeps one channel open throughout. Both measure and set the receiver gain, as `tune_gain` does, when they create a device set or move one to another band, and leave it alone otherwise or when told `tuneGain` false. A mode whose output goes to a feature (AIS, radiosondes, APRS) has `listen` add that feature when it is absent, and remove it again, along with the channels, once nothing it added feeds it; a feature that was already there is left alone. AIS gets a demodulator on each of its two channels with the device centred between them. Channels added any other way are kept on the frequency they had, by moving their offset, when the retuned baseband still holds them; an audio demodulator it cannot hold is removed, since all it could do is play noise, while anything else (a file sink, an analyser) is left in place and named in the reply. The rest mirror the Web API. Creation tools wait for SDRangel to complete the operation and return the index of the new object; the `set_*` tools reply with only the keys that were changed, since a client carries every reply in its context for the rest of the conversation. + +| Area | Tools | +|------|-------| +| Intent | `listen`, `scan`, `cleanup`, `tune_gain`, `get_status` | +| Discovery | `get_instance_summary`, `list_available_devices`, `list_channel_types`, `list_feature_types`, `describe_settings`, `get_receiving_guide`, `list_docs`, `get_docs`, `list_audio_devices`, `get_location`, `set_location` | +| Device sets | `add_deviceset`, `remove_last_deviceset`, `get_deviceset`, `set_device`, `get_device_settings`, `set_device_settings`, `set_center_frequency`, `start_device`, `stop_device`, `get_device_report`, `device_action`, `get_spectrum_settings`, `set_spectrum_settings`, `get_spectrum_data`, `get_spectrum_history`, `get_waterfall_image`, `spectrum_action` | +| Channels | `add_channel`, `delete_channel`, `get_channel_settings`, `set_channel_settings`, `get_channel_report`, `channel_action` | +| Features | `add_feature`, `delete_feature`, `get_feature_settings`, `set_feature_settings`, `get_feature_report`, `start_feature`, `stop_feature`, `feature_action` | +| Presets | `list_presets`, `load_preset`, `save_preset`, `list_configurations`, `load_configuration`, `save_configuration` | +| Workspaces (GUI only) | `add_workspace`, `delete_empty_workspaces`, `list_windows`, `set_workspace` (move, hide or show a window), `arrange_workspace` | +| Live data | `get_packets`, `clear_packets`, `get_map_items` | +| Capture | `capture_audio`, `record_iq`, `start_iq_recording`, `stop_iq_recording` | +| Server | `get_server_status` (open streams, capture directory and active recordings, data feed sources) | + +Each tool carries MCP annotations: whether it only reads, whether it overwrites state rather than only adding to it, whether repeating it lands in the same place, and whether it reaches beyond this application, which covers commanding the radio and data received from transmitters SDRangel does not control. + +`describe_settings` returns the OpenAPI documentation of the settings, report and actions keys of a device, channel or feature type, so that an agent can learn the valid keys rather than guess them. The `set_*_settings` tools accept a partial settings object containing only the keys to change. + +`get_packets` returns the packets received on the `packets`, `ais` and `radiosonde` message pipes of the packet, ChirpChat, M17, Meshtastic, MeshCore, Inmarsat, AIS and radiosonde demodulators, kept in a buffer of the last 1000. Each packet carries the raw bytes and, where possible, a decode: AIS message type, MMSI, position, course and speed; AX.25 addresses and data with the APRS position and comment; RS41 serial, position and height. `get_map_items` returns the objects that the same channels and features that feed the Map send on the `mapitems` pipe (aircraft, ships, APRS stations, radiosondes, satellites, Sun and Moon, beacons), with the image, text and, on request, the track. Items are removed when their source removes them or is deleted. Both work whether or not a Map or AIS/APRS feature is present. + +`record_iq` records baseband IQ to an `.sdriq` file for a fixed number of seconds and returns the files written; `start_iq_recording` and `stop_iq_recording` do the same without a time limit for longer captures. Both work by adding a File Sink channel to the device set, so the recording has the offset and decimation the tools are given. `capture_audio` records the demodulated audio of a channel to a WAV file, and reports the sample rate, the peak level and whether the audio was silent, which tells an agent that a squelch is closed rather than that nothing is wrong. It works with demodulators that feed the Demod Analyzer, such as NFMDemod, AMDemod, SSBDemod, WFMDemod and BFMDemod. With `inline` true it also returns the audio as base64, as a mono 16 kHz copy, since MCP clients refuse a tool result over about a megabyte and ten seconds at 48 kHz would exceed that once encoded; the file keeps the full rate. Both blocking tools are capped at 30 seconds so they cannot hold an MCP client's connection open indefinitely. + +`get_receiving_guide` serves a hand written guide in `bandguide.md`: which demodulator and frequency to use for each signal SDRangel can receive, the minimum device sample rate that ADS-B, DAB and broadcast FM need, and the usual reasons nothing is received. Its frequencies come from the plugin readmes, and a test checks that every channel id it names is registered in the build. Edit that file to correct or extend it; it is compiled into the plugin, so re-run cmake after changing it. + +`list_docs` and `get_docs` serve the readme of every plugin registered in the running instance, and the GUI's own pages for what no plugin owns: the spectrum display (`spectrum`, with `spectrummarkers`, `spectrummeasurements` and `spectrumcalibration`), the main spectrum window, audio management, configurations, device user arguments and the transverter dialog. The readmes are compiled into this plugin at build time (re-run cmake after adding a plugin), converted to plain markdown with images removed, and matched to plugin ids by name; the GUI pages are listed in `CMakeLists.txt` and given their ids in `MCPDocs::addGuiDocs`. `get_docs` accepts a plugin id or its displayed name and an optional section heading, so an agent can read just the part it needs from a long document. + +

Event stream

+ +A client can be told when a resource changes instead of polling for it. An HTTP GET on the endpoint with `Accept: text/event-stream` opens a Server-Sent Events stream, and `resources/subscribe` asks for a resource on it. Updates arrive as `notifications/resources/updated`, at most once a second per resource so that a busy decoder cannot flood the stream. `sdrangel://instance`, `sdrangel://packets`, `sdrangel://map/items` and `sdrangel://deviceset/{index}` can be subscribed to; the other resources never change. + +`initialize` returns an `Mcp-Session-Id` header. A client that sends it back keeps its own subscriptions and stream, and can end them with an HTTP DELETE. Clients that ignore it share an anonymous session, which works fully for one client at a time. A client keeps one stream: opening a second replaces the first, so a notification is never delivered twice. That applies to clients that send no session id as well, since they already share the anonymous subscriptions. Sessions with no stream are dropped after a day idle, and at most 32 are kept, each with at most 32 subscriptions. Up to eight streams may be open at once, and a stream is closed after ten minutes so that a client which vanished without closing its connection cannot hold a thread forever; clients reconnect. + +

Resources

+ +| URI | Content | +|-----|---------| +| `sdrangel://instance` | Instance summary | +| `sdrangel://plugins/devices` | Available sampling devices | +| `sdrangel://plugins/channels` | Available channel types | +| `sdrangel://plugins/features` | Available feature types | +| `sdrangel://presets` | Saved presets | +| `sdrangel://configurations` | Saved configurations | +| `sdrangel://deviceset/{index}` | A device set | +| `sdrangel://schema/{type}` | Settings documentation for a type | +| `sdrangel://packets` | The 100 most recent decoded packets, from a buffer of the last 1000 | +| `sdrangel://map/items` | Objects currently plotted on the map | +| `sdrangel://guide` | The receiving guide | +| `sdrangel://docs` | Index of plugin and GUI documentation with section headings | +| `sdrangel://docs/{kind}/{id}` | A document as markdown, e.g. `sdrangel://docs/channel/ADSBDemod` or `sdrangel://docs/gui/spectrum` | + +

Prompts

+ +`setup_receiver`, `record_iq` and `explain_configuration` are prompt templates that guide an agent through common tasks. + +

Security

+ +The server has no access control beyond the optional bearer token, and an agent connected to it can change anything in SDRangel. Keep the address at 127.0.0.1 unless a token is set. + +To keep web pages from driving the server through a browser, requests carrying an `Origin` header are only accepted from an `http` or `https` localhost origin (the opaque `null` origin is rejected), and the request body must be declared as `application/json`. + diff --git a/plugins/feature/mcpserver/toolsdump.cpp b/plugins/feature/mcpserver/toolsdump.cpp index 0590c153f..65dbc0e43 100644 --- a/plugins/feature/mcpserver/toolsdump.cpp +++ b/plugins/feature/mcpserver/toolsdump.cpp @@ -1,83 +1,83 @@ -/////////////////////////////////////////////////////////////////////////////////// -// Copyright (C) 2026 Jon Beniston, M7RCE // -// Some code by AI // -// // -// This program is free software; you can redistribute it and/or modify // -// it under the terms of the GNU General Public License as published by // -// the Free Software Foundation as version 3 of the License, or // -// (at your option) any later version. // -// // -// This program is distributed in the hope that it will be useful, // -// but WITHOUT ANY WARRANTY; without even the implied warranty of // -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // -// GNU General Public License V3 for more details. // -// // -// You should have received a copy of the GNU General Public License // -// along with this program. If not, see . // -/////////////////////////////////////////////////////////////////////////////////// - -// Writes the MCP tool list to a file at build time, so that the Claude Desktop extension can -// carry the real list rather than inventing one. A client that starts before SDRangel reads -// the tool list once and does not ask again, so the bridge has to be able to answer with the -// tools this very build of the server provides, before it has ever spoken to it. -// -// The registry is metadata and handler functions: building it touches neither the Web API nor -// any device, so a null adapter is all it needs. - -#include -#include - -#ifdef _WIN32 -#include -#endif - -#include -#include -#include -#include - -#include "mcptools.h" - -int main(int argc, char *argv[]) -{ - QCoreApplication application(argc, argv); - - if (argc < 2) - { - std::fprintf(stderr, "usage: %s \n", argv[0]); - return 2; - } - - std::fprintf(stderr, "toolsdump: application up\n"); - MCPTools tools(nullptr); - std::fprintf(stderr, "toolsdump: registry built\n"); - - QJsonObject result; - result["tools"] = tools.listTools(); - std::fprintf(stderr, "toolsdump: listed\n"); - - QFile file(QString::fromLocal8Bit(argv[1])); - - if (!file.open(QIODevice::WriteOnly)) - { - std::fprintf(stderr, "cannot write %s: %s\n", argv[1], qPrintable(file.errorString())); - return 1; - } - - file.write(QJsonDocument(result).toJson(QJsonDocument::Compact)); - file.close(); - std::fprintf(stderr, "toolsdump: written\n"); - - std::fprintf(stderr, "%s: %d tools\n", argv[1], result["tools"].toArray().size()); - - // The registry brings background threads up with it and they do not all stop when main - // returns, which leaves the process, and so the build, hanging. Even _Exit does not get - // out, since the runtime's own teardown waits on them, so end the process from the kernel - // side. The file is written and flushed by this point - std::fflush(nullptr); - -#ifdef _WIN32 - TerminateProcess(GetCurrentProcess(), 0); -#endif - std::_Exit(0); -} +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2026 Jon Beniston, M7RCE // +// Some code by AI // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +// Writes the MCP tool list to a file at build time, so that the Claude Desktop extension can +// carry the real list rather than inventing one. A client that starts before SDRangel reads +// the tool list once and does not ask again, so the bridge has to be able to answer with the +// tools this very build of the server provides, before it has ever spoken to it. +// +// The registry is metadata and handler functions: building it touches neither the Web API nor +// any device, so a null adapter is all it needs. + +#include +#include + +#ifdef _WIN32 +#include +#endif + +#include +#include +#include +#include + +#include "mcptools.h" + +int main(int argc, char *argv[]) +{ + QCoreApplication application(argc, argv); + + if (argc < 2) + { + std::fprintf(stderr, "usage: %s \n", argv[0]); + return 2; + } + + std::fprintf(stderr, "toolsdump: application up\n"); + MCPTools tools(nullptr); + std::fprintf(stderr, "toolsdump: registry built\n"); + + QJsonObject result; + result["tools"] = tools.listTools(); + std::fprintf(stderr, "toolsdump: listed\n"); + + QFile file(QString::fromLocal8Bit(argv[1])); + + if (!file.open(QIODevice::WriteOnly)) + { + std::fprintf(stderr, "cannot write %s: %s\n", argv[1], qPrintable(file.errorString())); + return 1; + } + + file.write(QJsonDocument(result).toJson(QJsonDocument::Compact)); + file.close(); + std::fprintf(stderr, "toolsdump: written\n"); + + std::fprintf(stderr, "%s: %d tools\n", argv[1], result["tools"].toArray().size()); + + // The registry brings background threads up with it and they do not all stop when main + // returns, which leaves the process, and so the build, hanging. Even _Exit does not get + // out, since the runtime's own teardown waits on them, so end the process from the kernel + // side. The file is written and flushed by this point + std::fflush(nullptr); + +#ifdef _WIN32 + TerminateProcess(GetCurrentProcess(), 0); +#endif + std::_Exit(0); +} diff --git a/plugins/feature/sid/icons/delta.svg b/plugins/feature/sid/icons/delta.svg index 53e96bb9b..4d8d96098 100644 --- a/plugins/feature/sid/icons/delta.svg +++ b/plugins/feature/sid/icons/delta.svg @@ -1,19 +1,19 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/gamma.svg b/plugins/feature/sid/icons/gamma.svg index 90de948d4..ce3cdad76 100644 --- a/plugins/feature/sid/icons/gamma.svg +++ b/plugins/feature/sid/icons/gamma.svg @@ -1,22 +1,22 @@ - - - - - - - - - - - - - - + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/proton.svg b/plugins/feature/sid/icons/proton.svg index fca02154c..9c9c50f24 100644 --- a/plugins/feature/sid/icons/proton.svg +++ b/plugins/feature/sid/icons/proton.svg @@ -1,37 +1,37 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/xlp.svg b/plugins/feature/sid/icons/xlp.svg index fb2d86505..2cc7fbd0d 100644 --- a/plugins/feature/sid/icons/xlp.svg +++ b/plugins/feature/sid/icons/xlp.svg @@ -1,45 +1,45 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/xls.svg b/plugins/feature/sid/icons/xls.svg index 6f2fc9919..fb91cf5d2 100644 --- a/plugins/feature/sid/icons/xls.svg +++ b/plugins/feature/sid/icons/xls.svg @@ -1,53 +1,53 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/xsp.svg b/plugins/feature/sid/icons/xsp.svg index e3cb553a1..f374d3ea1 100644 --- a/plugins/feature/sid/icons/xsp.svg +++ b/plugins/feature/sid/icons/xsp.svg @@ -1,48 +1,48 @@ - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/sid/icons/xss.svg b/plugins/feature/sid/icons/xss.svg index adf398da0..8fa2f1b99 100644 --- a/plugins/feature/sid/icons/xss.svg +++ b/plugins/feature/sid/icons/xss.svg @@ -1,56 +1,56 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/plugins/feature/skymap/html/aladin.html b/plugins/feature/skymap/html/aladin.html index dbba8975b..4fd328901 100644 --- a/plugins/feature/skymap/html/aladin.html +++ b/plugins/feature/skymap/html/aladin.html @@ -1,101 +1,101 @@ - - - - SDRangel Aladin - - - - - -
- - - - + + + - - + } else { + console.log(`Unknown command ${command.command}`); + } + + } catch (e) { + console.log(`Erroring processing received message:\n${e}\n${event.data}`); + } + }; + + function createAntennaFoV() { + antennaOverlay = A.graphicOverlay({ color: '#ffffff', lineWidth: 1 }); + aladin.addOverlay(antennaOverlay); + const [ra, dec] = aladin.getRaDec(); + antennaCircle = A.circle(ra, dec, antennaHpbw); + antennaOverlay.add(antennaCircle); + } + + function showAntennaFoV() { + antennaCircle.show(); + } + + function hideAntennaFoV() { + antennaCircle.hide(); + } + + function reportReady() { + console.log("reportReady " + socket.readyState); + + createAntennaFoV(); + + if (socket.readyState === 1) { + socket.send(JSON.stringify({ + event: "ready" + })); + } else { + setTimeout(reportReady, 100); + } + } + + function reportView() { + if (socket.readyState === 1) { + const [ra, dec] = aladin.getRaDec(); + const [fovX, fovY] = aladin.getFov(); + socket.send(JSON.stringify({ + event: "view", + ra: ra / 15.0, // Convert RA from degrees to hours + dec: dec, + fov: fovX + })); + + antennaCircle.setCenter([ra, dec]); + } + } + + + + diff --git a/sdrgui/gui/checklist.cpp b/sdrgui/gui/checklist.cpp index 419599523..89b00f295 100644 --- a/sdrgui/gui/checklist.cpp +++ b/sdrgui/gui/checklist.cpp @@ -1,172 +1,172 @@ -#include "checklist.h" - -CheckList::CheckList(QWidget* parent) : - QComboBox(parent) -{ - m_model = new QStandardItemModel(); - setModel(m_model); - - setEditable(true); - lineEdit()->setReadOnly(true); - lineEdit()->installEventFilter(this); - setItemDelegate(new QCheckListStyledItemDelegate(this)); - - connect(lineEdit(), &QLineEdit::selectionChanged, lineEdit(), &QLineEdit::deselect); - connect((QListView*) view(), SIGNAL(pressed(QModelIndex)), this, SLOT(on_itemPressed(QModelIndex))); - connect(m_model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector)), this, SLOT(on_modelDataChanged())); -} - -CheckList::~CheckList() -{ - delete m_model; -} - -void CheckList::setText(const QString &text) -{ - m_text = text; - updateText(); -} - -void CheckList::setAllCheckedText(const QString &text) -{ - m_allCheckedText = text; - updateText(); -} - -void CheckList::setNoneCheckedText(const QString &text) -{ - m_noneCheckedText = text; - updateText(); -} - -void CheckList::setUnknownlyCheckedText(const QString &text) -{ - m_unknownlyCheckedText = text; - updateText(); -} - -void CheckList::setSortRole(int role) -{ - m_model->setSortRole(role); -} - -QStandardItem* CheckList::addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState) -{ - QStandardItem* item = new QStandardItem(label); - item->setCheckState(checkState); - item->setData(data); - item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); - - m_model->appendRow(item); - - updateText(); - - return item; -} - -int CheckList::globalCheckState() -{ - int nbRows = m_model->rowCount(), nbChecked = 0, nbUnchecked = 0; - - if (nbRows == 0) - { - return StateUnknown; - } - - for (int i = 0; i < nbRows; i++) - { - if (m_model->item(i)->checkState() == Qt::Checked) - { - nbChecked++; - } - else if (m_model->item(i)->checkState() == Qt::Unchecked) - { - nbUnchecked++; - } - else - { - return StateUnknown; - } - } - - return nbChecked == nbRows ? Qt::Checked : nbUnchecked == nbRows ? Qt::Unchecked : Qt::PartiallyChecked; -} - -bool CheckList::eventFilter(QObject* _object, QEvent* _event) -{ - if (_object == lineEdit() && _event->type() == QEvent::MouseButtonPress) - { - showPopup(); - return true; - } - - return false; -} - -void CheckList::updateText() -{ - QString text; - - if (m_text.isEmpty()) - { - switch (globalCheckState()) - { - case Qt::Checked: - text = m_allCheckedText; - break; - - case Qt::Unchecked: - text = m_noneCheckedText; - break; - - case Qt::PartiallyChecked: - for (int i = 0; i < m_model->rowCount(); i++) - { - if (m_model->item(i)->checkState() == Qt::Checked) - { - if (!text.isEmpty()) - { - text+= ", "; - } - - text+= m_model->item(i)->text(); - } - } - break; - - default: - text = m_unknownlyCheckedText; - } - } - else - { - text = m_text; - } - - lineEdit()->setText(text); -} - -void CheckList::on_modelDataChanged() -{ - updateText(); - emit globalCheckStateChanged(globalCheckState()); -} - -void CheckList::on_itemPressed(const QModelIndex &index) -{ - QStandardItem* item = m_model->itemFromIndex(index); - - if (item->checkState() == Qt::Checked) - { - item->setCheckState(Qt::Unchecked); - } - else - { - item->setCheckState(Qt::Checked); - } -} - -bool CheckList::isChecked(int index) const -{ - return m_model->item(index)->checkState() == Qt::Checked; -} +#include "checklist.h" + +CheckList::CheckList(QWidget* parent) : + QComboBox(parent) +{ + m_model = new QStandardItemModel(); + setModel(m_model); + + setEditable(true); + lineEdit()->setReadOnly(true); + lineEdit()->installEventFilter(this); + setItemDelegate(new QCheckListStyledItemDelegate(this)); + + connect(lineEdit(), &QLineEdit::selectionChanged, lineEdit(), &QLineEdit::deselect); + connect((QListView*) view(), SIGNAL(pressed(QModelIndex)), this, SLOT(on_itemPressed(QModelIndex))); + connect(m_model, SIGNAL(dataChanged(QModelIndex, QModelIndex, QVector)), this, SLOT(on_modelDataChanged())); +} + +CheckList::~CheckList() +{ + delete m_model; +} + +void CheckList::setText(const QString &text) +{ + m_text = text; + updateText(); +} + +void CheckList::setAllCheckedText(const QString &text) +{ + m_allCheckedText = text; + updateText(); +} + +void CheckList::setNoneCheckedText(const QString &text) +{ + m_noneCheckedText = text; + updateText(); +} + +void CheckList::setUnknownlyCheckedText(const QString &text) +{ + m_unknownlyCheckedText = text; + updateText(); +} + +void CheckList::setSortRole(int role) +{ + m_model->setSortRole(role); +} + +QStandardItem* CheckList::addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState) +{ + QStandardItem* item = new QStandardItem(label); + item->setCheckState(checkState); + item->setData(data); + item->setFlags(Qt::ItemIsUserCheckable | Qt::ItemIsEnabled); + + m_model->appendRow(item); + + updateText(); + + return item; +} + +int CheckList::globalCheckState() +{ + int nbRows = m_model->rowCount(), nbChecked = 0, nbUnchecked = 0; + + if (nbRows == 0) + { + return StateUnknown; + } + + for (int i = 0; i < nbRows; i++) + { + if (m_model->item(i)->checkState() == Qt::Checked) + { + nbChecked++; + } + else if (m_model->item(i)->checkState() == Qt::Unchecked) + { + nbUnchecked++; + } + else + { + return StateUnknown; + } + } + + return nbChecked == nbRows ? Qt::Checked : nbUnchecked == nbRows ? Qt::Unchecked : Qt::PartiallyChecked; +} + +bool CheckList::eventFilter(QObject* _object, QEvent* _event) +{ + if (_object == lineEdit() && _event->type() == QEvent::MouseButtonPress) + { + showPopup(); + return true; + } + + return false; +} + +void CheckList::updateText() +{ + QString text; + + if (m_text.isEmpty()) + { + switch (globalCheckState()) + { + case Qt::Checked: + text = m_allCheckedText; + break; + + case Qt::Unchecked: + text = m_noneCheckedText; + break; + + case Qt::PartiallyChecked: + for (int i = 0; i < m_model->rowCount(); i++) + { + if (m_model->item(i)->checkState() == Qt::Checked) + { + if (!text.isEmpty()) + { + text+= ", "; + } + + text+= m_model->item(i)->text(); + } + } + break; + + default: + text = m_unknownlyCheckedText; + } + } + else + { + text = m_text; + } + + lineEdit()->setText(text); +} + +void CheckList::on_modelDataChanged() +{ + updateText(); + emit globalCheckStateChanged(globalCheckState()); +} + +void CheckList::on_itemPressed(const QModelIndex &index) +{ + QStandardItem* item = m_model->itemFromIndex(index); + + if (item->checkState() == Qt::Checked) + { + item->setCheckState(Qt::Unchecked); + } + else + { + item->setCheckState(Qt::Checked); + } +} + +bool CheckList::isChecked(int index) const +{ + return m_model->item(index)->checkState() == Qt::Checked; +} diff --git a/sdrgui/gui/checklist.h b/sdrgui/gui/checklist.h index 08b8c732f..396dbf2ef 100644 --- a/sdrgui/gui/checklist.h +++ b/sdrgui/gui/checklist.h @@ -1,105 +1,105 @@ -#ifndef CHECKLIST -#define CHECKLIST - -#include -#include -#include -#include -#include -#include -#include - -#include "export.h" - -/** -* @brief QComboBox with support of checkboxes -* http://stackoverflow.com/questions/8422760/combobox-of-checkboxes -*/ -class SDRGUI_API CheckList : public QComboBox -{ - Q_OBJECT - -public: - /** - * @brief Additional value to Qt::CheckState when some checkboxes are Qt::PartiallyChecked - */ - static const int StateUnknown = 3; - -private: - QStandardItemModel* m_model; - /** - * @brief Text to display regardless of what is checked - */ - QString m_text; - /** - * @brief Text displayed when no item is checked - */ - QString m_noneCheckedText; - /** - * @brief Text displayed when all items are checked - */ - QString m_allCheckedText; - /** - * @brief Text displayed when some items are partially checked - */ - QString m_unknownlyCheckedText; - -signals: - void globalCheckStateChanged(int); - -public: - CheckList(QWidget* parent = nullptr); - ~CheckList(); - - void setText(const QString &text); - void setAllCheckedText(const QString &text); - void setNoneCheckedText(const QString &text); - void setUnknownlyCheckedText(const QString &text); - - bool isChecked(int index) const; - - void setSortRole(int role); - - /** - * @brief Adds a item to the checklist - * @return the new QStandardItem - */ - QStandardItem* addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState); - - /** - * @brief Computes the global state of the checklist : - * - if there is no item: StateUnknown - * - if there is at least one item partially checked: StateUnknown - * - if all items are checked: Qt::Checked - * - if no item is checked: Qt::Unchecked - * - else: Qt::PartiallyChecked - */ - int globalCheckState(); - -protected: - bool eventFilter(QObject* _object, QEvent* _event); - -private: - void updateText(); - -private slots: - void on_modelDataChanged(); - - void on_itemPressed(const QModelIndex &index); - -public: - class QCheckListStyledItemDelegate : public QStyledItemDelegate - { - public: - QCheckListStyledItemDelegate(QObject* parent = 0) : QStyledItemDelegate(parent) {} - - void paint(QPainter * painter_, const QStyleOptionViewItem & option_, const QModelIndex & index_) const - { - QStyleOptionViewItem & refToNonConstOption = const_cast(option_); - refToNonConstOption.showDecorationSelected = false; - QStyledItemDelegate::paint(painter_, refToNonConstOption, index_); - } - }; -}; - -#endif +#ifndef CHECKLIST +#define CHECKLIST + +#include +#include +#include +#include +#include +#include +#include + +#include "export.h" + +/** +* @brief QComboBox with support of checkboxes +* http://stackoverflow.com/questions/8422760/combobox-of-checkboxes +*/ +class SDRGUI_API CheckList : public QComboBox +{ + Q_OBJECT + +public: + /** + * @brief Additional value to Qt::CheckState when some checkboxes are Qt::PartiallyChecked + */ + static const int StateUnknown = 3; + +private: + QStandardItemModel* m_model; + /** + * @brief Text to display regardless of what is checked + */ + QString m_text; + /** + * @brief Text displayed when no item is checked + */ + QString m_noneCheckedText; + /** + * @brief Text displayed when all items are checked + */ + QString m_allCheckedText; + /** + * @brief Text displayed when some items are partially checked + */ + QString m_unknownlyCheckedText; + +signals: + void globalCheckStateChanged(int); + +public: + CheckList(QWidget* parent = nullptr); + ~CheckList(); + + void setText(const QString &text); + void setAllCheckedText(const QString &text); + void setNoneCheckedText(const QString &text); + void setUnknownlyCheckedText(const QString &text); + + bool isChecked(int index) const; + + void setSortRole(int role); + + /** + * @brief Adds a item to the checklist + * @return the new QStandardItem + */ + QStandardItem* addCheckItem(const QString &label, const QVariant &data, const Qt::CheckState checkState); + + /** + * @brief Computes the global state of the checklist : + * - if there is no item: StateUnknown + * - if there is at least one item partially checked: StateUnknown + * - if all items are checked: Qt::Checked + * - if no item is checked: Qt::Unchecked + * - else: Qt::PartiallyChecked + */ + int globalCheckState(); + +protected: + bool eventFilter(QObject* _object, QEvent* _event); + +private: + void updateText(); + +private slots: + void on_modelDataChanged(); + + void on_itemPressed(const QModelIndex &index); + +public: + class QCheckListStyledItemDelegate : public QStyledItemDelegate + { + public: + QCheckListStyledItemDelegate(QObject* parent = 0) : QStyledItemDelegate(parent) {} + + void paint(QPainter * painter_, const QStyleOptionViewItem & option_, const QModelIndex & index_) const + { + QStyleOptionViewItem & refToNonConstOption = const_cast(option_); + refToNonConstOption.showDecorationSelected = false; + QStyledItemDelegate::paint(painter_, refToNonConstOption, index_); + } + }; +}; + +#endif From ec1779e0e324bf9b7b29f9f00abaee8b1c2f49ed Mon Sep 17 00:00:00 2001 From: Robin Getz Date: Sun, 27 Sep 2026 17:43:08 -0400 Subject: [PATCH 10/11] repowide: Add missing final newlines to text files Add a terminating LF to tracked text files that were missing a newline at end of file. This avoids Codacy whitespace failures and ensures text files conform to the repository line-ending policy. Affected files were identified and fixed with the following script. It checks all tracked files against .gitattributes, skips files marked as binary or -text, and reports the final 32 bytes of any non-empty text file that does not end with LF before adding the missing newline. git ls-files -z | while IFS= read -r -d '' f; do attr=$(git check-attr text -- "$f") case "$attr" in "$f: text: unset"|"$f: text: unspecified") continue ;; esac [ -f "$f" ] || continue [ -s "$f" ] || continue [ "$(tail -c 1 -- "$f" | od -An -t x1 | tr -d ' \n')" = "0a" ] || { printf '%s\n' "$f" tail -c 32 -- "$f" | hexdump -C printf '\n' >> "$f" } done Signed-off-by: Robin Getz --- android/qt6/res/mipmap-anydpi-v26/ic_launcher.xml | 2 +- cmake/Modules/FindCM256cc.cmake | 2 +- cmake/Modules/FindCodec2.cmake | 2 +- cmake/Modules/FindFFmpeg.cmake | 2 +- cmake/Modules/FindLibMbe.cmake | 2 +- cmake/Modules/FindLibXTRX.cmake | 2 +- cmake/Modules/FindLimeSuite.cmake | 2 +- cmake/Modules/FindOpus.cmake | 2 +- cmake/Modules/FindSerialDV.cmake | 2 +- cmake/include/uninstall.cmake.in | 2 +- debian/compat | 2 +- debian/source/format | 2 +- doc/model/SDRAngel.mdj | 2 +- json_udp_data_format.readme.md | 2 +- logging/readme.md | 2 +- modemm17/M17FrameDecoder.h | 2 +- plugins/channelrx/demodadsb/sideviews/ReadMe.txt | 2 +- plugins/channelrx/demoddatv/datvcstlnlut.h | 2 +- plugins/channelrx/remotetcpsink/remotetcpsinksettingsdialog.cpp | 2 +- plugins/feature/sid/icons/solar-orbiter.svg | 2 +- plugins/feature/startracker/spiceephemerides.cpp | 2 +- scriptsapi/requirements.txt | 2 +- sdrbase/resources/webapi/index.html | 2 +- swagger/docker/compose/login.sh | 2 +- swagger/docker/server/run.sh | 2 +- swagger/sdrangel/api/swagger/include/CWKeyer.yaml | 2 +- 26 files changed, 26 insertions(+), 26 deletions(-) diff --git a/android/qt6/res/mipmap-anydpi-v26/ic_launcher.xml b/android/qt6/res/mipmap-anydpi-v26/ic_launcher.xml index fcd3a1e20..ec59d6ec5 100644 --- a/android/qt6/res/mipmap-anydpi-v26/ic_launcher.xml +++ b/android/qt6/res/mipmap-anydpi-v26/ic_launcher.xml @@ -2,4 +2,4 @@ - \ No newline at end of file + diff --git a/cmake/Modules/FindCM256cc.cmake b/cmake/Modules/FindCM256cc.cmake index b7b0b2a22..3cb90ca64 100644 --- a/cmake/Modules/FindCM256cc.cmake +++ b/cmake/Modules/FindCM256cc.cmake @@ -53,4 +53,4 @@ if (NOT CM256CC_FOUND) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(CM256CC DEFAULT_MSG CM256CC_LIBRARIES CM256CC_INCLUDE_DIR) MARK_AS_ADVANCED(CM256CC_LIBRARIES CM256CC_INCLUDE_DIR) -endif (NOT CM256CC_FOUND) \ No newline at end of file +endif (NOT CM256CC_FOUND) diff --git a/cmake/Modules/FindCodec2.cmake b/cmake/Modules/FindCodec2.cmake index de1bc91b3..c9257b4f5 100644 --- a/cmake/Modules/FindCodec2.cmake +++ b/cmake/Modules/FindCodec2.cmake @@ -53,4 +53,4 @@ if (NOT CODEC2_FOUND) INCLUDE(FindPackageHandleStandardArgs) FIND_PACKAGE_HANDLE_STANDARD_ARGS(CODEC2 DEFAULT_MSG CODEC2_LIBRARIES CODEC2_INCLUDE_DIR) MARK_AS_ADVANCED(CODEC2_LIBRARIES CODEC2_INCLUDE_DIR) -endif (NOT CODEC2_FOUND) \ No newline at end of file +endif (NOT CODEC2_FOUND) diff --git a/cmake/Modules/FindFFmpeg.cmake b/cmake/Modules/FindFFmpeg.cmake index 0d741c4ba..abe9595fe 100644 --- a/cmake/Modules/FindFFmpeg.cmake +++ b/cmake/Modules/FindFFmpeg.cmake @@ -148,4 +148,4 @@ foreach (_component ${FFmpeg_FIND_COMPONENTS}) endforeach () # Give a nice error message if some of the required vars are missing. -find_package_handle_standard_args(FFmpeg DEFAULT_MSG ${_FFmpeg_REQUIRED_VARS}) \ No newline at end of file +find_package_handle_standard_args(FFmpeg DEFAULT_MSG ${_FFmpeg_REQUIRED_VARS}) diff --git a/cmake/Modules/FindLibMbe.cmake b/cmake/Modules/FindLibMbe.cmake index 28638a576..98014e980 100644 --- a/cmake/Modules/FindLibMbe.cmake +++ b/cmake/Modules/FindLibMbe.cmake @@ -31,4 +31,4 @@ if (NOT LIBMBE_FOUND) endif (LIBMBE_INCLUDE_DIR AND LIBMBE_LIBRARIES) mark_as_advanced(LIBMBE_INCLUDE_DIR LIBMBE_LIBRARIES) -endif (NOT LIBMBE_FOUND) \ No newline at end of file +endif (NOT LIBMBE_FOUND) diff --git a/cmake/Modules/FindLibXTRX.cmake b/cmake/Modules/FindLibXTRX.cmake index 8bcd8286a..5154c2503 100644 --- a/cmake/Modules/FindLibXTRX.cmake +++ b/cmake/Modules/FindLibXTRX.cmake @@ -31,4 +31,4 @@ if(NOT LIBXTRX_FOUND) mark_as_advanced(LIBXTRX_INCLUDE_DIRS LIBXTRX_LIBRARY) -endif(NOT LIBXTRX_FOUND) \ No newline at end of file +endif(NOT LIBXTRX_FOUND) diff --git a/cmake/Modules/FindLimeSuite.cmake b/cmake/Modules/FindLimeSuite.cmake index 2aafa2fbe..541d68e42 100644 --- a/cmake/Modules/FindLimeSuite.cmake +++ b/cmake/Modules/FindLimeSuite.cmake @@ -31,4 +31,4 @@ if (NOT LIMESUITE_FOUND) endif (LIMESUITE_INCLUDE_DIR AND LIMESUITE_LIBRARY) mark_as_advanced(LIMESUITE_INCLUDE_DIR LIMESUITE_LIBRARY) -endif (NOT LIMESUITE_FOUND) \ No newline at end of file +endif (NOT LIMESUITE_FOUND) diff --git a/cmake/Modules/FindOpus.cmake b/cmake/Modules/FindOpus.cmake index 2ec4281dc..b3b82345c 100644 --- a/cmake/Modules/FindOpus.cmake +++ b/cmake/Modules/FindOpus.cmake @@ -49,4 +49,4 @@ find_package_handle_standard_args(Opus OPUS_INCLUDE_DIRS OPUS_LIBRARIES HAVE_OPUS_OPUS_H ) -mark_as_advanced(OPUS_INCLUDE_DIRS OPUS_LIBRARIES HAVE_OPUS_OPUS_H) \ No newline at end of file +mark_as_advanced(OPUS_INCLUDE_DIRS OPUS_LIBRARIES HAVE_OPUS_OPUS_H) diff --git a/cmake/Modules/FindSerialDV.cmake b/cmake/Modules/FindSerialDV.cmake index 6d6862699..a0787a91c 100644 --- a/cmake/Modules/FindSerialDV.cmake +++ b/cmake/Modules/FindSerialDV.cmake @@ -31,4 +31,4 @@ if (NOT LIBSERIALDV_FOUND) endif (LIBSERIALDV_INCLUDE_DIR AND LIBSERIALDV_LIBRARY) mark_as_advanced(LIBSERIALDV_INCLUDE_DIR LIBSERIALDV_LIBRARY) -endif (NOT LIBSERIALDV_FOUND) \ No newline at end of file +endif (NOT LIBSERIALDV_FOUND) diff --git a/cmake/include/uninstall.cmake.in b/cmake/include/uninstall.cmake.in index 2c34c8199..2037e3653 100644 --- a/cmake/include/uninstall.cmake.in +++ b/cmake/include/uninstall.cmake.in @@ -18,4 +18,4 @@ foreach(file ${files}) else(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") message(STATUS "File $ENV{DESTDIR}${file} does not exist.") endif(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}") -endforeach(file) \ No newline at end of file +endforeach(file) diff --git a/debian/compat b/debian/compat index 9a037142a..f599e28b8 100644 --- a/debian/compat +++ b/debian/compat @@ -1 +1 @@ -10 \ No newline at end of file +10 diff --git a/debian/source/format b/debian/source/format index 46ebe0266..163aaf8d8 100644 --- a/debian/source/format +++ b/debian/source/format @@ -1 +1 @@ -3.0 (quilt) \ No newline at end of file +3.0 (quilt) diff --git a/doc/model/SDRAngel.mdj b/doc/model/SDRAngel.mdj index 13dac666c..e4a3648e2 100644 --- a/doc/model/SDRAngel.mdj +++ b/doc/model/SDRAngel.mdj @@ -32722,4 +32722,4 @@ "visibility": "public" } ] -} \ No newline at end of file +} diff --git a/json_udp_data_format.readme.md b/json_udp_data_format.readme.md index cf27676ba..cdd1ceff6 100644 --- a/json_udp_data_format.readme.md +++ b/json_udp_data_format.readme.md @@ -173,4 +173,4 @@ ... "payload_hex": "ffffffff363e0c47..." } - } \ No newline at end of file + } diff --git a/logging/readme.md b/logging/readme.md index 8b6af9220..c3f34c31a 100644 --- a/logging/readme.md +++ b/logging/readme.md @@ -6,4 +6,4 @@ This is based on the logging part of QtWebApp from Stefan Frings - [Link to API documentation](http://stefanfrings.de/qtwebapp/api/index.html) - [Link to tutorial](http://stefanfrings.de/qtwebapp/tutorial/index.html) -Some changes have been made to support the option of having a console logging plus optional file logging \ No newline at end of file +Some changes have been made to support the option of having a console logging plus optional file logging diff --git a/modemm17/M17FrameDecoder.h b/modemm17/M17FrameDecoder.h index 2656350b4..ed9c033b7 100644 --- a/modemm17/M17FrameDecoder.h +++ b/modemm17/M17FrameDecoder.h @@ -407,4 +407,4 @@ struct M17FrameDecoder State state() const { return state_; } }; -} // modemm17 \ No newline at end of file +} // modemm17 diff --git a/plugins/channelrx/demodadsb/sideviews/ReadMe.txt b/plugins/channelrx/demodadsb/sideviews/ReadMe.txt index 8f54542ed..b998ad1df 100644 --- a/plugins/channelrx/demodadsb/sideviews/ReadMe.txt +++ b/plugins/channelrx/demodadsb/sideviews/ReadMe.txt @@ -15,4 +15,4 @@ Note: We do not envisage users typically entering these codes using this interfa have provided this feature so that those existing third party applications that use BaseStation’s database interface to write registration data into the database can write in flag codes matching existing flag data sets, allowing the users of those third party products to have operator flags -automatically appear. \ No newline at end of file +automatically appear. diff --git a/plugins/channelrx/demoddatv/datvcstlnlut.h b/plugins/channelrx/demoddatv/datvcstlnlut.h index ac9888398..1ddc6a36f 100644 --- a/plugins/channelrx/demoddatv/datvcstlnlut.h +++ b/plugins/channelrx/demoddatv/datvcstlnlut.h @@ -191,4 +191,4 @@ static cstln_lut * make_dvbs2_constellation( } -#endif // DATV_CSTLN_LUT_H \ No newline at end of file +#endif // DATV_CSTLN_LUT_H diff --git a/plugins/channelrx/remotetcpsink/remotetcpsinksettingsdialog.cpp b/plugins/channelrx/remotetcpsink/remotetcpsinksettingsdialog.cpp index 0b45356aa..76a0ff391 100644 --- a/plugins/channelrx/remotetcpsink/remotetcpsinksettingsdialog.cpp +++ b/plugins/channelrx/remotetcpsink/remotetcpsinksettingsdialog.cpp @@ -384,4 +384,4 @@ void RemoteTCPSinkSettingsDialog::updateRotatorList(const AvailableChannelOrFeat ui->rotator->blockSignals(false); displayEnabled(); -} \ No newline at end of file +} diff --git a/plugins/feature/sid/icons/solar-orbiter.svg b/plugins/feature/sid/icons/solar-orbiter.svg index 6c5373978..981e951b9 100644 --- a/plugins/feature/sid/icons/solar-orbiter.svg +++ b/plugins/feature/sid/icons/solar-orbiter.svg @@ -27,4 +27,4 @@ - \ No newline at end of file + diff --git a/plugins/feature/startracker/spiceephemerides.cpp b/plugins/feature/startracker/spiceephemerides.cpp index 4b1e6fcec..883608f5e 100644 --- a/plugins/feature/startracker/spiceephemerides.cpp +++ b/plugins/feature/startracker/spiceephemerides.cpp @@ -144,4 +144,4 @@ QStringList SpiceEphemerides::getTargets(const QStringList &emphemeridesURLs) targets.removeDuplicates(); return targets; -} \ No newline at end of file +} diff --git a/scriptsapi/requirements.txt b/scriptsapi/requirements.txt index 836866ef8..4ee2b5db6 100644 --- a/scriptsapi/requirements.txt +++ b/scriptsapi/requirements.txt @@ -3,4 +3,4 @@ Flask numpy websockets websocket-client -mock \ No newline at end of file +mock diff --git a/sdrbase/resources/webapi/index.html b/sdrbase/resources/webapi/index.html index a64e4c92d..65b017f78 100644 --- a/sdrbase/resources/webapi/index.html +++ b/sdrbase/resources/webapi/index.html @@ -49,4 +49,4 @@

Click on links on the left for various types of documentation

- \ No newline at end of file + diff --git a/swagger/docker/compose/login.sh b/swagger/docker/compose/login.sh index 4d2a973ee..94b68283d 100755 --- a/swagger/docker/compose/login.sh +++ b/swagger/docker/compose/login.sh @@ -1,2 +1,2 @@ #!/bin/bash -docker exec -it sdrangel_swgcodegen /bin/bash \ No newline at end of file +docker exec -it sdrangel_swgcodegen /bin/bash diff --git a/swagger/docker/server/run.sh b/swagger/docker/server/run.sh index a3a331e32..064e73156 100755 --- a/swagger/docker/server/run.sh +++ b/swagger/docker/server/run.sh @@ -48,4 +48,4 @@ docker run -it --rm \ --name ${container_name} \ ${http_port} \ -v="/opt/build/sdrangel:/opt/build/sdrangel:rw" \ - ${image_name}:${image_tag} \ No newline at end of file + ${image_name}:${image_tag} diff --git a/swagger/sdrangel/api/swagger/include/CWKeyer.yaml b/swagger/sdrangel/api/swagger/include/CWKeyer.yaml index 662d6ec6a..023f7b18e 100644 --- a/swagger/sdrangel/api/swagger/include/CWKeyer.yaml +++ b/swagger/sdrangel/api/swagger/include/CWKeyer.yaml @@ -43,4 +43,4 @@ CWKeyerSettings: dashKeyModifiers: description: > Modifiers for the dash key. Modifier keys held with the key, as a sum of flags: 33554432 (0x02000000) shift, 67108864 (0x04000000) control, 134217728 (0x08000000) alt, 268435456 (0x10000000) meta. 0 for no modifier. - type: integer \ No newline at end of file + type: integer From 37d14e1064f54507ceec1413212d0b932eadb33f Mon Sep 17 00:00:00 2001 From: Robin Getz Date: Sun, 27 Sep 2026 18:12:35 -0400 Subject: [PATCH 11/11] workflow : add a workflow to check linefeeds so things don't accidently slip in. Signed-off-by: Robin Getz --- .github/workflows/git-attributes.yml | 29 ++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/workflows/git-attributes.yml diff --git a/.github/workflows/git-attributes.yml b/.github/workflows/git-attributes.yml new file mode 100644 index 000000000..7637713bd --- /dev/null +++ b/.github/workflows/git-attributes.yml @@ -0,0 +1,29 @@ +name: Check Git attributes + +on: + pull_request: + +jobs: + check-gitattributes: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Check for line ending violations + run: | + # Re-normalize all files according to .gitattributes + git add --renormalize . + + # Check if renormalization changed anything + if git diff --cached --name-only | grep -q .; then + echo "::error::The following files have line endings that don't match .gitattributes settings:" + git diff --cached --name-only + echo "" + echo "To fix, run:" + echo " git add --renormalize ." + echo " git commit -m 'Normalize line endings'" + exit 1 + fi + + echo "All files have correct line endings."