diff --git a/.clang-format b/.clang-format index 413c46d2..a3335575 100644 --- a/.clang-format +++ b/.clang-format @@ -17,7 +17,7 @@ AllowShortCaseLabelsOnASingleLine: false AllowShortFunctionsOnASingleLine: All AllowShortLambdasOnASingleLine: All AllowShortIfStatementsOnASingleLine: WithoutElse -AllowShortLoopsOnASingleLine: false +AllowShortLoopsOnASingleLine: true AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None AlwaysBreakBeforeMultilineStrings: false diff --git a/.github/workflows/build_all.yml b/.github/workflows/build_all.yml index db5f635d..b1eb25c1 100644 --- a/.github/workflows/build_all.yml +++ b/.github/workflows/build_all.yml @@ -359,3 +359,12 @@ jobs: - name: Running codespell run: cd $GITHUB_WORKSPACE && codespell -q 2 || true + + check_formatting: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + + - name: Run check_clang_format + run: cd $GITHUB_WORKSPACE && ./check_clang_format.sh || true diff --git a/core/src/config.cpp b/core/src/config.cpp index bf2e3100..2d29adb0 100644 --- a/core/src/config.cpp +++ b/core/src/config.cpp @@ -5,7 +5,6 @@ #include ConfigManager::ConfigManager() { - } ConfigManager::~ConfigManager() { @@ -31,7 +30,7 @@ void ConfigManager::load(json def, bool lock) { spdlog::error("Config file '{0}' isn't a file", path); return; } - + try { std::ifstream file(path.c_str()); file >> conf; @@ -96,7 +95,7 @@ void ConfigManager::autoSaveWorker() { // Sleep but listen for wakeup call { std::unique_lock lock(termMtx); - termCond.wait_for(lock, std::chrono::milliseconds(1000), [this]() { return termFlag; } ); + termCond.wait_for(lock, std::chrono::milliseconds(1000), [this]() { return termFlag; }); } } } \ No newline at end of file diff --git a/core/src/config.h b/core/src/config.h index e6bf10a2..fbbdeb4a 100644 --- a/core/src/config.h +++ b/core/src/config.h @@ -20,7 +20,7 @@ public: void release(bool modified = false); json conf; - + private: void autoSaveWorker(); @@ -33,5 +33,4 @@ private: std::mutex termMtx; std::condition_variable termCond; volatile bool termFlag = false; - }; \ No newline at end of file diff --git a/core/src/core.cpp b/core/src/core.cpp index a07e3d9d..97eb2902 100644 --- a/core/src/core.cpp +++ b/core/src/core.cpp @@ -30,11 +30,11 @@ #endif #ifndef INSTALL_PREFIX - #ifdef __APPLE__ - #define INSTALL_PREFIX "/usr/local" - #else - #define INSTALL_PREFIX "/usr" - #endif +#ifdef __APPLE__ +#define INSTALL_PREFIX "/usr/local" +#else +#define INSTALL_PREFIX "/usr" +#endif #endif const char* OPENGL_VERSIONS_GLSL[] = { @@ -99,7 +99,7 @@ static void maximized_callback(GLFWwindow* window, int n) { } // main -int sdrpp_main(int argc, char *argv[]) { +int sdrpp_main(int argc, char* argv[]) { spdlog::info("SDR++ v" VERSION_STR); #ifdef IS_MACOS_BUNDLE @@ -220,7 +220,7 @@ int sdrpp_main(int argc, char *argv[]) { defConfig["moduleInstances"]["Frequency Manager"] = "frequency_manager"; defConfig["moduleInstances"]["Recorder"] = "recorder"; defConfig["moduleInstances"]["Rigctl Server"] = "rigctl_server"; - + // Themes defConfig["theme"] = "Dark"; @@ -321,8 +321,8 @@ int sdrpp_main(int argc, char *argv[]) { const char* glsl_version = "#version 150"; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Required on Mac + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 3.2+ only + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Required on Mac // Create window with graphics context GLFWmonitor* monitor = glfwGetPrimaryMonitor(); @@ -343,14 +343,14 @@ int sdrpp_main(int argc, char *argv[]) { monitor = glfwGetPrimaryMonitor(); core::window = glfwCreateWindow(winWidth, winHeight, "SDR++ v" VERSION_STR " (Built at " __TIME__ ", " __DATE__ ")", NULL, NULL); if (core::window == NULL) { - spdlog::info("OpenGL {0}.{1} {2}was not supported", OPENGL_VERSIONS_MAJOR[i], OPENGL_VERSIONS_MINOR[i], OPENGL_VERSIONS_IS_ES[i] ? "ES ": ""); + spdlog::info("OpenGL {0}.{1} {2}was not supported", OPENGL_VERSIONS_MAJOR[i], OPENGL_VERSIONS_MINOR[i], OPENGL_VERSIONS_IS_ES[i] ? "ES " : ""); continue; } - spdlog::info("Using OpenGL {0}.{1}{2}", OPENGL_VERSIONS_MAJOR[i], OPENGL_VERSIONS_MINOR[i], OPENGL_VERSIONS_IS_ES[i] ? " ES": ""); + spdlog::info("Using OpenGL {0}.{1}{2}", OPENGL_VERSIONS_MAJOR[i], OPENGL_VERSIONS_MINOR[i], OPENGL_VERSIONS_IS_ES[i] ? " ES" : ""); glfwMakeContextCurrent(core::window); break; } - + #endif // Add callback for max/min if GLFW supports it @@ -370,15 +370,24 @@ int sdrpp_main(int argc, char *argv[]) { GLFWimage icons[10]; icons[0].pixels = stbi_load(((std::string)(resDir + "/icons/sdrpp.png")).c_str(), &icons[0].width, &icons[0].height, 0, 4); - icons[1].pixels = (unsigned char*)malloc(16 * 16 * 4); icons[1].width = icons[1].height = 16; - icons[2].pixels = (unsigned char*)malloc(24 * 24 * 4); icons[2].width = icons[2].height = 24; - icons[3].pixels = (unsigned char*)malloc(32 * 32 * 4); icons[3].width = icons[3].height = 32; - icons[4].pixels = (unsigned char*)malloc(48 * 48 * 4); icons[4].width = icons[4].height = 48; - icons[5].pixels = (unsigned char*)malloc(64 * 64 * 4); icons[5].width = icons[5].height = 64; - icons[6].pixels = (unsigned char*)malloc(96 * 96 * 4); icons[6].width = icons[6].height = 96; - icons[7].pixels = (unsigned char*)malloc(128 * 128 * 4); icons[7].width = icons[7].height = 128; - icons[8].pixels = (unsigned char*)malloc(196 * 196 * 4); icons[8].width = icons[8].height = 196; - icons[9].pixels = (unsigned char*)malloc(256 * 256 * 4); icons[9].width = icons[9].height = 256; + icons[1].pixels = (unsigned char*)malloc(16 * 16 * 4); + icons[1].width = icons[1].height = 16; + icons[2].pixels = (unsigned char*)malloc(24 * 24 * 4); + icons[2].width = icons[2].height = 24; + icons[3].pixels = (unsigned char*)malloc(32 * 32 * 4); + icons[3].width = icons[3].height = 32; + icons[4].pixels = (unsigned char*)malloc(48 * 48 * 4); + icons[4].width = icons[4].height = 48; + icons[5].pixels = (unsigned char*)malloc(64 * 64 * 4); + icons[5].width = icons[5].height = 64; + icons[6].pixels = (unsigned char*)malloc(96 * 96 * 4); + icons[6].width = icons[6].height = 96; + icons[7].pixels = (unsigned char*)malloc(128 * 128 * 4); + icons[7].width = icons[7].height = 128; + icons[8].pixels = (unsigned char*)malloc(196 * 196 * 4); + icons[8].width = icons[8].height = 196; + icons[9].pixels = (unsigned char*)malloc(256 * 256 * 4); + icons[9].width = icons[9].height = 256; stbir_resize_uint8(icons[0].pixels, icons[0].width, icons[0].height, icons[0].width * 4, icons[1].pixels, 16, 16, 16 * 4, 4); stbir_resize_uint8(icons[0].pixels, icons[0].width, icons[0].height, icons[0].width * 4, icons[2].pixels, 24, 24, 24 * 4, 4); stbir_resize_uint8(icons[0].pixels, icons[0].width, icons[0].height, icons[0].width * 4, icons[3].pixels, 32, 32, 32 * 4, 4); @@ -403,7 +412,8 @@ int sdrpp_main(int argc, char *argv[]) { // Setup Dear ImGui context IMGUI_CHECKVERSION(); ImGui::CreateContext(); - ImGuiIO& io = ImGui::GetIO(); (void)io; + ImGuiIO& io = ImGui::GetIO(); + (void)io; io.IniFilename = NULL; // Setup Platform/Renderer bindings @@ -445,7 +455,7 @@ int sdrpp_main(int argc, char *argv[]) { fsWidth = _winWidth; fsHeight = _winHeight; glfwGetWindowPos(core::window, &fsPosX, &fsPosY); - const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); + const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); glfwSetWindowMonitor(core::window, monitor, 0, 0, mode->width, mode->height, 0); } @@ -467,7 +477,7 @@ int sdrpp_main(int argc, char *argv[]) { if (_maximized != maximized) { _maximized = maximized; core::configManager.acquire(); - core::configManager.conf["maximized"]= _maximized; + core::configManager.conf["maximized"] = _maximized; if (!maximized) { glfwSetWindowSize(core::window, core::configManager.conf["windowSize"]["w"], core::configManager.conf["windowSize"]["h"]); } @@ -483,7 +493,7 @@ int sdrpp_main(int argc, char *argv[]) { fsWidth = _winWidth; fsHeight = _winHeight; glfwGetWindowPos(core::window, &fsPosX, &fsPosY); - const GLFWvidmode * mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); + const GLFWvidmode* mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); glfwSetWindowMonitor(core::window, monitor, 0, 0, mode->width, mode->height, 0); core::configManager.acquire(); core::configManager.conf["fullscreen"] = true; @@ -491,7 +501,7 @@ int sdrpp_main(int argc, char *argv[]) { } else { spdlog::info("Fullscreen: OFF"); - glfwSetWindowMonitor(core::window, nullptr, fsPosX, fsPosY, fsWidth, fsHeight, 0); + glfwSetWindowMonitor(core::window, nullptr, fsPosX, fsPosY, fsWidth, fsHeight, 0); core::configManager.acquire(); core::configManager.conf["fullscreen"] = false; core::configManager.release(); diff --git a/core/src/core.h b/core/src/core.h index c9d95b35..1b2dfa98 100644 --- a/core/src/core.h +++ b/core/src/core.h @@ -12,4 +12,4 @@ namespace core { void setInputSampleRate(double samplerate); }; -int sdrpp_main(int argc, char *argv[]); \ No newline at end of file +int sdrpp_main(int argc, char* argv[]); \ No newline at end of file diff --git a/core/src/dsp/audio.h b/core/src/dsp/audio.h index a9976a92..b51bf11d 100644 --- a/core/src/dsp/audio.h +++ b/core/src/dsp/audio.h @@ -40,7 +40,6 @@ namespace dsp { private: stream* _in; - }; class ChannelsToStereo : public generic_block { @@ -98,7 +97,6 @@ namespace dsp { stream* _in_right; float* nullbuf; - }; class StereoToMono : public generic_block { @@ -151,9 +149,8 @@ namespace dsp { stream out; private: - float* l_buf, *r_buf; + float *l_buf, *r_buf; stream* _in; - }; class StereoToChannels : public generic_block { @@ -197,6 +194,5 @@ namespace dsp { private: stream* _in; - }; } \ No newline at end of file diff --git a/core/src/dsp/block.h b/core/src/dsp/block.h index 2c959986..c67b0153 100644 --- a/core/src/dsp/block.h +++ b/core/src/dsp/block.h @@ -17,7 +17,7 @@ namespace dsp { virtual int calcOutSize(int inSize) { return inSize; } virtual int run() { return -1; } }; - + template class generic_block : public generic_unnamed_block { public: @@ -71,12 +71,12 @@ namespace dsp { } virtual int run() = 0; - + friend BLOCK; private: - void workerLoop() { - while (run() >= 0); + void workerLoop() { + while (run() >= 0) {} } void acquire() { @@ -139,7 +139,6 @@ namespace dsp { bool running = false; bool tempStopped = false; std::thread workerThread; - }; template @@ -224,6 +223,5 @@ namespace dsp { protected: bool _block_init = false; std::mutex ctrlMtx; - }; } \ No newline at end of file diff --git a/core/src/dsp/buffer.h b/core/src/dsp/buffer.h index 225cd5f4..ece1daab 100644 --- a/core/src/dsp/buffer.h +++ b/core/src/dsp/buffer.h @@ -47,7 +47,7 @@ namespace dsp { else { memcpy(&data[dataRead], &_buffer[readc], toRead * sizeof(T)); } - + dataRead += toRead; _readable_mtx.lock(); @@ -114,7 +114,7 @@ namespace dsp { int _r = getReadable(); if (_r != 0) { return _r; } std::unique_lock lck(_readable_mtx); - canReadVar.wait(lck, [=](){ return ((this->getReadable(false) > 0) || this->getReadStop()); }); + canReadVar.wait(lck, [=]() { return ((this->getReadable(false) > 0) || this->getReadStop()); }); if (_stopReader) { return -1; } return getReadable(false); } @@ -152,7 +152,7 @@ namespace dsp { writable -= toWrite; _writable_mtx.unlock(); writec = (writec + toWrite) % size; - + canReadVar.notify_one(); } return len; @@ -164,7 +164,7 @@ namespace dsp { int _w = getWritable(); if (_w != 0) { return _w; } std::unique_lock lck(_writable_mtx); - canWriteVar.wait(lck, [=](){ return ((this->getWritable(false) > 0) || this->getWriteStop()); }); + canWriteVar.wait(lck, [=]() { return ((this->getWritable(false) > 0) || this->getWriteStop()); }); if (_stopWriter) { return -1; } return getWritable(false); } @@ -173,7 +173,10 @@ namespace dsp { assert(_init); if (lock) { _writable_mtx.lock(); }; int _w = writable; - if (lock) { _writable_mtx.unlock(); _readable_mtx.lock(); }; + if (lock) { + _writable_mtx.unlock(); + _readable_mtx.lock(); + }; int _r = readable; if (lock) { _readable_mtx.unlock(); }; return std::max(std::min(_w, maxLatency - _r), 0); @@ -233,7 +236,7 @@ namespace dsp { std::condition_variable canWriteVar; }; -#define TEST_BUFFER_SIZE 32 +#define TEST_BUFFER_SIZE 32 template class SampleFrameBuffer : public generic_block> { @@ -303,7 +306,7 @@ namespace dsp { while (true) { // Wait for data std::unique_lock lck(bufMtx); - cnd.wait(lck, [this](){ return (((writeCur - readCur + TEST_BUFFER_SIZE) % TEST_BUFFER_SIZE) > 0) || stopWorker; }); + cnd.wait(lck, [this]() { return (((writeCur - readCur + TEST_BUFFER_SIZE) % TEST_BUFFER_SIZE) > 0) || stopWorker; }); if (stopWorker) { break; } // Write one to output buffer and unlock in preparation to swap buffers @@ -315,7 +318,7 @@ namespace dsp { // Swap if (!out.swap(count)) { break; } - } + } } stream out; @@ -352,8 +355,7 @@ namespace dsp { std::condition_variable cnd; T* buffers[TEST_BUFFER_SIZE]; int sizes[TEST_BUFFER_SIZE]; - - bool stopWorker = false; + bool stopWorker = false; }; }; diff --git a/core/src/dsp/chain.h b/core/src/dsp/chain.h index 1045d506..13a2fc1e 100644 --- a/core/src/dsp/chain.h +++ b/core/src/dsp/chain.h @@ -20,11 +20,11 @@ namespace dsp { class ChainLink : public ChainLinkAny { public: ~ChainLink() {} - + void setInput(stream* stream) { block.setInput(stream); } - + stream* getOutput() { return &block.out; } @@ -60,7 +60,7 @@ namespace dsp { spdlog::error("Could not add new link to the chain, link already in the chain"); return; } - + // Assert that the link is stopped and disabled link->stop(); link->enabled = false; @@ -85,7 +85,7 @@ namespace dsp { if (!(*i)->enabled) { continue; } input = (*i)->getOutput(); } - + // Find next block ChainLinkAny* nextLink = NULL; for (auto i = ++lnit; i < links.end(); i++) { @@ -127,7 +127,7 @@ namespace dsp { if (!(*i)->enabled) { continue; } input = (*i)->getOutput(); } - + // Find next block ChainLinkAny* nextLink = NULL; for (auto i = ++lnit; i < links.end(); i++) { @@ -157,7 +157,7 @@ namespace dsp { void setInput(stream* input) { _input = input; - + // Set input of first enabled link for (auto& ln : links) { if (!ln->enabled) { continue; } @@ -203,6 +203,5 @@ namespace dsp { stream* _input; std::vector*> links; bool running = false; - }; } \ No newline at end of file diff --git a/core/src/dsp/clock_recovery.h b/core/src/dsp/clock_recovery.h index 8e6eec4b..92a31f77 100644 --- a/core/src/dsp/clock_recovery.h +++ b/core/src/dsp/clock_recovery.h @@ -7,7 +7,7 @@ namespace dsp { class EdgeTrigClockRecovery : public generic_block { public: EdgeTrigClockRecovery() {} - + EdgeTrigClockRecovery(stream* in, int omega) { init(in, omega); } void init(stream* in, int omega) { @@ -51,7 +51,7 @@ namespace dsp { lastVal = _in->readBuf[i]; } - + _in->flush(); if (outCount > 0 && !out.swap(outCount)) { return -1; } return count; @@ -65,10 +65,9 @@ namespace dsp { int counter = 0; float lastVal = 0; stream* _in; - }; - template + template class MMClockRecovery : public generic_block> { public: MMClockRecovery() {} @@ -146,7 +145,7 @@ namespace dsp { int i = nextOffset; for (; i < count && outCount < maxOut;) { - + if constexpr (std::is_same_v) { // Calculate output value // If we still need to use the old values, calculate using delay buf @@ -160,7 +159,7 @@ namespace dsp { out.writeBuf[outCount++] = outVal; // Cursed phase detect approximation (don't ask me how this approximation works) - phaseError = (DSP_STEP(lastOutput)*outVal) - (lastOutput*DSP_STEP(outVal)); + phaseError = (DSP_STEP(lastOutput) * outVal) - (lastOutput * DSP_STEP(outVal)); lastOutput = outVal; } if constexpr (std::is_same_v || std::is_same_v) { @@ -195,7 +194,9 @@ namespace dsp { // TODO: Branchless clamp _dynOmega = _dynOmega + (_gainOmega * phaseError); if (_dynOmega > omegaMax) { _dynOmega = omegaMax; } - else if (_dynOmega < omegaMin) { _dynOmega = omegaMin; } + else if (_dynOmega < omegaMin) { + _dynOmega = omegaMin; + } // Adjust the symbol phase according to the phase error approximation // It will now contain the phase delta needed to jump to the next symbol @@ -215,7 +216,7 @@ namespace dsp { // Save the last 7 values for the next round memcpy(delay, &_in->readBuf[count - 7], 7 * sizeof(T)); - + _in->flush(); if (outCount > 0 && !out.swap(outCount)) { return -1; } return count; @@ -246,10 +247,9 @@ namespace dsp { float lastOutput = 0.0f; // Cursed complex stuff - complex_t _p_0T = {0,0}, _p_1T = {0,0}, _p_2T = {0,0}; - complex_t _c_0T = {0,0}, _c_1T = {0,0}, _c_2T = {0,0}; + complex_t _p_0T = { 0, 0 }, _p_1T = { 0, 0 }, _p_2T = { 0, 0 }; + complex_t _c_0T = { 0, 0 }, _c_1T = { 0, 0 }, _c_2T = { 0, 0 }; stream* _in; - }; } \ No newline at end of file diff --git a/core/src/dsp/compression.h b/core/src/dsp/compression.h index cf56117e..ee0db3d7 100644 --- a/core/src/dsp/compression.h +++ b/core/src/dsp/compression.h @@ -83,7 +83,7 @@ namespace dsp { else { _in->flush(); } - + return count; } @@ -92,13 +92,12 @@ namespace dsp { private: stream* _in; PCMType _pcmType; - }; class DynamicRangeDecompressor : public generic_block { public: DynamicRangeDecompressor() {} - + DynamicRangeDecompressor(stream* in) { init(in); } void init(stream* in) { @@ -147,8 +146,8 @@ namespace dsp { volk_16i_s32f_convert_32f((float*)out.writeBuf, (int16_t*)dataBuf, 32768.0f / absScale, outCount * 2); _in->flush(); if (!out.swap(outCount)) { return -1; } - } - + } + return count; } @@ -156,6 +155,5 @@ namespace dsp { private: stream* _in; - }; } \ No newline at end of file diff --git a/core/src/dsp/conversion.h b/core/src/dsp/conversion.h index e12aa470..593c3abc 100644 --- a/core/src/dsp/conversion.h +++ b/core/src/dsp/conversion.h @@ -42,7 +42,6 @@ namespace dsp { private: stream* _in; - }; class ComplexToReal : public generic_block { @@ -83,7 +82,6 @@ namespace dsp { private: stream* _in; - }; class ComplexToImag : public generic_block { @@ -116,7 +114,7 @@ namespace dsp { volk_32fc_deinterleave_imag_32f(out.writeBuf, (lv_32fc_t*)_in->readBuf, count); _in->flush(); - if(!out.swap(count)) { return -1; } + if (!out.swap(count)) { return -1; } return count; } @@ -124,7 +122,6 @@ namespace dsp { private: stream* _in; - }; @@ -176,7 +173,6 @@ namespace dsp { private: float* nullBuffer; stream* _in; - }; class Int16CToComplex : public generic_block { @@ -217,7 +213,6 @@ namespace dsp { private: stream* _in; - }; class ComplexToInt16C : public generic_block { @@ -258,7 +253,6 @@ namespace dsp { private: stream* _in; - }; class Int16ToFloat : public generic_block { @@ -299,7 +293,6 @@ namespace dsp { private: stream* _in; - }; class FloatToInt16 : public generic_block { @@ -340,6 +333,5 @@ namespace dsp { private: stream* _in; - }; } \ No newline at end of file diff --git a/core/src/dsp/correction.h b/core/src/dsp/correction.h index 133fe75a..ea2ffc8f 100644 --- a/core/src/dsp/correction.h +++ b/core/src/dsp/correction.h @@ -70,8 +70,6 @@ namespace dsp { private: stream* _in; float correctionRate = 0.00001; - - }; class DCBlocker : public generic_block { @@ -138,9 +136,7 @@ namespace dsp { private: stream* _in; float correctionRate = 0.00001; - - }; - + } \ No newline at end of file diff --git a/core/src/dsp/decimation.h b/core/src/dsp/decimation.h index 9287611a..58d63b0d 100644 --- a/core/src/dsp/decimation.h +++ b/core/src/dsp/decimation.h @@ -67,14 +67,14 @@ namespace dsp { int outIndex = 0; if constexpr (std::is_same_v) { while (inIndex < count) { - volk_32f_x2_dot_prod_32f((float*)&out.writeBuf[outIndex], (float*)&buffer[inIndex+1], taps, tapCount); + volk_32f_x2_dot_prod_32f((float*)&out.writeBuf[outIndex], (float*)&buffer[inIndex + 1], taps, tapCount); inIndex += 2; outIndex++; } } if constexpr (std::is_same_v) { while (inIndex < count) { - volk_32fc_32f_dot_prod_32fc((lv_32fc_t*)&out.writeBuf[outIndex], (lv_32fc_t*)&buffer[inIndex+1], taps, tapCount); + volk_32fc_32f_dot_prod_32fc((lv_32fc_t*)&out.writeBuf[outIndex], (lv_32fc_t*)&buffer[inIndex + 1], taps, tapCount); inIndex += 2; outIndex++; } @@ -84,7 +84,7 @@ namespace dsp { if (!out.swap(outIndex)) { return -1; } memmove(buffer, &buffer[count], tapCount * sizeof(T)); - + return count; } @@ -102,6 +102,5 @@ namespace dsp { int tapCount; float* taps; int _inIndex = 0; - }; } \ No newline at end of file diff --git a/core/src/dsp/deframing.h b/core/src/dsp/deframing.h index 4b8df54a..058fa2f1 100644 --- a/core/src/dsp/deframing.h +++ b/core/src/dsp/deframing.h @@ -2,8 +2,8 @@ #include #include -#define DSP_SIGN(n) ((n) >= 0) -#define DSP_STEP(n) (((n) > 0.0f) ? 1.0f : -1.0f) +#define DSP_SIGN(n) ((n) >= 0) +#define DSP_STEP(n) (((n) > 0.0f) ? 1.0f : -1.0f) namespace dsp { class Deframer : public generic_block { @@ -21,14 +21,14 @@ namespace dsp { void init(stream* in, int frameLen, uint8_t* syncWord, int syncLen) { _in = in; _frameLen = frameLen; - _syncword = new uint8_t[syncLen]; + _syncword = new uint8_t[syncLen]; _syncLen = syncLen; memcpy(_syncword, syncWord, syncLen); buffer = new uint8_t[STREAM_BUFFER_SIZE + syncLen]; memset(buffer, 0, syncLen); bufferStart = buffer + syncLen; - + generic_block::registerInput(_in); generic_block::registerOutput(&out); generic_block::_block_init = true; @@ -54,7 +54,7 @@ namespace dsp { // Iterate through all symbols for (int i = 0; i < count;) { - // If already in the process of reading bits + // If already in the process of reading bits if (bitsRead >= 0) { if ((bitsRead % 8) == 0) { out.writeBuf[bitsRead / 8] = 0; } out.writeBuf[bitsRead / 8] |= (buffer[i] << (7 - (bitsRead % 8))); @@ -80,27 +80,27 @@ namespace dsp { else if (nextBitIsStartOfFrame) { nextBitIsStartOfFrame = false; - // try to save + // try to save if (badFrameCount < 5) { badFrameCount++; //printf("Frame found!\n"); bitsRead = 0; continue; } - } - else { i++; } + else { + i++; + } nextBitIsStartOfFrame = false; - } // Keep last _syncLen4 symbols memcpy(buffer, &_in->readBuf[count - _syncLen], _syncLen); - + //printf("Block processed\n"); - callcount++; + callcount++; _in->flush(); return count; @@ -123,15 +123,14 @@ namespace dsp { bool nextBitIsStartOfFrame = false; int callcount = 0; - - stream* _in; + stream* _in; }; inline int MachesterHammingDistance(float* data, uint8_t* syncBits, int n) { int dist = 0; for (int i = 0; i < n; i++) { - if ((data[(2*i) + 1] > data[2*i]) != syncBits[i]) { dist++; } + if ((data[(2 * i) + 1] > data[2 * i]) != syncBits[i]) { dist++; } } return dist; } @@ -153,14 +152,14 @@ namespace dsp { void init(stream* in, int frameLen, uint8_t* syncWord, int syncLen) { _in = in; _frameLen = frameLen; - _syncword = new uint8_t[syncLen]; + _syncword = new uint8_t[syncLen]; _syncLen = syncLen; memcpy(_syncword, syncWord, syncLen); buffer = new float[STREAM_BUFFER_SIZE + (syncLen * 2)]; memset(buffer, 0, syncLen * 2 * sizeof(float)); bufferStart = &buffer[syncLen * 2]; - + generic_block::registerInput(_in); generic_block::registerOutput(&out); generic_block::_block_init = true; @@ -188,7 +187,7 @@ namespace dsp { // Iterate through all symbols for (int i = 0; i < count;) { - // If already in the process of reading bits + // If already in the process of reading bits if (bitsRead >= 0) { readable = std::min(count - i, _frameLen - bitsRead); memcpy(&out.writeBuf[bitsRead], &buffer[i], readable * sizeof(float)); @@ -208,7 +207,6 @@ namespace dsp { } i++; - } // Keep last _syncLen symbols @@ -228,9 +226,8 @@ namespace dsp { int _frameLen; int _syncLen; int bitsRead = -1; - - stream* _in; + stream* _in; }; class SymbolDeframer : public generic_block { @@ -242,14 +239,14 @@ namespace dsp { void init(stream* in, int frameLen, uint8_t* syncWord, int syncLen) { _in = in; _frameLen = frameLen; - _syncword = new uint8_t[syncLen]; + _syncword = new uint8_t[syncLen]; _syncLen = syncLen; memcpy(_syncword, syncWord, syncLen); buffer = new uint8_t[STREAM_BUFFER_SIZE + syncLen]; memset(buffer, 0, syncLen); bufferStart = &buffer[syncLen]; - + generic_block::registerInput(_in); generic_block::registerOutput(&out); generic_block::_block_init = true; @@ -277,7 +274,7 @@ namespace dsp { // Iterate through all symbols for (int i = 0; i < count;) { - // If already in the process of reading bits + // If already in the process of reading bits if (bitsRead >= 0) { readable = std::min(count - i, _frameLen - bitsRead); memcpy(&out.writeBuf[bitsRead], &buffer[i], readable); @@ -297,7 +294,6 @@ namespace dsp { } i++; - } // Keep last _syncLen symbols @@ -317,9 +313,8 @@ namespace dsp { int _frameLen; int _syncLen; int bitsRead = -1; - - stream* _in; + stream* _in; }; class ManchesterDecoder : public generic_block { @@ -352,12 +347,12 @@ namespace dsp { if (_inverted) { for (int i = 0; i < count; i += 2) { - out.writeBuf[i/2] = (_in->readBuf[i + 1] < _in->readBuf[i]); + out.writeBuf[i / 2] = (_in->readBuf[i + 1] < _in->readBuf[i]); } } else { for (int i = 0; i < count; i += 2) { - out.writeBuf[i/2] = (_in->readBuf[i + 1] > _in->readBuf[i]); + out.writeBuf[i / 2] = (_in->readBuf[i + 1] > _in->readBuf[i]); } } @@ -371,7 +366,6 @@ namespace dsp { private: stream* _in; bool _inverted; - }; class BitPacker : public generic_block { @@ -382,7 +376,7 @@ namespace dsp { void init(stream* in) { _in = in; - + generic_block::registerInput(_in); generic_block::registerOutput(&out); generic_block::_block_init = true; @@ -415,8 +409,6 @@ namespace dsp { stream out; private: - stream* _in; - }; } \ No newline at end of file diff --git a/core/src/dsp/demodulator.h b/core/src/dsp/demodulator.h index 4ef49610..545949cc 100644 --- a/core/src/dsp/demodulator.h +++ b/core/src/dsp/demodulator.h @@ -13,14 +13,14 @@ #include #include -#define FAST_ATAN2_COEF1 FL_M_PI / 4.0f -#define FAST_ATAN2_COEF2 3.0f * FAST_ATAN2_COEF1 +#define FAST_ATAN2_COEF1 FL_M_PI / 4.0f +#define FAST_ATAN2_COEF2 3.0f * FAST_ATAN2_COEF1 inline float fast_arctan2(float y, float x) { float abs_y = fabsf(y); float r, angle; if (x == 0.0f && y == 0.0f) { return 0.0f; } - if (x>=0.0f) { + if (x >= 0.0f) { r = (x - abs_y) / (x + abs_y); angle = FAST_ATAN2_COEF1 - FAST_ATAN2_COEF1 * r; } @@ -98,8 +98,10 @@ namespace dsp { for (int i = 0; i < count; i++) { currentPhase = fast_arctan2(_in->readBuf[i].im, _in->readBuf[i].re); diff = currentPhase - phase; - if (diff > 3.1415926535f) { diff -= 2 * 3.1415926535f; } - else if (diff <= -3.1415926535f) { diff += 2 * 3.1415926535f; } + if (diff > 3.1415926535f) { diff -= 2 * 3.1415926535f; } + else if (diff <= -3.1415926535f) { + diff += 2 * 3.1415926535f; + } out.writeBuf[i] = diff / phasorSpeed; phase = currentPhase; } @@ -115,7 +117,6 @@ namespace dsp { float phase = 0; float phasorSpeed, _sampleRate, _deviation; stream* _in; - }; class FMDemod : public generic_block { @@ -179,8 +180,10 @@ namespace dsp { for (int i = 0; i < count; i++) { currentPhase = fast_arctan2(_in->readBuf[i].im, _in->readBuf[i].re); diff = currentPhase - phase; - if (diff > 3.1415926535f) { diff -= 2 * 3.1415926535f; } - else if (diff <= -3.1415926535f) { diff += 2 * 3.1415926535f; } + if (diff > 3.1415926535f) { diff -= 2 * 3.1415926535f; } + else if (diff <= -3.1415926535f) { + diff += 2 * 3.1415926535f; + } out.writeBuf[i].l = diff / phasorSpeed; out.writeBuf[i].r = diff / phasorSpeed; phase = currentPhase; @@ -197,7 +200,6 @@ namespace dsp { float phase = 0; float phasorSpeed, _sampleRate, _deviation; stream* _in; - }; class AMDemod : public generic_block { @@ -245,7 +247,6 @@ namespace dsp { private: stream* _in; float avg = 0; - }; class SSBDemod : public generic_block { @@ -369,25 +370,24 @@ namespace dsp { lv_32fc_t* buffer; lv_32fc_t phase; lv_32fc_t phaseDelta; - }; class FSKDemod : public generic_hier_block { public: FSKDemod() {} - FSKDemod(stream* input, float sampleRate, float deviation, float baudRate, float omegaGain = (0.01*0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { + FSKDemod(stream* input, float sampleRate, float deviation, float baudRate, float omegaGain = (0.01 * 0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { init(input, sampleRate, deviation, baudRate, omegaGain, muGain, omegaRelLimit); } - void init(stream* input, float sampleRate, float deviation, float baudRate, float omegaGain = (0.01*0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { + void init(stream* input, float sampleRate, float deviation, float baudRate, float omegaGain = (0.01 * 0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { _sampleRate = sampleRate; _deviation = deviation; _baudRate = baudRate; _omegaGain = omegaGain; _muGain = muGain; _omegaRelLimit = omegaRelLimit; - + demod.init(input, _sampleRate, _deviation); recov.init(&demod.out, _sampleRate / _baudRate, _omegaGain, _muGain, _omegaRelLimit); out = &recov.out; @@ -455,11 +455,11 @@ namespace dsp { public: GFSKDemod() {} - GFSKDemod(stream* input, float sampleRate, float deviation, float rrcAlpha, float baudRate, float omegaGain = (0.01*0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { + GFSKDemod(stream* input, float sampleRate, float deviation, float rrcAlpha, float baudRate, float omegaGain = (0.01 * 0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { init(input, sampleRate, deviation, rrcAlpha, baudRate, omegaGain, muGain, omegaRelLimit); } - void init(stream* input, float sampleRate, float deviation, float rrcAlpha, float baudRate, float omegaGain = (0.01*0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { + void init(stream* input, float sampleRate, float deviation, float rrcAlpha, float baudRate, float omegaGain = (0.01 * 0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { _sampleRate = sampleRate; _deviation = deviation; _rrcAlpha = rrcAlpha; @@ -467,7 +467,7 @@ namespace dsp { _omegaGain = omegaGain; _muGain = muGain; _omegaRelLimit = omegaRelLimit; - + demod.init(input, _sampleRate, _deviation); rrc.init(31, _sampleRate, _baudRate, _rrcAlpha); fir.init(&demod.out, &rrc); @@ -550,16 +550,16 @@ namespace dsp { float _omegaRelLimit; }; - template + template class PSKDemod : public generic_hier_block> { public: PSKDemod() {} - PSKDemod(stream* input, float sampleRate, float baudRate, int RRCTapCount = 31, float RRCAlpha = 0.32f, float agcRate = 10e-4, float costasLoopBw = 0.004f, float omegaGain = (0.01*0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { + PSKDemod(stream* input, float sampleRate, float baudRate, int RRCTapCount = 31, float RRCAlpha = 0.32f, float agcRate = 10e-4, float costasLoopBw = 0.004f, float omegaGain = (0.01 * 0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { init(input, sampleRate, baudRate, RRCTapCount, RRCAlpha, agcRate, costasLoopBw, omegaGain, muGain, omegaRelLimit); } - void init(stream* input, float sampleRate, float baudRate, int RRCTapCount = 31, float RRCAlpha = 0.32f, float agcRate = 10e-4, float costasLoopBw = 0.004f, float omegaGain = (0.01*0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { + void init(stream* input, float sampleRate, float baudRate, int RRCTapCount = 31, float RRCAlpha = 0.32f, float agcRate = 10e-4, float costasLoopBw = 0.004f, float omegaGain = (0.01 * 0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { _RRCTapCount = RRCTapCount; _RRCAlpha = RRCAlpha; _sampleRate = sampleRate; @@ -569,7 +569,7 @@ namespace dsp { _omegaGain = omegaGain; _muGain = muGain; _omegaRelLimit = omegaRelLimit; - + agc.init(input, 1.0f, 65535, _agcRate); taps.init(_RRCTapCount, _sampleRate, _baudRate, _RRCAlpha); rrc.init(&agc.out, &taps); @@ -583,7 +583,7 @@ namespace dsp { delay.init(&demod.out); recov.init(&delay.out, _sampleRate / _baudRate, _omegaGain, _muGain, _omegaRelLimit); generic_hier_block>::registerBlock(&delay); - } + } else { recov.init(&demod.out, _sampleRate / _baudRate, _omegaGain, _muGain, _omegaRelLimit); } @@ -683,11 +683,11 @@ namespace dsp { public: PMDemod() {} - PMDemod(stream* input, float sampleRate, float baudRate, float agcRate = 0.02e-3f, float pllLoopBandwidth = (0.06f*0.06f) / 4.0f, int rrcTapCount = 31, float rrcAlpha = 0.6f, float omegaGain = (0.01*0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { + PMDemod(stream* input, float sampleRate, float baudRate, float agcRate = 0.02e-3f, float pllLoopBandwidth = (0.06f * 0.06f) / 4.0f, int rrcTapCount = 31, float rrcAlpha = 0.6f, float omegaGain = (0.01 * 0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { init(input, sampleRate, baudRate, agcRate, pllLoopBandwidth, rrcTapCount, rrcAlpha, omegaGain, muGain, omegaRelLimit); } - void init(stream* input, float sampleRate, float baudRate, float agcRate = 0.02e-3f, float pllLoopBandwidth = (0.06f*0.06f) / 4.0f, int rrcTapCount = 31, float rrcAlpha = 0.6f, float omegaGain = (0.01*0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { + void init(stream* input, float sampleRate, float baudRate, float agcRate = 0.02e-3f, float pllLoopBandwidth = (0.06f * 0.06f) / 4.0f, int rrcTapCount = 31, float rrcAlpha = 0.6f, float omegaGain = (0.01 * 0.01) / 4, float muGain = 0.01f, float omegaRelLimit = 0.005f) { _sampleRate = sampleRate; _baudRate = baudRate; _agcRate = agcRate; @@ -697,7 +697,7 @@ namespace dsp { _omegaGain = omegaGain; _muGain = muGain; _omegaRelLimit = omegaRelLimit; - + agc.init(input, 1.0f, 65535, _agcRate); pll.init(&agc.out, _pllLoopBandwidth); rrcwin.init(_rrcTapCount, _sampleRate, _baudRate, _rrcAlpha); @@ -796,7 +796,7 @@ namespace dsp { recon.init(&demux.AplusBOut, &demux.AminusBOut); out = &recon.out; - + generic_hier_block::registerBlock(&demod); generic_hier_block::registerBlock(&r2c); generic_hier_block::registerBlock(&pilotFilter); diff --git a/core/src/dsp/falcon_fec.h b/core/src/dsp/falcon_fec.h index 8c579735..73f012af 100644 --- a/core/src/dsp/falcon_fec.h +++ b/core/src/dsp/falcon_fec.h @@ -3,37 +3,36 @@ #include // WTF??? -extern "C" -{ +extern "C" { #include } -const uint8_t toDB[] = { -0x00, 0x7b, 0xaf, 0xd4, 0x99, 0xe2, 0x36, 0x4d, 0xfa, 0x81, 0x55, 0x2e, 0x63, 0x18, 0xcc, 0xb7, 0x86, 0xfd, 0x29, 0x52, 0x1f, - 0x64, 0xb0, 0xcb, 0x7c, 0x07, 0xd3, 0xa8, 0xe5, 0x9e, 0x4a, 0x31, 0xec, 0x97, 0x43, 0x38, 0x75, 0x0e, 0xda, 0xa1, 0x16, 0x6d, 0xb9, 0xc2, 0x8f, 0xf4, - 0x20, 0x5b, 0x6a, 0x11, 0xc5, 0xbe, 0xf3, 0x88, 0x5c, 0x27, 0x90, 0xeb, 0x3f, 0x44, 0x09, 0x72, 0xa6, 0xdd, 0xef, 0x94, 0x40, 0x3b, 0x76, 0x0d, 0xd9, - 0xa2, 0x15, 0x6e, 0xba, 0xc1, 0x8c, 0xf7, 0x23, 0x58, 0x69, 0x12, 0xc6, 0xbd, 0xf0, 0x8b, 0x5f, 0x24, 0x93, 0xe8, 0x3c, 0x47, 0x0a, 0x71, 0xa5, 0xde, - 0x03, 0x78, 0xac, 0xd7, 0x9a, 0xe1, 0x35, 0x4e, 0xf9, 0x82, 0x56, 0x2d, 0x60, 0x1b, 0xcf, 0xb4, 0x85, 0xfe, 0x2a, 0x51, 0x1c, 0x67, 0xb3, 0xc8, 0x7f, - 0x04, 0xd0, 0xab, 0xe6, 0x9d, 0x49, 0x32, 0x8d, 0xf6, 0x22, 0x59, 0x14, 0x6f, 0xbb, 0xc0, 0x77, 0x0c, 0xd8, 0xa3, 0xee, 0x95, 0x41, 0x3a, 0x0b, 0x70, - 0xa4, 0xdf, 0x92, 0xe9, 0x3d, 0x46, 0xf1, 0x8a, 0x5e, 0x25, 0x68, 0x13, 0xc7, 0xbc, 0x61, 0x1a, 0xce, 0xb5, 0xf8, 0x83, 0x57, 0x2c, 0x9b, 0xe0, 0x34, - 0x4f, 0x02, 0x79, 0xad, 0xd6, 0xe7, 0x9c, 0x48, 0x33, 0x7e, 0x05, 0xd1, 0xaa, 0x1d, 0x66, 0xb2, 0xc9, 0x84, 0xff, 0x2b, 0x50, 0x62, 0x19, 0xcd, 0xb6, - 0xfb, 0x80, 0x54, 0x2f, 0x98, 0xe3, 0x37, 0x4c, 0x01, 0x7a, 0xae, 0xd5, 0xe4, 0x9f, 0x4b, 0x30, 0x7d, 0x06, 0xd2, 0xa9, 0x1e, 0x65, 0xb1, 0xca, 0x87, - 0xfc, 0x28, 0x53, 0x8e, 0xf5, 0x21, 0x5a, 0x17, 0x6c, 0xb8, 0xc3, 0x74, 0x0f, 0xdb, 0xa0, 0xed, 0x96, 0x42, 0x39, 0x08, 0x73, 0xa7, 0xdc, 0x91, 0xea, - 0x3e, 0x45, 0xf2, 0x89, 0x5d, 0x26, 0x6b, 0x10, 0xc4, 0xbf +const uint8_t toDB[] = { + 0x00, 0x7b, 0xaf, 0xd4, 0x99, 0xe2, 0x36, 0x4d, 0xfa, 0x81, 0x55, 0x2e, 0x63, 0x18, 0xcc, 0xb7, 0x86, 0xfd, 0x29, 0x52, 0x1f, + 0x64, 0xb0, 0xcb, 0x7c, 0x07, 0xd3, 0xa8, 0xe5, 0x9e, 0x4a, 0x31, 0xec, 0x97, 0x43, 0x38, 0x75, 0x0e, 0xda, 0xa1, 0x16, 0x6d, 0xb9, 0xc2, 0x8f, 0xf4, + 0x20, 0x5b, 0x6a, 0x11, 0xc5, 0xbe, 0xf3, 0x88, 0x5c, 0x27, 0x90, 0xeb, 0x3f, 0x44, 0x09, 0x72, 0xa6, 0xdd, 0xef, 0x94, 0x40, 0x3b, 0x76, 0x0d, 0xd9, + 0xa2, 0x15, 0x6e, 0xba, 0xc1, 0x8c, 0xf7, 0x23, 0x58, 0x69, 0x12, 0xc6, 0xbd, 0xf0, 0x8b, 0x5f, 0x24, 0x93, 0xe8, 0x3c, 0x47, 0x0a, 0x71, 0xa5, 0xde, + 0x03, 0x78, 0xac, 0xd7, 0x9a, 0xe1, 0x35, 0x4e, 0xf9, 0x82, 0x56, 0x2d, 0x60, 0x1b, 0xcf, 0xb4, 0x85, 0xfe, 0x2a, 0x51, 0x1c, 0x67, 0xb3, 0xc8, 0x7f, + 0x04, 0xd0, 0xab, 0xe6, 0x9d, 0x49, 0x32, 0x8d, 0xf6, 0x22, 0x59, 0x14, 0x6f, 0xbb, 0xc0, 0x77, 0x0c, 0xd8, 0xa3, 0xee, 0x95, 0x41, 0x3a, 0x0b, 0x70, + 0xa4, 0xdf, 0x92, 0xe9, 0x3d, 0x46, 0xf1, 0x8a, 0x5e, 0x25, 0x68, 0x13, 0xc7, 0xbc, 0x61, 0x1a, 0xce, 0xb5, 0xf8, 0x83, 0x57, 0x2c, 0x9b, 0xe0, 0x34, + 0x4f, 0x02, 0x79, 0xad, 0xd6, 0xe7, 0x9c, 0x48, 0x33, 0x7e, 0x05, 0xd1, 0xaa, 0x1d, 0x66, 0xb2, 0xc9, 0x84, 0xff, 0x2b, 0x50, 0x62, 0x19, 0xcd, 0xb6, + 0xfb, 0x80, 0x54, 0x2f, 0x98, 0xe3, 0x37, 0x4c, 0x01, 0x7a, 0xae, 0xd5, 0xe4, 0x9f, 0x4b, 0x30, 0x7d, 0x06, 0xd2, 0xa9, 0x1e, 0x65, 0xb1, 0xca, 0x87, + 0xfc, 0x28, 0x53, 0x8e, 0xf5, 0x21, 0x5a, 0x17, 0x6c, 0xb8, 0xc3, 0x74, 0x0f, 0xdb, 0xa0, 0xed, 0x96, 0x42, 0x39, 0x08, 0x73, 0xa7, 0xdc, 0x91, 0xea, + 0x3e, 0x45, 0xf2, 0x89, 0x5d, 0x26, 0x6b, 0x10, 0xc4, 0xbf }; const uint8_t fromDB[] = { 0x00, 0xcc, 0xac, 0x60, 0x79, 0xb5, 0xd5, 0x19, 0xf0, 0x3c, 0x5c, 0x90, 0x89, 0x45, 0x25, 0xe9, 0xfd, 0x31, 0x51, 0x9d, - 0x84, 0x48, 0x28, 0xe4, 0x0d, 0xc1, 0xa1, 0x6d, 0x74, 0xb8, 0xd8, 0x14, 0x2e, 0xe2, 0x82, 0x4e, 0x57, 0x9b, 0xfb, 0x37, 0xde, 0x12, 0x72, 0xbe, 0xa7, - 0x6b, 0x0b, 0xc7, 0xd3, 0x1f, 0x7f, 0xb3, 0xaa, 0x66, 0x06, 0xca, 0x23, 0xef, 0x8f, 0x43, 0x5a, 0x96, 0xf6, 0x3a, 0x42, 0x8e, 0xee, 0x22, 0x3b, 0xf7, - 0x97, 0x5b, 0xb2, 0x7e, 0x1e, 0xd2, 0xcb, 0x07, 0x67, 0xab, 0xbf, 0x73, 0x13, 0xdf, 0xc6, 0x0a, 0x6a, 0xa6, 0x4f, 0x83, 0xe3, 0x2f, 0x36, 0xfa, 0x9a, - 0x56, 0x6c, 0xa0, 0xc0, 0x0c, 0x15, 0xd9, 0xb9, 0x75, 0x9c, 0x50, 0x30, 0xfc, 0xe5, 0x29, 0x49, 0x85, 0x91, 0x5d, 0x3d, 0xf1, 0xe8, 0x24, 0x44, 0x88, - 0x61, 0xad, 0xcd, 0x01, 0x18, 0xd4, 0xb4, 0x78, 0xc5, 0x09, 0x69, 0xa5, 0xbc, 0x70, 0x10, 0xdc, 0x35, 0xf9, 0x99, 0x55, 0x4c, 0x80, 0xe0, 0x2c, 0x38, - 0xf4, 0x94, 0x58, 0x41, 0x8d, 0xed, 0x21, 0xc8, 0x04, 0x64, 0xa8, 0xb1, 0x7d, 0x1d, 0xd1, 0xeb, 0x27, 0x47, 0x8b, 0x92, 0x5e, 0x3e, 0xf2, 0x1b, 0xd7, - 0xb7, 0x7b, 0x62, 0xae, 0xce, 0x02, 0x16, 0xda, 0xba, 0x76, 0x6f, 0xa3, 0xc3, 0x0f, 0xe6, 0x2a, 0x4a, 0x86, 0x9f, 0x53, 0x33, 0xff, 0x87, 0x4b, 0x2b, - 0xe7, 0xfe, 0x32, 0x52, 0x9e, 0x77, 0xbb, 0xdb, 0x17, 0x0e, 0xc2, 0xa2, 0x6e, 0x7a, 0xb6, 0xd6, 0x1a, 0x03, 0xcf, 0xaf, 0x63, 0x8a, 0x46, 0x26, 0xea, - 0xf3, 0x3f, 0x5f, 0x93, 0xa9, 0x65, 0x05, 0xc9, 0xd0, 0x1c, 0x7c, 0xb0, 0x59, 0x95, 0xf5, 0x39, 0x20, 0xec, 0x8c, 0x40, 0x54, 0x98, 0xf8, 0x34, 0x2d, - 0xe1, 0x81, 0x4d, 0xa4, 0x68, 0x08, 0xc4, 0xdd, 0x11, 0x71, 0xbd + 0x84, 0x48, 0x28, 0xe4, 0x0d, 0xc1, 0xa1, 0x6d, 0x74, 0xb8, 0xd8, 0x14, 0x2e, 0xe2, 0x82, 0x4e, 0x57, 0x9b, 0xfb, 0x37, 0xde, 0x12, 0x72, 0xbe, 0xa7, + 0x6b, 0x0b, 0xc7, 0xd3, 0x1f, 0x7f, 0xb3, 0xaa, 0x66, 0x06, 0xca, 0x23, 0xef, 0x8f, 0x43, 0x5a, 0x96, 0xf6, 0x3a, 0x42, 0x8e, 0xee, 0x22, 0x3b, 0xf7, + 0x97, 0x5b, 0xb2, 0x7e, 0x1e, 0xd2, 0xcb, 0x07, 0x67, 0xab, 0xbf, 0x73, 0x13, 0xdf, 0xc6, 0x0a, 0x6a, 0xa6, 0x4f, 0x83, 0xe3, 0x2f, 0x36, 0xfa, 0x9a, + 0x56, 0x6c, 0xa0, 0xc0, 0x0c, 0x15, 0xd9, 0xb9, 0x75, 0x9c, 0x50, 0x30, 0xfc, 0xe5, 0x29, 0x49, 0x85, 0x91, 0x5d, 0x3d, 0xf1, 0xe8, 0x24, 0x44, 0x88, + 0x61, 0xad, 0xcd, 0x01, 0x18, 0xd4, 0xb4, 0x78, 0xc5, 0x09, 0x69, 0xa5, 0xbc, 0x70, 0x10, 0xdc, 0x35, 0xf9, 0x99, 0x55, 0x4c, 0x80, 0xe0, 0x2c, 0x38, + 0xf4, 0x94, 0x58, 0x41, 0x8d, 0xed, 0x21, 0xc8, 0x04, 0x64, 0xa8, 0xb1, 0x7d, 0x1d, 0xd1, 0xeb, 0x27, 0x47, 0x8b, 0x92, 0x5e, 0x3e, 0xf2, 0x1b, 0xd7, + 0xb7, 0x7b, 0x62, 0xae, 0xce, 0x02, 0x16, 0xda, 0xba, 0x76, 0x6f, 0xa3, 0xc3, 0x0f, 0xe6, 0x2a, 0x4a, 0x86, 0x9f, 0x53, 0x33, 0xff, 0x87, 0x4b, 0x2b, + 0xe7, 0xfe, 0x32, 0x52, 0x9e, 0x77, 0xbb, 0xdb, 0x17, 0x0e, 0xc2, 0xa2, 0x6e, 0x7a, 0xb6, 0xd6, 0x1a, 0x03, 0xcf, 0xaf, 0x63, 0x8a, 0x46, 0x26, 0xea, + 0xf3, 0x3f, 0x5f, 0x93, 0xa9, 0x65, 0x05, 0xc9, 0xd0, 0x1c, 0x7c, 0xb0, 0x59, 0x95, 0xf5, 0x39, 0x20, 0xec, 0x8c, 0x40, 0x54, 0x98, 0xf8, 0x34, 0x2d, + 0xe1, 0x81, 0x4d, 0xa4, 0x68, 0x08, 0xc4, 0xdd, 0x11, 0x71, 0xbd }; const uint8_t randVals[] = { @@ -69,7 +68,7 @@ namespace dsp { for (int i = 0; i < 5; i++) { memset(outBuffers[i], 0, 255); } rs = correct_reed_solomon_create(correct_rs_primitive_polynomial_ccsds, 120, 11, 16); if (rs == NULL) { printf("Error creating the reed solomon decoder\n"); } - + generic_block::registerInput(_in); generic_block::registerOutput(&out); generic_block::_block_init = true; @@ -92,29 +91,44 @@ namespace dsp { uint8_t* data = _in->readBuf + 4; // Deinterleave - for (int i = 0; i < 255*5; i++) { - buffers[i%5][i/5] = fromDB[data[i]]; + for (int i = 0; i < 255 * 5; i++) { + buffers[i % 5][i / 5] = fromDB[data[i]]; } // Reed the solomon :weary: int result = 0; result = correct_reed_solomon_decode(rs, buffers[0], 255, outBuffers[0]); - if (result == -1) { _in->flush(); return count; } + if (result == -1) { + _in->flush(); + return count; + } result = correct_reed_solomon_decode(rs, buffers[1], 255, outBuffers[1]); - if (result == -1) { _in->flush(); return count; } + if (result == -1) { + _in->flush(); + return count; + } result = correct_reed_solomon_decode(rs, buffers[2], 255, outBuffers[2]); - if (result == -1) { _in->flush(); return count; } + if (result == -1) { + _in->flush(); + return count; + } result = correct_reed_solomon_decode(rs, buffers[3], 255, outBuffers[3]); - if (result == -1) { _in->flush(); return count; } + if (result == -1) { + _in->flush(); + return count; + } result = correct_reed_solomon_decode(rs, buffers[4], 255, outBuffers[4]); - if (result == -1) { _in->flush(); return count; } - - // Reinterleave - for (int i = 0; i < 255*5; i++) { - out.writeBuf[i] = toDB[outBuffers[i%5][i/5]] ^ randVals[i % 255]; + if (result == -1) { + _in->flush(); + return count; } - out.swap(255*5); + // Reinterleave + for (int i = 0; i < 255 * 5; i++) { + out.writeBuf[i] = toDB[outBuffers[i % 5][i / 5]] ^ randVals[i % 255]; + } + + out.swap(255 * 5); _in->flush(); return count; @@ -127,8 +141,7 @@ namespace dsp { uint8_t buffers[5][255]; uint8_t outBuffers[5][255]; correct_reed_solomon* rs; - - stream* _in; + stream* _in; }; } \ No newline at end of file diff --git a/core/src/dsp/falcon_packet.h b/core/src/dsp/falcon_packet.h index c4cdce5e..c1486dba 100644 --- a/core/src/dsp/falcon_packet.h +++ b/core/src/dsp/falcon_packet.h @@ -16,7 +16,7 @@ namespace dsp { void init(stream* in) { _in = in; - + generic_block::registerInput(_in); generic_block::registerOutput(&out); generic_block::_block_init = true; @@ -63,7 +63,7 @@ namespace dsp { else if (header.packet == 2047) { printf("Wow, all data\n"); _in->flush(); - return count; + return count; } // Finish reading the last package and send it @@ -91,9 +91,8 @@ namespace dsp { packetRead = -1; break; } - - uint64_t pktId = ((uint64_t)data[i + 2] << 56) | ((uint64_t)data[i + 3] << 48) | ((uint64_t)data[i + 4] << 40) | ((uint64_t)data[i + 5] << 32) - | ((uint64_t)data[i + 6] << 24) | ((uint64_t)data[i + 7] << 16) | ((uint64_t)data[i + 8] << 8) | data[i + 9]; + + uint64_t pktId = ((uint64_t)data[i + 2] << 56) | ((uint64_t)data[i + 3] << 48) | ((uint64_t)data[i + 4] << 40) | ((uint64_t)data[i + 5] << 32) | ((uint64_t)data[i + 6] << 24) | ((uint64_t)data[i + 7] << 16) | ((uint64_t)data[i + 8] << 8) | data[i + 9]; // If the packet doesn't fit the frame, save and go to next frame if (dataLen - i < length) { @@ -106,7 +105,6 @@ namespace dsp { memcpy(out.writeBuf, &data[i], length); out.swap(length); i += length; - } _in->flush(); @@ -121,8 +119,7 @@ namespace dsp { int packetRead = -1; uint8_t packet[0x4008]; - - stream* _in; + stream* _in; }; } \ No newline at end of file diff --git a/core/src/dsp/filter.h b/core/src/dsp/filter.h index 463ac92d..ce6e7624 100644 --- a/core/src/dsp/filter.h +++ b/core/src/dsp/filter.h @@ -66,12 +66,12 @@ namespace dsp { if constexpr (std::is_same_v) { for (int i = 0; i < count; i++) { - volk_32f_x2_dot_prod_32f((float*)&out.writeBuf[i], (float*)&buffer[i+1], taps, tapCount); + volk_32f_x2_dot_prod_32f((float*)&out.writeBuf[i], (float*)&buffer[i + 1], taps, tapCount); } } if constexpr (std::is_same_v) { for (int i = 0; i < count; i++) { - volk_32fc_32f_dot_prod_32fc((lv_32fc_t*)&out.writeBuf[i], (lv_32fc_t*)&buffer[i+1], taps, tapCount); + volk_32fc_32f_dot_prod_32fc((lv_32fc_t*)&out.writeBuf[i], (lv_32fc_t*)&buffer[i + 1], taps, tapCount); } } @@ -95,7 +95,6 @@ namespace dsp { T* buffer; int tapCount; float* taps; - }; class ComplexFIR : public generic_block { @@ -157,7 +156,7 @@ namespace dsp { _in->flush(); for (int i = 0; i < count; i++) { - volk_32fc_x2_dot_prod_32fc((lv_32fc_t*)&out.writeBuf[i], (lv_32fc_t*)&buffer[i+1], (lv_32fc_t*)taps, tapCount); + volk_32fc_x2_dot_prod_32fc((lv_32fc_t*)&out.writeBuf[i], (lv_32fc_t*)&buffer[i + 1], (lv_32fc_t*)taps, tapCount); } if (!out.swap(count)) { return -1; } @@ -180,7 +179,6 @@ namespace dsp { complex_t* buffer; int tapCount; complex_t* taps; - }; class BFMDeemp : public generic_block { @@ -241,8 +239,8 @@ namespace dsp { if (isnan(lastOutR)) { lastOutR = 0.0f; } - out.writeBuf[0].l = (alpha * _in->readBuf[0].l) + ((1-alpha) * lastOutL); - out.writeBuf[0].r = (alpha * _in->readBuf[0].r) + ((1-alpha) * lastOutR); + out.writeBuf[0].l = (alpha * _in->readBuf[0].l) + ((1 - alpha) * lastOutL); + out.writeBuf[0].r = (alpha * _in->readBuf[0].r) + ((1 - alpha) * lastOutR); for (int i = 1; i < count; i++) { out.writeBuf[i].l = (alpha * _in->readBuf[i].l) + ((1 - alpha) * out.writeBuf[i - 1].l); out.writeBuf[i].r = (alpha * _in->readBuf[i].r) + ((1 - alpha) * out.writeBuf[i - 1].r); @@ -267,6 +265,5 @@ namespace dsp { float _tau; float _sampleRate; stream* _in; - }; } \ No newline at end of file diff --git a/core/src/dsp/math.h b/core/src/dsp/math.h index 8c71249a..ac24a13c 100644 --- a/core/src/dsp/math.h +++ b/core/src/dsp/math.h @@ -82,7 +82,6 @@ namespace dsp { private: stream* _a; stream* _b; - }; template @@ -163,7 +162,6 @@ namespace dsp { private: stream* _a; stream* _b; - }; template @@ -244,6 +242,5 @@ namespace dsp { private: stream* _a; stream* _b; - }; } \ No newline at end of file diff --git a/core/src/dsp/measure.h b/core/src/dsp/measure.h index fa1a8721..d2d26ae3 100644 --- a/core/src/dsp/measure.h +++ b/core/src/dsp/measure.h @@ -46,14 +46,14 @@ namespace dsp { float _lvlL = 10.0f * logf(maxL); float _lvlR = 10.0f * logf(maxR); - + // Update max values { std::lock_guard lck(lvlMtx); if (_lvlL > lvlL) { lvlL = _lvlL; } if (_lvlR > lvlR) { lvlR = _lvlR; } } - + return count; } @@ -77,6 +77,5 @@ namespace dsp { float lvlR = -90.0f; stream* _in; std::mutex lvlMtx; - }; } \ No newline at end of file diff --git a/core/src/dsp/meteor/hrpt.h b/core/src/dsp/meteor/hrpt.h index 74c14064..f4c75a24 100644 --- a/core/src/dsp/meteor/hrpt.h +++ b/core/src/dsp/meteor/hrpt.h @@ -61,7 +61,6 @@ namespace dsp { private: stream* _in; - }; } } \ No newline at end of file diff --git a/core/src/dsp/meteor/msumr.h b/core/src/dsp/meteor/msumr.h index d05e4925..a3b2b67e 100644 --- a/core/src/dsp/meteor/msumr.h +++ b/core/src/dsp/meteor/msumr.h @@ -72,7 +72,6 @@ namespace dsp { private: stream* _in; - }; } } \ No newline at end of file diff --git a/core/src/dsp/noaa/hrpt.h b/core/src/dsp/noaa/hrpt.h index 4c4a4ae8..a7a08b3b 100644 --- a/core/src/dsp/noaa/hrpt.h +++ b/core/src/dsp/noaa/hrpt.h @@ -9,12 +9,12 @@ namespace dsp { } const uint8_t HRPTSyncWord[] = { - 1,0,1,0,0,0,0,1,0,0, - 0,1,0,1,1,0,1,1,1,1, - 1,1,0,1,0,1,1,1,0,0, - 0,1,1,0,0,1,1,1,0,1, - 1,0,0,0,0,0,1,1,1,1, - 0,0,1,0,0,1,0,1,0,1 + 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, + 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, + 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, + 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, + 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, + 0, 0, 1, 0, 0, 1, 0, 1, 0, 1 }; class HRPTDemux : public generic_block { @@ -105,7 +105,6 @@ namespace dsp { private: stream* _in; - }; } } diff --git a/core/src/dsp/noaa/tip.h b/core/src/dsp/noaa/tip.h index 5578d152..77478be2 100644 --- a/core/src/dsp/noaa/tip.h +++ b/core/src/dsp/noaa/tip.h @@ -132,7 +132,6 @@ namespace dsp { private: stream* _in; - }; inline uint16_t HIRSSignedToUnsigned(uint16_t n) { @@ -236,7 +235,6 @@ namespace dsp { stream* _in; int lastElement = 0; bool newImageData = false; - }; } } diff --git a/core/src/dsp/noise_reduction.h b/core/src/dsp/noise_reduction.h index 43911f2c..08c35fe4 100644 --- a/core/src/dsp/noise_reduction.h +++ b/core/src/dsp/noise_reduction.h @@ -3,7 +3,7 @@ #include #include -#define NR_TAP_COUNT 64 +#define NR_TAP_COUNT 64 namespace dsp { class FMIFNoiseReduction : public generic_block { @@ -30,22 +30,22 @@ namespace dsp { _in = in; _tapCount = tapCount; - delay = (complex_t*)fftwf_malloc(sizeof(complex_t)*STREAM_BUFFER_SIZE); - fft_in = (complex_t*)fftwf_malloc(sizeof(complex_t)*_tapCount); - fft_window = (float*)fftwf_malloc(sizeof(float)*_tapCount); - amp_buf = (float*)fftwf_malloc(sizeof(float)*_tapCount); - fft_cout = (complex_t*)fftwf_malloc(sizeof(complex_t)*_tapCount); - fft_cin = (complex_t*)fftwf_malloc(sizeof(complex_t)*_tapCount); - fft_fcout = (complex_t*)fftwf_malloc(sizeof(complex_t)*_tapCount); + delay = (complex_t*)fftwf_malloc(sizeof(complex_t) * STREAM_BUFFER_SIZE); + fft_in = (complex_t*)fftwf_malloc(sizeof(complex_t) * _tapCount); + fft_window = (float*)fftwf_malloc(sizeof(float) * _tapCount); + amp_buf = (float*)fftwf_malloc(sizeof(float) * _tapCount); + fft_cout = (complex_t*)fftwf_malloc(sizeof(complex_t) * _tapCount); + fft_cin = (complex_t*)fftwf_malloc(sizeof(complex_t) * _tapCount); + fft_fcout = (complex_t*)fftwf_malloc(sizeof(complex_t) * _tapCount); delay_start = &delay[_tapCount]; - memset(delay, 0, sizeof(complex_t)*STREAM_BUFFER_SIZE); - memset(fft_in, 0, sizeof(complex_t)*_tapCount); - memset(amp_buf, 0, sizeof(float)*_tapCount); - memset(fft_cout, 0, sizeof(complex_t)*_tapCount); - memset(fft_cin, 0, sizeof(complex_t)*_tapCount); - memset(fft_fcout, 0, sizeof(complex_t)*_tapCount); - + memset(delay, 0, sizeof(complex_t) * STREAM_BUFFER_SIZE); + memset(fft_in, 0, sizeof(complex_t) * _tapCount); + memset(amp_buf, 0, sizeof(float) * _tapCount); + memset(fft_cout, 0, sizeof(complex_t) * _tapCount); + memset(fft_cin, 0, sizeof(complex_t) * _tapCount); + memset(fft_fcout, 0, sizeof(complex_t) * _tapCount); + for (int i = 0; i < _tapCount; i++) { fft_window[i] = window_function::blackman(i, _tapCount - 1); } @@ -86,22 +86,22 @@ namespace dsp { fftwf_free(fft_cin); fftwf_free(fft_fcout); - delay = (complex_t*)fftwf_malloc(sizeof(complex_t)*STREAM_BUFFER_SIZE); - fft_in = (complex_t*)fftwf_malloc(sizeof(complex_t)*_tapCount); - fft_window = (float*)fftwf_malloc(sizeof(float)*_tapCount); - amp_buf = (float*)fftwf_malloc(sizeof(float)*_tapCount); - fft_cout = (complex_t*)fftwf_malloc(sizeof(complex_t)*_tapCount); - fft_cin = (complex_t*)fftwf_malloc(sizeof(complex_t)*_tapCount); - fft_fcout = (complex_t*)fftwf_malloc(sizeof(complex_t)*_tapCount); + delay = (complex_t*)fftwf_malloc(sizeof(complex_t) * STREAM_BUFFER_SIZE); + fft_in = (complex_t*)fftwf_malloc(sizeof(complex_t) * _tapCount); + fft_window = (float*)fftwf_malloc(sizeof(float) * _tapCount); + amp_buf = (float*)fftwf_malloc(sizeof(float) * _tapCount); + fft_cout = (complex_t*)fftwf_malloc(sizeof(complex_t) * _tapCount); + fft_cin = (complex_t*)fftwf_malloc(sizeof(complex_t) * _tapCount); + fft_fcout = (complex_t*)fftwf_malloc(sizeof(complex_t) * _tapCount); delay_start = &delay[_tapCount]; - memset(delay, 0, sizeof(complex_t)*STREAM_BUFFER_SIZE); - memset(fft_in, 0, sizeof(complex_t)*_tapCount); - memset(amp_buf, 0, sizeof(float)*_tapCount); - memset(fft_cout, 0, sizeof(complex_t)*_tapCount); - memset(fft_cin, 0, sizeof(complex_t)*_tapCount); - memset(fft_fcout, 0, sizeof(complex_t)*_tapCount); - + memset(delay, 0, sizeof(complex_t) * STREAM_BUFFER_SIZE); + memset(fft_in, 0, sizeof(complex_t) * _tapCount); + memset(amp_buf, 0, sizeof(float) * _tapCount); + memset(fft_cout, 0, sizeof(complex_t) * _tapCount); + memset(fft_cin, 0, sizeof(complex_t) * _tapCount); + memset(fft_fcout, 0, sizeof(complex_t) * _tapCount); + for (int i = 0; i < _tapCount; i++) { fft_window[i] = window_function::blackman(i, _tapCount - 1); } @@ -154,13 +154,13 @@ namespace dsp { // Do reverse FFT and get first element fftwf_execute(backwardPlan); - out.writeBuf[i] = fft_fcout[_tapCount/2]; + out.writeBuf[i] = fft_fcout[_tapCount / 2]; // Reset the input buffer - fft_cin[idx] = {0, 0}; + fft_cin[idx] = { 0, 0 }; } - volk_32f_s32f_multiply_32f((float*)out.writeBuf, (float*)out.writeBuf, 1.0f/(float)_tapCount, count * 2); + volk_32f_s32f_multiply_32f((float*)out.writeBuf, (float*)out.writeBuf, 1.0f / (float)_tapCount, count * 2); // Copy last values to delay memmove(delay, &delay[count], _tapCount * sizeof(complex_t)); @@ -169,7 +169,7 @@ namespace dsp { if (!out.swap(count)) { return -1; } return count; } - + bool bypass = true; stream out; @@ -189,7 +189,6 @@ namespace dsp { complex_t* fft_fcout; int _tapCount; - }; class FFTNoiseReduction : public generic_block { @@ -214,20 +213,20 @@ namespace dsp { void init(stream* in) { _in = in; - delay = (float*)fftwf_malloc(sizeof(float)*STREAM_BUFFER_SIZE); - fft_in = (float*)fftwf_malloc(sizeof(float)*NR_TAP_COUNT); - fft_window = (float*)fftwf_malloc(sizeof(float)*NR_TAP_COUNT); - amp_buf = (float*)fftwf_malloc(sizeof(float)*NR_TAP_COUNT); - fft_cout = (complex_t*)fftwf_malloc(sizeof(complex_t)*NR_TAP_COUNT); - fft_fout = (float*)fftwf_malloc(sizeof(float)*NR_TAP_COUNT); + delay = (float*)fftwf_malloc(sizeof(float) * STREAM_BUFFER_SIZE); + fft_in = (float*)fftwf_malloc(sizeof(float) * NR_TAP_COUNT); + fft_window = (float*)fftwf_malloc(sizeof(float) * NR_TAP_COUNT); + amp_buf = (float*)fftwf_malloc(sizeof(float) * NR_TAP_COUNT); + fft_cout = (complex_t*)fftwf_malloc(sizeof(complex_t) * NR_TAP_COUNT); + fft_fout = (float*)fftwf_malloc(sizeof(float) * NR_TAP_COUNT); delay_start = &delay[NR_TAP_COUNT]; - memset(delay, 0, sizeof(float)*STREAM_BUFFER_SIZE); - memset(fft_in, 0, sizeof(float)*NR_TAP_COUNT); - memset(amp_buf, 0, sizeof(float)*NR_TAP_COUNT); - memset(fft_cout, 0, sizeof(complex_t)*NR_TAP_COUNT); - memset(fft_fout, 0, sizeof(float)*NR_TAP_COUNT); - + memset(delay, 0, sizeof(float) * STREAM_BUFFER_SIZE); + memset(fft_in, 0, sizeof(float) * NR_TAP_COUNT); + memset(amp_buf, 0, sizeof(float) * NR_TAP_COUNT); + memset(fft_cout, 0, sizeof(complex_t) * NR_TAP_COUNT); + memset(fft_fout, 0, sizeof(float) * NR_TAP_COUNT); + for (int i = 0; i < NR_TAP_COUNT; i++) { fft_window[i] = window_function::blackman(i, NR_TAP_COUNT - 1); } @@ -274,19 +273,19 @@ namespace dsp { fftwf_execute(forwardPlan); // Process bins here - volk_32fc_magnitude_32f(amp_buf, (lv_32fc_t*)fft_cout, NR_TAP_COUNT/2); - for (int j = 1; j < NR_TAP_COUNT/2; j++) { + volk_32fc_magnitude_32f(amp_buf, (lv_32fc_t*)fft_cout, NR_TAP_COUNT / 2); + for (int j = 1; j < NR_TAP_COUNT / 2; j++) { if (log10f(amp_buf[0]) < level) { - fft_cout[j] = {0, 0}; + fft_cout[j] = { 0, 0 }; } } // Do reverse FFT and get first element fftwf_execute(backwardPlan); - out.writeBuf[i] = fft_fout[NR_TAP_COUNT/2]; + out.writeBuf[i] = fft_fout[NR_TAP_COUNT / 2]; } - volk_32f_s32f_multiply_32f(out.writeBuf, out.writeBuf, 1.0f/(float)NR_TAP_COUNT, count); + volk_32f_s32f_multiply_32f(out.writeBuf, out.writeBuf, 1.0f / (float)NR_TAP_COUNT, count); // Copy last values to delay memmove(delay, &delay[count], NR_TAP_COUNT * sizeof(float)); @@ -295,7 +294,7 @@ namespace dsp { if (!out.swap(count)) { return -1; } return count; } - + bool bypass = true; stream out; @@ -312,7 +311,6 @@ namespace dsp { float* delay_start; complex_t* fft_cout; float* fft_fout; - }; class NoiseBlanker : public generic_block { @@ -329,9 +327,10 @@ namespace dsp { void init(stream* in, float level) { _in = in; - _level = powf(10.0f, level / 10.0f);; + _level = powf(10.0f, level / 10.0f); + ; - ampBuf = (float*)volk_malloc(STREAM_BUFFER_SIZE*sizeof(float), volk_get_alignment()); + ampBuf = (float*)volk_malloc(STREAM_BUFFER_SIZE * sizeof(float), volk_get_alignment()); generic_block::registerInput(_in); generic_block::registerOutput(&out); @@ -377,9 +376,8 @@ namespace dsp { float* ampBuf; float _level; - - stream* _in; + stream* _in; }; class NotchFilter : public generic_block { @@ -395,7 +393,7 @@ namespace dsp { _sampleRate = sampleRate; phaseDelta = lv_cmake(std::cos((-_offset / _sampleRate) * 2.0f * FL_M_PI), std::sin((-_offset / _sampleRate) * 2.0f * FL_M_PI)); - phaseDeltaConj = {phaseDelta.real(), -phaseDelta.imag()}; + phaseDeltaConj = { phaseDelta.real(), -phaseDelta.imag() }; generic_block::registerInput(_in); generic_block::registerOutput(&out); @@ -419,13 +417,13 @@ namespace dsp { void setOffset(float offset) { _offset = offset; phaseDelta = lv_cmake(std::cos((-_offset / _sampleRate) * 2.0f * FL_M_PI), std::sin((-_offset / _sampleRate) * 2.0f * FL_M_PI)); - phaseDeltaConj = {phaseDelta.real(), -phaseDelta.imag()}; + phaseDeltaConj = { phaseDelta.real(), -phaseDelta.imag() }; } void setSampleRate(float sampleRate) { _sampleRate = sampleRate; phaseDelta = lv_cmake(std::cos((-_offset / _sampleRate) * 2.0f * FL_M_PI), std::sin((-_offset / _sampleRate) * 2.0f * FL_M_PI)); - phaseDeltaConj = {phaseDelta.real(), -phaseDelta.imag()}; + phaseDeltaConj = { phaseDelta.real(), -phaseDelta.imag() }; } int run() { @@ -452,14 +450,13 @@ namespace dsp { private: stream* _in; - complex_t offset = {0, 0}; - lv_32fc_t inPhase = {1, 0}; - lv_32fc_t outPhase = {4, 0}; + complex_t offset = { 0, 0 }; + lv_32fc_t inPhase = { 1, 0 }; + lv_32fc_t outPhase = { 4, 0 }; lv_32fc_t phaseDelta; lv_32fc_t phaseDeltaConj; float _offset; float _sampleRate; float correctionRate; - }; } \ No newline at end of file diff --git a/core/src/dsp/pll.h b/core/src/dsp/pll.h index 7a824099..4b80169e 100644 --- a/core/src/dsp/pll.h +++ b/core/src/dsp/pll.h @@ -7,7 +7,7 @@ namespace dsp { template - class CostasLoop: public generic_block> { + class CostasLoop : public generic_block> { public: CostasLoop() {} @@ -59,8 +59,8 @@ namespace dsp { for (int i = 0; i < count; i++) { // Mix the VFO with the input to create the output value - outVal.re = (lastVCO.re*_in->readBuf[i].re) - (lastVCO.im*_in->readBuf[i].im); - outVal.im = (lastVCO.im*_in->readBuf[i].re) + (lastVCO.re*_in->readBuf[i].im); + outVal.re = (lastVCO.re * _in->readBuf[i].re) - (lastVCO.im * _in->readBuf[i].im); + outVal.im = (lastVCO.im * _in->readBuf[i].re) + (lastVCO.re * _in->readBuf[i].im); out.writeBuf[i] = outVal; // Calculate the phase error estimation @@ -75,20 +75,25 @@ namespace dsp { const float K = (sqrtf(2.0) - 1); if (fabsf(outVal.re) >= fabsf(outVal.im)) { error = ((outVal.re > 0.0f ? 1.0f : -1.0f) * outVal.im - - (outVal.im > 0.0f ? 1.0f : -1.0f) * outVal.re * K); - } else { + (outVal.im > 0.0f ? 1.0f : -1.0f) * outVal.re * K); + } + else { error = ((outVal.re > 0.0f ? 1.0f : -1.0f) * outVal.im * K - - (outVal.im > 0.0f ? 1.0f : -1.0f) * outVal.re); + (outVal.im > 0.0f ? 1.0f : -1.0f) * outVal.re); } } - + if (error > 1.0f) { error = 1.0f; } - else if (error < -1.0f) { error = -1.0f; } - + else if (error < -1.0f) { + error = -1.0f; + } + // Integrate frequency and clamp it vcoFrequency += _beta * error; if (vcoFrequency > 1.0f) { vcoFrequency = 1.0f; } - else if (vcoFrequency < -1.0f) { vcoFrequency = -1.0f; } + else if (vcoFrequency < -1.0f) { + vcoFrequency = -1.0f; + } // Calculate new phase and wrap it vcoPhase += vcoFrequency + (_alpha * error); @@ -98,9 +103,8 @@ namespace dsp { // Calculate output lastVCO.re = cosf(-vcoPhase); lastVCO.im = sinf(-vcoPhase); - } - + _in->flush(); if (!out.swap(count)) { return -1; } return count; @@ -112,17 +116,16 @@ namespace dsp { float _loopBandwidth = 1.0f; float _alpha; // Integral coefficient - float _beta; // Proportional coefficient + float _beta; // Proportional coefficient float vcoFrequency = 0.0f; float vcoPhase = 0.0f; complex_t lastVCO; stream* _in; - }; template - class CarrierTrackingPLL: public generic_block> { + class CarrierTrackingPLL : public generic_block> { public: CarrierTrackingPLL() {} @@ -174,8 +177,8 @@ namespace dsp { for (int i = 0; i < count; i++) { // Mix the VFO with the input to create the output value - outVal.re = (lastVCO.re*_in->readBuf[i].re) - ((-lastVCO.im)*_in->readBuf[i].im); - outVal.im = ((-lastVCO.im)*_in->readBuf[i].re) + (lastVCO.re*_in->readBuf[i].im); + outVal.re = (lastVCO.re * _in->readBuf[i].re) - ((-lastVCO.im) * _in->readBuf[i].im); + outVal.im = ((-lastVCO.im) * _in->readBuf[i].re) + (lastVCO.re * _in->readBuf[i].im); if constexpr (std::is_same_v) { out.writeBuf[i] = outVal.fastPhase(); @@ -187,16 +190,20 @@ namespace dsp { // Calculate the phase error estimation // TODO: Figure out why fastPhase doesn't work error = _in->readBuf[i].phase() - vcoPhase; - if (error > 3.1415926535f) { error -= 2.0f * 3.1415926535f; } - else if (error <= -3.1415926535f) { error += 2.0f * 3.1415926535f; } - + if (error > 3.1415926535f) { error -= 2.0f * 3.1415926535f; } + else if (error <= -3.1415926535f) { + error += 2.0f * 3.1415926535f; + } + // if (error > 1.0f) { error = 1.0f; } // else if (error < -1.0f) { error = -1.0f; } - + // Integrate frequency and clamp it vcoFrequency += _beta * error; if (vcoFrequency > 1.0f) { vcoFrequency = 1.0f; } - else if (vcoFrequency < -1.0f) { vcoFrequency = -1.0f; } + else if (vcoFrequency < -1.0f) { + vcoFrequency = -1.0f; + } // Calculate new phase and wrap it vcoPhase += vcoFrequency + (_alpha * error); @@ -206,9 +213,8 @@ namespace dsp { // Calculate output lastVCO.re = cosf(vcoPhase); lastVCO.im = sinf(vcoPhase); - } - + _in->flush(); if (!out.swap(count)) { return -1; } return count; @@ -220,16 +226,15 @@ namespace dsp { float _loopBandwidth = 1.0f; float _alpha; // Integral coefficient - float _beta; // Proportional coefficient + float _beta; // Proportional coefficient float vcoFrequency = 0.0f; float vcoPhase = 0.0f; complex_t lastVCO; stream* _in; - }; - class PLL: public generic_block { + class PLL : public generic_block { public: PLL() {} @@ -284,13 +289,17 @@ namespace dsp { // Calculate the phase error estimation // TODO: Figure out why fastPhase doesn't work error = _in->readBuf[i].phase() - vcoPhase; - if (error > 3.1415926535f) { error -= 2.0f * 3.1415926535f; } - else if (error <= -3.1415926535f) { error += 2.0f * 3.1415926535f; } - + if (error > 3.1415926535f) { error -= 2.0f * 3.1415926535f; } + else if (error <= -3.1415926535f) { + error += 2.0f * 3.1415926535f; + } + // Integrate frequency and clamp it vcoFrequency += _beta * error; if (vcoFrequency > 1.0f) { vcoFrequency = 1.0f; } - else if (vcoFrequency < -1.0f) { vcoFrequency = -1.0f; } + else if (vcoFrequency < -1.0f) { + vcoFrequency = -1.0f; + } // Calculate new phase and wrap it vcoPhase += vcoFrequency + (_alpha * error); @@ -300,9 +309,8 @@ namespace dsp { // Calculate output lastVCO.re = cosf(vcoPhase); lastVCO.im = sinf(vcoPhase); - } - + _in->flush(); if (!out.swap(count)) { return -1; } return count; @@ -314,12 +322,11 @@ namespace dsp { float _loopBandwidth = 1.0f; float _alpha; // Integral coefficient - float _beta; // Proportional coefficient + float _beta; // Proportional coefficient float vcoFrequency = ((19000.0f / 250000.0f) * 2.0f * FL_M_PI); float vcoPhase = 0.0f; complex_t lastVCO; stream* _in; - }; } \ No newline at end of file diff --git a/core/src/dsp/processing.h b/core/src/dsp/processing.h index 6fd9564a..1cda025a 100644 --- a/core/src/dsp/processing.h +++ b/core/src/dsp/processing.h @@ -82,7 +82,6 @@ namespace dsp { lv_32fc_t phaseDelta; lv_32fc_t phase; stream* _in; - }; class AGC : public generic_block { @@ -155,7 +154,6 @@ namespace dsp { float _CorrectedFallRate; float _sampleRate; stream* _in; - }; class ComplexAGC : public generic_block { @@ -223,9 +221,8 @@ namespace dsp { float _setPoint = 1.0f; float _maxGain = 10e4; float _rate = 10e-4; - - stream* _in; + stream* _in; }; class DelayImag : public generic_block { @@ -273,11 +270,9 @@ namespace dsp { private: float lastIm = 0.0f; stream* _in; - }; - template class Volume : public generic_block> { public: @@ -358,7 +353,6 @@ namespace dsp { float _volume = 1.0f; bool _muted = false; stream* _in; - }; class Squelch : public generic_block { @@ -421,7 +415,7 @@ namespace dsp { _in->flush(); if (!out.swap(count)) { return -1; } - return count; + return count; } stream out; @@ -431,7 +425,6 @@ namespace dsp { float* normBuffer; float _level = -50.0f; stream* _in; - }; template @@ -487,7 +480,7 @@ namespace dsp { } _in->flush(); - + return count; } @@ -497,7 +490,6 @@ namespace dsp { int samples = 1; int read = 0; stream* _in; - }; class Threshold : public generic_block { @@ -551,7 +543,7 @@ namespace dsp { _in->flush(); if (!out.swap(count)) { return -1; } - return count; + return count; } stream out; @@ -561,7 +553,6 @@ namespace dsp { float* normBuffer; float _level = -50.0f; stream* _in; - }; class BFMPilotToStereo : public generic_block { @@ -614,6 +605,5 @@ namespace dsp { stream* _in; complex_t* buffer; - }; } \ No newline at end of file diff --git a/core/src/dsp/resampling.h b/core/src/dsp/resampling.h index 09eeb020..ab6202f7 100644 --- a/core/src/dsp/resampling.h +++ b/core/src/dsp/resampling.h @@ -160,39 +160,39 @@ namespace dsp { stream out; private: - void buildTapPhases(){ - if(!taps){ + void buildTapPhases() { + if (!taps) { return; } - if(!tapPhases.empty()){ + if (!tapPhases.empty()) { freeTapPhases(); } int phases = _interp; - tapsPerPhase = (tapCount+phases-1)/phases; //Integer division ceiling + tapsPerPhase = (tapCount + phases - 1) / phases; //Integer division ceiling bufStart = &buffer[tapsPerPhase]; - for(int i = 0; i < phases; i++){ + for (int i = 0; i < phases; i++) { tapPhases.push_back((float*)volk_malloc(tapsPerPhase * sizeof(float), volk_get_alignment())); } int currentTap = 0; - for(int tap = 0; tap < tapsPerPhase; tap++) { + for (int tap = 0; tap < tapsPerPhase; tap++) { for (int phase = 0; phase < phases; phase++) { - if(currentTap < tapCount) { + if (currentTap < tapCount) { tapPhases[(_interp - 1) - phase][tap] = taps[currentTap++]; } - else{ + else { tapPhases[(_interp - 1) - phase][tap] = 0; } } } } - void freeTapPhases(){ - for(auto & tapPhase : tapPhases){ + void freeTapPhases() { + for (auto& tapPhase : tapPhases) { volk_free(tapPhase); } tapPhases.clear(); @@ -214,6 +214,5 @@ namespace dsp { int tapsPerPhase; std::vector tapPhases; - }; } \ No newline at end of file diff --git a/core/src/dsp/routing.h b/core/src/dsp/routing.h index 58f5e021..761f2cd8 100644 --- a/core/src/dsp/routing.h +++ b/core/src/dsp/routing.h @@ -62,7 +62,6 @@ namespace dsp { stream* _in; std::vector*> out; - }; template @@ -105,12 +104,11 @@ namespace dsp { if (!outA.swap(count)) { return -1; } if (!outB.swap(count)) { return -1; } - + return count; } stream* _in; - }; @@ -183,7 +181,8 @@ namespace dsp { } void loop() { - while (run() >= 0); + while (run() >= 0) + ; } void doStop() override { @@ -240,6 +239,5 @@ namespace dsp { std::thread bufferWorkerThread; std::thread workThread; int _keep, _skip; - }; } \ No newline at end of file diff --git a/core/src/dsp/sink.h b/core/src/dsp/sink.h index cb97402a..c17c58ff 100644 --- a/core/src/dsp/sink.h +++ b/core/src/dsp/sink.h @@ -50,7 +50,6 @@ namespace dsp { stream* _in; void (*_handler)(T* data, int count, void* ctx); void* _ctx; - }; template @@ -99,7 +98,6 @@ namespace dsp { } stream* _in; - }; template @@ -134,7 +132,6 @@ namespace dsp { private: stream* _in; - }; template @@ -188,6 +185,5 @@ namespace dsp { private: stream* _in; std::ofstream file; - }; } \ No newline at end of file diff --git a/core/src/dsp/source.h b/core/src/dsp/source.h index 535544d3..1efb4ae8 100644 --- a/core/src/dsp/source.h +++ b/core/src/dsp/source.h @@ -60,7 +60,7 @@ namespace dsp { int run() { volk_32fc_s32fc_x2_rotator_32fc((lv_32fc_t*)out.writeBuf, zeroPhase, phaseDelta, &phase, _blockSize); - if(!out.swap(_blockSize)) { return -1; } + if (!out.swap(_blockSize)) { return -1; } return _blockSize; } @@ -73,7 +73,6 @@ namespace dsp { lv_32fc_t phaseDelta; lv_32fc_t phase; lv_32fc_t* zeroPhase; - }; template @@ -111,6 +110,5 @@ namespace dsp { private: int (*_handler)(T* data, void* ctx); void* _ctx; - }; } \ No newline at end of file diff --git a/core/src/dsp/stereo_fm.h b/core/src/dsp/stereo_fm.h index 0ab00a3b..dc364e2c 100644 --- a/core/src/dsp/stereo_fm.h +++ b/core/src/dsp/stereo_fm.h @@ -66,10 +66,10 @@ namespace dsp { _in->flush(); for (int i = 0; i < count; i++) { - volk_32fc_x2_dot_prod_32fc((lv_32fc_t*)&pilotOut.writeBuf[i], (lv_32fc_t*)&buffer[i+1], (lv_32fc_t*)taps, tapCount); + volk_32fc_x2_dot_prod_32fc((lv_32fc_t*)&pilotOut.writeBuf[i], (lv_32fc_t*)&buffer[i + 1], (lv_32fc_t*)taps, tapCount); } - memcpy(dataOut.writeBuf, &buffer[tapCount - ((tapCount-1)/2)], count * sizeof(complex_t)); + memcpy(dataOut.writeBuf, &buffer[tapCount - ((tapCount - 1) / 2)], count * sizeof(complex_t)); if (!pilotOut.swap(count) || !dataOut.swap(count)) { bufMtx.unlock(); @@ -85,7 +85,7 @@ namespace dsp { stream dataOut; stream pilotOut; - + private: stream* _in; @@ -98,10 +98,9 @@ namespace dsp { complex_t* buffer; int tapCount; complex_t* taps; - }; - class FMStereoDemux: public generic_block { + class FMStereoDemux : public generic_block { public: FMStereoDemux() {} @@ -163,18 +162,22 @@ namespace dsp { for (int i = 0; i < count; i++) { // Double the VCO, then mix it with the input data. // IMPORTANT: THERE SHOULDN'T BE A NEED FOR A GAIN HERE - doubledVCO = lastVCO*lastVCO; + doubledVCO = lastVCO * lastVCO; AminusBOut.writeBuf[i] = (_data->readBuf[i].re * doubledVCO.re) * 2.0f; // Calculate the phase error estimation error = _pilot->readBuf[i].phase() - vcoPhase; - if (error > 3.1415926535f) { error -= 2.0f * 3.1415926535f; } - else if (error <= -3.1415926535f) { error += 2.0f * 3.1415926535f; } - + if (error > 3.1415926535f) { error -= 2.0f * 3.1415926535f; } + else if (error <= -3.1415926535f) { + error += 2.0f * 3.1415926535f; + } + // Integrate frequency and clamp it vcoFrequency += _beta * error; if (vcoFrequency > upperLimit) { vcoFrequency = upperLimit; } - else if (vcoFrequency < lowerLimit) { vcoFrequency = lowerLimit; } + else if (vcoFrequency < lowerLimit) { + vcoFrequency = lowerLimit; + } // Calculate new phase and wrap it vcoPhase += vcoFrequency + (_alpha * error); @@ -185,7 +188,7 @@ namespace dsp { lastVCO.re = cosf(vcoPhase); lastVCO.im = sinf(vcoPhase); } - + _data->flush(); _pilot->flush(); @@ -207,7 +210,7 @@ namespace dsp { const float lowerLimit = ((18800.0f / 250000.0f) * 2.0f * FL_M_PI); float _alpha; // Integral coefficient - float _beta; // Proportional coefficient + float _beta; // Proportional coefficient float vcoFrequency = expectedFreq; float vcoPhase = 0.0f; complex_t lastVCO; @@ -284,6 +287,5 @@ namespace dsp { float* leftBuf; float* rightBuf; - }; } \ No newline at end of file diff --git a/core/src/dsp/stream.h b/core/src/dsp/stream.h index 73874f71..abe5dd5b 100644 --- a/core/src/dsp/stream.h +++ b/core/src/dsp/stream.h @@ -4,7 +4,7 @@ #include // 1MB buffer -#define STREAM_BUFFER_SIZE 1000000 +#define STREAM_BUFFER_SIZE 1000000 namespace dsp { class untyped_stream { @@ -35,7 +35,7 @@ namespace dsp { { // Wait to either swap or stop std::unique_lock lck(swapMtx); - swapCV.wait(lck, [this]{ return (canSwap || writerStop); }); + swapCV.wait(lck, [this] { return (canSwap || writerStop); }); // If writer was stopped, abandon operation if (writerStop) { return false; } @@ -61,7 +61,7 @@ namespace dsp { int read() { // Wait for data to be ready or to be stopped std::unique_lock lck(rdyMtx); - rdyCV.wait(lck, [this]{ return (dataReady || readerStop); }); + rdyCV.wait(lck, [this] { return (dataReady || readerStop); }); return (readerStop ? -1 : dataSize); } diff --git a/core/src/dsp/types.h b/core/src/dsp/types.h index e743e5f8..679ba96c 100644 --- a/core/src/dsp/types.h +++ b/core/src/dsp/types.h @@ -5,27 +5,27 @@ namespace dsp { struct complex_t { complex_t operator*(const float b) { - return complex_t{re*b, im*b}; + return complex_t{ re * b, im * b }; } complex_t operator/(const float b) { - return complex_t{re/b, im/b}; + return complex_t{ re / b, im / b }; } complex_t operator*(const complex_t& b) { - return complex_t{(re*b.re) - (im*b.im), (im*b.re) + (re*b.im)}; + return complex_t{ (re * b.re) - (im * b.im), (im * b.re) + (re * b.im) }; } complex_t operator+(const complex_t& b) { - return complex_t{re+b.re, im+b.im}; + return complex_t{ re + b.re, im + b.im }; } complex_t operator-(const complex_t& b) { - return complex_t{re-b.re, im-b.im}; + return complex_t{ re - b.re, im - b.im }; } inline complex_t conj() { - return complex_t{re, -im}; + return complex_t{ re, -im }; } inline float phase() { @@ -36,7 +36,7 @@ namespace dsp { float abs_im = fabsf(im); float r, angle; if (re == 0.0f && im == 0.0f) { return 0.0f; } - if (re>=0.0f) { + if (re >= 0.0f) { r = (re - abs_im) / (re + abs_im); angle = (FL_M_PI / 4.0f) - (FL_M_PI / 4.0f) * r; } @@ -51,14 +51,14 @@ namespace dsp { } inline float amplitude() { - return sqrt((re*re) + (im*im)); + return sqrt((re * re) + (im * im)); } inline float fastAmplitude() { float re_abs = fabsf(re); float im_abs = fabsf(re); if (re_abs > im_abs) { return re_abs + 0.4f * im_abs; } - return im_abs + 0.4f * re_abs; + return im_abs + 0.4f * re_abs; } float re; @@ -67,15 +67,15 @@ namespace dsp { struct stereo_t { stereo_t operator*(const float b) { - return stereo_t{l*b, r*b}; + return stereo_t{ l * b, r * b }; } stereo_t operator+(const stereo_t& b) { - return stereo_t{l+b.l, r+b.r}; + return stereo_t{ l + b.l, r + b.r }; } stereo_t operator-(const stereo_t& b) { - return stereo_t{l-b.l, r-b.r}; + return stereo_t{ l - b.l, r - b.r }; } float l; diff --git a/core/src/dsp/utils/bitstream.h b/core/src/dsp/utils/bitstream.h index 8d3deb46..ebd73ba9 100644 --- a/core/src/dsp/utils/bitstream.h +++ b/core/src/dsp/utils/bitstream.h @@ -3,7 +3,7 @@ namespace dsp { inline uint64_t readBits(int offset, int length, uint8_t* buffer) { uint64_t outputValue = 0; - + int lastBit = offset + (length - 1); int firstWord = offset / 8; diff --git a/core/src/dsp/utils/ccsds.h b/core/src/dsp/utils/ccsds.h index 36958d9a..48db0675 100644 --- a/core/src/dsp/utils/ccsds.h +++ b/core/src/dsp/utils/ccsds.h @@ -3,7 +3,7 @@ namespace dsp { namespace ccsds { - const uint8_t TO_DUAL_BASIS[256] = { + const uint8_t TO_DUAL_BASIS[256] = { 0x00, 0x7b, 0xaf, 0xd4, 0x99, 0xe2, 0x36, 0x4d, 0xfa, 0x81, 0x55, 0x2e, 0x63, 0x18, 0xcc, 0xb7, 0x86, 0xfd, 0x29, 0x52, 0x1f, 0x64, 0xb0, 0xcb, 0x7c, 0x07, 0xd3, 0xa8, 0xe5, 0x9e, 0x4a, 0x31, 0xec, 0x97, 0x43, 0x38, 0x75, 0x0e, 0xda, 0xa1, 0x16, 0x6d, 0xb9, 0xc2, 0x8f, 0xf4, 0x20, 0x5b, @@ -61,9 +61,9 @@ namespace dsp { }; const uint32_t ASM_VALUE = 0x1ACFFC1D; - const uint8_t ASM_BYTES[4] = {0x1A, 0xCF, 0xFC, 0x1D}; - const uint8_t ASM_SYMS[16] = {0b00, 0b01, 0b10, 0b10, 0b11, 0b00, 0b11, 0b11, 0b11, 0b11, 0b11, 0b00, 0b00, 0b01, 0b11, 0b01}; - const uint8_t ASM_BITS[32] = {0,0,0,1,1,0,1,0,1,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,1}; + const uint8_t ASM_BYTES[4] = { 0x1A, 0xCF, 0xFC, 0x1D }; + const uint8_t ASM_SYMS[16] = { 0b00, 0b01, 0b10, 0b10, 0b11, 0b00, 0b11, 0b11, 0b11, 0b11, 0b11, 0b00, 0b00, 0b01, 0b11, 0b01 }; + const uint8_t ASM_BITS[32] = { 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1 }; class FrameDataDecoder { public: @@ -109,11 +109,10 @@ namespace dsp { bool _dualBasis; int _rsBlockSize; int _rsParitySize; - }; inline void descramble(uint8_t* in, uint8_t* out, int count) { - for (int i = 0; i < count; i++){ + for (int i = 0; i < count; i++) { out[i] = in[i] ^ SCRAMBLING_SEQUENCE[i % 255]; } } diff --git a/core/src/dsp/utils/macros.h b/core/src/dsp/utils/macros.h index f6d0b089..9400805d 100644 --- a/core/src/dsp/utils/macros.h +++ b/core/src/dsp/utils/macros.h @@ -1,6 +1,6 @@ #pragma once #include -#define DSP_SIGN(n) ((n) >= 0) -#define DSP_STEP_CPLX(c) (complex_t{(c.re > 0.0f) ? 1.0f : -1.0f, (c.im > 0.0f) ? 1.0f : -1.0f}) -#define DSP_STEP(n) (((n) > 0.0f) ? 1.0f : -1.0f) \ No newline at end of file +#define DSP_SIGN(n) ((n) >= 0) +#define DSP_STEP_CPLX(c) (complex_t{ (c.re > 0.0f) ? 1.0f : -1.0f, (c.im > 0.0f) ? 1.0f : -1.0f }) +#define DSP_STEP(n) (((n) > 0.0f) ? 1.0f : -1.0f) \ No newline at end of file diff --git a/core/src/dsp/utils/math.h b/core/src/dsp/utils/math.h index fcae2f46..44fca8a4 100644 --- a/core/src/dsp/utils/math.h +++ b/core/src/dsp/utils/math.h @@ -1,12 +1,12 @@ #pragma once #include -#define FL_M_PI 3.1415926535f +#define FL_M_PI 3.1415926535f namespace dsp { namespace math { inline double sinc(double omega, double x, double norm) { - return (x == 0.0f) ? 1.0f : (sin(omega*x)/(norm*x)); + return (x == 0.0f) ? 1.0f : (sin(omega * x) / (norm * x)); } } } \ No newline at end of file diff --git a/core/src/dsp/utils/window_functions.h b/core/src/dsp/utils/window_functions.h index c3a1379b..2283a681 100644 --- a/core/src/dsp/utils/window_functions.h +++ b/core/src/dsp/utils/window_functions.h @@ -4,13 +4,13 @@ namespace dsp { namespace window_function { inline double blackman(double n, double N, double alpha = 0.16f) { - double a0 = (1.0f-alpha) / 2.0f; + double a0 = (1.0f - alpha) / 2.0f; double a2 = alpha / 2.0f; - return a0 - (0.5f*cos(2.0f*FL_M_PI*(n/N))) + (a2*cos(4.0f*FL_M_PI*(n/N))); + return a0 - (0.5f * cos(2.0f * FL_M_PI * (n / N))) + (a2 * cos(4.0f * FL_M_PI * (n / N))); } inline double blackmanThirdOrder(double n, double N, double a0, double a1, double a2, double a3) { - return a0 - (a1*cos(2.0f*FL_M_PI*(n/N))) + (a2*cos(4.0f*FL_M_PI*(n/N))) - (a3*cos(6.0f*FL_M_PI*(n/N))); + return a0 - (a1 * cos(2.0f * FL_M_PI * (n / N))) + (a2 * cos(4.0f * FL_M_PI * (n / N))) - (a3 * cos(6.0f * FL_M_PI * (n / N))); } inline double nuttall(double n, double N) { diff --git a/core/src/dsp/vfo.h b/core/src/dsp/vfo.h index 63190b3e..5aa5cfb0 100644 --- a/core/src/dsp/vfo.h +++ b/core/src/dsp/vfo.h @@ -60,7 +60,10 @@ namespace dsp { void setInSampleRate(float inSampleRate) { assert(_init); _inSampleRate = inSampleRate; - if (running) { xlator.stop(); resamp.stop(); } + if (running) { + xlator.stop(); + resamp.stop(); + } xlator.setSampleRate(_inSampleRate); resamp.setInSampleRate(_inSampleRate); float realCutoff = std::min(_bandWidth, std::min(_inSampleRate, _outSampleRate)) / 2.0f; @@ -68,7 +71,10 @@ namespace dsp { win.setCutoff(realCutoff); win.setTransWidth(realCutoff); resamp.updateWindow(&win); - if (running) { xlator.start(); resamp.start(); } + if (running) { + xlator.start(); + resamp.start(); + } } void setOutSampleRate(float outSampleRate) { @@ -123,6 +129,5 @@ namespace dsp { stream* _in; FrequencyXlator xlator; PolyphaseResampler resamp; - }; } \ No newline at end of file diff --git a/core/src/dsp/window.h b/core/src/dsp/window.h index 7f45e7c7..c479e207 100644 --- a/core/src/dsp/window.h +++ b/core/src/dsp/window.h @@ -36,7 +36,7 @@ namespace dsp { void setCutoff(float cutoff) { _cutoff = cutoff; } - + void setTransWidth(float transWidth) { _transWidth = transWidth; } @@ -67,7 +67,7 @@ namespace dsp { float sum = 0.0f; float tc = tapCount; for (int i = 0; i < tapCount; i++) { - val = math::sinc(omega, (float)i - (tc/2), FL_M_PI) * window_function::blackman(i, tc - 1); + val = math::sinc(omega, (float)i - (tc / 2), FL_M_PI) * window_function::blackman(i, tc - 1); taps[i] = val; sum += val; } @@ -81,7 +81,6 @@ namespace dsp { private: float _cutoff, _transWidth, _sampleRate; - }; class BandPassBlackmanWindow : public filter_window::generic_complex_window { @@ -132,7 +131,7 @@ namespace dsp { _offset = (_lowCutoff + _highCutoff) / 2.0f; _cutoff = fabs((_highCutoff - _lowCutoff) / 2.0f); } - + void setTransWidth(float transWidth) { _transWidth = transWidth; } @@ -163,7 +162,7 @@ namespace dsp { float sum = 0.0f; float tc = tapCount; for (int i = 0; i < tapCount; i++) { - val = math::sinc(omega, (float)i - (tc/2), FL_M_PI) * window_function::blackman(i, tc - 1); + val = math::sinc(omega, (float)i - (tc / 2), FL_M_PI) * window_function::blackman(i, tc - 1); taps[i].re = val; taps[i].im = 0; sum += val; @@ -225,26 +224,24 @@ namespace dsp { double spb = _sampleRate / _baudRate; // samples per bit/symbol double scale = 0; - for (int i = 0; i < tapCount; i++) - { + for (int i = 0; i < tapCount; i++) { double x1, x2, x3, num, den; double xindx = i - tapCount / 2; x1 = FL_M_PI * xindx / spb; x2 = 4 * _alpha * xindx / spb; x3 = x2 * x2 - 1; - // Avoid Rounding errors... + // Avoid Rounding errors... if (fabs(x3) >= 0.000001) { if (i != tapCount / 2) num = cos((1 + _alpha) * x1) + - sin((1 - _alpha) * x1) / (4 * _alpha * xindx / spb); + sin((1 - _alpha) * x1) / (4 * _alpha * xindx / spb); else num = cos((1 + _alpha) * x1) + (1 - _alpha) * FL_M_PI / (4 * _alpha); den = x3 * FL_M_PI; } else { - if (_alpha == 1) - { + if (_alpha == 1) { taps[i] = -1; scale += taps[i]; continue; @@ -252,8 +249,8 @@ namespace dsp { x3 = (1 - _alpha) * x1; x2 = (1 + _alpha) * x1; num = (sin(x2) * (1 + _alpha) * FL_M_PI - - cos(x3) * ((1 - _alpha) * FL_M_PI * spb) / (4 * _alpha * xindx) + - sin(x3) * spb * spb / (4 * _alpha * xindx * xindx)); + cos(x3) * ((1 - _alpha) * FL_M_PI * spb) / (4 * _alpha * xindx) + + sin(x3) * spb * spb / (4 * _alpha * xindx * xindx)); den = -32 * FL_M_PI * _alpha * _alpha * xindx / spb; } taps[i] = 4 * _alpha * num / den; @@ -268,7 +265,6 @@ namespace dsp { private: int _tapCount; float _sampleRate, _baudRate, _alpha; - }; // class NotchWindow : public filter_window::generic_complex_window { @@ -290,8 +286,8 @@ namespace dsp { // _tapCount = tapCount; // // Ensure the number of taps is even - // if (_tapCount & 1) { _tapCount++; } - + // if (_tapCount & 1) { _tapCount++; } + // fft_in = (complex_t*)fftwf_malloc(_tapCount * sizeof(complex_t)); // fft_out = (complex_t*)fftwf_malloc(_tapCount * sizeof(complex_t)); @@ -337,7 +333,7 @@ namespace dsp { // int thalf = tapCount / 2; // float start = _frequency - (_width / 2.0f); // float stop = _frequency + (_width / 2.0f); - + // // Fill taps // float freq; // float pratio = 2.0f * FL_M_PI / (float)tapCount; @@ -407,7 +403,7 @@ namespace dsp { // Generate exponential decay float fact = 1.0f / (float)tapCount; for (int i = 0; i < tapCount; i++) { - taps[tapCount - i - 1] = {expf(-fact*i) * (float)window_function::blackman(i, tapCount - 1), 0}; + taps[tapCount - i - 1] = { expf(-fact * i) * (float)window_function::blackman(i, tapCount - 1), 0 }; } // Frequency translate it to the right place @@ -419,6 +415,5 @@ namespace dsp { private: float _frequency, _sampleRate; int _tapCount; - }; } \ No newline at end of file diff --git a/core/src/gui/colormaps.cpp b/core/src/gui/colormaps.cpp index b1e00bcd..48161176 100644 --- a/core/src/gui/colormaps.cpp +++ b/core/src/gui/colormaps.cpp @@ -36,7 +36,7 @@ namespace colormaps { map.entryCount = mapTxt.size(); map.map = new float[mapTxt.size() * 3]; int i = 0; - for(auto const& col : mapTxt) { + for (auto const& col : mapTxt) { uint8_t r, g, b, a; map.map[i * 3] = std::stoi(col.substr(1, 2), NULL, 16); map.map[(i * 3) + 1] = std::stoi(col.substr(3, 2), NULL, 16); diff --git a/core/src/gui/dialogs/credits.cpp b/core/src/gui/dialogs/credits.cpp index bffe8e53..fd8abc40 100644 --- a/core/src/gui/dialogs/credits.cpp +++ b/core/src/gui/dialogs/credits.cpp @@ -10,14 +10,13 @@ namespace credits { ImFont* bigFont; void init() { - } void show() { ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(20.0f, 20.0f)); - ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0,0,0,0)); + ImGui::PushStyleColor(ImGuiCol_Border, ImVec4(0, 0, 0, 0)); ImVec2 dispSize = ImGui::GetIO().DisplaySize; - ImVec2 center = ImVec2(dispSize.x/2.0f, dispSize.y/2.0f); + ImVec2 center = ImVec2(dispSize.x / 2.0f, dispSize.y / 2.0f); ImGui::SetNextWindowPos(center, ImGuiCond_Always, ImVec2(0.5f, 0.5f)); ImGui::OpenPopup("Credits"); ImGui::BeginPopupModal("Credits", NULL, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove); diff --git a/core/src/gui/dialogs/dialog_box.h b/core/src/gui/dialogs/dialog_box.h index d06615f8..1212dff3 100644 --- a/core/src/gui/dialogs/dialog_box.h +++ b/core/src/gui/dialogs/dialog_box.h @@ -4,19 +4,19 @@ #include #include -#define GENERIC_DIALOG_BUTTONS_OK "Ok\0" -#define GENERIC_DIALOG_BUTTONS_YES_NO "Yes\0No\0" -#define GENERIC_DIALOG_BUTTONS_APPLY_CANCEL "Apply\0Cancel\0" -#define GENERIC_DIALOG_BUTTONS_OK_CANCEL "Ok\0Cancel\0" +#define GENERIC_DIALOG_BUTTONS_OK "Ok\0" +#define GENERIC_DIALOG_BUTTONS_YES_NO "Yes\0No\0" +#define GENERIC_DIALOG_BUTTONS_APPLY_CANCEL "Apply\0Cancel\0" +#define GENERIC_DIALOG_BUTTONS_OK_CANCEL "Ok\0Cancel\0" -#define GENERIC_DIALOG_BUTTON_OK 0 -#define GENERIC_DIALOG_BUTTON_YES 0 -#define GENERIC_DIALOG_BUTTON_NO 1 -#define GENERIC_DIALOG_BUTTON_APPLY 0 -#define GENERIC_DIALOG_BUTTON_CANCE 1 +#define GENERIC_DIALOG_BUTTON_OK 0 +#define GENERIC_DIALOG_BUTTON_YES 0 +#define GENERIC_DIALOG_BUTTON_NO 1 +#define GENERIC_DIALOG_BUTTON_APPLY 0 +#define GENERIC_DIALOG_BUTTON_CANCE 1 namespace ImGui { - template + template int GenericDialog(const char* id, bool& open, const char* buttons, Func draw) { // If not open, return if (!open) { return -1; } diff --git a/core/src/gui/file_dialogs.h b/core/src/gui/file_dialogs.h index 2f72008a..29df07cb 100644 --- a/core/src/gui/file_dialogs.h +++ b/core/src/gui/file_dialogs.h @@ -14,7 +14,7 @@ #if _WIN32 #ifndef WIN32_LEAN_AND_MEAN -# define WIN32_LEAN_AND_MEAN 1 +#define WIN32_LEAN_AND_MEAN 1 #endif #include #include @@ -22,17 +22,17 @@ #include // IFileDialog #include #include -#include // std::async +#include // std::async #elif __EMSCRIPTEN__ #include #else #ifndef _POSIX_C_SOURCE -# define _POSIX_C_SOURCE 2 // for popen() +#define _POSIX_C_SOURCE 2 // for popen() #endif #ifdef __APPLE__ -# define _DARWIN_C_SOURCE +#define _DARWIN_C_SOURCE #endif #include // popen() #include // std::getenv() @@ -51,837 +51,777 @@ #include // std::mutex, std::this_thread #include // std::chrono -namespace pfd -{ +namespace pfd { -enum class button -{ - cancel = -1, - ok, - yes, - no, - abort, - retry, - ignore, -}; - -enum class choice -{ - ok = 0, - ok_cancel, - yes_no, - yes_no_cancel, - retry_cancel, - abort_retry_ignore, -}; - -enum class icon -{ - info = 0, - warning, - error, - question, -}; - -// Additional option flags for various dialog constructors -enum class opt : uint8_t -{ - none = 0, - // For file open, allow multiselect. - multiselect = 0x1, - // For file save, force overwrite and disable the confirmation dialog. - force_overwrite = 0x2, - // For folder select, force path to be the provided argument instead - // of the last opened directory, which is the Microsoft-recommended, - // user-friendly behaviour. - force_path = 0x4, -}; - -inline opt operator |(opt a, opt b) { return opt(uint8_t(a) | uint8_t(b)); } -inline bool operator &(opt a, opt b) { return bool(uint8_t(a) & uint8_t(b)); } - -// The settings class, only exposing to the user a way to set verbose mode -// and to force a rescan of installed desktop helpers (zenity, kdialog…). -class settings -{ -public: - static bool available(); - - static void verbose(bool value); - static void rescan(); - -protected: - explicit settings(bool resync = false); - - bool check_program(std::string const &program); - - inline bool is_osascript() const; - inline bool is_zenity() const; - inline bool is_kdialog() const; - - enum class flag - { - is_scanned = 0, - is_verbose, - - has_zenity, - has_matedialog, - has_qarma, - has_kdialog, - is_vista, - - max_flag, + enum class button { + cancel = -1, + ok, + yes, + no, + abort, + retry, + ignore, }; - // Static array of flags for internal state - bool const &flags(flag in_flag) const; + enum class choice { + ok = 0, + ok_cancel, + yes_no, + yes_no_cancel, + retry_cancel, + abort_retry_ignore, + }; - // Non-const getter for the static array of flags - bool &flags(flag in_flag); -}; + enum class icon { + info = 0, + warning, + error, + question, + }; -// Internal classes, not to be used by client applications -namespace internal -{ + // Additional option flags for various dialog constructors + enum class opt : uint8_t { + none = 0, + // For file open, allow multiselect. + multiselect = 0x1, + // For file save, force overwrite and disable the confirmation dialog. + force_overwrite = 0x2, + // For folder select, force path to be the provided argument instead + // of the last opened directory, which is the Microsoft-recommended, + // user-friendly behaviour. + force_path = 0x4, + }; -// Process wait timeout, in milliseconds -static int const default_wait_timeout = 20; + inline opt operator|(opt a, opt b) { return opt(uint8_t(a) | uint8_t(b)); } + inline bool operator&(opt a, opt b) { return bool(uint8_t(a) & uint8_t(b)); } -class executor -{ - friend class dialog; - -public: - // High level function to get the result of a command - std::string result(int *exit_code = nullptr); - - // High level function to abort - bool kill(); - -#if _WIN32 - void start_func(std::function const &fun); - static BOOL CALLBACK enum_windows_callback(HWND hwnd, LPARAM lParam); -#elif __EMSCRIPTEN__ - void start(int exit_code); -#else - void start_process(std::vector const &command); -#endif - - ~executor(); - -protected: - bool ready(int timeout = default_wait_timeout); - void stop(); - -private: - bool m_running = false; - std::string m_stdout; - int m_exit_code = -1; -#if _WIN32 - std::future m_future; - std::set m_windows; - std::condition_variable m_cond; - std::mutex m_mutex; - DWORD m_tid; -#elif __EMSCRIPTEN__ || __NX__ - // FIXME: do something -#else - pid_t m_pid = 0; - int m_fd = -1; -#endif -}; - -class platform -{ -protected: -#if _WIN32 - // Helper class around LoadLibraryA() and GetProcAddress() with some safety - class dll - { + // The settings class, only exposing to the user a way to set verbose mode + // and to force a rescan of installed desktop helpers (zenity, kdialog…). + class settings { public: - dll(std::string const &name); - ~dll(); + static bool available(); - template class proc - { - public: - proc(dll const &lib, std::string const &sym) - : m_proc(reinterpret_cast(::GetProcAddress(lib.handle, sym.c_str()))) - {} + static void verbose(bool value); + static void rescan(); - operator bool() const { return m_proc != nullptr; } - operator T *() const { return m_proc; } + protected: + explicit settings(bool resync = false); - private: - T *m_proc; + bool check_program(std::string const& program); + + inline bool is_osascript() const; + inline bool is_zenity() const; + inline bool is_kdialog() const; + + enum class flag { + is_scanned = 0, + is_verbose, + + has_zenity, + has_matedialog, + has_qarma, + has_kdialog, + is_vista, + + max_flag, }; - private: - HMODULE handle; + // Static array of flags for internal state + bool const& flags(flag in_flag) const; + + // Non-const getter for the static array of flags + bool& flags(flag in_flag); }; - // Helper class around CoInitialize() and CoUnInitialize() - class ole32_dll : public dll - { - public: - ole32_dll(); - ~ole32_dll(); - bool is_initialized(); + // Internal classes, not to be used by client applications + namespace internal { - private: - HRESULT m_state; - }; + // Process wait timeout, in milliseconds + static int const default_wait_timeout = 20; - // Helper class around CreateActCtx() and ActivateActCtx() - class new_style_context - { - public: - new_style_context(); - ~new_style_context(); + class executor { + friend class dialog; - private: - HANDLE create(); - ULONG_PTR m_cookie = 0; - }; -#endif -}; + public: + // High level function to get the result of a command + std::string result(int* exit_code = nullptr); -class dialog : protected settings, protected platform -{ -public: - bool ready(int timeout = default_wait_timeout) const; - bool kill() const; - -protected: - explicit dialog(); - - std::vector desktop_helper() const; - static std::string buttons_to_name(choice _choice); - static std::string get_icon_name(icon _icon); - - std::string powershell_quote(std::string const &str) const; - std::string osascript_quote(std::string const &str) const; - std::string shell_quote(std::string const &str) const; - - // Keep handle to executing command - std::shared_ptr m_async; -}; - -class file_dialog : public dialog -{ -protected: - enum type - { - open, - save, - folder, - }; - - file_dialog(type in_type, - std::string const &title, - std::string const &default_path = "", - std::vector const &filters = {}, - opt options = opt::none); - -protected: - std::string string_result(); - std::vector vector_result(); + // High level function to abort + bool kill(); #if _WIN32 - static int CALLBACK bffcallback(HWND hwnd, UINT uMsg, LPARAM, LPARAM pData); - std::string select_folder_vista(IFileDialog *ifd, bool force_path); - - std::wstring m_wtitle; - std::wstring m_wdefault_path; - - std::vector m_vector_result; + void start_func(std::function const& fun); + static BOOL CALLBACK enum_windows_callback(HWND hwnd, LPARAM lParam); +#elif __EMSCRIPTEN__ + void start(int exit_code); +#else + void start_process(std::vector const& command); #endif -}; -} // namespace internal + ~executor(); -// -// The notify widget -// + protected: + bool ready(int timeout = default_wait_timeout); + void stop(); -class notify : public internal::dialog -{ -public: - notify(std::string const &title, - std::string const &message, - icon _icon = icon::info); -}; - -// -// The message widget -// - -class message : public internal::dialog -{ -public: - message(std::string const &title, - std::string const &text, - choice _choice = choice::ok_cancel, - icon _icon = icon::info); - - button result(); - -private: - // Some extra logic to map the exit code to button number - std::map m_mappings; -}; - -// -// The open_file, save_file, and open_folder widgets -// - -class open_file : public internal::file_dialog -{ -public: - open_file(std::string const &title, - std::string const &default_path = "", - std::vector const &filters = { "All Files", "*" }, - opt options = opt::none); - -#if defined(__has_cpp_attribute) -#if __has_cpp_attribute(deprecated) - // Backwards compatibility - [[deprecated("Use pfd::opt::multiselect instead of allow_multiselect")]] + private: + bool m_running = false; + std::string m_stdout; + int m_exit_code = -1; +#if _WIN32 + std::future m_future; + std::set m_windows; + std::condition_variable m_cond; + std::mutex m_mutex; + DWORD m_tid; +#elif __EMSCRIPTEN__ || __NX__ + // FIXME: do something +#else + pid_t m_pid = 0; + int m_fd = -1; #endif + }; + + class platform { + protected: +#if _WIN32 + // Helper class around LoadLibraryA() and GetProcAddress() with some safety + class dll { + public: + dll(std::string const& name); + ~dll(); + + template + class proc { + public: + proc(dll const& lib, std::string const& sym) + : m_proc(reinterpret_cast(::GetProcAddress(lib.handle, sym.c_str()))) {} + + operator bool() const { return m_proc != nullptr; } + operator T*() const { return m_proc; } + + private: + T* m_proc; + }; + + private: + HMODULE handle; + }; + + // Helper class around CoInitialize() and CoUnInitialize() + class ole32_dll : public dll { + public: + ole32_dll(); + ~ole32_dll(); + bool is_initialized(); + + private: + HRESULT m_state; + }; + + // Helper class around CreateActCtx() and ActivateActCtx() + class new_style_context { + public: + new_style_context(); + ~new_style_context(); + + private: + HANDLE create(); + ULONG_PTR m_cookie = 0; + }; #endif - open_file(std::string const &title, - std::string const &default_path, - std::vector const &filters, - bool allow_multiselect); + }; - std::vector result(); -}; + class dialog : protected settings, protected platform { + public: + bool ready(int timeout = default_wait_timeout) const; + bool kill() const; -class save_file : public internal::file_dialog -{ -public: - save_file(std::string const &title, - std::string const &default_path = "", - std::vector const &filters = { "All Files", "*" }, - opt options = opt::none); + protected: + explicit dialog(); -#if defined(__has_cpp_attribute) -#if __has_cpp_attribute(deprecated) - // Backwards compatibility - [[deprecated("Use pfd::opt::force_overwrite instead of confirm_overwrite")]] + std::vector desktop_helper() const; + static std::string buttons_to_name(choice _choice); + static std::string get_icon_name(icon _icon); + + std::string powershell_quote(std::string const& str) const; + std::string osascript_quote(std::string const& str) const; + std::string shell_quote(std::string const& str) const; + + // Keep handle to executing command + std::shared_ptr m_async; + }; + + class file_dialog : public dialog { + protected: + enum type { + open, + save, + folder, + }; + + file_dialog(type in_type, + std::string const& title, + std::string const& default_path = "", + std::vector const& filters = {}, + opt options = opt::none); + + protected: + std::string string_result(); + std::vector vector_result(); + +#if _WIN32 + static int CALLBACK bffcallback(HWND hwnd, UINT uMsg, LPARAM, LPARAM pData); + std::string select_folder_vista(IFileDialog* ifd, bool force_path); + + std::wstring m_wtitle; + std::wstring m_wdefault_path; + + std::vector m_vector_result; #endif -#endif - save_file(std::string const &title, - std::string const &default_path, - std::vector const &filters, - bool confirm_overwrite); + }; - std::string result(); -}; + } // namespace internal -class select_folder : public internal::file_dialog -{ -public: - select_folder(std::string const &title, - std::string const &default_path = "", + // + // The notify widget + // + + class notify : public internal::dialog { + public: + notify(std::string const& title, + std::string const& message, + icon _icon = icon::info); + }; + + // + // The message widget + // + + class message : public internal::dialog { + public: + message(std::string const& title, + std::string const& text, + choice _choice = choice::ok_cancel, + icon _icon = icon::info); + + button result(); + + private: + // Some extra logic to map the exit code to button number + std::map m_mappings; + }; + + // + // The open_file, save_file, and open_folder widgets + // + + class open_file : public internal::file_dialog { + public: + open_file(std::string const& title, + std::string const& default_path = "", + std::vector const& filters = { "All Files", "*" }, opt options = opt::none); - std::string result(); -}; +#if defined(__has_cpp_attribute) +#if __has_cpp_attribute(deprecated) + // Backwards compatibility + [[deprecated("Use pfd::opt::multiselect instead of allow_multiselect")]] +#endif +#endif + open_file(std::string const& title, + std::string const& default_path, + std::vector const& filters, + bool allow_multiselect); -// -// Below this are all the method implementations. You may choose to define the -// macro PFD_SKIP_IMPLEMENTATION everywhere before including this header except -// in one place. This may reduce compilation times. -// + std::vector result(); + }; + + class save_file : public internal::file_dialog { + public: + save_file(std::string const& title, + std::string const& default_path = "", + std::vector const& filters = { "All Files", "*" }, + opt options = opt::none); + +#if defined(__has_cpp_attribute) +#if __has_cpp_attribute(deprecated) + // Backwards compatibility + [[deprecated("Use pfd::opt::force_overwrite instead of confirm_overwrite")]] +#endif +#endif + save_file(std::string const& title, + std::string const& default_path, + std::vector const& filters, + bool confirm_overwrite); + + std::string result(); + }; + + class select_folder : public internal::file_dialog { + public: + select_folder(std::string const& title, + std::string const& default_path = "", + opt options = opt::none); + + std::string result(); + }; + + // + // Below this are all the method implementations. You may choose to define the + // macro PFD_SKIP_IMPLEMENTATION everywhere before including this header except + // in one place. This may reduce compilation times. + // #if !defined PFD_SKIP_IMPLEMENTATION -// internal free functions implementations + // internal free functions implementations -namespace internal -{ + namespace internal { #if _WIN32 -static inline std::wstring str2wstr(std::string const &str) -{ - int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), nullptr, 0); - std::wstring ret(len, '\0'); - MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), (LPWSTR)ret.data(), (int)ret.size()); - return ret; -} + static inline std::wstring str2wstr(std::string const& str) { + int len = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), nullptr, 0); + std::wstring ret(len, '\0'); + MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), (LPWSTR)ret.data(), (int)ret.size()); + return ret; + } -static inline std::string wstr2str(std::wstring const &str) -{ - int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), (int)str.size(), nullptr, 0, nullptr, nullptr); - std::string ret(len, '\0'); - WideCharToMultiByte(CP_UTF8, 0, str.c_str(), (int)str.size(), (LPSTR)ret.data(), (int)ret.size(), nullptr, nullptr); - return ret; -} + static inline std::string wstr2str(std::wstring const& str) { + int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), (int)str.size(), nullptr, 0, nullptr, nullptr); + std::string ret(len, '\0'); + WideCharToMultiByte(CP_UTF8, 0, str.c_str(), (int)str.size(), (LPSTR)ret.data(), (int)ret.size(), nullptr, nullptr); + return ret; + } -static inline bool is_vista() -{ - OSVERSIONINFOEXW osvi; - memset(&osvi, 0, sizeof(osvi)); - DWORDLONG const mask = VerSetConditionMask( - VerSetConditionMask( + static inline bool is_vista() { + OSVERSIONINFOEXW osvi; + memset(&osvi, 0, sizeof(osvi)); + DWORDLONG const mask = VerSetConditionMask( + VerSetConditionMask( VerSetConditionMask( - 0, VER_MAJORVERSION, VER_GREATER_EQUAL), + 0, VER_MAJORVERSION, VER_GREATER_EQUAL), VER_MINORVERSION, VER_GREATER_EQUAL), - VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); - osvi.dwOSVersionInfoSize = sizeof(osvi); - osvi.dwMajorVersion = HIBYTE(_WIN32_WINNT_VISTA); - osvi.dwMinorVersion = LOBYTE(_WIN32_WINNT_VISTA); - osvi.wServicePackMajor = 0; + VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL); + osvi.dwOSVersionInfoSize = sizeof(osvi); + osvi.dwMajorVersion = HIBYTE(_WIN32_WINNT_VISTA); + osvi.dwMinorVersion = LOBYTE(_WIN32_WINNT_VISTA); + osvi.wServicePackMajor = 0; - return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, mask) != FALSE; -} + return VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_SERVICEPACKMAJOR, mask) != FALSE; + } #endif -// This is necessary until C++20 which will have std::string::ends_with() etc. + // This is necessary until C++20 which will have std::string::ends_with() etc. -static inline bool ends_with(std::string const &str, std::string const &suffix) -{ - return suffix.size() <= str.size() && - str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; -} + static inline bool ends_with(std::string const& str, std::string const& suffix) { + return suffix.size() <= str.size() && + str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0; + } -static inline bool starts_with(std::string const &str, std::string const &prefix) -{ - return prefix.size() <= str.size() && - str.compare(0, prefix.size(), prefix) == 0; -} + static inline bool starts_with(std::string const& str, std::string const& prefix) { + return prefix.size() <= str.size() && + str.compare(0, prefix.size(), prefix) == 0; + } -} // namespace internal + } // namespace internal -// settings implementation + // settings implementation -inline settings::settings(bool resync) -{ - flags(flag::is_scanned) &= !resync; + inline settings::settings(bool resync) { + flags(flag::is_scanned) &= !resync; - if (flags(flag::is_scanned)) - return; + if (flags(flag::is_scanned)) + return; #if _WIN32 - flags(flag::is_vista) = internal::is_vista(); + flags(flag::is_vista) = internal::is_vista(); #elif !__APPLE__ - flags(flag::has_zenity) = check_program("zenity"); - flags(flag::has_matedialog) = check_program("matedialog"); - flags(flag::has_qarma) = check_program("qarma"); - flags(flag::has_kdialog) = check_program("kdialog"); + flags(flag::has_zenity) = check_program("zenity"); + flags(flag::has_matedialog) = check_program("matedialog"); + flags(flag::has_qarma) = check_program("qarma"); + flags(flag::has_kdialog) = check_program("kdialog"); - // If multiple helpers are available, try to default to the best one - if (flags(flag::has_zenity) && flags(flag::has_kdialog)) - { - auto desktop_name = std::getenv("XDG_SESSION_DESKTOP"); - if (desktop_name && desktop_name == std::string("gnome")) - flags(flag::has_kdialog) = false; - else if (desktop_name && desktop_name == std::string("KDE")) - flags(flag::has_zenity) = false; - } + // If multiple helpers are available, try to default to the best one + if (flags(flag::has_zenity) && flags(flag::has_kdialog)) { + auto desktop_name = std::getenv("XDG_SESSION_DESKTOP"); + if (desktop_name && desktop_name == std::string("gnome")) + flags(flag::has_kdialog) = false; + else if (desktop_name && desktop_name == std::string("KDE")) + flags(flag::has_zenity) = false; + } #endif - flags(flag::is_scanned) = true; -} - -inline bool settings::available() -{ -#if _WIN32 - return true; -#elif __APPLE__ - return true; -#else - settings tmp; - return tmp.flags(flag::has_zenity) || - tmp.flags(flag::has_matedialog) || - tmp.flags(flag::has_qarma) || - tmp.flags(flag::has_kdialog); -#endif -} - -inline void settings::verbose(bool value) -{ - settings().flags(flag::is_verbose) = value; -} - -inline void settings::rescan() -{ - settings(/* resync = */ true); -} - -// Check whether a program is present using “which”. -inline bool settings::check_program(std::string const &program) -{ -#if _WIN32 - (void)program; - return false; -#elif __EMSCRIPTEN__ - (void)program; - return false; -#else - int exit_code = -1; - internal::executor async; - async.start_process({"/bin/sh", "-c", "which " + program}); - async.result(&exit_code); - return exit_code == 0; -#endif -} - -inline bool settings::is_osascript() const -{ -#if __APPLE__ - return true; -#else - return false; -#endif -} - -inline bool settings::is_zenity() const -{ - return flags(flag::has_zenity) || - flags(flag::has_matedialog) || - flags(flag::has_qarma); -} - -inline bool settings::is_kdialog() const -{ - return flags(flag::has_kdialog); -} - -inline bool const &settings::flags(flag in_flag) const -{ - static bool flags[size_t(flag::max_flag)]; - return flags[size_t(in_flag)]; -} - -inline bool &settings::flags(flag in_flag) -{ - return const_cast(static_cast(this)->flags(in_flag)); -} - -// executor implementation - -inline std::string internal::executor::result(int *exit_code /* = nullptr */) -{ - stop(); - if (exit_code) - *exit_code = m_exit_code; - return m_stdout; -} - -inline bool internal::executor::kill() -{ -#if _WIN32 - if (m_future.valid()) - { - // Close all windows that weren’t open when we started the future - auto previous_windows = m_windows; - EnumWindows(&enum_windows_callback, (LPARAM)this); - for (auto hwnd : m_windows) - if (previous_windows.find(hwnd) == previous_windows.end()) - SendMessage(hwnd, WM_CLOSE, 0, 0); - } -#elif __EMSCRIPTEN__ || __NX__ - // FIXME: do something - (void)timeout; - return false; // cannot kill -#else - ::kill(m_pid, SIGKILL); -#endif - stop(); - return true; -} - -#if _WIN32 -inline BOOL CALLBACK internal::executor::enum_windows_callback(HWND hwnd, LPARAM lParam) -{ - auto that = (executor *)lParam; - - DWORD pid; - auto tid = GetWindowThreadProcessId(hwnd, &pid); - if (tid == that->m_tid) - that->m_windows.insert(hwnd); - return TRUE; -} -#endif - -#if _WIN32 -inline void internal::executor::start_func(std::function const &fun) -{ - stop(); - - auto trampoline = [fun, this]() - { - // Save our thread id so that the caller can cancel us - m_tid = GetCurrentThreadId(); - EnumWindows(&enum_windows_callback, (LPARAM)this); - m_cond.notify_all(); - return fun(&m_exit_code); - }; - - std::unique_lock lock(m_mutex); - m_future = std::async(std::launch::async, trampoline); - m_cond.wait(lock); - m_running = true; -} - -#elif __EMSCRIPTEN__ -inline void internal::executor::start(int exit_code) -{ - m_exit_code = exit_code; -} - -#else -inline void internal::executor::start_process(std::vector const &command) -{ - stop(); - m_stdout.clear(); - m_exit_code = -1; - - int in[2], out[2]; - if (pipe(in) != 0 || pipe(out) != 0) - return; - - m_pid = fork(); - if (m_pid < 0) - return; - - close(in[m_pid ? 0 : 1]); - close(out[m_pid ? 1 : 0]); - - if (m_pid == 0) - { - dup2(in[0], STDIN_FILENO); - dup2(out[1], STDOUT_FILENO); - - // Ignore stderr so that it doesn’t pollute the console (e.g. GTK+ errors from zenity) - int fd = open("/dev/null", O_WRONLY); - dup2(fd, STDERR_FILENO); - close(fd); - - std::vector args; - std::transform(command.cbegin(), command.cend(), std::back_inserter(args), - [](std::string const &s) { return const_cast(s.c_str()); }); - args.push_back(nullptr); // null-terminate argv[] - - execvp(args[0], args.data()); - exit(1); + flags(flag::is_scanned) = true; } - close(in[1]); - m_fd = out[0]; - auto flags = fcntl(m_fd, F_GETFL); - fcntl(m_fd, F_SETFL, flags | O_NONBLOCK); - - m_running = true; -} -#endif - -inline internal::executor::~executor() -{ - stop(); -} - -inline bool internal::executor::ready(int timeout /* = default_wait_timeout */) -{ - if (!m_running) + inline bool settings::available() { +#if _WIN32 return true; +#elif __APPLE__ + return true; +#else + settings tmp; + return tmp.flags(flag::has_zenity) || + tmp.flags(flag::has_matedialog) || + tmp.flags(flag::has_qarma) || + tmp.flags(flag::has_kdialog); +#endif + } + + inline void settings::verbose(bool value) { + settings().flags(flag::is_verbose) = value; + } + + inline void settings::rescan() { + settings(/* resync = */ true); + } + + // Check whether a program is present using “which”. + inline bool settings::check_program(std::string const& program) { +#if _WIN32 + (void)program; + return false; +#elif __EMSCRIPTEN__ + (void)program; + return false; +#else + int exit_code = -1; + internal::executor async; + async.start_process({ "/bin/sh", "-c", "which " + program }); + async.result(&exit_code); + return exit_code == 0; +#endif + } + + inline bool settings::is_osascript() const { +#if __APPLE__ + return true; +#else + return false; +#endif + } + + inline bool settings::is_zenity() const { + return flags(flag::has_zenity) || + flags(flag::has_matedialog) || + flags(flag::has_qarma); + } + + inline bool settings::is_kdialog() const { + return flags(flag::has_kdialog); + } + + inline bool const& settings::flags(flag in_flag) const { + static bool flags[size_t(flag::max_flag)]; + return flags[size_t(in_flag)]; + } + + inline bool& settings::flags(flag in_flag) { + return const_cast(static_cast(this)->flags(in_flag)); + } + + // executor implementation + + inline std::string internal::executor::result(int* exit_code /* = nullptr */) { + stop(); + if (exit_code) + *exit_code = m_exit_code; + return m_stdout; + } + + inline bool internal::executor::kill() { +#if _WIN32 + if (m_future.valid()) { + // Close all windows that weren’t open when we started the future + auto previous_windows = m_windows; + EnumWindows(&enum_windows_callback, (LPARAM)this); + for (auto hwnd : m_windows) + if (previous_windows.find(hwnd) == previous_windows.end()) + SendMessage(hwnd, WM_CLOSE, 0, 0); + } +#elif __EMSCRIPTEN__ || __NX__ + // FIXME: do something + (void)timeout; + return false; // cannot kill +#else + ::kill(m_pid, SIGKILL); +#endif + stop(); + return true; + } #if _WIN32 - if (m_future.valid()) - { - auto status = m_future.wait_for(std::chrono::milliseconds(timeout)); - if (status != std::future_status::ready) - { - // On Windows, we need to run the message pump. If the async - // thread uses a Windows API dialog, it may be attached to the - // main thread and waiting for messages that only we can dispatch. - MSG msg; - while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) - { - TranslateMessage(&msg); - DispatchMessage(&msg); + inline BOOL CALLBACK internal::executor::enum_windows_callback(HWND hwnd, LPARAM lParam) { + auto that = (executor*)lParam; + + DWORD pid; + auto tid = GetWindowThreadProcessId(hwnd, &pid); + if (tid == that->m_tid) + that->m_windows.insert(hwnd); + return TRUE; + } +#endif + +#if _WIN32 + inline void internal::executor::start_func(std::function const& fun) { + stop(); + + auto trampoline = [fun, this]() { + // Save our thread id so that the caller can cancel us + m_tid = GetCurrentThreadId(); + EnumWindows(&enum_windows_callback, (LPARAM)this); + m_cond.notify_all(); + return fun(&m_exit_code); + }; + + std::unique_lock lock(m_mutex); + m_future = std::async(std::launch::async, trampoline); + m_cond.wait(lock); + m_running = true; + } + +#elif __EMSCRIPTEN__ + inline void internal::executor::start(int exit_code) { + m_exit_code = exit_code; + } + +#else + inline void internal::executor::start_process(std::vector const& command) { + stop(); + m_stdout.clear(); + m_exit_code = -1; + + int in[2], out[2]; + if (pipe(in) != 0 || pipe(out) != 0) + return; + + m_pid = fork(); + if (m_pid < 0) + return; + + close(in[m_pid ? 0 : 1]); + close(out[m_pid ? 1 : 0]); + + if (m_pid == 0) { + dup2(in[0], STDIN_FILENO); + dup2(out[1], STDOUT_FILENO); + + // Ignore stderr so that it doesn’t pollute the console (e.g. GTK+ errors from zenity) + int fd = open("/dev/null", O_WRONLY); + dup2(fd, STDERR_FILENO); + close(fd); + + std::vector args; + std::transform(command.cbegin(), command.cend(), std::back_inserter(args), + [](std::string const& s) { return const_cast(s.c_str()); }); + args.push_back(nullptr); // null-terminate argv[] + + execvp(args[0], args.data()); + exit(1); + } + + close(in[1]); + m_fd = out[0]; + auto flags = fcntl(m_fd, F_GETFL); + fcntl(m_fd, F_SETFL, flags | O_NONBLOCK); + + m_running = true; + } +#endif + + inline internal::executor::~executor() { + stop(); + } + + inline bool internal::executor::ready(int timeout /* = default_wait_timeout */) { + if (!m_running) + return true; + +#if _WIN32 + if (m_future.valid()) { + auto status = m_future.wait_for(std::chrono::milliseconds(timeout)); + if (status != std::future_status::ready) { + // On Windows, we need to run the message pump. If the async + // thread uses a Windows API dialog, it may be attached to the + // main thread and waiting for messages that only we can dispatch. + MSG msg; + while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessage(&msg); + } + return false; } + + m_stdout = m_future.get(); + } +#elif __EMSCRIPTEN__ || __NX__ + // FIXME: do something + (void)timeout; +#else + char buf[BUFSIZ]; + ssize_t received = read(m_fd, buf, BUFSIZ); // Flawfinder: ignore + if (received > 0) { + m_stdout += std::string(buf, received); return false; } - m_stdout = m_future.get(); - } -#elif __EMSCRIPTEN__ || __NX__ - // FIXME: do something - (void)timeout; -#else - char buf[BUFSIZ]; - ssize_t received = read(m_fd, buf, BUFSIZ); // Flawfinder: ignore - if (received > 0) - { - m_stdout += std::string(buf, received); - return false; - } + // Reap child process if it is dead. It is possible that the system has already reaped it + // (this happens when the calling application handles or ignores SIG_CHLD) and results in + // waitpid() failing with ECHILD. Otherwise we assume the child is running and we sleep for + // a little while. + int status; + pid_t child = waitpid(m_pid, &status, WNOHANG); + if (child != m_pid && (child >= 0 || errno != ECHILD)) { + // FIXME: this happens almost always at first iteration + std::this_thread::sleep_for(std::chrono::milliseconds(timeout)); + return false; + } - // Reap child process if it is dead. It is possible that the system has already reaped it - // (this happens when the calling application handles or ignores SIG_CHLD) and results in - // waitpid() failing with ECHILD. Otherwise we assume the child is running and we sleep for - // a little while. - int status; - pid_t child = waitpid(m_pid, &status, WNOHANG); - if (child != m_pid && (child >= 0 || errno != ECHILD)) - { - // FIXME: this happens almost always at first iteration - std::this_thread::sleep_for(std::chrono::milliseconds(timeout)); - return false; - } - - close(m_fd); - m_exit_code = WEXITSTATUS(status); + close(m_fd); + m_exit_code = WEXITSTATUS(status); #endif - m_running = false; - return true; -} + m_running = false; + return true; + } -inline void internal::executor::stop() -{ - // Loop until the user closes the dialog - while (!ready()) - ; -} + inline void internal::executor::stop() { + // Loop until the user closes the dialog + while (!ready()) + ; + } -// dll implementation + // dll implementation #if _WIN32 -inline internal::platform::dll::dll(std::string const &name) - : handle(::LoadLibraryA(name.c_str())) -{} + inline internal::platform::dll::dll(std::string const& name) + : handle(::LoadLibraryA(name.c_str())) {} -inline internal::platform::dll::~dll() -{ - if (handle) - ::FreeLibrary(handle); -} + inline internal::platform::dll::~dll() { + if (handle) + ::FreeLibrary(handle); + } #endif // _WIN32 -// ole32_dll implementation + // ole32_dll implementation #if _WIN32 -inline internal::platform::ole32_dll::ole32_dll() - : dll("ole32.dll") -{ - // Use COINIT_MULTITHREADED because COINIT_APARTMENTTHREADED causes crashes. - // See https://github.com/samhocevar/portable-file-dialogs/issues/51 - auto coinit = proc(*this, "CoInitializeEx"); - m_state = coinit(nullptr, COINIT_MULTITHREADED); -} + inline internal::platform::ole32_dll::ole32_dll() + : dll("ole32.dll") { + // Use COINIT_MULTITHREADED because COINIT_APARTMENTTHREADED causes crashes. + // See https://github.com/samhocevar/portable-file-dialogs/issues/51 + auto coinit = proc(*this, "CoInitializeEx"); + m_state = coinit(nullptr, COINIT_MULTITHREADED); + } -inline internal::platform::ole32_dll::~ole32_dll() -{ - if (is_initialized()) - proc(*this, "CoUninitialize")(); -} + inline internal::platform::ole32_dll::~ole32_dll() { + if (is_initialized()) + proc(*this, "CoUninitialize")(); + } -inline bool internal::platform::ole32_dll::is_initialized() -{ - return m_state == S_OK || m_state == S_FALSE; -} + inline bool internal::platform::ole32_dll::is_initialized() { + return m_state == S_OK || m_state == S_FALSE; + } #endif -// new_style_context implementation + // new_style_context implementation #if _WIN32 -inline internal::platform::new_style_context::new_style_context() -{ - // Only create one activation context for the whole app lifetime. - static HANDLE hctx = create(); + inline internal::platform::new_style_context::new_style_context() { + // Only create one activation context for the whole app lifetime. + static HANDLE hctx = create(); - if (hctx != INVALID_HANDLE_VALUE) - ActivateActCtx(hctx, &m_cookie); -} + if (hctx != INVALID_HANDLE_VALUE) + ActivateActCtx(hctx, &m_cookie); + } -inline internal::platform::new_style_context::~new_style_context() -{ - DeactivateActCtx(0, m_cookie); -} + inline internal::platform::new_style_context::~new_style_context() { + DeactivateActCtx(0, m_cookie); + } -inline HANDLE internal::platform::new_style_context::create() -{ - // This “hack” seems to be necessary for this code to work on windows XP. - // Without it, dialogs do not show and close immediately. GetError() - // returns 0 so I don’t know what causes this. I was not able to reproduce - // this behavior on Windows 7 and 10 but just in case, let it be here for - // those versions too. - // This hack is not required if other dialogs are used (they load comdlg32 - // automatically), only if message boxes are used. - dll comdlg32("comdlg32.dll"); + inline HANDLE internal::platform::new_style_context::create() { + // This “hack” seems to be necessary for this code to work on windows XP. + // Without it, dialogs do not show and close immediately. GetError() + // returns 0 so I don’t know what causes this. I was not able to reproduce + // this behavior on Windows 7 and 10 but just in case, let it be here for + // those versions too. + // This hack is not required if other dialogs are used (they load comdlg32 + // automatically), only if message boxes are used. + dll comdlg32("comdlg32.dll"); - // Using approach as shown here: https://stackoverflow.com/a/10444161 - UINT len = ::GetSystemDirectoryA(nullptr, 0); - std::string sys_dir(len, '\0'); - ::GetSystemDirectoryA(&sys_dir[0], len); + // Using approach as shown here: https://stackoverflow.com/a/10444161 + UINT len = ::GetSystemDirectoryA(nullptr, 0); + std::string sys_dir(len, '\0'); + ::GetSystemDirectoryA(&sys_dir[0], len); - ACTCTXA act_ctx = - { - // Do not set flag ACTCTX_FLAG_SET_PROCESS_DEFAULT, since it causes a - // crash with error “default context is already set”. - sizeof(act_ctx), - ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID, - "shell32.dll", 0, 0, sys_dir.c_str(), (LPCSTR)124, - }; + ACTCTXA act_ctx = { + // Do not set flag ACTCTX_FLAG_SET_PROCESS_DEFAULT, since it causes a + // crash with error “default context is already set”. + sizeof(act_ctx), + ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_ASSEMBLY_DIRECTORY_VALID, + "shell32.dll", + 0, + 0, + sys_dir.c_str(), + (LPCSTR)124, + }; - return ::CreateActCtxA(&act_ctx); -} + return ::CreateActCtxA(&act_ctx); + } #endif // _WIN32 -// dialog implementation + // dialog implementation -inline bool internal::dialog::ready(int timeout /* = default_wait_timeout */) const -{ - return m_async->ready(timeout); -} + inline bool internal::dialog::ready(int timeout /* = default_wait_timeout */) const { + return m_async->ready(timeout); + } -inline bool internal::dialog::kill() const -{ - return m_async->kill(); -} + inline bool internal::dialog::kill() const { + return m_async->kill(); + } -inline internal::dialog::dialog() - : m_async(std::make_shared()) -{ -} + inline internal::dialog::dialog() + : m_async(std::make_shared()) { + } -inline std::vector internal::dialog::desktop_helper() const -{ + inline std::vector internal::dialog::desktop_helper() const { #if __APPLE__ - return { "osascript" }; + return { "osascript" }; #else - return { flags(flag::has_zenity) ? "zenity" - : flags(flag::has_matedialog) ? "matedialog" - : flags(flag::has_qarma) ? "qarma" - : flags(flag::has_kdialog) ? "kdialog" - : "echo" }; + return { flags(flag::has_zenity) ? "zenity" + : flags(flag::has_matedialog) ? "matedialog" + : flags(flag::has_qarma) ? "qarma" + : flags(flag::has_kdialog) ? "kdialog" + : "echo" }; #endif -} - -inline std::string internal::dialog::buttons_to_name(choice _choice) -{ - switch (_choice) - { - case choice::ok_cancel: return "okcancel"; - case choice::yes_no: return "yesno"; - case choice::yes_no_cancel: return "yesnocancel"; - case choice::retry_cancel: return "retrycancel"; - case choice::abort_retry_ignore: return "abortretryignore"; - /* case choice::ok: */ default: return "ok"; } -} -inline std::string internal::dialog::get_icon_name(icon _icon) -{ - switch (_icon) - { - case icon::warning: return "warning"; - case icon::error: return "error"; - case icon::question: return "question"; + inline std::string internal::dialog::buttons_to_name(choice _choice) { + switch (_choice) { + case choice::ok_cancel: + return "okcancel"; + case choice::yes_no: + return "yesno"; + case choice::yes_no_cancel: + return "yesnocancel"; + case choice::retry_cancel: + return "retrycancel"; + case choice::abort_retry_ignore: + return "abortretryignore"; + /* case choice::ok: */ default: + return "ok"; + } + } + + inline std::string internal::dialog::get_icon_name(icon _icon) { + switch (_icon) { + case icon::warning: + return "warning"; + case icon::error: + return "error"; + case icon::question: + return "question"; // Zenity wants "information" but WinForms wants "info" /* case icon::info: */ default: #if _WIN32 @@ -889,203 +829,184 @@ inline std::string internal::dialog::get_icon_name(icon _icon) #else return "information"; #endif + } } -} -// THis is only used for debugging purposes -inline std::ostream& operator <<(std::ostream &s, std::vector const &v) -{ - int not_first = 0; - for (auto &e : v) - s << (not_first++ ? " " : "") << e; - return s; -} + // THis is only used for debugging purposes + inline std::ostream& operator<<(std::ostream& s, std::vector const& v) { + int not_first = 0; + for (auto& e : v) + s << (not_first++ ? " " : "") << e; + return s; + } -// Properly quote a string for Powershell: replace ' or " with '' or "" -// FIXME: we should probably get rid of newlines! -// FIXME: the \" sequence seems unsafe, too! -// XXX: this is no longer used but I would like to keep it around just in case -inline std::string internal::dialog::powershell_quote(std::string const &str) const -{ - return "'" + std::regex_replace(str, std::regex("['\"]"), "$&$&") + "'"; -} + // Properly quote a string for Powershell: replace ' or " with '' or "" + // FIXME: we should probably get rid of newlines! + // FIXME: the \" sequence seems unsafe, too! + // XXX: this is no longer used but I would like to keep it around just in case + inline std::string internal::dialog::powershell_quote(std::string const& str) const { + return "'" + std::regex_replace(str, std::regex("['\"]"), "$&$&") + "'"; + } -// Properly quote a string for osascript: replace \ or " with \\ or \" -// XXX: this also used to replace ' with \' when popen was used, but it would be -// smarter to do shell_quote(osascript_quote(...)) if this is needed again. -inline std::string internal::dialog::osascript_quote(std::string const &str) const -{ - return "\"" + std::regex_replace(str, std::regex("[\\\\\"]"), "\\$&") + "\""; -} + // Properly quote a string for osascript: replace \ or " with \\ or \" + // XXX: this also used to replace ' with \' when popen was used, but it would be + // smarter to do shell_quote(osascript_quote(...)) if this is needed again. + inline std::string internal::dialog::osascript_quote(std::string const& str) const { + return "\"" + std::regex_replace(str, std::regex("[\\\\\"]"), "\\$&") + "\""; + } -// Properly quote a string for the shell: just replace ' with '\'' -// XXX: this is no longer used but I would like to keep it around just in case -inline std::string internal::dialog::shell_quote(std::string const &str) const -{ - return "'" + std::regex_replace(str, std::regex("'"), "'\\''") + "'"; -} + // Properly quote a string for the shell: just replace ' with '\'' + // XXX: this is no longer used but I would like to keep it around just in case + inline std::string internal::dialog::shell_quote(std::string const& str) const { + return "'" + std::regex_replace(str, std::regex("'"), "'\\''") + "'"; + } -// file_dialog implementation + // file_dialog implementation -inline internal::file_dialog::file_dialog(type in_type, - std::string const &title, - std::string const &default_path /* = "" */, - std::vector const &filters /* = {} */, - opt options /* = opt::none */) -{ + inline internal::file_dialog::file_dialog(type in_type, + std::string const& title, + std::string const& default_path /* = "" */, + std::vector const& filters /* = {} */, + opt options /* = opt::none */) { #if _WIN32 - std::string filter_list; - std::regex whitespace(" *"); - for (size_t i = 0; i + 1 < filters.size(); i += 2) - { - filter_list += filters[i] + '\0'; - filter_list += std::regex_replace(filters[i + 1], whitespace, ";") + '\0'; - } - filter_list += '\0'; + std::string filter_list; + std::regex whitespace(" *"); + for (size_t i = 0; i + 1 < filters.size(); i += 2) { + filter_list += filters[i] + '\0'; + filter_list += std::regex_replace(filters[i + 1], whitespace, ";") + '\0'; + } + filter_list += '\0'; - m_async->start_func([this, in_type, title, default_path, filter_list, - options](int *exit_code) -> std::string - { - (void)exit_code; - m_wtitle = internal::str2wstr(title); - m_wdefault_path = internal::str2wstr(default_path); - auto wfilter_list = internal::str2wstr(filter_list); + m_async->start_func([this, in_type, title, default_path, filter_list, + options](int* exit_code) -> std::string { + (void)exit_code; + m_wtitle = internal::str2wstr(title); + m_wdefault_path = internal::str2wstr(default_path); + auto wfilter_list = internal::str2wstr(filter_list); - // Initialise COM. This is required for the new folder selection window, - // (see https://github.com/samhocevar/portable-file-dialogs/pull/21) - // and to avoid random crashes with GetOpenFileNameW() (see - // https://github.com/samhocevar/portable-file-dialogs/issues/51) - ole32_dll ole32; + // Initialise COM. This is required for the new folder selection window, + // (see https://github.com/samhocevar/portable-file-dialogs/pull/21) + // and to avoid random crashes with GetOpenFileNameW() (see + // https://github.com/samhocevar/portable-file-dialogs/issues/51) + ole32_dll ole32; - // Folder selection uses a different method - if (in_type == type::folder) - { - if (flags(flag::is_vista)) - { - // On Vista and higher we should be able to use IFileDialog for folder selection - IFileDialog *ifd; - HRESULT hr = dll::proc(ole32, "CoCreateInstance") - (CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ifd)); + // Folder selection uses a different method + if (in_type == type::folder) { + if (flags(flag::is_vista)) { + // On Vista and higher we should be able to use IFileDialog for folder selection + IFileDialog* ifd; + HRESULT hr = dll::proc(ole32, "CoCreateInstance")(CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&ifd)); - // In case CoCreateInstance fails (which it should not), try legacy approach - if (SUCCEEDED(hr)) - return select_folder_vista(ifd, options & opt::force_path); + // In case CoCreateInstance fails (which it should not), try legacy approach + if (SUCCEEDED(hr)) + return select_folder_vista(ifd, options & opt::force_path); + } + + BROWSEINFOW bi; + memset(&bi, 0, sizeof(bi)); + + bi.lpfn = &bffcallback; + bi.lParam = (LPARAM)this; + + if (flags(flag::is_vista)) { + if (ole32.is_initialized()) + bi.ulFlags |= BIF_NEWDIALOGSTYLE; + bi.ulFlags |= BIF_EDITBOX; + bi.ulFlags |= BIF_STATUSTEXT; + } + + auto* list = SHBrowseForFolderW(&bi); + std::string ret; + if (list) { + auto buffer = new wchar_t[MAX_PATH]; + SHGetPathFromIDListW(list, buffer); + dll::proc(ole32, "CoTaskMemFree")(list); + ret = internal::wstr2str(buffer); + delete[] buffer; + } + return ret; } - BROWSEINFOW bi; - memset(&bi, 0, sizeof(bi)); + OPENFILENAMEW ofn; + memset(&ofn, 0, sizeof(ofn)); + ofn.lStructSize = sizeof(OPENFILENAMEW); + ofn.hwndOwner = GetActiveWindow(); - bi.lpfn = &bffcallback; - bi.lParam = (LPARAM)this; + ofn.lpstrFilter = wfilter_list.c_str(); - if (flags(flag::is_vista)) - { - if (ole32.is_initialized()) - bi.ulFlags |= BIF_NEWDIALOGSTYLE; - bi.ulFlags |= BIF_EDITBOX; - bi.ulFlags |= BIF_STATUSTEXT; + auto woutput = std::wstring(MAX_PATH * 256, L'\0'); + ofn.lpstrFile = (LPWSTR)woutput.data(); + ofn.nMaxFile = (DWORD)woutput.size(); + if (!m_wdefault_path.empty()) { + // If a directory was provided, use it as the initial directory. If + // a valid path was provided, use it as the initial file. Otherwise, + // let the Windows API decide. + auto path_attr = GetFileAttributesW(m_wdefault_path.c_str()); + if (path_attr != INVALID_FILE_ATTRIBUTES && (path_attr & FILE_ATTRIBUTE_DIRECTORY)) + ofn.lpstrInitialDir = m_wdefault_path.c_str(); + else if (m_wdefault_path.size() <= woutput.size()) + //second argument is size of buffer, not length of string + StringCchCopyW(ofn.lpstrFile, MAX_PATH * 256 + 1, m_wdefault_path.c_str()); + else { + ofn.lpstrFileTitle = (LPWSTR)m_wdefault_path.data(); + ofn.nMaxFileTitle = (DWORD)m_wdefault_path.size(); + } + } + ofn.lpstrTitle = m_wtitle.c_str(); + ofn.Flags = OFN_NOCHANGEDIR | OFN_EXPLORER; + + dll comdlg32("comdlg32.dll"); + + // Apply new visual style (required for windows XP) + new_style_context ctx; + + if (in_type == type::save) { + if (!(options & opt::force_overwrite)) + ofn.Flags |= OFN_OVERWRITEPROMPT; + + dll::proc get_save_file_name(comdlg32, "GetSaveFileNameW"); + if (get_save_file_name(&ofn) == 0) + return ""; + return internal::wstr2str(woutput.c_str()); + } + else { + if (options & opt::multiselect) + ofn.Flags |= OFN_ALLOWMULTISELECT; + ofn.Flags |= OFN_PATHMUSTEXIST; + + dll::proc get_open_file_name(comdlg32, "GetOpenFileNameW"); + if (get_open_file_name(&ofn) == 0) + return ""; } - auto *list = SHBrowseForFolderW(&bi); - std::string ret; - if (list) - { - auto buffer = new wchar_t[MAX_PATH]; - SHGetPathFromIDListW(list, buffer); - dll::proc(ole32, "CoTaskMemFree")(list); - ret = internal::wstr2str(buffer); - delete[] buffer; - } - return ret; - } + std::string prefix; + for (wchar_t const* p = woutput.c_str(); *p;) { + auto filename = internal::wstr2str(p); + p += wcslen(p); + // In multiselect mode, we advance p one wchar further and + // check for another filename. If there is one and the + // prefix is empty, it means we just read the prefix. + if ((options & opt::multiselect) && *++p && prefix.empty()) { + prefix = filename + "/"; + continue; + } - OPENFILENAMEW ofn; - memset(&ofn, 0, sizeof(ofn)); - ofn.lStructSize = sizeof(OPENFILENAMEW); - ofn.hwndOwner = GetActiveWindow(); - - ofn.lpstrFilter = wfilter_list.c_str(); - - auto woutput = std::wstring(MAX_PATH * 256, L'\0'); - ofn.lpstrFile = (LPWSTR)woutput.data(); - ofn.nMaxFile = (DWORD)woutput.size(); - if (!m_wdefault_path.empty()) - { - // If a directory was provided, use it as the initial directory. If - // a valid path was provided, use it as the initial file. Otherwise, - // let the Windows API decide. - auto path_attr = GetFileAttributesW(m_wdefault_path.c_str()); - if (path_attr != INVALID_FILE_ATTRIBUTES && (path_attr & FILE_ATTRIBUTE_DIRECTORY)) - ofn.lpstrInitialDir = m_wdefault_path.c_str(); - else if (m_wdefault_path.size() <= woutput.size()) - //second argument is size of buffer, not length of string - StringCchCopyW(ofn.lpstrFile, MAX_PATH*256+1, m_wdefault_path.c_str()); - else - { - ofn.lpstrFileTitle = (LPWSTR)m_wdefault_path.data(); - ofn.nMaxFileTitle = (DWORD)m_wdefault_path.size(); - } - } - ofn.lpstrTitle = m_wtitle.c_str(); - ofn.Flags = OFN_NOCHANGEDIR | OFN_EXPLORER; - - dll comdlg32("comdlg32.dll"); - - // Apply new visual style (required for windows XP) - new_style_context ctx; - - if (in_type == type::save) - { - if (!(options & opt::force_overwrite)) - ofn.Flags |= OFN_OVERWRITEPROMPT; - - dll::proc get_save_file_name(comdlg32, "GetSaveFileNameW"); - if (get_save_file_name(&ofn) == 0) - return ""; - return internal::wstr2str(woutput.c_str()); - } - else - { - if (options & opt::multiselect) - ofn.Flags |= OFN_ALLOWMULTISELECT; - ofn.Flags |= OFN_PATHMUSTEXIST; - - dll::proc get_open_file_name(comdlg32, "GetOpenFileNameW"); - if (get_open_file_name(&ofn) == 0) - return ""; - } - - std::string prefix; - for (wchar_t const *p = woutput.c_str(); *p; ) - { - auto filename = internal::wstr2str(p); - p += wcslen(p); - // In multiselect mode, we advance p one wchar further and - // check for another filename. If there is one and the - // prefix is empty, it means we just read the prefix. - if ((options & opt::multiselect) && *++p && prefix.empty()) - { - prefix = filename + "/"; - continue; + m_vector_result.push_back(prefix + filename); } - m_vector_result.push_back(prefix + filename); - } - - return ""; - }); + return ""; + }); #else - auto command = desktop_helper(); + auto command = desktop_helper(); - if (is_osascript()) - { - std::string script = "set ret to choose"; - switch (in_type) - { + if (is_osascript()) { + std::string script = "set ret to choose"; + switch (in_type) { case type::save: script += " file name"; break; - case type::open: default: + case type::open: + default: script += " file"; if (options & opt::multiselect) script += " with multiple selections allowed"; @@ -1093,402 +1014,411 @@ inline internal::file_dialog::file_dialog(type in_type, case type::folder: script += " folder"; break; - } - - if (default_path.size()) - script += " default location " + osascript_quote(default_path); - script += " with prompt " + osascript_quote(title); - - if (in_type == type::open) - { - // Concatenate all user-provided filter patterns - std::string patterns; - for (size_t i = 0; i < filters.size() / 2; ++i) - patterns += " " + filters[2 * i + 1]; - - // Split the pattern list to check whether "*" is in there; if it - // is, we have to disable filters because there is no mechanism in - // OS X for the user to override the filter. - std::regex sep("\\s+"); - std::string filter_list; - bool has_filter = true; - std::sregex_token_iterator iter(patterns.begin(), patterns.end(), sep, -1); - std::sregex_token_iterator end; - for ( ; iter != end; ++iter) - { - auto pat = iter->str(); - if (pat == "*" || pat == "*.*") - has_filter = false; - else if (internal::starts_with(pat, "*.")) - filter_list += (filter_list.size() == 0 ? "" : ",") + - osascript_quote(pat.substr(2, pat.size() - 2)); } - if (has_filter && filter_list.size() > 0) - script += " of type {" + filter_list + "}"; + + if (default_path.size()) + script += " default location " + osascript_quote(default_path); + script += " with prompt " + osascript_quote(title); + + if (in_type == type::open) { + // Concatenate all user-provided filter patterns + std::string patterns; + for (size_t i = 0; i < filters.size() / 2; ++i) + patterns += " " + filters[2 * i + 1]; + + // Split the pattern list to check whether "*" is in there; if it + // is, we have to disable filters because there is no mechanism in + // OS X for the user to override the filter. + std::regex sep("\\s+"); + std::string filter_list; + bool has_filter = true; + std::sregex_token_iterator iter(patterns.begin(), patterns.end(), sep, -1); + std::sregex_token_iterator end; + for (; iter != end; ++iter) { + auto pat = iter->str(); + if (pat == "*" || pat == "*.*") + has_filter = false; + else if (internal::starts_with(pat, "*.")) + filter_list += (filter_list.size() == 0 ? "" : ",") + + osascript_quote(pat.substr(2, pat.size() - 2)); + } + if (has_filter && filter_list.size() > 0) + script += " of type {" + filter_list + "}"; + } + + if (in_type == type::open && (options & opt::multiselect)) { + script += "\nset s to \"\""; + script += "\nrepeat with i in ret"; + script += "\n set s to s & (POSIX path of i) & \"\\n\""; + script += "\nend repeat"; + script += "\ncopy s to stdout"; + } + else { + script += "\nPOSIX path of ret"; + } + + command.push_back("-e"); + command.push_back(script); + } + else if (is_zenity()) { + command.push_back("--file-selection"); + command.push_back("--filename=" + default_path); + command.push_back("--title"); + command.push_back(title); + command.push_back("--separator=\n"); + + for (size_t i = 0; i < filters.size() / 2; ++i) { + command.push_back("--file-filter"); + command.push_back(filters[2 * i] + "|" + filters[2 * i + 1]); + } + + if (in_type == type::save) + command.push_back("--save"); + if (in_type == type::folder) + command.push_back("--directory"); + if (!(options & opt::force_overwrite)) + command.push_back("--confirm-overwrite"); + if (options & opt::multiselect) + command.push_back("--multiple"); + } + else if (is_kdialog()) { + switch (in_type) { + case type::save: + command.push_back("--getsavefilename"); + break; + case type::open: + command.push_back("--getopenfilename"); + break; + case type::folder: + command.push_back("--getexistingdirectory"); + break; + } + if (options & opt::multiselect) + command.push_back(" --multiple"); + + command.push_back(default_path); + + std::string filter; + for (size_t i = 0; i < filters.size() / 2; ++i) + filter += (i == 0 ? "" : " | ") + filters[2 * i] + "(" + filters[2 * i + 1] + ")"; + command.push_back(filter); + + command.push_back("--title"); + command.push_back(title); } - if (in_type == type::open && (options & opt::multiselect)) - { - script += "\nset s to \"\""; - script += "\nrepeat with i in ret"; - script += "\n set s to s & (POSIX path of i) & \"\\n\""; - script += "\nend repeat"; - script += "\ncopy s to stdout"; - } - else - { - script += "\nPOSIX path of ret"; - } + if (flags(flag::is_verbose)) + std::cerr << "pfd: " << command << std::endl; - command.push_back("-e"); - command.push_back(script); - } - else if (is_zenity()) - { - command.push_back("--file-selection"); - command.push_back("--filename=" + default_path); - command.push_back("--title"); - command.push_back(title); - command.push_back("--separator=\n"); - - for (size_t i = 0; i < filters.size() / 2; ++i) - { - command.push_back("--file-filter"); - command.push_back(filters[2 * i] + "|" + filters[2 * i + 1]); - } - - if (in_type == type::save) - command.push_back("--save"); - if (in_type == type::folder) - command.push_back("--directory"); - if (!(options & opt::force_overwrite)) - command.push_back("--confirm-overwrite"); - if (options & opt::multiselect) - command.push_back("--multiple"); - } - else if (is_kdialog()) - { - switch (in_type) - { - case type::save: command.push_back("--getsavefilename"); break; - case type::open: command.push_back("--getopenfilename"); break; - case type::folder: command.push_back("--getexistingdirectory"); break; - } - if (options & opt::multiselect) - command.push_back(" --multiple"); - - command.push_back(default_path); - - std::string filter; - for (size_t i = 0; i < filters.size() / 2; ++i) - filter += (i == 0 ? "" : " | ") + filters[2 * i] + "(" + filters[2 * i + 1] + ")"; - command.push_back(filter); - - command.push_back("--title"); - command.push_back(title); - } - - if (flags(flag::is_verbose)) - std::cerr << "pfd: " << command << std::endl; - - m_async->start_process(command); + m_async->start_process(command); #endif -} + } -inline std::string internal::file_dialog::string_result() -{ + inline std::string internal::file_dialog::string_result() { #if _WIN32 - return m_async->result(); + return m_async->result(); #else - auto ret = m_async->result(); - // Strip potential trailing newline (zenity). Also strip trailing slash - // added by osascript for consistency with other backends. - while (!ret.empty() && (ret.back() == '\n' || ret.back() == '/')) - ret.pop_back(); - return ret; + auto ret = m_async->result(); + // Strip potential trailing newline (zenity). Also strip trailing slash + // added by osascript for consistency with other backends. + while (!ret.empty() && (ret.back() == '\n' || ret.back() == '/')) + ret.pop_back(); + return ret; #endif -} - -inline std::vector internal::file_dialog::vector_result() -{ -#if _WIN32 - m_async->result(); - return m_vector_result; -#else - std::vector ret; - auto result = m_async->result(); - for (;;) - { - // Split result along newline characters - auto i = result.find('\n'); - if (i == 0 || i == std::string::npos) - break; - ret.push_back(result.substr(0, i)); - result = result.substr(i + 1, result.size()); } - return ret; + + inline std::vector internal::file_dialog::vector_result() { +#if _WIN32 + m_async->result(); + return m_vector_result; +#else + std::vector ret; + auto result = m_async->result(); + for (;;) { + // Split result along newline characters + auto i = result.find('\n'); + if (i == 0 || i == std::string::npos) + break; + ret.push_back(result.substr(0, i)); + result = result.substr(i + 1, result.size()); + } + return ret; #endif -} + } #if _WIN32 -// Use a static function to pass as BFFCALLBACK for legacy folder select -inline int CALLBACK internal::file_dialog::bffcallback(HWND hwnd, UINT uMsg, - LPARAM, LPARAM pData) -{ - auto inst = (file_dialog *)pData; - switch (uMsg) - { + // Use a static function to pass as BFFCALLBACK for legacy folder select + inline int CALLBACK internal::file_dialog::bffcallback(HWND hwnd, UINT uMsg, + LPARAM, LPARAM pData) { + auto inst = (file_dialog*)pData; + switch (uMsg) { case BFFM_INITIALIZED: SendMessage(hwnd, BFFM_SETSELECTIONW, TRUE, (LPARAM)inst->m_wdefault_path.c_str()); break; - } - return 0; -} - -inline std::string internal::file_dialog::select_folder_vista(IFileDialog *ifd, bool force_path) -{ - std::string result; - - IShellItem *folder; - - // Load library at runtime so app doesn't link it at load time (which will fail on windows XP) - dll shell32("shell32.dll"); - dll::proc - create_item(shell32, "SHCreateItemFromParsingName"); - - if (!create_item) - return ""; - - auto hr = create_item(m_wdefault_path.c_str(), - nullptr, - IID_PPV_ARGS(&folder)); - - // Set default folder if found. This only sets the default folder. If - // Windows has any info about the most recently selected folder, it - // will display it instead. Generally, calling SetFolder() to set the - // current directory “is not a good or expected user experience and - // should therefore be avoided”: - // https://docs.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfolder - if (SUCCEEDED(hr)) - { - if (force_path) - ifd->SetFolder(folder); - else - ifd->SetDefaultFolder(folder); - folder->Release(); + } + return 0; } - // Set the dialog title and option to select folders - ifd->SetOptions(FOS_PICKFOLDERS); - ifd->SetTitle(m_wtitle.c_str()); + inline std::string internal::file_dialog::select_folder_vista(IFileDialog* ifd, bool force_path) { + std::string result; - hr = ifd->Show(GetActiveWindow()); - if (SUCCEEDED(hr)) - { - IShellItem* item; - hr = ifd->GetResult(&item); - if (SUCCEEDED(hr)) - { - wchar_t* wselected = nullptr; - item->GetDisplayName(SIGDN_FILESYSPATH, &wselected); - item->Release(); + IShellItem* folder; - if (wselected) - { - result = internal::wstr2str(std::wstring(wselected)); - dll::proc(ole32_dll(), "CoTaskMemFree")(wselected); + // Load library at runtime so app doesn't link it at load time (which will fail on windows XP) + dll shell32("shell32.dll"); + dll::proc + create_item(shell32, "SHCreateItemFromParsingName"); + + if (!create_item) + return ""; + + auto hr = create_item(m_wdefault_path.c_str(), + nullptr, + IID_PPV_ARGS(&folder)); + + // Set default folder if found. This only sets the default folder. If + // Windows has any info about the most recently selected folder, it + // will display it instead. Generally, calling SetFolder() to set the + // current directory “is not a good or expected user experience and + // should therefore be avoided”: + // https://docs.microsoft.com/windows/win32/api/shobjidl_core/nf-shobjidl_core-ifiledialog-setfolder + if (SUCCEEDED(hr)) { + if (force_path) + ifd->SetFolder(folder); + else + ifd->SetDefaultFolder(folder); + folder->Release(); + } + + // Set the dialog title and option to select folders + ifd->SetOptions(FOS_PICKFOLDERS); + ifd->SetTitle(m_wtitle.c_str()); + + hr = ifd->Show(GetActiveWindow()); + if (SUCCEEDED(hr)) { + IShellItem* item; + hr = ifd->GetResult(&item); + if (SUCCEEDED(hr)) { + wchar_t* wselected = nullptr; + item->GetDisplayName(SIGDN_FILESYSPATH, &wselected); + item->Release(); + + if (wselected) { + result = internal::wstr2str(std::wstring(wselected)); + dll::proc(ole32_dll(), "CoTaskMemFree")(wselected); + } } } + + ifd->Release(); + + return result; } - - ifd->Release(); - - return result; -} #endif -// notify implementation + // notify implementation -inline notify::notify(std::string const &title, - std::string const &message, - icon _icon /* = icon::info */) -{ - if (_icon == icon::question) // Not supported by notifications - _icon = icon::info; + inline notify::notify(std::string const& title, + std::string const& message, + icon _icon /* = icon::info */) { + if (_icon == icon::question) // Not supported by notifications + _icon = icon::info; #if _WIN32 - // Use a static shared pointer for notify_icon so that we can delete - // it whenever we need to display a new one, and we can also wait - // until the program has finished running. - struct notify_icon_data : public NOTIFYICONDATAW - { - ~notify_icon_data() { Shell_NotifyIconW(NIM_DELETE, this); } - }; + // Use a static shared pointer for notify_icon so that we can delete + // it whenever we need to display a new one, and we can also wait + // until the program has finished running. + struct notify_icon_data : public NOTIFYICONDATAW { + ~notify_icon_data() { Shell_NotifyIconW(NIM_DELETE, this); } + }; - static std::shared_ptr nid; + static std::shared_ptr nid; - // Release the previous notification icon, if any, and allocate a new - // one. Note that std::make_shared() does value initialization, so there - // is no need to memset the structure. - nid = nullptr; - nid = std::make_shared(); + // Release the previous notification icon, if any, and allocate a new + // one. Note that std::make_shared() does value initialization, so there + // is no need to memset the structure. + nid = nullptr; + nid = std::make_shared(); - // For XP support - nid->cbSize = NOTIFYICONDATAW_V2_SIZE; - nid->hWnd = nullptr; - nid->uID = 0; + // For XP support + nid->cbSize = NOTIFYICONDATAW_V2_SIZE; + nid->hWnd = nullptr; + nid->uID = 0; - // Flag Description: - // - NIF_ICON The hIcon member is valid. - // - NIF_MESSAGE The uCallbackMessage member is valid. - // - NIF_TIP The szTip member is valid. - // - NIF_STATE The dwState and dwStateMask members are valid. - // - NIF_INFO Use a balloon ToolTip instead of a standard ToolTip. The szInfo, uTimeout, szInfoTitle, and dwInfoFlags members are valid. - // - NIF_GUID Reserved. - nid->uFlags = NIF_MESSAGE | NIF_ICON | NIF_INFO; + // Flag Description: + // - NIF_ICON The hIcon member is valid. + // - NIF_MESSAGE The uCallbackMessage member is valid. + // - NIF_TIP The szTip member is valid. + // - NIF_STATE The dwState and dwStateMask members are valid. + // - NIF_INFO Use a balloon ToolTip instead of a standard ToolTip. The szInfo, uTimeout, szInfoTitle, and dwInfoFlags members are valid. + // - NIF_GUID Reserved. + nid->uFlags = NIF_MESSAGE | NIF_ICON | NIF_INFO; - // Flag Description - // - NIIF_ERROR An error icon. - // - NIIF_INFO An information icon. - // - NIIF_NONE No icon. - // - NIIF_WARNING A warning icon. - // - NIIF_ICON_MASK Version 6.0. Reserved. - // - NIIF_NOSOUND Version 6.0. Do not play the associated sound. Applies only to balloon ToolTips - switch (_icon) - { - case icon::warning: nid->dwInfoFlags = NIIF_WARNING; break; - case icon::error: nid->dwInfoFlags = NIIF_ERROR; break; - /* case icon::info: */ default: nid->dwInfoFlags = NIIF_INFO; break; - } + // Flag Description + // - NIIF_ERROR An error icon. + // - NIIF_INFO An information icon. + // - NIIF_NONE No icon. + // - NIIF_WARNING A warning icon. + // - NIIF_ICON_MASK Version 6.0. Reserved. + // - NIIF_NOSOUND Version 6.0. Do not play the associated sound. Applies only to balloon ToolTips + switch (_icon) { + case icon::warning: + nid->dwInfoFlags = NIIF_WARNING; + break; + case icon::error: + nid->dwInfoFlags = NIIF_ERROR; + break; + /* case icon::info: */ default: + nid->dwInfoFlags = NIIF_INFO; + break; + } - ENUMRESNAMEPROC icon_enum_callback = [](HMODULE, LPCTSTR, LPTSTR lpName, LONG_PTR lParam) -> BOOL - { - ((NOTIFYICONDATAW *)lParam)->hIcon = ::LoadIcon(GetModuleHandle(nullptr), lpName); - return false; - }; + ENUMRESNAMEPROC icon_enum_callback = [](HMODULE, LPCTSTR, LPTSTR lpName, LONG_PTR lParam) -> BOOL { + ((NOTIFYICONDATAW*)lParam)->hIcon = ::LoadIcon(GetModuleHandle(nullptr), lpName); + return false; + }; - nid->hIcon = ::LoadIcon(nullptr, IDI_APPLICATION); - ::EnumResourceNames(nullptr, RT_GROUP_ICON, icon_enum_callback, (LONG_PTR)nid.get()); + nid->hIcon = ::LoadIcon(nullptr, IDI_APPLICATION); + ::EnumResourceNames(nullptr, RT_GROUP_ICON, icon_enum_callback, (LONG_PTR)nid.get()); - nid->uTimeout = 5000; + nid->uTimeout = 5000; - StringCchCopyW(nid->szInfoTitle, ARRAYSIZE(nid->szInfoTitle), internal::str2wstr(title).c_str()); - StringCchCopyW(nid->szInfo, ARRAYSIZE(nid->szInfo), internal::str2wstr(message).c_str()); + StringCchCopyW(nid->szInfoTitle, ARRAYSIZE(nid->szInfoTitle), internal::str2wstr(title).c_str()); + StringCchCopyW(nid->szInfo, ARRAYSIZE(nid->szInfo), internal::str2wstr(message).c_str()); - // Display the new icon - Shell_NotifyIconW(NIM_ADD, nid.get()); + // Display the new icon + Shell_NotifyIconW(NIM_ADD, nid.get()); #else - auto command = desktop_helper(); + auto command = desktop_helper(); - if (is_osascript()) - { - command.push_back("-e"); - command.push_back("display notification " + osascript_quote(message) + - " with title " + osascript_quote(title)); - } - else if (is_zenity()) - { - command.push_back("--notification"); - command.push_back("--window-icon"); - command.push_back(get_icon_name(_icon)); - command.push_back("--text"); - command.push_back(title + "\n" + message); - } - else if (is_kdialog()) - { - command.push_back("--icon"); - command.push_back(get_icon_name(_icon)); - command.push_back("--title"); - command.push_back(title); - command.push_back("--passivepopup"); - command.push_back(message); - command.push_back("5"); - } + if (is_osascript()) { + command.push_back("-e"); + command.push_back("display notification " + osascript_quote(message) + + " with title " + osascript_quote(title)); + } + else if (is_zenity()) { + command.push_back("--notification"); + command.push_back("--window-icon"); + command.push_back(get_icon_name(_icon)); + command.push_back("--text"); + command.push_back(title + "\n" + message); + } + else if (is_kdialog()) { + command.push_back("--icon"); + command.push_back(get_icon_name(_icon)); + command.push_back("--title"); + command.push_back(title); + command.push_back("--passivepopup"); + command.push_back(message); + command.push_back("5"); + } - if (flags(flag::is_verbose)) - std::cerr << "pfd: " << command << std::endl; + if (flags(flag::is_verbose)) + std::cerr << "pfd: " << command << std::endl; - m_async->start_process(command); + m_async->start_process(command); #endif -} + } -// message implementation + // message implementation -inline message::message(std::string const &title, - std::string const &text, - choice _choice /* = choice::ok_cancel */, - icon _icon /* = icon::info */) -{ + inline message::message(std::string const& title, + std::string const& text, + choice _choice /* = choice::ok_cancel */, + icon _icon /* = icon::info */) { #if _WIN32 - // Use MB_SYSTEMMODAL rather than MB_TOPMOST to ensure the message window is brought - // to front. See https://github.com/samhocevar/portable-file-dialogs/issues/52 - UINT style = MB_SYSTEMMODAL; - switch (_icon) - { - case icon::warning: style |= MB_ICONWARNING; break; - case icon::error: style |= MB_ICONERROR; break; - case icon::question: style |= MB_ICONQUESTION; break; - /* case icon::info: */ default: style |= MB_ICONINFORMATION; break; - } + // Use MB_SYSTEMMODAL rather than MB_TOPMOST to ensure the message window is brought + // to front. See https://github.com/samhocevar/portable-file-dialogs/issues/52 + UINT style = MB_SYSTEMMODAL; + switch (_icon) { + case icon::warning: + style |= MB_ICONWARNING; + break; + case icon::error: + style |= MB_ICONERROR; + break; + case icon::question: + style |= MB_ICONQUESTION; + break; + /* case icon::info: */ default: + style |= MB_ICONINFORMATION; + break; + } - switch (_choice) - { - case choice::ok_cancel: style |= MB_OKCANCEL; break; - case choice::yes_no: style |= MB_YESNO; break; - case choice::yes_no_cancel: style |= MB_YESNOCANCEL; break; - case choice::retry_cancel: style |= MB_RETRYCANCEL; break; - case choice::abort_retry_ignore: style |= MB_ABORTRETRYIGNORE; break; - /* case choice::ok: */ default: style |= MB_OK; break; - } + switch (_choice) { + case choice::ok_cancel: + style |= MB_OKCANCEL; + break; + case choice::yes_no: + style |= MB_YESNO; + break; + case choice::yes_no_cancel: + style |= MB_YESNOCANCEL; + break; + case choice::retry_cancel: + style |= MB_RETRYCANCEL; + break; + case choice::abort_retry_ignore: + style |= MB_ABORTRETRYIGNORE; + break; + /* case choice::ok: */ default: + style |= MB_OK; + break; + } - m_mappings[IDCANCEL] = button::cancel; - m_mappings[IDOK] = button::ok; - m_mappings[IDYES] = button::yes; - m_mappings[IDNO] = button::no; - m_mappings[IDABORT] = button::abort; - m_mappings[IDRETRY] = button::retry; - m_mappings[IDIGNORE] = button::ignore; + m_mappings[IDCANCEL] = button::cancel; + m_mappings[IDOK] = button::ok; + m_mappings[IDYES] = button::yes; + m_mappings[IDNO] = button::no; + m_mappings[IDABORT] = button::abort; + m_mappings[IDRETRY] = button::retry; + m_mappings[IDIGNORE] = button::ignore; - m_async->start_func([text, title, style](int* exit_code) -> std::string - { - auto wtext = internal::str2wstr(text); - auto wtitle = internal::str2wstr(title); - // Apply new visual style (required for all Windows versions) - new_style_context ctx; - *exit_code = MessageBoxW(GetActiveWindow(), wtext.c_str(), wtitle.c_str(), style); - return ""; - }); + m_async->start_func([text, title, style](int* exit_code) -> std::string { + auto wtext = internal::str2wstr(text); + auto wtitle = internal::str2wstr(title); + // Apply new visual style (required for all Windows versions) + new_style_context ctx; + *exit_code = MessageBoxW(GetActiveWindow(), wtext.c_str(), wtitle.c_str(), style); + return ""; + }); #elif __EMSCRIPTEN__ - std::string full_message; - switch (_icon) - { - case icon::warning: full_message = "⚠️"; break; - case icon::error: full_message = "⛔"; break; - case icon::question: full_message = "❓"; break; - /* case icon::info: */ default: full_message = "ℹ"; break; - } + std::string full_message; + switch (_icon) { + case icon::warning: + full_message = "⚠️"; + break; + case icon::error: + full_message = "⛔"; + break; + case icon::question: + full_message = "❓"; + break; + /* case icon::info: */ default: + full_message = "ℹ"; + break; + } - full_message += ' ' + title + "\n\n" + text; + full_message += ' ' + title + "\n\n" + text; - // This does not really start an async task; it just passes the - // EM_ASM_INT return value to a fake start() function. - m_async->start(EM_ASM_INT( - { - if ($1) - return window.confirm(UTF8ToString($0)) ? 0 : -1; - alert(UTF8ToString($0)); - return 0; - }, full_message.c_str(), _choice == choice::ok_cancel)); + // This does not really start an async task; it just passes the + // EM_ASM_INT return value to a fake start() function. + m_async->start(EM_ASM_INT( + { + if ($1) + return window.confirm(UTF8ToString($0)) ? 0 : -1; + alert(UTF8ToString($0)); + return 0; + }, + full_message.c_str(), _choice == choice::ok_cancel)); #else - auto command = desktop_helper(); + auto command = desktop_helper(); - if (is_osascript()) - { - std::string script = "display dialog " + osascript_quote(text) + - " with title " + osascript_quote(title); - switch (_choice) - { + if (is_osascript()) { + std::string script = "display dialog " + osascript_quote(text) + + " with title " + osascript_quote(title); + switch (_choice) { case choice::ok_cancel: script += "buttons {\"OK\", \"Cancel\"}" " default button \"OK\"" @@ -1519,191 +1449,199 @@ inline message::message(std::string const &title, " cancel button \"Retry\""; m_mappings[256] = button::cancel; break; - case choice::ok: default: + case choice::ok: + default: script += "buttons {\"OK\"}" " default button \"OK\"" " cancel button \"OK\""; m_mappings[256] = button::ok; break; - } - script += " with icon "; - switch (_icon) - { - #define PFD_OSX_ICON(n) "alias ((path to library folder from system domain) as text " \ - "& \"CoreServices:CoreTypes.bundle:Contents:Resources:" n ".icns\")" - case icon::info: default: script += PFD_OSX_ICON("ToolBarInfo"); break; - case icon::warning: script += "caution"; break; - case icon::error: script += "stop"; break; - case icon::question: script += PFD_OSX_ICON("GenericQuestionMarkIcon"); break; - #undef PFD_OSX_ICON - } + } + script += " with icon "; + switch (_icon) { +#define PFD_OSX_ICON(n) "alias ((path to library folder from system domain) as text " \ + "& \"CoreServices:CoreTypes.bundle:Contents:Resources:" n ".icns\")" + case icon::info: + default: + script += PFD_OSX_ICON("ToolBarInfo"); + break; + case icon::warning: + script += "caution"; + break; + case icon::error: + script += "stop"; + break; + case icon::question: + script += PFD_OSX_ICON("GenericQuestionMarkIcon"); + break; +#undef PFD_OSX_ICON + } - command.push_back("-e"); - command.push_back(script); - } - else if (is_zenity()) - { - switch (_choice) - { + command.push_back("-e"); + command.push_back(script); + } + else if (is_zenity()) { + switch (_choice) { case choice::ok_cancel: - command.insert(command.end(), { "--question", "--cancel-label=Cancel", "--ok-label=OK" }); break; + command.insert(command.end(), { "--question", "--cancel-label=Cancel", "--ok-label=OK" }); + break; case choice::yes_no: // Do not use standard --question because it causes “No” to return -1, // which is inconsistent with the “Yes/No/Cancel” mode below. - command.insert(command.end(), { "--question", "--switch", "--extra-button=No", "--extra-button=Yes" }); break; + command.insert(command.end(), { "--question", "--switch", "--extra-button=No", "--extra-button=Yes" }); + break; case choice::yes_no_cancel: - command.insert(command.end(), { "--question", "--switch", "--extra-button=Cancel", "--extra-button=No", "--extra-button=Yes" }); break; + command.insert(command.end(), { "--question", "--switch", "--extra-button=Cancel", "--extra-button=No", "--extra-button=Yes" }); + break; case choice::retry_cancel: - command.insert(command.end(), { "--question", "--switch", "--extra-button=Cancel", "--extra-button=Retry" }); break; + command.insert(command.end(), { "--question", "--switch", "--extra-button=Cancel", "--extra-button=Retry" }); + break; case choice::abort_retry_ignore: - command.insert(command.end(), { "--question", "--switch", "--extra-button=Ignore", "--extra-button=Abort", "--extra-button=Retry" }); break; + command.insert(command.end(), { "--question", "--switch", "--extra-button=Ignore", "--extra-button=Abort", "--extra-button=Retry" }); + break; case choice::ok: default: - switch (_icon) - { - case icon::error: command.push_back("--error"); break; - case icon::warning: command.push_back("--warning"); break; - default: command.push_back("--info"); break; + switch (_icon) { + case icon::error: + command.push_back("--error"); + break; + case icon::warning: + command.push_back("--warning"); + break; + default: + command.push_back("--info"); + break; } - } - - command.insert(command.end(), { "--title", title, - "--width=300", "--height=0", // sensible defaults - "--text", text, - "--icon-name=dialog-" + get_icon_name(_icon) }); - } - else if (is_kdialog()) - { - if (_choice == choice::ok) - { - switch (_icon) - { - case icon::error: command.push_back("--error"); break; - case icon::warning: command.push_back("--sorry"); break; - default: command.push_back("--msgbox"); break; } + + command.insert(command.end(), { "--title", title, + "--width=300", "--height=0", // sensible defaults + "--text", text, + "--icon-name=dialog-" + get_icon_name(_icon) }); } - else - { - std::string flag = "--"; - if (_icon == icon::warning || _icon == icon::error) - flag += "warning"; - flag += "yesno"; - if (_choice == choice::yes_no_cancel) - flag += "cancel"; - command.push_back(flag); - if (_choice == choice::yes_no || _choice == choice::yes_no_cancel) - { - m_mappings[0] = button::yes; - m_mappings[256] = button::no; + else if (is_kdialog()) { + if (_choice == choice::ok) { + switch (_icon) { + case icon::error: + command.push_back("--error"); + break; + case icon::warning: + command.push_back("--sorry"); + break; + default: + command.push_back("--msgbox"); + break; + } } + else { + std::string flag = "--"; + if (_icon == icon::warning || _icon == icon::error) + flag += "warning"; + flag += "yesno"; + if (_choice == choice::yes_no_cancel) + flag += "cancel"; + command.push_back(flag); + if (_choice == choice::yes_no || _choice == choice::yes_no_cancel) { + m_mappings[0] = button::yes; + m_mappings[256] = button::no; + } + } + + command.push_back(text); + command.push_back("--title"); + command.push_back(title); + + // Must be after the above part + if (_choice == choice::ok_cancel) + command.insert(command.end(), { "--yes-label", "OK", "--no-label", "Cancel" }); } - command.push_back(text); - command.push_back("--title"); - command.push_back(title); + if (flags(flag::is_verbose)) + std::cerr << "pfd: " << command << std::endl; - // Must be after the above part - if (_choice == choice::ok_cancel) - command.insert(command.end(), { "--yes-label", "OK", "--no-label", "Cancel" }); - } - - if (flags(flag::is_verbose)) - std::cerr << "pfd: " << command << std::endl; - - m_async->start_process(command); + m_async->start_process(command); #endif -} + } -inline button message::result() -{ - int exit_code; - auto ret = m_async->result(&exit_code); - // osascript will say "button returned:Cancel\n" - // and others will just say "Cancel\n" - if (exit_code < 0 || // this means cancel - internal::ends_with(ret, "Cancel\n")) - return button::cancel; - if (internal::ends_with(ret, "OK\n")) - return button::ok; - if (internal::ends_with(ret, "Yes\n")) - return button::yes; - if (internal::ends_with(ret, "No\n")) - return button::no; - if (internal::ends_with(ret, "Abort\n")) - return button::abort; - if (internal::ends_with(ret, "Retry\n")) - return button::retry; - if (internal::ends_with(ret, "Ignore\n")) - return button::ignore; - if (m_mappings.count(exit_code) != 0) - return m_mappings[exit_code]; - return exit_code == 0 ? button::ok : button::cancel; -} + inline button message::result() { + int exit_code; + auto ret = m_async->result(&exit_code); + // osascript will say "button returned:Cancel\n" + // and others will just say "Cancel\n" + if (exit_code < 0 || // this means cancel + internal::ends_with(ret, "Cancel\n")) + return button::cancel; + if (internal::ends_with(ret, "OK\n")) + return button::ok; + if (internal::ends_with(ret, "Yes\n")) + return button::yes; + if (internal::ends_with(ret, "No\n")) + return button::no; + if (internal::ends_with(ret, "Abort\n")) + return button::abort; + if (internal::ends_with(ret, "Retry\n")) + return button::retry; + if (internal::ends_with(ret, "Ignore\n")) + return button::ignore; + if (m_mappings.count(exit_code) != 0) + return m_mappings[exit_code]; + return exit_code == 0 ? button::ok : button::cancel; + } -// open_file implementation + // open_file implementation -inline open_file::open_file(std::string const &title, - std::string const &default_path /* = "" */, - std::vector const &filters /* = { "All Files", "*" } */, - opt options /* = opt::none */) - : file_dialog(type::open, title, default_path, filters, options) -{ -} + inline open_file::open_file(std::string const& title, + std::string const& default_path /* = "" */, + std::vector const& filters /* = { "All Files", "*" } */, + opt options /* = opt::none */) + : file_dialog(type::open, title, default_path, filters, options) { + } -inline open_file::open_file(std::string const &title, - std::string const &default_path, - std::vector const &filters, - bool allow_multiselect) - : open_file(title, default_path, filters, - (allow_multiselect ? opt::multiselect : opt::none)) -{ -} + inline open_file::open_file(std::string const& title, + std::string const& default_path, + std::vector const& filters, + bool allow_multiselect) + : open_file(title, default_path, filters, + (allow_multiselect ? opt::multiselect : opt::none)) { + } -inline std::vector open_file::result() -{ - return vector_result(); -} + inline std::vector open_file::result() { + return vector_result(); + } -// save_file implementation + // save_file implementation -inline save_file::save_file(std::string const &title, - std::string const &default_path /* = "" */, - std::vector const &filters /* = { "All Files", "*" } */, - opt options /* = opt::none */) - : file_dialog(type::save, title, default_path, filters, options) -{ -} + inline save_file::save_file(std::string const& title, + std::string const& default_path /* = "" */, + std::vector const& filters /* = { "All Files", "*" } */, + opt options /* = opt::none */) + : file_dialog(type::save, title, default_path, filters, options) { + } -inline save_file::save_file(std::string const &title, - std::string const &default_path, - std::vector const &filters, - bool confirm_overwrite) - : save_file(title, default_path, filters, - (confirm_overwrite ? opt::none : opt::force_overwrite)) -{ -} + inline save_file::save_file(std::string const& title, + std::string const& default_path, + std::vector const& filters, + bool confirm_overwrite) + : save_file(title, default_path, filters, + (confirm_overwrite ? opt::none : opt::force_overwrite)) { + } -inline std::string save_file::result() -{ - return string_result(); -} + inline std::string save_file::result() { + return string_result(); + } -// select_folder implementation + // select_folder implementation -inline select_folder::select_folder(std::string const &title, - std::string const &default_path /* = "" */, - opt options /* = opt::none */) - : file_dialog(type::folder, title, default_path, {}, options) -{ -} + inline select_folder::select_folder(std::string const& title, + std::string const& default_path /* = "" */, + opt options /* = opt::none */) + : file_dialog(type::folder, title, default_path, {}, options) { + } -inline std::string select_folder::result() -{ - return string_result(); -} + inline std::string select_folder::result() { + return string_result(); + } #endif // PFD_SKIP_IMPLEMENTATION } // namespace pfd - diff --git a/core/src/gui/icons.cpp b/core/src/gui/icons.cpp index b57cdedd..77c2fa74 100644 --- a/core/src/gui/icons.cpp +++ b/core/src/gui/icons.cpp @@ -20,7 +20,7 @@ namespace icons { ImTextureID CENTER_TUNING; GLuint loadTexture(std::string path) { - int w,h,n; + int w, h, n; stbi_uc* data = stbi_load(path.c_str(), &w, &h, &n, 0); GLuint texId; glGenTextures(1, &texId); diff --git a/core/src/gui/main_window.cpp b/core/src/gui/main_window.cpp index d4d76acb..976d381a 100644 --- a/core/src/gui/main_window.cpp +++ b/core/src/gui/main_window.cpp @@ -49,10 +49,22 @@ void MainWindow::init() { // Load menu elements gui::menu.order.clear(); for (auto& elem : menuElements) { - if (!elem.contains("name")) { spdlog::error("Menu element is missing name key"); continue; } - if (!elem["name"].is_string()) { spdlog::error("Menu element name isn't a string"); continue; } - if (!elem.contains("open")) { spdlog::error("Menu element is missing open key"); continue; } - if (!elem["open"].is_boolean()) { spdlog::error("Menu element name isn't a string"); continue; } + if (!elem.contains("name")) { + spdlog::error("Menu element is missing name key"); + continue; + } + if (!elem["name"].is_string()) { + spdlog::error("Menu element name isn't a string"); + continue; + } + if (!elem.contains("open")) { + spdlog::error("Menu element is missing open key"); + continue; + } + if (!elem["open"].is_boolean()) { + spdlog::error("Menu element name isn't a string"); + continue; + } Menu::MenuOption_t opt; opt.name = elem["name"]; opt.open = elem["open"]; @@ -66,15 +78,15 @@ void MainWindow::init() { gui::menu.registerEntry("Theme", thememenu::draw, NULL); gui::menu.registerEntry("VFO Color", vfo_color_menu::draw, NULL); gui::menu.registerEntry("Module Manager", module_manager_menu::draw, NULL); - + gui::freqSelect.init(); // Set default values for waterfall in case no source init's it gui::waterfall.setBandwidth(8000000); gui::waterfall.setViewBandwidth(8000000); - - fft_in = (fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex) * fftSize); - fft_out = (fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex) * fftSize); + + fft_in = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * fftSize); + fft_out = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * fftSize); fftwPlan = fftwf_plan_dft_1d(fftSize, fft_in, fft_out, FFTW_FORWARD, FFTW_ESTIMATE); sigpath::signalPath.init(8000000, 20, fftSize, &dummyStream, (dsp::complex_t*)fft_in, fftHandler, this); @@ -88,7 +100,7 @@ void MainWindow::init() { // Load modules from /module directory if (std::filesystem::is_directory(modulesDir)) { - for (const auto & file : std::filesystem::directory_iterator(modulesDir)) { + for (const auto& file : std::filesystem::directory_iterator(modulesDir)) { std::string path = file.path().generic_string(); if (file.path().extension().generic_string() != SDRPP_MOD_EXTENTSION) { continue; @@ -130,7 +142,7 @@ void MainWindow::init() { LoadingScreen::show("Loading color maps"); spdlog::info("Loading color maps"); if (std::filesystem::is_directory(resourcesDir + "/colormaps")) { - for (const auto & file : std::filesystem::directory_iterator(resourcesDir + "/colormaps")) { + for (const auto& file : std::filesystem::directory_iterator(resourcesDir + "/colormaps")) { std::string path = file.path().generic_string(); LoadingScreen::show("Loading " + path); spdlog::info("Loading {0}", path); @@ -196,11 +208,11 @@ void MainWindow::init() { float finalBwHalf = gui::waterfall.getBandwidth() / 2.0; for (auto& [_name, _vfo] : gui::waterfall.vfos) { if (_vfo->lowerOffset < -finalBwHalf) { - sigpath::vfoManager.setCenterOffset(_name, (_vfo->bandwidth/2)-finalBwHalf); + sigpath::vfoManager.setCenterOffset(_name, (_vfo->bandwidth / 2) - finalBwHalf); continue; } if (_vfo->upperOffset > finalBwHalf) { - sigpath::vfoManager.setCenterOffset(_name, finalBwHalf-(_vfo->bandwidth/2)); + sigpath::vfoManager.setCenterOffset(_name, finalBwHalf - (_vfo->bandwidth / 2)); continue; } } @@ -224,8 +236,8 @@ void MainWindow::fftHandler(dsp::complex_t* samples, int count, void* ctx) { // Zero out the rest of the samples if (count < _this->fftSize) { - memset(&_this->fft_in[count], 0, (_this->fftSize-count) * sizeof(dsp::complex_t)); - } + memset(&_this->fft_in[count], 0, (_this->fftSize - count) * sizeof(dsp::complex_t)); + } // Execute FFT fftwf_execute(_this->fftwPlan); @@ -258,14 +270,12 @@ void MainWindow::vfoAddedHandler(VFOManager::VFO* vfo, void* ctx) { double viewBW = gui::waterfall.getViewBandwidth(); double viewOffset = gui::waterfall.getViewOffset(); - double viewLower = viewOffset - (viewBW/2.0); - double viewUpper = viewOffset + (viewBW/2.0); + double viewLower = viewOffset - (viewBW / 2.0); + double viewUpper = viewOffset + (viewBW / 2.0); double newOffset = std::clamp(offset, viewLower, viewUpper); sigpath::vfoManager.setCenterOffset(name, _this->initComplete ? newOffset : offset); - - } void MainWindow::draw() { @@ -289,7 +299,7 @@ void MainWindow::draw() { core::configManager.release(true); } } - + sigpath::vfoManager.updateFromWaterfall(&gui::waterfall); // Handle selection of another VFO @@ -415,7 +425,7 @@ void MainWindow::draw() { int snrWidth = std::min(300, ImGui::GetWindowSize().x - ImGui::GetCursorPosX() - 87); - ImGui::SetCursorPosX(ImGui::GetWindowSize().x - (snrWidth+87)); + ImGui::SetCursorPosX(ImGui::GetWindowSize().x - (snrWidth + 87)); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5); ImGui::SetNextItemWidth(snrWidth); ImGui::SNRMeter((vfo != NULL) ? gui::waterfall.selectedVFOSNR : 0); @@ -456,7 +466,7 @@ void MainWindow::draw() { else { ImGui::SetMouseCursor(ImGuiMouseCursor_Arrow); } - if(!down && grabbingMenu) { + if (!down && grabbingMenu) { grabbingMenu = false; menuWidth = newWidth; core::configManager.acquire(); @@ -494,13 +504,13 @@ void MainWindow::draw() { core::configManager.release(true); } if (startedWithMenuClosed) { - startedWithMenuClosed = false; + startedWithMenuClosed = false; } else { firstMenuRender = false; } - if(ImGui::CollapsingHeader("Debug")) { + if (ImGui::CollapsingHeader("Debug")) { ImGui::Text("Frame time: %.3f ms/frame", 1000.0 / ImGui::GetIO().Framerate); ImGui::Text("Framerate: %.1f FPS", ImGui::GetIO().Framerate); ImGui::Text("Center Frequency: %.0f Hz", gui::waterfall.getCenterFrequency()); @@ -511,7 +521,7 @@ void MainWindow::draw() { ImGui::Checkbox("Bypass buffering", &sigpath::signalPath.inputBuffer.bypass); ImGui::Text("Buffering: %d", (sigpath::signalPath.inputBuffer.writeCur - sigpath::signalPath.inputBuffer.readCur + 32) % 32); - + if (ImGui::Button("Test Bug")) { spdlog::error("Will this make the software crash?"); } @@ -543,7 +553,7 @@ void MainWindow::draw() { ImGui::BeginChild("Waterfall"); - gui::waterfall.draw(); + gui::waterfall.draw(); ImGui::EndChild(); @@ -589,7 +599,7 @@ void MainWindow::draw() { core::configManager.release(true); } } - + ImGui::NextColumn(); ImGui::BeginChild("WaterfallControls"); @@ -598,7 +608,7 @@ void MainWindow::draw() { ImGui::SetCursorPosX((ImGui::GetWindowSize().x / 2.0) - 10); if (ImGui::VSliderFloat("##_7_", ImVec2(20.0, 150.0), &bw, 1.0, 0.0, "")) { double factor = (double)bw * (double)bw; - + // Map 0.0 -> 1.0 to 1000.0 -> bandwidth double wfBw = gui::waterfall.getBandwidth(); double delta = wfBw - 1000.0; @@ -687,7 +697,7 @@ void MainWindow::setFFTSize(int size) { fftwf_destroy_plan(fftwPlan); fftwf_free(fft_in); fftwf_free(fft_out); - + fft_in = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * fftSize); fft_out = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * fftSize); fftwPlan = fftwf_plan_dft_1d(fftSize, fft_in, fft_out, FFTW_FORWARD, FFTW_ESTIMATE); diff --git a/core/src/gui/main_window.h b/core/src/gui/main_window.h index 265ee549..51cc5fcd 100644 --- a/core/src/gui/main_window.h +++ b/core/src/gui/main_window.h @@ -9,7 +9,7 @@ #include #include -#define WINDOW_FLAGS ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoBackground +#define WINDOW_FLAGS ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoBackground class MainWindow { public: @@ -20,7 +20,7 @@ public: void setFFTSize(int size); void setFFTWindow(int win); - // TODO: Replace with it's own class + // TODO: Replace with it's own class void setVFO(double freq); void setPlayState(bool _playing); @@ -40,7 +40,7 @@ private: std::mutex fft_mtx; fftwf_complex *fft_in, *fft_out; fftwf_plan fftwPlan; - + // GUI Variables bool firstMenuRender = true; bool startedWithMenuClosed = false; @@ -64,5 +64,4 @@ private: bool initComplete = false; EventHandler vfoCreatedHandler; - }; \ No newline at end of file diff --git a/core/src/gui/menus/bandplan.cpp b/core/src/gui/menus/bandplan.cpp index 211557ae..5c138d06 100644 --- a/core/src/gui/menus/bandplan.cpp +++ b/core/src/gui/menus/bandplan.cpp @@ -21,7 +21,7 @@ namespace bandplanmenu { if (bandplan::bandplans.find(core::configManager.conf["bandPlan"]) != bandplan::bandplans.end()) { std::string name = core::configManager.conf["bandPlan"]; bandplanId = std::distance(bandplan::bandplanNames.begin(), std::find(bandplan::bandplanNames.begin(), - bandplan::bandplanNames.end(), name)); + bandplan::bandplanNames.end(), name)); gui::waterfall.bandplan = &bandplan::bandplans[name]; } else { diff --git a/core/src/gui/menus/display.cpp b/core/src/gui/menus/display.cpp index 6fcb9c15..e04ea3bc 100644 --- a/core/src/gui/menus/display.cpp +++ b/core/src/gui/menus/display.cpp @@ -33,15 +33,15 @@ namespace displaymenu { }; const char* FFTSizesStr = "524288\0" - "262144\0" - "131072\0" - "65536\0" - "32768\0" - "16384\0" - "8192\0" - "4096\0" - "2048\0" - "1024\0"; + "262144\0" + "131072\0" + "65536\0" + "32768\0" + "16384\0" + "8192\0" + "4096\0" + "2048\0" + "1024\0"; int fftSizeId = 0; @@ -83,7 +83,7 @@ namespace displaymenu { fftRate = core::configManager.conf["fftRate"]; sigpath::signalPath.setFFTRate(fftRate); - selectedWindow = std::clamp((int)core::configManager.conf["fftWindow"], 0, _FFT_WINDOW_COUNT-1); + selectedWindow = std::clamp((int)core::configManager.conf["fftWindow"], 0, _FFT_WINDOW_COUNT - 1); gui::mainWindow.setFFTWindow(selectedWindow); } @@ -153,7 +153,5 @@ namespace displaymenu { } ImGui::Text("Color map Author: %s", colorMapAuthor.c_str()); } - - } } \ No newline at end of file diff --git a/core/src/gui/menus/module_manager.cpp b/core/src/gui/menus/module_manager.cpp index ec0583c7..f750d750 100644 --- a/core/src/gui/menus/module_manager.cpp +++ b/core/src/gui/menus/module_manager.cpp @@ -51,7 +51,7 @@ namespace module_manager_menu { ImGui::TableSetColumnIndex(2); ImVec2 origPos = ImGui::GetCursorPos(); ImGui::SetCursorPos(ImVec2(origPos.x - 3, origPos.y)); - if (ImGui::Button(("##module_mgr_"+name).c_str(), ImVec2(height,height))) { + if (ImGui::Button(("##module_mgr_" + name).c_str(), ImVec2(height, height))) { toBeRemoved = name; confirmOpened = true; } @@ -61,14 +61,14 @@ namespace module_manager_menu { ImGui::EndTable(); } - if (ImGui::GenericDialog("module_mgr_confirm_", confirmOpened, GENERIC_DIALOG_BUTTONS_YES_NO, [](){ - ImGui::Text("Deleting \"%s\". Are you sure?", toBeRemoved.c_str()); - }) == GENERIC_DIALOG_BUTTON_YES) { + if (ImGui::GenericDialog("module_mgr_confirm_", confirmOpened, GENERIC_DIALOG_BUTTONS_YES_NO, []() { + ImGui::Text("Deleting \"%s\". Are you sure?", toBeRemoved.c_str()); + }) == GENERIC_DIALOG_BUTTON_YES) { core::moduleManager.deleteInstance(toBeRemoved); modified = true; } - ImGui::GenericDialog("module_mgr_error_", errorOpen, GENERIC_DIALOG_BUTTONS_OK, [](){ + ImGui::GenericDialog("module_mgr_error_", errorOpen, GENERIC_DIALOG_BUTTONS_OK, []() { ImGui::Text(errorMessage.c_str()); }); @@ -89,7 +89,7 @@ namespace module_manager_menu { ImGui::TableSetColumnIndex(2); if (strlen(modName) == 0) { style::beginDisabled(); } - if (ImGui::Button("+##module_mgr_add_btn", ImVec2(16,0))) { + if (ImGui::Button("+##module_mgr_add_btn", ImVec2(16, 0))) { if (!core::moduleManager.createInstance(modName, modTypes[modTypeId])) { core::moduleManager.postInit(modName); modified = true; diff --git a/core/src/gui/menus/source.cpp b/core/src/gui/menus/source.cpp index eabc4c59..f3b65b51 100644 --- a/core/src/gui/menus/source.cpp +++ b/core/src/gui/menus/source.cpp @@ -34,29 +34,41 @@ namespace sourecmenu { }; const char* offsetModesTxt = "None\0" - "Custom\0" - "SpyVerter\0" - "Ham-It-Up\0" - "DK5AV X-Band\0" - "Ku LNB (9750MHz)\0" - "Ku LNB (10700MHz)\0"; + "Custom\0" + "SpyVerter\0" + "Ham-It-Up\0" + "DK5AV X-Band\0" + "Ku LNB (9750MHz)\0" + "Ku LNB (10700MHz)\0"; const char* decimationStages = "None\0" - "2\0" - "4\0" - "8\0" - "16\0" - "32\0" - "64\0"; + "2\0" + "4\0" + "8\0" + "16\0" + "32\0" + "64\0"; void updateOffset() { - if (offsetMode == OFFSET_MODE_CUSTOM) { effectiveOffset = customOffset; } - else if (offsetMode == OFFSET_MODE_SPYVERTER) { effectiveOffset = 120000000; } // 120MHz Up-conversion - else if (offsetMode == OFFSET_MODE_HAM_IT_UP) { effectiveOffset = 125000000; } // 125MHz Up-conversion - else if (offsetMode == OFFSET_MODE_DK5AV_XB) { effectiveOffset = -6800000000; } // 6.8GHz Down-conversion - else if (offsetMode == OFFSET_MODE_KU_LNB_9750) { effectiveOffset = -9750000000; } // 9.750GHz Down-conversion - else if (offsetMode == OFFSET_MODE_KU_LNB_10700) { effectiveOffset = -10700000000; } // 10.7GHz Down-conversion - else { effectiveOffset = 0; } + if (offsetMode == OFFSET_MODE_CUSTOM) { effectiveOffset = customOffset; } + else if (offsetMode == OFFSET_MODE_SPYVERTER) { + effectiveOffset = 120000000; + } // 120MHz Up-conversion + else if (offsetMode == OFFSET_MODE_HAM_IT_UP) { + effectiveOffset = 125000000; + } // 125MHz Up-conversion + else if (offsetMode == OFFSET_MODE_DK5AV_XB) { + effectiveOffset = -6800000000; + } // 6.8GHz Down-conversion + else if (offsetMode == OFFSET_MODE_KU_LNB_9750) { + effectiveOffset = -9750000000; + } // 9.750GHz Down-conversion + else if (offsetMode == OFFSET_MODE_KU_LNB_10700) { + effectiveOffset = -10700000000; + } // 10.7GHz Down-conversion + else { + effectiveOffset = 0; + } sigpath::sourceManager.setTuningOffset(effectiveOffset); } @@ -86,7 +98,7 @@ namespace sourecmenu { void onSourceRegistered(std::string name, void* ctx) { refreshSources(); - + if (selectedSource.empty()) { sourceId = 0; selectSource(sourceNames[0]); diff --git a/core/src/gui/menus/vfo_color.cpp b/core/src/gui/menus/vfo_color.cpp index dbb322f5..b3b33777 100644 --- a/core/src/gui/menus/vfo_color.cpp +++ b/core/src/gui/menus/vfo_color.cpp @@ -29,7 +29,7 @@ namespace vfo_color_menu { json conf = core::configManager.conf["vfoColors"]; for (auto& [name, val] : conf.items()) { // If not a string, repair with default - if (!val.is_string()) { + if (!val.is_string()) { core::configManager.conf["vfoColors"][name] = "#FFFFFF"; vfoColors[name] = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); modified = true; @@ -120,7 +120,7 @@ namespace vfo_color_menu { if (vfoColors.find(name) != vfoColors.end()) { col = vfoColors[name]; } - if (ImGui::ColorEdit3(("##vfo_color_"+name).c_str(), (float*)&col, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel)) { + if (ImGui::ColorEdit3(("##vfo_color_" + name).c_str(), (float*)&col, ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel)) { vfoColors[name] = col; vfo->color = IM_COL32((int)roundf(col.x * 255), (int)roundf(col.y * 255), (int)roundf(col.z * 255), 50); core::configManager.acquire(); diff --git a/core/src/gui/theme_manager.cpp b/core/src/gui/theme_manager.cpp index da49253e..ca121608 100644 --- a/core/src/gui/theme_manager.cpp +++ b/core/src/gui/theme_manager.cpp @@ -27,7 +27,7 @@ bool ThemeManager::loadThemesFromDir(std::string path) { return false; } themes.clear(); - for (const auto & file : std::filesystem::directory_iterator(path)) { + for (const auto& file : std::filesystem::directory_iterator(path)) { std::string _path = file.path().generic_string(); if (file.path().extension().generic_string() != ".json") { continue; @@ -108,7 +108,7 @@ bool ThemeManager::loadTheme(std::string path) { return false; } } - + thm.data = data; themes[name] = thm; @@ -134,7 +134,7 @@ bool ThemeManager::applyTheme(std::string name) { ImVec4* colors = style.Colors; Theme thm = themes[name]; - + uint8_t ret[4]; std::map params = thm.data; for (auto const& [param, val] : params) { @@ -142,20 +142,20 @@ bool ThemeManager::applyTheme(std::string name) { if (param == "WaterfallBackground") { decodeRGBA(val, ret); - waterfallBg = ImVec4((float)ret[0]/255.0f, (float)ret[1]/255.0f, (float)ret[2]/255.0f, (float)ret[3]/255.0f); + waterfallBg = ImVec4((float)ret[0] / 255.0f, (float)ret[1] / 255.0f, (float)ret[2] / 255.0f, (float)ret[3] / 255.0f); continue; } if (param == "ClearColor") { decodeRGBA(val, ret); - clearColor = ImVec4((float)ret[0]/255.0f, (float)ret[1]/255.0f, (float)ret[2]/255.0f, (float)ret[3]/255.0f); + clearColor = ImVec4((float)ret[0] / 255.0f, (float)ret[1] / 255.0f, (float)ret[2] / 255.0f, (float)ret[3] / 255.0f); continue; } // If param is a color, check that it's a valid RGBA hex value if (IMGUI_COL_IDS.find(param) != IMGUI_COL_IDS.end()) { decodeRGBA(val, ret); - colors[IMGUI_COL_IDS[param]] = ImVec4((float)ret[0]/255.0f, (float)ret[1]/255.0f, (float)ret[2]/255.0f, (float)ret[3]/255.0f); + colors[IMGUI_COL_IDS[param]] = ImVec4((float)ret[0] / 255.0f, (float)ret[1] / 255.0f, (float)ret[2] / 255.0f, (float)ret[3] / 255.0f); continue; } } @@ -181,57 +181,57 @@ std::vector ThemeManager::getThemeNames() { } std::map ThemeManager::IMGUI_COL_IDS = { - {"Text", ImGuiCol_Text}, - {"TextDisabled", ImGuiCol_TextDisabled}, - {"WindowBg", ImGuiCol_WindowBg}, - {"ChildBg", ImGuiCol_ChildBg}, - {"PopupBg", ImGuiCol_PopupBg}, - {"Border", ImGuiCol_Border}, - {"BorderShadow", ImGuiCol_BorderShadow}, - {"FrameBg", ImGuiCol_FrameBg}, - {"FrameBgHovered", ImGuiCol_FrameBgHovered}, - {"FrameBgActive", ImGuiCol_FrameBgActive}, - {"TitleBg", ImGuiCol_TitleBg}, - {"TitleBgActive", ImGuiCol_TitleBgActive}, - {"TitleBgCollapsed", ImGuiCol_TitleBgCollapsed}, - {"MenuBarBg", ImGuiCol_MenuBarBg}, - {"ScrollbarBg", ImGuiCol_ScrollbarBg}, - {"ScrollbarGrab", ImGuiCol_ScrollbarGrab}, - {"ScrollbarGrabHovered", ImGuiCol_ScrollbarGrabHovered}, - {"ScrollbarGrabActive", ImGuiCol_ScrollbarGrabActive}, - {"CheckMark", ImGuiCol_CheckMark}, - {"SliderGrab", ImGuiCol_SliderGrab}, - {"SliderGrabActive", ImGuiCol_SliderGrabActive}, - {"Button", ImGuiCol_Button}, - {"ButtonHovered", ImGuiCol_ButtonHovered}, - {"ButtonActive", ImGuiCol_ButtonActive}, - {"Header", ImGuiCol_Header}, - {"HeaderHovered", ImGuiCol_HeaderHovered}, - {"HeaderActive", ImGuiCol_HeaderActive}, - {"Separator", ImGuiCol_Separator}, - {"SeparatorHovered", ImGuiCol_SeparatorHovered}, - {"SeparatorActive", ImGuiCol_SeparatorActive}, - {"ResizeGrip", ImGuiCol_ResizeGrip}, - {"ResizeGripHovered", ImGuiCol_ResizeGripHovered}, - {"ResizeGripActive", ImGuiCol_ResizeGripActive}, - {"Tab", ImGuiCol_Tab}, - {"TabHovered", ImGuiCol_TabHovered}, - {"TabActive", ImGuiCol_TabActive}, - {"TabUnfocused", ImGuiCol_TabUnfocused}, - {"TabUnfocusedActive", ImGuiCol_TabUnfocusedActive}, - {"PlotLines", ImGuiCol_PlotLines}, - {"PlotLinesHovered", ImGuiCol_PlotLinesHovered}, - {"PlotHistogram", ImGuiCol_PlotHistogram}, - {"PlotHistogramHovered", ImGuiCol_PlotHistogramHovered}, - {"TableHeaderBg", ImGuiCol_TableHeaderBg}, - {"TableBorderStrong", ImGuiCol_TableBorderStrong}, - {"TableBorderLight", ImGuiCol_TableBorderLight}, - {"TableRowBg", ImGuiCol_TableRowBg}, - {"TableRowBgAlt", ImGuiCol_TableRowBgAlt}, - {"TextSelectedBg", ImGuiCol_TextSelectedBg}, - {"DragDropTarget", ImGuiCol_DragDropTarget}, - {"NavHighlight", ImGuiCol_NavHighlight}, - {"NavWindowingHighlight", ImGuiCol_NavWindowingHighlight}, - {"NavWindowingDimBg", ImGuiCol_NavWindowingDimBg}, - {"ModalWindowDimBg", ImGuiCol_ModalWindowDimBg} + { "Text", ImGuiCol_Text }, + { "TextDisabled", ImGuiCol_TextDisabled }, + { "WindowBg", ImGuiCol_WindowBg }, + { "ChildBg", ImGuiCol_ChildBg }, + { "PopupBg", ImGuiCol_PopupBg }, + { "Border", ImGuiCol_Border }, + { "BorderShadow", ImGuiCol_BorderShadow }, + { "FrameBg", ImGuiCol_FrameBg }, + { "FrameBgHovered", ImGuiCol_FrameBgHovered }, + { "FrameBgActive", ImGuiCol_FrameBgActive }, + { "TitleBg", ImGuiCol_TitleBg }, + { "TitleBgActive", ImGuiCol_TitleBgActive }, + { "TitleBgCollapsed", ImGuiCol_TitleBgCollapsed }, + { "MenuBarBg", ImGuiCol_MenuBarBg }, + { "ScrollbarBg", ImGuiCol_ScrollbarBg }, + { "ScrollbarGrab", ImGuiCol_ScrollbarGrab }, + { "ScrollbarGrabHovered", ImGuiCol_ScrollbarGrabHovered }, + { "ScrollbarGrabActive", ImGuiCol_ScrollbarGrabActive }, + { "CheckMark", ImGuiCol_CheckMark }, + { "SliderGrab", ImGuiCol_SliderGrab }, + { "SliderGrabActive", ImGuiCol_SliderGrabActive }, + { "Button", ImGuiCol_Button }, + { "ButtonHovered", ImGuiCol_ButtonHovered }, + { "ButtonActive", ImGuiCol_ButtonActive }, + { "Header", ImGuiCol_Header }, + { "HeaderHovered", ImGuiCol_HeaderHovered }, + { "HeaderActive", ImGuiCol_HeaderActive }, + { "Separator", ImGuiCol_Separator }, + { "SeparatorHovered", ImGuiCol_SeparatorHovered }, + { "SeparatorActive", ImGuiCol_SeparatorActive }, + { "ResizeGrip", ImGuiCol_ResizeGrip }, + { "ResizeGripHovered", ImGuiCol_ResizeGripHovered }, + { "ResizeGripActive", ImGuiCol_ResizeGripActive }, + { "Tab", ImGuiCol_Tab }, + { "TabHovered", ImGuiCol_TabHovered }, + { "TabActive", ImGuiCol_TabActive }, + { "TabUnfocused", ImGuiCol_TabUnfocused }, + { "TabUnfocusedActive", ImGuiCol_TabUnfocusedActive }, + { "PlotLines", ImGuiCol_PlotLines }, + { "PlotLinesHovered", ImGuiCol_PlotLinesHovered }, + { "PlotHistogram", ImGuiCol_PlotHistogram }, + { "PlotHistogramHovered", ImGuiCol_PlotHistogramHovered }, + { "TableHeaderBg", ImGuiCol_TableHeaderBg }, + { "TableBorderStrong", ImGuiCol_TableBorderStrong }, + { "TableBorderLight", ImGuiCol_TableBorderLight }, + { "TableRowBg", ImGuiCol_TableRowBg }, + { "TableRowBgAlt", ImGuiCol_TableRowBgAlt }, + { "TextSelectedBg", ImGuiCol_TextSelectedBg }, + { "DragDropTarget", ImGuiCol_DragDropTarget }, + { "NavHighlight", ImGuiCol_NavHighlight }, + { "NavWindowingHighlight", ImGuiCol_NavWindowingHighlight }, + { "NavWindowingDimBg", ImGuiCol_NavWindowingDimBg }, + { "ModalWindowDimBg", ImGuiCol_ModalWindowDimBg } }; \ No newline at end of file diff --git a/core/src/gui/theme_manager.h b/core/src/gui/theme_manager.h index 74646002..f36c6013 100644 --- a/core/src/gui/theme_manager.h +++ b/core/src/gui/theme_manager.h @@ -20,7 +20,8 @@ public: std::vector getThemeNames(); - ImVec4 waterfallBg = ImVec4(0.0f, 0.0f, 0.0f, 1.0f);; + ImVec4 waterfallBg = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); + ; ImVec4 clearColor = ImVec4(0.0666f, 0.0666f, 0.0666f, 1.0f); private: @@ -29,5 +30,4 @@ private: static std::map IMGUI_COL_IDS; std::map themes; - }; \ No newline at end of file diff --git a/core/src/gui/tuner.cpp b/core/src/gui/tuner.cpp index e1a98b18..16382612 100644 --- a/core/src/gui/tuner.cpp +++ b/core/src/gui/tuner.cpp @@ -31,7 +31,7 @@ namespace tuner { ImGui::WaterfallVFO* vfo = gui::waterfall.vfos[vfoName]; - double currentOff = vfo->centerOffset; + double currentOff = vfo->centerOffset; double currentTune = gui::waterfall.getCenterFrequency() + vfo->generalOffset; double delta = freq - currentTune; @@ -119,21 +119,21 @@ namespace tuner { void tune(int mode, std::string vfoName, double freq) { switch (mode) { - case TUNER_MODE_CENTER: - centerTuning(vfoName, freq); - break; - case TUNER_MODE_NORMAL: - normalTuning(vfoName, freq); - break; - case TUNER_MODE_LOWER_HALF: - normalTuning(vfoName, freq); - break; - case TUNER_MODE_UPPER_HALF: - normalTuning(vfoName, freq); - break; - case TUNER_MODE_IQ_ONLY: - iqTuning(freq); - break; + case TUNER_MODE_CENTER: + centerTuning(vfoName, freq); + break; + case TUNER_MODE_NORMAL: + normalTuning(vfoName, freq); + break; + case TUNER_MODE_LOWER_HALF: + normalTuning(vfoName, freq); + break; + case TUNER_MODE_UPPER_HALF: + normalTuning(vfoName, freq); + break; + case TUNER_MODE_IQ_ONLY: + iqTuning(freq); + break; } } } \ No newline at end of file diff --git a/core/src/gui/widgets/bandplan.cpp b/core/src/gui/widgets/bandplan.cpp index 9e00fa65..1e0c2518 100644 --- a/core/src/gui/widgets/bandplan.cpp +++ b/core/src/gui/widgets/bandplan.cpp @@ -21,10 +21,10 @@ namespace bandplan { void to_json(json& j, const Band_t& b) { j = json{ - {"name", b.name}, - {"type", b.type}, - {"start", b.start}, - {"end", b.end}, + { "name", b.name }, + { "type", b.type }, + { "start", b.start }, + { "end", b.end }, }; } @@ -37,12 +37,12 @@ namespace bandplan { void to_json(json& j, const BandPlan_t& b) { j = json{ - {"name", b.name}, - {"country_name", b.countryName}, - {"country_code", b.countryCode}, - {"author_name", b.authorName}, - {"author_url", b.authorURL}, - {"bands", b.bands} + { "name", b.name }, + { "country_name", b.countryName }, + { "country_code", b.countryCode }, + { "author_name", b.authorName }, + { "author_url", b.authorURL }, + { "bands", b.bands } }; } @@ -58,7 +58,7 @@ namespace bandplan { void to_json(json& j, const BandPlanColor_t& ct) { spdlog::error("ImGui color to JSON not implemented!!!"); } - + void from_json(const json& j, BandPlanColor_t& ct) { std::string col = j.get(); if (col[0] != '#' || !std::all_of(col.begin() + 1, col.end(), ::isxdigit)) { @@ -99,7 +99,7 @@ namespace bandplan { return; } bandplans.clear(); - for (const auto & file : std::filesystem::directory_iterator(path)) { + for (const auto& file : std::filesystem::directory_iterator(path)) { std::string path = file.path().generic_string(); if (file.path().extension().generic_string() != ".json") { continue; diff --git a/core/src/gui/widgets/bandplan.h b/core/src/gui/widgets/bandplan.h index e3129774..d29385c5 100644 --- a/core/src/gui/widgets/bandplan.h +++ b/core/src/gui/widgets/bandplan.h @@ -35,7 +35,7 @@ namespace bandplan { void to_json(json& j, const BandPlanColor_t& ct); void from_json(const json& j, BandPlanColor_t& ct); - + void loadBandPlan(std::string path); void loadFromDir(std::string path); void loadColorTable(json table); diff --git a/core/src/gui/widgets/constellation_diagram.cpp b/core/src/gui/widgets/constellation_diagram.cpp index 48026f4d..5da4d1a5 100644 --- a/core/src/gui/widgets/constellation_diagram.cpp +++ b/core/src/gui/widgets/constellation_diagram.cpp @@ -12,7 +12,7 @@ namespace ImGui { float pad = style.FramePadding.y; ImVec2 min = window->DC.CursorPos; ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), CalcItemWidth()); - ImRect bb(min, ImVec2(min.x+size.x, min.y+size.y)); + ImRect bb(min, ImVec2(min.x + size.x, min.y + size.y)); float lineHeight = size.y; ItemSize(size, style.FramePadding.y); @@ -20,13 +20,13 @@ namespace ImGui { return; } - window->DrawList->AddRectFilled(min, ImVec2(min.x+size.x, min.y+size.y), IM_COL32(0,0,0,255)); + window->DrawList->AddRectFilled(min, ImVec2(min.x + size.x, min.y + size.y), IM_COL32(0, 0, 0, 255)); ImU32 col = ImGui::GetColorU32(ImGuiCol_CheckMark, 0.7f); float increment = size.x / 1024.0f; for (int i = 0; i < 1024; i++) { if (buffer[i].re > 1.5f || buffer[i].re < -1.5f) { continue; } if (buffer[i].im > 1.5f || buffer[i].im < -1.5f) { continue; } - window->DrawList->AddCircleFilled(ImVec2((((buffer[i].re / 1.5f) + 1) * (size.x*0.5f)) + min.x, (((buffer[i].im / 1.5f) + 1) * (size.y*0.5f)) + min.y), 2, col); + window->DrawList->AddCircleFilled(ImVec2((((buffer[i].re / 1.5f) + 1) * (size.x * 0.5f)) + min.x, (((buffer[i].im / 1.5f) + 1) * (size.y * 0.5f)) + min.y), 2, col); } } diff --git a/core/src/gui/widgets/constellation_diagram.h b/core/src/gui/widgets/constellation_diagram.h index b37f522f..c3d9fa00 100644 --- a/core/src/gui/widgets/constellation_diagram.h +++ b/core/src/gui/widgets/constellation_diagram.h @@ -20,6 +20,5 @@ namespace ImGui { private: std::mutex bufferMtx; dsp::complex_t buffer[1024]; - }; } \ No newline at end of file diff --git a/core/src/gui/widgets/file_select.cpp b/core/src/gui/widgets/file_select.cpp index 6a909525..520b5cd4 100644 --- a/core/src/gui/widgets/file_select.cpp +++ b/core/src/gui/widgets/file_select.cpp @@ -39,7 +39,7 @@ bool FileSelect::render(std::string id) { if (workerThread.joinable()) { workerThread.join(); } workerThread = std::thread(&FileSelect::worker, this); } - + _pathChanged |= pathChanged; pathChanged = false; return _pathChanged; @@ -63,15 +63,15 @@ bool FileSelect::pathIsValid() { } void FileSelect::worker() { - auto file = pfd::open_file("Open File", pathValid ? std::filesystem::path(expandString(path)).parent_path().string() : "", _filter); - std::vector res = file.result(); + auto file = pfd::open_file("Open File", pathValid ? std::filesystem::path(expandString(path)).parent_path().string() : "", _filter); + std::vector res = file.result(); - if (res.size() > 0) { - path = res[0]; - strcpy(strPath, path.c_str()); - pathChanged = true; - } + if (res.size() > 0) { + path = res[0]; + strcpy(strPath, path.c_str()); + pathChanged = true; + } - pathValid = std::filesystem::is_regular_file(expandString(path)); - dialogOpen = false; + pathValid = std::filesystem::is_regular_file(expandString(path)); + dialogOpen = false; } \ No newline at end of file diff --git a/core/src/gui/widgets/file_select.h b/core/src/gui/widgets/file_select.h index e5d578c1..25755a3d 100644 --- a/core/src/gui/widgets/file_select.h +++ b/core/src/gui/widgets/file_select.h @@ -8,7 +8,7 @@ class FileSelect { public: - FileSelect(std::string defaultPath, std::vector filter = {"All Files", "*"}); + FileSelect(std::string defaultPath, std::vector filter = { "All Files", "*" }); bool render(std::string id); void setPath(std::string path, bool markChanged = false); bool pathIsValid(); @@ -16,7 +16,7 @@ public: std::string expandString(std::string input); std::string path = ""; - + private: void worker(); diff --git a/core/src/gui/widgets/folder_select.cpp b/core/src/gui/widgets/folder_select.cpp index a2fb5169..8cb668c2 100644 --- a/core/src/gui/widgets/folder_select.cpp +++ b/core/src/gui/widgets/folder_select.cpp @@ -38,7 +38,7 @@ bool FolderSelect::render(std::string id) { if (workerThread.joinable()) { workerThread.join(); } workerThread = std::thread(&FolderSelect::worker, this); } - + _pathChanged |= pathChanged; pathChanged = false; return _pathChanged; @@ -62,15 +62,15 @@ bool FolderSelect::pathIsValid() { } void FolderSelect::worker() { - auto fold = pfd::select_folder("Select Folder", pathValid ? std::filesystem::path(expandString(path)).parent_path().string() : ""); - std::string res = fold.result(); + auto fold = pfd::select_folder("Select Folder", pathValid ? std::filesystem::path(expandString(path)).parent_path().string() : ""); + std::string res = fold.result(); - if (res != "") { - path = res; - strcpy(strPath, path.c_str()); - pathChanged = true; - } + if (res != "") { + path = res; + strcpy(strPath, path.c_str()); + pathChanged = true; + } - pathValid = std::filesystem::is_directory(expandString(path)); - dialogOpen = false; + pathValid = std::filesystem::is_directory(expandString(path)); + dialogOpen = false; } \ No newline at end of file diff --git a/core/src/gui/widgets/folder_select.h b/core/src/gui/widgets/folder_select.h index 0f7ce60e..194e94a6 100644 --- a/core/src/gui/widgets/folder_select.h +++ b/core/src/gui/widgets/folder_select.h @@ -15,7 +15,7 @@ public: std::string expandString(std::string input); std::string path = ""; - + private: void worker(); diff --git a/core/src/gui/widgets/frequency_select.cpp b/core/src/gui/widgets/frequency_select.cpp index 1fbec67e..261dfc22 100644 --- a/core/src/gui/widgets/frequency_select.cpp +++ b/core/src/gui/widgets/frequency_select.cpp @@ -15,13 +15,11 @@ bool isInArea(ImVec2 val, ImVec2 min, ImVec2 max) { } FrequencySelect::FrequencySelect() { - } void FrequencySelect::init() { for (int i = 0; i < 12; i++) { digits[i] = 0; - } } @@ -45,7 +43,6 @@ void FrequencySelect::onPosChange() { } void FrequencySelect::onResize() { - } void FrequencySelect::incrementDigit(int i) { @@ -126,7 +123,7 @@ void FrequencySelect::draw() { int digitWidth = digitSz.x; int commaOffset = 0; bool zeros = true; - + ImGui::ItemSize(ImRect(digitTopMins[0], ImVec2(digitBottomMaxs[11].x + 15, digitBottomMaxs[11].y))); for (int i = 0; i < 12; i++) { @@ -134,12 +131,12 @@ void FrequencySelect::draw() { zeros = false; } sprintf(buf, "%d", digits[i]); - window->DrawList->AddText(ImVec2(widgetPos.x + (i * digitWidth) + commaOffset, widgetPos.y), - zeros ? disabledColor : textColor, buf); + window->DrawList->AddText(ImVec2(widgetPos.x + (i * digitWidth) + commaOffset, widgetPos.y), + zeros ? disabledColor : textColor, buf); if ((i + 1) % 3 == 0 && i < 11) { commaOffset += commaSz.x; - window->DrawList->AddText(ImVec2(widgetPos.x + (i * digitWidth) + commaOffset + 11, widgetPos.y), - zeros ? disabledColor : textColor, "."); + window->DrawList->AddText(ImVec2(widgetPos.x + (i * digitWidth) + commaOffset + 11, widgetPos.y), + zeros ? disabledColor : textColor, "."); } } @@ -183,7 +180,7 @@ void FrequencySelect::draw() { decrementDigit(i); } if ((ImGui::IsKeyPressed(GLFW_KEY_LEFT) || ImGui::IsKeyPressed(GLFW_KEY_BACKSPACE)) && i > 0) { - moveCursorToDigit(i - 1); + moveCursorToDigit(i - 1); } if (ImGui::IsKeyPressed(GLFW_KEY_RIGHT) && i < 11) { moveCursorToDigit(i + 1); diff --git a/core/src/gui/widgets/image.cpp b/core/src/gui/widgets/image.cpp index 6350df59..974d14ab 100644 --- a/core/src/gui/widgets/image.cpp +++ b/core/src/gui/widgets/image.cpp @@ -30,7 +30,7 @@ namespace ImGui { float height = roundf((width / (float)_width) * (float)_height); ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), height); - ImRect bb(min, ImVec2(min.x+size.x, min.y+size.y)); + ImRect bb(min, ImVec2(min.x + size.x, min.y + size.y)); float lineHeight = size.y; ItemSize(size, style.FramePadding.y); @@ -42,7 +42,7 @@ namespace ImGui { newData = false; updateTexture(); } - + window->DrawList->AddImage((void*)(intptr_t)textureId, min, ImVec2(min.x + width, min.y + height)); } diff --git a/core/src/gui/widgets/image.h b/core/src/gui/widgets/image.h index 13f67d24..3a7b77f5 100644 --- a/core/src/gui/widgets/image.h +++ b/core/src/gui/widgets/image.h @@ -28,6 +28,5 @@ namespace ImGui { GLuint textureId; bool newData = false; - }; } \ No newline at end of file diff --git a/core/src/gui/widgets/line_push_image.cpp b/core/src/gui/widgets/line_push_image.cpp index fca796d2..6c553898 100644 --- a/core/src/gui/widgets/line_push_image.cpp +++ b/core/src/gui/widgets/line_push_image.cpp @@ -23,7 +23,7 @@ namespace ImGui { float height = roundf((width / (float)_frameWidth) * (float)_lineCount); ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), height); - ImRect bb(min, ImVec2(min.x+size.x, min.y+size.y)); + ImRect bb(min, ImVec2(min.x + size.x, min.y + size.y)); float lineHeight = size.y; // If there are no lines, there is no point in drawing anything @@ -38,7 +38,7 @@ namespace ImGui { newData = false; updateTexture(); } - + window->DrawList->AddImage((void*)(intptr_t)textureId, min, ImVec2(min.x + width, min.y + height)); } diff --git a/core/src/gui/widgets/line_push_image.h b/core/src/gui/widgets/line_push_image.h index a13ee80a..f739b442 100644 --- a/core/src/gui/widgets/line_push_image.h +++ b/core/src/gui/widgets/line_push_image.h @@ -37,7 +37,5 @@ namespace ImGui { GLuint textureId; bool newData = false; - - }; } \ No newline at end of file diff --git a/core/src/gui/widgets/menu.cpp b/core/src/gui/widgets/menu.cpp index 9a0ff3ac..df8eaee4 100644 --- a/core/src/gui/widgets/menu.cpp +++ b/core/src/gui/widgets/menu.cpp @@ -4,7 +4,6 @@ #include Menu::Menu() { - } void Menu::registerEntry(std::string name, void (*drawHandler)(void* ctx), void* ctx, ModuleManager::Instance* inst) { @@ -67,9 +66,9 @@ bool Menu::draw(bool updateStates) { window->DrawList->AddRect(posMin, posMax, textColor); } displayedCount++; - + MenuItem_t& item = items[opt.name]; - + ImRect orginalRect = window->WorkRect; if (item.inst != NULL) { @@ -79,8 +78,8 @@ bool Menu::draw(bool updateStates) { ImVec2 posMin = ImGui::GetCursorScreenPos(); ImVec2 posMax = ImVec2(posMin.x + menuWidth, posMin.y + ImGui::GetFrameHeight()); - headerTops[displayedCount-1] = posMin.y; - optionIDs[displayedCount-1] = rawId-1; + headerTops[displayedCount - 1] = posMin.y; + optionIDs[displayedCount - 1] = rawId - 1; if (ImGui::IsMouseClicked(ImGuiMouseButton_Left) && ImGui::IsMouseHoveringRect(posMin, posMax)) { menuClicked = true; @@ -89,7 +88,7 @@ bool Menu::draw(bool updateStates) { if (menuClicked && ImGui::IsMouseDragging(ImGuiMouseButton_Left) && draggedMenuName.empty() && clickedMenuName == opt.name) { draggedMenuName = opt.name; - draggedId = rawId-1; + draggedId = rawId - 1; draggedOpt = opt; continue; } @@ -142,7 +141,7 @@ bool Menu::draw(bool updateStates) { } if (!ImGui::IsMouseDown(ImGuiMouseButton_Left) && menuClicked) { - + if (!draggedMenuName.empty()) { // Move menu order.erase(order.begin() + draggedId); @@ -162,7 +161,7 @@ bool Menu::draw(bool updateStates) { } changed = true; } - + menuClicked = false; draggedMenuName = ""; insertBeforeName = ""; diff --git a/core/src/gui/widgets/menu.h b/core/src/gui/widgets/menu.h index dc3e0902..1e85cb90 100644 --- a/core/src/gui/widgets/menu.h +++ b/core/src/gui/widgets/menu.h @@ -4,7 +4,7 @@ #include #include -#define MAX_MENU_COUNT 1024 +#define MAX_MENU_COUNT 1024 class Menu { public: diff --git a/core/src/gui/widgets/snr_meter.cpp b/core/src/gui/widgets/snr_meter.cpp index c9126797..74c5fd86 100644 --- a/core/src/gui/widgets/snr_meter.cpp +++ b/core/src/gui/widgets/snr_meter.cpp @@ -39,7 +39,7 @@ namespace ImGui { window->DrawList->AddLine(min + ImVec2(roundf((float)i * it), 9), min + ImVec2(roundf((float)i * it), 14), text); sprintf(buf, "%d", i * 10); ImVec2 sz = ImGui::CalcTextSize(buf); - window->DrawList->AddText(min + ImVec2(roundf(((float)i * it) - (sz.x/2.0)) + 1, 16), text, buf); + window->DrawList->AddText(min + ImVec2(roundf(((float)i * it) - (sz.x / 2.0)) + 1, 16), text, buf); } } } \ No newline at end of file diff --git a/core/src/gui/widgets/stepped_slider.cpp b/core/src/gui/widgets/stepped_slider.cpp index 6dbf62bc..ff4be4e4 100644 --- a/core/src/gui/widgets/stepped_slider.cpp +++ b/core/src/gui/widgets/stepped_slider.cpp @@ -13,8 +13,8 @@ namespace ImGui { ImFormatString(text_buf, IM_ARRAYSIZE(text_buf), display_format, *v); // Map from [v_min,v_max] to [0,N] - const int countValues = int((v_max-v_min)/v_step); - int v_i = int((*v - v_min)/v_step); + const int countValues = int((v_max - v_min) / v_step); + int v_i = int((*v - v_min) / v_step); bool value_changed = ImGui::SliderInt(label, &v_i, 0, countValues, text_buf); // Remap from [0,N] to [v_min,v_max] diff --git a/core/src/gui/widgets/symbol_diagram.cpp b/core/src/gui/widgets/symbol_diagram.cpp index c1606620..608f4fbd 100644 --- a/core/src/gui/widgets/symbol_diagram.cpp +++ b/core/src/gui/widgets/symbol_diagram.cpp @@ -21,7 +21,7 @@ namespace ImGui { float pad = style.FramePadding.y; ImVec2 min = window->DC.CursorPos; ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), 100); - ImRect bb(min, ImVec2(min.x+size.x, min.y+size.y)); + ImRect bb(min, ImVec2(min.x + size.x, min.y + size.y)); float lineHeight = size.y; ItemSize(size, style.FramePadding.y); @@ -29,20 +29,20 @@ namespace ImGui { return; } - window->DrawList->AddRectFilled(min, ImVec2(min.x+size.x, min.y+size.y), IM_COL32(0,0,0,255)); + window->DrawList->AddRectFilled(min, ImVec2(min.x + size.x, min.y + size.y), IM_COL32(0, 0, 0, 255)); ImU32 col = ImGui::GetColorU32(ImGuiCol_CheckMark, 0.7f); ImU32 col2 = ImGui::GetColorU32(ImGuiCol_CheckMark, 0.7f); float increment = size.x / (float)sampleCount; float val; for (auto l : lines) { - window->DrawList->AddLine(ImVec2(min.x, (((l * _scale) + 1) * (size.y*0.5f)) + min.y), ImVec2(min.x + size.x, (((l * _scale) + 1) * (size.y*0.5f)) + min.y), IM_COL32(80, 80, 80, 255)); + window->DrawList->AddLine(ImVec2(min.x, (((l * _scale) + 1) * (size.y * 0.5f)) + min.y), ImVec2(min.x + size.x, (((l * _scale) + 1) * (size.y * 0.5f)) + min.y), IM_COL32(80, 80, 80, 255)); } for (int i = 0; i < sampleCount; i++) { val = buffer[i] * _scale; if (val > 1.0f || val < -1.0f) { continue; } - window->DrawList->AddCircleFilled(ImVec2(((float)i * increment) + min.x, ((val + 1) * (size.y*0.5f)) + min.y), 2, col); + window->DrawList->AddCircleFilled(ImVec2(((float)i * increment) + min.x, ((val + 1) * (size.y * 0.5f)) + min.y), 2, col); } } diff --git a/core/src/gui/widgets/symbol_diagram.h b/core/src/gui/widgets/symbol_diagram.h index 9ca6ed85..dbb08bf7 100644 --- a/core/src/gui/widgets/symbol_diagram.h +++ b/core/src/gui/widgets/symbol_diagram.h @@ -25,6 +25,5 @@ namespace ImGui { float* buffer; float _scale; int sampleCount = 0; - }; } \ No newline at end of file diff --git a/core/src/gui/widgets/volume_meter.cpp b/core/src/gui/widgets/volume_meter.cpp index 4032f640..b0b8a8a0 100644 --- a/core/src/gui/widgets/volume_meter.cpp +++ b/core/src/gui/widgets/volume_meter.cpp @@ -29,25 +29,25 @@ namespace ImGui { float zeroDb = roundf(((-val_min) / (val_max - val_min)) * size.x); - window->DrawList->AddRectFilled(min, min + ImVec2(zeroDb, lineHeight), IM_COL32( 9, 136, 9, 255 )); - window->DrawList->AddRectFilled(min + ImVec2(zeroDb, 0), min + ImVec2(size.x, lineHeight), IM_COL32( 136, 9, 9, 255 )); + window->DrawList->AddRectFilled(min, min + ImVec2(zeroDb, lineHeight), IM_COL32(9, 136, 9, 255)); + window->DrawList->AddRectFilled(min + ImVec2(zeroDb, 0), min + ImVec2(size.x, lineHeight), IM_COL32(136, 9, 9, 255)); float end = roundf(((avg - val_min) / (val_max - val_min)) * size.x); float endP = roundf(((peak - val_min) / (val_max - val_min)) * size.x); if (avg <= 0) { - window->DrawList->AddRectFilled(min, min + ImVec2(end, lineHeight), IM_COL32( 0, 255, 0, 255 )); + window->DrawList->AddRectFilled(min, min + ImVec2(end, lineHeight), IM_COL32(0, 255, 0, 255)); } else { - window->DrawList->AddRectFilled(min, min + ImVec2(zeroDb, lineHeight), IM_COL32( 0, 255, 0, 255 )); - window->DrawList->AddRectFilled(min + ImVec2(zeroDb, 0), min + ImVec2(end, lineHeight), IM_COL32( 255, 0, 0, 255 )); + window->DrawList->AddRectFilled(min, min + ImVec2(zeroDb, lineHeight), IM_COL32(0, 255, 0, 255)); + window->DrawList->AddRectFilled(min + ImVec2(zeroDb, 0), min + ImVec2(end, lineHeight), IM_COL32(255, 0, 0, 255)); } if (peak <= 0) { - window->DrawList->AddLine(min + ImVec2(endP, -1), min + ImVec2(endP, lineHeight - 1), IM_COL32( 127, 255, 127, 255 )); + window->DrawList->AddLine(min + ImVec2(endP, -1), min + ImVec2(endP, lineHeight - 1), IM_COL32(127, 255, 127, 255)); } else { - window->DrawList->AddLine(min + ImVec2(endP, -1), min + ImVec2(endP, lineHeight - 1), IM_COL32( 255, 127, 127, 255 )); + window->DrawList->AddLine(min + ImVec2(endP, -1), min + ImVec2(endP, lineHeight - 1), IM_COL32(255, 127, 127, 255)); } } } \ No newline at end of file diff --git a/core/src/gui/widgets/waterfall.cpp b/core/src/gui/widgets/waterfall.cpp index b7a16b5d..f1993b07 100644 --- a/core/src/gui/widgets/waterfall.cpp +++ b/core/src/gui/widgets/waterfall.cpp @@ -10,32 +10,32 @@ #include float DEFAULT_COLOR_MAP[][3] = { - {0x00, 0x00, 0x20}, - {0x00, 0x00, 0x30}, - {0x00, 0x00, 0x50}, - {0x00, 0x00, 0x91}, - {0x1E, 0x90, 0xFF}, - {0xFF, 0xFF, 0xFF}, - {0xFF, 0xFF, 0x00}, - {0xFE, 0x6D, 0x16}, - {0xFF, 0x00, 0x00}, - {0xC6, 0x00, 0x00}, - {0x9F, 0x00, 0x00}, - {0x75, 0x00, 0x00}, - {0x4A, 0x00, 0x00} + { 0x00, 0x00, 0x20 }, + { 0x00, 0x00, 0x30 }, + { 0x00, 0x00, 0x50 }, + { 0x00, 0x00, 0x91 }, + { 0x1E, 0x90, 0xFF }, + { 0xFF, 0xFF, 0xFF }, + { 0xFF, 0xFF, 0x00 }, + { 0xFE, 0x6D, 0x16 }, + { 0xFF, 0x00, 0x00 }, + { 0xC6, 0x00, 0x00 }, + { 0x9F, 0x00, 0x00 }, + { 0x75, 0x00, 0x00 }, + { 0x4A, 0x00, 0x00 } }; // TODO: Fix this hacky BS double freq_ranges[] = { - 1.0, 2.0, 2.5, 5.0, - 10.0, 20.0, 25.0, 50.0, - 100.0, 200.0, 250.0, 500.0, - 1000.0, 2000.0, 2500.0, 5000.0, - 10000.0, 20000.0, 25000.0, 50000.0, - 100000.0, 200000.0, 250000.0, 500000.0, - 1000000.0, 2000000.0, 2500000.0, 5000000.0, - 10000000.0, 20000000.0, 25000000.0, 50000000.0 + 1.0, 2.0, 2.5, 5.0, + 10.0, 20.0, 25.0, 50.0, + 100.0, 200.0, 250.0, 500.0, + 1000.0, 2000.0, 2500.0, 5000.0, + 10000.0, 20000.0, 25000.0, 50000.0, + 100000.0, 200000.0, 250000.0, 500000.0, + 1000000.0, 2000000.0, 2500000.0, 5000000.0, + 10000000.0, 20000000.0, 25000000.0, 50000000.0 }; inline double findBestRange(double bandwidth, int maxSteps) { @@ -104,9 +104,9 @@ namespace ImGui { // Vertical scale for (float line = startLine; line > fftMin; line -= vRange) { float yPos = widgetPos.y + fftHeight + 10 - ((line - fftMin) * scaleFactor); - window->DrawList->AddLine(ImVec2(roundf(widgetPos.x + 50), roundf(yPos)), - ImVec2(roundf(widgetPos.x + dataWidth + 50), roundf(yPos)), - IM_COL32(50, 50, 50, 255), 1.0); + window->DrawList->AddLine(ImVec2(roundf(widgetPos.x + 50), roundf(yPos)), + ImVec2(roundf(widgetPos.x + dataWidth + 50), roundf(yPos)), + IM_COL32(50, 50, 50, 255), 1.0); sprintf(buf, "%d", (int)line); ImVec2 txtSz = ImGui::CalcTextSize(buf); window->DrawList->AddText(ImVec2(widgetPos.x + 40 - txtSz.x, roundf(yPos - (txtSz.y / 2.0))), text, buf); @@ -117,12 +117,12 @@ namespace ImGui { double horizScale = (double)dataWidth / viewBandwidth; for (double freq = startFreq; freq < upperFreq; freq += range) { double xPos = widgetPos.x + 50 + ((freq - lowerFreq) * horizScale); - window->DrawList->AddLine(ImVec2(roundf(xPos), widgetPos.y + 10), - ImVec2(roundf(xPos), widgetPos.y + fftHeight + 10), - IM_COL32(50, 50, 50, 255), 1.0); - window->DrawList->AddLine(ImVec2(roundf(xPos), widgetPos.y + fftHeight + 10), - ImVec2(roundf(xPos), widgetPos.y + fftHeight + 17), - text, 1.0); + window->DrawList->AddLine(ImVec2(roundf(xPos), widgetPos.y + 10), + ImVec2(roundf(xPos), widgetPos.y + fftHeight + 10), + IM_COL32(50, 50, 50, 255), 1.0); + window->DrawList->AddLine(ImVec2(roundf(xPos), widgetPos.y + fftHeight + 10), + ImVec2(roundf(xPos), widgetPos.y + fftHeight + 17), + text, 1.0); printAndScale(freq, buf); ImVec2 txtSz = ImGui::CalcTextSize(buf); window->DrawList->AddText(ImVec2(roundf(xPos - (txtSz.x / 2.0)), widgetPos.y + fftHeight + 10 + txtSz.y), text, buf); @@ -130,15 +130,15 @@ namespace ImGui { // Data if (latestFFT != NULL && fftLines != 0) { - for (int i = 1; i < dataWidth; i++) { + for (int i = 1; i < dataWidth; i++) { double aPos = widgetPos.y + fftHeight + 10 - ((latestFFT[i - 1] - fftMin) * scaleFactor); double bPos = widgetPos.y + fftHeight + 10 - ((latestFFT[i] - fftMin) * scaleFactor); aPos = std::clamp(aPos, widgetPos.y + 10, widgetPos.y + fftHeight + 10); bPos = std::clamp(bPos, widgetPos.y + 10, widgetPos.y + fftHeight + 10); - window->DrawList->AddLine(ImVec2(widgetPos.x + 49 + i, roundf(aPos)), - ImVec2(widgetPos.x + 50 + i, roundf(bPos)), trace, 1.0); - window->DrawList->AddLine(ImVec2(widgetPos.x + 50 + i, roundf(bPos)), - ImVec2(widgetPos.x + 50 + i, widgetPos.y + fftHeight + 10), shadow, 1.0); + window->DrawList->AddLine(ImVec2(widgetPos.x + 49 + i, roundf(aPos)), + ImVec2(widgetPos.x + 50 + i, roundf(bPos)), trace, 1.0); + window->DrawList->AddLine(ImVec2(widgetPos.x + 50 + i, roundf(bPos)), + ImVec2(widgetPos.x + 50 + i, widgetPos.y + fftHeight + 10), shadow, 1.0); } } @@ -153,13 +153,13 @@ namespace ImGui { onFFTRedraw.emit(args); // X Axis - window->DrawList->AddLine(ImVec2(widgetPos.x + 50, widgetPos.y + fftHeight + 10), - ImVec2(widgetPos.x + dataWidth + 50, widgetPos.y + fftHeight + 10), - text, 1.0); + window->DrawList->AddLine(ImVec2(widgetPos.x + 50, widgetPos.y + fftHeight + 10), + ImVec2(widgetPos.x + dataWidth + 50, widgetPos.y + fftHeight + 10), + text, 1.0); // Y Axis - window->DrawList->AddLine(ImVec2(widgetPos.x + 50, widgetPos.y + 9), - ImVec2(widgetPos.x + 50, widgetPos.y + fftHeight + 9), - text, 1.0); + window->DrawList->AddLine(ImVec2(widgetPos.x + 50, widgetPos.y + 9), + ImVec2(widgetPos.x + 50, widgetPos.y + fftHeight + 9), + text, 1.0); } void WaterFall::drawWaterfall() { @@ -210,8 +210,8 @@ namespace ImGui { ImVec2 dragOrigin(mousePos.x - drag.x, mousePos.y - drag.y); bool mouseHovered, mouseHeld; - bool mouseClicked = ImGui::ButtonBehavior(ImRect(fftAreaMin, wfMax), GetID("WaterfallID"), &mouseHovered, &mouseHeld, - ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_PressedOnClick); + bool mouseClicked = ImGui::ButtonBehavior(ImRect(fftAreaMin, wfMax), GetID("WaterfallID"), &mouseHovered, &mouseHeld, + ImGuiButtonFlags_MouseButtonLeft | ImGuiButtonFlags_PressedOnClick); mouseInFFTResize = (dragOrigin.x > widgetPos.x && dragOrigin.x < widgetPos.x + widgetSize.x && dragOrigin.y >= widgetPos.y + newFFTAreaHeight - 2 && dragOrigin.y <= widgetPos.y + newFFTAreaHeight + 2); mouseInFreq = IS_IN_AREA(dragOrigin, freqAreaMin, freqAreaMax); @@ -268,12 +268,16 @@ namespace ImGui { bool resizing = false; if (_vfo->reference != REF_LOWER) { if (IS_IN_AREA(mousePos, _vfo->lbwSelMin, _vfo->lbwSelMax)) { resizing = true; } - else if (IS_IN_AREA(mousePos, _vfo->wfLbwSelMin, _vfo->wfLbwSelMax)) { resizing = true; } + else if (IS_IN_AREA(mousePos, _vfo->wfLbwSelMin, _vfo->wfLbwSelMax)) { + resizing = true; + } } if (_vfo->reference != REF_UPPER) { if (IS_IN_AREA(mousePos, _vfo->rbwSelMin, _vfo->rbwSelMax)) { resizing = true; } - else if (IS_IN_AREA(mousePos, _vfo->wfRbwSelMin, _vfo->wfRbwSelMax)) { resizing = true; } - } + else if (IS_IN_AREA(mousePos, _vfo->wfRbwSelMin, _vfo->wfRbwSelMax)) { + resizing = true; + } + } if (!resizing) { continue; } relatedVfo = _vfo; vfoBorderSelect = true; @@ -300,7 +304,7 @@ namespace ImGui { ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeNS); newFFTAreaHeight = mousePos.y - widgetPos.y; newFFTAreaHeight = std::clamp(newFFTAreaHeight, 150, widgetSize.y - 50); - ImGui::GetForegroundDrawList()->AddLine(ImVec2(widgetPos.x, newFFTAreaHeight + widgetPos.y), ImVec2(widgetEndPos.x, newFFTAreaHeight + widgetPos.y), + ImGui::GetForegroundDrawList()->AddLine(ImVec2(widgetPos.x, newFFTAreaHeight + widgetPos.y), ImVec2(widgetEndPos.x, newFFTAreaHeight + widgetPos.y), ImGui::GetColorU32(ImGuiCol_SeparatorActive)); return; } @@ -386,7 +390,7 @@ namespace ImGui { // If the left and right keys are pressed while hovering the freq scale, move it too bool leftKeyPressed = ImGui::IsKeyPressed(GLFW_KEY_LEFT); if ((leftKeyPressed || ImGui::IsKeyPressed(GLFW_KEY_RIGHT)) && mouseInFreq) { - viewOffset += leftKeyPressed ? (viewBandwidth / 20.0) : (-viewBandwidth / 20.0); + viewOffset += leftKeyPressed ? (viewBandwidth / 20.0) : (-viewBandwidth / 20.0); if (viewOffset + (viewBandwidth / 2.0) > wholeBandwidth / 2.0) { double freqOffset = (viewOffset + (viewBandwidth / 2.0)) - (wholeBandwidth / 2.0); @@ -412,7 +416,7 @@ namespace ImGui { } // Finally, if nothing else was selected, just move the VFO - if ((VFOMoveSingleClick ? ImGui::IsMouseClicked(ImGuiMouseButton_Left) : ImGui::IsMouseDown(ImGuiMouseButton_Left)) && (mouseInFFT|mouseInWaterfall) && (mouseMoved || hoveredVFOName == "")) { + if ((VFOMoveSingleClick ? ImGui::IsMouseClicked(ImGuiMouseButton_Left) : ImGui::IsMouseDown(ImGuiMouseButton_Left)) && (mouseInFFT | mouseInWaterfall) && (mouseMoved || hoveredVFOName == "")) { if (selVfo != NULL) { int refCenter = mousePos.x - (widgetPos.x + 50); if (refCenter >= 0 && refCenter < dataWidth) { @@ -509,13 +513,13 @@ namespace ImGui { // Calculate FFT index data double vfoMinSizeFreq = _vfo->centerOffset - _vfo->bandwidth; - double vfoMinFreq = _vfo->centerOffset - (_vfo->bandwidth/2.0); - double vfoMaxFreq = _vfo->centerOffset + (_vfo->bandwidth/2.0); + double vfoMinFreq = _vfo->centerOffset - (_vfo->bandwidth / 2.0); + double vfoMaxFreq = _vfo->centerOffset + (_vfo->bandwidth / 2.0); double vfoMaxSizeFreq = _vfo->centerOffset + _vfo->bandwidth; - int vfoMinSideOffset = std::clamp(((vfoMinSizeFreq / (wholeBandwidth/2.0)) * (double)(rawFFTSize/2)) + (rawFFTSize/2), 0, rawFFTSize); - int vfoMinOffset = std::clamp(((vfoMinFreq / (wholeBandwidth/2.0)) * (double)(rawFFTSize/2)) + (rawFFTSize/2), 0, rawFFTSize); - int vfoMaxOffset = std::clamp(((vfoMaxFreq / (wholeBandwidth/2.0)) * (double)(rawFFTSize/2)) + (rawFFTSize/2), 0, rawFFTSize); - int vfoMaxSideOffset = std::clamp(((vfoMaxSizeFreq / (wholeBandwidth/2.0)) * (double)(rawFFTSize/2)) + (rawFFTSize/2), 0, rawFFTSize); + int vfoMinSideOffset = std::clamp(((vfoMinSizeFreq / (wholeBandwidth / 2.0)) * (double)(rawFFTSize / 2)) + (rawFFTSize / 2), 0, rawFFTSize); + int vfoMinOffset = std::clamp(((vfoMinFreq / (wholeBandwidth / 2.0)) * (double)(rawFFTSize / 2)) + (rawFFTSize / 2), 0, rawFFTSize); + int vfoMaxOffset = std::clamp(((vfoMaxFreq / (wholeBandwidth / 2.0)) * (double)(rawFFTSize / 2)) + (rawFFTSize / 2), 0, rawFFTSize); + int vfoMaxSideOffset = std::clamp(((vfoMaxSizeFreq / (wholeBandwidth / 2.0)) * (double)(rawFFTSize / 2)) + (rawFFTSize / 2), 0, rawFFTSize); double avg = 0; float max = -INFINITY; @@ -601,7 +605,7 @@ namespace ImGui { else { bpBottom = widgetPos.y + height + 10; } - + for (int i = 0; i < count; i++) { start = bandplan->bands[i].start; @@ -637,20 +641,20 @@ namespace ImGui { bPos = widgetPos.x + 51; } if (width >= 1.0) { - window->DrawList->AddRectFilled(ImVec2(roundf(aPos), bpBottom - height), - ImVec2(roundf(bPos), bpBottom), colorTrans); + window->DrawList->AddRectFilled(ImVec2(roundf(aPos), bpBottom - height), + ImVec2(roundf(bPos), bpBottom), colorTrans); if (startVis) { - window->DrawList->AddLine(ImVec2(roundf(aPos), bpBottom - height - 1), - ImVec2(roundf(aPos), bpBottom - 1), color); + window->DrawList->AddLine(ImVec2(roundf(aPos), bpBottom - height - 1), + ImVec2(roundf(aPos), bpBottom - 1), color); } if (endVis) { - window->DrawList->AddLine(ImVec2(roundf(bPos), bpBottom - height - 1), - ImVec2(roundf(bPos), bpBottom - 1), color); + window->DrawList->AddLine(ImVec2(roundf(bPos), bpBottom - height - 1), + ImVec2(roundf(bPos), bpBottom - 1), color); } } if (txtSz.x <= width) { - window->DrawList->AddText(ImVec2(cPos - (txtSz.x / 2.0), bpBottom - (height / 2.0f) - (txtSz.y / 2.0f)), - IM_COL32(255, 255, 255, 255), bandplan->bands[i].name.c_str()); + window->DrawList->AddText(ImVec2(cPos - (txtSz.x / 2.0), bpBottom - (height / 2.0f) - (txtSz.y / 2.0f)), + IM_COL32(255, 255, 255, 255), bandplan->bands[i].name.c_str()); } } } @@ -682,7 +686,7 @@ namespace ImGui { waterfallHeight = widgetSize.y - fftHeight - 52; } else { - fftHeight = widgetSize.y - 50; + fftHeight = widgetSize.y - 50; } dataWidth = widgetSize.x - 60.0; @@ -766,7 +770,7 @@ namespace ImGui { //window->DrawList->AddRectFilled(widgetPos, widgetEndPos, IM_COL32( 0, 0, 0, 255 )); ImU32 bg = ImGui::ColorConvertFloat4ToU32(gui::themeManager.waterfallBg); window->DrawList->AddRectFilled(widgetPos, widgetEndPos, bg); - window->DrawList->AddRect(widgetPos, widgetEndPos, IM_COL32( 50, 50, 50, 255 )); + window->DrawList->AddRect(widgetPos, widgetEndPos, IM_COL32(50, 50, 50, 255)); window->DrawList->AddLine(ImVec2(widgetPos.x, widgetPos.y + fftHeight + 50), ImVec2(widgetPos.x + widgetSize.x, widgetPos.y + fftHeight + 50), IM_COL32(50, 50, 50, 255), 1.0); if (!gui::mainWindow.lockWaterfallControls) { @@ -787,7 +791,7 @@ namespace ImGui { } updateAllVFOs(true); - + drawFFT(); if (waterfallVisible) { drawWaterfall(); @@ -823,7 +827,7 @@ namespace ImGui { double offsetRatio = viewOffset / (wholeBandwidth / 2.0); int drawDataSize = (viewBandwidth / wholeBandwidth) * rawFFTSize; int drawDataStart = (((double)rawFFTSize / 2.0) * (offsetRatio + 1)) - (drawDataSize / 2); - + // If in fast mode, apply IIR filtering float* buf = &rawFFTs[currentFFTLine * rawFFTSize]; if (_fastFFT) { @@ -855,7 +859,7 @@ namespace ImGui { float dummy; calculateVFOSignalInfo(waterfallVisible ? &rawFFTs[currentFFTLine * rawFFTSize] : rawFFTs, vfos[selectedVFO], dummy, selectedVFOSNR); } - + buf_mtx.unlock(); } @@ -982,7 +986,7 @@ namespace ImGui { double WaterFall::getViewOffset() { return viewOffset; } - + void WaterFall::setFFTMin(float min) { fftMin = min; vRange = findBestRange(fftMax - fftMin, maxVSteps); @@ -1138,7 +1142,6 @@ namespace ImGui { } reference = ref; setOffset(generalOffset); - } void WaterfallVFO::updateDrawingVars(double viewBandwidth, float dataWidth, double viewOffset, ImVec2 widgetPos, int fftHeight) { @@ -1202,18 +1205,22 @@ namespace ImGui { if (rectMax.x - rectMin.x < 10) { return; } if (reference != REF_LOWER && !bandwidthLocked && !leftClamped) { if (IS_IN_AREA(mousePos, lbwSelMin, lbwSelMax)) { ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); } - else if (IS_IN_AREA(mousePos, wfLbwSelMin, wfLbwSelMax)) { ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); } + else if (IS_IN_AREA(mousePos, wfLbwSelMin, wfLbwSelMax)) { + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); + } } if (reference != REF_UPPER && !bandwidthLocked && !rightClamped) { if (IS_IN_AREA(mousePos, rbwSelMin, rbwSelMax)) { ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); } - else if (IS_IN_AREA(mousePos, wfRbwSelMin, wfRbwSelMax)) { ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); } + else if (IS_IN_AREA(mousePos, wfRbwSelMin, wfRbwSelMax)) { + ImGui::SetMouseCursor(ImGuiMouseCursor_ResizeEW); + } } } }; void WaterFall::showWaterfall() { buf_mtx.lock(); - if (rawFFTs == NULL) { + if (rawFFTs == NULL) { spdlog::error("Null rawFFT"); } waterfallVisible = true; @@ -1237,7 +1244,7 @@ namespace ImGui { onResize(); buf_mtx.unlock(); } - + int WaterFall::getFFTHeight() { return FFTAreaHeight; } @@ -1254,4 +1261,3 @@ namespace ImGui { snapInterval = interval; } }; - diff --git a/core/src/gui/widgets/waterfall.h b/core/src/gui/widgets/waterfall.h index 0cbc4e4e..64c0fdf1 100644 --- a/core/src/gui/widgets/waterfall.h +++ b/core/src/gui/widgets/waterfall.h @@ -7,7 +7,7 @@ #include #include -#define WATERFALL_RESOLUTION 1000000 +#define WATERFALL_RESOLUTION 1000000 namespace ImGui { class WaterfallVFO { @@ -244,7 +244,7 @@ namespace ImGui { bool waterfallUpdate = false; uint32_t waterfallPallet[WATERFALL_RESOLUTION]; - + ImVec2 widgetPos; ImVec2 widgetEndPos; ImVec2 widgetSize; @@ -270,9 +270,9 @@ namespace ImGui { int maxVSteps; int maxHSteps; - int dataWidth; // Width of the FFT and waterfall - int fftHeight; // Height of the fft graph - int waterfallHeight = 0; // Height of the waterfall + int dataWidth; // Width of the FFT and waterfall + int fftHeight; // Height of the fft graph + int waterfallHeight = 0; // Height of the waterfall double viewBandwidth; double viewOffset; diff --git a/core/src/module.cpp b/core/src/module.cpp index 7d932404..1889ba68 100644 --- a/core/src/module.cpp +++ b/core/src/module.cpp @@ -22,10 +22,10 @@ ModuleManager::Module_t ModuleManager::loadModule(std::string path) { return mod; } mod.info = (ModuleInfo_t*)GetProcAddress(mod.handle, "_INFO_"); - mod.init = (void(*)())GetProcAddress(mod.handle, "_INIT_"); - mod.createInstance = (Instance*(*)(std::string))GetProcAddress(mod.handle, "_CREATE_INSTANCE_"); - mod.deleteInstance = (void(*)(Instance*))GetProcAddress(mod.handle, "_DELETE_INSTANCE_"); - mod.end = (void(*)())GetProcAddress(mod.handle, "_END_"); + mod.init = (void (*)())GetProcAddress(mod.handle, "_INIT_"); + mod.createInstance = (Instance * (*)(std::string)) GetProcAddress(mod.handle, "_CREATE_INSTANCE_"); + mod.deleteInstance = (void (*)(Instance*))GetProcAddress(mod.handle, "_DELETE_INSTANCE_"); + mod.end = (void (*)())GetProcAddress(mod.handle, "_END_"); #else mod.handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL); if (mod.handle == NULL) { @@ -34,10 +34,10 @@ ModuleManager::Module_t ModuleManager::loadModule(std::string path) { return mod; } mod.info = (ModuleInfo_t*)dlsym(mod.handle, "_INFO_"); - mod.init = (void(*)())dlsym(mod.handle, "_INIT_"); - mod.createInstance = (Instance*(*)(std::string))dlsym(mod.handle, "_CREATE_INSTANCE_"); - mod.deleteInstance = (void(*)(Instance*))dlsym(mod.handle, "_DELETE_INSTANCE_"); - mod.end = (void(*)())dlsym(mod.handle, "_END_"); + mod.init = (void (*)())dlsym(mod.handle, "_INIT_"); + mod.createInstance = (Instance * (*)(std::string)) dlsym(mod.handle, "_CREATE_INSTANCE_"); + mod.deleteInstance = (void (*)(Instance*))dlsym(mod.handle, "_DELETE_INSTANCE_"); + mod.end = (void (*)())dlsym(mod.handle, "_END_"); #endif if (mod.info == NULL) { spdlog::error("{0} is missing _INFO_ symbol", path); @@ -107,7 +107,7 @@ int ModuleManager::deleteInstance(std::string name) { return -1; } onInstanceDelete.emit(name); - Instance_t inst = instances[name]; + Instance_t inst = instances[name]; inst.module.deleteInstance(inst.instance); instances.erase(name); onInstanceDeleted.emit(name); diff --git a/core/src/module.h b/core/src/module.h index 710a0215..5e6fd9d1 100644 --- a/core/src/module.h +++ b/core/src/module.h @@ -15,17 +15,17 @@ #endif #ifdef _WIN32 - #include - #define MOD_EXPORT extern "C" __declspec(dllexport) - #define SDRPP_MOD_EXTENTSION ".dll" +#include +#define MOD_EXPORT extern "C" __declspec(dllexport) +#define SDRPP_MOD_EXTENTSION ".dll" #else - #include - #define MOD_EXPORT extern "C" - #ifdef __APPLE__ - #define SDRPP_MOD_EXTENTSION ".dylib" - #else - #define SDRPP_MOD_EXTENTSION ".so" - #endif +#include +#define MOD_EXPORT extern "C" +#ifdef __APPLE__ +#define SDRPP_MOD_EXTENTSION ".dylib" +#else +#define SDRPP_MOD_EXTENTSION ".so" +#endif #endif class ModuleManager { @@ -98,7 +98,6 @@ public: std::map modules; std::map instances; - }; -#define SDRPP_MOD_INFO MOD_EXPORT const ModuleManager::ModuleInfo_t _INFO_ \ No newline at end of file +#define SDRPP_MOD_INFO MOD_EXPORT const ModuleManager::ModuleInfo_t _INFO_ \ No newline at end of file diff --git a/core/src/options.cpp b/core/src/options.cpp index 1418541d..38d14da0 100644 --- a/core/src/options.cpp +++ b/core/src/options.cpp @@ -18,7 +18,7 @@ namespace options { #endif } - bool parse(int argc, char *argv[]) { + bool parse(int argc, char* argv[]) { for (int i = 1; i < argc; i++) { char* arg = argv[i]; if (!strcmp(arg, "-r") || !strcmp(arg, "--root")) { diff --git a/core/src/options.h b/core/src/options.h index f1736033..8ada592f 100644 --- a/core/src/options.h +++ b/core/src/options.h @@ -12,5 +12,5 @@ namespace options { SDRPP_EXPORT CMDLineOptions opts; void loadDefaults(); - bool parse(int argc, char *argv[]); + bool parse(int argc, char* argv[]); } \ No newline at end of file diff --git a/core/src/signal_path/dsp.cpp b/core/src/signal_path/dsp.cpp index 7cf9cb98..54c476df 100644 --- a/core/src/signal_path/dsp.cpp +++ b/core/src/signal_path/dsp.cpp @@ -2,10 +2,9 @@ #include SignalPath::SignalPath() { - } -void SignalPath::init(uint64_t sampleRate, int fftRate, int fftSize, dsp::stream* input, dsp::complex_t* fftBuffer, void fftHandler(dsp::complex_t*,int,void*), void* fftHandlerCtx) { +void SignalPath::init(uint64_t sampleRate, int fftRate, int fftSize, dsp::stream* input, dsp::complex_t* fftBuffer, void fftHandler(dsp::complex_t*, int, void*), void* fftHandlerCtx) { this->sampleRate = sampleRate; this->sourceSampleRate = sampleRate; this->fftRate = fftRate; @@ -179,12 +178,12 @@ void SignalPath::setDecimation(int dec) { else { split.setInput(&inputBuffer.out); } - + if (running) { split.start(); } core::setInputSampleRate(sourceSampleRate); return; } - + // Create new decimators for (int i = 0; i < dec; i++) { dsp::HalfDecimator* decimator; @@ -195,13 +194,13 @@ void SignalPath::setDecimation(int dec) { decimator = new dsp::HalfDecimator(&inputBuffer.out, &halfBandWindow); } else { - decimator = new dsp::HalfDecimator(&decimators[i-1]->out, &halfBandWindow); + decimator = new dsp::HalfDecimator(&decimators[i - 1]->out, &halfBandWindow); } - + if (running) { decimator->start(); } decimators.push_back(decimator); } - split.setInput(&decimators[decimators.size()-1]->out); + split.setInput(&decimators[decimators.size() - 1]->out); if (running) { split.start(); } // Update the DSP sample rate @@ -247,12 +246,12 @@ void SignalPath::setFFTWindow(int win) { void SignalPath::generateFFTWindow(int win, float* taps, int size) { if (win == FFT_WINDOW_RECTANGULAR) { for (int i = 0; i < size; i++) { - taps[i] = (i%2) ? 1 : -1; + taps[i] = (i % 2) ? 1 : -1; } } else if (win == FFT_WINDOW_BLACKMAN) { for (int i = 0; i < size; i++) { - taps[i] = ((i%2) ? dsp::window_function::blackman(i, size) : -dsp::window_function::blackman(i, size))*2; + taps[i] = ((i % 2) ? dsp::window_function::blackman(i, size) : -dsp::window_function::blackman(i, size)) * 2; } } } diff --git a/core/src/signal_path/dsp.h b/core/src/signal_path/dsp.h index 59f1f02d..30fe46bb 100644 --- a/core/src/signal_path/dsp.h +++ b/core/src/signal_path/dsp.h @@ -15,7 +15,7 @@ enum { class SignalPath { public: SignalPath(); - void init(uint64_t sampleRate, int fftRate, int fftSize, dsp::stream* input, dsp::complex_t* fftBuffer, void fftHandler(dsp::complex_t*,int,void*), void* fftHandlerCtx); + void init(uint64_t sampleRate, int fftRate, int fftSize, dsp::stream* input, dsp::complex_t* fftBuffer, void fftHandler(dsp::complex_t*, int, void*), void* fftHandlerCtx); void start(); void stop(); void setSampleRate(double sampleRate); diff --git a/core/src/signal_path/sink.cpp b/core/src/signal_path/sink.cpp index 7902e777..7f62838f 100644 --- a/core/src/signal_path/sink.cpp +++ b/core/src/signal_path/sink.cpp @@ -32,7 +32,7 @@ void SinkManager::Stream::start() { if (running) { return; } - + splitter.start(); volumeAjust.start(); sink->start(); @@ -113,7 +113,7 @@ void SinkManager::unregisterSinkProvider(std::string name) { } onSinkProviderUnregister.emit(name); - + // Switch all sinks using it to a null sink for (auto& [streamName, stream] : streams) { if (providerNames[stream->providerId] != name) { continue; } @@ -344,7 +344,7 @@ void SinkManager::showMenu() { float menuWidth = ImGui::GetContentRegionAvailWidth(); int count = 0; int maxCount = streams.size(); - + std::string provStr = ""; for (auto const& name : providerNames) { provStr += name; diff --git a/core/src/signal_path/sink.h b/core/src/signal_path/sink.h index b1f68690..e45c3241 100644 --- a/core/src/signal_path/sink.h +++ b/core/src/signal_path/sink.h @@ -48,7 +48,7 @@ public: dsp::stream* sinkOut; - Event srChange; + Event srChange; private: dsp::stream* _in; @@ -86,7 +86,6 @@ public: private: dsp::NullSink ns; - }; void registerSinkProvider(std::string name, SinkProvider provider); @@ -130,5 +129,4 @@ private: std::vector providerNames; std::string providerNamesTxt; std::vector streamNames; - }; \ No newline at end of file diff --git a/core/src/signal_path/source.cpp b/core/src/signal_path/source.cpp index 5a7a43ee..13d72186 100644 --- a/core/src/signal_path/source.cpp +++ b/core/src/signal_path/source.cpp @@ -3,7 +3,6 @@ #include SourceManager::SourceManager() { - } void SourceManager::registerSource(std::string name, SourceHandler* handler) { @@ -34,11 +33,11 @@ void SourceManager::unregisterSource(std::string name) { std::vector SourceManager::getSourceNames() { std::vector names; - for (auto const& [name, src] : sources) { names.push_back(name); } + for (auto const& [name, src] : sources) { names.push_back(name); } return names; } -void SourceManager::selectSource(std::string name) { +void SourceManager::selectSource(std::string name) { if (sources.find(name) == sources.end()) { spdlog::error("Tried to select non existent source: {0}", name); return; diff --git a/core/src/signal_path/source.h b/core/src/signal_path/source.h index 1d692fa5..887a0f7d 100644 --- a/core/src/signal_path/source.h +++ b/core/src/signal_path/source.h @@ -23,7 +23,7 @@ public: void registerSource(std::string name, SourceHandler* handler); void unregisterSource(std::string name); - void selectSource(std::string name); + void selectSource(std::string name); void showSelectedMenu(); void start(); void stop(); @@ -43,5 +43,4 @@ private: double tuneOffset; double currentFreq; dsp::stream nullSource; - }; \ No newline at end of file diff --git a/core/src/signal_path/vfo_manager.cpp b/core/src/signal_path/vfo_manager.cpp index 6eb26c6e..5fe8df6e 100644 --- a/core/src/signal_path/vfo_manager.cpp +++ b/core/src/signal_path/vfo_manager.cpp @@ -87,7 +87,6 @@ std::string VFOManager::VFO::getName() { } VFOManager::VFOManager() { - } VFOManager::VFO* VFOManager::createVFO(std::string name, int reference, double offset, double bandwidth, double sampleRate, double minBandwidth, double maxBandwidth, bool bandwidthLocked) { @@ -187,7 +186,7 @@ int VFOManager::getReference(std::string name) { return vfos[name]->getReference(); } -void VFOManager::setColor(std::string name, ImU32 color) { +void VFOManager::setColor(std::string name, ImU32 color) { if (vfos.find(name) == vfos.end()) { return; } diff --git a/core/src/signal_path/vfo_manager.h b/core/src/signal_path/vfo_manager.h index e932eb1f..6a0d1762 100644 --- a/core/src/signal_path/vfo_manager.h +++ b/core/src/signal_path/vfo_manager.h @@ -35,7 +35,6 @@ public: private: std::string name; - }; VFOManager::VFO* createVFO(std::string name, int reference, double offset, double bandwidth, double sampleRate, double minBandwidth, double maxBandwidth, bool bandwidthLocked); diff --git a/core/src/utils/color.h b/core/src/utils/color.h index 450dbaa7..64cbc178 100644 --- a/core/src/utils/color.h +++ b/core/src/utils/color.h @@ -11,9 +11,15 @@ namespace color { // Calculate the hue if (delta == 0) { h = 0; } - else if (r > g && r > b) { h = 60.0f * fmodf((g - b) / delta, 6.0f); } - else if (g > r && g > b) { h = 60.0f * (((b - r) / delta) + 2.0f); } - else { h = 60.0f * (((r - g) / delta) + 4.0f); } + else if (r > g && r > b) { + h = 60.0f * fmodf((g - b) / delta, 6.0f); + } + else if (g > r && g > b) { + h = 60.0f * (((b - r) / delta) + 2.0f); + } + else { + h = 60.0f * (((r - g) / delta) + 4.0f); + } // Calculate lightness l = (cmin + cmax) / 2.0f; @@ -29,12 +35,36 @@ namespace color { float m = l - (c / 2.0f); // Affect coefficients to R, G or B depending on hue - if (h < 60) { r = c; g = x; b = 0; } - else if (h < 120) { r = x; g = c; b = 0; } - else if (h < 180) { r = 0; g = c; b = x; } - else if (h < 240) { r = 0; g = x; b = c; } - else if (h < 300) { r = x; g = 0; b = c; } - else { r = c; g = 0; b = x; } + if (h < 60) { + r = c; + g = x; + b = 0; + } + else if (h < 120) { + r = x; + g = c; + b = 0; + } + else if (h < 180) { + r = 0; + g = c; + b = x; + } + else if (h < 240) { + r = 0; + g = x; + b = c; + } + else if (h < 300) { + r = x; + g = 0; + b = c; + } + else { + r = c; + g = 0; + b = x; + } // Add m r += m; diff --git a/core/src/utils/event.h b/core/src/utils/event.h index 1df0354b..cf7c72ae 100644 --- a/core/src/utils/event.h +++ b/core/src/utils/event.h @@ -40,5 +40,4 @@ public: private: std::vector*> handlers; - }; \ No newline at end of file diff --git a/core/src/utils/freq_formatting.h b/core/src/utils/freq_formatting.h index f18a6cc9..716ef1c3 100644 --- a/core/src/utils/freq_formatting.h +++ b/core/src/utils/freq_formatting.h @@ -9,7 +9,10 @@ namespace utils { int len = strlen(str) - 1; while ((str[len] == '0' || str[len] == '.') && len > 0) { len--; - if (str[len] == '.') { len--; break; } + if (str[len] == '.') { + len--; + break; + } } return std::string(str).substr(0, len + 1) + "MHz"; } @@ -18,7 +21,10 @@ namespace utils { int len = strlen(str) - 1; while ((str[len] == '0' || str[len] == '.') && len > 0) { len--; - if (str[len] == '.') { len--; break; } + if (str[len] == '.') { + len--; + break; + } } return std::string(str).substr(0, len + 1) + "KHz"; } @@ -27,7 +33,10 @@ namespace utils { int len = strlen(str) - 1; while ((str[len] == '0' || str[len] == '.') && len > 0) { len--; - if (str[len] == '.') { len--; break; } + if (str[len] == '.') { + len--; + break; + } } return std::string(str).substr(0, len + 1) + "Hz"; } diff --git a/core/src/utils/networking.cpp b/core/src/utils/networking.cpp index b86fb887..08f9d264 100644 --- a/core/src/utils/networking.cpp +++ b/core/src/utils/networking.cpp @@ -15,7 +15,7 @@ namespace net { readWorkerThread = std::thread(&ConnClass::readWorker, this); writeWorkerThread = std::thread(&ConnClass::writeWorker, this); } - + ConnClass::~ConnClass() { ConnClass::close(); } @@ -28,7 +28,7 @@ namespace net { std::lock_guard lck2(writeQueueMtx); stopWorkers = true; } - + // Notify the workers of the change readQueueCnd.notify_all(); writeQueueCnd.notify_all(); @@ -59,7 +59,7 @@ namespace net { void ConnClass::waitForEnd() { std::unique_lock lck(readQueueMtx); - connectionOpenCnd.wait(lck, [this](){ return !connectionOpen; }); + connectionOpenCnd.wait(lck, [this]() { return !connectionOpen; }); } int ConnClass::read(int count, uint8_t* buf) { @@ -148,7 +148,7 @@ namespace net { while (true) { // Wait for wakeup and exit if it's for terminating the thread std::unique_lock lck(readQueueMtx); - readQueueCnd.wait(lck, [this](){ return (readQueue.size() > 0 || stopWorkers); }); + readQueueCnd.wait(lck, [this]() { return (readQueue.size() > 0 || stopWorkers); }); if (stopWorkers || !connectionOpen) { return; } // Pop first element off the list @@ -174,7 +174,7 @@ namespace net { while (true) { // Wait for wakeup and exit if it's for terminating the thread std::unique_lock lck(writeQueueMtx); - writeQueueCnd.wait(lck, [this](){ return (writeQueue.size() > 0 || stopWorkers); }); + writeQueueCnd.wait(lck, [this]() { return (writeQueue.size() > 0 || stopWorkers); }); if (stopWorkers || !connectionOpen) { return; } // Pop first element off the list @@ -261,7 +261,6 @@ namespace net { if (acceptWorkerThread.joinable()) { acceptWorkerThread.join(); } - listening = false; } @@ -273,7 +272,7 @@ namespace net { while (true) { // Wait for wakeup and exit if it's for terminating the thread std::unique_lock lck(acceptQueueMtx); - acceptQueueCnd.wait(lck, [this](){ return (acceptQueue.size() > 0 || stopWorker); }); + acceptQueueCnd.wait(lck, [this]() { return (acceptQueue.size() > 0 || stopWorker); }); if (stopWorker || !listening) { return; } // Pop first element off the list @@ -299,13 +298,13 @@ namespace net { Conn connect(std::string host, uint16_t port) { - Socket sock; + Socket sock; #ifdef _WIN32 // Initialize WinSock2 if (!winsock_init) { WSADATA wsa; - if (WSAStartup(MAKEWORD(2,2),&wsa)) { + if (WSAStartup(MAKEWORD(2, 2), &wsa)) { throw std::runtime_error("Could not initialize WinSock2"); return NULL; } @@ -330,12 +329,12 @@ namespace net { return NULL; } uint32_t* naddr = (uint32_t*)remoteHost->h_addr_list[0]; - + // Create host address struct sockaddr_in addr; addr.sin_addr.s_addr = *naddr; addr.sin_family = AF_INET; - addr.sin_port = htons(port); + addr.sin_port = htons(port); // Connect to host if (::connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) { @@ -353,7 +352,7 @@ namespace net { // Initialize WinSock2 if (!winsock_init) { WSADATA wsa; - if (WSAStartup(MAKEWORD(2,2),&wsa)) { + if (WSAStartup(MAKEWORD(2, 2), &wsa)) { throw std::runtime_error("Could not initialize WinSock2"); return NULL; } @@ -372,14 +371,14 @@ namespace net { } #ifndef _WIN32 - // Allow port reusing if the app was killed or crashed + // Allow port reusing if the app was killed or crashed // and the socket is stuck in TIME_WAIT state. - // This option has a different meaning on Windows, + // This option has a different meaning on Windows, // so we use it only for non-Windows systems int enable = 1; - if (setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof (int)) < 0) { + if (setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0) { throw std::runtime_error("Could not configure socket"); - return NULL; + return NULL; } #endif @@ -395,7 +394,7 @@ namespace net { struct sockaddr_in addr; addr.sin_addr.s_addr = *naddr; addr.sin_family = AF_INET; - addr.sin_port = htons(port); + addr.sin_port = htons(port); // Bind socket if (bind(listenSock, (struct sockaddr*)&addr, sizeof(addr)) < 0) { @@ -419,7 +418,7 @@ namespace net { // Initialize WinSock2 if (!winsock_init) { WSADATA wsa; - if (WSAStartup(MAKEWORD(2,2),&wsa)) { + if (WSAStartup(MAKEWORD(2, 2), &wsa)) { throw std::runtime_error("Could not initialize WinSock2"); return NULL; } @@ -455,15 +454,15 @@ namespace net { // Create host address struct sockaddr_in addr; - addr.sin_addr.s_addr = INADDR_ANY;//*naddr; + addr.sin_addr.s_addr = INADDR_ANY; //*naddr; addr.sin_family = AF_INET; - addr.sin_port = htons(port); + addr.sin_port = htons(port); // Create remote host address struct sockaddr_in raddr; raddr.sin_addr.s_addr = *rnaddr; raddr.sin_family = AF_INET; - raddr.sin_port = htons(remotePort); + raddr.sin_port = htons(remotePort); // Bind socket if (bindSocket) { @@ -473,7 +472,7 @@ namespace net { return NULL; } } - + return Conn(new ConnClass(sock, raddr, true)); } } \ No newline at end of file diff --git a/core/src/utils/networking.h b/core/src/utils/networking.h index e985b76a..1cd7534d 100644 --- a/core/src/utils/networking.h +++ b/core/src/utils/networking.h @@ -78,7 +78,6 @@ namespace net { Socket _sock; bool _udp; struct sockaddr_in remoteAddr; - }; typedef std::unique_ptr Conn; @@ -112,7 +111,6 @@ namespace net { std::thread acceptWorkerThread; Socket sock; - }; typedef std::unique_ptr Listener; diff --git a/core/src/utils/optionlist.h b/core/src/utils/optionlist.h index 21982c76..e541786b 100644 --- a/core/src/utils/optionlist.h +++ b/core/src/utils/optionlist.h @@ -95,7 +95,7 @@ public: return values[id]; } - T operator [](int& id) { + T operator[](int& id) { return value(id); } @@ -115,5 +115,4 @@ private: std::vector names; std::vector values; std::string _txt; - }; \ No newline at end of file diff --git a/decoder_modules/falcon9_decoder/src/falcon_fec.h b/decoder_modules/falcon9_decoder/src/falcon_fec.h index 560895d6..277acc4e 100644 --- a/decoder_modules/falcon9_decoder/src/falcon_fec.h +++ b/decoder_modules/falcon9_decoder/src/falcon_fec.h @@ -3,37 +3,36 @@ #include // WTF??? -extern "C" -{ +extern "C" { #include } -const uint8_t toDB[] = { -0x00, 0x7b, 0xaf, 0xd4, 0x99, 0xe2, 0x36, 0x4d, 0xfa, 0x81, 0x55, 0x2e, 0x63, 0x18, 0xcc, 0xb7, 0x86, 0xfd, 0x29, 0x52, 0x1f, - 0x64, 0xb0, 0xcb, 0x7c, 0x07, 0xd3, 0xa8, 0xe5, 0x9e, 0x4a, 0x31, 0xec, 0x97, 0x43, 0x38, 0x75, 0x0e, 0xda, 0xa1, 0x16, 0x6d, 0xb9, 0xc2, 0x8f, 0xf4, - 0x20, 0x5b, 0x6a, 0x11, 0xc5, 0xbe, 0xf3, 0x88, 0x5c, 0x27, 0x90, 0xeb, 0x3f, 0x44, 0x09, 0x72, 0xa6, 0xdd, 0xef, 0x94, 0x40, 0x3b, 0x76, 0x0d, 0xd9, - 0xa2, 0x15, 0x6e, 0xba, 0xc1, 0x8c, 0xf7, 0x23, 0x58, 0x69, 0x12, 0xc6, 0xbd, 0xf0, 0x8b, 0x5f, 0x24, 0x93, 0xe8, 0x3c, 0x47, 0x0a, 0x71, 0xa5, 0xde, - 0x03, 0x78, 0xac, 0xd7, 0x9a, 0xe1, 0x35, 0x4e, 0xf9, 0x82, 0x56, 0x2d, 0x60, 0x1b, 0xcf, 0xb4, 0x85, 0xfe, 0x2a, 0x51, 0x1c, 0x67, 0xb3, 0xc8, 0x7f, - 0x04, 0xd0, 0xab, 0xe6, 0x9d, 0x49, 0x32, 0x8d, 0xf6, 0x22, 0x59, 0x14, 0x6f, 0xbb, 0xc0, 0x77, 0x0c, 0xd8, 0xa3, 0xee, 0x95, 0x41, 0x3a, 0x0b, 0x70, - 0xa4, 0xdf, 0x92, 0xe9, 0x3d, 0x46, 0xf1, 0x8a, 0x5e, 0x25, 0x68, 0x13, 0xc7, 0xbc, 0x61, 0x1a, 0xce, 0xb5, 0xf8, 0x83, 0x57, 0x2c, 0x9b, 0xe0, 0x34, - 0x4f, 0x02, 0x79, 0xad, 0xd6, 0xe7, 0x9c, 0x48, 0x33, 0x7e, 0x05, 0xd1, 0xaa, 0x1d, 0x66, 0xb2, 0xc9, 0x84, 0xff, 0x2b, 0x50, 0x62, 0x19, 0xcd, 0xb6, - 0xfb, 0x80, 0x54, 0x2f, 0x98, 0xe3, 0x37, 0x4c, 0x01, 0x7a, 0xae, 0xd5, 0xe4, 0x9f, 0x4b, 0x30, 0x7d, 0x06, 0xd2, 0xa9, 0x1e, 0x65, 0xb1, 0xca, 0x87, - 0xfc, 0x28, 0x53, 0x8e, 0xf5, 0x21, 0x5a, 0x17, 0x6c, 0xb8, 0xc3, 0x74, 0x0f, 0xdb, 0xa0, 0xed, 0x96, 0x42, 0x39, 0x08, 0x73, 0xa7, 0xdc, 0x91, 0xea, - 0x3e, 0x45, 0xf2, 0x89, 0x5d, 0x26, 0x6b, 0x10, 0xc4, 0xbf +const uint8_t toDB[] = { + 0x00, 0x7b, 0xaf, 0xd4, 0x99, 0xe2, 0x36, 0x4d, 0xfa, 0x81, 0x55, 0x2e, 0x63, 0x18, 0xcc, 0xb7, 0x86, 0xfd, 0x29, 0x52, 0x1f, + 0x64, 0xb0, 0xcb, 0x7c, 0x07, 0xd3, 0xa8, 0xe5, 0x9e, 0x4a, 0x31, 0xec, 0x97, 0x43, 0x38, 0x75, 0x0e, 0xda, 0xa1, 0x16, 0x6d, 0xb9, 0xc2, 0x8f, 0xf4, + 0x20, 0x5b, 0x6a, 0x11, 0xc5, 0xbe, 0xf3, 0x88, 0x5c, 0x27, 0x90, 0xeb, 0x3f, 0x44, 0x09, 0x72, 0xa6, 0xdd, 0xef, 0x94, 0x40, 0x3b, 0x76, 0x0d, 0xd9, + 0xa2, 0x15, 0x6e, 0xba, 0xc1, 0x8c, 0xf7, 0x23, 0x58, 0x69, 0x12, 0xc6, 0xbd, 0xf0, 0x8b, 0x5f, 0x24, 0x93, 0xe8, 0x3c, 0x47, 0x0a, 0x71, 0xa5, 0xde, + 0x03, 0x78, 0xac, 0xd7, 0x9a, 0xe1, 0x35, 0x4e, 0xf9, 0x82, 0x56, 0x2d, 0x60, 0x1b, 0xcf, 0xb4, 0x85, 0xfe, 0x2a, 0x51, 0x1c, 0x67, 0xb3, 0xc8, 0x7f, + 0x04, 0xd0, 0xab, 0xe6, 0x9d, 0x49, 0x32, 0x8d, 0xf6, 0x22, 0x59, 0x14, 0x6f, 0xbb, 0xc0, 0x77, 0x0c, 0xd8, 0xa3, 0xee, 0x95, 0x41, 0x3a, 0x0b, 0x70, + 0xa4, 0xdf, 0x92, 0xe9, 0x3d, 0x46, 0xf1, 0x8a, 0x5e, 0x25, 0x68, 0x13, 0xc7, 0xbc, 0x61, 0x1a, 0xce, 0xb5, 0xf8, 0x83, 0x57, 0x2c, 0x9b, 0xe0, 0x34, + 0x4f, 0x02, 0x79, 0xad, 0xd6, 0xe7, 0x9c, 0x48, 0x33, 0x7e, 0x05, 0xd1, 0xaa, 0x1d, 0x66, 0xb2, 0xc9, 0x84, 0xff, 0x2b, 0x50, 0x62, 0x19, 0xcd, 0xb6, + 0xfb, 0x80, 0x54, 0x2f, 0x98, 0xe3, 0x37, 0x4c, 0x01, 0x7a, 0xae, 0xd5, 0xe4, 0x9f, 0x4b, 0x30, 0x7d, 0x06, 0xd2, 0xa9, 0x1e, 0x65, 0xb1, 0xca, 0x87, + 0xfc, 0x28, 0x53, 0x8e, 0xf5, 0x21, 0x5a, 0x17, 0x6c, 0xb8, 0xc3, 0x74, 0x0f, 0xdb, 0xa0, 0xed, 0x96, 0x42, 0x39, 0x08, 0x73, 0xa7, 0xdc, 0x91, 0xea, + 0x3e, 0x45, 0xf2, 0x89, 0x5d, 0x26, 0x6b, 0x10, 0xc4, 0xbf }; const uint8_t fromDB[] = { 0x00, 0xcc, 0xac, 0x60, 0x79, 0xb5, 0xd5, 0x19, 0xf0, 0x3c, 0x5c, 0x90, 0x89, 0x45, 0x25, 0xe9, 0xfd, 0x31, 0x51, 0x9d, - 0x84, 0x48, 0x28, 0xe4, 0x0d, 0xc1, 0xa1, 0x6d, 0x74, 0xb8, 0xd8, 0x14, 0x2e, 0xe2, 0x82, 0x4e, 0x57, 0x9b, 0xfb, 0x37, 0xde, 0x12, 0x72, 0xbe, 0xa7, - 0x6b, 0x0b, 0xc7, 0xd3, 0x1f, 0x7f, 0xb3, 0xaa, 0x66, 0x06, 0xca, 0x23, 0xef, 0x8f, 0x43, 0x5a, 0x96, 0xf6, 0x3a, 0x42, 0x8e, 0xee, 0x22, 0x3b, 0xf7, - 0x97, 0x5b, 0xb2, 0x7e, 0x1e, 0xd2, 0xcb, 0x07, 0x67, 0xab, 0xbf, 0x73, 0x13, 0xdf, 0xc6, 0x0a, 0x6a, 0xa6, 0x4f, 0x83, 0xe3, 0x2f, 0x36, 0xfa, 0x9a, - 0x56, 0x6c, 0xa0, 0xc0, 0x0c, 0x15, 0xd9, 0xb9, 0x75, 0x9c, 0x50, 0x30, 0xfc, 0xe5, 0x29, 0x49, 0x85, 0x91, 0x5d, 0x3d, 0xf1, 0xe8, 0x24, 0x44, 0x88, - 0x61, 0xad, 0xcd, 0x01, 0x18, 0xd4, 0xb4, 0x78, 0xc5, 0x09, 0x69, 0xa5, 0xbc, 0x70, 0x10, 0xdc, 0x35, 0xf9, 0x99, 0x55, 0x4c, 0x80, 0xe0, 0x2c, 0x38, - 0xf4, 0x94, 0x58, 0x41, 0x8d, 0xed, 0x21, 0xc8, 0x04, 0x64, 0xa8, 0xb1, 0x7d, 0x1d, 0xd1, 0xeb, 0x27, 0x47, 0x8b, 0x92, 0x5e, 0x3e, 0xf2, 0x1b, 0xd7, - 0xb7, 0x7b, 0x62, 0xae, 0xce, 0x02, 0x16, 0xda, 0xba, 0x76, 0x6f, 0xa3, 0xc3, 0x0f, 0xe6, 0x2a, 0x4a, 0x86, 0x9f, 0x53, 0x33, 0xff, 0x87, 0x4b, 0x2b, - 0xe7, 0xfe, 0x32, 0x52, 0x9e, 0x77, 0xbb, 0xdb, 0x17, 0x0e, 0xc2, 0xa2, 0x6e, 0x7a, 0xb6, 0xd6, 0x1a, 0x03, 0xcf, 0xaf, 0x63, 0x8a, 0x46, 0x26, 0xea, - 0xf3, 0x3f, 0x5f, 0x93, 0xa9, 0x65, 0x05, 0xc9, 0xd0, 0x1c, 0x7c, 0xb0, 0x59, 0x95, 0xf5, 0x39, 0x20, 0xec, 0x8c, 0x40, 0x54, 0x98, 0xf8, 0x34, 0x2d, - 0xe1, 0x81, 0x4d, 0xa4, 0x68, 0x08, 0xc4, 0xdd, 0x11, 0x71, 0xbd + 0x84, 0x48, 0x28, 0xe4, 0x0d, 0xc1, 0xa1, 0x6d, 0x74, 0xb8, 0xd8, 0x14, 0x2e, 0xe2, 0x82, 0x4e, 0x57, 0x9b, 0xfb, 0x37, 0xde, 0x12, 0x72, 0xbe, 0xa7, + 0x6b, 0x0b, 0xc7, 0xd3, 0x1f, 0x7f, 0xb3, 0xaa, 0x66, 0x06, 0xca, 0x23, 0xef, 0x8f, 0x43, 0x5a, 0x96, 0xf6, 0x3a, 0x42, 0x8e, 0xee, 0x22, 0x3b, 0xf7, + 0x97, 0x5b, 0xb2, 0x7e, 0x1e, 0xd2, 0xcb, 0x07, 0x67, 0xab, 0xbf, 0x73, 0x13, 0xdf, 0xc6, 0x0a, 0x6a, 0xa6, 0x4f, 0x83, 0xe3, 0x2f, 0x36, 0xfa, 0x9a, + 0x56, 0x6c, 0xa0, 0xc0, 0x0c, 0x15, 0xd9, 0xb9, 0x75, 0x9c, 0x50, 0x30, 0xfc, 0xe5, 0x29, 0x49, 0x85, 0x91, 0x5d, 0x3d, 0xf1, 0xe8, 0x24, 0x44, 0x88, + 0x61, 0xad, 0xcd, 0x01, 0x18, 0xd4, 0xb4, 0x78, 0xc5, 0x09, 0x69, 0xa5, 0xbc, 0x70, 0x10, 0xdc, 0x35, 0xf9, 0x99, 0x55, 0x4c, 0x80, 0xe0, 0x2c, 0x38, + 0xf4, 0x94, 0x58, 0x41, 0x8d, 0xed, 0x21, 0xc8, 0x04, 0x64, 0xa8, 0xb1, 0x7d, 0x1d, 0xd1, 0xeb, 0x27, 0x47, 0x8b, 0x92, 0x5e, 0x3e, 0xf2, 0x1b, 0xd7, + 0xb7, 0x7b, 0x62, 0xae, 0xce, 0x02, 0x16, 0xda, 0xba, 0x76, 0x6f, 0xa3, 0xc3, 0x0f, 0xe6, 0x2a, 0x4a, 0x86, 0x9f, 0x53, 0x33, 0xff, 0x87, 0x4b, 0x2b, + 0xe7, 0xfe, 0x32, 0x52, 0x9e, 0x77, 0xbb, 0xdb, 0x17, 0x0e, 0xc2, 0xa2, 0x6e, 0x7a, 0xb6, 0xd6, 0x1a, 0x03, 0xcf, 0xaf, 0x63, 0x8a, 0x46, 0x26, 0xea, + 0xf3, 0x3f, 0x5f, 0x93, 0xa9, 0x65, 0x05, 0xc9, 0xd0, 0x1c, 0x7c, 0xb0, 0x59, 0x95, 0xf5, 0x39, 0x20, 0xec, 0x8c, 0x40, 0x54, 0x98, 0xf8, 0x34, 0x2d, + 0xe1, 0x81, 0x4d, 0xa4, 0x68, 0x08, 0xc4, 0xdd, 0x11, 0x71, 0xbd }; const uint8_t randVals[] = { @@ -73,7 +72,7 @@ namespace dsp { for (int i = 0; i < 5; i++) { memset(outBuffers[i], 0, 255); } rs = correct_reed_solomon_create(correct_rs_primitive_polynomial_ccsds, 120, 11, 16); if (rs == NULL) { printf("Error creating the reed solomon decoder\n"); } - + generic_block::registerInput(_in); generic_block::registerOutput(&out); } @@ -85,29 +84,44 @@ namespace dsp { uint8_t* data = _in->readBuf + 4; // Deinterleave - for (int i = 0; i < 255*5; i++) { - buffers[i%5][i/5] = fromDB[data[i]]; + for (int i = 0; i < 255 * 5; i++) { + buffers[i % 5][i / 5] = fromDB[data[i]]; } // Reed the solomon :weary: int result = 0; result = correct_reed_solomon_decode(rs, buffers[0], 255, outBuffers[0]); - if (result == -1) { _in->flush(); return count; } + if (result == -1) { + _in->flush(); + return count; + } result = correct_reed_solomon_decode(rs, buffers[1], 255, outBuffers[1]); - if (result == -1) { _in->flush(); return count; } + if (result == -1) { + _in->flush(); + return count; + } result = correct_reed_solomon_decode(rs, buffers[2], 255, outBuffers[2]); - if (result == -1) { _in->flush(); return count; } + if (result == -1) { + _in->flush(); + return count; + } result = correct_reed_solomon_decode(rs, buffers[3], 255, outBuffers[3]); - if (result == -1) { _in->flush(); return count; } + if (result == -1) { + _in->flush(); + return count; + } result = correct_reed_solomon_decode(rs, buffers[4], 255, outBuffers[4]); - if (result == -1) { _in->flush(); return count; } - - // Reinterleave - for (int i = 0; i < 255*5; i++) { - out.writeBuf[i] = toDB[outBuffers[i%5][i/5]] ^ randVals[i % 255]; + if (result == -1) { + _in->flush(); + return count; } - out.swap(255*5); + // Reinterleave + for (int i = 0; i < 255 * 5; i++) { + out.writeBuf[i] = toDB[outBuffers[i % 5][i / 5]] ^ randVals[i % 255]; + } + + out.swap(255 * 5); _in->flush(); return count; @@ -120,8 +134,7 @@ namespace dsp { uint8_t buffers[5][255]; uint8_t outBuffers[5][255]; correct_reed_solomon* rs; - - stream* _in; + stream* _in; }; } \ No newline at end of file diff --git a/decoder_modules/falcon9_decoder/src/falcon_packet.h b/decoder_modules/falcon9_decoder/src/falcon_packet.h index e1d7aca9..e6886c5b 100644 --- a/decoder_modules/falcon9_decoder/src/falcon_packet.h +++ b/decoder_modules/falcon9_decoder/src/falcon_packet.h @@ -20,7 +20,7 @@ namespace dsp { void init(stream* in) { _in = in; - + generic_block::registerInput(_in); generic_block::registerOutput(&out); } @@ -56,7 +56,7 @@ namespace dsp { else if (header.packet == 2047) { printf("Wow, all data\n"); _in->flush(); - return count; + return count; } // Finish reading the last package and send it @@ -84,9 +84,8 @@ namespace dsp { packetRead = -1; break; } - - uint64_t pktId = ((uint64_t)data[i + 2] << 56) | ((uint64_t)data[i + 3] << 48) | ((uint64_t)data[i + 4] << 40) | ((uint64_t)data[i + 5] << 32) - | ((uint64_t)data[i + 6] << 24) | ((uint64_t)data[i + 7] << 16) | ((uint64_t)data[i + 8] << 8) | data[i + 9]; + + uint64_t pktId = ((uint64_t)data[i + 2] << 56) | ((uint64_t)data[i + 3] << 48) | ((uint64_t)data[i + 4] << 40) | ((uint64_t)data[i + 5] << 32) | ((uint64_t)data[i + 6] << 24) | ((uint64_t)data[i + 7] << 16) | ((uint64_t)data[i + 8] << 8) | data[i + 9]; // If the packet doesn't fit the frame, save and go to next frame if (dataLen - i < length) { @@ -99,7 +98,6 @@ namespace dsp { memcpy(out.writeBuf, &data[i], length); out.swap(length); i += length; - } _in->flush(); @@ -114,8 +112,7 @@ namespace dsp { int packetRead = -1; uint8_t packet[0x4008]; - - stream* _in; + stream* _in; }; } \ No newline at end of file diff --git a/decoder_modules/falcon9_decoder/src/main.cpp b/decoder_modules/falcon9_decoder/src/main.cpp index 160c5967..151ac351 100644 --- a/decoder_modules/falcon9_decoder/src/main.cpp +++ b/decoder_modules/falcon9_decoder/src/main.cpp @@ -23,9 +23,9 @@ #include -#define CONCAT(a, b) ((std::string(a) + b).c_str()) +#define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "falcon9_decoder", /* Description: */ "Falcon9 telemetry decoder for SDR++", /* Author: */ "Ryzerth", @@ -33,7 +33,7 @@ SDRPP_MOD_INFO { /* Max instances */ -1 }; -#define INPUT_SAMPLE_RATE 6000000 +#define INPUT_SAMPLE_RATE 6000000 std::ofstream file("output.ts"); @@ -84,7 +84,6 @@ public: } ~Falcon9DecoderModule() { - } void postInit() {} @@ -187,10 +186,9 @@ private: Falcon9DecoderModule* _this = (Falcon9DecoderModule*)ctx; uint16_t length = (((data[0] & 0b1111) << 8) | data[1]) + 2; - uint64_t pktId = ((uint64_t)data[2] << 56) | ((uint64_t)data[3] << 48) | ((uint64_t)data[4] << 40) | ((uint64_t)data[5] << 32) - | ((uint64_t)data[6] << 24) | ((uint64_t)data[7] << 16) | ((uint64_t)data[8] << 8) | data[9]; + uint64_t pktId = ((uint64_t)data[2] << 56) | ((uint64_t)data[3] << 48) | ((uint64_t)data[4] << 40) | ((uint64_t)data[5] << 32) | ((uint64_t)data[6] << 24) | ((uint64_t)data[7] << 16) | ((uint64_t)data[8] << 8) | data[9]; - if (pktId == 0x0117FE0800320303 || pktId == 0x0112FA0800320303) { + if (pktId == 0x0117FE0800320303 || pktId == 0x0112FA0800320303) { data[length - 2] = 0; _this->logsMtx.lock(); _this->gpsLogs += (char*)(data + 25); @@ -207,13 +205,13 @@ private: static void symSinkHandler(float* data, int count, void* ctx) { Falcon9DecoderModule* _this = (Falcon9DecoderModule*)ctx; float* buf = _this->symDiag.acquireBuffer(); - memcpy(buf, data, 1024*sizeof(float)); + memcpy(buf, data, 1024 * sizeof(float)); _this->symDiag.releaseBuffer(); } std::string name; bool enabled = true; - + bool logsVisible = false; std::mutex logsMtx; @@ -232,7 +230,7 @@ private: dsp::stream thrInput; dsp::Threshold thr; - uint8_t syncWord[32] = {0,0,0,1,1,0,1,0,1,1,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,0,1}; + uint8_t syncWord[32] = { 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1 }; dsp::Deframer deframe; dsp::FalconRS falconRS; dsp::FalconPacketSync pkt; @@ -243,7 +241,6 @@ private: VFOManager::VFO* vfo; ImGui::SymbolDiagram symDiag; - }; MOD_EXPORT void _INIT_() { diff --git a/decoder_modules/m17_decoder/src/base40.cpp b/decoder_modules/m17_decoder/src/base40.cpp index 61ae84c9..4c7a5a17 100644 --- a/decoder_modules/m17_decoder/src/base40.cpp +++ b/decoder_modules/m17_decoder/src/base40.cpp @@ -1,11 +1,11 @@ #include -void decode_callsign_base40(uint64_t encoded, char *callsign) { +void decode_callsign_base40(uint64_t encoded, char* callsign) { if (encoded >= 262144000000000) { // 40^9 *callsign = 0; return; } - char *p = callsign; + char* p = callsign; for (; encoded > 0; p++) { *p = " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-/."[encoded % 40]; encoded /= 40; diff --git a/decoder_modules/m17_decoder/src/crc16.h b/decoder_modules/m17_decoder/src/crc16.h index 467f5a4e..eba89088 100644 --- a/decoder_modules/m17_decoder/src/crc16.h +++ b/decoder_modules/m17_decoder/src/crc16.h @@ -6,67 +6,57 @@ #include #include -namespace mobilinkd -{ +namespace mobilinkd { -template -struct CRC16 -{ - static constexpr uint16_t MASK = 0xFFFF; - static constexpr uint16_t LSB = 0x0001; - static constexpr uint16_t MSB = 0x8000; + template + struct CRC16 { + static constexpr uint16_t MASK = 0xFFFF; + static constexpr uint16_t LSB = 0x0001; + static constexpr uint16_t MSB = 0x8000; - uint16_t reg_ = Init; + uint16_t reg_ = Init; - void reset() - { - reg_ = Init; + void reset() { + reg_ = Init; - for (size_t i = 0; i != 16; ++i) - { - auto bit = reg_ & LSB; - if (bit) reg_ ^= Poly; - reg_ >>= 1; - if (bit) reg_ |= MSB; + for (size_t i = 0; i != 16; ++i) { + auto bit = reg_ & LSB; + if (bit) reg_ ^= Poly; + reg_ >>= 1; + if (bit) reg_ |= MSB; + } + + reg_ &= MASK; } - reg_ &= MASK; - } - - void operator()(uint8_t byte) - { - reg_ = crc(byte, reg_); - } - - uint16_t crc(uint8_t byte, uint16_t reg) - { - for (size_t i = 0; i != 8; ++i) - { - auto msb = reg & MSB; - reg = ((reg << 1) & MASK) | ((byte >> (7 - i)) & LSB); - if (msb) reg ^= Poly; + void operator()(uint8_t byte) { + reg_ = crc(byte, reg_); } - return reg & MASK; - } - - uint16_t get() - { - auto reg = reg_; - for (size_t i = 0; i != 16; ++i) - { - auto msb = reg & MSB; - reg = ((reg << 1) & MASK); - if (msb) reg ^= Poly; + + uint16_t crc(uint8_t byte, uint16_t reg) { + for (size_t i = 0; i != 8; ++i) { + auto msb = reg & MSB; + reg = ((reg << 1) & MASK) | ((byte >> (7 - i)) & LSB); + if (msb) reg ^= Poly; + } + return reg & MASK; } - return reg; - } - - std::array get_bytes() - { - auto crc = get(); - std::array result{uint8_t((crc >> 8) & 0xFF), uint8_t(crc & 0xFF)}; - return result; - } -}; + + uint16_t get() { + auto reg = reg_; + for (size_t i = 0; i != 16; ++i) { + auto msb = reg & MSB; + reg = ((reg << 1) & MASK); + if (msb) reg ^= Poly; + } + return reg; + } + + std::array get_bytes() { + auto crc = get(); + std::array result{ uint8_t((crc >> 8) & 0xFF), uint8_t(crc & 0xFF) }; + return result; + } + }; } // mobilinkd \ No newline at end of file diff --git a/decoder_modules/m17_decoder/src/golay24.h b/decoder_modules/m17_decoder/src/golay24.h index 92a22de2..fb6cf84e 100644 --- a/decoder_modules/m17_decoder/src/golay24.h +++ b/decoder_modules/m17_decoder/src/golay24.h @@ -10,224 +10,194 @@ namespace mobilinkd { -// Parts are adapted from: -// http://aqdi.com/articles/using-the-golay-error-detection-and-correction-code-3/ + // Parts are adapted from: + // http://aqdi.com/articles/using-the-golay-error-detection-and-correction-code-3/ -namespace Golay24 -{ + namespace Golay24 { - int popcount(uint32_t n) { - int count = 0; - for (int i = 0; i < 32; i++) { - count += ((n >> i) & 1); + int popcount(uint32_t n) { + int count = 0; + for (int i = 0; i < 32; i++) { + count += ((n >> i) & 1); + } + return count; } - return count; - } -namespace detail -{ + namespace detail { -// Need a constexpr sort. -// https://stackoverflow.com/a/40030044/854133 -template -void swap(T& l, T& r) -{ - T tmp = std::move(l); - l = std::move(r); - r = std::move(tmp); -} + // Need a constexpr sort. + // https://stackoverflow.com/a/40030044/854133 + template + void swap(T& l, T& r) { + T tmp = std::move(l); + l = std::move(r); + r = std::move(tmp); + } -template -struct array -{ - constexpr T& operator[](size_t i) - { - return arr[i]; - } + template + struct array { + constexpr T& operator[](size_t i) { + return arr[i]; + } - constexpr const T& operator[](size_t i) const - { - return arr[i]; - } + constexpr const T& operator[](size_t i) const { + return arr[i]; + } - constexpr const T* begin() const - { - return arr; - } - constexpr const T* end() const - { - return arr + N; - } + constexpr const T* begin() const { + return arr; + } + constexpr const T* end() const { + return arr + N; + } - T arr[N]; -}; + T arr[N]; + }; -template -void sort_impl(array &array, size_t left, size_t right) -{ - if (left < right) - { - size_t m = left; + template + void sort_impl(array& array, size_t left, size_t right) { + if (left < right) { + size_t m = left; - for (size_t i = left + 1; i -array sort(array array) -{ - auto sorted = array; - sort_impl(sorted, 0, N); - return sorted; -} + template + array sort(array array) { + auto sorted = array; + sort_impl(sorted, 0, N); + return sorted; + } -} // detail + } // detail -// static constexpr uint16_t POLY = 0xAE3; -constexpr uint16_t POLY = 0xC75; + // static constexpr uint16_t POLY = 0xAE3; + constexpr uint16_t POLY = 0xC75; #pragma pack(push, 1) -struct SyndromeMapEntry -{ - uint32_t a{0}; - uint16_t b{0}; -}; + struct SyndromeMapEntry { + uint32_t a{ 0 }; + uint16_t b{ 0 }; + }; #pragma pack(pop) -/** + /** * Calculate the syndrome of a [23,12] Golay codeword. * * @return the 11-bit syndrome of the codeword in bits [22:12]. */ -uint32_t syndrome(uint32_t codeword) -{ - codeword &= 0xffffffl; - for (size_t i = 0; i != 12; ++i) - { - if (codeword & 1) - codeword ^= POLY; - codeword >>= 1; - } - return (codeword << 12); -} - -bool parity(uint32_t codeword) -{ - return popcount(codeword) & 1; -} - -SyndromeMapEntry makeSyndromeMapEntry(uint64_t val) -{ - return SyndromeMapEntry{uint32_t(val >> 16), uint16_t(val & 0xFFFF)}; -} - -uint64_t makeSME(uint64_t syndrome, uint32_t bits) -{ - return (syndrome << 24) | (bits & 0xFFFFFF); -} - -constexpr size_t LUT_SIZE = 2048; - -std::array make_lut() -{ - constexpr size_t VECLEN=23; - detail::array result{}; - - size_t index = 0; - result[index++] = makeSME(syndrome(0), 0); - - for (size_t i = 0; i != VECLEN; ++i) - { - auto v = (1 << i); - result[index++] = makeSME(syndrome(v), v); - } - - for (size_t i = 0; i != VECLEN - 1; ++i) - { - for (size_t j = i + 1; j != VECLEN; ++j) - { - auto v = (1 << i) | (1 << j); - result[index++] = makeSME(syndrome(v), v); + uint32_t syndrome(uint32_t codeword) { + codeword &= 0xffffffl; + for (size_t i = 0; i != 12; ++i) { + if (codeword & 1) + codeword ^= POLY; + codeword >>= 1; + } + return (codeword << 12); } - } - for (size_t i = 0; i != VECLEN - 2; ++i) - { - for (size_t j = i + 1; j != VECLEN - 1; ++j) - { - for (size_t k = j + 1; k != VECLEN; ++k) - { - auto v = (1 << i) | (1 << j) | (1 << k); + bool parity(uint32_t codeword) { + return popcount(codeword) & 1; + } + + SyndromeMapEntry makeSyndromeMapEntry(uint64_t val) { + return SyndromeMapEntry{ uint32_t(val >> 16), uint16_t(val & 0xFFFF) }; + } + + uint64_t makeSME(uint64_t syndrome, uint32_t bits) { + return (syndrome << 24) | (bits & 0xFFFFFF); + } + + constexpr size_t LUT_SIZE = 2048; + + std::array make_lut() { + constexpr size_t VECLEN = 23; + detail::array result{}; + + size_t index = 0; + result[index++] = makeSME(syndrome(0), 0); + + for (size_t i = 0; i != VECLEN; ++i) { + auto v = (1 << i); result[index++] = makeSME(syndrome(v), v); } + + for (size_t i = 0; i != VECLEN - 1; ++i) { + for (size_t j = i + 1; j != VECLEN; ++j) { + auto v = (1 << i) | (1 << j); + result[index++] = makeSME(syndrome(v), v); + } + } + + for (size_t i = 0; i != VECLEN - 2; ++i) { + for (size_t j = i + 1; j != VECLEN - 1; ++j) { + for (size_t k = j + 1; k != VECLEN; ++k) { + auto v = (1 << i) | (1 << j) | (1 << k); + result[index++] = makeSME(syndrome(v), v); + } + } + } + + result = detail::sort(result); + + std::array tmp; + for (size_t i = 0; i != LUT_SIZE; ++i) { + tmp[i] = makeSyndromeMapEntry(result[i]); + } + + return tmp; } - } - result = detail::sort(result); + inline auto LUT = make_lut(); - std::array tmp; - for (size_t i = 0; i != LUT_SIZE; ++i) - { - tmp[i] = makeSyndromeMapEntry(result[i]); - } - - return tmp; -} - -inline auto LUT = make_lut(); - -/** + /** * Calculate [23,12] Golay codeword. * * @return checkbits(11)|data(12). */ -uint32_t encode23(uint16_t data) -{ - // data &= 0xfff; - uint32_t codeword = data; - for (size_t i = 0; i != 12; ++i) - { - if (codeword & 1) - codeword ^= POLY; - codeword >>= 1; - } - return codeword | (data << 11); -} + uint32_t encode23(uint16_t data) { + // data &= 0xfff; + uint32_t codeword = data; + for (size_t i = 0; i != 12; ++i) { + if (codeword & 1) + codeword ^= POLY; + codeword >>= 1; + } + return codeword | (data << 11); + } -uint32_t encode24(uint16_t data) -{ - auto codeword = encode23(data); - return ((codeword << 1) | parity(codeword)); -} + uint32_t encode24(uint16_t data) { + auto codeword = encode23(data); + return ((codeword << 1) | parity(codeword)); + } -bool decode(uint32_t input, uint32_t& output) -{ - auto syndrm = syndrome(input >> 1); - auto it = std::lower_bound(LUT.begin(), LUT.end(), syndrm, - [](const SyndromeMapEntry& sme, uint32_t val){ - return (sme.a >> 8) < val; - }); + bool decode(uint32_t input, uint32_t& output) { + auto syndrm = syndrome(input >> 1); + auto it = std::lower_bound(LUT.begin(), LUT.end(), syndrm, + [](const SyndromeMapEntry& sme, uint32_t val) { + return (sme.a >> 8) < val; + }); - if ((it->a >> 8) == syndrm) - { - // Build the correction from the compressed entry. - auto correction = ((((it->a & 0xFF) << 16) | it->b) << 1); - // Apply the correction to the input. - output = input ^ correction; - // Only test parity for 3-bit errors. - return popcount(syndrm) < 3 || !parity(output); - } + if ((it->a >> 8) == syndrm) { + // Build the correction from the compressed entry. + auto correction = ((((it->a & 0xFF) << 16) | it->b) << 1); + // Apply the correction to the input. + output = input ^ correction; + // Only test parity for 3-bit errors. + return popcount(syndrm) < 3 || !parity(output); + } - return false; -} + return false; + } -} // Golay24 + } // Golay24 } // mobilinkd \ No newline at end of file diff --git a/decoder_modules/m17_decoder/src/lsf_decode.cpp b/decoder_modules/m17_decoder/src/lsf_decode.cpp index a2687652..7e3dc25d 100644 --- a/decoder_modules/m17_decoder/src/lsf_decode.cpp +++ b/decoder_modules/m17_decoder/src/lsf_decode.cpp @@ -31,7 +31,7 @@ M17LSF M17DecodeLSF(uint8_t* _lsf) { // Extract CRC lsf.rawCRC = 0; for (int i = 0; i < 16; i++) { - lsf.rawCRC |= (((uint16_t)_lsf[(i+48+48+16+112) / 8] >> (7 - (i%8))) & 1) << (15 - i); + lsf.rawCRC |= (((uint16_t)_lsf[(i + 48 + 48 + 16 + 112) / 8] >> (7 - (i % 8))) & 1) << (15 - i); } // Check CRC @@ -50,19 +50,19 @@ M17LSF M17DecodeLSF(uint8_t* _lsf) { // Extract DST lsf.rawDst = 0; for (int i = 0; i < 48; i++) { - lsf.rawDst |= (((uint64_t)_lsf[i / 8] >> (7 - (i%8))) & 1) << (47 - i); + lsf.rawDst |= (((uint64_t)_lsf[i / 8] >> (7 - (i % 8))) & 1) << (47 - i); } // Extract SRC lsf.rawSrc = 0; for (int i = 0; i < 48; i++) { - lsf.rawSrc |= (((uint64_t)_lsf[(i+48) / 8] >> (7 - (i%8))) & 1) << (47 - i); + lsf.rawSrc |= (((uint64_t)_lsf[(i + 48) / 8] >> (7 - (i % 8))) & 1) << (47 - i); } // Extract TYPE lsf.rawType = 0; for (int i = 0; i < 16; i++) { - lsf.rawType |= (((uint16_t)_lsf[(i+48+48) / 8] >> (7 - (i%8))) & 1) << (15 - i); + lsf.rawType |= (((uint16_t)_lsf[(i + 48 + 48) / 8] >> (7 - (i % 8))) & 1) << (15 - i); } // Extract META diff --git a/decoder_modules/m17_decoder/src/lsf_decode.h b/decoder_modules/m17_decoder/src/lsf_decode.h index 4ee6d7df..266b2e63 100644 --- a/decoder_modules/m17_decoder/src/lsf_decode.h +++ b/decoder_modules/m17_decoder/src/lsf_decode.h @@ -3,17 +3,17 @@ #include enum M17DataType { - M17_DATATYPE_UNKNOWN = 0b00, - M17_DATATYPE_DATA = 0b01, - M17_DATATYPE_VOICE = 0b10, + M17_DATATYPE_UNKNOWN = 0b00, + M17_DATATYPE_DATA = 0b01, + M17_DATATYPE_VOICE = 0b10, M17_DATATYPE_DATA_VOICE = 0b11 }; enum M17EncryptionType { - M17_ENCRYPTION_NONE = 0b00, - M17_ENCRYPTION_AES = 0b01, + M17_ENCRYPTION_NONE = 0b00, + M17_ENCRYPTION_AES = 0b01, M17_ENCRYPTION_SCRAMBLE = 0b10, - M17_ENCRYPTION_UNKNOWN = 0b11 + M17_ENCRYPTION_UNKNOWN = 0b11 }; extern const char* M17DataTypesTxt[4]; diff --git a/decoder_modules/m17_decoder/src/m17dsp.h b/decoder_modules/m17_decoder/src/m17dsp.h index 337a38ca..5429905a 100644 --- a/decoder_modules/m17_decoder/src/m17dsp.h +++ b/decoder_modules/m17_decoder/src/m17dsp.h @@ -7,50 +7,50 @@ #include extern "C" { - #include +#include } -#define M17_DEVIATION 2400.0f -#define M17_BAUDRATE 4800.0f -#define M17_RRC_ALPHA 0.5f -#define M17_4FSK_HIGH_CUT 0.5f +#define M17_DEVIATION 2400.0f +#define M17_BAUDRATE 4800.0f +#define M17_RRC_ALPHA 0.5f +#define M17_4FSK_HIGH_CUT 0.5f -#define M17_SYNC_SIZE 16 -#define M17_LICH_SIZE 96 -#define M17_PAYLOAD_SIZE 144 -#define M17_ENCODED_PAYLOAD_SIZE 296 -#define M17_LSF_SIZE 240 -#define M17_ENCODED_LSF_SIZE 488 -#define M17_RAW_FRAME_SIZE 384 -#define M17_CUT_FRAME_SIZE 368 +#define M17_SYNC_SIZE 16 +#define M17_LICH_SIZE 96 +#define M17_PAYLOAD_SIZE 144 +#define M17_ENCODED_PAYLOAD_SIZE 296 +#define M17_LSF_SIZE 240 +#define M17_ENCODED_LSF_SIZE 488 +#define M17_RAW_FRAME_SIZE 384 +#define M17_CUT_FRAME_SIZE 368 -const uint8_t M17_LSF_SYNC[16] = { 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1 }; -const uint8_t M17_STF_SYNC[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 }; -const uint8_t M17_PKF_SYNC[16] = { 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; +const uint8_t M17_LSF_SYNC[16] = { 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1 }; +const uint8_t M17_STF_SYNC[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1 }; +const uint8_t M17_PKF_SYNC[16] = { 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; -const uint8_t M17_SCRAMBLER[368] = { 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, - 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, - 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, - 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, - 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, - 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, - 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, - 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, - 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, - 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, - 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, - 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, - 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, - 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, - 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, - 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, - 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, - 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, - 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, - 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, - 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1 }; +const uint8_t M17_SCRAMBLER[368] = { 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, + 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, + 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, + 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, + 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, + 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, + 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, + 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, + 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, + 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, + 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, + 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, + 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, + 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, + 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, + 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, + 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, + 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, + 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, + 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1 }; const uint16_t M17_INTERLEAVER[368] = { 0, 137, 90, 227, 180, 317, 270, 39, 360, 129, 82, 219, 172, 309, 262, 31, 352, 121, 74, 211, 164, 301, 254, 23, 344, 113, 66, 203, 156, 293, 246, 15, @@ -83,7 +83,7 @@ const uint8_t M17_PUNCTURING_P1[61] = { 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1 const uint8_t M17_PUNCTURING_P2[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 }; -static const correct_convolutional_polynomial_t correct_conv_m17_polynomial[] = {0b11001, 0b10111}; +static const correct_convolutional_polynomial_t correct_conv_m17_polynomial[] = { 0b11001, 0b10111 }; namespace dsp { class M17Slice4FSK : public generic_block { @@ -116,8 +116,8 @@ namespace dsp { float val; for (int i = 0; i < count; i++) { val = _in->readBuf[i]; - out.writeBuf[i*2] = (val < 0.0f); - out.writeBuf[(i*2)+1] = (fabsf(val) > M17_4FSK_HIGH_CUT); + out.writeBuf[i * 2] = (val < 0.0f); + out.writeBuf[(i * 2) + 1] = (fabsf(val) > M17_4FSK_HIGH_CUT); } _in->flush(); @@ -130,7 +130,6 @@ namespace dsp { private: stream* _in; - }; class M17FrameDemux : public generic_block { @@ -176,7 +175,10 @@ namespace dsp { for (int i = 0; i < count;) { if (detect) { - if (outCount < M17_SYNC_SIZE) { outCount++; i++; } + if (outCount < M17_SYNC_SIZE) { + outCount++; + i++; + } else { int id = M17_INTERLEAVER[outCount - M17_SYNC_SIZE]; @@ -192,21 +194,21 @@ namespace dsp { else if (type == 2) { packetOut.writeBuf[id - M17_LICH_SIZE] = (delay[i++] ^ M17_SCRAMBLER[outCount - M17_SYNC_SIZE]); } - + outCount++; } - + if (outCount >= M17_RAW_FRAME_SIZE) { detect = false; if (type == 0) { if (!linkSetupOut.swap(M17_CUT_FRAME_SIZE)) { return -1; } } else if (type == 1) { - if (!lichOut.swap(M17_LICH_SIZE)) {return -1; } - if (!streamOut.swap(M17_CUT_FRAME_SIZE)) {return -1; } + if (!lichOut.swap(M17_LICH_SIZE)) { return -1; } + if (!streamOut.swap(M17_CUT_FRAME_SIZE)) { return -1; } } else if (type == 2) { - if (!lichOut.swap(M17_LICH_SIZE)) {return -1; } + if (!lichOut.swap(M17_LICH_SIZE)) { return -1; } if (!packetOut.swap(M17_CUT_FRAME_SIZE)) { return -1; } } } @@ -242,7 +244,7 @@ namespace dsp { i++; } - + memmove(delay, &delay[count], 16); _in->flush(); @@ -264,7 +266,6 @@ namespace dsp { int type; int outCount = 0; - }; class M17LSFDecoder : public generic_block { @@ -283,7 +284,7 @@ namespace dsp { _in = in; _handler = handler; _ctx = ctx; - + conv = correct_convolutional_create(2, 5, correct_conv_m17_polynomial); generic_block::registerInput(_in); @@ -319,7 +320,7 @@ namespace dsp { // Pack into bytes memset(packed, 0, 61); for (int i = 0; i < M17_ENCODED_LSF_SIZE; i++) { - packed[i/8] |= depunctured[i] << (7 - (i%8)); + packed[i / 8] |= depunctured[i] << (7 - (i % 8)); } // Run through convolutional decoder @@ -343,7 +344,6 @@ namespace dsp { uint8_t lsf[30]; correct_convolutional* conv; - }; class M17PayloadFEC : public generic_block { @@ -360,7 +360,7 @@ namespace dsp { void init(stream* in) { _in = in; - + conv = correct_convolutional_create(2, 5, correct_conv_m17_polynomial); generic_block::registerInput(_in); @@ -395,13 +395,13 @@ namespace dsp { // Pack into bytes memset(packed, 0, 37); for (int i = 0; i < M17_ENCODED_PAYLOAD_SIZE; i++) { - if (!(i%8)) { packed[i/8] = 0; } - packed[i/8] |= depunctured[i] << (7 - (i%8)); + if (!(i % 8)) { packed[i / 8] = 0; } + packed[i / 8] |= depunctured[i] << (7 - (i % 8)); } // Run through convolutional decoder correct_convolutional_decode(conv, packed, M17_ENCODED_PAYLOAD_SIZE, out.writeBuf); - + _in->flush(); if (!out.swap(M17_PAYLOAD_SIZE / 8)) { return -1; } @@ -417,7 +417,6 @@ namespace dsp { uint8_t packed[37]; correct_convolutional* conv; - }; class M17Codec2Decode : public generic_block { @@ -464,7 +463,7 @@ namespace dsp { // Decode both parts using codec codec2_decode(codec, int16Audio, &_in->readBuf[2]); - codec2_decode(codec, &int16Audio[sampsPerC2Frame], &_in->readBuf[2+8]); + codec2_decode(codec, &int16Audio[sampsPerC2Frame], &_in->readBuf[2 + 8]); // Convert to float volk_16i_s32f_convert_32f(floatAudio, int16Audio, 32768.0f, sampsPerC2FrameDouble); @@ -489,7 +488,6 @@ namespace dsp { CODEC2* codec; int sampsPerC2Frame = 0; int sampsPerC2FrameDouble = 0; - }; class M17LICHDecoder : public generic_block { @@ -543,7 +541,7 @@ namespace dsp { uint8_t temp; for (int i = 0; i < 12; i++) { id = (b * 12) + i; - chunk[id / 8] |= ((decodedBlock >> (23 - i)) & 1) << (7 - (id%8)); + chunk[id / 8] |= ((decodedBlock >> (23 - i)) & 1) << (7 - (id % 8)); } } @@ -555,7 +553,7 @@ namespace dsp { if (partId == 0) { newFrame = true; lastId = 0; - memcpy(&lsf[partId*5], chunk, 5); + memcpy(&lsf[partId * 5], chunk, 5); return count; } @@ -568,7 +566,7 @@ namespace dsp { // If we're recording and there's no discontinuity (see above), add the data to the full frame if (newFrame) { lastId = partId; - memcpy(&lsf[partId*5], chunk, 5); + memcpy(&lsf[partId * 5], chunk, 5); // If the lsf is complete, send it out if (partId == 5) { @@ -590,7 +588,6 @@ namespace dsp { uint8_t lsf[240]; bool newFrame = false; int lastId = 0; - }; class M17Decoder : public generic_hier_block { @@ -620,7 +617,7 @@ namespace dsp { diagOut = &doubler.outB; out = &decodeAudio.out; - + generic_hier_block::registerBlock(&demod); generic_hier_block::registerBlock(&fir); generic_hier_block::registerBlock(&recov); @@ -661,7 +658,6 @@ namespace dsp { NullSink ns2; - float _sampleRate; - + float _sampleRate; }; } \ No newline at end of file diff --git a/decoder_modules/m17_decoder/src/main.cpp b/decoder_modules/m17_decoder/src/main.cpp index b833b7d3..c95a598a 100644 --- a/decoder_modules/m17_decoder/src/main.cpp +++ b/decoder_modules/m17_decoder/src/main.cpp @@ -21,9 +21,9 @@ #include #include -#define CONCAT(a, b) ((std::string(a) + b).c_str()) +#define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "m17_decoder", /* Description: */ "M17 Digital Voice Decoder for SDR++", /* Author: */ "Ryzerth", @@ -84,7 +84,7 @@ public: sigpath::sinkManager.registerStream(name, &stream); stream.start(); - + gui::menu.registerEntry(name, menuHandler, this, this); } @@ -107,7 +107,7 @@ public: void enable() { double bw = gui::waterfall.getBandwidth(); - vfo = sigpath::vfoManager.createVFO(name, ImGui::WaterfallVFO::REF_CENTER, std::clamp(0, -bw/2.0, bw/2.0), 9600, INPUT_SAMPLE_RATE, 9600, 9600, true); + vfo = sigpath::vfoManager.createVFO(name, ImGui::WaterfallVFO::REF_CENTER, std::clamp(0, -bw / 2.0, bw / 2.0), 9600, INPUT_SAMPLE_RATE, 9600, 9600, true); vfo->setSnapInterval(250); // Set Input of demod here @@ -152,7 +152,7 @@ private: std::lock_guard lck(_this->lsfMtx); auto now = std::chrono::high_resolution_clock::now(); - if (std::chrono::duration_cast(now-_this->lastUpdated).count() > 1000) { + if (std::chrono::duration_cast(now - _this->lastUpdated).count() > 1000) { _this->lsf.valid = false; } @@ -251,7 +251,7 @@ private: M17DecoderModule* _this = (M17DecoderModule*)ctx; // TODO: If too slow, change all demods here and not when setting _this->audioSampRate = sampleRate; - _this->resampWin.setCutoff(std::min(sampleRate/2, 4000)); + _this->resampWin.setCutoff(std::min(sampleRate / 2, 4000)); _this->resamp.tempStop(); _this->resamp.setOutSampleRate(sampleRate); _this->resampWin.setSampleRate(8000 * _this->resamp.getInterpolation()); @@ -273,7 +273,7 @@ private: VFOManager::VFO* vfo; dsp::M17Decoder decoder; - + dsp::Reshaper reshape; dsp::HandlerSink diagHandler; diff --git a/decoder_modules/meteor_demodulator/src/main.cpp b/decoder_modules/meteor_demodulator/src/main.cpp index 0e889f84..63bb4fcc 100644 --- a/decoder_modules/meteor_demodulator/src/main.cpp +++ b/decoder_modules/meteor_demodulator/src/main.cpp @@ -21,9 +21,9 @@ #include -#define CONCAT(a, b) ((std::string(a) + b).c_str()) +#define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "meteor_demodulator", /* Description: */ "Meteor demodulator for SDR++", /* Author: */ "Ryzerth", @@ -35,7 +35,7 @@ ConfigManager config; std::string genFileName(std::string prefix, std::string suffix) { time_t now = time(0); - tm *ltm = localtime(&now); + tm* ltm = localtime(&now); char buf[1024]; sprintf(buf, "%s_%02d-%02d-%02d_%02d-%02d-%02d%s", prefix.c_str(), ltm->tm_hour, ltm->tm_min, ltm->tm_sec, ltm->tm_mday, ltm->tm_mon + 1, ltm->tm_year + 1900, suffix.c_str()); return buf; @@ -74,7 +74,7 @@ public: reshape.start(); symSink.start(); sink.start(); - + gui::menu.registerEntry(name, menuHandler, this, this); core::modComManager.registerInterface("meteor_demodulator", name, moduleInterfaceHandler, this); } @@ -98,7 +98,7 @@ public: void enable() { double bw = gui::waterfall.getBandwidth(); - vfo = sigpath::vfoManager.createVFO(name, ImGui::WaterfallVFO::REF_CENTER, std::clamp(0, -bw/2.0, bw/2.0), 150000, INPUT_SAMPLE_RATE, 150000, 150000, true); + vfo = sigpath::vfoManager.createVFO(name, ImGui::WaterfallVFO::REF_CENTER, std::clamp(0, -bw / 2.0, bw / 2.0), 150000, INPUT_SAMPLE_RATE, 150000, 150000, true); demod.setInput(vfo->output); @@ -155,12 +155,12 @@ private: } else { if (ImGui::Button(CONCAT("Record##_recorder_rec_", _this->name), ImVec2(menuWidth, 0))) { - _this->startRecording(); + _this->startRecording(); } ImGui::Text("Idle --.--MB"); } - if (!_this->folderSelect.pathIsValid() && _this->enabled) { style::endDisabled(); } + if (!_this->folderSelect.pathIsValid() && _this->enabled) { style::endDisabled(); } if (!_this->enabled) { style::endDisabled(); } } @@ -196,7 +196,7 @@ private: } else { spdlog::error("Could not open file for recording!"); - } + } } void stopRecording() { @@ -240,7 +240,6 @@ private: std::ofstream recFile; int8_t* writeBuffer; - }; MOD_EXPORT void _INIT_() { diff --git a/decoder_modules/radio/src/demod.h b/decoder_modules/radio/src/demod.h index 64f490d0..6863eb31 100644 --- a/decoder_modules/radio/src/demod.h +++ b/decoder_modules/radio/src/demod.h @@ -40,7 +40,7 @@ namespace demod { virtual double getAFBandwidth(double bandwidth) = 0; virtual bool getFMIFNRAllowed() = 0; virtual bool getNBAllowed() = 0; - + virtual bool getDynamicAFBandwidth() = 0; virtual dsp::stream* getOutput() = 0; }; diff --git a/decoder_modules/radio/src/demodulators/am.h b/decoder_modules/radio/src/demodulators/am.h index f2470fec..d682c36a 100644 --- a/decoder_modules/radio/src/demodulators/am.h +++ b/decoder_modules/radio/src/demodulators/am.h @@ -7,7 +7,7 @@ namespace demod { class AM : public Demodulator { public: AM() {} - + AM(std::string name, ConfigManager* config, dsp::stream* input, double bandwidth, EventHandler*> outputChangeHandler, double audioSR) { init(name, config, input, bandwidth, outputChangeHandler, audioSR); } @@ -52,23 +52,23 @@ namespace demod { // ============= INFO ============= - const char* getName() { return "AM"; } - double getIFSampleRate() { return 15000.0; } - double getAFSampleRate() { return getIFSampleRate(); } - double getDefaultBandwidth() { return 10000.0; } - double getMinBandwidth() { return 1000.0; } - double getMaxBandwidth() { return getIFSampleRate(); } - bool getBandwidthLocked() { return false; } - double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } - double getDefaultSnapInterval() { return 1000.0; } - int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } - bool getDeempAllowed() { return false; } - bool getPostProcEnabled() { return true; } - int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } + const char* getName() { return "AM"; } + double getIFSampleRate() { return 15000.0; } + double getAFSampleRate() { return getIFSampleRate(); } + double getDefaultBandwidth() { return 10000.0; } + double getMinBandwidth() { return 1000.0; } + double getMaxBandwidth() { return getIFSampleRate(); } + bool getBandwidthLocked() { return false; } + double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } + double getDefaultSnapInterval() { return 1000.0; } + int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } + bool getDeempAllowed() { return false; } + bool getPostProcEnabled() { return true; } + int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } double getAFBandwidth(double bandwidth) { return bandwidth / 2.0; } - bool getDynamicAFBandwidth() { return true; } - bool getFMIFNRAllowed() { return false; } - bool getNBAllowed() { return false; } + bool getDynamicAFBandwidth() { return true; } + bool getFMIFNRAllowed() { return false; } + bool getNBAllowed() { return false; } dsp::stream* getOutput() { return &m2s.out; } private: diff --git a/decoder_modules/radio/src/demodulators/cw.h b/decoder_modules/radio/src/demodulators/cw.h index 9eafd2b7..8443917a 100644 --- a/decoder_modules/radio/src/demodulators/cw.h +++ b/decoder_modules/radio/src/demodulators/cw.h @@ -7,7 +7,7 @@ namespace demod { class CW : public Demodulator { public: CW() {} - + CW(std::string name, ConfigManager* config, dsp::stream* input, double bandwidth, EventHandler*> outputChangeHandler, double audioSR) { init(name, config, input, bandwidth, outputChangeHandler, audioSR); } @@ -53,23 +53,23 @@ namespace demod { // ============= INFO ============= - const char* getName() { return "CW"; } - double getIFSampleRate() { return 3000.0; } - double getAFSampleRate() { return getIFSampleRate(); } - double getDefaultBandwidth() { return 500.0; } - double getMinBandwidth() { return 50.0; } - double getMaxBandwidth() { return 500.0; } - bool getBandwidthLocked() { return false; } - double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } - double getDefaultSnapInterval() { return 10.0; } - int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } - bool getDeempAllowed() { return false; } - bool getPostProcEnabled() { return true; } - int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } + const char* getName() { return "CW"; } + double getIFSampleRate() { return 3000.0; } + double getAFSampleRate() { return getIFSampleRate(); } + double getDefaultBandwidth() { return 500.0; } + double getMinBandwidth() { return 50.0; } + double getMaxBandwidth() { return 500.0; } + bool getBandwidthLocked() { return false; } + double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } + double getDefaultSnapInterval() { return 10.0; } + int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } + bool getDeempAllowed() { return false; } + bool getPostProcEnabled() { return true; } + int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } double getAFBandwidth(double bandwidth) { return (bandwidth / 2.0) + 1000.0; } - bool getDynamicAFBandwidth() { return true; } - bool getFMIFNRAllowed() { return false; } - bool getNBAllowed() { return false; } + bool getDynamicAFBandwidth() { return true; } + bool getFMIFNRAllowed() { return false; } + bool getNBAllowed() { return false; } dsp::stream* getOutput() { return &m2s.out; } private: diff --git a/decoder_modules/radio/src/demodulators/dsb.h b/decoder_modules/radio/src/demodulators/dsb.h index f0854e1d..1e10faa5 100644 --- a/decoder_modules/radio/src/demodulators/dsb.h +++ b/decoder_modules/radio/src/demodulators/dsb.h @@ -7,7 +7,7 @@ namespace demod { class DSB : public Demodulator { public: DSB() {} - + DSB(std::string name, ConfigManager* config, dsp::stream* input, double bandwidth, EventHandler*> outputChangeHandler, double audioSR) { init(name, config, input, bandwidth, outputChangeHandler, audioSR); } @@ -54,23 +54,23 @@ namespace demod { // ============= INFO ============= - const char* getName() { return "DSB"; } - double getIFSampleRate() { return 24000.0; } - double getAFSampleRate() { return getIFSampleRate(); } - double getDefaultBandwidth() { return 4600.0; } - double getMinBandwidth() { return 1000.0; } - double getMaxBandwidth() { return getIFSampleRate() / 2.0; } - bool getBandwidthLocked() { return false; } - double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } - double getDefaultSnapInterval() { return 100.0; } - int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } - bool getDeempAllowed() { return false; } - bool getPostProcEnabled() { return true; } - int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } + const char* getName() { return "DSB"; } + double getIFSampleRate() { return 24000.0; } + double getAFSampleRate() { return getIFSampleRate(); } + double getDefaultBandwidth() { return 4600.0; } + double getMinBandwidth() { return 1000.0; } + double getMaxBandwidth() { return getIFSampleRate() / 2.0; } + bool getBandwidthLocked() { return false; } + double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } + double getDefaultSnapInterval() { return 100.0; } + int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } + bool getDeempAllowed() { return false; } + bool getPostProcEnabled() { return true; } + int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } double getAFBandwidth(double bandwidth) { return bandwidth / 2.0; } - bool getDynamicAFBandwidth() { return true; } - bool getFMIFNRAllowed() { return false; } - bool getNBAllowed() { return true; } + bool getDynamicAFBandwidth() { return true; } + bool getFMIFNRAllowed() { return false; } + bool getNBAllowed() { return true; } dsp::stream* getOutput() { return &m2s.out; } private: diff --git a/decoder_modules/radio/src/demodulators/lsb.h b/decoder_modules/radio/src/demodulators/lsb.h index 0d423ebc..1cf26bd1 100644 --- a/decoder_modules/radio/src/demodulators/lsb.h +++ b/decoder_modules/radio/src/demodulators/lsb.h @@ -7,7 +7,7 @@ namespace demod { class LSB : public Demodulator { public: LSB() {} - + LSB(std::string name, ConfigManager* config, dsp::stream* input, double bandwidth, EventHandler*> outputChangeHandler, double audioSR) { init(name, config, input, bandwidth, outputChangeHandler, audioSR); } @@ -54,23 +54,23 @@ namespace demod { // ============= INFO ============= - const char* getName() { return "LSB"; } - double getIFSampleRate() { return 24000.0; } - double getAFSampleRate() { return getIFSampleRate(); } - double getDefaultBandwidth() { return 2800.0; } - double getMinBandwidth() { return 500.0; } - double getMaxBandwidth() { return getIFSampleRate() / 2.0; } - bool getBandwidthLocked() { return false; } - double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } - double getDefaultSnapInterval() { return 100.0; } - int getVFOReference() { return ImGui::WaterfallVFO::REF_UPPER; } - bool getDeempAllowed() { return false; } - bool getPostProcEnabled() { return true; } - int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } + const char* getName() { return "LSB"; } + double getIFSampleRate() { return 24000.0; } + double getAFSampleRate() { return getIFSampleRate(); } + double getDefaultBandwidth() { return 2800.0; } + double getMinBandwidth() { return 500.0; } + double getMaxBandwidth() { return getIFSampleRate() / 2.0; } + bool getBandwidthLocked() { return false; } + double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } + double getDefaultSnapInterval() { return 100.0; } + int getVFOReference() { return ImGui::WaterfallVFO::REF_UPPER; } + bool getDeempAllowed() { return false; } + bool getPostProcEnabled() { return true; } + int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } double getAFBandwidth(double bandwidth) { return bandwidth; } - bool getDynamicAFBandwidth() { return true; } - bool getFMIFNRAllowed() { return false; } - bool getNBAllowed() { return true; } + bool getDynamicAFBandwidth() { return true; } + bool getFMIFNRAllowed() { return false; } + bool getNBAllowed() { return true; } dsp::stream* getOutput() { return &m2s.out; } private: diff --git a/decoder_modules/radio/src/demodulators/nfm.h b/decoder_modules/radio/src/demodulators/nfm.h index 6a5f93ce..f4c200d2 100644 --- a/decoder_modules/radio/src/demodulators/nfm.h +++ b/decoder_modules/radio/src/demodulators/nfm.h @@ -7,7 +7,7 @@ namespace demod { class NFM : public Demodulator { public: NFM() {} - + NFM(std::string name, ConfigManager* config, dsp::stream* input, double bandwidth, EventHandler*> outputChangeHandler, double audioSR) { init(name, config, input, bandwidth, outputChangeHandler, audioSR); } @@ -46,23 +46,23 @@ namespace demod { // ============= INFO ============= - const char* getName() { return "FM"; } - double getIFSampleRate() { return 50000.0; } - double getAFSampleRate() { return getIFSampleRate(); } - double getDefaultBandwidth() { return 12500.0; } - double getMinBandwidth() { return 1000.0; } - double getMaxBandwidth() { return getIFSampleRate(); } - bool getBandwidthLocked() { return false; } - double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } - double getDefaultSnapInterval() { return 2500.0; } - int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } - bool getDeempAllowed() { return true; } - bool getPostProcEnabled() { return true; } - int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } + const char* getName() { return "FM"; } + double getIFSampleRate() { return 50000.0; } + double getAFSampleRate() { return getIFSampleRate(); } + double getDefaultBandwidth() { return 12500.0; } + double getMinBandwidth() { return 1000.0; } + double getMaxBandwidth() { return getIFSampleRate(); } + bool getBandwidthLocked() { return false; } + double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } + double getDefaultSnapInterval() { return 2500.0; } + int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } + bool getDeempAllowed() { return true; } + bool getPostProcEnabled() { return true; } + int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } double getAFBandwidth(double bandwidth) { return bandwidth / 2.0; } - bool getDynamicAFBandwidth() { return true; } - bool getFMIFNRAllowed() { return true; } - bool getNBAllowed() { return false; } + bool getDynamicAFBandwidth() { return true; } + bool getFMIFNRAllowed() { return true; } + bool getNBAllowed() { return false; } dsp::stream* getOutput() { return &demod.out; } private: diff --git a/decoder_modules/radio/src/demodulators/raw.h b/decoder_modules/radio/src/demodulators/raw.h index 1956a807..88fa3a95 100644 --- a/decoder_modules/radio/src/demodulators/raw.h +++ b/decoder_modules/radio/src/demodulators/raw.h @@ -7,7 +7,7 @@ namespace demod { class RAW : public Demodulator { public: RAW() {} - + RAW(std::string name, ConfigManager* config, dsp::stream* input, double bandwidth, EventHandler*> outputChangeHandler, double audioSR) { init(name, config, input, bandwidth, outputChangeHandler, audioSR); } @@ -47,23 +47,23 @@ namespace demod { // ============= INFO ============= - const char* getName() { return "RAW"; } - double getIFSampleRate() { return audioSampleRate; } - double getAFSampleRate() { return audioSampleRate; } - double getDefaultBandwidth() { return audioSampleRate; } - double getMinBandwidth() { return audioSampleRate; } - double getMaxBandwidth() { return audioSampleRate; } - bool getBandwidthLocked() { return true; } - double getMaxAFBandwidth() { return audioSampleRate; } - double getDefaultSnapInterval() { return 2500.0; } - int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } - bool getDeempAllowed() { return false; } - bool getPostProcEnabled() { return false; } - int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } + const char* getName() { return "RAW"; } + double getIFSampleRate() { return audioSampleRate; } + double getAFSampleRate() { return audioSampleRate; } + double getDefaultBandwidth() { return audioSampleRate; } + double getMinBandwidth() { return audioSampleRate; } + double getMaxBandwidth() { return audioSampleRate; } + bool getBandwidthLocked() { return true; } + double getMaxAFBandwidth() { return audioSampleRate; } + double getDefaultSnapInterval() { return 2500.0; } + int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } + bool getDeempAllowed() { return false; } + bool getPostProcEnabled() { return false; } + int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } double getAFBandwidth(double bandwidth) { return bandwidth; } - bool getDynamicAFBandwidth() { return false; } - bool getFMIFNRAllowed() { return false; } - bool getNBAllowed() { return true; } + bool getDynamicAFBandwidth() { return false; } + bool getFMIFNRAllowed() { return false; } + bool getNBAllowed() { return true; } dsp::stream* getOutput() { return &c2s.out; } private: diff --git a/decoder_modules/radio/src/demodulators/usb.h b/decoder_modules/radio/src/demodulators/usb.h index 1b9ac233..cb3a55a5 100644 --- a/decoder_modules/radio/src/demodulators/usb.h +++ b/decoder_modules/radio/src/demodulators/usb.h @@ -7,7 +7,7 @@ namespace demod { class USB : public Demodulator { public: USB() {} - + USB(std::string name, ConfigManager* config, dsp::stream* input, double bandwidth, EventHandler*> outputChangeHandler, double audioSR) { init(name, config, input, bandwidth, outputChangeHandler, audioSR); } @@ -54,23 +54,23 @@ namespace demod { // ============= INFO ============= - const char* getName() { return "USB"; } - double getIFSampleRate() { return 24000.0; } - double getAFSampleRate() { return getIFSampleRate(); } - double getDefaultBandwidth() { return 2800.0; } - double getMinBandwidth() { return 500.0; } - double getMaxBandwidth() { return getIFSampleRate() / 2.0; } - bool getBandwidthLocked() { return false; } - double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } - double getDefaultSnapInterval() { return 100.0; } - int getVFOReference() { return ImGui::WaterfallVFO::REF_LOWER; } - bool getDeempAllowed() { return false; } - bool getPostProcEnabled() { return true; } - int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } + const char* getName() { return "USB"; } + double getIFSampleRate() { return 24000.0; } + double getAFSampleRate() { return getIFSampleRate(); } + double getDefaultBandwidth() { return 2800.0; } + double getMinBandwidth() { return 500.0; } + double getMaxBandwidth() { return getIFSampleRate() / 2.0; } + bool getBandwidthLocked() { return false; } + double getMaxAFBandwidth() { return getIFSampleRate() / 2.0; } + double getDefaultSnapInterval() { return 100.0; } + int getVFOReference() { return ImGui::WaterfallVFO::REF_LOWER; } + bool getDeempAllowed() { return false; } + bool getPostProcEnabled() { return true; } + int getDefaultDeemphasisMode() { return DEEMP_MODE_NONE; } double getAFBandwidth(double bandwidth) { return bandwidth; } - bool getDynamicAFBandwidth() { return true; } - bool getFMIFNRAllowed() { return false; } - bool getNBAllowed() { return true; } + bool getDynamicAFBandwidth() { return true; } + bool getFMIFNRAllowed() { return false; } + bool getNBAllowed() { return true; } dsp::stream* getOutput() { return &m2s.out; } private: diff --git a/decoder_modules/radio/src/demodulators/wfm.h b/decoder_modules/radio/src/demodulators/wfm.h index 5d512a0f..7ca1a11f 100644 --- a/decoder_modules/radio/src/demodulators/wfm.h +++ b/decoder_modules/radio/src/demodulators/wfm.h @@ -7,7 +7,7 @@ namespace demod { class WFM : public Demodulator { public: WFM() {} - + WFM(std::string name, ConfigManager* config, dsp::stream* input, double bandwidth, EventHandler*> outputChangeHandler, double audioSR) { init(name, config, input, bandwidth, outputChangeHandler, audioSR); } @@ -23,7 +23,7 @@ namespace demod { // Load config _config->acquire(); - bool modified =false; + bool modified = false; if (!config->conf[name].contains(getName())) { config->conf[name][getName()]["stereo"] = false; modified = true; @@ -70,23 +70,23 @@ namespace demod { // ============= INFO ============= - const char* getName() { return "WFM"; } - double getIFSampleRate() { return 250000.0; } - double getAFSampleRate() { return getIFSampleRate(); } - double getDefaultBandwidth() { return 150000.0; } - double getMinBandwidth() { return 50000.0; } - double getMaxBandwidth() { return getIFSampleRate(); } - bool getBandwidthLocked() { return false; } - double getMaxAFBandwidth() { return 16000.0; } - double getDefaultSnapInterval() { return 100000.0; } - int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } - bool getDeempAllowed() { return true; } - bool getPostProcEnabled() { return true; } - int getDefaultDeemphasisMode() { return DEEMP_MODE_50US; } + const char* getName() { return "WFM"; } + double getIFSampleRate() { return 250000.0; } + double getAFSampleRate() { return getIFSampleRate(); } + double getDefaultBandwidth() { return 150000.0; } + double getMinBandwidth() { return 50000.0; } + double getMaxBandwidth() { return getIFSampleRate(); } + bool getBandwidthLocked() { return false; } + double getMaxAFBandwidth() { return 16000.0; } + double getDefaultSnapInterval() { return 100000.0; } + int getVFOReference() { return ImGui::WaterfallVFO::REF_CENTER; } + bool getDeempAllowed() { return true; } + bool getPostProcEnabled() { return true; } + int getDefaultDeemphasisMode() { return DEEMP_MODE_50US; } double getAFBandwidth(double bandwidth) { return 16000.0; } - bool getDynamicAFBandwidth() { return false; } - bool getFMIFNRAllowed() { return true; } - bool getNBAllowed() { return false; } + bool getDynamicAFBandwidth() { return false; } + bool getFMIFNRAllowed() { return true; } + bool getNBAllowed() { return false; } dsp::stream* getOutput() { return stereo ? demodStereo.out : &demod.out; } // ============= DEDICATED FUNCTIONS ============= @@ -108,9 +108,9 @@ namespace demod { private: dsp::FMDemod demod; dsp::StereoFMDemod demodStereo; - + ConfigManager* _config = NULL; - + bool stereo = false; std::string name; diff --git a/decoder_modules/radio/src/main.cpp b/decoder_modules/radio/src/main.cpp index f1bc4ebe..d65ff421 100644 --- a/decoder_modules/radio/src/main.cpp +++ b/decoder_modules/radio/src/main.cpp @@ -1,7 +1,7 @@ #include "radio_module.h" #include -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "radio", /* Description: */ "Analog radio decoder", /* Author: */ "Ryzerth", diff --git a/decoder_modules/radio/src/radio_module.h b/decoder_modules/radio/src/radio_module.h index 6c253e20..6f12cf27 100644 --- a/decoder_modules/radio/src/radio_module.h +++ b/decoder_modules/radio/src/radio_module.h @@ -14,12 +14,12 @@ ConfigManager config; -#define CONCAT(a, b) ((std::string(a) + b).c_str()) +#define CONCAT(a, b) ((std::string(a) + b).c_str()) std::map deempTaus = { - {DEEMP_MODE_22US, 22e-6}, - {DEEMP_MODE_50US, 50e-6}, - {DEEMP_MODE_75US, 75e-6} + { DEEMP_MODE_22US, 22e-6 }, + { DEEMP_MODE_50US, 50e-6 }, + { DEEMP_MODE_75US, 75e-6 } }; class RadioModule : public ModuleManager::Instance { @@ -91,11 +91,11 @@ public: config.conf[name][demod->getName()]["squelchEnabled"] = false; } bw = std::clamp(bw, demod->getMinBandwidth(), demod->getMaxBandwidth()); - + // Initialize demod->init(name, &config, ifChain.getOutput(), bw, _demodOutputChangeHandler, stream.getSampleRate()); } - + // Initialize audio DSP chain afChainOutputChanged.ctx = this; afChainOutputChanged.handler = afChainOutputChangeHandler; @@ -194,7 +194,7 @@ private: ImGui::BeginGroup(); ImGui::Columns(4, CONCAT("RadioModeColumns##_", _this->name), false); - if (ImGui::RadioButton(CONCAT("NFM##_", _this->name), _this->selectedDemodID == 0) && _this->selectedDemodID != 0) { + if (ImGui::RadioButton(CONCAT("NFM##_", _this->name), _this->selectedDemodID == 0) && _this->selectedDemodID != 0) { _this->selectDemodByID(RADIO_DEMOD_NFM); } if (ImGui::RadioButton(CONCAT("WFM##_", _this->name), _this->selectedDemodID == 1) && _this->selectedDemodID != 1) { @@ -204,7 +204,7 @@ private: if (ImGui::RadioButton(CONCAT("AM##_", _this->name), _this->selectedDemodID == 2) && _this->selectedDemodID != 2) { _this->selectDemodByID(RADIO_DEMOD_AM); } - if (ImGui::RadioButton(CONCAT("DSB##_", _this->name), _this->selectedDemodID == 3) && _this->selectedDemodID != 3) { + if (ImGui::RadioButton(CONCAT("DSB##_", _this->name), _this->selectedDemodID == 3) && _this->selectedDemodID != 3) { _this->selectDemodByID(RADIO_DEMOD_DSB); } ImGui::NextColumn(); @@ -279,7 +279,7 @@ private: } if (!_this->nbEnabled && _this->enabled) { style::endDisabled(); } } - + // // Notch filter // if (ImGui::Checkbox("Notch##_radio_notch_ena_", &_this->notchEnabled)) { @@ -484,7 +484,7 @@ private: // Configure deemphasis sample rate deemp.block.setSampleRate(audioSampleRate); - + afChain.start(); } @@ -626,7 +626,7 @@ private: // Success return; } - + // Handlers EventHandler onUserChangedBandwidthHandler; EventHandler srChangeHandler; @@ -686,5 +686,4 @@ private: const double MAX_SQUELCH = 0.0; bool enabled = true; - }; diff --git a/decoder_modules/weather_sat_decoder/src/main.cpp b/decoder_modules/weather_sat_decoder/src/main.cpp index e25ebe75..193268f6 100644 --- a/decoder_modules/weather_sat_decoder/src/main.cpp +++ b/decoder_modules/weather_sat_decoder/src/main.cpp @@ -22,9 +22,9 @@ #include #include -#define CONCAT(a, b) ((std::string(a) + b).c_str()) +#define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "weather_sat_decoder", /* Description: */ "Weather Satellite Decoder for SDR++", /* Author: */ "Ryzerth", @@ -34,7 +34,7 @@ SDRPP_MOD_INFO { std::string genFileName(std::string prefix, std::string suffix) { time_t now = time(0); - tm *ltm = localtime(&now); + tm* ltm = localtime(&now); char buf[1024]; sprintf(buf, "%s_%02d-%02d-%02d_%02d-%02d-%02d%s", prefix.c_str(), ltm->tm_hour, ltm->tm_min, ltm->tm_sec, ltm->tm_mday, ltm->tm_mon + 1, ltm->tm_year + 1900, suffix.c_str()); return buf; @@ -59,7 +59,7 @@ public: } selectDecoder(decoderNames[0], false); - + gui::menu.registerEntry(name, menuHandler, this, this); } @@ -120,7 +120,7 @@ private: std::string name; bool enabled = true; - + VFOManager::VFO* vfo; std::map decoders; @@ -129,7 +129,6 @@ private: int decoderId = 0; SatDecoder* decoder; - }; MOD_EXPORT void _INIT_() { diff --git a/decoder_modules/weather_sat_decoder/src/noaa_hrpt_decoder.h b/decoder_modules/weather_sat_decoder/src/noaa_hrpt_decoder.h index 8baccb93..8584f9f1 100644 --- a/decoder_modules/weather_sat_decoder/src/noaa_hrpt_decoder.h +++ b/decoder_modules/weather_sat_decoder/src/noaa_hrpt_decoder.h @@ -9,8 +9,8 @@ #include #include -#define NOAA_HRPT_VFO_SR 3000000.0f -#define NOAA_HRPT_VFO_BW 2000000.0f +#define NOAA_HRPT_VFO_SR 3000000.0f +#define NOAA_HRPT_VFO_BW 2000000.0f class NOAAHRPTDecoder : public SatDecoder { public: @@ -19,15 +19,15 @@ public: _name = name; // Core DSP - demod.init(vfo->output, NOAA_HRPT_VFO_SR, 665400.0f * 2.0f, 0.02e-3, (0.06f*0.06f) / 2.0f, 32, 0.6f, (0.01f*0.01f) / 4.0f, 0.01f, 0.005); - + demod.init(vfo->output, NOAA_HRPT_VFO_SR, 665400.0f * 2.0f, 0.02e-3, (0.06f * 0.06f) / 2.0f, 32, 0.6f, (0.01f * 0.01f) / 4.0f, 0.01f, 0.005); + split.init(demod.out); split.bindStream(&dataStream); split.bindStream(&visStream); - reshape.init(&visStream, 1024, (NOAA_HRPT_VFO_SR/30) - 1024); + reshape.init(&visStream, 1024, (NOAA_HRPT_VFO_SR / 30) - 1024); visSink.init(&reshape.out, visHandler, this); - + deframe.init(&dataStream, 11090 * 10 * 2, (uint8_t*)dsp::noaa::HRPTSyncWord, 60); manDec.init(&deframe.out, false); packer.init(&manDec.out); @@ -125,7 +125,7 @@ public: compositeThread = std::thread(&NOAAHRPTDecoder::avhrrCompositeWorker, this); }; - + void stop() { compositeIn1.stopReader(); compositeIn1.stopWriter(); @@ -187,7 +187,7 @@ public: compositeIn2.clearReadStop(); compositeIn2.clearWriteStop(); }; - + void setVFO(VFOManager::VFO* vfo) { _vfo = vfo; demod.setInput(_vfo->output); @@ -196,7 +196,7 @@ public: virtual bool canRecord() { return false; } - + // bool startRecording(std::string recPath) { // }; @@ -208,7 +208,7 @@ public: // bool isRecording() { // }; - + void drawMenu(float menuWidth) { ImGui::SetNextItemWidth(menuWidth); symDiag.draw(); @@ -285,7 +285,7 @@ public: ImGui::Checkbox("Show Image", &showWindow); }; - + private: // AVHRR Data Handlers void avhrrCompositeWorker() { @@ -294,16 +294,16 @@ private: while (true) { if (compositeIn1.read() < 0) { return; } if (compositeIn2.read() < 0) { return; } - + uint8_t* buf = avhrrRGBImage.acquireNextLine(); float rg, b; for (int i = 0; i < 2048; i++) { b = ((float)compositeIn1.readBuf[i] * 255.0f) / 1024.0f; rg = ((float)compositeIn2.readBuf[i] * 255.0f) / 1024.0f; - buf[(i*4)] = rg; - buf[(i*4) + 1] = rg; - buf[(i*4) + 2] = b; - buf[(i*4) + 3] = 255; + buf[(i * 4)] = rg; + buf[(i * 4) + 1] = rg; + buf[(i * 4) + 2] = b; + buf[(i * 4) + 3] = 255; } avhrrRGBImage.releaseNextLine(); @@ -318,10 +318,10 @@ private: float val; for (int i = 0; i < 2048; i++) { val = ((float)data[i] * 255.0f) / 1024.0f; - buf[(i*4)] = val; - buf[(i*4) + 1] = val; - buf[(i*4) + 2] = val; - buf[(i*4) + 3] = 255; + buf[(i * 4)] = val; + buf[(i * 4) + 1] = val; + buf[(i * 4) + 2] = val; + buf[(i * 4) + 3] = 255; } _this->avhrr1Image.releaseNextLine(); @@ -335,10 +335,10 @@ private: float val; for (int i = 0; i < 2048; i++) { val = ((float)data[i] * 255.0f) / 1024.0f; - buf[(i*4)] = val; - buf[(i*4) + 1] = val; - buf[(i*4) + 2] = val; - buf[(i*4) + 3] = 255; + buf[(i * 4)] = val; + buf[(i * 4) + 1] = val; + buf[(i * 4) + 2] = val; + buf[(i * 4) + 3] = 255; } _this->avhrr2Image.releaseNextLine(); @@ -352,10 +352,10 @@ private: float val; for (int i = 0; i < 2048; i++) { val = ((float)data[i] * 255.0f) / 1024.0f; - buf[(i*4)] = val; - buf[(i*4) + 1] = val; - buf[(i*4) + 2] = val; - buf[(i*4) + 3] = 255; + buf[(i * 4)] = val; + buf[(i * 4) + 1] = val; + buf[(i * 4) + 2] = val; + buf[(i * 4) + 3] = 255; } _this->avhrr3Image.releaseNextLine(); } @@ -366,10 +366,10 @@ private: float val; for (int i = 0; i < 2048; i++) { val = ((float)data[i] * 255.0f) / 1024.0f; - buf[(i*4)] = val; - buf[(i*4) + 1] = val; - buf[(i*4) + 2] = val; - buf[(i*4) + 3] = 255; + buf[(i * 4)] = val; + buf[(i * 4) + 1] = val; + buf[(i * 4) + 2] = val; + buf[(i * 4) + 3] = 255; } _this->avhrr4Image.releaseNextLine(); } @@ -380,10 +380,10 @@ private: float val; for (int i = 0; i < 2048; i++) { val = ((float)data[i] * 255.0f) / 1024.0f; - buf[(i*4)] = val; - buf[(i*4) + 1] = val; - buf[(i*4) + 2] = val; - buf[(i*4) + 3] = 255; + buf[(i * 4)] = val; + buf[(i * 4) + 1] = val; + buf[(i * 4) + 2] = val; + buf[(i * 4) + 3] = 255; } _this->avhrr5Image.releaseNextLine(); } @@ -391,102 +391,82 @@ private: // HIRS Data Handlers static void hirs1Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs2Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs3Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs4Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs5Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs6Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs7Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs8Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs9Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs10Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs11Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs12Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs13Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs14Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs15Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs16Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs17Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs18Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs19Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void hirs20Handler(uint16_t* data, int count, void* ctx) { NOAAHRPTDecoder* _this = (NOAAHRPTDecoder*)ctx; - } static void visHandler(float* data, int count, void* ctx) { @@ -568,5 +548,4 @@ private: std::thread compositeThread; bool showWindow = false; - }; \ No newline at end of file diff --git a/decoder_modules/weather_sat_decoder/src/sat_decoder.h b/decoder_modules/weather_sat_decoder/src/sat_decoder.h index ad90469c..0a717e64 100644 --- a/decoder_modules/weather_sat_decoder/src/sat_decoder.h +++ b/decoder_modules/weather_sat_decoder/src/sat_decoder.h @@ -10,7 +10,7 @@ public: virtual void setVFO(VFOManager::VFO* vfo) = 0; virtual bool canRecord() = 0; virtual bool startRecording(std::string recPath) { return false; }; - virtual void stopRecording() { }; + virtual void stopRecording(){}; virtual bool isRecording() { return false; }; virtual void drawMenu(float menuWidth) = 0; }; \ No newline at end of file diff --git a/misc_modules/demo_module/src/main.cpp b/misc_modules/demo_module/src/main.cpp index 2f31504c..ca760015 100644 --- a/misc_modules/demo_module/src/main.cpp +++ b/misc_modules/demo_module/src/main.cpp @@ -2,7 +2,7 @@ #include #include -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "demo", /* Description: */ "My fancy new module", /* Author: */ "author1;author2,author3,etc...", @@ -43,7 +43,6 @@ private: std::string name; bool enabled = true; - }; MOD_EXPORT void _INIT_() { diff --git a/misc_modules/discord_integration/src/main.cpp b/misc_modules/discord_integration/src/main.cpp index ec22c659..7314d58e 100644 --- a/misc_modules/discord_integration/src/main.cpp +++ b/misc_modules/discord_integration/src/main.cpp @@ -8,7 +8,7 @@ #include #include -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "discord_integration", /* Description: */ "Discord Rich Presence module for SDR++", /* Author: */ "Cam K.;Ryzerth", @@ -16,7 +16,7 @@ SDRPP_MOD_INFO { /* Max instances */ 1 }; -#define DISCORD_APP_ID "834590435708108860" +#define DISCORD_APP_ID "834590435708108860" class DiscordIntegrationModule : public ModuleManager::Instance { public: @@ -61,14 +61,13 @@ public: } private: - // Main thread void worker() { // TODO: Switch out for condition variable to terminate thread instantly // OR even better, the new timer class that I still need to add while (workerRunning) { workerCounter++; - if(workerCounter >= 1000) { + if (workerCounter >= 1000) { workerCounter = 0; updatePresence(); } @@ -87,15 +86,27 @@ private: int modeNum; core::modComManager.callInterface(selectedName, RADIO_IFACE_CMD_GET_MODE, NULL, &modeNum); if (modeNum == RADIO_IFACE_MODE_NFM) { strcpy(mode, "NFM"); } - else if (modeNum == RADIO_IFACE_MODE_WFM) { strcpy(mode, "FM"); } - else if (modeNum == RADIO_IFACE_MODE_AM) { strcpy(mode, "AM"); } - else if (modeNum == RADIO_IFACE_MODE_DSB) { strcpy(mode, "DSB"); } - else if (modeNum == RADIO_IFACE_MODE_USB) { strcpy(mode, "USB"); } - else if (modeNum == RADIO_IFACE_MODE_CW) { strcpy(mode, "CW"); } - else if (modeNum == RADIO_IFACE_MODE_LSB) { strcpy(mode, "LSB"); } + else if (modeNum == RADIO_IFACE_MODE_WFM) { + strcpy(mode, "FM"); + } + else if (modeNum == RADIO_IFACE_MODE_AM) { + strcpy(mode, "AM"); + } + else if (modeNum == RADIO_IFACE_MODE_DSB) { + strcpy(mode, "DSB"); + } + else if (modeNum == RADIO_IFACE_MODE_USB) { + strcpy(mode, "USB"); + } + else if (modeNum == RADIO_IFACE_MODE_CW) { + strcpy(mode, "CW"); + } + else if (modeNum == RADIO_IFACE_MODE_LSB) { + strcpy(mode, "LSB"); + } } } - + if (selectedFreq != lastFreq || mode != lastMode) { lastFreq = selectedFreq; lastMode = mode; @@ -146,7 +157,6 @@ private: int workerCounter = 0; std::thread workerThread; bool workerRunning; - }; MOD_EXPORT void _INIT_() { diff --git a/misc_modules/frequency_manager/src/main.cpp b/misc_modules/frequency_manager/src/main.cpp index 4de26024..a793c447 100644 --- a/misc_modules/frequency_manager/src/main.cpp +++ b/misc_modules/frequency_manager/src/main.cpp @@ -14,7 +14,7 @@ #include #include -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "frequency_manager", /* Description: */ "Frequency manager module for SDR++", /* Author: */ "Ryzerth;Zimm", @@ -104,7 +104,6 @@ public: } private: - static void applyBookmark(FrequencyBookmark bm, std::string vfoName) { if (vfoName == "") { // TODO: Replace with proper tune call @@ -135,14 +134,14 @@ private: strcpy(nameBuf, editedBookmarkName.c_str()); if (ImGui::BeginPopup(id.c_str(), ImGuiWindowFlags_NoResize)) { - ImGui::BeginTable(("freq_manager_edit_table"+name).c_str(), 2); - + ImGui::BeginTable(("freq_manager_edit_table" + name).c_str(), 2); + ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::LeftLabel("Name"); ImGui::TableSetColumnIndex(1); ImGui::SetNextItemWidth(200); - if (ImGui::InputText(("##freq_manager_edit_name"+name).c_str(), nameBuf, 1023)) { + if (ImGui::InputText(("##freq_manager_edit_name" + name).c_str(), nameBuf, 1023)) { editedBookmarkName = nameBuf; } @@ -151,14 +150,14 @@ private: ImGui::LeftLabel("Frequency"); ImGui::TableSetColumnIndex(1); ImGui::SetNextItemWidth(200); - ImGui::InputDouble(("##freq_manager_edit_freq"+name).c_str(), &editedBookmark.frequency); + ImGui::InputDouble(("##freq_manager_edit_freq" + name).c_str(), &editedBookmark.frequency); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); ImGui::LeftLabel("Bandwidth"); ImGui::TableSetColumnIndex(1); ImGui::SetNextItemWidth(200); - ImGui::InputDouble(("##freq_manager_edit_bw"+name).c_str(), &editedBookmark.bandwidth); + ImGui::InputDouble(("##freq_manager_edit_bw" + name).c_str(), &editedBookmark.bandwidth); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); @@ -166,7 +165,7 @@ private: ImGui::TableSetColumnIndex(1); ImGui::SetNextItemWidth(200); - ImGui::Combo(("##freq_manager_edit_mode"+name).c_str(), &editedBookmark.mode, demodModeListTxt); + ImGui::Combo(("##freq_manager_edit_mode" + name).c_str(), &editedBookmark.mode, demodModeListTxt); ImGui::EndTable(); @@ -174,7 +173,7 @@ private: if (applyDisabled) { style::beginDisabled(); } if (ImGui::Button("Apply")) { open = false; - + // If editing, delete the original one if (editOpen) { bookmarks.erase(firstEditedBookmarkName); @@ -208,7 +207,7 @@ private: if (ImGui::BeginPopup(id.c_str(), ImGuiWindowFlags_NoResize)) { ImGui::LeftLabel("Name"); ImGui::SetNextItemWidth(menuWidth - ImGui::GetCursorPosX()); - if (ImGui::InputText(("##freq_manager_edit_name"+name).c_str(), nameBuf, 1023)) { + if (ImGui::InputText(("##freq_manager_edit_name" + name).c_str(), nameBuf, 1023)) { editedListName = nameBuf; } @@ -256,7 +255,7 @@ private: // No need to lock config since we're not modifying anything and there's only one instance for (auto [listName, list] : config.conf["lists"].items()) { bool shown = list["showOnWaterfall"]; - if (ImGui::Checkbox((listName+"##freq_manager_sel_list_").c_str(), &shown)) { + if (ImGui::Checkbox((listName + "##freq_manager_sel_list_").c_str(), &shown)) { config.acquire(); config.conf["lists"][listName]["showOnWaterfall"] = shown; refreshWaterfallBookmarks(false); @@ -353,13 +352,15 @@ private: // TODO: Replace with something that won't iterate every frame std::vector selectedNames; - for (auto& [name, bm] : _this->bookmarks) { if (bm.selected) { selectedNames.push_back(name); } } + for (auto& [name, bm] : _this->bookmarks) { + if (bm.selected) { selectedNames.push_back(name); } + } float lineHeight = ImGui::GetTextLineHeightWithSpacing(); float btnSize = ImGui::CalcTextSize("Rename").x + 8; - ImGui::SetNextItemWidth(menuWidth - 24 - (2*lineHeight) - btnSize); - if (ImGui::Combo(("##freq_manager_list_sel"+_this->name).c_str(), &_this->selectedListId, _this->listNamesTxt.c_str())) { + ImGui::SetNextItemWidth(menuWidth - 24 - (2 * lineHeight) - btnSize); + if (ImGui::Combo(("##freq_manager_list_sel" + _this->name).c_str(), &_this->selectedListId, _this->listNamesTxt.c_str())) { _this->loadByName(_this->listNames[_this->selectedListId]); config.acquire(); config.conf["selectedList"] = _this->selectedListName; @@ -397,9 +398,9 @@ private: if (_this->selectedListName == "") { style::endDisabled(); } // List delete confirmation - if (ImGui::GenericDialog(("freq_manager_del_list_confirm"+_this->name).c_str(), _this->deleteListOpen, GENERIC_DIALOG_BUTTONS_YES_NO, [_this](){ - ImGui::Text("Deleting list named \"%s\". Are you sure?", _this->selectedListName.c_str()); - }) == GENERIC_DIALOG_BUTTON_YES) { + if (ImGui::GenericDialog(("freq_manager_del_list_confirm" + _this->name).c_str(), _this->deleteListOpen, GENERIC_DIALOG_BUTTONS_YES_NO, [_this]() { + ImGui::Text("Deleting list named \"%s\". Are you sure?", _this->selectedListName.c_str()); + }) == GENERIC_DIALOG_BUTTON_YES) { config.acquire(); config.conf["lists"].erase(_this->selectedListName); _this->refreshWaterfallBookmarks(false); @@ -413,10 +414,10 @@ private: _this->selectedListName = ""; } } - + if (_this->selectedListName == "") { style::beginDisabled(); } //Draw buttons on top of the list - ImGui::BeginTable(("freq_manager_btn_table"+_this->name).c_str(), 3); + ImGui::BeginTable(("freq_manager_btn_table" + _this->name).c_str(), 3); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); @@ -471,20 +472,20 @@ private: _this->firstEditedBookmarkName = selectedNames[0]; } if (selectedNames.size() != 1 && _this->selectedListName != "") { style::endDisabled(); } - + ImGui::EndTable(); // Bookmark delete confirm dialog // List delete confirmation - if (ImGui::GenericDialog(("freq_manager_del_list_confirm"+_this->name).c_str(), _this->deleteBookmarksOpen, GENERIC_DIALOG_BUTTONS_YES_NO, [_this](){ - ImGui::Text("Deleting selected bookmaks. Are you sure?"); - }) == GENERIC_DIALOG_BUTTON_YES) { + if (ImGui::GenericDialog(("freq_manager_del_list_confirm" + _this->name).c_str(), _this->deleteBookmarksOpen, GENERIC_DIALOG_BUTTONS_YES_NO, [_this]() { + ImGui::Text("Deleting selected bookmaks. Are you sure?"); + }) == GENERIC_DIALOG_BUTTON_YES) { for (auto& _name : selectedNames) { _this->bookmarks.erase(_name); } _this->saveByName(_this->selectedListName); } // Bookmark list - if (ImGui::BeginTable(("freq_manager_bkm_table"+_this->name).c_str(), 2, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, ImVec2(0, 200))) { + if (ImGui::BeginTable(("freq_manager_bkm_table" + _this->name).c_str(), 2, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, ImVec2(0, 200))) { ImGui::TableSetupColumn("Name"); ImGui::TableSetupColumn("Bookmark"); ImGui::TableSetupScrollFreeze(2, 1); @@ -514,7 +515,7 @@ private: } ImGui::EndTable(); } - + if (selectedNames.size() != 1 && _this->selectedListName != "") { style::beginDisabled(); } if (ImGui::Button(("Apply##_freq_mgr_apply_" + _this->name).c_str(), ImVec2(menuWidth, 0))) { @@ -525,13 +526,13 @@ private: if (selectedNames.size() != 1 && _this->selectedListName != "") { style::endDisabled(); } //Draw import and export buttons - ImGui::BeginTable(("freq_manager_bottom_btn_table"+_this->name).c_str(), 2); + ImGui::BeginTable(("freq_manager_bottom_btn_table" + _this->name).c_str(), 2); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); if (ImGui::Button(("Import##_freq_mgr_imp_" + _this->name).c_str(), ImVec2(ImGui::GetContentRegionAvailWidth(), 0)) && !_this->importOpen) { _this->importOpen = true; - _this->importDialog = new pfd::open_file("Import bookmarks", "", {"JSON Files (*.json)", "*.json", "All Files", "*"}, true); + _this->importDialog = new pfd::open_file("Import bookmarks", "", { "JSON Files (*.json)", "*.json", "All Files", "*" }, true); } ImGui::TableSetColumnIndex(1); @@ -544,7 +545,7 @@ private: } config.release(); _this->exportOpen = true; - _this->exportDialog = new pfd::save_file("Export bookmarks", "", {"JSON Files (*.json)", "*.json", "All Files", "*"}, true); + _this->exportDialog = new pfd::save_file("Export bookmarks", "", { "JSON Files (*.json)", "*.json", "All Files", "*" }, true); } if (selectedNames.size() == 0 && _this->selectedListName != "") { style::endDisabled(); } ImGui::EndTable(); @@ -606,17 +607,17 @@ private: FrequencyManagerModule* _this = (FrequencyManagerModule*)ctx; if (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_OFF) { return; } - if (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_TOP) { + if (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_TOP) { for (auto const bm : _this->waterfallBookmarks) { double centerXpos = args.min.x + std::round((bm.bookmark.frequency - args.lowFreq) * args.freqToPixelRatio); - + if (bm.bookmark.frequency >= args.lowFreq && bm.bookmark.frequency <= args.highFreq) { args.window->DrawList->AddLine(ImVec2(centerXpos, args.min.y), ImVec2(centerXpos, args.max.y), IM_COL32(255, 255, 0, 255)); } ImVec2 nameSize = ImGui::CalcTextSize(bm.bookmarkName.c_str()); - ImVec2 rectMin = ImVec2(centerXpos-(nameSize.x/2)-5, args.min.y); - ImVec2 rectMax = ImVec2(centerXpos+(nameSize.x/2)+5, args.min.y+nameSize.y); + ImVec2 rectMin = ImVec2(centerXpos - (nameSize.x / 2) - 5, args.min.y); + ImVec2 rectMax = ImVec2(centerXpos + (nameSize.x / 2) + 5, args.min.y + nameSize.y); ImVec2 clampedRectMin = ImVec2(std::clamp(rectMin.x, args.min.x, args.max.x), rectMin.y); ImVec2 clampedRectMax = ImVec2(std::clamp(rectMax.x, args.min.x, args.max.x), rectMax.y); @@ -624,21 +625,21 @@ private: args.window->DrawList->AddRectFilled(clampedRectMin, clampedRectMax, IM_COL32(255, 255, 0, 255)); } if (rectMin.x >= args.min.x && rectMax.x <= args.max.x) { - args.window->DrawList->AddText(ImVec2(centerXpos-(nameSize.x/2), args.min.y), IM_COL32(0, 0, 0, 255), bm.bookmarkName.c_str()); + args.window->DrawList->AddText(ImVec2(centerXpos - (nameSize.x / 2), args.min.y), IM_COL32(0, 0, 0, 255), bm.bookmarkName.c_str()); } } } else if (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_BOTTOM) { for (auto const bm : _this->waterfallBookmarks) { double centerXpos = args.min.x + std::round((bm.bookmark.frequency - args.lowFreq) * args.freqToPixelRatio); - + if (bm.bookmark.frequency >= args.lowFreq && bm.bookmark.frequency <= args.highFreq) { args.window->DrawList->AddLine(ImVec2(centerXpos, args.min.y), ImVec2(centerXpos, args.max.y), IM_COL32(255, 255, 0, 255)); } ImVec2 nameSize = ImGui::CalcTextSize(bm.bookmarkName.c_str()); - ImVec2 rectMin = ImVec2(centerXpos-(nameSize.x/2)-5, args.max.y - nameSize.y); - ImVec2 rectMax = ImVec2(centerXpos+(nameSize.x/2)+5, args.max.y); + ImVec2 rectMin = ImVec2(centerXpos - (nameSize.x / 2) - 5, args.max.y - nameSize.y); + ImVec2 rectMax = ImVec2(centerXpos + (nameSize.x / 2) + 5, args.max.y); ImVec2 clampedRectMin = ImVec2(std::clamp(rectMin.x, args.min.x, args.max.x), rectMin.y); ImVec2 clampedRectMax = ImVec2(std::clamp(rectMax.x, args.min.x, args.max.x), rectMax.y); @@ -646,10 +647,10 @@ private: args.window->DrawList->AddRectFilled(clampedRectMin, clampedRectMax, IM_COL32(255, 255, 0, 255)); } if (rectMin.x >= args.min.x && rectMax.x <= args.max.x) { - args.window->DrawList->AddText(ImVec2(centerXpos-(nameSize.x/2), args.max.y - nameSize.y), IM_COL32(0, 0, 0, 255), bm.bookmarkName.c_str()); + args.window->DrawList->AddText(ImVec2(centerXpos - (nameSize.x / 2), args.max.y - nameSize.y), IM_COL32(0, 0, 0, 255), bm.bookmarkName.c_str()); } } - } + } } bool mouseAlreadyDown = false; @@ -673,12 +674,12 @@ private: if (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_TOP) { int count = _this->waterfallBookmarks.size(); - for (int i = count-1; i >= 0; i--) { + for (int i = count - 1; i >= 0; i--) { auto& bm = _this->waterfallBookmarks[i]; double centerXpos = args.fftRectMin.x + std::round((bm.bookmark.frequency - args.lowFreq) * args.freqToPixelRatio); ImVec2 nameSize = ImGui::CalcTextSize(bm.bookmarkName.c_str()); - ImVec2 rectMin = ImVec2(centerXpos-(nameSize.x/2)-5, args.fftRectMin.y); - ImVec2 rectMax = ImVec2(centerXpos+(nameSize.x/2)+5, args.fftRectMin.y+nameSize.y); + ImVec2 rectMin = ImVec2(centerXpos - (nameSize.x / 2) - 5, args.fftRectMin.y); + ImVec2 rectMax = ImVec2(centerXpos + (nameSize.x / 2) + 5, args.fftRectMin.y + nameSize.y); ImVec2 clampedRectMin = ImVec2(std::clamp(rectMin.x, args.fftRectMin.x, args.fftRectMax.x), rectMin.y); ImVec2 clampedRectMax = ImVec2(std::clamp(rectMax.x, args.fftRectMin.x, args.fftRectMax.x), rectMax.y); @@ -692,12 +693,12 @@ private: } else if (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_BOTTOM) { int count = _this->waterfallBookmarks.size(); - for (int i = count-1; i >= 0; i--) { + for (int i = count - 1; i >= 0; i--) { auto& bm = _this->waterfallBookmarks[i]; double centerXpos = args.fftRectMin.x + std::round((bm.bookmark.frequency - args.lowFreq) * args.freqToPixelRatio); ImVec2 nameSize = ImGui::CalcTextSize(bm.bookmarkName.c_str()); - ImVec2 rectMin = ImVec2(centerXpos-(nameSize.x/2)-5, args.fftRectMax.y-nameSize.y); - ImVec2 rectMax = ImVec2(centerXpos+(nameSize.x/2)+5, args.fftRectMax.y); + ImVec2 rectMin = ImVec2(centerXpos - (nameSize.x / 2) - 5, args.fftRectMax.y - nameSize.y); + ImVec2 rectMax = ImVec2(centerXpos + (nameSize.x / 2) + 5, args.fftRectMax.y); ImVec2 clampedRectMin = ImVec2(std::clamp(rectMin.x, args.fftRectMin.x, args.fftRectMax.x), rectMin.y); ImVec2 clampedRectMax = ImVec2(std::clamp(rectMax.x, args.fftRectMin.x, args.fftRectMax.x), rectMax.y); @@ -726,8 +727,8 @@ private: double centerXpos = args.fftRectMin.x + std::round((hoveredBookmark.bookmark.frequency - args.lowFreq) * args.freqToPixelRatio); ImVec2 nameSize = ImGui::CalcTextSize(hoveredBookmarkName.c_str()); - ImVec2 rectMin = ImVec2(centerXpos-(nameSize.x/2)-5, (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_BOTTOM) ? (args.fftRectMax.y - nameSize.y) : args.fftRectMin.y); - ImVec2 rectMax = ImVec2(centerXpos+(nameSize.x/2)+5, (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_BOTTOM) ? args.fftRectMax.y : args.fftRectMin.y+nameSize.y); + ImVec2 rectMin = ImVec2(centerXpos - (nameSize.x / 2) - 5, (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_BOTTOM) ? (args.fftRectMax.y - nameSize.y) : args.fftRectMin.y); + ImVec2 rectMax = ImVec2(centerXpos + (nameSize.x / 2) + 5, (_this->bookmarkDisplayMode == BOOKMARK_DISP_MODE_BOTTOM) ? args.fftRectMax.y : args.fftRectMin.y + nameSize.y); ImVec2 clampedRectMin = ImVec2(std::clamp(rectMin.x, args.fftRectMin.x, args.fftRectMax.x), rectMin.y); ImVec2 clampedRectMax = ImVec2(std::clamp(rectMax.x, args.fftRectMin.x, args.fftRectMax.x), rectMax.y); @@ -822,7 +823,6 @@ private: std::vector waterfallBookmarks; int bookmarkDisplayMode = 0; - }; MOD_EXPORT void _INIT_() { diff --git a/misc_modules/recorder/src/main.cpp b/misc_modules/recorder/src/main.cpp index ba0762ac..ddbcecd4 100644 --- a/misc_modules/recorder/src/main.cpp +++ b/misc_modules/recorder/src/main.cpp @@ -19,7 +19,7 @@ #include #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "recorder", /* Description: */ "Recorder module for SDR++", /* Author: */ "Ryzerth", @@ -36,9 +36,10 @@ std::string expandString(std::string input) { std::string genFileName(std::string prefix, bool isVfo, std::string name = "") { time_t now = time(0); - tm *ltm = localtime(&now); + tm* ltm = localtime(&now); char buf[1024]; - double freq = gui::waterfall.getCenterFrequency();; + double freq = gui::waterfall.getCenterFrequency(); + ; if (isVfo && gui::waterfall.vfos.find(name) != gui::waterfall.vfos.end()) { freq += gui::waterfall.vfos[name]->generalOffset; } @@ -49,12 +50,12 @@ std::string genFileName(std::string prefix, bool isVfo, std::string name = "") { class RecorderModule : public ModuleManager::Instance { public: RecorderModule(std::string name) : folderSelect("%ROOT%/recordings") { - this->name = name; + this->name = name; // Load config config.acquire(); bool created = false; - + // Create config if it doesn't exist if (!config.conf.contains(name)) { config.conf[name]["mode"] = RECORDER_MODE_AUDIO; @@ -108,7 +109,7 @@ public: std::lock_guard lck(recMtx); gui::menu.removeEntry(name); core::modComManager.unregisterInterface(name); - + // Stop recording if (recording) { stopRecording(); } @@ -156,7 +157,7 @@ private: streamNamesTxt = ""; // If there are no stream, cancel - if (names.size() == 0) {return; } + if (names.size() == 0) { return; } // List streams for (auto const& name : names) { @@ -249,7 +250,7 @@ private: } uint64_t seconds = samplesWritten / (uint64_t)sampleRate; time_t diff = seconds; - tm *dtm = gmtime(&diff); + tm* dtm = gmtime(&diff); ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "Recording %02d:%02d:%02d", dtm->tm_hour, dtm->tm_min, dtm->tm_sec); } if (!folderSelect.pathIsValid()) { style::endDisabled(); } @@ -305,22 +306,22 @@ private: } uint64_t seconds = samplesWritten / (uint64_t)sampleRate; time_t diff = seconds; - tm *dtm = gmtime(&diff); + tm* dtm = gmtime(&diff); ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "Recording %02d:%02d:%02d", dtm->tm_hour, dtm->tm_min, dtm->tm_sec); } if (!folderSelect.pathIsValid() || selectedStreamName == "") { style::endDisabled(); } } - static void _audioHandler(dsp::stereo_t *data, int count, void *ctx) { + static void _audioHandler(dsp::stereo_t* data, int count, void* ctx) { RecorderModule* _this = (RecorderModule*)ctx; - volk_32f_s32f_convert_16i(_this->wavSampleBuf, (float*)data, 32767.0f, count*2); + volk_32f_s32f_convert_16i(_this->wavSampleBuf, (float*)data, 32767.0f, count * 2); _this->audioWriter->writeSamples(_this->wavSampleBuf, count * 2 * sizeof(int16_t)); _this->samplesWritten += count; } - static void _basebandHandler(dsp::complex_t *data, int count, void *ctx) { + static void _basebandHandler(dsp::complex_t* data, int count, void* ctx) { RecorderModule* _this = (RecorderModule*)ctx; - volk_32f_s32f_convert_16i(_this->wavSampleBuf, (float*)data, 32767.0f, count*2); + volk_32f_s32f_convert_16i(_this->wavSampleBuf, (float*)data, 32767.0f, count * 2); _this->basebandWriter->writeSamples(_this->wavSampleBuf, count * 2 * sizeof(int16_t)); _this->samplesWritten += count; } @@ -364,7 +365,7 @@ private: else if (recMode == RECORDER_MODE_AUDIO) { if (selectedStreamName.empty()) { spdlog::error("Cannot record with no selected stream"); - } + } samplesWritten = 0; std::string expandedPath = expandString(folderSelect.path + genFileName("/audio_", true, selectedStreamName)); sampleRate = sigpath::sinkManager.getStreamSampleRate(selectedStreamName); @@ -398,7 +399,7 @@ private: } } - static void onStreamRegistered(std::string name, void* ctx){ + static void onStreamRegistered(std::string name, void* ctx) { RecorderModule* _this = (RecorderModule*)ctx; _this->refreshStreams(); @@ -423,7 +424,7 @@ private: } } - static void onStreamUnregister(std::string name, void* ctx){ + static void onStreamUnregister(std::string name, void* ctx) { RecorderModule* _this = (RecorderModule*)ctx; if (name != _this->selectedStreamName) { return; } if (_this->recording) { _this->stopRecording(); } @@ -434,7 +435,7 @@ private: } } - static void onStreamUnregistered(std::string name, void* ctx){ + static void onStreamUnregistered(std::string name, void* ctx) { RecorderModule* _this = (RecorderModule*)ctx; _this->refreshStreams(); @@ -476,7 +477,7 @@ private: float lvlR = -90.0f; dsp::stream dummyStream; - + std::mutex recMtx; FolderSelect folderSelect; @@ -507,7 +508,6 @@ private: EventHandler streamRegisteredHandler; EventHandler streamUnregisterHandler; EventHandler streamUnregisteredHandler; - }; struct RecorderContext_t { diff --git a/misc_modules/recorder/src/wav.h b/misc_modules/recorder/src/wav.h index 4b10885f..f17ed312 100644 --- a/misc_modules/recorder/src/wav.h +++ b/misc_modules/recorder/src/wav.h @@ -34,7 +34,7 @@ public: file.write((char*)data, size); bytesWritten += size; } - + void close() { hdr.fileSize = bytesWritten + sizeof(WavHeader_t) - 8; hdr.dataSize = bytesWritten; @@ -45,18 +45,18 @@ public: private: struct WavHeader_t { - char signature[4]; // "RIFF" - uint32_t fileSize; // data bytes + sizeof(WavHeader_t) - 8 - char fileType[4]; // "WAVE" - char formatMarker[4]; // "fmt " - uint32_t formatHeaderLength; // Always 16 - uint16_t sampleType; // PCM (1) + char signature[4]; // "RIFF" + uint32_t fileSize; // data bytes + sizeof(WavHeader_t) - 8 + char fileType[4]; // "WAVE" + char formatMarker[4]; // "fmt " + uint32_t formatHeaderLength; // Always 16 + uint16_t sampleType; // PCM (1) uint16_t channelCount; uint32_t sampleRate; uint32_t bytesPerSecond; uint16_t bytesPerSample; uint16_t bitDepth; - char dataMarker[4]; // "data" + char dataMarker[4]; // "data" uint32_t dataSize; }; diff --git a/misc_modules/rigctl_server/src/main.cpp b/misc_modules/rigctl_server/src/main.cpp index 07535f8b..068f8277 100644 --- a/misc_modules/rigctl_server/src/main.cpp +++ b/misc_modules/rigctl_server/src/main.cpp @@ -13,9 +13,9 @@ #include #define CONCAT(a, b) ((std::string(a) + b).c_str()) -#define MAX_COMMAND_LENGTH 8192 +#define MAX_COMMAND_LENGTH 8192 -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "rigctl_server", /* Description: */ "My fancy new module", /* Author: */ "Ryzerth", @@ -139,7 +139,7 @@ private: config.release(true); } } - + ImGui::LeftLabel("Controlled Recorder"); ImGui::SetNextItemWidth(menuWidth - ImGui::GetCursorPosX()); { @@ -175,7 +175,7 @@ private: config.conf[_this->name]["autoStart"] = _this->autoStart; config.release(true); } - + if (listening && ImGui::Button(CONCAT("Stop##_rigctl_srv_stop_", _this->name), ImVec2(menuWidth, 0))) { _this->stopServer(); } @@ -247,7 +247,7 @@ private: selectVfoByName(vfoNames[0]); return; } - + // Select the VFO { if (lock) { std::lock_guard lck(vfoMtx); } @@ -271,8 +271,8 @@ private: } std::string type = core::modComManager.getModuleName(_name); - - + + // Select the VFO { if (lock) { std::lock_guard lck(recorderMtx); } @@ -483,7 +483,7 @@ private: core::modComManager.callInterface(selectedVfo, RADIO_IFACE_CMD_SET_BANDWIDTH, &newBandwidth, NULL); } } - + client->write(resp.size(), (uint8_t*)resp.c_str()); } else if (parts[0] == "m" || parts[0] == "\\get_mode") { @@ -493,7 +493,7 @@ private: if (!selectedVfo.empty() && core::modComManager.getModuleName(selectedVfo) == "radio") { int mode; core::modComManager.callInterface(selectedVfo, RADIO_IFACE_CMD_GET_MODE, NULL, &mode); - + if (mode == RADIO_IFACE_MODE_NFM) { resp = "FM\n"; } @@ -684,7 +684,7 @@ private: /* Bit field list of get level */ "0x40000020\n" /* RIG_LEVEL_SQL | RIG_LEVEL_STRENGTH */ /* Bit field list of set level */ - "0x20\n" /* RIG_LEVEL_SQL */ + "0x20\n" /* RIG_LEVEL_SQL */ /* Bit field list of get parm */ "0\n" /* RIG_PARM_NONE */ /* Bit field list of set parm */ diff --git a/misc_modules/scanner/src/main.cpp b/misc_modules/scanner/src/main.cpp index 881a5846..ff66fb1f 100644 --- a/misc_modules/scanner/src/main.cpp +++ b/misc_modules/scanner/src/main.cpp @@ -2,7 +2,7 @@ #include #include -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "scanner", /* Description: */ "Frequency scanner for SDR++", /* Author: */ "Ryzerth", @@ -43,7 +43,6 @@ private: std::string name; bool enabled = true; - }; MOD_EXPORT void _INIT_() { diff --git a/misc_modules/scheduler/src/actions/start_recorder.h b/misc_modules/scheduler/src/actions/start_recorder.h index 9680b543..0ecb153b 100644 --- a/misc_modules/scheduler/src/actions/start_recorder.h +++ b/misc_modules/scheduler/src/actions/start_recorder.h @@ -8,11 +8,9 @@ namespace sched_action { ~StartRecorderClass() {} void trigger() { - } void prepareEditMenu() { - } bool showEditMenu(bool& valid) { @@ -40,7 +38,6 @@ namespace sched_action { std::string recorderName; std::string name = "Start \"\""; - }; Action StartRecorder() { diff --git a/misc_modules/scheduler/src/actions/tune_vfo.h b/misc_modules/scheduler/src/actions/tune_vfo.h index 223235bc..127bda68 100644 --- a/misc_modules/scheduler/src/actions/tune_vfo.h +++ b/misc_modules/scheduler/src/actions/tune_vfo.h @@ -138,7 +138,6 @@ namespace sched_action { int vfoNameId = -1; std::string name; - }; Action TuneVFO() { diff --git a/misc_modules/scheduler/src/main.cpp b/misc_modules/scheduler/src/main.cpp index 5337e3c6..16ae853e 100644 --- a/misc_modules/scheduler/src/main.cpp +++ b/misc_modules/scheduler/src/main.cpp @@ -4,7 +4,7 @@ #include #include -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "scheduler", /* Description: */ "SDR++ Scheduler", /* Author: */ "Ryzerth", @@ -23,7 +23,7 @@ public: json recStartConfig; recStartConfig["recorder"] = "Recorder"; - + json tuneVFOConfig; tuneVFOConfig["vfo"] = "Radio"; tuneVFOConfig["frequency"] = 103500000.0; @@ -62,7 +62,7 @@ public: private: static void menuHandler(void* ctx) { DemoModule* _this = (DemoModule*)ctx; - + // If editing, show menu if (!_this->editedTask.empty()) { gui::mainWindow.lockWaterfallControls = true; @@ -89,7 +89,7 @@ private: } } - if (ImGui::BeginTable(("freq_manager_bkm_table"+_this->name).c_str(), 2, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, ImVec2(0, 200))) { + if (ImGui::BeginTable(("freq_manager_bkm_table" + _this->name).c_str(), 2, ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY, ImVec2(0, 200))) { ImGui::TableSetupColumn("Name"); ImGui::TableSetupColumn("Countdown"); ImGui::TableSetupScrollFreeze(2, 1); @@ -127,7 +127,6 @@ private: char editedName[1024]; std::map tasks; - }; MOD_EXPORT void _INIT_() { diff --git a/misc_modules/scheduler/src/sched_action.h b/misc_modules/scheduler/src/sched_action.h index 34a06667..814ceaf8 100644 --- a/misc_modules/scheduler/src/sched_action.h +++ b/misc_modules/scheduler/src/sched_action.h @@ -8,7 +8,7 @@ using namespace nlohmann; namespace sched_action { class ActionClass { public: - virtual ~ActionClass() {}; + virtual ~ActionClass(){}; virtual void trigger() = 0; virtual void prepareEditMenu() = 0; virtual bool showEditMenu(bool& valid) = 0; @@ -21,12 +21,12 @@ namespace sched_action { } bool selected = false; - + private: bool valid = false; }; - typedef std::shared_ptr Action; + typedef std::shared_ptr Action; } #include diff --git a/misc_modules/scheduler/src/sched_task.h b/misc_modules/scheduler/src/sched_task.h index 3faf7383..6f9eeaa6 100644 --- a/misc_modules/scheduler/src/sched_task.h +++ b/misc_modules/scheduler/src/sched_task.h @@ -56,7 +56,7 @@ public: ImGui::TableSetupColumn("Triggers"); ImGui::TableSetupScrollFreeze(1, 1); ImGui::TableHeadersRow(); - + // Fill rows here ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); @@ -119,5 +119,4 @@ private: std::vector actions; int editedAction = -1; - }; \ No newline at end of file diff --git a/sink_modules/audio_sink/src/main.cpp b/sink_modules/audio_sink/src/main.cpp index 705ac7bc..fff558cf 100644 --- a/sink_modules/audio_sink/src/main.cpp +++ b/sink_modules/audio_sink/src/main.cpp @@ -12,7 +12,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "audio_sink", /* Description: */ "Audio sink module for SDR++", /* Author: */ "Ryzerth", @@ -59,7 +59,6 @@ public: } ~AudioSink() { - } void start() { @@ -131,12 +130,12 @@ public: if (running) { doStop(); } if (running) { doStart(); } } - + void menuHandler() { float menuWidth = ImGui::GetContentRegionAvailWidth(); ImGui::SetNextItemWidth(menuWidth); - if (ImGui::Combo(("##_audio_sink_dev_"+_streamName).c_str(), &devId, txtDevList.c_str())) { + if (ImGui::Combo(("##_audio_sink_dev_" + _streamName).c_str(), &devId, txtDevList.c_str())) { selectById(devId); config.acquire(); config.conf[_streamName]["device"] = devList[devId].name; @@ -144,7 +143,7 @@ public: } ImGui::SetNextItemWidth(menuWidth); - if (ImGui::Combo(("##_audio_sink_sr_"+_streamName).c_str(), &srId, sampleRatesTxt.c_str())) { + if (ImGui::Combo(("##_audio_sink_sr_" + _streamName).c_str(), &srId, sampleRatesTxt.c_str())) { sampleRate = sampleRates[srId]; _stream->setSampleRate(sampleRate); if (running) { @@ -173,7 +172,7 @@ private: audio.startStream(); stereoPacker.start(); } - catch ( RtAudioError& e ) { + catch (RtAudioError& e) { spdlog::error("Could not open audio device"); return; } @@ -193,7 +192,7 @@ private: stereoPacker.out.clearReadStop(); } - static int callback( void *outputBuffer, void *inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData) { + static int callback(void* outputBuffer, void* inputBuffer, unsigned int nBufferFrames, double streamTime, RtAudioStreamStatus status, void* userData) { AudioSink* _this = (AudioSink*)userData; int count = _this->stereoPacker.out.read(); if (count < 0) { return 0; } @@ -210,7 +209,7 @@ private: _this->stereoPacker.out.flush(); return 0; } - + SinkManager::Stream* _stream; dsp::StereoToMono s2m; dsp::Packer monoPacker; @@ -234,7 +233,6 @@ private: unsigned int sampleRate = 48000; RtAudio audio; - }; class AudioSinkModule : public ModuleManager::Instance { @@ -274,7 +272,6 @@ private: std::string name; bool enabled = true; SinkManager::SinkProvider provider; - }; MOD_EXPORT void _INIT_() { diff --git a/sink_modules/network_sink/src/main.cpp b/sink_modules/network_sink/src/main.cpp index d8f14337..daa38269 100644 --- a/sink_modules/network_sink/src/main.cpp +++ b/sink_modules/network_sink/src/main.cpp @@ -13,7 +13,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "network_sink", /* Description: */ "Network sink module for SDR++", /* Author: */ "Ryzerth", @@ -61,7 +61,7 @@ public: s2m.init(&packer.out); monoSink.init(&s2m.out, monoHandler, this); stereoSink.init(&packer.out, stereoHandler, this); - + // Create a list of sample rates for (int sr = 12000; sr < 200000; sr += 12000) { @@ -83,11 +83,17 @@ public: sprintf(buffer, "%d", (int)sr); sampleRatesTxt += buffer; sampleRatesTxt += '\0'; - if (sr == sampleRate) { srId = id; found = true; } + if (sr == sampleRate) { + srId = id; + found = true; + } if (sr == 48000.0) { _48kId = id; } id++; } - if (!found) { srId = _48kId; sampleRate = 48000.0; } + if (!found) { + srId = _48kId; + sampleRate = 48000.0; + } _stream->setSampleRate(sampleRate); // Start if needed @@ -220,7 +226,7 @@ private: conn = net::openUDP("0.0.0.0", port, hostname, port, false); } } - + void stopServer() { if (conn) { conn->close(); } if (listener) { listener->close(); } @@ -230,10 +236,10 @@ private: NetworkSink* _this = (NetworkSink*)ctx; std::lock_guard lck(_this->connMtx); if (!_this->conn || !_this->conn->isOpen()) { return; } - + volk_32f_s32f_convert_16i(_this->netBuf, (float*)samples, 32768.0f, count); - _this->conn->write(count*sizeof(int16_t), (uint8_t*)_this->netBuf); + _this->conn->write(count * sizeof(int16_t), (uint8_t*)_this->netBuf); } static void stereoHandler(dsp::stereo_t* samples, int count, void* ctx) { @@ -241,9 +247,9 @@ private: std::lock_guard lck(_this->connMtx); if (!_this->conn || !_this->conn->isOpen()) { return; } - volk_32f_s32f_convert_16i(_this->netBuf, (float*)samples, 32768.0f, count*2); + volk_32f_s32f_convert_16i(_this->netBuf, (float*)samples, 32768.0f, count * 2); - _this->conn->write(count*2*sizeof(int16_t), (uint8_t*)_this->netBuf); + _this->conn->write(count * 2 * sizeof(int16_t), (uint8_t*)_this->netBuf); } static void clientHandler(net::Conn client, void* ctx) { @@ -259,12 +265,11 @@ private: _this->conn->close(); } else { - } _this->listener->acceptAsync(clientHandler, _this); } - + SinkManager::Stream* _stream; dsp::Packer packer; dsp::StereoToMono s2m; @@ -291,7 +296,6 @@ private: net::Listener listener; net::Conn conn; std::mutex connMtx; - }; class NetworkSinkModule : public ModuleManager::Instance { @@ -331,7 +335,6 @@ private: std::string name; bool enabled = true; SinkManager::SinkProvider provider; - }; MOD_EXPORT void _INIT_() { diff --git a/sink_modules/new_portaudio_sink/src/main.cpp b/sink_modules/new_portaudio_sink/src/main.cpp index 745d286b..ca7252d2 100644 --- a/sink_modules/new_portaudio_sink/src/main.cpp +++ b/sink_modules/new_portaudio_sink/src/main.cpp @@ -13,10 +13,10 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -#define BLOCK_SIZE_DIVIDER 60 -#define AUDIO_LATENCY 1.0 / 60.0 +#define BLOCK_SIZE_DIVIDER 60 +#define AUDIO_LATENCY 1.0 / 60.0 -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "new_portaudio_sink", /* Description: */ "Audio sink module for SDR++", /* Author: */ "Ryzerth;Maxime Biette", @@ -37,7 +37,7 @@ public: std::vector sampleRates; std::string sampleRatesTxt; }; - + AudioSink(SinkManager::Stream* stream, std::string streamName) { _stream = stream; _streamName = streamName; @@ -72,7 +72,7 @@ public: void start() { if (running || selectedDevName.empty()) { return; } - + // Get device and samplerate AudioDevice_t& dev = devices[deviceNames[devId]]; double sampleRate = dev.sampleRates[srId]; @@ -80,7 +80,7 @@ public: // Set the SDR++ stream sample rate _stream->setSampleRate(sampleRate); - + // Update the block size on the packer packer.setSampleCount(blockSize); @@ -126,7 +126,7 @@ public: // Stop DSP packer.stop(); s2m.stop(); - + // Stop stream Pa_AbortStream(devStream); @@ -135,7 +135,7 @@ public: running = false; } - + void menuHandler() { float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -327,13 +327,13 @@ private: } } - static int _mono_cb(const void *input, void *output, unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { + static int _mono_cb(const void* input, void* output, unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData) { AudioSink* _this = (AudioSink*)userData; - + // For OSX, mute audio when not playing - if (!gui::mainWindow.isPlaying()) { - memset(output, 0, frameCount*sizeof(float)); + if (!gui::mainWindow.isPlaying()) { + memset(output, 0, frameCount * sizeof(float)); _this->s2m.out.flush(); return 0; } @@ -345,13 +345,13 @@ private: return 0; } - static int _stereo_cb(const void *input, void *output, unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { + static int _stereo_cb(const void* input, void* output, unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData) { AudioSink* _this = (AudioSink*)userData; - + // For OSX, mute audio when not playing - if (!gui::mainWindow.isPlaying()) { - memset(output, 0, frameCount*sizeof(dsp::stereo_t)); + if (!gui::mainWindow.isPlaying()) { + memset(output, 0, frameCount * sizeof(dsp::stereo_t)); _this->packer.out.flush(); return 0; } @@ -377,7 +377,7 @@ private: dsp::Packer packer; dsp::StereoToMono s2m; - PaStream *devStream; + PaStream* devStream; EventHandler playStateHandler; }; @@ -421,7 +421,6 @@ private: std::string name; bool enabled = true; SinkManager::SinkProvider provider; - }; MOD_EXPORT void _INIT_() { diff --git a/sink_modules/portaudio_sink/src/main.cpp b/sink_modules/portaudio_sink/src/main.cpp index a1e8cc3f..508286a4 100644 --- a/sink_modules/portaudio_sink/src/main.cpp +++ b/sink_modules/portaudio_sink/src/main.cpp @@ -10,7 +10,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "audio_sink", /* Description: */ "Audio sink module for SDR++", /* Author: */ "Ryzerth", @@ -28,7 +28,7 @@ public: std::vector sampleRates; std::string txtSampleRates; }; - + AudioSink(SinkManager::Stream* stream, std::string streamName) { _stream = stream; _streamName = streamName; @@ -42,13 +42,13 @@ public: // Initialize PortAudio devCount = Pa_GetDeviceCount(); devId = Pa_GetDefaultOutputDevice(); - const PaDeviceInfo *deviceInfo; + const PaDeviceInfo* deviceInfo; PaStreamParameters outputParams; outputParams.sampleFormat = paFloat32; outputParams.hostApiSpecificStreamInfo = NULL; // Gather hardware info - for(int i = 0; i < devCount; i++) { + for (int i = 0; i < devCount; i++) { deviceInfo = Pa_GetDeviceInfo(i); if (deviceInfo->maxOutputChannels < 1) { continue; @@ -114,12 +114,12 @@ public: doStop(); running = false; } - + void menuHandler() { float menuWidth = ImGui::GetContentRegionAvailWidth(); ImGui::SetNextItemWidth(menuWidth); - if (ImGui::Combo(("##_audio_sink_dev_"+_streamName).c_str(), &devListId, txtDevList.c_str())) { + if (ImGui::Combo(("##_audio_sink_dev_" + _streamName).c_str(), &devListId, txtDevList.c_str())) { // TODO: Load SR from config if (running) { doStop(); @@ -131,7 +131,7 @@ public: AudioDevice_t* dev = devices[devListId]; ImGui::SetNextItemWidth(menuWidth); - if (ImGui::Combo(("##_audio_sink_sr_"+_streamName).c_str(), &dev->srId, dev->txtSampleRates.c_str())) { + if (ImGui::Combo(("##_audio_sink_sr_" + _streamName).c_str(), &dev->srId, dev->txtSampleRates.c_str())) { _stream->setSampleRate(dev->sampleRates[dev->srId]); if (running) { doStop(); @@ -143,7 +143,7 @@ public: private: void doStart() { - const PaDeviceInfo *deviceInfo; + const PaDeviceInfo* deviceInfo; AudioDevice_t* dev = devices[devListId]; PaStreamParameters outputParams; deviceInfo = Pa_GetDeviceInfo(dev->index); @@ -206,22 +206,22 @@ private: // stereoPacker.out.clearWriteStop(); } - static int _mono_cb(const void *input, void *output, unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { + static int _mono_cb(const void* input, void* output, unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData) { AudioSink* _this = (AudioSink*)userData; - if (!gui::mainWindow.isPlaying()) { - memset(output, 0, frameCount*sizeof(float)); + if (!gui::mainWindow.isPlaying()) { + memset(output, 0, frameCount * sizeof(float)); return 0; } _this->monoRB.data.read((float*)output, frameCount); return 0; } - static int _stereo_cb(const void *input, void *output, unsigned long frameCount, - const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void *userData) { + static int _stereo_cb(const void* input, void* output, unsigned long frameCount, + const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags, void* userData) { AudioSink* _this = (AudioSink*)userData; - if (!gui::mainWindow.isPlaying()) { - memset(output, 0, frameCount*sizeof(dsp::stereo_t)); + if (!gui::mainWindow.isPlaying()) { + memset(output, 0, frameCount * sizeof(dsp::stereo_t)); return 0; } _this->stereoRB.data.read((dsp::stereo_t*)output, frameCount); @@ -245,8 +245,8 @@ private: // _this->stereoPacker.out.flush(); // return 0; // } - - + + SinkManager::Stream* _stream; dsp::StereoToMono s2m; dsp::RingBufferSink monoRB; @@ -256,7 +256,7 @@ private: // dsp::Packer stereoPacker; std::string _streamName; - PaStream *stream; + PaStream* stream; int srId = 0; int devCount; @@ -277,7 +277,6 @@ private: std::vector devices; std::vector deviceNames; std::string txtDevList; - }; class AudioSinkModule : public ModuleManager::Instance { @@ -319,7 +318,6 @@ private: std::string name; bool enabled = true; SinkManager::SinkProvider provider; - }; MOD_EXPORT void _INIT_() { @@ -333,9 +331,7 @@ MOD_EXPORT void* _CREATE_INSTANCE_(std::string name) { } MOD_EXPORT void _DELETE_INSTANCE_() { - } MOD_EXPORT void _END_() { - } \ No newline at end of file diff --git a/source_modules/airspy_source/src/main.cpp b/source_modules/airspy_source/src/main.cpp index c2d04256..9b53bac6 100644 --- a/source_modules/airspy_source/src/main.cpp +++ b/source_modules/airspy_source/src/main.cpp @@ -12,7 +12,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "airspy_source", /* Description: */ "Airspy source module for SDR++", /* Author: */ "Ryzerth", @@ -33,7 +33,7 @@ public: handler.ctx = this; handler.selectHandler = menuSelected; - handler.deselectHandler = menuDeselected; + handler.deselectHandler = menuDeselected; handler.menuHandler = menuHandler; handler.startHandler = start; handler.stopHandler = stop; @@ -236,7 +236,7 @@ private: AirspySourceModule* _this = (AirspySourceModule*)ctx; spdlog::info("AirspySourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { AirspySourceModule* _this = (AirspySourceModule*)ctx; if (_this->running) { return; } @@ -255,7 +255,7 @@ private: airspy_set_samplerate(_this->openDev, _this->sampleRateList[_this->srId]); airspy_set_freq(_this->openDev, _this->freq); - + if (_this->gainMode == 0) { airspy_set_lna_agc(_this->openDev, 0); airspy_set_mixer_agc(_this->openDev, 0); @@ -291,7 +291,7 @@ private: _this->running = true; spdlog::info("AirspySourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { AirspySourceModule* _this = (AirspySourceModule*)ctx; if (!_this->running) { return; } @@ -301,7 +301,7 @@ private: _this->stream.clearWriteStop(); spdlog::info("AirspySourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { AirspySourceModule* _this = (AirspySourceModule*)ctx; if (_this->running) { @@ -310,7 +310,7 @@ private: _this->freq = freq; spdlog::info("AirspySourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { AirspySourceModule* _this = (AirspySourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -536,8 +536,6 @@ private: config.release(true); } } - - } static int callback(airspy_transfer_t* transfer) { diff --git a/source_modules/airspyhf_source/src/main.cpp b/source_modules/airspyhf_source/src/main.cpp index 6d036972..0e28c4ae 100644 --- a/source_modules/airspyhf_source/src/main.cpp +++ b/source_modules/airspyhf_source/src/main.cpp @@ -12,7 +12,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "airspyhf_source", /* Description: */ "Airspy HF+ source module for SDR++", /* Author: */ "Ryzerth", @@ -127,7 +127,7 @@ public: sprintf(buf, "%016" PRIX64, selectedSerial); spdlog::error("Could not open Airspy HF+ {0}", buf); } - + selectedSerial = serial; uint32_t sampleRates[256]; @@ -212,7 +212,7 @@ private: AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; spdlog::info("AirspyHFSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; if (_this->running) { return; } @@ -243,7 +243,7 @@ private: _this->running = true; spdlog::info("AirspyHFSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; if (!_this->running) { return; } @@ -253,7 +253,7 @@ private: _this->stream.clearWriteStop(); spdlog::info("AirspyHFSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; if (_this->running) { @@ -262,7 +262,7 @@ private: _this->freq = freq; spdlog::info("AirspyHFSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -330,18 +330,18 @@ private: config.conf["devices"][_this->selectedSerStr]["attenuation"] = _this->atten; config.release(true); } - } + } if (ImGui::Checkbox(CONCAT("HF LNA##_airspyhf_lna_", _this->name), &_this->hfLNA)) { if (_this->running) { airspyhf_set_hf_lna(_this->openDev, _this->hfLNA); - } + } if (_this->selectedSerStr != "") { config.acquire(); config.conf["devices"][_this->selectedSerStr]["lna"] = _this->hfLNA; config.release(true); } - } + } } static int callback(airspyhf_transfer_t* transfer) { diff --git a/source_modules/bladerf_source/src/main.cpp b/source_modules/bladerf_source/src/main.cpp index ac0af123..8c82d566 100644 --- a/source_modules/bladerf_source/src/main.cpp +++ b/source_modules/bladerf_source/src/main.cpp @@ -14,10 +14,10 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -#define NUM_BUFFERS 128 -#define NUM_TRANSFERS 1 +#define NUM_BUFFERS 128 +#define NUM_TRANSFERS 1 -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "bladerf_source", /* Description: */ "BladeRF source module for SDR++", /* Author: */ "Ryzerth", @@ -100,11 +100,13 @@ public: void selectFirst() { if (devCount > 0) { selectByInfo(&devInfoList[0]); } - else { selectedSerial = ""; } + else { + selectedSerial = ""; + } } void selectBySerial(std::string serial, bool reloadChannelId = true) { - if (serial == "") { + if (serial == "") { selectFirst(); return; } @@ -134,10 +136,10 @@ public: // Get the board type const char* bname = bladerf_get_board_name(openDev); - if (!strcmp(bname ,"bladerf1")) { + if (!strcmp(bname, "bladerf1")) { selectedBladeType = BLADERF_TYPE_V1; } - else if (!strcmp(bname ,"bladerf2")) { + else if (!strcmp(bname, "bladerf2")) { selectedBladeType = BLADERF_TYPE_V2; } else { @@ -154,9 +156,13 @@ public: if (config.conf["devices"][info->serial].contains("channelId")) { chanId = config.conf["devices"][info->serial]["channelId"]; } - else { chanId = 0; } + else { + chanId = 0; + } + } + else { + chanId = 0; } - else { chanId = 0; } config.release(); } @@ -203,7 +209,7 @@ public: channelNamesTxt = ""; char buf[32]; for (int i = 0; i < channelCount; i++) { - sprintf(buf, "RX %d", i+1); + sprintf(buf, "RX %d", i + 1); channelNamesTxt += buf; channelNamesTxt += '\0'; } @@ -338,7 +344,7 @@ private: BladeRFSourceModule* _this = (BladeRFSourceModule*)ctx; spdlog::info("BladeRFSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { BladeRFSourceModule* _this = (BladeRFSourceModule*)ctx; if (_this->running) { return; } @@ -361,8 +367,7 @@ private: // Setup device parameters bladerf_set_sample_rate(_this->openDev, BLADERF_CHANNEL_RX(_this->chanId), _this->sampleRate, NULL); bladerf_set_frequency(_this->openDev, BLADERF_CHANNEL_RX(_this->chanId), _this->freq); - bladerf_set_bandwidth(_this->openDev, BLADERF_CHANNEL_RX(_this->chanId), (_this->bwId == _this->bandwidths.size()) ? - std::clamp(_this->sampleRate, _this->bwRange->min, _this->bwRange->max) : _this->bandwidths[_this->bwId], NULL); + bladerf_set_bandwidth(_this->openDev, BLADERF_CHANNEL_RX(_this->chanId), (_this->bwId == _this->bandwidths.size()) ? std::clamp(_this->sampleRate, _this->bwRange->min, _this->bwRange->max) : _this->bandwidths[_this->bwId], NULL); bladerf_set_gain_mode(_this->openDev, BLADERF_CHANNEL_RX(_this->chanId), _this->gainModes[_this->gainMode].mode); if (_this->selectedBladeType == BLADERF_TYPE_V2) { @@ -373,7 +378,7 @@ private: if (_this->gainModes[_this->gainMode].mode == BLADERF_GAIN_MANUAL) { bladerf_set_gain(_this->openDev, BLADERF_CHANNEL_RX(_this->chanId), _this->overallGain); } - + _this->streamingEnabled = true; // Setup synchronous transfer @@ -387,7 +392,7 @@ private: spdlog::info("BladeRFSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { BladeRFSourceModule* _this = (BladeRFSourceModule*)ctx; if (!_this->running) { return; } @@ -399,7 +404,7 @@ private: if (_this->workerThread.joinable()) { _this->workerThread.join(); } - + // Disable streaming bladerf_enable_module(_this->openDev, BLADERF_CHANNEL_RX(_this->chanId), false); @@ -409,7 +414,7 @@ private: _this->stream.clearWriteStop(); spdlog::info("BladeRFSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { BladeRFSourceModule* _this = (BladeRFSourceModule*)ctx; _this->freq = freq; @@ -418,7 +423,7 @@ private: } spdlog::info("BladeRFSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { BladeRFSourceModule* _this = (BladeRFSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -472,8 +477,7 @@ private: ImGui::SetNextItemWidth(menuWidth - ImGui::GetCursorPosX()); if (ImGui::Combo(CONCAT("##_balderf_bw_sel_", _this->name), &_this->bwId, _this->bandwidthsTxt.c_str())) { if (_this->running) { - bladerf_set_bandwidth(_this->openDev, BLADERF_CHANNEL_RX(_this->chanId), (_this->bwId == _this->bandwidths.size()) ? - std::clamp(_this->sampleRate, _this->bwRange->min, _this->bwRange->max) : _this->bandwidths[_this->bwId], NULL); + bladerf_set_bandwidth(_this->openDev, BLADERF_CHANNEL_RX(_this->chanId), (_this->bwId == _this->bandwidths.size()) ? std::clamp(_this->sampleRate, _this->bwRange->min, _this->bwRange->max) : _this->bandwidths[_this->bwId], NULL); } if (_this->selectedSerial != "") { config.acquire(); @@ -500,7 +504,9 @@ private: } } - if (_this->selectedSerial != "") { if (_this->gainModes[_this->gainMode].mode != BLADERF_GAIN_MANUAL) { style::beginDisabled(); } } + if (_this->selectedSerial != "") { + if (_this->gainModes[_this->gainMode].mode != BLADERF_GAIN_MANUAL) { style::beginDisabled(); } + } ImGui::LeftLabel("Gain"); ImGui::SetNextItemWidth(menuWidth - ImGui::GetCursorPosX()); if (ImGui::SliderInt("##_balderf_oag_sel_", &_this->overallGain, (_this->gainRange != NULL) ? _this->gainRange->min : 0, (_this->gainRange != NULL) ? _this->gainRange->max : 60)) { @@ -514,7 +520,9 @@ private: config.release(true); } } - if (_this->selectedSerial != "") { if (_this->gainModes[_this->gainMode].mode != BLADERF_GAIN_MANUAL) { style::endDisabled(); } } + if (_this->selectedSerial != "") { + if (_this->gainModes[_this->gainMode].mode != BLADERF_GAIN_MANUAL) { style::endDisabled(); } + } if (_this->selectedBladeType == BLADERF_TYPE_V2) { if (ImGui::Checkbox("Bias-T##_balderf_biast_", &_this->biasT)) { @@ -526,13 +534,12 @@ private: config.release(true); } } - } void worker() { int16_t* buffer = new int16_t[bufferSize * 2]; bladerf_metadata meta; - + while (streamingEnabled) { // Receive from the stream and break on error int ret = bladerf_sync_rx(openDev, buffer, bufferSize, &meta, 3500); diff --git a/source_modules/file_source/src/main.cpp b/source_modules/file_source/src/main.cpp index d6a1a5cf..bc1a9105 100644 --- a/source_modules/file_source/src/main.cpp +++ b/source_modules/file_source/src/main.cpp @@ -13,7 +13,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "file_source", /* Description: */ "Wav file source module for SDR++", /* Author: */ "Ryzerth", @@ -23,9 +23,9 @@ SDRPP_MOD_INFO { ConfigManager config; -class FileSourceModule : public ModuleManager::Instance { +class FileSourceModule : public ModuleManager::Instance { public: - FileSourceModule(std::string name) : fileSelect("", {"Wav IQ Files (*.wav)", "*.wav", "All Files", "*"}) { + FileSourceModule(std::string name) : fileSelect("", { "Wav IQ Files (*.wav)", "*.wav", "All Files", "*" }) { this->name = name; config.acquire(); @@ -82,7 +82,7 @@ private: gui::waterfall.centerFrequencyLocked = false; spdlog::info("FileSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { FileSourceModule* _this = (FileSourceModule*)ctx; if (_this->running) { return; } @@ -91,7 +91,7 @@ private: _this->workerThread = _this->float32Mode ? std::thread(floatWorker, _this) : std::thread(worker, _this); spdlog::info("FileSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { FileSourceModule* _this = (FileSourceModule*)ctx; if (!_this->running) { return; } @@ -103,12 +103,12 @@ private: _this->reader->rewind(); spdlog::info("FileSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { FileSourceModule* _this = (FileSourceModule*)ctx; spdlog::info("FileSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { FileSourceModule* _this = (FileSourceModule*)ctx; diff --git a/source_modules/file_source/src/wavreader.h b/source_modules/file_source/src/wavreader.h index a0e9f3c3..e3d7f739 100644 --- a/source_modules/file_source/src/wavreader.h +++ b/source_modules/file_source/src/wavreader.h @@ -53,25 +53,25 @@ public: void rewind() { file.seekg(sizeof(WavHeader_t)); } - + void close() { file.close(); } private: struct WavHeader_t { - char signature[4]; // "RIFF" - uint32_t fileSize; // data bytes + sizeof(WavHeader_t) - 8 - char fileType[4]; // "WAVE" - char formatMarker[4]; // "fmt " - uint32_t formatHeaderLength; // Always 16 - uint16_t sampleType; // PCM (1) + char signature[4]; // "RIFF" + uint32_t fileSize; // data bytes + sizeof(WavHeader_t) - 8 + char fileType[4]; // "WAVE" + char formatMarker[4]; // "fmt " + uint32_t formatHeaderLength; // Always 16 + uint16_t sampleType; // PCM (1) uint16_t channelCount; uint32_t sampleRate; uint32_t bytesPerSecond; uint16_t bytesPerSample; uint16_t bitDepth; - char dataMarker[4]; // "data" + char dataMarker[4]; // "data" uint32_t dataSize; }; diff --git a/source_modules/hackrf_source/src/main.cpp b/source_modules/hackrf_source/src/main.cpp index 20f6cf1b..bb22917c 100644 --- a/source_modules/hackrf_source/src/main.cpp +++ b/source_modules/hackrf_source/src/main.cpp @@ -12,7 +12,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "hackrf_source", /* Description: */ "HackRF source module for SDR++", /* Author: */ "Ryzerth", @@ -38,21 +38,21 @@ const int sampleRates[] = { const int bandwidths[] = { 1750000, - 2500000, - 3500000, - 5000000, - 5500000, - 6000000, - 7000000, - 8000000, - 9000000, - 10000000, - 12000000, - 14000000, - 15000000, - 20000000, - 24000000, - 28000000, + 2500000, + 3500000, + 5000000, + 5500000, + 6000000, + 7000000, + 8000000, + 9000000, + 10000000, + 12000000, + 14000000, + 15000000, + 20000000, + 24000000, + 28000000, }; const char* bandwidthsTxt = "1.75MHz\0" @@ -220,7 +220,7 @@ private: if (id == 16) { return hackrf_compute_baseband_filter_bw(sampleRate); } return bandwidths[id]; } - + static void start(void* ctx) { HackRFSourceModule* _this = (HackRFSourceModule*)ctx; if (_this->running) { return; } @@ -249,7 +249,7 @@ private: _this->running = true; spdlog::info("HackRFSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { HackRFSourceModule* _this = (HackRFSourceModule*)ctx; if (!_this->running) { return; } @@ -263,7 +263,7 @@ private: _this->stream.clearWriteStop(); spdlog::info("HackRFSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { HackRFSourceModule* _this = (HackRFSourceModule*)ctx; if (_this->running) { @@ -272,7 +272,7 @@ private: _this->freq = freq; spdlog::info("HackRFSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { HackRFSourceModule* _this = (HackRFSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -300,7 +300,7 @@ private: if (ImGui::Button(CONCAT("Refresh##_hackrf_refr_", _this->name), ImVec2(refreshBtnWdith, 0))) { _this->refresh(); _this->selectBySerial(_this->selectedSerial); - core::setInputSampleRate(_this->sampleRate); + core::setInputSampleRate(_this->sampleRate); } if (_this->running) { style::endDisabled(); } @@ -336,7 +336,7 @@ private: config.acquire(); config.conf["devices"][_this->selectedSerial]["vgaGain"] = (int)_this->vga; config.release(true); - } + } if (ImGui::Checkbox(CONCAT("Bias-T##_hackrf_bt_", _this->name), &_this->biasT)) { if (_this->running) { @@ -354,14 +354,14 @@ private: config.acquire(); config.conf["devices"][_this->selectedSerial]["amp"] = _this->amp; config.release(true); - } + } } static int callback(hackrf_transfer* transfer) { HackRFSourceModule* _this = (HackRFSourceModule*)transfer->rx_ctx; int count = transfer->valid_length / 2; int8_t* buffer = (int8_t*)transfer->buffer; - volk_8i_s32f_convert_32f((float*)_this->stream.writeBuf, buffer, 128.0f, count*2); + volk_8i_s32f_convert_32f((float*)_this->stream.writeBuf, buffer, 128.0f, count * 2); if (!_this->stream.swap(count)) { return -1; } return 0; } diff --git a/source_modules/limesdr_source/src/main.cpp b/source_modules/limesdr_source/src/main.cpp index 02b56c77..b20fbd09 100644 --- a/source_modules/limesdr_source/src/main.cpp +++ b/source_modules/limesdr_source/src/main.cpp @@ -12,7 +12,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "limesdr_source", /* Description: */ "LimeSDR source module for SDR++", /* Author: */ "Ryzerth", @@ -33,7 +33,7 @@ public: handler.ctx = this; handler.selectHandler = menuSelected; - handler.deselectHandler = menuDeselected; + handler.deselectHandler = menuDeselected; handler.menuHandler = menuHandler; handler.startHandler = start; handler.stopHandler = stop; @@ -124,7 +124,7 @@ public: channelCount = LMS_GetNumChannels(dev, false); char buf[32]; for (int i = 0; i < channelCount; i++) { - sprintf(buf, "CH %d", i+1); + sprintf(buf, "CH %d", i + 1); channelNamesTxt += buf; channelNamesTxt += '\0'; } @@ -134,9 +134,13 @@ public: if (config.conf["devices"][selectedDevName].contains("channel")) { chanId = config.conf["devices"][selectedDevName]["channel"]; } - else { chanId = 0; } + else { + chanId = 0; + } + } + else { + chanId = 0; } - else { chanId = 0; } config.release(); chanId = std::clamp(chanId, 0, channelCount - 1); @@ -299,7 +303,7 @@ private: return bandwidths[i]; } } - return bandwidths[bandwidths.size()-1]; + return bandwidths[bandwidths.size() - 1]; } static void menuSelected(void* ctx) { @@ -312,11 +316,11 @@ private: LimeSDRSourceModule* _this = (LimeSDRSourceModule*)ctx; spdlog::info("LimeSDRSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { LimeSDRSourceModule* _this = (LimeSDRSourceModule*)ctx; if (_this->running) { return; } - + // Open device _this->openDev = NULL; LMS_Open(&_this->openDev, _this->devList[_this->devId], NULL); @@ -350,7 +354,7 @@ private: _this->running = true; spdlog::info("LimeSDRSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { LimeSDRSourceModule* _this = (LimeSDRSourceModule*)ctx; if (!_this->running) { return; } @@ -366,7 +370,7 @@ private: spdlog::info("LimeSDRSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { LimeSDRSourceModule* _this = (LimeSDRSourceModule*)ctx; _this->freq = freq; @@ -375,7 +379,7 @@ private: } spdlog::info("LimeSDRSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { LimeSDRSourceModule* _this = (LimeSDRSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); diff --git a/source_modules/plutosdr_source/src/main.cpp b/source_modules/plutosdr_source/src/main.cpp index 9f043ecb..bcc255af 100644 --- a/source_modules/plutosdr_source/src/main.cpp +++ b/source_modules/plutosdr_source/src/main.cpp @@ -12,7 +12,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "plutosdr_source", /* Description: */ "PlutoSDR source module for SDR++", /* Author: */ "Ryzerth", @@ -38,7 +38,7 @@ public: strcpy(&ip[3], _ip.c_str()); sampleRate = config.conf["sampleRate"]; gainMode = config.conf["gainMode"]; - gain = config.conf["gain"]; + gain = config.conf["gain"]; config.release(); // Generate the samplerate list and find srId @@ -116,18 +116,18 @@ private: PlutoSDRSourceModule* _this = (PlutoSDRSourceModule*)ctx; spdlog::info("PlutoSDRSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { PlutoSDRSourceModule* _this = (PlutoSDRSourceModule*)ctx; if (_this->running) { return; } - + // TODO: INIT CONTEXT HERE _this->ctx = iio_create_context_from_uri(_this->ip); if (_this->ctx == NULL) { spdlog::error("Could not open pluto"); return; } - _this->phy = iio_context_find_device(_this->ctx, "ad9361-phy"); + _this->phy = iio_context_find_device(_this->ctx, "ad9361-phy"); if (_this->phy == NULL) { spdlog::error("Could not connect to pluto phy"); iio_context_destroy(_this->ctx); @@ -145,17 +145,17 @@ private: iio_channel_attr_write_bool(iio_device_find_channel(_this->phy, "altvoltage0", true), "powerdown", false); iio_channel_attr_write(iio_device_find_channel(_this->phy, "voltage0", false), "rf_port_select", "A_BALANCED"); - iio_channel_attr_write_longlong(iio_device_find_channel(_this->phy, "altvoltage0", true), "frequency", round(_this->freq)); // Freq - iio_channel_attr_write_longlong(iio_device_find_channel(_this->phy, "voltage0", false), "sampling_frequency", round(_this->sampleRate)); // Sample rate - iio_channel_attr_write(iio_device_find_channel(_this->phy, "voltage0", false), "gain_control_mode", gainModes[_this->gainMode]); // manual gain - iio_channel_attr_write_longlong(iio_device_find_channel(_this->phy, "voltage0", false), "hardwaregain", round(_this->gain)); // gain + iio_channel_attr_write_longlong(iio_device_find_channel(_this->phy, "altvoltage0", true), "frequency", round(_this->freq)); // Freq + iio_channel_attr_write_longlong(iio_device_find_channel(_this->phy, "voltage0", false), "sampling_frequency", round(_this->sampleRate)); // Sample rate + iio_channel_attr_write(iio_device_find_channel(_this->phy, "voltage0", false), "gain_control_mode", gainModes[_this->gainMode]); // manual gain + iio_channel_attr_write_longlong(iio_device_find_channel(_this->phy, "voltage0", false), "hardwaregain", round(_this->gain)); // gain ad9361_set_bb_rate(_this->phy, round(_this->sampleRate)); - + _this->running = true; _this->workerThread = std::thread(worker, _this); spdlog::info("PlutoSDRSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { PlutoSDRSourceModule* _this = (PlutoSDRSourceModule*)ctx; if (!_this->running) { return; } @@ -172,7 +172,7 @@ private: spdlog::info("PlutoSDRSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { PlutoSDRSourceModule* _this = (PlutoSDRSourceModule*)ctx; _this->freq = freq; @@ -182,7 +182,7 @@ private: } spdlog::info("PlutoSDRSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { PlutoSDRSourceModule* _this = (PlutoSDRSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -195,10 +195,10 @@ private: config.conf["IP"] = &_this->ip[3]; config.release(true); } - + ImGui::LeftLabel("Samplerate"); ImGui::SetNextItemWidth(menuWidth - ImGui::GetCursorPosX()); - + if (ImGui::Combo(CONCAT("##_pluto_sr_", _this->name), &_this->srId, _this->sampleRatesTxt.c_str())) { _this->sampleRate = _this->sampleRates[_this->srId]; core::setInputSampleRate(_this->sampleRate); @@ -224,7 +224,7 @@ private: if (_this->gainMode) { style::beginDisabled(); } if (ImGui::SliderFloat(CONCAT("##_gain_select_", _this->name), &_this->gain, 0, 76)) { if (_this->running) { - iio_channel_attr_write_longlong(iio_device_find_channel(_this->phy, "voltage0", false),"hardwaregain", round(_this->gain)); + iio_channel_attr_write_longlong(iio_device_find_channel(_this->phy, "voltage0", false), "hardwaregain", round(_this->gain)); } config.acquire(); config.conf["gain"] = _this->gain; @@ -238,14 +238,14 @@ private: int blockSize = _this->sampleRate / 200.0f; struct iio_channel *rx0_i, *rx0_q; - struct iio_buffer *rxbuf; - + struct iio_buffer* rxbuf; + rx0_i = iio_device_find_channel(_this->dev, "voltage0", 0); rx0_q = iio_device_find_channel(_this->dev, "voltage1", 0); - + iio_channel_enable(rx0_i); iio_channel_enable(rx0_q); - + rxbuf = iio_device_create_buffer(_this->dev, blockSize, false); if (!rxbuf) { spdlog::error("Could not create RX buffer"); @@ -264,7 +264,7 @@ private: _this->stream.writeBuf[i].im = (float)buf[(i * 2) + 1] / 32768.0f; } - volk_16i_s32f_convert_32f((float*)_this->stream.writeBuf, buf, 32768.0f, blockSize*2); + volk_16i_s32f_convert_32f((float*)_this->stream.writeBuf, buf, 32768.0f, blockSize * 2); if (!_this->stream.swap(blockSize)) { break; }; } @@ -278,9 +278,9 @@ private: float sampleRate; SourceManager::SourceHandler handler; std::thread workerThread; - struct iio_context *ctx = NULL; - struct iio_device *phy = NULL; - struct iio_device *dev = NULL; + struct iio_context* ctx = NULL; + struct iio_device* phy = NULL; + struct iio_device* dev = NULL; bool running = false; bool ipMode = true; double freq; diff --git a/source_modules/rfspace_source/src/main.cpp b/source_modules/rfspace_source/src/main.cpp index a988b1bd..77236df4 100644 --- a/source_modules/rfspace_source/src/main.cpp +++ b/source_modules/rfspace_source/src/main.cpp @@ -13,7 +13,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "rfspace_source", /* Description: */ "RFspace source module for SDR++", /* Author: */ "Ryzerth", @@ -88,7 +88,7 @@ private: gui::mainWindow.playButtonLocked = false; spdlog::info("SpyServerSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { SpyServerSourceModule* _this = (SpyServerSourceModule*)ctx; if (_this->running) { return; } @@ -98,17 +98,17 @@ private: _this->running = true; spdlog::info("SpyServerSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { SpyServerSourceModule* _this = (SpyServerSourceModule*)ctx; if (!_this->running) { return; } - + // TODO: Stop _this->running = false; spdlog::info("SpyServerSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { SpyServerSourceModule* _this = (SpyServerSourceModule*)ctx; if (_this->running) { @@ -117,7 +117,7 @@ private: _this->freq = freq; spdlog::info("SpyServerSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { SpyServerSourceModule* _this = (SpyServerSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -154,7 +154,6 @@ private: } if (_this->running) { style::endDisabled(); } - if (connected) { // TODO: Options here diff --git a/source_modules/rfspace_source/src/rfspace_client.cpp b/source_modules/rfspace_source/src/rfspace_client.cpp index 84f32e63..82a328bc 100644 --- a/source_modules/rfspace_source/src/rfspace_client.cpp +++ b/source_modules/rfspace_source/src/rfspace_client.cpp @@ -24,7 +24,7 @@ namespace rfspace { udpClient->readAsync(sizeof(udpHeader), (uint8_t*)&udpHeader, udpHandler, this); // Start SDR - uint8_t args[4] = {0x70, 2, 0, 0}; + uint8_t args[4] = { 0x70, 2, 0, 0 }; setControlItem(0x18, args, 4); } diff --git a/source_modules/rfspace_source/src/rfspace_client.h b/source_modules/rfspace_source/src/rfspace_client.h index 55bbdef6..9903cfd4 100644 --- a/source_modules/rfspace_source/src/rfspace_client.h +++ b/source_modules/rfspace_source/src/rfspace_client.h @@ -4,7 +4,7 @@ #include #include -#define RFSPACE_MAX_SIZE 8192 +#define RFSPACE_MAX_SIZE 8192 namespace rfspace { enum { @@ -40,7 +40,7 @@ namespace rfspace { // Wait for data std::unique_lock lck(mtx); - return cnd.wait_for(lck, std::chrono::milliseconds(timeoutMS), [this](){ return triggered; }); + return cnd.wait_for(lck, std::chrono::milliseconds(timeoutMS), [this]() { return triggered; }); // Mark as not waiting { @@ -75,7 +75,7 @@ namespace rfspace { // Wait for waiter to handle { std::unique_lock lck(mtx); - cnd.wait(lck, [this](){ return !triggered; }); + cnd.wait(lck, [this]() { return !triggered; }); } } @@ -86,7 +86,6 @@ namespace rfspace { bool waiting; std::mutex waitingmtx; - }; class RFspaceClientClass { @@ -122,9 +121,9 @@ namespace rfspace { SyncEvent SCIRRecv; int SCIRSize; }; - + typedef std::unique_ptr RFspaceClient; RFspaceClient connect(std::string host, uint16_t port, dsp::stream* out); - + } diff --git a/source_modules/rtl_sdr_source/src/main.cpp b/source_modules/rtl_sdr_source/src/main.cpp index 605dd5f8..fdf6bb5b 100644 --- a/source_modules/rtl_sdr_source/src/main.cpp +++ b/source_modules/rtl_sdr_source/src/main.cpp @@ -12,7 +12,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "rtl_sdr_source", /* Description: */ "RTL-SDR source module for SDR++", /* Author: */ "Ryzerth", @@ -61,7 +61,7 @@ public: handler.ctx = this; handler.selectHandler = menuSelected; - handler.deselectHandler = menuDeselected; + handler.deselectHandler = menuDeselected; handler.menuHandler = menuHandler; handler.startHandler = start; handler.stopHandler = stop; @@ -243,7 +243,7 @@ private: RTLSDRSourceModule* _this = (RTLSDRSourceModule*)ctx; spdlog::info("RTLSDRSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { RTLSDRSourceModule* _this = (RTLSDRSourceModule*)ctx; if (_this->running) { return; } @@ -256,7 +256,7 @@ private: spdlog::error("Could not open RTL-SDR"); return; } - + spdlog::info("RTL-SDR Sample Rate: {0}", _this->sampleRate); rtlsdr_set_sample_rate(_this->openDev, _this->sampleRate); @@ -283,7 +283,7 @@ private: _this->running = true; spdlog::info("RTLSDRSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { RTLSDRSourceModule* _this = (RTLSDRSourceModule*)ctx; if (!_this->running) { return; } @@ -295,7 +295,7 @@ private: rtlsdr_close(_this->openDev); spdlog::info("RTLSDRSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { RTLSDRSourceModule* _this = (RTLSDRSourceModule*)ctx; if (_this->running) { @@ -308,12 +308,11 @@ private: if (i > 1) { spdlog::warn("RTL-SDR took {0} attempts to tune...", i); } - } _this->freq = freq; spdlog::info("RTLSDRSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { RTLSDRSourceModule* _this = (RTLSDRSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -462,7 +461,7 @@ private: rtlsdr_read_async(openDev, asyncHandler, this, 0, asyncCount); } - static void asyncHandler(unsigned char *buf, uint32_t len, void *ctx) { + static void asyncHandler(unsigned char* buf, uint32_t len, void* ctx) { RTLSDRSourceModule* _this = (RTLSDRSourceModule*)ctx; int sampCount = len / 2; for (int i = 0; i < sampCount; i++) { diff --git a/source_modules/rtl_tcp_source/src/main.cpp b/source_modules/rtl_tcp_source/src/main.cpp index 7ed3769e..cd8af4b4 100644 --- a/source_modules/rtl_tcp_source/src/main.cpp +++ b/source_modules/rtl_tcp_source/src/main.cpp @@ -10,7 +10,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "rtl_tcp_source", /* Description: */ "RTL-TCP source module for SDR++", /* Author: */ "Ryzerth", @@ -48,7 +48,7 @@ const char* sampleRatesTxt[] = { "3.2MHz" }; -#define SAMPLE_RATE_COUNT (sizeof(sampleRates) / sizeof(double)) +#define SAMPLE_RATE_COUNT (sizeof(sampleRates) / sizeof(double)) class RTLTCPSourceModule : public ModuleManager::Instance { public: @@ -135,7 +135,7 @@ private: RTLTCPSourceModule* _this = (RTLTCPSourceModule*)ctx; spdlog::info("RTLTCPSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { RTLTCPSourceModule* _this = (RTLTCPSourceModule*)ctx; if (_this->running) { return; } @@ -160,12 +160,12 @@ private: // Setting it twice because for some reason it refuses to do it on the first time _this->client.setGainIndex(_this->gain); } - + _this->running = true; _this->workerThread = std::thread(worker, _this); spdlog::info("RTLTCPSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { RTLTCPSourceModule* _this = (RTLTCPSourceModule*)ctx; if (!_this->running) { return; } @@ -176,7 +176,7 @@ private: _this->client.disconnect(); spdlog::info("RTLTCPSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { RTLTCPSourceModule* _this = (RTLTCPSourceModule*)ctx; if (_this->running) { @@ -185,7 +185,7 @@ private: _this->freq = freq; spdlog::info("RTLTCPSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { RTLTCPSourceModule* _this = (RTLTCPSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -338,20 +338,20 @@ private: }; MOD_EXPORT void _INIT_() { - config.setPath(options::opts.root + "/rtl_tcp_config.json"); - json defConf; - defConf["host"] = "localhost"; - defConf["port"] = 1234; - defConf["sampleRate"] = 2400000.0; - defConf["directSamplingMode"] = 0; - defConf["ppm"] = 0; - defConf["rtlAGC"] = false; - defConf["tunerAGC"] = false; - defConf["gainIndex"] = 0; - defConf["biasTee"] = false; - defConf["offsetTuning"] = false; - config.load(defConf); - config.enableAutoSave(); + config.setPath(options::opts.root + "/rtl_tcp_config.json"); + json defConf; + defConf["host"] = "localhost"; + defConf["port"] = 1234; + defConf["sampleRate"] = 2400000.0; + defConf["directSamplingMode"] = 0; + defConf["ppm"] = 0; + defConf["rtlAGC"] = false; + defConf["tunerAGC"] = false; + defConf["gainIndex"] = 0; + defConf["biasTee"] = false; + defConf["offsetTuning"] = false; + config.load(defConf); + config.enableAutoSave(); config.acquire(); if (!config.conf.contains("biasTee")) { diff --git a/source_modules/rtl_tcp_source/src/rtltcp_client.h b/source_modules/rtl_tcp_source/src/rtltcp_client.h index 0358f8ed..cdae214f 100644 --- a/source_modules/rtl_tcp_source/src/rtltcp_client.h +++ b/source_modules/rtl_tcp_source/src/rtltcp_client.h @@ -12,17 +12,17 @@ #include #include #include -#include +#include #endif #ifdef _WIN32 #define __attribute__(x) #pragma pack(push, 1) #endif -struct command_t{ - unsigned char cmd; - unsigned int param; -}__attribute__((packed)); +struct command_t { + unsigned char cmd; + unsigned int param; +} __attribute__((packed)); #ifdef _WIN32 #pragma pack(pop) #endif @@ -30,7 +30,6 @@ struct command_t{ class RTLTCPClient { public: RTLTCPClient() { - } bool connectToRTL(char* host, uint16_t port) { @@ -39,14 +38,14 @@ public: } #ifdef _WIN32 - struct addrinfo *result = NULL; - struct addrinfo *ptr = NULL; + struct addrinfo* result = NULL; + struct addrinfo* ptr = NULL; struct addrinfo hints; WSADATA wsaData; - WSAStartup(MAKEWORD(2,2), &wsaData); + WSAStartup(MAKEWORD(2, 2), &wsaData); - ZeroMemory( &hints, sizeof(hints) ); + ZeroMemory(&hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; @@ -88,13 +87,13 @@ public: // TODO: Log error return false; } - struct hostent *server = gethostbyname(host); + struct hostent* server = gethostbyname(host); struct sockaddr_in serv_addr; bzero(&serv_addr, sizeof(struct sockaddr_in)); serv_addr.sin_family = AF_INET; - bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); + bcopy((char*)server->h_addr, (char*)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(port); - if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0) { + if (connect(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) { // TODO: log error return false; } @@ -130,7 +129,7 @@ public: cmd.cmd = command; cmd.param = htonl(param); #ifdef _WIN32 - send(sock, (char*)&cmd, sizeof(command_t), 0); + send(sock, (char*)&cmd, sizeof(command_t), 0); #else (void)write(sockfd, &cmd, sizeof(command_t)); #endif @@ -196,7 +195,6 @@ private: #else int sockfd; #endif - - bool connected = false; + bool connected = false; }; \ No newline at end of file diff --git a/source_modules/sddc_source/src/main.cpp b/source_modules/sddc_source/src/main.cpp index d72560ff..e86fbde8 100644 --- a/source_modules/sddc_source/src/main.cpp +++ b/source_modules/sddc_source/src/main.cpp @@ -12,7 +12,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "sddc_source", /* Description: */ "SDDC source module for SDR++", /* Author: */ "Ryzerth;pkuznetsov", @@ -142,7 +142,7 @@ private: AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; spdlog::info("AirspyHFSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; if (_this->running) { return; } @@ -153,19 +153,19 @@ private: _this->running = true; spdlog::info("AirspyHFSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; if (!_this->running) { return; } _this->running = false; _this->stream.stopWriter(); - + // Stop device _this->stream.clearWriteStop(); spdlog::info("AirspyHFSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; if (_this->running) { @@ -174,7 +174,7 @@ private: _this->freq = freq; spdlog::info("AirspyHFSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { AirspyHFSourceModule* _this = (AirspyHFSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -202,7 +202,6 @@ private: if (_this->running) { style::endDisabled(); } // All other controls - } std::string name; diff --git a/source_modules/sdrplay_source/src/main.cpp b/source_modules/sdrplay_source/src/main.cpp index d1367f47..4e3f177c 100644 --- a/source_modules/sdrplay_source/src/main.cpp +++ b/source_modules/sdrplay_source/src/main.cpp @@ -12,7 +12,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "sdrplay_source", /* Description: */ "SDRplay source module for SDR++", /* Author: */ "Ryzerth", @@ -103,13 +103,13 @@ struct ifMode_t { }; ifMode_t ifModes[] = { - { sdrplay_api_IF_Zero, sdrplay_api_BW_1_536, 2000000, 2000000}, - { sdrplay_api_IF_2_048, sdrplay_api_BW_1_536, 8000000, 2000000}, - { sdrplay_api_IF_2_048, sdrplay_api_BW_5_000, 8000000, 2000000}, - { sdrplay_api_IF_1_620, sdrplay_api_BW_1_536, 6000000, 2000000}, - { sdrplay_api_IF_0_450, sdrplay_api_BW_0_600, 2000000, 1000000}, - { sdrplay_api_IF_0_450, sdrplay_api_BW_0_300, 2000000, 500000}, - { sdrplay_api_IF_0_450, sdrplay_api_BW_0_200, 2000000, 500000}, + { sdrplay_api_IF_Zero, sdrplay_api_BW_1_536, 2000000, 2000000 }, + { sdrplay_api_IF_2_048, sdrplay_api_BW_1_536, 8000000, 2000000 }, + { sdrplay_api_IF_2_048, sdrplay_api_BW_5_000, 8000000, 2000000 }, + { sdrplay_api_IF_1_620, sdrplay_api_BW_1_536, 6000000, 2000000 }, + { sdrplay_api_IF_0_450, sdrplay_api_BW_0_600, 2000000, 1000000 }, + { sdrplay_api_IF_0_450, sdrplay_api_BW_0_300, 2000000, 500000 }, + { sdrplay_api_IF_0_450, sdrplay_api_BW_0_200, 2000000, 500000 }, }; const char* ifModeTxt = @@ -147,7 +147,7 @@ public: handler.ctx = this; handler.selectHandler = menuSelected; - handler.deselectHandler = menuDeselected; + handler.deselectHandler = menuDeselected; handler.menuHandler = menuHandler; handler.startHandler = start; handler.stopHandler = stop; @@ -210,24 +210,36 @@ public: devList.push_back(devArr[i]); std::string name = ""; switch (devArr[i].hwVer) { - case SDRPLAY_RSP1_ID: - name = "RSP1 ("; name += devArr[i].SerNo; name += ')'; - break; - case SDRPLAY_RSP1A_ID: - name = "RSP1A ("; name += devArr[i].SerNo; name += ')'; - break; - case SDRPLAY_RSP2_ID: - name = "RSP2 ("; name += devArr[i].SerNo; name += ')'; - break; - case SDRPLAY_RSPduo_ID: - name = "RSPduo ("; name += devArr[i].SerNo; name += ')'; - break; - case SDRPLAY_RSPdx_ID: - name = "RSPdx ("; name += devArr[i].SerNo; name += ')'; - break; - default: - name = "Unknown ("; name += devArr[i].SerNo; name += ')'; - break; + case SDRPLAY_RSP1_ID: + name = "RSP1 ("; + name += devArr[i].SerNo; + name += ')'; + break; + case SDRPLAY_RSP1A_ID: + name = "RSP1A ("; + name += devArr[i].SerNo; + name += ')'; + break; + case SDRPLAY_RSP2_ID: + name = "RSP2 ("; + name += devArr[i].SerNo; + name += ')'; + break; + case SDRPLAY_RSPduo_ID: + name = "RSPduo ("; + name += devArr[i].SerNo; + name += ')'; + break; + case SDRPLAY_RSPdx_ID: + name = "RSPdx ("; + name += devArr[i].SerNo; + name += ')'; + break; + default: + name = "Unknown ("; + name += devArr[i].SerNo; + name += ')'; + break; } devNameList.push_back(name); devListTxt += name; @@ -372,9 +384,9 @@ public: } } - if(config.conf["devices"][selectedName].contains("ifModeId")) { - ifModeId=config.conf["devices"][selectedName]["ifModeId"]; - if(ifModeId != 0){ + if (config.conf["devices"][selectedName].contains("ifModeId")) { + ifModeId = config.conf["devices"][selectedName]["ifModeId"]; + if (ifModeId != 0) { sampleRate = ifModes[ifModeId].effectiveSamplerate; } } @@ -473,14 +485,14 @@ public: } config.release(created); - + if (lnaGain >= lnaSteps) { lnaGain = lnaSteps - 1; } // Release device after selecting sdrplay_api_Uninit(openDev.dev); sdrplay_api_ReleaseDevice(&openDev); } - + void rspDuoSelectTuner(sdrplay_api_TunerSelectT tuner, sdrplay_api_RspDuo_AmPortSelectT amPort) { if (openDev.tuner != tuner) { spdlog::info("Swapping tuners"); @@ -500,7 +512,6 @@ public: channelParams->tunerParams.gain.gRdB = gain; sdrplay_api_Update(openDev.dev, openDev.tuner, sdrplay_api_Update_Tuner_Gr, sdrplay_api_Update_Ext1_None); sdrplay_api_Update(openDev.dev, openDev.tuner, sdrplay_api_Update_Tuner_Gr, sdrplay_api_Update_Ext1_None); - } void rspDuoSelectAntennaPort(int port) { @@ -534,7 +545,7 @@ private: SDRPlaySourceModule* _this = (SDRPlaySourceModule*)ctx; spdlog::info("SDRPlaySourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { SDRPlaySourceModule* _this = (SDRPlaySourceModule*)ctx; if (_this->running) { return; } @@ -620,11 +631,12 @@ private: } // General options - if(_this->ifModeId == 0){ + if (_this->ifModeId == 0) { _this->bandwidth = (_this->bandwidthId == 8) ? preferedBandwidth[_this->srId] : bandwidths[_this->bandwidthId]; _this->openDevParams->devParams->fsFreq.fsHz = _this->sampleRate; _this->channelParams->tunerParams.bwType = _this->bandwidth; - } else { + } + else { _this->openDevParams->devParams->fsFreq.fsHz = ifModes[_this->ifModeId].deviceSamplerate; _this->channelParams->tunerParams.bwType = ifModes[_this->ifModeId].bw; } @@ -658,13 +670,13 @@ private: _this->running = true; spdlog::info("SDRPlaySourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { SDRPlaySourceModule* _this = (SDRPlaySourceModule*)ctx; if (!_this->running) { return; } _this->running = false; _this->stream.stopWriter(); - + // Release device after stopping sdrplay_api_Uninit(_this->openDev.dev); sdrplay_api_ReleaseDevice(&_this->openDev); @@ -672,7 +684,7 @@ private: _this->stream.clearWriteStop(); spdlog::info("SDRPlaySourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { SDRPlaySourceModule* _this = (SDRPlaySourceModule*)ctx; if (_this->running) { @@ -682,7 +694,7 @@ private: _this->freq = freq; spdlog::info("SDRPlaySourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { SDRPlaySourceModule* _this = (SDRPlaySourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -690,8 +702,8 @@ private: if (_this->running) { style::beginDisabled(); } ImGui::SetNextItemWidth(menuWidth); - - + + if (ImGui::Combo(CONCAT("##sdrplay_dev", _this->name), &_this->devId, _this->devListTxt.c_str())) { _this->selectById(_this->devId); config.acquire(); @@ -736,28 +748,29 @@ private: _this->selectByName(_this->selectedName); } } - + ImGui::Text("IF Mode"); ImGui::SameLine(); ImGui::SetNextItemWidth(menuWidth - ImGui::GetCursorPosX()); if (ImGui::Combo(CONCAT("##sdrplay_ifmode", _this->name), &_this->ifModeId, ifModeTxt)) { - if(_this->ifModeId != 0){ + if (_this->ifModeId != 0) { _this->bandwidth = ifModes[_this->ifModeId].bw; _this->sampleRate = ifModes[_this->ifModeId].effectiveSamplerate; - } else { + } + else { config.acquire(); _this->sampleRate = config.conf["devices"][_this->selectedName]["sampleRate"]; _this->bandwidthId = config.conf["devices"][_this->selectedName]["bwMode"]; config.release(false); _this->bandwidth = (_this->bandwidthId == 8) ? preferedBandwidth[_this->srId] : bandwidths[_this->bandwidthId]; - } + } core::setInputSampleRate(_this->sampleRate); config.acquire(); config.conf["devices"][_this->selectedName]["ifModeId"] = _this->ifModeId; config.release(true); } - if (_this->running) { style::endDisabled(); } + if (_this->running) { style::endDisabled(); } if (_this->selectedName != "") { ImGui::PushItemWidth(menuWidth - ImGui::CalcTextSize("LNA Gain").x - 10); @@ -850,29 +863,29 @@ private: } switch (_this->openDev.hwVer) { - case SDRPLAY_RSP1_ID: - _this->RSP1Menu(menuWidth); - break; - case SDRPLAY_RSP1A_ID: - _this->RSP1AMenu(menuWidth); - break; - case SDRPLAY_RSP2_ID: - _this->RSP2Menu(menuWidth); - break; - case SDRPLAY_RSPduo_ID: - _this->RSPduoMenu(menuWidth); - break; - case SDRPLAY_RSPdx_ID: - _this->RSPdxMenu(menuWidth); - break; - default: - _this->RSPUnsupportedMenu(menuWidth); - break; + case SDRPLAY_RSP1_ID: + _this->RSP1Menu(menuWidth); + break; + case SDRPLAY_RSP1A_ID: + _this->RSP1AMenu(menuWidth); + break; + case SDRPLAY_RSP2_ID: + _this->RSP2Menu(menuWidth); + break; + case SDRPLAY_RSPduo_ID: + _this->RSPduoMenu(menuWidth); + break; + case SDRPLAY_RSPdx_ID: + _this->RSPdxMenu(menuWidth); + break; + default: + _this->RSPUnsupportedMenu(menuWidth); + break; } } else { ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "No device available"); - } + } } bool agcParamMenu(bool& valid) { @@ -881,7 +894,7 @@ private: ImGui::OpenPopup("Edit##sdrplay_source_edit_agc_params_"); if (ImGui::BeginPopup("Edit##sdrplay_source_edit_agc_params_", ImGuiWindowFlags_NoResize)) { - ImGui::BeginTable(("sdrplay_source_agc_param_tbl"+name).c_str(), 2); + ImGui::BeginTable(("sdrplay_source_agc_param_tbl" + name).c_str(), 2); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); @@ -938,7 +951,7 @@ private: } return open; } - + void RSP1Menu(float menuWidth) { // No options? } @@ -1103,8 +1116,8 @@ private: ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "Device currently unsupported"); } - static void streamCB(short *xi, short *xq, sdrplay_api_StreamCbParamsT *params, - unsigned int numSamples, unsigned int reset, void *cbContext) { + static void streamCB(short* xi, short* xq, sdrplay_api_StreamCbParamsT* params, + unsigned int numSamples, unsigned int reset, void* cbContext) { SDRPlaySourceModule* _this = (SDRPlaySourceModule*)cbContext; // TODO: Optimise using volk and math if (!_this->running) { return; } @@ -1121,7 +1134,7 @@ private: } static void eventCB(sdrplay_api_EventT eventId, sdrplay_api_TunerSelectT tuner, - sdrplay_api_EventParamsT *params, void *cbContext) { + sdrplay_api_EventParamsT* params, void* cbContext) { SDRPlaySourceModule* _this = (SDRPlaySourceModule*)cbContext; } @@ -1137,7 +1150,7 @@ private: sdrplay_api_CallbackFnsT cbFuncs; sdrplay_api_DeviceT openDev; - sdrplay_api_DeviceParamsT * openDevParams; + sdrplay_api_DeviceParamsT* openDevParams; sdrplay_api_RxChannelParamsT* channelParams; sdrplay_api_Bw_MHzT bandwidth; @@ -1149,7 +1162,7 @@ private: int lnaGain = 9; int gain = 59; int lnaSteps = 9; - + bool agc = false; bool agcParamEdit = false; int agcAttack = 500; diff --git a/source_modules/soapy_source/src/main.cpp b/source_modules/soapy_source/src/main.cpp index 68788ef6..cb92fe05 100644 --- a/source_modules/soapy_source/src/main.cpp +++ b/source_modules/soapy_source/src/main.cpp @@ -14,7 +14,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "soapy_source", /* Description: */ "SoapySDR source module for SDR++", /* Author: */ "Ryzerth", @@ -70,7 +70,7 @@ public: bool isEnabled() { return enabled; } - + template std::string to_string_with_precision(const T a_value, const int n = 6) { std::ostringstream out; @@ -90,15 +90,16 @@ private: i++; } } - + float selectBwBySr(double samplerate) { float cur = bandwidthList[1]; std::vector bwListReversed = bandwidthList; std::reverse(bwListReversed.begin(), bwListReversed.end()); - for(auto bw : bwListReversed) { - if(bw >= samplerate) { + for (auto bw : bwListReversed) { + if (bw >= samplerate) { cur = bw; - } else { + } + else { break; } } @@ -156,7 +157,7 @@ private: antennaList = dev->listAntennas(SOAPY_SDR_RX, channelId); txtAntennaList = ""; - for (const std::string & ant : antennaList) { + for (const std::string& ant : antennaList) { txtAntennaList += ant + '\0'; } @@ -164,27 +165,29 @@ private: delete[] uiGains; uiGains = new float[gainList.size()]; gainRanges.clear(); - + for (auto gain : gainList) { gainRanges.push_back(dev->getGainRange(SOAPY_SDR_RX, channelId, gain)); } - + SoapySDR::RangeList bandwidthRange = dev->getBandwidthRange(SOAPY_SDR_RX, channelId); - + txtBwList = ""; bandwidthList.clear(); bandwidthList.push_back(-1); txtBwList += "Auto"; txtBwList += '\0'; - - for(auto bwr : bandwidthRange) { + + for (auto bwr : bandwidthRange) { float bw = bwr.minimum(); bandwidthList.push_back(bw); if (bw > 1.0e3 && bw <= 1.0e6) { txtBwList += to_string_with_precision((bw / 1.0e3), 2) + " kHz"; - } else if (bw > 1.0e6) { + } + else if (bw > 1.0e6) { txtBwList += to_string_with_precision((bw / 1.0e6), 2) + " MHz"; - } else { + } + else { txtBwList += to_string_with_precision(bw, 0); } txtBwList += '\0'; @@ -195,9 +198,11 @@ private: for (double sr : sampleRates) { if (sr > 1.0e3 && sr <= 1.0e6) { txtSrList += to_string_with_precision((sr / 1.0e3), 2) + " kHz"; - } else if (sr > 1.0e6) { + } + else if (sr > 1.0e6) { txtSrList += to_string_with_precision((sr / 1.0e6), 2) + " MHz"; - } else { + } + else { txtSrList += to_string_with_precision(sr, 0); } txtSrList += '\0'; @@ -209,9 +214,10 @@ private: config.acquire(); if (config.conf["devices"].contains(name)) { - if(config.conf["devices"][name].contains("antenna")) { + if (config.conf["devices"][name].contains("antenna")) { uiAntennaId = config.conf["devices"][name]["antenna"]; - } else { + } + else { uiAntennaId = 0; } int i = 0; @@ -224,9 +230,10 @@ private: } i++; } - if(config.conf["devices"][name].contains("bandwidth")) { + if (config.conf["devices"][name].contains("bandwidth")) { uiBandwidthId = config.conf["devices"][name]["bandwidth"]; - } else if(bandwidthList.size() > 2) { + } + else if (bandwidthList.size() > 2) { uiBandwidthId = 0; } if (hasAgc && config.conf["devices"][name].contains("agc")) { @@ -249,7 +256,7 @@ private: uiGains[i] = gainRanges[i].minimum(); i++; } - if(bandwidthList.size() > 2) + if (bandwidthList.size() > 2) uiBandwidthId = 0; if (hasAgc) { agc = false; @@ -257,7 +264,6 @@ private: selectSampleRate(sampleRates[0]); // Select default } config.release(); - } void saveCurrent() { @@ -269,7 +275,7 @@ private: conf["gains"][gain] = uiGains[i]; i++; } - if(bandwidthList.size() > 2) + if (bandwidthList.size() > 2) conf["bandwidth"] = uiBandwidthId; if (hasAgc) { conf["agc"] = agc; @@ -292,7 +298,7 @@ private: SoapyModule* _this = (SoapyModule*)ctx; spdlog::info("SoapyModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { SoapyModule* _this = (SoapyModule*)ctx; if (_this->running) { return; } @@ -307,8 +313,8 @@ private: _this->dev->setAntenna(SOAPY_SDR_RX, _this->channelId, _this->antennaList[_this->uiAntennaId]); - if(_this->bandwidthList.size() > 2) { - if(_this->bandwidthList[_this->uiBandwidthId] == -1) + if (_this->bandwidthList.size() > 2) { + if (_this->bandwidthList[_this->uiBandwidthId] == -1) _this->dev->setBandwidth(SOAPY_SDR_RX, _this->channelId, _this->selectBwBySr(_this->sampleRates[_this->srId])); else _this->dev->setBandwidth(SOAPY_SDR_RX, _this->channelId, _this->bandwidthList[_this->uiBandwidthId]); @@ -332,7 +338,7 @@ private: _this->workerThread = std::thread(_worker, _this); spdlog::info("SoapyModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { SoapyModule* _this = (SoapyModule*)ctx; if (!_this->running) { return; } @@ -343,10 +349,10 @@ private: _this->workerThread.join(); _this->stream.clearWriteStop(); SoapySDR::Device::unmake(_this->dev); - + spdlog::info("SoapyModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { SoapyModule* _this = (SoapyModule*)ctx; _this->freq = freq; @@ -355,12 +361,12 @@ private: } spdlog::info("SoapyModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { SoapyModule* _this = (SoapyModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); - + // If no device is selected, draw only the refresh button if (_this->devId < 0) { if (ImGui::Button(CONCAT("Refresh##_dev_select_", _this->name), ImVec2(menuWidth, 0))) { @@ -382,7 +388,7 @@ private: if (ImGui::Combo(CONCAT("##_sr_select_", _this->name), &_this->srId, _this->txtSrList.c_str())) { _this->selectSampleRate(_this->sampleRates[_this->srId]); - if(_this->bandwidthList.size() > 2 && _this->running && _this->bandwidthList[_this->uiBandwidthId] == -1) + if (_this->bandwidthList.size() > 2 && _this->running && _this->bandwidthList[_this->uiBandwidthId] == -1) _this->dev->setBandwidth(SOAPY_SDR_RX, _this->channelId, _this->selectBwBySr(_this->sampleRates[_this->srId])); _this->saveCurrent(); } @@ -440,12 +446,13 @@ private: ImGui::SetNextItemWidth(menuWidth - gainNameLen); float step = _this->gainRanges[i].step(); bool res; - if(step == 0.0f) { - res = ImGui::SliderFloat((std::string("##_gain_sel_") + _this->name + gain).c_str(), &_this->uiGains[i], _this->gainRanges[i].minimum(), _this->gainRanges[i].maximum()); - } else { + if (step == 0.0f) { + res = ImGui::SliderFloat((std::string("##_gain_sel_") + _this->name + gain).c_str(), &_this->uiGains[i], _this->gainRanges[i].minimum(), _this->gainRanges[i].maximum()); + } + else { res = ImGui::SliderFloatWithSteps((std::string("##_gain_sel_") + _this->name + gain).c_str(), &_this->uiGains[i], _this->gainRanges[i].minimum(), _this->gainRanges[i].maximum(), step); } - if(res) { + if (res) { if (_this->running) { _this->dev->setGain(SOAPY_SDR_RX, _this->channelId, gain, _this->uiGains[i]); } @@ -453,12 +460,12 @@ private: } i++; } - if(_this->bandwidthList.size() > 2) { + if (_this->bandwidthList.size() > 2) { ImGui::LeftLabel("Bandwidth"); ImGui::SetNextItemWidth(menuWidth - ImGui::GetCursorPosX()); if (ImGui::Combo(CONCAT("##_bw_select_", _this->name), &_this->uiBandwidthId, _this->txtBwList.c_str())) { - if(_this->running) { - if(_this->bandwidthList[_this->uiBandwidthId] == -1) + if (_this->running) { + if (_this->bandwidthList[_this->uiBandwidthId] == -1) _this->dev->setBandwidth(SOAPY_SDR_RX, _this->channelId, _this->selectBwBySr(_this->sampleRates[_this->srId])); else _this->dev->setBandwidth(SOAPY_SDR_RX, _this->channelId, _this->bandwidthList[_this->uiBandwidthId]); @@ -472,7 +479,7 @@ private: int blockSize = _this->sampleRate / 200.0f; int flags = 0; long long timeMs = 0; - + while (_this->running) { int res = _this->dev->readStream(_this->devStream, (void**)&_this->stream.writeBuf, blockSize, flags, timeMs); if (res < 1) { @@ -515,12 +522,12 @@ private: }; MOD_EXPORT void _INIT_() { - config.setPath(options::opts.root + "/soapy_source_config.json"); - json defConf; - defConf["device"] = ""; - defConf["devices"] = json({}); - config.load(defConf); - config.enableAutoSave(); + config.setPath(options::opts.root + "/soapy_source_config.json"); + json defConf; + defConf["device"] = ""; + defConf["devices"] = json({}); + config.load(defConf); + config.enableAutoSave(); } MOD_EXPORT ModuleManager::Instance* _CREATE_INSTANCE_(std::string name) { diff --git a/source_modules/spyserver_source/src/main.cpp b/source_modules/spyserver_source/src/main.cpp index 1a4cc05a..3bbdaeea 100644 --- a/source_modules/spyserver_source/src/main.cpp +++ b/source_modules/spyserver_source/src/main.cpp @@ -13,7 +13,7 @@ #define CONCAT(a, b) ((std::string(a) + b).c_str()) -SDRPP_MOD_INFO { +SDRPP_MOD_INFO{ /* Name: */ "spyserver_source", /* Description: */ "SpyServer source module for SDR++", /* Author: */ "Ryzerth", @@ -29,8 +29,8 @@ const char* deviceTypesStr[] = { }; const char* streamFormatStr = "UInt8\0" - "Int16\0" - "Float32\0"; + "Int16\0" + "Float32\0"; const SpyServerStreamFormat streamFormats[] = { SPYSERVER_STREAM_FORMAT_UINT8, @@ -116,7 +116,7 @@ private: gui::mainWindow.playButtonLocked = false; spdlog::info("SpyServerSourceModule '{0}': Menu Deselect!", _this->name); } - + static void start(void* ctx) { SpyServerSourceModule* _this = (SpyServerSourceModule*)ctx; if (_this->running) { return; } @@ -133,17 +133,17 @@ private: _this->running = true; spdlog::info("SpyServerSourceModule '{0}': Start!", _this->name); } - + static void stop(void* ctx) { SpyServerSourceModule* _this = (SpyServerSourceModule*)ctx; if (!_this->running) { return; } - + _this->client->stopStream(); _this->running = false; spdlog::info("SpyServerSourceModule '{0}': Stop!", _this->name); } - + static void tune(double freq, void* ctx) { SpyServerSourceModule* _this = (SpyServerSourceModule*)ctx; if (_this->running) { @@ -152,7 +152,7 @@ private: _this->freq = freq; spdlog::info("SpyServerSourceModule '{0}': Tune: {1}!", _this->name, freq); } - + static void menuHandler(void* ctx) { SpyServerSourceModule* _this = (SpyServerSourceModule*)ctx; float menuWidth = ImGui::GetContentRegionAvailWidth(); @@ -211,7 +211,7 @@ private: _this->sampleRatesTxt += '\0'; } - _this->srId = std::clamp(_this->srId, 0, _this->sampleRates.size()-1); + _this->srId = std::clamp(_this->srId, 0, _this->sampleRates.size() - 1); _this->sampleRate = _this->sampleRates[_this->srId]; core::setInputSampleRate(_this->sampleRate); @@ -227,7 +227,6 @@ private: } if (_this->running) { style::endDisabled(); } - if (connected) { if (_this->running) { style::beginDisabled(); } @@ -248,7 +247,7 @@ private: int srvBits = streamFormatsBitCount[_this->iqType]; _this->client->setSetting(SPYSERVER_SETTING_IQ_FORMAT, streamFormats[_this->iqType]); _this->client->setSetting(SPYSERVER_SETTING_IQ_DIGITAL_GAIN, _this->client->computeDigitalGain(srvBits, _this->gain, _this->srId + _this->client->devInfo.MinimumIQDecimation)); - + config.acquire(); config.conf["devices"][_this->devRef]["sampleBitDepthId"] = _this->iqType; config.release(true); diff --git a/source_modules/spyserver_source/src/spyserver_client.cpp b/source_modules/spyserver_source/src/spyserver_client.cpp index 368b4488..c37914fa 100644 --- a/source_modules/spyserver_source/src/spyserver_client.cpp +++ b/source_modules/spyserver_source/src/spyserver_client.cpp @@ -62,7 +62,7 @@ namespace spyserver { bool SpyServerClientClass::waitForDevInfo(int timeoutMS) { std::unique_lock lck(deviceInfoMtx); auto now = std::chrono::system_clock::now(); - deviceInfoCnd.wait_until(lck, now + (timeoutMS*1ms), [this](){ return deviceInfoAvailable; }); + deviceInfoCnd.wait_until(lck, now + (timeoutMS * 1ms), [this]() { return deviceInfoAvailable; }); return deviceInfoAvailable; } @@ -109,7 +109,7 @@ namespace spyserver { SpyServerClientClass* _this = (SpyServerClientClass*)ctx; if (count < sizeof(SpyServerMessageHeader)) { - _this->readSize(sizeof(SpyServerMessageHeader)-count, &buf[count]); + _this->readSize(sizeof(SpyServerMessageHeader) - count, &buf[count]); } int size = _this->readSize(_this->receivedHeader.BodySize, _this->readBuf); @@ -133,19 +133,19 @@ namespace spyserver { _this->deviceInfoCnd.notify_all(); } else if (mtype == SPYSERVER_MSG_TYPE_UINT8_IQ) { - int sampCount = _this->receivedHeader.BodySize / (sizeof(uint8_t)*2); + int sampCount = _this->receivedHeader.BodySize / (sizeof(uint8_t) * 2); float gain = pow(10, (double)mflags / 20.0); float scale = 1.0f / (gain * 128.0f); for (int i = 0; i < sampCount; i++) { - _this->output->writeBuf[i].re = ((float)_this->readBuf[(2*i)] - 128.0f) * scale; - _this->output->writeBuf[i].im = ((float)_this->readBuf[(2*i)+1] - 128.0f) * scale; + _this->output->writeBuf[i].re = ((float)_this->readBuf[(2 * i)] - 128.0f) * scale; + _this->output->writeBuf[i].im = ((float)_this->readBuf[(2 * i) + 1] - 128.0f) * scale; } _this->output->swap(sampCount); } else if (mtype == SPYSERVER_MSG_TYPE_INT16_IQ) { - int sampCount = _this->receivedHeader.BodySize / (sizeof(int16_t)*2); + int sampCount = _this->receivedHeader.BodySize / (sizeof(int16_t) * 2); float gain = pow(10, (double)mflags / 20.0); - volk_16i_s32f_convert_32f((float*)_this->output->writeBuf, (int16_t*)_this->readBuf, 32768.0 * gain, sampCount*2); + volk_16i_s32f_convert_32f((float*)_this->output->writeBuf, (int16_t*)_this->readBuf, 32768.0 * gain, sampCount * 2); _this->output->swap(sampCount); } else if (mtype == SPYSERVER_MSG_TYPE_INT24_IQ) { @@ -155,7 +155,7 @@ namespace spyserver { else if (mtype == SPYSERVER_MSG_TYPE_FLOAT_IQ) { int sampCount = _this->receivedHeader.BodySize / sizeof(dsp::complex_t); float gain = pow(10, (double)mflags / 20.0); - volk_32f_s32f_multiply_32f((float*)_this->output->writeBuf, (float*)_this->readBuf, gain, sampCount*2); + volk_32f_s32f_multiply_32f((float*)_this->output->writeBuf, (float*)_this->readBuf, gain, sampCount * 2); _this->output->swap(sampCount); } diff --git a/source_modules/spyserver_source/src/spyserver_client.h b/source_modules/spyserver_source/src/spyserver_client.h index 0745385e..95d072ae 100644 --- a/source_modules/spyserver_source/src/spyserver_client.h +++ b/source_modules/spyserver_source/src/spyserver_client.h @@ -44,11 +44,10 @@ namespace spyserver { SpyServerMessageHeader receivedHeader; dsp::stream* output; - }; - + typedef std::unique_ptr SpyServerClient; SpyServerClient connect(std::string host, uint16_t port, dsp::stream* out); - + } diff --git a/source_modules/spyserver_source/src/spyserver_protocol.h b/source_modules/spyserver_source/src/spyserver_protocol.h index debacc60..139e97f2 100644 --- a/source_modules/spyserver_source/src/spyserver_protocol.h +++ b/source_modules/spyserver_source/src/spyserver_protocol.h @@ -17,85 +17,85 @@ Corrections by Ryzerth. #define SPYSERVER_MAX_COMMAND_BODY_SIZE (256) #define SPYSERVER_MAX_MESSAGE_BODY_SIZE (1 << 20) -#define SPYSERVER_MAX_DISPLAY_PIXELS (1 << 15) -#define SPYSERVER_MIN_DISPLAY_PIXELS (100) -#define SPYSERVER_MAX_FFT_DB_RANGE (150) -#define SPYSERVER_MIN_FFT_DB_RANGE (10) -#define SPYSERVER_MAX_FFT_DB_OFFSET (100) +#define SPYSERVER_MAX_DISPLAY_PIXELS (1 << 15) +#define SPYSERVER_MIN_DISPLAY_PIXELS (100) +#define SPYSERVER_MAX_FFT_DB_RANGE (150) +#define SPYSERVER_MIN_FFT_DB_RANGE (10) +#define SPYSERVER_MAX_FFT_DB_OFFSET (100) enum SpyServerDeviceType { - SPYSERVER_DEVICE_INVALID = 0, - SPYSERVER_DEVICE_AIRSPY_ONE = 1, - SPYSERVER_DEVICE_AIRSPY_HF = 2, - SPYSERVER_DEVICE_RTLSDR = 3, + SPYSERVER_DEVICE_INVALID = 0, + SPYSERVER_DEVICE_AIRSPY_ONE = 1, + SPYSERVER_DEVICE_AIRSPY_HF = 2, + SPYSERVER_DEVICE_RTLSDR = 3, }; enum SpyServerCommandType { - SPYSERVER_CMD_HELLO = 0, - SPYSERVER_CMD_SET_SETTING = 2, - SPYSERVER_CMD_PING = 3, + SPYSERVER_CMD_HELLO = 0, + SPYSERVER_CMD_SET_SETTING = 2, + SPYSERVER_CMD_PING = 3, }; enum SpyServerSettingType { - SPYSERVER_SETTING_STREAMING_MODE = 0, - SPYSERVER_SETTING_STREAMING_ENABLED = 1, - SPYSERVER_SETTING_GAIN = 2, + SPYSERVER_SETTING_STREAMING_MODE = 0, + SPYSERVER_SETTING_STREAMING_ENABLED = 1, + SPYSERVER_SETTING_GAIN = 2, - SPYSERVER_SETTING_IQ_FORMAT = 100, // 0x64 - SPYSERVER_SETTING_IQ_FREQUENCY = 101, // 0x65 - SPYSERVER_SETTING_IQ_DECIMATION = 102, // 0x66 - SPYSERVER_SETTING_IQ_DIGITAL_GAIN = 103, // 0x67 + SPYSERVER_SETTING_IQ_FORMAT = 100, // 0x64 + SPYSERVER_SETTING_IQ_FREQUENCY = 101, // 0x65 + SPYSERVER_SETTING_IQ_DECIMATION = 102, // 0x66 + SPYSERVER_SETTING_IQ_DIGITAL_GAIN = 103, // 0x67 - SPYSERVER_SETTING_FFT_FORMAT = 200, // 0xc8 - SPYSERVER_SETTING_FFT_FREQUENCY = 201, // 0xc9 - SPYSERVER_SETTING_FFT_DECIMATION = 202, // 0xca - SPYSERVER_SETTING_FFT_DB_OFFSET = 203, // 0xcb - SPYSERVER_SETTING_FFT_DB_RANGE = 204, // 0xcc - SPYSERVER_SETTING_FFT_DISPLAY_PIXELS = 205, // 0xcd + SPYSERVER_SETTING_FFT_FORMAT = 200, // 0xc8 + SPYSERVER_SETTING_FFT_FREQUENCY = 201, // 0xc9 + SPYSERVER_SETTING_FFT_DECIMATION = 202, // 0xca + SPYSERVER_SETTING_FFT_DB_OFFSET = 203, // 0xcb + SPYSERVER_SETTING_FFT_DB_RANGE = 204, // 0xcc + SPYSERVER_SETTING_FFT_DISPLAY_PIXELS = 205, // 0xcd }; enum SpyServerStreamType { - SPYSERVER_STREAM_TYPE_STATUS = 0, - SPYSERVER_STREAM_TYPE_IQ = 1, - SPYSERVER_STREAM_TYPE_AF = 2, - SPYSERVER_STREAM_TYPE_FFT = 4, + SPYSERVER_STREAM_TYPE_STATUS = 0, + SPYSERVER_STREAM_TYPE_IQ = 1, + SPYSERVER_STREAM_TYPE_AF = 2, + SPYSERVER_STREAM_TYPE_FFT = 4, }; enum SpyServerStreamingMode { - SPYSERVER_STREAM_MODE_IQ_ONLY = SPYSERVER_STREAM_TYPE_IQ, // 0x01 - SPYSERVER_STREAM_MODE_AF_ONLY = SPYSERVER_STREAM_TYPE_AF, // 0x02 - SPYSERVER_STREAM_MODE_FFT_ONLY = SPYSERVER_STREAM_TYPE_FFT, // 0x04 - SPYSERVER_STREAM_MODE_FFT_IQ = SPYSERVER_STREAM_TYPE_FFT | SPYSERVER_STREAM_TYPE_IQ, // 0x05 - SPYSERVER_STREAM_MODE_FFT_AF = SPYSERVER_STREAM_TYPE_FFT | SPYSERVER_STREAM_TYPE_AF, // 0x06 + SPYSERVER_STREAM_MODE_IQ_ONLY = SPYSERVER_STREAM_TYPE_IQ, // 0x01 + SPYSERVER_STREAM_MODE_AF_ONLY = SPYSERVER_STREAM_TYPE_AF, // 0x02 + SPYSERVER_STREAM_MODE_FFT_ONLY = SPYSERVER_STREAM_TYPE_FFT, // 0x04 + SPYSERVER_STREAM_MODE_FFT_IQ = SPYSERVER_STREAM_TYPE_FFT | SPYSERVER_STREAM_TYPE_IQ, // 0x05 + SPYSERVER_STREAM_MODE_FFT_AF = SPYSERVER_STREAM_TYPE_FFT | SPYSERVER_STREAM_TYPE_AF, // 0x06 }; enum SpyServerStreamFormat { - SPYSERVER_STREAM_FORMAT_INVALID = 0, - SPYSERVER_STREAM_FORMAT_UINT8 = 1, - SPYSERVER_STREAM_FORMAT_INT16 = 2, - SPYSERVER_STREAM_FORMAT_INT24 = 3, - SPYSERVER_STREAM_FORMAT_FLOAT = 4, - SPYSERVER_STREAM_FORMAT_DINT4 = 5, + SPYSERVER_STREAM_FORMAT_INVALID = 0, + SPYSERVER_STREAM_FORMAT_UINT8 = 1, + SPYSERVER_STREAM_FORMAT_INT16 = 2, + SPYSERVER_STREAM_FORMAT_INT24 = 3, + SPYSERVER_STREAM_FORMAT_FLOAT = 4, + SPYSERVER_STREAM_FORMAT_DINT4 = 5, }; enum SpyServerMessageType { - SPYSERVER_MSG_TYPE_DEVICE_INFO = 0, - SPYSERVER_MSG_TYPE_CLIENT_SYNC = 1, - SPYSERVER_MSG_TYPE_PONG = 2, - SPYSERVER_MSG_TYPE_READ_SETTING = 3, + SPYSERVER_MSG_TYPE_DEVICE_INFO = 0, + SPYSERVER_MSG_TYPE_CLIENT_SYNC = 1, + SPYSERVER_MSG_TYPE_PONG = 2, + SPYSERVER_MSG_TYPE_READ_SETTING = 3, - SPYSERVER_MSG_TYPE_UINT8_IQ = 100, // 0x64 - SPYSERVER_MSG_TYPE_INT16_IQ = 101, // 0x65 - SPYSERVER_MSG_TYPE_INT24_IQ = 102, // 0x66 - SPYSERVER_MSG_TYPE_FLOAT_IQ = 103, // 0x67 + SPYSERVER_MSG_TYPE_UINT8_IQ = 100, // 0x64 + SPYSERVER_MSG_TYPE_INT16_IQ = 101, // 0x65 + SPYSERVER_MSG_TYPE_INT24_IQ = 102, // 0x66 + SPYSERVER_MSG_TYPE_FLOAT_IQ = 103, // 0x67 - SPYSERVER_MSG_TYPE_UINT8_AF = 200, // 0xc8 - SPYSERVER_MSG_TYPE_INT16_AF = 201, // 0xc9 - SPYSERVER_MSG_TYPE_INT24_AF = 202, // 0xca - SPYSERVER_MSG_TYPE_FLOAT_AF = 203, // 0xcb + SPYSERVER_MSG_TYPE_UINT8_AF = 200, // 0xc8 + SPYSERVER_MSG_TYPE_INT16_AF = 201, // 0xc9 + SPYSERVER_MSG_TYPE_INT24_AF = 202, // 0xca + SPYSERVER_MSG_TYPE_FLOAT_AF = 203, // 0xcb - SPYSERVER_MSG_TYPE_DINT4_FFT = 300, //0x12C - SPYSERVER_MSG_TYPE_UINT8_FFT = 301, //0x12D + SPYSERVER_MSG_TYPE_DINT4_FFT = 300, //0x12C + SPYSERVER_MSG_TYPE_UINT8_FFT = 301, //0x12D }; struct SpyServerClientHandshake { diff --git a/src/main.cpp b/src/main.cpp index d349eb46..9fc1638c 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,6 +1,6 @@ #include #include -int main(int argc, char *argv[]) { +int main(int argc, char* argv[]) { return sdrpp_main(argc, argv); } \ No newline at end of file