From 7d3bfb26fcfb38c19b972b4d7a897cef2deaa590 Mon Sep 17 00:00:00 2001 From: Hexameron Date: Sun, 18 May 2014 16:52:39 +0100 Subject: [PATCH] git clone git://git.osmocom.org/sdrangelove.git --- .gitignore | 3 + CMakeLists.txt | 294 + cmake/Modules/FindFFTW3F.cmake | 40 + cmake/Modules/FindGruel.cmake | 29 + cmake/Modules/FindLibOsmoSDR.cmake | 28 + cmake/Modules/FindLibRTLSDR.cmake | 28 + cmake/Modules/FindLibUSB.cmake | 28 + include-gpl/audio/audiodeviceinfo.h | 49 + include-gpl/audio/audiofifo.h | 65 + include-gpl/audio/audiooutput.h | 57 + include-gpl/dsp/channelizer.h | 109 + include-gpl/dsp/dspcommands.h | 255 + include-gpl/dsp/dspengine.h | 119 + include-gpl/dsp/fftengine.h | 20 + include-gpl/dsp/fftwengine.h | 37 + include-gpl/dsp/fftwindow.h | 82 + include-gpl/dsp/interpolator.h | 130 + include-gpl/dsp/inthalfbandfilter.h | 314 ++ include-gpl/dsp/kissengine.h | 23 + include-gpl/dsp/lowpass.h | 88 + include-gpl/dsp/movingaverage.h | 53 + include-gpl/dsp/nco.h | 45 + include-gpl/dsp/scopevis.h | 44 + include-gpl/dsp/spectrumvis.h | 42 + include-gpl/gui/aboutdialog.h | 21 + include-gpl/gui/addpresetdialog.h | 30 + include-gpl/gui/buttonswitch.h | 19 + include-gpl/gui/channelwindow.h | 25 + include-gpl/gui/glscope.h | 110 + include-gpl/gui/glspectrum.h | 157 + include-gpl/gui/glspectrumgui.h | 65 + include-gpl/gui/indicator.h | 41 + include-gpl/gui/physicalunit.h | 35 + include-gpl/gui/pluginsdialog.h | 22 + include-gpl/gui/preferencesdialog.h | 34 + include-gpl/gui/presetitem.h | 27 + include-gpl/gui/scale.h | 37 + include-gpl/gui/scaleengine.h | 90 + include-gpl/gui/scopewindow.h | 67 + include-gpl/gui/valuedial.h | 72 + include-gpl/mainwindow.h | 136 + include-gpl/plugin/pluginmanager.h | 131 + include-gpl/settings/preferences.h | 32 + include-gpl/settings/preset.h | 98 + include-gpl/settings/settings.h | 32 + include/dsp/channelmarker.h | 43 + include/dsp/dsptypes.h | 54 + include/dsp/kissfft.h | 391 ++ include/dsp/samplefifo.h | 66 + include/dsp/samplesink.h | 21 + include/dsp/samplesource/samplesource.h | 61 + include/dsp/threadedsamplesink.h | 41 + include/gui/basicchannelsettingswidget.h | 34 + include/gui/rollupwidget.h | 42 + include/plugin/pluginapi.h | 60 + include/plugin/plugingui.h | 28 + include/plugin/plugininterface.h | 48 + include/util/export.h | 46 + include/util/message.h | 58 + include/util/messagequeue.h | 31 + include/util/miniz.h | 7 + include/util/simpleserializer.h | 112 + include/util/spinlock.h | 39 + main.cpp | 101 + plugins/CMakeLists.txt | 4 + plugins/channel/CMakeLists.txt | 5 + plugins/channel/nfm/CMakeLists.txt | 47 + plugins/channel/nfm/nfmdemod.cpp | 147 + plugins/channel/nfm/nfmdemod.h | 104 + plugins/channel/nfm/nfmdemodgui.cpp | 210 + plugins/channel/nfm/nfmdemodgui.h | 64 + plugins/channel/nfm/nfmdemodgui.ui | 250 + plugins/channel/nfm/nfmplugin.cpp | 53 + plugins/channel/nfm/nfmplugin.h | 29 + plugins/channel/tcpsrc/CMakeLists.txt | 47 + plugins/channel/tcpsrc/tcpsrc.cpp | 205 + plugins/channel/tcpsrc/tcpsrc.h | 153 + plugins/channel/tcpsrc/tcpsrcgui.cpp | 278 + plugins/channel/tcpsrc/tcpsrcgui.h | 72 + plugins/channel/tcpsrc/tcpsrcgui.ui | 213 + plugins/channel/tcpsrc/tcpsrcplugin.cpp | 53 + plugins/channel/tcpsrc/tcpsrcplugin.h | 29 + plugins/channel/tetra/CMakeLists.txt | 47 + plugins/channel/tetra/tetrademod.cpp | 106 + plugins/channel/tetra/tetrademod.h | 67 + plugins/channel/tetra/tetrademodgui.cpp | 110 + plugins/channel/tetra/tetrademodgui.h | 56 + plugins/channel/tetra/tetrademodgui.ui | 56 + plugins/channel/tetra/tetraplugin.cpp | 50 + plugins/channel/tetra/tetraplugin.h | 29 + plugins/samplesource/CMakeLists.txt | 15 + plugins/samplesource/gnuradio/CMakeLists.txt | 87 + .../cmake/Modules/FindGnuradioOsmosdr.cmake | 29 + .../cmake/Modules/FindGnuradioRuntime.cmake | 29 + plugins/samplesource/gnuradio/gnuradiogui.cpp | 422 ++ plugins/samplesource/gnuradio/gnuradiogui.h | 99 + plugins/samplesource/gnuradio/gnuradiogui.ui | 301 + .../samplesource/gnuradio/gnuradioinput.cpp | 332 ++ plugins/samplesource/gnuradio/gnuradioinput.h | 156 + .../samplesource/gnuradio/gnuradioplugin.cpp | 52 + .../samplesource/gnuradio/gnuradioplugin.h | 27 + .../samplesource/gnuradio/gnuradiothread.cpp | 144 + .../samplesource/gnuradio/gnuradiothread.h | 64 + plugins/samplesource/osmosdr/CMakeLists.txt | 54 + plugins/samplesource/osmosdr/osmosdrgui.cpp | 310 ++ plugins/samplesource/osmosdr/osmosdrgui.h | 70 + plugins/samplesource/osmosdr/osmosdrgui.ui | 770 +++ plugins/samplesource/osmosdr/osmosdrinput.cpp | 479 ++ plugins/samplesource/osmosdr/osmosdrinput.h | 99 + .../samplesource/osmosdr/osmosdrplugin.cpp | 69 + plugins/samplesource/osmosdr/osmosdrplugin.h | 27 + .../samplesource/osmosdr/osmosdrthread.cpp | 116 + plugins/samplesource/osmosdr/osmosdrthread.h | 66 + .../samplesource/osmosdr/osmosdrupgrade.cpp | 518 ++ plugins/samplesource/osmosdr/osmosdrupgrade.h | 60 + .../samplesource/osmosdr/osmosdrupgrade.ui | 213 + plugins/samplesource/rtlsdr/CMakeLists.txt | 50 + plugins/samplesource/rtlsdr/rtlsdrgui.cpp | 154 + plugins/samplesource/rtlsdr/rtlsdrgui.h | 53 + plugins/samplesource/rtlsdr/rtlsdrgui.ui | 229 + plugins/samplesource/rtlsdr/rtlsdrinput.cpp | 230 + plugins/samplesource/rtlsdr/rtlsdrinput.h | 105 + plugins/samplesource/rtlsdr/rtlsdrplugin.cpp | 67 + plugins/samplesource/rtlsdr/rtlsdrplugin.h | 27 + plugins/samplesource/rtlsdr/rtlsdrthread.cpp | 172 + plugins/samplesource/rtlsdr/rtlsdrthread.h | 67 + sdrbase/audio/audiodeviceinfo.cpp | 28 + sdrbase/audio/audiofifo.cpp | 218 + sdrbase/audio/audiooutput.cpp | 172 + sdrbase/dsp/channelizer.cpp | 328 ++ sdrbase/dsp/channelmarker.cpp | 68 + sdrbase/dsp/dspcommands.cpp | 19 + sdrbase/dsp/dspengine.cpp | 517 ++ sdrbase/dsp/fftengine.cpp | 26 + sdrbase/dsp/fftwengine.cpp | 69 + sdrbase/dsp/fftwindow.cpp | 73 + sdrbase/dsp/interpolator.cpp | 120 + sdrbase/dsp/inthalfbandfilter.cpp | 11 + sdrbase/dsp/kissengine.cpp | 25 + sdrbase/dsp/lowpass.cpp | 6 + sdrbase/dsp/movingaverage.cpp | 1 + sdrbase/dsp/nco.cpp | 70 + sdrbase/dsp/pidcontroller.cpp | 17 + sdrbase/dsp/pidcontroller.h | 28 + sdrbase/dsp/samplefifo.cpp | 231 + sdrbase/dsp/samplesink.cpp | 66 + sdrbase/dsp/samplesource/samplesource.cpp | 64 + sdrbase/dsp/scopevis.cpp | 141 + sdrbase/dsp/spectrumvis.cpp | 125 + sdrbase/dsp/threadedsamplesink.cpp | 111 + sdrbase/gui/aboutdialog.cpp | 14 + sdrbase/gui/aboutdialog.ui | 161 + sdrbase/gui/addpresetdialog.cpp | 26 + sdrbase/gui/addpresetdialog.ui | 121 + sdrbase/gui/basicchannelsettingswidget.cpp | 77 + sdrbase/gui/basicchannelsettingswidget.ui | 107 + sdrbase/gui/buttonswitch.cpp | 21 + sdrbase/gui/channelwindow.cpp | 36 + sdrbase/gui/glscope.cpp | 478 ++ sdrbase/gui/glspectrum.cpp | 1278 +++++ sdrbase/gui/glspectrumgui.cpp | 210 + sdrbase/gui/glspectrumgui.ui | 476 ++ sdrbase/gui/indicator.cpp | 56 + sdrbase/gui/pluginsdialog.cpp | 42 + sdrbase/gui/pluginsdialog.ui | 67 + sdrbase/gui/preferencesdialog.cpp | 55 + sdrbase/gui/preferencesdialog.ui | 109 + sdrbase/gui/presetitem.cpp | 29 + sdrbase/gui/rollupwidget.cpp | 348 ++ sdrbase/gui/scale.cpp | 129 + sdrbase/gui/scaleengine.cpp | 569 ++ sdrbase/gui/scopewindow.cpp | 185 + sdrbase/gui/scopewindow.ui | 320 ++ sdrbase/gui/valuedial.cpp | 427 ++ sdrbase/mainwindow.cpp | 526 ++ sdrbase/mainwindow.ui | 483 ++ sdrbase/plugin/pluginapi.cpp | 99 + sdrbase/plugin/plugingui.cpp | 16 + sdrbase/plugin/plugininterface.cpp | 1 + sdrbase/plugin/pluginmanager.cpp | 280 + sdrbase/resources/appicon.ico | Bin 0 -> 9062 bytes sdrbase/resources/appicon.png | Bin 0 -> 326 bytes sdrbase/resources/grid.png | Bin 0 -> 259 bytes sdrbase/resources/histogram.png | Bin 0 -> 1160 bytes sdrbase/resources/horizontal.png | Bin 0 -> 187 bytes sdrbase/resources/invertspectrum.png | Bin 0 -> 1272 bytes sdrbase/resources/logo.png | Bin 0 -> 35172 bytes sdrbase/resources/maxhold.png | Bin 0 -> 594 bytes sdrbase/resources/preset-delete.png | Bin 0 -> 731 bytes sdrbase/resources/preset-load.png | Bin 0 -> 925 bytes sdrbase/resources/preset-save.png | Bin 0 -> 996 bytes sdrbase/resources/res.qrc | 16 + sdrbase/resources/sdrangelove.rc | 1 + sdrbase/resources/vertical.png | Bin 0 -> 195 bytes sdrbase/resources/waterfall.png | Bin 0 -> 1368 bytes sdrbase/settings/preferences.cpp | 46 + sdrbase/settings/preset.cpp | 88 + sdrbase/settings/settings.cpp | 76 + sdrbase/util/message.cpp | 79 + sdrbase/util/messagequeue.cpp | 40 + sdrbase/util/miniz.cpp | 4835 +++++++++++++++++ sdrbase/util/simpleserializer.cpp | 704 +++ sdrbase/util/spinlock.cpp | 1 + 203 files changed, 27958 insertions(+) create mode 100644 .gitignore create mode 100644 CMakeLists.txt create mode 100644 cmake/Modules/FindFFTW3F.cmake create mode 100644 cmake/Modules/FindGruel.cmake create mode 100644 cmake/Modules/FindLibOsmoSDR.cmake create mode 100644 cmake/Modules/FindLibRTLSDR.cmake create mode 100644 cmake/Modules/FindLibUSB.cmake create mode 100644 include-gpl/audio/audiodeviceinfo.h create mode 100644 include-gpl/audio/audiofifo.h create mode 100644 include-gpl/audio/audiooutput.h create mode 100644 include-gpl/dsp/channelizer.h create mode 100644 include-gpl/dsp/dspcommands.h create mode 100644 include-gpl/dsp/dspengine.h create mode 100644 include-gpl/dsp/fftengine.h create mode 100644 include-gpl/dsp/fftwengine.h create mode 100644 include-gpl/dsp/fftwindow.h create mode 100644 include-gpl/dsp/interpolator.h create mode 100644 include-gpl/dsp/inthalfbandfilter.h create mode 100644 include-gpl/dsp/kissengine.h create mode 100644 include-gpl/dsp/lowpass.h create mode 100644 include-gpl/dsp/movingaverage.h create mode 100644 include-gpl/dsp/nco.h create mode 100644 include-gpl/dsp/scopevis.h create mode 100644 include-gpl/dsp/spectrumvis.h create mode 100644 include-gpl/gui/aboutdialog.h create mode 100644 include-gpl/gui/addpresetdialog.h create mode 100644 include-gpl/gui/buttonswitch.h create mode 100644 include-gpl/gui/channelwindow.h create mode 100644 include-gpl/gui/glscope.h create mode 100644 include-gpl/gui/glspectrum.h create mode 100644 include-gpl/gui/glspectrumgui.h create mode 100644 include-gpl/gui/indicator.h create mode 100644 include-gpl/gui/physicalunit.h create mode 100644 include-gpl/gui/pluginsdialog.h create mode 100644 include-gpl/gui/preferencesdialog.h create mode 100644 include-gpl/gui/presetitem.h create mode 100644 include-gpl/gui/scale.h create mode 100644 include-gpl/gui/scaleengine.h create mode 100644 include-gpl/gui/scopewindow.h create mode 100644 include-gpl/gui/valuedial.h create mode 100644 include-gpl/mainwindow.h create mode 100644 include-gpl/plugin/pluginmanager.h create mode 100644 include-gpl/settings/preferences.h create mode 100644 include-gpl/settings/preset.h create mode 100644 include-gpl/settings/settings.h create mode 100644 include/dsp/channelmarker.h create mode 100644 include/dsp/dsptypes.h create mode 100644 include/dsp/kissfft.h create mode 100644 include/dsp/samplefifo.h create mode 100644 include/dsp/samplesink.h create mode 100644 include/dsp/samplesource/samplesource.h create mode 100644 include/dsp/threadedsamplesink.h create mode 100644 include/gui/basicchannelsettingswidget.h create mode 100644 include/gui/rollupwidget.h create mode 100644 include/plugin/pluginapi.h create mode 100644 include/plugin/plugingui.h create mode 100644 include/plugin/plugininterface.h create mode 100644 include/util/export.h create mode 100644 include/util/message.h create mode 100644 include/util/messagequeue.h create mode 100644 include/util/miniz.h create mode 100644 include/util/simpleserializer.h create mode 100644 include/util/spinlock.h create mode 100644 main.cpp create mode 100644 plugins/CMakeLists.txt create mode 100644 plugins/channel/CMakeLists.txt create mode 100644 plugins/channel/nfm/CMakeLists.txt create mode 100644 plugins/channel/nfm/nfmdemod.cpp create mode 100644 plugins/channel/nfm/nfmdemod.h create mode 100644 plugins/channel/nfm/nfmdemodgui.cpp create mode 100644 plugins/channel/nfm/nfmdemodgui.h create mode 100644 plugins/channel/nfm/nfmdemodgui.ui create mode 100644 plugins/channel/nfm/nfmplugin.cpp create mode 100644 plugins/channel/nfm/nfmplugin.h create mode 100644 plugins/channel/tcpsrc/CMakeLists.txt create mode 100644 plugins/channel/tcpsrc/tcpsrc.cpp create mode 100644 plugins/channel/tcpsrc/tcpsrc.h create mode 100644 plugins/channel/tcpsrc/tcpsrcgui.cpp create mode 100644 plugins/channel/tcpsrc/tcpsrcgui.h create mode 100644 plugins/channel/tcpsrc/tcpsrcgui.ui create mode 100644 plugins/channel/tcpsrc/tcpsrcplugin.cpp create mode 100644 plugins/channel/tcpsrc/tcpsrcplugin.h create mode 100644 plugins/channel/tetra/CMakeLists.txt create mode 100644 plugins/channel/tetra/tetrademod.cpp create mode 100644 plugins/channel/tetra/tetrademod.h create mode 100644 plugins/channel/tetra/tetrademodgui.cpp create mode 100644 plugins/channel/tetra/tetrademodgui.h create mode 100644 plugins/channel/tetra/tetrademodgui.ui create mode 100644 plugins/channel/tetra/tetraplugin.cpp create mode 100644 plugins/channel/tetra/tetraplugin.h create mode 100644 plugins/samplesource/CMakeLists.txt create mode 100644 plugins/samplesource/gnuradio/CMakeLists.txt create mode 100644 plugins/samplesource/gnuradio/cmake/Modules/FindGnuradioOsmosdr.cmake create mode 100644 plugins/samplesource/gnuradio/cmake/Modules/FindGnuradioRuntime.cmake create mode 100644 plugins/samplesource/gnuradio/gnuradiogui.cpp create mode 100644 plugins/samplesource/gnuradio/gnuradiogui.h create mode 100644 plugins/samplesource/gnuradio/gnuradiogui.ui create mode 100644 plugins/samplesource/gnuradio/gnuradioinput.cpp create mode 100644 plugins/samplesource/gnuradio/gnuradioinput.h create mode 100644 plugins/samplesource/gnuradio/gnuradioplugin.cpp create mode 100644 plugins/samplesource/gnuradio/gnuradioplugin.h create mode 100644 plugins/samplesource/gnuradio/gnuradiothread.cpp create mode 100644 plugins/samplesource/gnuradio/gnuradiothread.h create mode 100644 plugins/samplesource/osmosdr/CMakeLists.txt create mode 100644 plugins/samplesource/osmosdr/osmosdrgui.cpp create mode 100644 plugins/samplesource/osmosdr/osmosdrgui.h create mode 100644 plugins/samplesource/osmosdr/osmosdrgui.ui create mode 100644 plugins/samplesource/osmosdr/osmosdrinput.cpp create mode 100644 plugins/samplesource/osmosdr/osmosdrinput.h create mode 100644 plugins/samplesource/osmosdr/osmosdrplugin.cpp create mode 100644 plugins/samplesource/osmosdr/osmosdrplugin.h create mode 100644 plugins/samplesource/osmosdr/osmosdrthread.cpp create mode 100644 plugins/samplesource/osmosdr/osmosdrthread.h create mode 100644 plugins/samplesource/osmosdr/osmosdrupgrade.cpp create mode 100644 plugins/samplesource/osmosdr/osmosdrupgrade.h create mode 100644 plugins/samplesource/osmosdr/osmosdrupgrade.ui create mode 100644 plugins/samplesource/rtlsdr/CMakeLists.txt create mode 100644 plugins/samplesource/rtlsdr/rtlsdrgui.cpp create mode 100644 plugins/samplesource/rtlsdr/rtlsdrgui.h create mode 100644 plugins/samplesource/rtlsdr/rtlsdrgui.ui create mode 100644 plugins/samplesource/rtlsdr/rtlsdrinput.cpp create mode 100644 plugins/samplesource/rtlsdr/rtlsdrinput.h create mode 100644 plugins/samplesource/rtlsdr/rtlsdrplugin.cpp create mode 100644 plugins/samplesource/rtlsdr/rtlsdrplugin.h create mode 100644 plugins/samplesource/rtlsdr/rtlsdrthread.cpp create mode 100644 plugins/samplesource/rtlsdr/rtlsdrthread.h create mode 100644 sdrbase/audio/audiodeviceinfo.cpp create mode 100644 sdrbase/audio/audiofifo.cpp create mode 100644 sdrbase/audio/audiooutput.cpp create mode 100644 sdrbase/dsp/channelizer.cpp create mode 100644 sdrbase/dsp/channelmarker.cpp create mode 100644 sdrbase/dsp/dspcommands.cpp create mode 100644 sdrbase/dsp/dspengine.cpp create mode 100644 sdrbase/dsp/fftengine.cpp create mode 100644 sdrbase/dsp/fftwengine.cpp create mode 100644 sdrbase/dsp/fftwindow.cpp create mode 100644 sdrbase/dsp/interpolator.cpp create mode 100644 sdrbase/dsp/inthalfbandfilter.cpp create mode 100644 sdrbase/dsp/kissengine.cpp create mode 100644 sdrbase/dsp/lowpass.cpp create mode 100644 sdrbase/dsp/movingaverage.cpp create mode 100644 sdrbase/dsp/nco.cpp create mode 100644 sdrbase/dsp/pidcontroller.cpp create mode 100644 sdrbase/dsp/pidcontroller.h create mode 100644 sdrbase/dsp/samplefifo.cpp create mode 100644 sdrbase/dsp/samplesink.cpp create mode 100644 sdrbase/dsp/samplesource/samplesource.cpp create mode 100644 sdrbase/dsp/scopevis.cpp create mode 100644 sdrbase/dsp/spectrumvis.cpp create mode 100644 sdrbase/dsp/threadedsamplesink.cpp create mode 100644 sdrbase/gui/aboutdialog.cpp create mode 100644 sdrbase/gui/aboutdialog.ui create mode 100644 sdrbase/gui/addpresetdialog.cpp create mode 100644 sdrbase/gui/addpresetdialog.ui create mode 100644 sdrbase/gui/basicchannelsettingswidget.cpp create mode 100644 sdrbase/gui/basicchannelsettingswidget.ui create mode 100644 sdrbase/gui/buttonswitch.cpp create mode 100644 sdrbase/gui/channelwindow.cpp create mode 100644 sdrbase/gui/glscope.cpp create mode 100644 sdrbase/gui/glspectrum.cpp create mode 100644 sdrbase/gui/glspectrumgui.cpp create mode 100644 sdrbase/gui/glspectrumgui.ui create mode 100644 sdrbase/gui/indicator.cpp create mode 100644 sdrbase/gui/pluginsdialog.cpp create mode 100644 sdrbase/gui/pluginsdialog.ui create mode 100644 sdrbase/gui/preferencesdialog.cpp create mode 100644 sdrbase/gui/preferencesdialog.ui create mode 100644 sdrbase/gui/presetitem.cpp create mode 100644 sdrbase/gui/rollupwidget.cpp create mode 100644 sdrbase/gui/scale.cpp create mode 100644 sdrbase/gui/scaleengine.cpp create mode 100644 sdrbase/gui/scopewindow.cpp create mode 100644 sdrbase/gui/scopewindow.ui create mode 100644 sdrbase/gui/valuedial.cpp create mode 100644 sdrbase/mainwindow.cpp create mode 100644 sdrbase/mainwindow.ui create mode 100644 sdrbase/plugin/pluginapi.cpp create mode 100644 sdrbase/plugin/plugingui.cpp create mode 100644 sdrbase/plugin/plugininterface.cpp create mode 100644 sdrbase/plugin/pluginmanager.cpp create mode 100644 sdrbase/resources/appicon.ico create mode 100644 sdrbase/resources/appicon.png create mode 100644 sdrbase/resources/grid.png create mode 100644 sdrbase/resources/histogram.png create mode 100644 sdrbase/resources/horizontal.png create mode 100644 sdrbase/resources/invertspectrum.png create mode 100644 sdrbase/resources/logo.png create mode 100644 sdrbase/resources/maxhold.png create mode 100644 sdrbase/resources/preset-delete.png create mode 100644 sdrbase/resources/preset-load.png create mode 100644 sdrbase/resources/preset-save.png create mode 100644 sdrbase/resources/res.qrc create mode 100644 sdrbase/resources/sdrangelove.rc create mode 100644 sdrbase/resources/vertical.png create mode 100644 sdrbase/resources/waterfall.png create mode 100644 sdrbase/settings/preferences.cpp create mode 100644 sdrbase/settings/preset.cpp create mode 100644 sdrbase/settings/settings.cpp create mode 100644 sdrbase/util/message.cpp create mode 100644 sdrbase/util/messagequeue.cpp create mode 100644 sdrbase/util/miniz.cpp create mode 100644 sdrbase/util/simpleserializer.cpp create mode 100644 sdrbase/util/spinlock.cpp diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..f859d569c --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +CMakeLists.txt.user* +build/* +LOCAL/* diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..ab899f272 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,294 @@ +cmake_minimum_required(VERSION 2.8.9) +list(APPEND CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/Modules) + +project(sdrangelove) + +set(CMAKE_BUILD_TYPE "Release") +#set(CMAKE_BUILD_TYPE "ReleaseWithDebugInfo") +#set(CMAKE_BUILD_TYPE "Debug") + +set(QT_USE_QTOPENGL TRUE) +set(CMAKE_AUTOMOC ON) + +#find_package(Qt4 REQUIRED) +find_package(Qt5Core 5.0 REQUIRED) +find_package(Qt5Widgets 5.0 REQUIRED) +find_package(Qt5Multimedia 5.0 REQUIRED) +#find_package(QT5OpenGL 5.0 REQUIRED) +find_package(OpenGL REQUIRED) +find_package(PkgConfig) + +find_package(FFTW3F) + +############################################################################## + +#include(${QT_USE_FILE}) +add_definitions(${QT_DEFINITIONS}) + +if(MSVC) + foreach(OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES}) + string(TOUPPER ${OUTPUTCONFIG} OUTPUTCONFIG) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_BINARY_DIR}/bin_${OUTPUTCONFIG}) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_BINARY_DIR}/bin_${OUTPUTCONFIG}) + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_BINARY_DIR}/bin_${OUTPUTCONFIG}) + endforeach(OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES) +endif() + +############################################################################## + +set(sdrbase_SOURCES + sdrbase/mainwindow.cpp + + sdrbase/audio/audiodeviceinfo.cpp + sdrbase/audio/audiofifo.cpp + sdrbase/audio/audiooutput.cpp + + sdrbase/dsp/channelizer.cpp + sdrbase/dsp/channelmarker.cpp + sdrbase/dsp/dspcommands.cpp + sdrbase/dsp/dspengine.cpp + sdrbase/dsp/fftengine.cpp + sdrbase/dsp/fftwindow.cpp + sdrbase/dsp/interpolator.cpp + sdrbase/dsp/inthalfbandfilter.cpp + sdrbase/dsp/lowpass.cpp + sdrbase/dsp/movingaverage.cpp + sdrbase/dsp/nco.cpp + sdrbase/dsp/pidcontroller.cpp + sdrbase/dsp/samplefifo.cpp + sdrbase/dsp/samplesink.cpp + sdrbase/dsp/scopevis.cpp + sdrbase/dsp/spectrumvis.cpp + sdrbase/dsp/threadedsamplesink.cpp + + sdrbase/gui/aboutdialog.cpp + sdrbase/gui/addpresetdialog.cpp + sdrbase/gui/basicchannelsettingswidget.cpp + sdrbase/gui/buttonswitch.cpp + sdrbase/gui/channelwindow.cpp + sdrbase/gui/glscope.cpp + sdrbase/gui/glspectrum.cpp + sdrbase/gui/glspectrumgui.cpp + sdrbase/gui/indicator.cpp + sdrbase/gui/pluginsdialog.cpp + sdrbase/gui/preferencesdialog.cpp + sdrbase/gui/presetitem.cpp + sdrbase/gui/rollupwidget.cpp + sdrbase/gui/scale.cpp + sdrbase/gui/scaleengine.cpp + sdrbase/gui/scopewindow.cpp + sdrbase/gui/valuedial.cpp + + sdrbase/dsp/samplesource/samplesource.cpp + + sdrbase/plugin/pluginapi.cpp + sdrbase/plugin/plugingui.cpp + sdrbase/plugin/plugininterface.cpp + sdrbase/plugin/pluginmanager.cpp + + sdrbase/settings/preferences.cpp + sdrbase/settings/preset.cpp + sdrbase/settings/settings.cpp + + sdrbase/util/message.cpp + sdrbase/util/messagequeue.cpp + sdrbase/util/miniz.cpp + sdrbase/util/simpleserializer.cpp + sdrbase/util/spinlock.cpp +) + +set(sdrbase_HEADERS + include-gpl/mainwindow.h + + include-gpl/audio/audiodeviceinfo.h + include-gpl/audio/audiofifo.h + include-gpl/audio/audiooutput.h + + include-gpl/dsp/channelizer.h + include/dsp/channelmarker.h + include-gpl/dsp/dspcommands.h + include-gpl/dsp/dspengine.h + include/dsp/dsptypes.h + include-gpl/dsp/fftengine.h + include-gpl/dsp/fftwengine.h + include-gpl/dsp/fftwindow.h + include-gpl/dsp/interpolator.h + include-gpl/dsp/inthalfbandfilter.h + include/dsp/kissfft.h + include-gpl/dsp/kissengine.h + include-gpl/dsp/lowpass.h + include-gpl/dsp/movingaverage.h + include-gpl/dsp/nco.h + sdrbase/dsp/pidcontroller.h + include/dsp/samplefifo.h + include/dsp/samplesink.h + include-gpl/dsp/scopevis.h + include-gpl/dsp/spectrumvis.h + include/dsp/threadedsamplesink.h + + include-gpl/gui/aboutdialog.h + include-gpl/gui/addpresetdialog.h + include/gui/basicchannelsettingswidget.h + include-gpl/gui/buttonswitch.h + include-gpl/gui/channelwindow.h + include-gpl/gui/glscope.h + include-gpl/gui/glspectrum.h + include-gpl/gui/glspectrumgui.h + include-gpl/gui/indicator.h + include-gpl/gui/physicalunit.h + include-gpl/gui/pluginsdialog.h + include-gpl/gui/preferencesdialog.h + include-gpl/gui/presetitem.h + include/gui/rollupwidget.h + include-gpl/gui/scale.h + include-gpl/gui/scaleengine.h + include-gpl/gui/scopewindow.h + include-gpl/gui/valuedial.h + + include/dsp/samplesource/samplesource.h + + include/plugin/pluginapi.h + include/plugin/plugingui.h + include/plugin/plugininterface.h + include-gpl/plugin/pluginmanager.h + + include-gpl/settings/preferences.h + include-gpl/settings/preset.h + include-gpl/settings/settings.h + + include/util/export.h + include/util/message.h + include/util/messagequeue.h + include/util/miniz.h + include/util/simpleserializer.h + include/util/spinlock.h +) + +set(sdrbase_SOURCES + ${sdrbase_SOURCES} + ${sdrbase_HEADERS} +) + +set(sdrbase_FORMS + sdrbase/mainwindow.ui + + sdrbase/gui/aboutdialog.ui + sdrbase/gui/addpresetdialog.ui + sdrbase/gui/basicchannelsettingswidget.ui + sdrbase/gui/glspectrumgui.ui + sdrbase/gui/pluginsdialog.ui + sdrbase/gui/preferencesdialog.ui + sdrbase/gui/scopewindow.ui +) + +set(sdrbase_RESOURCES + sdrbase/resources/res.qrc +) + +if(FFTW3F_FOUND) + set(sdrbase_SOURCES + ${sdrbase_SOURCES} + sdrbase/dsp/fftwengine.cpp + ) + set(sdrbase_HEADERS + ${sdrbase_HEADERS} + include-gpl/dsp/fftwengine.h + ) + add_definitions(-DUSE_FFTW) + include_directories(${FFTW3F_INCLUDE_DIRS}) +else(FFTW3F_FOUND) + set(sdrbase_SOURCES + ${sdrbase_SOURCES} + sdrbase/dsp/kissengine.cpp + include/dsp/kissfft.h + ) + set(sdrbase_HEADERS + ${sdrbase_HEADERS} + include-gpl/dsp/kissengine.h + ) + add_definitions(-DUSE_KISSFFT) +endif(FFTW3F_FOUND) + +#include(${QT_USE_FILE}) +add_definitions(${QT_DEFINITIONS}) + +#qt5_wrap_cpp(sdrbase_HEADERS_MOC ${sdrbase_HEADERS}) +qt5_wrap_ui(sdrbase_FORMS_HEADERS ${sdrbase_FORMS}) +qt5_add_resources(sdrbase_RESOURCES_RCC ${sdrbase_RESOURCES}) + +if(WIN32) + SET(sdrbase_SOURCES ${sdrbase_SOURCES} sdrbase/resources/sdrangelove.rc) +endif(WIN32) + +add_library(sdrbase SHARED + ${sdrbase_SOURCES} + ${sdrbase_HEADERS_MOC} + ${sdrbase_FORMS_HEADERS} + ${sdrbase_RESOURCES_RCC} +) + +target_link_libraries(sdrbase + ${QT_LIBRARIES} + ${OPENGL_LIBRARIES} + ${LIBUSB_LIBRARIES} +) + +if(FFTW3F_FOUND) + target_link_libraries(sdrbase ${FFTW3F_LIBRARIES}) +endif(FFTW3F_FOUND) + +set_target_properties(sdrbase PROPERTIES DEFINE_SYMBOL "sdrangelove_EXPORTS") + +qt5_use_modules(sdrbase Core Widgets OpenGL Multimedia) + +include_directories( + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include-gpl + ${OPENGL_INCLUDE_DIR} +) + +if(MSVC) + set( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /arch:SSE2" ) + set( CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /Oi /GL /Ot /Ox /arch:SSE2" ) + set( CMAKE_EXE_LINKER_FLAGS_RELEASE "${CMAKE_EXE_LINKER_FLAGS_RELEASE} /LTCG" ) + add_definitions (/D "_CRT_SECURE_NO_WARNINGS") +else() +set( CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -msse2" ) +set( CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -msse2" ) +endif() + +############################################################################## + +set(sdrangelove_SOURCES + main.cpp +) + +if(WIN32) + SET(sdrangelove_SOURCES ${sdrangelove_SOURCES} sdrbase/resources/sdrangelove.rc) +endif(WIN32) + +add_executable(sdrangelove + ${sdrangelove_SOURCES} +) + +target_link_libraries(sdrangelove + sdrbase + ${QT_LIBRARIES} + ${OPENGL_LIBRARIES} +) + +if(WIN32) + set_target_properties(sdrangelove PROPERTIES LINK_FLAGS_DEBUG "/SUBSYSTEM:CONSOLE") + set_target_properties(sdrangelove PROPERTIES COMPILE_DEFINITIONS_DEBUG "_CONSOLE") + set_target_properties(sdrangelove PROPERTIES LINK_FLAGS_RELWITHDEBINFO "/SUBSYSTEM:CONSOLE") + set_target_properties(sdrangelove PROPERTIES COMPILE_DEFINITIONS_RELWITHDEBINFO "_CONSOLE") + set_target_properties(sdrangelove PROPERTIES LINK_FLAGS_RELEASE "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") + set_target_properties(sdrangelove PROPERTIES LINK_FLAGS_MINSIZEREL "/SUBSYSTEM:windows /ENTRY:mainCRTStartup") +endif(WIN32) + +qt5_use_modules(sdrangelove Widgets Multimedia) + +############################################################################## + +add_subdirectory(plugins) diff --git a/cmake/Modules/FindFFTW3F.cmake b/cmake/Modules/FindFFTW3F.cmake new file mode 100644 index 000000000..2a99ee31b --- /dev/null +++ b/cmake/Modules/FindFFTW3F.cmake @@ -0,0 +1,40 @@ +# http://tim.klingt.org/code/projects/supernova/repository/revisions/d336dd6f400e381bcfd720e96139656de0c53b6a/entry/cmake_modules/FindFFTW3f.cmake +# Modified to use pkg config and use standard var names + +# Find single-precision (float) version of FFTW3 + +INCLUDE(FindPkgConfig) +PKG_CHECK_MODULES(PC_FFTW3F "fftw3f >= 3.0") + +FIND_PATH( + FFTW3F_INCLUDE_DIRS + NAMES fftw3.h + HINTS $ENV{FFTW3_DIR}/include + ${PC_FFTW3F_INCLUDE_DIR} + PATHS /usr/local/include + /usr/include +) + +FIND_LIBRARY( + FFTW3F_LIBRARIES + NAMES fftw3f libfftw3f + HINTS $ENV{FFTW3_DIR}/lib + ${PC_FFTW3F_LIBDIR} + PATHS /usr/local/lib + /usr/lib + /usr/lib64 +) + +FIND_LIBRARY( + FFTW3F_THREADS_LIBRARIES + NAMES fftw3f_threads libfftw3f_threads + HINTS $ENV{FFTW3_DIR}/lib + ${PC_FFTW3F_LIBDIR} + PATHS /usr/local/lib + /usr/lib + /usr/lib64 +) + +INCLUDE(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(FFTW3F DEFAULT_MSG FFTW3F_LIBRARIES FFTW3F_INCLUDE_DIRS) +MARK_AS_ADVANCED(FFTW3F_LIBRARIES FFTW3F_INCLUDE_DIRS FFTW3F_THREADS_LIBRARIES) diff --git a/cmake/Modules/FindGruel.cmake b/cmake/Modules/FindGruel.cmake new file mode 100644 index 000000000..1d044eebd --- /dev/null +++ b/cmake/Modules/FindGruel.cmake @@ -0,0 +1,29 @@ +INCLUDE(FindPkgConfig) +PKG_CHECK_MODULES(PC_GRUEL gruel) + +FIND_PATH( + GRUEL_INCLUDE_DIRS + NAMES gruel/attributes.h + HINTS $ENV{GRUEL_DIR}/include + ${PC_GRUEL_INCLUDEDIR} + ${CMAKE_INSTALL_PREFIX}/include + PATHS /usr/local/include + /usr/include +) + +FIND_LIBRARY( + GRUEL_LIBRARIES + NAMES gruel + HINTS $ENV{GRUEL_DIR}/lib + ${PC_GRUEL_LIBDIR} + ${CMAKE_INSTALL_PREFIX}/lib + ${CMAKE_INSTALL_PREFIX}/lib64 + PATHS /usr/local/lib + /usr/local/lib64 + /usr/lib + /usr/lib64 +) + +INCLUDE(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(GRUEL DEFAULT_MSG GRUEL_LIBRARIES GRUEL_INCLUDE_DIRS) +MARK_AS_ADVANCED(GRUEL_LIBRARIES GRUEL_INCLUDE_DIRS) diff --git a/cmake/Modules/FindLibOsmoSDR.cmake b/cmake/Modules/FindLibOsmoSDR.cmake new file mode 100644 index 000000000..ba0c77df7 --- /dev/null +++ b/cmake/Modules/FindLibOsmoSDR.cmake @@ -0,0 +1,28 @@ +if(NOT LIBOSMOSDR_FOUND) + + pkg_check_modules (LIBOSMOSDR_PKG libosmosdr) + find_path(LIBOSMOSDR_INCLUDE_DIR NAMES osmosdr.h + PATHS + ${LIBOSMOSDR_PKG_INCLUDE_DIRS} + /usr/include + /usr/local/include + ) + + find_library(LIBOSMOSDR_LIBRARIES NAMES osmosdr + PATHS + ${LIBOSMOSDR_PKG_LIBRARY_DIRS} + /usr/lib + /usr/local/lib + ) + + if(LIBOSMOSDR_INCLUDE_DIR AND LIBOSMOSDR_LIBRARIES) + set(LIBOSMOSDR_FOUND TRUE CACHE INTERNAL "libosmosdr found") + message(STATUS "Found libosmosdr: ${LIBOSMOSDR_INCLUDE_DIR}, ${LIBOSMOSDR_LIBRARIES}") + else(LIBOSMOSDR_INCLUDE_DIR AND LIBOSMOSDR_LIBRARIES) + set(LIBOSMOSDR_FOUND FALSE CACHE INTERNAL "libosmosdr found") + message(STATUS "libosmosdr not found.") + endif(LIBOSMOSDR_INCLUDE_DIR AND LIBOSMOSDR_LIBRARIES) + + mark_as_advanced(LIBOSMOSDR_INCLUDE_DIR LIBOSMOSDR_LIBRARIES) + +endif(NOT LIBOSMOSDR_FOUND) diff --git a/cmake/Modules/FindLibRTLSDR.cmake b/cmake/Modules/FindLibRTLSDR.cmake new file mode 100644 index 000000000..25a1d05dc --- /dev/null +++ b/cmake/Modules/FindLibRTLSDR.cmake @@ -0,0 +1,28 @@ +if(NOT LIBRTLSDR_FOUND) + + pkg_check_modules (LIBRTLSDR_PKG librtlsdr) + find_path(LIBRTLSDR_INCLUDE_DIR NAMES rtl-sdr.h + PATHS + ${LIBRTLSDR_PKG_INCLUDE_DIRS} + /usr/include + /usr/local/include + ) + + find_library(LIBRTLSDR_LIBRARIES NAMES rtlsdr + PATHS + ${LIBRTLSDR_PKG_LIBRARY_DIRS} + /usr/lib + /usr/local/lib + ) + + if(LIBRTLSDR_INCLUDE_DIR AND LIBRTLSDR_LIBRARIES) + set(LIBRTLSDR_FOUND TRUE CACHE INTERNAL "librtlsdr found") + message(STATUS "Found librtlsdr: ${LIBRTLSDR_INCLUDE_DIR}, ${LIBRTLSDR_LIBRARIES}") + else(LIBRTLSDR_INCLUDE_DIR AND LIBRTLSDR_LIBRARIES) + set(LIBRTLSDR_FOUND FALSE CACHE INTERNAL "librtlsdr found") + message(STATUS "librtlsdr not found.") + endif(LIBRTLSDR_INCLUDE_DIR AND LIBRTLSDR_LIBRARIES) + + mark_as_advanced(LIBRTLSDR_INCLUDE_DIR LIBRTLSDR_LIBRARIES) + +endif(NOT LIBRTLSDR_FOUND) diff --git a/cmake/Modules/FindLibUSB.cmake b/cmake/Modules/FindLibUSB.cmake new file mode 100644 index 000000000..97f3db675 --- /dev/null +++ b/cmake/Modules/FindLibUSB.cmake @@ -0,0 +1,28 @@ +if(NOT LIBUSB_FOUND) + pkg_check_modules (LIBUSB_PKG libusb-1.0) + find_path(LIBUSB_INCLUDE_DIR NAMES libusb.h + PATHS + ${LIBUSB_PKG_INCLUDE_DIRS} + /usr/include/libusb-1.0 + /usr/include + /usr/local/include + ) + + find_library(LIBUSB_LIBRARIES NAMES usb-1.0 + PATHS + ${LIBUSB_PKG_LIBRARY_DIRS} + /usr/lib + /usr/local/lib + ) + +if(LIBUSB_INCLUDE_DIR AND LIBUSB_LIBRARIES) + set(LIBUSB_FOUND TRUE CACHE INTERNAL "libusb-1.0 found") + message(STATUS "Found libusb-1.0: ${LIBUSB_INCLUDE_DIR}, ${LIBUSB_LIBRARIES}") +else(LIBUSB_INCLUDE_DIR AND LIBUSB_LIBRARIES) + set(LIBUSB_FOUND FALSE CACHE INTERNAL "libusb-1.0 found") + message(STATUS "libusb-1.0 not found.") +endif(LIBUSB_INCLUDE_DIR AND LIBUSB_LIBRARIES) + +mark_as_advanced(LIBUSB_INCLUDE_DIR LIBUSB_LIBRARIES) + +endif(NOT LIBUSB_FOUND) diff --git a/include-gpl/audio/audiodeviceinfo.h b/include-gpl/audio/audiodeviceinfo.h new file mode 100644 index 000000000..ca285f549 --- /dev/null +++ b/include-gpl/audio/audiodeviceinfo.h @@ -0,0 +1,49 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_AUDIODEVICEINFO_H +#define INCLUDE_AUDIODEVICEINFO_H + +#include +#include "util/export.h" + +class SDRANGELOVE_API AudioDeviceInfo { +public: + struct Device { + QString name; + QString api; + int id; + + Device(const QString& _name, const QString& _api, int _id) : + name(_name), + api(_api), + id(_id) + { } + }; + typedef QList Devices; + + AudioDeviceInfo(); + + int match(const QString& api, const QString device) const; + + const Devices& getDevices() const { return m_devices; } + +private: + Devices m_devices; +}; + +#endif // INCLUDE_AUDIODEVICEINFO_H diff --git a/include-gpl/audio/audiofifo.h b/include-gpl/audio/audiofifo.h new file mode 100644 index 000000000..98f35b886 --- /dev/null +++ b/include-gpl/audio/audiofifo.h @@ -0,0 +1,65 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_AUDIOFIFO_H +#define INCLUDE_AUDIOFIFO_H + +#include +#include +#include "util/export.h" + +class SDRANGELOVE_API AudioFifo { +public: + AudioFifo(); + AudioFifo(uint sampleSize, uint numSamples); + ~AudioFifo(); + + bool setSize(uint sampleSize, uint numSamples); + + uint write(const quint8* data, uint numSamples, int timeout = INT_MAX); + uint read(quint8* data, uint numSamples, int timeout = INT_MAX); + + uint drain(uint numSamples); + void clear(); + + inline uint flush() { return drain(m_fill); } + inline uint fill() const { return m_fill; } + inline bool isEmpty() const { return m_fill == 0; } + inline bool isFull() const { return m_fill == m_size; } + inline uint size() const { return m_size; } + +private: + QMutex m_mutex; + + qint8* m_fifo; + + uint m_sampleSize; + + uint m_size; + uint m_fill; + uint m_head; + uint m_tail; + + QMutex m_writeWaitLock; + QMutex m_readWaitLock; + QWaitCondition m_writeWaitCondition; + QWaitCondition m_readWaitCondition; + + bool create(uint sampleSize, uint numSamples); +}; + +#endif // INCLUDE_AUDIOFIFO_H diff --git a/include-gpl/audio/audiooutput.h b/include-gpl/audio/audiooutput.h new file mode 100644 index 000000000..10816ac51 --- /dev/null +++ b/include-gpl/audio/audiooutput.h @@ -0,0 +1,57 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_AUDIOOUTPUT_H +#define INCLUDE_AUDIOOUTPUT_H + +#include +#include +#include +#include +#include "util/export.h" + +class QAudioOutput; +class AudioFifo; +class AudioOutputPipe; + +class SDRANGELOVE_API AudioOutput : QIODevice { +public: + AudioOutput(); + ~AudioOutput(); + + bool start(int device, int rate); + void stop(); + + void addFifo(AudioFifo* audioFifo); + void removeFifo(AudioFifo* audioFifo); + +private: + QMutex m_mutex; + QAudioOutput* m_audioOutput; + + typedef std::list AudioFifos; + AudioFifos m_audioFifos; + std::vector m_mixBuffer; + + bool open(OpenMode mode); + qint64 readData(char* data, qint64 maxLen); + qint64 writeData(const char* data, qint64 len); + + friend class AudioOutputPipe; +}; + +#endif // INCLUDE_AUDIOOUTPUT_H diff --git a/include-gpl/dsp/channelizer.h b/include-gpl/dsp/channelizer.h new file mode 100644 index 000000000..cf3ede3ac --- /dev/null +++ b/include-gpl/dsp/channelizer.h @@ -0,0 +1,109 @@ +#ifndef INCLUDE_CHANNELIZER_H +#define INCLUDE_CHANNELIZER_H + +#include +#include "dsp/samplesink.h" +#include "util/export.h" + +class MessageQueue; +class IntHalfbandFilter; + +class SDRANGELOVE_API Channelizer : public SampleSink { +public: + Channelizer(SampleSink* sampleSink); + ~Channelizer(); + + void configure(MessageQueue* messageQueue, int sampleRate, int centerFrequency); + + void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst); + void start(); + void stop(); + bool handleMessage(Message* cmd); + +protected: + struct FilterStage { + enum Mode { + ModeCenter, + ModeLowerHalf, + ModeUpperHalf + }; + + typedef bool (IntHalfbandFilter::*WorkFunction)(Sample* s); + IntHalfbandFilter* m_filter; + WorkFunction m_workFunction; + + FilterStage(Mode mode); + ~FilterStage(); + + bool work(Sample* sample) + { + return (m_filter->*m_workFunction)(sample); + } + }; + typedef std::list FilterStages; + FilterStages m_filterStages; + SampleSink* m_sampleSink; + int m_inputSampleRate; + int m_requestedOutputSampleRate; + int m_requestedCenterFrequency; + int m_currentOutputSampleRate; + int m_currentCenterFrequency; + SampleVector m_sampleBuffer; + + void applyConfiguration(); + bool signalContainsChannel(Real sigStart, Real sigEnd, Real chanStart, Real chanEnd) const; + Real createFilterChain(Real sigStart, Real sigEnd, Real chanStart, Real chanEnd); + void freeFilterChain(); +}; + +#endif // INCLUDE_CHANNELIZER_H + +#if 0 + +#ifndef INCLUDE_CHANNELIZER_H +#define INCLUDE_CHANNELIZER_H + +#include "samplesink.h" +#include "spectrum.h" +#include "nco.h" +#include "interpolator.h" +#include "pidcontroller.h" +#include "hardware/audiofifo.h" + +class AudioOutput; + +class Channelizer : public SampleSink { +public: + Channelizer(); + ~Channelizer(); + +#if 0 + void setGLSpectrum(GLSpectrum* glSpectrum); +#endif + + size_t workUnitSize(); + size_t work(SampleVector::const_iterator begin, SampleVector::const_iterator end); + +private: +#if 0 + NCO m_nco; + Interpolator m_interpolator; + Real m_distance; + Interpolator m_interpolator2; + Real m_distance2; + + SampleVector m_buffer; + size_t m_bufferFill; + Complex m_lastSample; + + AudioOutput* m_audioOutput; + AudioFifo m_audioFifo; + Real m_resampler; + PIDController m_resamplerCtrl; + + Spectrum m_spectrum; +#endif +}; + +#endif // INCLUDE_CHANNELIZER_H +#endif diff --git a/include-gpl/dsp/dspcommands.h b/include-gpl/dsp/dspcommands.h new file mode 100644 index 000000000..58663fe3d --- /dev/null +++ b/include-gpl/dsp/dspcommands.h @@ -0,0 +1,255 @@ +#ifndef INCLUDE_DSPCOMMANDS_H +#define INCLUDE_DSPCOMMANDS_H + +#include +#include "util/message.h" +#include "fftwindow.h" +#include "util/export.h" + +class SampleSource; +class SampleSink; +class AudioFifo; + +class SDRANGELOVE_API DSPPing : public Message { + MESSAGE_CLASS_DECLARATION +}; + +class SDRANGELOVE_API DSPExit : public Message { + MESSAGE_CLASS_DECLARATION +}; + +class SDRANGELOVE_API DSPAcquisitionStart : public Message { + MESSAGE_CLASS_DECLARATION +}; + +class SDRANGELOVE_API DSPAcquisitionStop : public Message { + MESSAGE_CLASS_DECLARATION +}; + +class SDRANGELOVE_API DSPGetDeviceDescription : public Message { + MESSAGE_CLASS_DECLARATION + +public: + void setDeviceDescription(const QString& text) { m_deviceDescription = text; } + const QString& getDeviceDescription() const { return m_deviceDescription; } + +private: + QString m_deviceDescription; +}; + +class SDRANGELOVE_API DSPGetErrorMessage : public Message { + MESSAGE_CLASS_DECLARATION + +public: + void setErrorMessage(const QString& text) { m_errorMessage = text; } + const QString& getErrorMessage() const { return m_errorMessage; } + +private: + QString m_errorMessage; +}; + +class SDRANGELOVE_API DSPSetSource : public Message { + MESSAGE_CLASS_DECLARATION + +public: + DSPSetSource(SampleSource* sampleSource) : Message(), m_sampleSource(sampleSource) { } + + SampleSource* getSampleSource() const { return m_sampleSource; } + +private: + SampleSource* m_sampleSource; +}; + +class SDRANGELOVE_API DSPAddSink : public Message { + MESSAGE_CLASS_DECLARATION + +public: + DSPAddSink(SampleSink* sampleSink) : Message(), m_sampleSink(sampleSink) { } + + SampleSink* getSampleSink() const { return m_sampleSink; } + +private: + SampleSink* m_sampleSink; +}; + +class SDRANGELOVE_API DSPRemoveSink : public Message { + MESSAGE_CLASS_DECLARATION + +public: + DSPRemoveSink(SampleSink* sampleSink) : Message(), m_sampleSink(sampleSink) { } + + SampleSink* getSampleSink() const { return m_sampleSink; } + +private: + SampleSink* m_sampleSink; +}; + +class SDRANGELOVE_API DSPAddAudioSource : public Message { + MESSAGE_CLASS_DECLARATION + +public: + DSPAddAudioSource(AudioFifo* audioFifo) : Message(), m_audioFifo(audioFifo) { } + + AudioFifo* getAudioFifo() const { return m_audioFifo; } + +private: + AudioFifo* m_audioFifo; +}; + +class SDRANGELOVE_API DSPRemoveAudioSource : public Message { + MESSAGE_CLASS_DECLARATION + +public: + DSPRemoveAudioSource(AudioFifo* audioFifo) : Message(), m_audioFifo(audioFifo) { } + + AudioFifo* getAudioFifo() const { return m_audioFifo; } + +private: + AudioFifo* m_audioFifo; +}; + +class SDRANGELOVE_API DSPConfigureSpectrumVis : public Message { + MESSAGE_CLASS_DECLARATION + +public: + int getFFTSize() const { return m_fftSize; } + int getOverlapPercent() const { return m_overlapPercent; } + FFTWindow::Function getWindow() const { return m_window; } + + static DSPConfigureSpectrumVis* create(int fftSize, int overlapPercent, FFTWindow::Function window) + { + return new DSPConfigureSpectrumVis(fftSize, overlapPercent, window); + } + +private: + int m_fftSize; + int m_overlapPercent; + FFTWindow::Function m_window; + + DSPConfigureSpectrumVis(int fftSize, int overlapPercent, FFTWindow::Function window) : + Message(), + m_fftSize(fftSize), + m_overlapPercent(overlapPercent), + m_window(window) + { } +}; + +class SDRANGELOVE_API DSPConfigureCorrection : public Message { + MESSAGE_CLASS_DECLARATION + +public: + bool getDCOffsetCorrection() const { return m_dcOffsetCorrection; } + bool getIQImbalanceCorrection() const { return m_iqImbalanceCorrection; } + + static DSPConfigureCorrection* create(bool dcOffsetCorrection, bool iqImbalanceCorrection) + { + return new DSPConfigureCorrection(dcOffsetCorrection, iqImbalanceCorrection); + } + +private: + bool m_dcOffsetCorrection; + bool m_iqImbalanceCorrection; + + DSPConfigureCorrection(bool dcOffsetCorrection, bool iqImbalanceCorrection) : + Message(), + m_dcOffsetCorrection(dcOffsetCorrection), + m_iqImbalanceCorrection(iqImbalanceCorrection) + { } +}; + +class SDRANGELOVE_API DSPEngineReport : public Message { + MESSAGE_CLASS_DECLARATION + +public: + int getSampleRate() const { return m_sampleRate; } + quint64 getCenterFrequency() const { return m_centerFrequency; } + + static DSPEngineReport* create(int sampleRate, quint64 centerFrequency) + { + return new DSPEngineReport(sampleRate, centerFrequency); + } + +private: + int m_sampleRate; + quint64 m_centerFrequency; + + DSPEngineReport(int sampleRate, quint64 centerFrequency) : + Message(), + m_sampleRate(sampleRate), + m_centerFrequency(centerFrequency) + { } +}; + +class SDRANGELOVE_API DSPConfigureScopeVis : public Message { + MESSAGE_CLASS_DECLARATION + +public: + int getTriggerChannel() const { return m_triggerChannel; } + Real getTriggerLevelHigh() const { return m_triggerLevelHigh; } + Real getTriggerLevelLow() const { return m_triggerLevelLow; } + + static DSPConfigureScopeVis* create(int triggerChannel, Real triggerLevelHigh, Real triggerLevelLow) + { + return new DSPConfigureScopeVis(triggerChannel, triggerLevelHigh, triggerLevelLow); + } + +private: + int m_triggerChannel; + Real m_triggerLevelHigh; + Real m_triggerLevelLow; + + DSPConfigureScopeVis(int triggerChannel, Real triggerLevelHigh, Real triggerLevelLow) : + Message(), + m_triggerChannel(triggerChannel), + m_triggerLevelHigh(triggerLevelHigh), + m_triggerLevelLow(triggerLevelLow) + { } +}; + +class SDRANGELOVE_API DSPSignalNotification : public Message { + MESSAGE_CLASS_DECLARATION + +public: + int getSampleRate() const { return m_sampleRate; } + qint64 getFrequencyOffset() const { return m_frequencyOffset; } + + static DSPSignalNotification* create(int sampleRate, quint64 frequencyOffset) + { + return new DSPSignalNotification(sampleRate, frequencyOffset); + } + +private: + int m_sampleRate; + qint64 m_frequencyOffset; + + DSPSignalNotification(int samplerate, qint64 frequencyOffset) : + Message(), + m_sampleRate(samplerate), + m_frequencyOffset(frequencyOffset) + { } +}; + +class SDRANGELOVE_API DSPConfigureChannelizer : public Message { + MESSAGE_CLASS_DECLARATION + +public: + int getSampleRate() const { return m_sampleRate; } + int getCenterFrequency() const { return m_centerFrequency; } + + static DSPConfigureChannelizer* create(int sampleRate, int centerFrequency) + { + return new DSPConfigureChannelizer(sampleRate, centerFrequency); + } + +private: + int m_sampleRate; + int m_centerFrequency; + + DSPConfigureChannelizer(int sampleRate, int centerFrequency) : + Message(), + m_sampleRate(sampleRate), + m_centerFrequency(centerFrequency) + { } +}; + +#endif // INCLUDE_DSPCOMMANDS_H diff --git a/include-gpl/dsp/dspengine.h b/include-gpl/dsp/dspengine.h new file mode 100644 index 000000000..28d2dae45 --- /dev/null +++ b/include-gpl/dsp/dspengine.h @@ -0,0 +1,119 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DSPENGINE_H +#define INCLUDE_DSPENGINE_H + +#include +#include +#include +#include +#include "dsp/dsptypes.h" +#include "dsp/fftwindow.h" +#include "dsp/samplefifo.h" +#include "audio/audiooutput.h" +#include "util/messagequeue.h" +#include "util/export.h" + +class SampleSource; +class SampleSink; +class AudioFifo; + +class SDRANGELOVE_API DSPEngine : public QThread { + Q_OBJECT + +public: + enum State { + StNotStarted, + StIdle, + StRunning, + StError + }; + + DSPEngine(MessageQueue* reportQueue, QObject* parent = NULL); + ~DSPEngine(); + + MessageQueue* getMessageQueue() { return &m_messageQueue; } + + void start(); + void stop(); + + bool startAcquisition(); + void stopAcquistion(); + + void setSource(SampleSource* source); + + void addSink(SampleSink* sink); + void removeSink(SampleSink* sink); + + void addAudioSource(AudioFifo* audioFifo); + void removeAudioSource(AudioFifo* audioFifo); + + void configureCorrections(bool dcOffsetCorrection, bool iqImbalanceCorrection); + + State state() const { return m_state; } + + QString errorMessage(); + QString deviceDescription(); + +private: + MessageQueue m_messageQueue; + MessageQueue* m_reportQueue; + + State m_state; + + QString m_errorMessage; + QString m_deviceDescription; + + SampleSource* m_sampleSource; + + typedef std::list SampleSinks; + SampleSinks m_sampleSinks; + + AudioOutput m_audioOutput; + + uint m_sampleRate; + quint64 m_centerFrequency; + + bool m_dcOffsetCorrection; + bool m_iqImbalanceCorrection; + qint32 m_iOffset; + qint32 m_qOffset; + qint32 m_iRange; + qint32 m_qRange; + qint32 m_imbalance; + + void run(); + + void dcOffset(SampleVector::iterator begin, SampleVector::iterator end); + void imbalance(SampleVector::iterator begin, SampleVector::iterator end); + void work(); + + State gotoIdle(); + State gotoRunning(); + State gotoError(const QString& errorMsg); + + void handleSetSource(SampleSource* source); + void generateReport(); + bool distributeMessage(Message* message); + +private slots: + void handleData(); + void handleMessages(); +}; + +#endif // INCLUDE_DSPENGINE_H diff --git a/include-gpl/dsp/fftengine.h b/include-gpl/dsp/fftengine.h new file mode 100644 index 000000000..bf8f4243d --- /dev/null +++ b/include-gpl/dsp/fftengine.h @@ -0,0 +1,20 @@ +#ifndef INCLUDE_FFTENGINE_H +#define INCLUDE_FFTENGINE_H + +#include "dsp/dsptypes.h" +#include "util/export.h" + +class SDRANGELOVE_API FFTEngine { +public: + virtual ~FFTEngine(); + + virtual void configure(int n, bool inverse) = 0; + virtual void transform() = 0; + + virtual Complex* in() = 0; + virtual Complex* out() = 0; + + static FFTEngine* create(); +}; + +#endif // INCLUDE_FFTENGINE_H diff --git a/include-gpl/dsp/fftwengine.h b/include-gpl/dsp/fftwengine.h new file mode 100644 index 000000000..9224ba4ad --- /dev/null +++ b/include-gpl/dsp/fftwengine.h @@ -0,0 +1,37 @@ +#ifndef INCLUDE_FFTWENGINE_H +#define INCLUDE_FFTWENGINE_H + +#include +#include +#include +#include "dsp/fftengine.h" + +class FFTWEngine : public FFTEngine { +public: + FFTWEngine(); + ~FFTWEngine(); + + void configure(int n, bool inverse); + void transform(); + + Complex* in(); + Complex* out(); + +protected: + static QMutex m_globalPlanMutex; + + struct Plan { + int n; + bool inverse; + fftwf_plan plan; + fftwf_complex* in; + fftwf_complex* out; + }; + typedef std::list Plans; + Plans m_plans; + Plan* m_currentPlan; + + void freeAll(); +}; + +#endif // INCLUDE_FFTWENGINE_H diff --git a/include-gpl/dsp/fftwindow.h b/include-gpl/dsp/fftwindow.h new file mode 100644 index 000000000..095dc291d --- /dev/null +++ b/include-gpl/dsp/fftwindow.h @@ -0,0 +1,82 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_FFTWINDOW_H +#define INCLUDE_FFTWINDOW_H + +#include +#define _USE_MATH_DEFINES +#include +#include "dsp/dsptypes.h" +#include "util/export.h" + +class SDRANGELOVE_API FFTWindow { +public: + enum Function { + Bartlett, + BlackmanHarris, + Flattop, + Hamming, + Hanning, + Rectangle + }; + + void create(Function function, int n); + void apply(const std::vector& in, std::vector* out); + void apply(const std::vector& in, std::vector* out); + void apply(const Complex* in, Complex* out); + +private: + std::vector m_window; + + static inline Real flatTop(Real n, Real i) + { + // correction ? + return 1.0 - 1.93 * cos((2.0 * M_PI * i) / n) + 1.29 * cos((4.0 * M_PI * i) / n) - 0.388 * cos((6.0 * M_PI * i) / n) + 0.03222 * cos((8.0 * M_PI * i) / n); + } + + static inline Real bartlett(Real n, Real i) + { + // amplitude correction = 2.0 + return (2.0 / (n - 1.0)) * ( (n - 1.0) / 2.0 - fabs(i - (n - 1.0) / 2.0)) * 2.0; + } + + static inline Real blackmanHarris(Real n, Real i) + { + // amplitude correction = 2.79 + return (0.35875 - 0.48829 * cos((2.0 * M_PI * i) / n) + 0.14128 * cos((4.0 * M_PI * i) / n) - 0.01168 * cos((6.0 * M_PI * i) / n)) * 2.79; + } + + static inline Real hamming(Real n, Real i) + { + // amplitude correction = 1.855, energy correction = 1.586 + return (0.54 - 0.46 * cos((2.0 * M_PI * i) / n)) * 1.855; + } + + static inline Real hanning(Real n, Real i) + { + // amplitude correction = 2.0, energy correction = 1.633 + return (0.5 - 0.5 * cos((2.0 * M_PI * i) / n)) * 2.0; + } + + static inline Real rectangle(Real, Real) + { + return 1.0; + } +}; + +#endif // INCLUDE_FFTWINDOWS_H diff --git a/include-gpl/dsp/interpolator.h b/include-gpl/dsp/interpolator.h new file mode 100644 index 000000000..ae91062e2 --- /dev/null +++ b/include-gpl/dsp/interpolator.h @@ -0,0 +1,130 @@ +#ifndef INCLUDE_INTERPOLATOR_H +#define INCLUDE_INTERPOLATOR_H + +#include +#include "dsp/dsptypes.h" +#include "util/export.h" +#include +#ifndef WIN32 +#include +#endif + +class SDRANGELOVE_API Interpolator { +public: + Interpolator(); + ~Interpolator(); + + void create(int phaseSteps, double sampleRate, double cutoff); + void free(); + + bool interpolate(Real* distance, const Complex& next, bool* consumed, Complex* result) + { + while(*distance >= 1.0) { + if(!(*consumed)) { + advanceFilter(next); + *distance -= 1.0; + *consumed = true; + } else { + return false; + } + } + doInterpolate((int)floor(*distance * (Real)m_phaseSteps), result); + return true; + } + + +private: + float* m_taps; + float* m_alignedTaps; + float* m_taps2; + float* m_alignedTaps2; + std::vector m_samples; + int m_ptr; + int m_phaseSteps; + int m_nTaps; + + void createTaps(int nTaps, double sampleRate, double cutoff, std::vector* taps); + + void advanceFilter(const Complex& next) + { + m_ptr--; + if(m_ptr < 0) + m_ptr = m_nTaps - 1; + m_samples[m_ptr] = next; + } + + void doInterpolate(int phase, Complex* result) + { +#if 1 + // beware of the ringbuffer + if(m_ptr == 0) { + // only one straight block + const float* src = (const float*)&m_samples[0]; + const __m128* filter = (const __m128*)&m_alignedTaps[phase * m_nTaps * 2]; + __m128 sum = _mm_setzero_ps(); + int todo = m_nTaps / 2; + + for(int i = 0; i < todo; i++) { + sum = _mm_add_ps(sum, _mm_mul_ps(_mm_loadu_ps(src), *filter)); + src += 4; + filter += 1; + } + + // add upper half to lower half and store + _mm_storel_pi((__m64*)result, _mm_add_ps(sum, _mm_shuffle_ps(sum, _mm_setzero_ps(), _MM_SHUFFLE(1, 0, 3, 2)))); + } else { + // two blocks + const float* src = (const float*)&m_samples[m_ptr]; + const __m128* filter = (const __m128*)&m_alignedTaps[phase * m_nTaps * 2]; + __m128 sum = _mm_setzero_ps(); + + // first block + int block = m_nTaps - m_ptr; + int todo = block / 2; + if(block & 1) + todo++; + for(int i = 0; i < todo; i++) { + sum = _mm_add_ps(sum, _mm_mul_ps(_mm_loadu_ps(src), *filter)); + src += 4; + filter += 1; + } + if(block & 1) { + // one sample beyond the end -> switch coefficient table + filter = (const __m128*)&m_alignedTaps2[phase * m_nTaps * 2 + todo * 4 - 4]; + } + // second block + src = (const float*)&m_samples[0]; + block = m_ptr; + todo = block / 2; + for(int i = 0; i < todo; i++) { + sum = _mm_add_ps(sum, _mm_mul_ps(_mm_loadu_ps(src), *filter)); + src += 4; + filter += 1; + } + if(block & 1) { + // one sample remaining + sum = _mm_add_ps(sum, _mm_mul_ps(_mm_loadl_pi(_mm_setzero_ps(), (const __m64*)src), filter[0])); + } + + // add upper half to lower half and store + _mm_storel_pi((__m64*)result, _mm_add_ps(sum, _mm_shuffle_ps(sum, _mm_setzero_ps(), _MM_SHUFFLE(1, 0, 3, 2)))); + } +#else + int sample = m_ptr; + const Real* coeff = &m_alignedTaps[phase * m_nTaps * 2]; + Real rAcc = 0; + Real iAcc = 0; + + for(int i = 0; i < m_nTaps; i++) { + rAcc += *coeff * m_samples[sample].real(); + iAcc += *coeff * m_samples[sample].imag(); + sample = (sample + 1) % m_nTaps; + coeff += 2; + } + *result = Complex(rAcc, iAcc); +#endif + + } +}; + +#endif // INCLUDE_INTERPOLATOR_H diff --git a/include-gpl/dsp/inthalfbandfilter.h b/include-gpl/dsp/inthalfbandfilter.h new file mode 100644 index 000000000..ccc1bfa45 --- /dev/null +++ b/include-gpl/dsp/inthalfbandfilter.h @@ -0,0 +1,314 @@ +#ifndef INCLUDE_INTHALFBANDFILTER_H +#define INCLUDE_INTHALFBANDFILTER_H + +#include +#include "dsp/dsptypes.h" +#include "util/export.h" + +// uses Q1.14 format internally, input and output are S16 + +/* + * supported filter orders: 64, 48, 32 + */ +#define HB_FILTERORDER 32 +#define HB_SHIFT 14 + +class SDRANGELOVE_API IntHalfbandFilter { +public: + IntHalfbandFilter(); + + // downsample by 2, return center part of original spectrum + bool workDecimateCenter(Sample* sample) + { + // insert sample into ring-buffer + m_samples[m_ptr][0] = sample->real(); + m_samples[m_ptr][1] = sample->imag(); + + switch(m_state) { + case 0: + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 1; + + // tell caller we don't have a new sample + return false; + + default: + // save result + doFIR(sample); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 0; + + // tell caller we have a new sample + return true; + } + } + + // downsample by 2, return edges of spectrum rotated into center + bool workDecimateFullRotate(Sample* sample) + { + switch(m_state) { + case 0: + // insert sample into ring-buffer + m_samples[m_ptr][0] = sample->real(); + m_samples[m_ptr][1] = sample->imag(); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 1; + + // tell caller we don't have a new sample + return false; + + default: + // insert sample into ring-buffer + m_samples[m_ptr][0] = -sample->real(); + m_samples[m_ptr][1] = sample->imag(); + + // save result + doFIR(sample); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 0; + + // tell caller we have a new sample + return true; + } + } + + // downsample by 2, return lower half of original spectrum + bool workDecimateLowerHalf(Sample* sample) + { + switch(m_state) { + case 0: + // insert sample into ring-buffer + m_samples[m_ptr][0] = -sample->imag(); + m_samples[m_ptr][1] = sample->real(); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 1; + + // tell caller we don't have a new sample + return false; + + case 1: + // insert sample into ring-buffer + m_samples[m_ptr][0] = -sample->real(); + m_samples[m_ptr][1] = -sample->imag(); + + // save result + doFIR(sample); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 2; + + // tell caller we have a new sample + return true; + + case 2: + // insert sample into ring-buffer + m_samples[m_ptr][0] = sample->imag(); + m_samples[m_ptr][1] = -sample->real(); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 3; + + // tell caller we don't have a new sample + return false; + + default: + // insert sample into ring-buffer + m_samples[m_ptr][0] = sample->real(); + m_samples[m_ptr][1] = sample->imag(); + + // save result + doFIR(sample); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 0; + + // tell caller we have a new sample + return true; + } + } + + // downsample by 2, return upper half of original spectrum + bool workDecimateUpperHalf(Sample* sample) + { + switch(m_state) { + case 0: + // insert sample into ring-buffer + m_samples[m_ptr][0] = sample->imag(); + m_samples[m_ptr][1] = -sample->real(); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 1; + + // tell caller we don't have a new sample + return false; + + case 1: + // insert sample into ring-buffer + m_samples[m_ptr][0] = -sample->real(); + m_samples[m_ptr][1] = -sample->imag(); + + // save result + doFIR(sample); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 2; + + // tell caller we have a new sample + return true; + + case 2: + // insert sample into ring-buffer + m_samples[m_ptr][0] = -sample->imag(); + m_samples[m_ptr][1] = sample->real(); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 3; + + // tell caller we don't have a new sample + return false; + + default: + // insert sample into ring-buffer + m_samples[m_ptr][0] = sample->real(); + m_samples[m_ptr][1] = sample->imag(); + + // save result + doFIR(sample); + + // advance write-pointer + m_ptr = (m_ptr + HB_FILTERORDER) % (HB_FILTERORDER + 1); + + // next state + m_state = 0; + + // tell caller we have a new sample + return true; + } + } + +protected: + qint16 m_samples[HB_FILTERORDER + 1][2]; + int m_ptr; + int m_state; + + void doFIR(Sample* sample) + { + // coefficents + +#if HB_FILTERORDER == 64 + static const qint32 COEFF[16] = { + -0.001114417441601693505720538368564120901 * (1 << HB_SHIFT), + 0.001268007827185253051302527005361753254 * (1 << HB_SHIFT), + -0.001959831378850490895410230152151598304 * (1 << HB_SHIFT), + 0.002878308307661380308073439948657323839 * (1 << HB_SHIFT), + -0.004071361818258721100571850826099762344 * (1 << HB_SHIFT), + 0.005597288494657440618973431867289036745 * (1 << HB_SHIFT), + -0.007532345003308904551886371336877346039 * (1 << HB_SHIFT), + 0.009980346844667375288961963519795972388 * (1 << HB_SHIFT), + -0.013092614174300500062830820979797863401 * (1 << HB_SHIFT), + 0.01710934914871829748417297878404497169 * (1 << HB_SHIFT), + -0.022443558692997273018576720460259821266 * (1 << HB_SHIFT), + 0.029875811511593811098386197500076377764 * (1 << HB_SHIFT), + -0.041086352085710403647667021687084343284 * (1 << HB_SHIFT), + 0.060465467462665789533104998554335907102 * (1 << HB_SHIFT), + -0.104159517495977321788203084906854201108 * (1 << HB_SHIFT), + 0.317657589850154464805598308885237202048 * (1 << HB_SHIFT), + }; +#elif HB_FILTERORDER == 48 + static const qint32 COEFF[12] = { + -0.004102576237611492253332112767338912818 * (1 << HB_SHIFT), + 0.003950551047979387886410762575906119309 * (1 << HB_SHIFT), + -0.005807875789391703583164350277456833282 * (1 << HB_SHIFT), + 0.00823497890520805998770814682075069868 * (1 << HB_SHIFT), + -0.011372226513199541059195851744334504474 * (1 << HB_SHIFT), + 0.015471557140973646315984524335362948477 * (1 << HB_SHIFT), + -0.020944996398689276484450516591095947661 * (1 << HB_SHIFT), + 0.028568078132034283034279553703527199104 * (1 << HB_SHIFT), + -0.040015143905614086738964374490024056286 * (1 << HB_SHIFT), + 0.059669519431831075095828964549582451582 * (1 << HB_SHIFT), + -0.103669138691865420076609893840213771909 * (1 << HB_SHIFT), + 0.317491986549921390015072120149852707982 * (1 << HB_SHIFT) + }; +#elif HB_FILTERORDER == 32 + static const qint32 COEFF[8] = { + -0.015956912844043127236437484839370881673 * (1 << HB_SHIFT), + 0.013023031678944928940522274274371739011 * (1 << HB_SHIFT), + -0.01866942273717486777684371190844103694 * (1 << HB_SHIFT), + 0.026550887571157304190005987720724078827 * (1 << HB_SHIFT), + -0.038350314277854319344740474662103224546 * (1 << HB_SHIFT), + 0.058429248652825838128421764849917963147 * (1 << HB_SHIFT), + -0.102889802028955756885153505209018476307 * (1 << HB_SHIFT), + 0.317237706405931241260276465254719369113 * (1 << HB_SHIFT) + }; +#else +#error unsupported filter order +#endif + + + // init read-pointer + int a = (m_ptr + 1) % (HB_FILTERORDER + 1); + int b = (m_ptr + (HB_FILTERORDER - 1)) % (HB_FILTERORDER + 1); + + // go through samples in buffer + qint32 iAcc = 0; + qint32 qAcc = 0; + for(int i = 0; i < HB_FILTERORDER / 4; i++) { + // do multiply-accumulate + qint32 iTmp = m_samples[a][0] + m_samples[b][0]; + qint32 qTmp = m_samples[a][1] + m_samples[b][1]; + iAcc += iTmp * COEFF[i]; + qAcc += qTmp * COEFF[i]; + + // update read-pointer + a = (a + 2) % (HB_FILTERORDER + 1); + b = (b + (HB_FILTERORDER - 1)) % (HB_FILTERORDER + 1); + } + + a = (a + HB_FILTERORDER) % (HB_FILTERORDER + 1); + iAcc += m_samples[a][0] * (qint32)(0.5 * (1 << HB_SHIFT)); + qAcc += m_samples[a][1] * (qint32)(0.5 * (1 << HB_SHIFT)); + + // done, save result + sample->setReal((iAcc + (qint32)(0.5 * (1 << HB_SHIFT))) >> HB_SHIFT); + sample->setImag((qAcc + (qint32)(0.5 * (1 << HB_SHIFT))) >> HB_SHIFT); + } +}; + +#endif // INCLUDE_INTHALFBANDFILTER_H diff --git a/include-gpl/dsp/kissengine.h b/include-gpl/dsp/kissengine.h new file mode 100644 index 000000000..ad8e53c32 --- /dev/null +++ b/include-gpl/dsp/kissengine.h @@ -0,0 +1,23 @@ +#ifndef INCLUDE_KISSENGINE_H +#define INCLUDE_KISSENGINE_H + +#include "dsp/fftengine.h" +#include "dsp/kissfft.h" + +class KissEngine : public FFTEngine { +public: + void configure(int n, bool inverse); + void transform(); + + Complex* in(); + Complex* out(); + +protected: + typedef kissfft KissFFT; + KissFFT m_fft; + + std::vector m_in; + std::vector m_out; +}; + +#endif // INCLUDE_KISSENGINE_H diff --git a/include-gpl/dsp/lowpass.h b/include-gpl/dsp/lowpass.h new file mode 100644 index 000000000..c415a9484 --- /dev/null +++ b/include-gpl/dsp/lowpass.h @@ -0,0 +1,88 @@ +#ifndef INCLUDE_LOWPASS_H +#define INCLUDE_LOWPASS_H + +#define _USE_MATH_DEFINES +#include +#include "dsp/dsptypes.h" + +template class Lowpass { +public: + Lowpass() { } + + void create(int nTaps, double sampleRate, double cutoff) + { + double wc = 2.0 * M_PI * cutoff; + double Wc = wc / sampleRate; + int i; + + // check constraints + if(!(nTaps & 1)) { + qDebug("Lowpass filter has to have an odd number of taps"); + nTaps++; + } + + // make room + m_samples.resize(nTaps); + for(int i = 0; i < nTaps; i++) + m_samples[i] = 0; + m_ptr = 0; + m_taps.resize(nTaps / 2 + 1); + + // generate Sinc filter core + for(i = 0; i < nTaps / 2 + 1; i++) { + if(i == (nTaps - 1) / 2) + m_taps[i] = Wc / M_PI; + else + m_taps[i] = sin(((double)i - ((double)nTaps - 1.0) / 2.0) * Wc) / (((double)i - ((double)nTaps - 1.0) / 2.0) * M_PI); + } + + // apply Hamming window + for(i = 0; i < nTaps / 2 + 1; i++) + m_taps[i] *= 0.54 + 0.46 * cos((2.0 * M_PI * ((double)i - ((double)nTaps - 1.0) / 2.0)) / (double)nTaps); + + // normalize + Real sum = 0; + for(i = 0; i < (int)m_taps.size() - 1; i++) + sum += m_taps[i] * 2; + sum += m_taps[i]; + for(i = 0; i < (int)m_taps.size(); i++) + m_taps[i] /= sum; + } + + Type filter(Type sample) + { + Type acc = 0; + int a = m_ptr; + int b = a - 1; + int i; + + m_samples[m_ptr] = sample; + + while(b < 0) + b += m_samples.size(); + + for(i = 0; i < (int)m_taps.size() - 1; i++) { + acc += (m_samples[a] + m_samples[b]) * m_taps[i]; + a++; + while(a >= (int)m_samples.size()) + a -= m_samples.size(); + b--; + while(b < 0) + b += m_samples.size(); + } + acc += m_samples[a] * m_taps[i]; + + m_ptr++; + while(m_ptr >= (int)m_samples.size()) + m_ptr -= m_samples.size(); + + return acc; + } + +private: + std::vector m_taps; + std::vector m_samples; + int m_ptr; +}; + +#endif // INCLUDE_LOWPASS_H diff --git a/include-gpl/dsp/movingaverage.h b/include-gpl/dsp/movingaverage.h new file mode 100644 index 000000000..e608efbd6 --- /dev/null +++ b/include-gpl/dsp/movingaverage.h @@ -0,0 +1,53 @@ +#ifndef INCLUDE_MOVINGAVERAGE_H +#define INCLUDE_MOVINGAVERAGE_H + +#include +#include "dsp/dsptypes.h" + +class MovingAverage { +public: + MovingAverage() : + m_history(), + m_sum(0), + m_ptr(0) + { + } + + MovingAverage(int historySize, Real initial) : + m_history(historySize, initial), + m_sum(historySize * initial), + m_ptr(0) + { + } + + void resize(int historySize, Real initial) + { + m_history.resize(historySize); + for(size_t i = 0; i < m_history.size(); i++) + m_history[i] = initial; + m_sum = m_history.size() * initial; + m_ptr = 0; + } + + void feed(Real value) + { + m_sum -= m_history[m_ptr]; + m_history[m_ptr] = value; + m_sum += value; + m_ptr++; + if(m_ptr >= m_history.size()) + m_ptr = 0; + } + + Real average() const + { + return m_sum / (Real)m_history.size(); + } + +protected: + std::vector m_history; + Real m_sum; + uint m_ptr; +}; + +#endif // INCLUDE_MOVINGAVERAGE_H diff --git a/include-gpl/dsp/nco.h b/include-gpl/dsp/nco.h new file mode 100644 index 000000000..55db852fa --- /dev/null +++ b/include-gpl/dsp/nco.h @@ -0,0 +1,45 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_NCO_H +#define INCLUDE_NCO_H + +#include "dsp/dsptypes.h" +#include "util/export.h" + +class SDRANGELOVE_API NCO { +private: + enum { + TableSize = (1 << 12), + }; + static Real m_table[TableSize]; + static bool m_tableInitialized; + + static void initTable(); + + int m_phaseIncrement; + int m_phase; + +public: + NCO(); + + void setFreq(Real freq, Real sampleRate); + Real next(); + Complex nextIQ(); +}; + +#endif // INCLUDE_NCO_H diff --git a/include-gpl/dsp/scopevis.h b/include-gpl/dsp/scopevis.h new file mode 100644 index 000000000..4845a632f --- /dev/null +++ b/include-gpl/dsp/scopevis.h @@ -0,0 +1,44 @@ +#ifndef INCLUDE_SCOPEVIS_H +#define INCLUDE_SCOPEVIS_H + +#include "dsp/samplesink.h" +#include "util/export.h" + +class GLScope; +class MessageQueue; + +class SDRANGELOVE_API ScopeVis : public SampleSink { +public: + enum TriggerChannel { + TriggerFreeRun, + TriggerChannelI, + TriggerChannelQ + }; + + ScopeVis(GLScope* glScope = NULL); + + void configure(MessageQueue* msgQueue, TriggerChannel triggerChannel, Real triggerLevelHigh, Real triggerLevelLow); + + void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst); + void start(); + void stop(); + bool handleMessage(Message* message); + +private: + enum TriggerState { + Untriggered, + Triggered, + WaitForReset + }; + + GLScope* m_glScope; + std::vector m_trace; + uint m_fill; + TriggerState m_triggerState; + TriggerChannel m_triggerChannel; + FixReal m_triggerLevelHigh; + FixReal m_triggerLevelLow; + int m_sampleRate; +}; + +#endif // INCLUDE_SCOPEVIS_H diff --git a/include-gpl/dsp/spectrumvis.h b/include-gpl/dsp/spectrumvis.h new file mode 100644 index 000000000..ebc16ab09 --- /dev/null +++ b/include-gpl/dsp/spectrumvis.h @@ -0,0 +1,42 @@ +#ifndef INCLUDE_SPECTRUMVIS_H +#define INCLUDE_SPECTRUMVIS_H + +#include "dsp/samplesink.h" +#include "dsp/fftengine.h" +#include "fftwindow.h" +#include "util/export.h" + +class GLSpectrum; +class MessageQueue; + +class SDRANGELOVE_API SpectrumVis : public SampleSink { +public: + SpectrumVis(GLSpectrum* glSpectrum = NULL); + ~SpectrumVis(); + + void configure(MessageQueue* msgQueue, int fftSize, int overlapPercent, FFTWindow::Function window); + + void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst); + void start(); + void stop(); + bool handleMessage(Message* message); + +private: + FFTEngine* m_fft; + FFTWindow m_window; + + std::vector m_fftBuffer; + std::vector m_logPowerSpectrum; + + size_t m_fftSize; + size_t m_overlapPercent; + size_t m_overlapSize; + size_t m_refillSize; + size_t m_fftBufferFill; + + GLSpectrum* m_glSpectrum; + + void handleConfigure(int fftSize, int overlapPercent, FFTWindow::Function window); +}; + +#endif // INCLUDE_SPECTRUMVIS_H diff --git a/include-gpl/gui/aboutdialog.h b/include-gpl/gui/aboutdialog.h new file mode 100644 index 000000000..cf5559d6f --- /dev/null +++ b/include-gpl/gui/aboutdialog.h @@ -0,0 +1,21 @@ +#ifndef INCLUDE_ABOUTDIALOG_H +#define INCLUDE_ABOUTDIALOG_H + +#include + +namespace Ui { + class AboutDialog; +} + +class AboutDialog : public QDialog { + Q_OBJECT + +public: + explicit AboutDialog(QWidget* parent = NULL); + ~AboutDialog(); + +private: + Ui::AboutDialog* ui; +}; + +#endif // INCLUDE_ABOUTDIALOG_H diff --git a/include-gpl/gui/addpresetdialog.h b/include-gpl/gui/addpresetdialog.h new file mode 100644 index 000000000..8d3a7ee28 --- /dev/null +++ b/include-gpl/gui/addpresetdialog.h @@ -0,0 +1,30 @@ +#ifndef INCLUDE_ADDPRESETDIALOG_H +#define INCLUDE_ADDPRESETDIALOG_H + +#include + +namespace Ui { + class AddPresetDialog; +} + +class AddPresetDialog : public QDialog { + Q_OBJECT + +public: + explicit AddPresetDialog(const QStringList& groups, const QString& group, QWidget* parent = NULL); + ~AddPresetDialog(); + + QString group() const; + QString description() const; + +private: + enum Audio { + ATDefault, + ATInterface, + ATDevice + }; + + Ui::AddPresetDialog* ui; +}; + +#endif // INCLUDE_ADDPRESETDIALOG_H diff --git a/include-gpl/gui/buttonswitch.h b/include-gpl/gui/buttonswitch.h new file mode 100644 index 000000000..672a5afea --- /dev/null +++ b/include-gpl/gui/buttonswitch.h @@ -0,0 +1,19 @@ +#ifndef INCLUDE_BUTTONSWITCH_H +#define INCLUDE_BUTTONSWITCH_H + +#include + +class ButtonSwitch : public QToolButton { + Q_OBJECT + +public: + ButtonSwitch(QWidget* parent = NULL); + +private slots: + void onToggled(bool checked); + +private: + QPalette m_originalPalette; +}; + +#endif // INCLUDE_BUTTONSWITCH_H diff --git a/include-gpl/gui/channelwindow.h b/include-gpl/gui/channelwindow.h new file mode 100644 index 000000000..6bc87e3e5 --- /dev/null +++ b/include-gpl/gui/channelwindow.h @@ -0,0 +1,25 @@ +#ifndef INCLUDE_CHANNELWINDOW_H +#define INCLUDE_CHANNELWINDOW_H + +#include + +class QBoxLayout; +class QSpacerItem; +class RollupWidget; + +class ChannelWindow : public QScrollArea { + Q_OBJECT + +public: + ChannelWindow(QWidget* parent = NULL); + + void addRollupWidget(QWidget* rollupWidget); + +protected: + QWidget* m_container; + QBoxLayout* m_layout; + + void resizeEvent(QResizeEvent* event); +}; + +#endif // INCLUDE_CHANNELWINDOW_H diff --git a/include-gpl/gui/glscope.h b/include-gpl/gui/glscope.h new file mode 100644 index 000000000..62671c454 --- /dev/null +++ b/include-gpl/gui/glscope.h @@ -0,0 +1,110 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_GLSCOPE_H +#define INCLUDE_GLSCOPE_H + +#include +#include +#include +#include +#include "dsp/dsptypes.h" +#include "dsp/scopevis.h" +#include "util/export.h" + +class DSPEngine; +class ScopeVis; + +class SDRANGELOVE_API GLScope: public QGLWidget { + Q_OBJECT + +public: + enum Mode { + ModeIQ, + ModeMagLinPha, + ModeMagdBPha, + ModeDerived12, + ModeCyclostationary + }; + + GLScope(QWidget* parent = NULL); + ~GLScope(); + + void setDSPEngine(DSPEngine* dspEngine); + void setAmp(Real amp); + void setTimeBase(int timeBase); + void setTimeOfsProMill(int timeOfsProMill); + void setMode(Mode mode); + void setOrientation(Qt::Orientation orientation); + + void newTrace(const std::vector& trace, int sampleRate); + + int getTraceSize() const { return m_rawTrace.size(); } + +signals: + void traceSizeChanged(int); + +private: + // state + QTimer m_timer; + QMutex m_mutex; + bool m_dataChanged; + bool m_configChanged; + Mode m_mode; + Qt::Orientation m_orientation; + + // traces + std::vector m_rawTrace; + std::vector m_mathTrace; + std::vector* m_displayTrace; + int m_oldTraceSize; + int m_sampleRate; + Real m_amp1; + Real m_amp2; + Real m_ofs1; + Real m_ofs2; + + // sample sink + DSPEngine* m_dspEngine; + ScopeVis* m_scopeVis; + + // config + Real m_amp; + int m_timeBase; + int m_timeOfsProMill; + ScopeVis::TriggerChannel m_triggerChannel; + Real m_triggerLevelHigh; + Real m_triggerLevelLow; + + // graphics stuff + QRectF m_glScopeRect1; + QRectF m_glScopeRect2; + + void initializeGL(); + void resizeGL(int width, int height); + void paintGL(); + + void mousePressEvent(QMouseEvent*); + + void handleMode(); + void applyConfig(); + +protected slots: + void tick(); +}; + +#endif // INCLUDE_GLSCOPE_H diff --git a/include-gpl/gui/glspectrum.h b/include-gpl/gui/glspectrum.h new file mode 100644 index 000000000..794780b71 --- /dev/null +++ b/include-gpl/gui/glspectrum.h @@ -0,0 +1,157 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_GLSPECTRUM_H +#define INCLUDE_GLSPECTRUM_H + +#include +#include +#include +#include "dsp/dsptypes.h" +#include "gui/scaleengine.h" +#include "dsp/channelmarker.h" +#include "util/export.h" + +class SDRANGELOVE_API GLSpectrum : public QGLWidget { + Q_OBJECT + +public: + GLSpectrum(QWidget* parent = NULL); + ~GLSpectrum(); + + void setCenterFrequency(quint64 frequency); + void setSampleRate(qint32 sampleRate); + void setReferenceLevel(Real referenceLevel); + void setPowerRange(Real powerRange); + void setDecay(int decay); + void setDisplayWaterfall(bool display); + void setInvertedWaterfall(bool inv); + void setDisplayMaxHold(bool display); + void setDisplayHistogram(bool display); + void setDisplayGrid(bool display); + + void addChannelMarker(ChannelMarker* channelMarker); + void removeChannelMarker(ChannelMarker* channelMarker); + + void newSpectrum(const std::vector& spectrum, int fftSize); + +private: + struct ChannelMarkerState { + ChannelMarker* m_channelMarker; + QRectF m_glRect; + QRect m_rect; + + ChannelMarkerState(ChannelMarker* channelMarker) : + m_channelMarker(channelMarker), + m_glRect() + { } + }; + QList m_channelMarkerStates; + + enum CursorState { + CSNormal, + CSSplitter, + CSSplitterMoving, + CSChannel, + CSChannelMoving + }; + + CursorState m_cursorState; + int m_cursorChannel; + + QTimer m_timer; + QMutex m_mutex; + bool m_mouseInside; + bool m_changesPending; + + qint64 m_centerFrequency; + Real m_referenceLevel; + Real m_powerRange; + int m_decay; + quint32 m_sampleRate; + + int m_fftSize; + + bool m_displayGrid; + bool m_invertedWaterfall; + + std::vector m_maxHold; + bool m_displayMaxHold; + + Real m_waterfallShare; + + QPixmap m_leftMarginPixmap; + bool m_leftMarginTextureAllocated; + GLuint m_leftMarginTexture; + QPixmap m_frequencyPixmap; + bool m_frequencyTextureAllocated; + GLuint m_frequencyTexture; + ScaleEngine m_timeScale; + ScaleEngine m_powerScale; + ScaleEngine m_frequencyScale; + QRectF m_glLeftScaleRect; + QRectF m_glFrequencyScaleRect; + QRect m_frequencyScaleRect; + + QRgb m_waterfallPalette[240]; + QImage* m_waterfallBuffer; + int m_waterfallBufferPos; + bool m_waterfallTextureAllocated; + GLuint m_waterfallTexture; + int m_waterfallTextureHeight; + int m_waterfallTexturePos; + QRectF m_glWaterfallRect; + bool m_displayWaterfall; + + QRgb m_histogramPalette[240]; + QImage* m_histogramBuffer; + quint8* m_histogram; + quint8* m_histogramHoldoff; + bool m_histogramTextureAllocated; + GLuint m_histogramTexture; + int m_histogramHoldoffBase; + int m_histogramHoldoffCount; + int m_histogramLateHoldoff; + QRectF m_glHistogramRect; + bool m_displayHistogram; + + bool m_displayChanged; + + void updateWaterfall(const std::vector& spectrum); + void updateHistogram(const std::vector& spectrum); + + void initializeGL(); + void resizeGL(int width, int height); + void paintGL(); + + void stopDrag(); + void applyChanges(); + + void mouseMoveEvent(QMouseEvent* event); + void mousePressEvent(QMouseEvent* event); + void mouseReleaseEvent(QMouseEvent* event); + + void enterEvent(QEvent* event); + void leaveEvent(QEvent* event); + +private slots: + void tick(); + void channelMarkerChanged(); + void channelMarkerDestroyed(QObject* object); +}; + +#endif // INCLUDE_GLSPECTRUM_H diff --git a/include-gpl/gui/glspectrumgui.h b/include-gpl/gui/glspectrumgui.h new file mode 100644 index 000000000..b515aed27 --- /dev/null +++ b/include-gpl/gui/glspectrumgui.h @@ -0,0 +1,65 @@ +#ifndef INCLUDE_GLSPECTRUMGUI_H +#define INCLUDE_GLSPECTRUMGUI_H + +#include +#include "dsp/dsptypes.h" +#include "util/export.h" + +namespace Ui { + class GLSpectrumGUI; +} + +class MessageQueue; +class SpectrumVis; +class GLSpectrum; + +class SDRANGELOVE_API GLSpectrumGUI : public QWidget { + Q_OBJECT + +public: + explicit GLSpectrumGUI(QWidget* parent = NULL); + ~GLSpectrumGUI(); + + void setBuddies(MessageQueue* messageQueue, SpectrumVis* spectrumVis, GLSpectrum* glSpectrum); + + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + +private: + Ui::GLSpectrumGUI* ui; + + MessageQueue* m_messageQueue; + SpectrumVis* m_spectrumVis; + GLSpectrum* m_glSpectrum; + + qint32 m_fftSize; + qint32 m_fftOverlap; + qint32 m_fftWindow; + Real m_refLevel; + Real m_powerRange; + int m_decay; + bool m_displayWaterfall; + bool m_invertedWaterfall; + bool m_displayMaxHold; + bool m_displayHistogram; + bool m_displayGrid; + bool m_invert; + + void applySettings(); + +private slots: + void on_fftWindow_currentIndexChanged(int index); + void on_fftSize_currentIndexChanged(int index); + void on_refLevel_currentIndexChanged(int index); + void on_levelRange_currentIndexChanged(int index); + void on_decay_currentIndexChanged(int index); + + void on_waterfall_toggled(bool checked); + void on_histogram_toggled(bool checked); + void on_maxHold_toggled(bool checked); + void on_invert_toggled(bool checked); + void on_grid_toggled(bool checked); +}; + +#endif // INCLUDE_GLSPECTRUMGUI_H diff --git a/include-gpl/gui/indicator.h b/include-gpl/gui/indicator.h new file mode 100644 index 000000000..596956f19 --- /dev/null +++ b/include-gpl/gui/indicator.h @@ -0,0 +1,41 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_INDICATOR_H +#define INCLUDE_INDICATOR_H + +#include +#include "util/export.h" + +class SDRANGELOVE_API Indicator : public QWidget { +private: + Q_OBJECT; + + QColor m_color; + QString m_text; + +protected: + void paintEvent(QPaintEvent* event); + QSize sizeHint() const; + +public: + Indicator(const QString& text, QWidget* parent = NULL); + + void setColor(const QColor& color); +}; + +#endif // INCLUDE_INDICATOR_H diff --git a/include-gpl/gui/physicalunit.h b/include-gpl/gui/physicalunit.h new file mode 100644 index 000000000..e8eda2b9f --- /dev/null +++ b/include-gpl/gui/physicalunit.h @@ -0,0 +1,35 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_PHYSICALUNIT_H +#define INCLUDE_PHYSICALUNIT_H + +namespace Unit { + enum Physical { + None, + Frequency, + Information, + Percent, + Decibel, + DecibelMilliWatt, + DecibelMicroVolt, + AngleDegrees, + Time + }; +}; + +#endif // INCLUDE_PHYSICALUNIT_H diff --git a/include-gpl/gui/pluginsdialog.h b/include-gpl/gui/pluginsdialog.h new file mode 100644 index 000000000..d0f7305a7 --- /dev/null +++ b/include-gpl/gui/pluginsdialog.h @@ -0,0 +1,22 @@ +#ifndef INCLUDE_PLUGINSDIALOG_H +#define INCLUDE_PLUGINSDIALOG_H + +#include +#include "plugin/pluginmanager.h" + +namespace Ui { + class PluginsDialog; +} + +class PluginsDialog : public QDialog { + Q_OBJECT + +public: + explicit PluginsDialog(PluginManager* pluginManager, QWidget* parent = NULL); + ~PluginsDialog(); + +private: + Ui::PluginsDialog* ui; +}; + +#endif // INCLUDE_PLUGINSDIALOG_H diff --git a/include-gpl/gui/preferencesdialog.h b/include-gpl/gui/preferencesdialog.h new file mode 100644 index 000000000..86247f325 --- /dev/null +++ b/include-gpl/gui/preferencesdialog.h @@ -0,0 +1,34 @@ +#ifndef INCLUDE_PREFERENCESDIALOG_H +#define INCLUDE_PREFERENCESDIALOG_H + +#include + +class AudioDeviceInfo; + +namespace Ui { + class PreferencesDialog; +} + +class PreferencesDialog : public QDialog { + Q_OBJECT + +public: + explicit PreferencesDialog(AudioDeviceInfo* audioDeviceInfo, QWidget* parent = NULL); + ~PreferencesDialog(); + +private: + enum Audio { + ATDefault, + ATInterface, + ATDevice + }; + + Ui::PreferencesDialog* ui; + + AudioDeviceInfo* m_audioDeviceInfo; + +private slots: + void accept(); +}; + +#endif // INCLUDE_PREFERENCESDIALOG_H diff --git a/include-gpl/gui/presetitem.h b/include-gpl/gui/presetitem.h new file mode 100644 index 000000000..fa455435b --- /dev/null +++ b/include-gpl/gui/presetitem.h @@ -0,0 +1,27 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include + +class PresetItem : public QTreeWidgetItem { +public: + PresetItem(QTreeWidgetItem* parent, const QStringList& strings, quint64 frequency, int type); + bool operator<(const QTreeWidgetItem& other) const; + +private: + quint64 m_frequency; +}; diff --git a/include-gpl/gui/scale.h b/include-gpl/gui/scale.h new file mode 100644 index 000000000..82f6f8fb4 --- /dev/null +++ b/include-gpl/gui/scale.h @@ -0,0 +1,37 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include "gui/scaleengine.h" +#include "util/export.h" + +class SDRANGELOVE_API Scale : public QWidget { + Q_OBJECT + +public: + Scale(QWidget* parent = NULL); + + void setOrientation(Qt::Orientation orientation); + void setRange(Unit::Physical physicalUnit, float rangeMin, float rangeMax); + +private: + Qt::Orientation m_orientation; + ScaleEngine m_scaleEngine; + + void paintEvent(QPaintEvent*); + void resizeEvent(QResizeEvent*); +}; diff --git a/include-gpl/gui/scaleengine.h b/include-gpl/gui/scaleengine.h new file mode 100644 index 000000000..38693a831 --- /dev/null +++ b/include-gpl/gui/scaleengine.h @@ -0,0 +1,90 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_SCALEENGINE_H +#define INCLUDE_SCALEENGINE_H + +#include +#include +#include +#include "physicalunit.h" +#include "util/export.h" + +class SDRANGELOVE_API ScaleEngine { +public: + struct Tick { + float pos; + bool major; + float textPos; + float textSize; + QString text; + }; + typedef QList TickList; + +private: + // base configuration + Qt::Orientation m_orientation; + QFont m_font; + float m_charSize; + + // graph configuration + float m_size; + Unit::Physical m_physicalUnit; + float m_rangeMin; + float m_rangeMax; + + // calculated values + bool m_recalc; + double m_scale; + QString m_unitStr; + TickList m_tickList; + double m_majorTickValueDistance; + double m_firstMajorTickValue; + int m_numMinorTicks; + int m_decimalPlaces; + + QString formatTick(double value, int decimalPlaces, bool fancyTime = true); + void calcCharSize(); + void calcScaleFactor(); + double calcMajorTickUnits(double distance, int* retDecimalPlaces); + int calcTickTextSize(); + void forceTwoTicks(); + void reCalc(); + + double majorTickValue(int tick); + double minorTickValue(int tick); + +public: + ScaleEngine(); + + void setOrientation(Qt::Orientation orientation); + void setFont(const QFont& font); + void setSize(float size); + float getSize() { return m_size; } + void setRange(Unit::Physical physicalUnit, float rangeMin, float rangeMax); + + float getPosFromValue(double value); + float getValueFromPos(double pos); + const TickList& getTickList(); + + QString getRangeMinStr(); + QString getRangeMaxStr(); + + float getScaleWidth(); +}; + +#endif // INCLUDE_SCALEENGINE_H diff --git a/include-gpl/gui/scopewindow.h b/include-gpl/gui/scopewindow.h new file mode 100644 index 000000000..2761dcc0d --- /dev/null +++ b/include-gpl/gui/scopewindow.h @@ -0,0 +1,67 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_SCOPEWINDOW_H +#define INCLUDE_SCOPEWINDOW_H + +#include +#include "dsp/dsptypes.h" +#include "util/export.h" + +class DSPEngine; + +namespace Ui { + class ScopeWindow; +} + +class SDRANGELOVE_API ScopeWindow : public QWidget { + Q_OBJECT + +public: + explicit ScopeWindow(DSPEngine* dspEngine, QWidget* parent = NULL); + ~ScopeWindow(); + + void setSampleRate(int sampleRate); + + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + +private slots: + void on_amp_valueChanged(int value); + void on_scope_traceSizeChanged(int value); + void on_time_valueChanged(int value); + void on_timeOfs_valueChanged(int value); + void on_displayMode_currentIndexChanged(int index); + + void on_horizView_clicked(); + void on_vertView_clicked(); + +private: + Ui::ScopeWindow *ui; + int m_sampleRate; + + qint32 m_displayData; + qint32 m_displayOrientation; + qint32 m_timeBase; + qint32 m_timeOffset; + qint32 m_amplification; + + void applySettings(); +}; + +#endif // INCLUDE_SCOPEWINDOW_H diff --git a/include-gpl/gui/valuedial.h b/include-gpl/gui/valuedial.h new file mode 100644 index 000000000..a04825da8 --- /dev/null +++ b/include-gpl/gui/valuedial.h @@ -0,0 +1,72 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "util/export.h" + +class SDRANGELOVE_API ValueDial : public QWidget { + Q_OBJECT + +public: + ValueDial(QWidget* parent = NULL); + + void setValue(quint64 value); + void setValueRange(uint numDigits, quint64 min, quint64 max); + void setFont(const QFont& font); + +signals: + void changed(quint64 value); + +private: + QLinearGradient m_background; + int m_numDigits; + int m_numDecimalPoints; + int m_digitWidth; + int m_digitHeight; + int m_hightlightedDigit; + int m_cursor; + bool m_cursorState; + quint64 m_value; + quint64 m_valueMax; + quint64 m_valueMin; + QString m_text; + + quint64 m_valueNew; + QString m_textNew; + int m_animationState; + QTimer m_animationTimer; + QTimer m_blinkTimer; + + quint64 findExponent(int digit); + QChar digitNeigh(QChar c, bool dir); + QString formatText(quint64 value); + + void paintEvent(QPaintEvent*); + + void mousePressEvent(QMouseEvent*); + void mouseMoveEvent(QMouseEvent*); + void wheelEvent(QWheelEvent*); + void leaveEvent(QEvent*); + void keyPressEvent(QKeyEvent*); + void focusInEvent(QFocusEvent*); + void focusOutEvent(QFocusEvent*); + +private slots: + void animate(); + void blink(); +}; diff --git a/include-gpl/mainwindow.h b/include-gpl/mainwindow.h new file mode 100644 index 000000000..0f0b48106 --- /dev/null +++ b/include-gpl/mainwindow.h @@ -0,0 +1,136 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_MAINWINDOW_H +#define INCLUDE_MAINWINDOW_H + +#include +#include +#include "settings/settings.h" +#include "util/export.h" + +class QLabel; +class QTreeWidgetItem; +class QDir; + +class AudioDeviceInfo; +class DSPEngine; +class Indicator; +class ScopeWindow; +class SpectrumVis; +class SampleSource; +class PluginAPI; +class PluginGUI; +class ChannelMarker; +class MessageQueue; +class PluginManager; +class PluginInterface; + +namespace Ui { + class MainWindow; +} + +class SDRANGELOVE_API MainWindow : public QMainWindow { + Q_OBJECT + +public: + explicit MainWindow(QWidget* parent = NULL); + ~MainWindow(); + + MessageQueue* getMessageQueue() { return m_messageQueue; } + + void addChannelCreateAction(QAction* action); + void addChannelRollup(QWidget* widget); + void addViewAction(QAction* action); + + void addChannelMarker(ChannelMarker* channelMarker); + void removeChannelMarker(ChannelMarker* channelMarker); + + void setInputGUI(QWidget* gui); + +private: + enum { + PGroup, + PItem + }; + + Ui::MainWindow* ui; + + AudioDeviceInfo* m_audioDeviceInfo; + + MessageQueue* m_messageQueue; + + Settings m_settings; + + SpectrumVis* m_spectrumVis; + + DSPEngine* m_dspEngine; + + QTimer m_statusTimer; + int m_lastEngineState; + + QLabel* m_sampleRateWidget; + Indicator* m_engineIdle; + Indicator* m_engineRunning; + Indicator* m_engineError; + + bool m_startOsmoSDRUpdateAfterStop; + + ScopeWindow* m_scopeWindow; + QWidget* m_inputGUI; + + int m_sampleRate; + quint64 m_centerFrequency; + + PluginManager* m_pluginManager; + + void loadSettings(); + void loadSettings(const Preset* preset); + void saveSettings(Preset* preset); + void saveSettings(); + + void createStatusBar(); + void closeEvent(QCloseEvent*); + void updateCenterFreqDisplay(); + void updateSampleRate(); + void updatePresets(); + QTreeWidgetItem* addPresetToTree(const Preset* preset); + void applySettings(); + +private slots: + void handleMessages(); + void updateStatus(); + void scopeWindowDestroyed(); + void on_action_Start_triggered(); + void on_action_Stop_triggered(); + void on_dcOffset_toggled(bool checked); + void on_iqImbalance_toggled(bool checked); + void on_action_View_Fullscreen_toggled(bool checked); + void on_actionOsmoSDR_Firmware_Upgrade_triggered(); + void on_presetSave_clicked(); + void on_presetLoad_clicked(); + void on_presetDelete_clicked(); + void on_presetTree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous); + void on_presetTree_itemActivated(QTreeWidgetItem *item, int column); + void on_action_Oscilloscope_triggered(); + void on_action_Loaded_Plugins_triggered(); + void on_action_Preferences_triggered(); + void on_sampleSource_currentIndexChanged(int index); + void on_action_About_triggered(); +}; + +#endif // INCLUDE_MAINWINDOW_H diff --git a/include-gpl/plugin/pluginmanager.h b/include-gpl/plugin/pluginmanager.h new file mode 100644 index 000000000..8080b5ad1 --- /dev/null +++ b/include-gpl/plugin/pluginmanager.h @@ -0,0 +1,131 @@ +#ifndef INCLUDE_PLUGINMANAGER_H +#define INCLUDE_PLUGINMANAGER_H + +#include +#include +#include "plugin/plugininterface.h" +#include "plugin/pluginapi.h" +#include "util/export.h" + +class QAction; +class QComboBox; +class QPluginLoader; +class Preset; +class MainWindow; +class SampleSource; +class Message; + +class SDRANGELOVE_API PluginManager : public QObject { + Q_OBJECT + +public: + struct Plugin { + QString filename; + QPluginLoader* loader; + PluginInterface* plugin; + Plugin(const QString& _filename, QPluginLoader* pluginLoader, PluginInterface* _plugin) : + filename(_filename), + loader(pluginLoader), + plugin(_plugin) + { } + }; + typedef QList Plugins; + + explicit PluginManager(MainWindow* mainWindow, DSPEngine* dspEngine, QObject* parent = NULL); + ~PluginManager(); + void loadPlugins(); + + const Plugins& getPlugins() const { return m_plugins; } + + void registerChannel(const QString& channelName, PluginInterface* plugin, QAction* action); + void registerChannelInstance(const QString& channelName, PluginGUI* pluginGUI); + void addChannelRollup(QWidget* pluginGUI); + void removeChannelInstance(PluginGUI* pluginGUI); + + void registerSampleSource(const QString& sourceName, PluginInterface* plugin); + + void loadSettings(const Preset* preset); + void saveSettings(Preset* preset) const; + + void freeAll(); + + bool handleMessage(Message* message); + + void updateSampleSourceDevices(); + void fillSampleSourceSelector(QComboBox* comboBox); + int selectSampleSource(int index); + int selectSampleSource(const QString& source); + +private: + struct ChannelRegistration { + QString m_channelName; + PluginInterface* m_plugin; + ChannelRegistration(const QString& channelName, PluginInterface* plugin) : + m_channelName(channelName), + m_plugin(plugin) + { } + }; + typedef QList ChannelRegistrations; + + struct ChannelInstanceRegistration { + QString m_channelName; + PluginGUI* m_gui; + ChannelInstanceRegistration() : + m_channelName(), + m_gui(NULL) + { } + ChannelInstanceRegistration(const QString& channelName, PluginGUI* pluginGUI) : + m_channelName(channelName), + m_gui(pluginGUI) + { } + }; + typedef QList ChannelInstanceRegistrations; + + struct SampleSourceRegistration { + QString m_sourceName; + PluginInterface* m_plugin; + SampleSourceRegistration(const QString& sourceName, PluginInterface* plugin) : + m_sourceName(sourceName), + m_plugin(plugin) + { } + }; + typedef QList SampleSourceRegistrations; + + struct SampleSourceDevice { + PluginInterface* m_plugin; + QString m_displayName; + QString m_sourceName; + QByteArray m_address; + + SampleSourceDevice(PluginInterface* plugin, const QString& displayName, const QString& sourceName, const QByteArray& address) : + m_plugin(plugin), + m_displayName(displayName), + m_sourceName(sourceName), + m_address(address) + { } + }; + typedef QList SampleSourceDevices; + + PluginAPI m_pluginAPI; + MainWindow* m_mainWindow; + DSPEngine* m_dspEngine; + Plugins m_plugins; + + ChannelRegistrations m_channelRegistrations; + ChannelInstanceRegistrations m_channelInstanceRegistrations; + SampleSourceRegistrations m_sampleSourceRegistrations; + SampleSourceDevices m_sampleSourceDevices; + + QString m_sampleSource; + PluginGUI* m_sampleSourceInstance; + + void loadPlugins(const QDir& dir); + void renameChannelInstances(); +}; + +static inline bool operator<(const PluginManager::Plugin& a, const PluginManager::Plugin& b) +{ + return a.plugin->getPluginDescriptor().displayedName < b.plugin->getPluginDescriptor().displayedName; +} + +#endif // INCLUDE_PLUGINMANAGER_H diff --git a/include-gpl/settings/preferences.h b/include-gpl/settings/preferences.h new file mode 100644 index 000000000..74de287ed --- /dev/null +++ b/include-gpl/settings/preferences.h @@ -0,0 +1,32 @@ +#ifndef INCLUDE_PREFERENCES_H +#define INCLUDE_PREFERENCES_H + +#include + +class Preferences { +public: + Preferences(); + + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + + void setSourceType(const QString& value) { m_sourceType = value; } + const QString& getSourceType() const { return m_sourceType; } + void setSourceDevice(const QString& value) { m_sourceDevice= value; } + const QString& getSourceDevice() const { return m_sourceDevice; } + + void setAudioType(const QString& value) { m_audioType = value; } + const QString& getAudioType() const { return m_audioType; } + void setAudioDevice(const QString& value) { m_audioDevice= value; } + const QString& getAudioDevice() const { return m_audioDevice; } + +protected: + QString m_sourceType; + QString m_sourceDevice; + + QString m_audioType; + QString m_audioDevice; +}; + +#endif // INCLUDE_PREFERENCES_H diff --git a/include-gpl/settings/preset.h b/include-gpl/settings/preset.h new file mode 100644 index 000000000..1396e2388 --- /dev/null +++ b/include-gpl/settings/preset.h @@ -0,0 +1,98 @@ +#ifndef INCLUDE_PRESET_H +#define INCLUDE_PRESET_H + +#include +#include +#include + +class Preset { +public: + struct ChannelConfig { + QString m_channel; + QByteArray m_config; + + ChannelConfig(const QString& channel, const QByteArray& config) : + m_channel(channel), + m_config(config) + { } + }; + typedef QList ChannelConfigs; + + Preset(); + + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + + void setGroup(const QString& group) { m_group = group; } + const QString& getGroup() const { return m_group; } + void setDescription(const QString& description) { m_description = description; } + const QString& getDescription() const { return m_description; } + void setCenterFrequency(const quint64 centerFrequency) { m_centerFrequency = centerFrequency; } + quint64 getCenterFrequency() const { return m_centerFrequency; } + + void setSpectrumConfig(const QByteArray& data) { m_spectrumConfig = data; } + const QByteArray& getSpectrumConfig() const { return m_spectrumConfig; } + + void setShowScope(bool value) { m_showScope = value; } + bool getShowScope() const { return m_showScope; } + + void setLayout(const QByteArray& data) { m_layout = data; } + const QByteArray& getLayout() const { return m_layout; } + + void setDCOffsetCorrection(bool value) { m_dcOffsetCorrection = value; } + bool getDCOffsetCorrection() const { return m_dcOffsetCorrection; } + + void setIQImbalanceCorrection(bool value) { m_iqImbalanceCorrection = value; } + bool getIQImbalanceCorrection() const { return m_iqImbalanceCorrection; } + + void setScopeConfig(const QByteArray& data) { m_scopeConfig = data; } + const QByteArray& getScopeConfig() const { return m_scopeConfig; } + + void clearChannels() { m_channelConfigs.clear(); } + void addChannel(const QString& channel, const QByteArray& config) { m_channelConfigs.append(ChannelConfig(channel, config)); } + int getChannelCount() const { return m_channelConfigs.count(); } + const ChannelConfig& getChannelConfig(int index) const { return m_channelConfigs.at(index); } + + void setSourceConfig(const QString& source, const QByteArray& generalConfig, const QByteArray& config) + { + m_source = source; + m_sourceGeneralConfig = generalConfig; + m_sourceConfig = config; + } + const QString& getSource() const { return m_source; } + const QByteArray& getSourceGeneralConfig() const { return m_sourceGeneralConfig; } + const QByteArray& getSourceConfig() const { return m_sourceConfig; } + +protected: + // group and preset description + QString m_group; + QString m_description; + quint64 m_centerFrequency; + + // general configuration + QByteArray m_spectrumConfig; + QByteArray m_scopeConfig; + + // dc offset and i/q imbalance correction + bool m_dcOffsetCorrection; + bool m_iqImbalanceCorrection; + + // display scope dock + bool m_showScope; + + // sample source and sample source configuration + QString m_source; + QByteArray m_sourceGeneralConfig; + QByteArray m_sourceConfig; + + // channels and configurations + ChannelConfigs m_channelConfigs; + + // screen and dock layout + QByteArray m_layout; +}; + +Q_DECLARE_METATYPE(const Preset*) + +#endif // INCLUDE_PRESET_H diff --git a/include-gpl/settings/settings.h b/include-gpl/settings/settings.h new file mode 100644 index 000000000..a6cf04fa5 --- /dev/null +++ b/include-gpl/settings/settings.h @@ -0,0 +1,32 @@ +#ifndef INCLUDE_SETTINGS_H +#define INCLUDE_SETTINGS_H + +#include +#include "preferences.h" +#include "preset.h" + +class Settings { +public: + Settings(); + ~Settings(); + + void load(); + void save() const; + + void resetToDefaults(); + + Preset* newPreset(const QString& group, const QString& description); + void deletePreset(const Preset* preset); + int getPresetCount() const { return m_presets.count(); } + const Preset* getPreset(int index) const { return m_presets[index]; } + + Preset* getCurrent() { return &m_current; } + +protected: + Preferences m_preferences; + Preset m_current; + typedef QList Presets; + Presets m_presets; +}; + +#endif // INCLUDE_SETTINGS_H diff --git a/include/dsp/channelmarker.h b/include/dsp/channelmarker.h new file mode 100644 index 000000000..df9c1730c --- /dev/null +++ b/include/dsp/channelmarker.h @@ -0,0 +1,43 @@ +#ifndef INCLUDE_CHANNELMARKER_H +#define INCLUDE_CHANNELMARKER_H + +#include +#include +#include "util/export.h" + +class SDRANGELOVE_API ChannelMarker : public QObject { + Q_OBJECT + +public: + ChannelMarker(QObject* parent = NULL); + + void setTitle(const QString& title); + const QString& getTitle() const { return m_title; } + + void setCenterFrequency(int centerFrequency); + int getCenterFrequency() const { return m_centerFrequency; } + + void setBandwidth(int bandwidth); + int getBandwidth() const { return m_bandwidth; } + + void setVisible(bool visible); + bool getVisible() const { return m_visible; } + + void setColor(const QColor& color); + const QColor& getColor() const { return m_color; } + +protected: + static QRgb m_colorTable[]; + static int m_nextColor; + + QString m_title; + int m_centerFrequency; + int m_bandwidth; + bool m_visible; + QColor m_color; + +signals: + void changed(); +}; + +#endif // INCLUDE_CHANNELMARKER_H diff --git a/include/dsp/dsptypes.h b/include/dsp/dsptypes.h new file mode 100644 index 000000000..b6bbf6710 --- /dev/null +++ b/include/dsp/dsptypes.h @@ -0,0 +1,54 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_DSPTYPES_H +#define INCLUDE_DSPTYPES_H + +#include +#include +#include + +typedef float Real; +typedef std::complex Complex; + +typedef qint16 FixReal; + +#pragma pack(push, 1) +struct Sample { + Sample() {} + Sample(FixReal real) : m_real(real), m_imag(0) {} + Sample(FixReal real, FixReal imag) : m_real(real), m_imag(imag) {} + Sample(const Sample& other) : m_real(other.m_real), m_imag(other.m_imag) {} + Sample& operator=(const Sample& other) { m_real = other.m_real; m_imag = other.m_imag; return *this; } + + Sample& operator+=(const Sample& other) { m_real += other.m_real; m_imag += other.m_imag; return *this; } + Sample& operator-=(const Sample& other) { m_real -= other.m_real; m_imag -= other.m_imag; return *this; } + + void setReal(FixReal v) { m_real = v; } + void setImag(FixReal v) { m_imag = v; } + + FixReal real() const { return m_real; } + FixReal imag() const { return m_imag; } + + FixReal m_real; + FixReal m_imag; +}; +#pragma pack(pop) + +typedef std::vector SampleVector; + +#endif // INCLUDE_DSPTYPES_H diff --git a/include/dsp/kissfft.h b/include/dsp/kissfft.h new file mode 100644 index 000000000..ba1256c30 --- /dev/null +++ b/include/dsp/kissfft.h @@ -0,0 +1,391 @@ +#ifndef INCLUDE_KISSFFT_H +#define INCLUDE_KISSFFT_H + +#include +#include + +/* +Copyright (c) 2003-2010 Mark Borgerding + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the author nor the names of any contributors may be used to + endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. +*/ + +namespace kissfft_utils { + + template + struct traits { + typedef T_scalar scalar_type; + typedef T_complex cpx_type; + void fill_twiddles(std::complex* dst, int nfft, bool inverse) + { + T_scalar phinc = (inverse ? 2 : -2) * acos((T_scalar)-1) / nfft; + for(int i = 0; i < nfft; ++i) + dst[i] = exp(std::complex(0, i * phinc)); + } + + void prepare(std::vector >& dst, int nfft, bool inverse, std::vector& stageRadix, std::vector& stageRemainder) + { + _twiddles.resize(nfft); + fill_twiddles(&_twiddles[0], nfft, inverse); + dst = _twiddles; + + //factorize + //start factoring out 4's, then 2's, then 3,5,7,9,... + int n = nfft; + int p = 4; + do { + while(n % p) { + switch(p) { + case 4: + p = 2; + break; + case 2: + p = 3; + break; + default: + p += 2; + break; + } + if(p * p > n) + p = n;// no more factors + } + n /= p; + stageRadix.push_back(p); + stageRemainder.push_back(n); + } while(n > 1); + } + std::vector _twiddles; + + const cpx_type twiddle(int i) + { + return _twiddles[i]; + } + }; + +} // namespace + +template > +class kissfft { +public: + typedef T_traits traits_type; + typedef typename traits_type::scalar_type scalar_type; + typedef typename traits_type::cpx_type cpx_type; + + kissfft() + { + } + + kissfft(int nfft, bool inverse, const traits_type & traits = traits_type()) : + _nfft(nfft), _inverse(inverse), _traits(traits) + { + _traits.prepare(_twiddles, _nfft, _inverse, _stageRadix, _stageRemainder); + } + + void configure(int nfft, bool inverse, const traits_type & traits = traits_type()) + { + _twiddles.clear(); + _stageRadix.clear(); + _stageRemainder.clear(); + + _nfft = nfft; + _inverse = inverse; + _traits = traits; + _traits.prepare(_twiddles, _nfft, _inverse, _stageRadix, _stageRemainder); + } + + void transform(const cpx_type* src, cpx_type* dst) + { + kf_work(0, dst, src, 1, 1); + } + +private: + void kf_work(int stage, cpx_type* Fout, const cpx_type* f, size_t fstride, size_t in_stride) + { + int p = _stageRadix[stage]; + int m = _stageRemainder[stage]; + cpx_type * Fout_beg = Fout; + cpx_type * Fout_end = Fout + p * m; + + if(m == 1) { + do { + *Fout = *f; + f += fstride * in_stride; + } while(++Fout != Fout_end); + } else { + do { + // recursive call: + // DFT of size m*p performed by doing + // p instances of smaller DFTs of size m, + // each one takes a decimated version of the input + kf_work(stage + 1, Fout, f, fstride * p, in_stride); + f += fstride * in_stride; + } while((Fout += m) != Fout_end); + } + + Fout = Fout_beg; + + // recombine the p smaller DFTs + switch(p) { + case 2: + kf_bfly2(Fout, fstride, m); + break; + case 3: + kf_bfly3(Fout, fstride, m); + break; + case 4: + kf_bfly4(Fout, fstride, m); + break; + case 5: + kf_bfly5(Fout, fstride, m); + break; + default: + kf_bfly_generic(Fout, fstride, m, p); + break; + } + } + + // these were #define macros in the original kiss_fft + void C_ADD(cpx_type& c, const cpx_type& a, const cpx_type& b) + { + c = a + b; + } + void C_MUL(cpx_type& c, const cpx_type& a, const cpx_type& b) + { + //c = a * b; + c = cpx_type(a.real() * b.real() - a.imag() * b.imag(), a.real() * b.imag() + a.imag() * b.real()); + } + void C_SUB(cpx_type& c, const cpx_type& a, const cpx_type& b) + { + c = a - b; + } + void C_ADDTO(cpx_type& c, const cpx_type& a) + { + c += a; + } + void C_FIXDIV(cpx_type&, int) + { + } // NO-OP for float types + scalar_type S_MUL(const scalar_type& a, const scalar_type& b) + { + return a * b; + } + scalar_type HALF_OF(const scalar_type& a) + { + return a * .5; + } + void C_MULBYSCALAR(cpx_type& c, const scalar_type& a) + { + c *= a; + } + + void kf_bfly2(cpx_type* Fout, const size_t fstride, int m) + { + for(int k = 0; k < m; ++k) { + //cpx_type t = Fout[m + k] * _traits.twiddle(k * fstride); + cpx_type t; + C_MUL(t, Fout[m + k], _traits.twiddle(k * fstride)); + Fout[m + k] = Fout[k] - t; + Fout[k] += t; + } + } + + void kf_bfly4(cpx_type* Fout, const size_t fstride, const size_t m) + { + cpx_type scratch[7]; + int negative_if_inverse = _inverse * -2 + 1; + for(size_t k = 0; k < m; ++k) { + //scratch[0] = Fout[k + m] * _traits.twiddle(k * fstride); + C_MUL(scratch[0], Fout[k + m], _traits.twiddle(k * fstride)); + C_MUL(scratch[1], Fout[k + 2 * m], _traits.twiddle(k * fstride * 2)); + C_MUL(scratch[2], Fout[k + 3 * m], _traits.twiddle(k * fstride * 3)); + scratch[5] = Fout[k] - scratch[1]; + + Fout[k] += scratch[1]; + scratch[3] = scratch[0] + scratch[2]; + scratch[4] = scratch[0] - scratch[2]; + scratch[4] = cpx_type(scratch[4].imag() * negative_if_inverse, -scratch[4].real() * negative_if_inverse); + + Fout[k + 2 * m] = Fout[k] - scratch[3]; + Fout[k] += scratch[3]; + Fout[k + m] = scratch[5] + scratch[4]; + Fout[k + 3 * m] = scratch[5] - scratch[4]; + } + } + + void kf_bfly3(cpx_type* Fout, const size_t fstride, const size_t m) + { + size_t k = m; + const size_t m2 = 2 * m; + cpx_type* tw1; + cpx_type* tw2; + cpx_type scratch[5]; + cpx_type epi3; + epi3 = _twiddles[fstride * m]; + tw1 = tw2 = &_twiddles[0]; + + do { + C_FIXDIV(*Fout, 3); + C_FIXDIV(Fout[m], 3); + C_FIXDIV(Fout[m2], 3); + + C_MUL(scratch[1], Fout[m], *tw1); + C_MUL(scratch[2], Fout[m2], *tw2); + + C_ADD(scratch[3], scratch[1], scratch[2]); + C_SUB(scratch[0], scratch[1], scratch[2]); + tw1 += fstride; + tw2 += fstride * 2; + + Fout[m] = cpx_type(Fout->real() - HALF_OF(scratch[3].real()), Fout->imag() - HALF_OF(scratch[3].imag())); + + C_MULBYSCALAR(scratch[0], epi3.imag()); + + C_ADDTO(*Fout, scratch[3]); + + Fout[m2] = cpx_type(Fout[m].real() + scratch[0].imag(), Fout[m].imag() - scratch[0].real()); + + C_ADDTO(Fout[m], cpx_type(-scratch[0].imag(), scratch[0].real())); + ++Fout; + } while(--k); + } + + void kf_bfly5(cpx_type* Fout, const size_t fstride, const size_t m) + { + cpx_type* Fout0; + cpx_type* Fout1; + cpx_type* Fout2; + cpx_type* Fout3; + cpx_type* Fout4; + size_t u; + cpx_type scratch[13]; + cpx_type* twiddles = &_twiddles[0]; + cpx_type* tw; + cpx_type ya, yb; + ya = twiddles[fstride * m]; + yb = twiddles[fstride * 2 * m]; + + Fout0 = Fout; + Fout1 = Fout0 + m; + Fout2 = Fout0 + 2 * m; + Fout3 = Fout0 + 3 * m; + Fout4 = Fout0 + 4 * m; + + tw = twiddles; + for(u = 0; u < m; ++u) { + C_FIXDIV(*Fout0, 5); + C_FIXDIV(*Fout1, 5); + C_FIXDIV(*Fout2, 5); + C_FIXDIV(*Fout3, 5); + C_FIXDIV(*Fout4, 5); + scratch[0] = *Fout0; + + C_MUL(scratch[1], *Fout1, tw[u * fstride]); + C_MUL(scratch[2], *Fout2, tw[2 * u * fstride]); + C_MUL(scratch[3], *Fout3, tw[3 * u * fstride]); + C_MUL(scratch[4], *Fout4, tw[4 * u * fstride]); + + C_ADD(scratch[7], scratch[1], scratch[4]); + C_SUB(scratch[10], scratch[1], scratch[4]); + C_ADD(scratch[8], scratch[2], scratch[3]); + C_SUB(scratch[9], scratch[2], scratch[3]); + + C_ADDTO(*Fout0, scratch[7]); + C_ADDTO(*Fout0, scratch[8]); + + scratch[5] = scratch[0] + cpx_type(S_MUL(scratch[7].real(), ya.real()) + S_MUL(scratch[8].real(), yb.real()), S_MUL(scratch[7].imag(), ya.real()) + + S_MUL(scratch[8].imag(), yb.real())); + + scratch[6] = cpx_type(S_MUL(scratch[10].imag(), ya.imag()) + S_MUL(scratch[9].imag(), yb.imag()), -S_MUL(scratch[10].real(), ya.imag()) - S_MUL( + scratch[9].real(), yb.imag())); + + C_SUB(*Fout1, scratch[5], scratch[6]); + C_ADD(*Fout4, scratch[5], scratch[6]); + + scratch[11] = scratch[0] + cpx_type(S_MUL(scratch[7].real(), yb.real()) + S_MUL(scratch[8].real(), ya.real()), S_MUL(scratch[7].imag(), yb.real()) + + S_MUL(scratch[8].imag(), ya.real())); + + scratch[12] = cpx_type(-S_MUL(scratch[10].imag(), yb.imag()) + S_MUL(scratch[9].imag(), ya.imag()), S_MUL(scratch[10].real(), yb.imag()) - S_MUL( + scratch[9].real(), ya.imag())); + + C_ADD(*Fout2, scratch[11], scratch[12]); + C_SUB(*Fout3, scratch[11], scratch[12]); + + ++Fout0; + ++Fout1; + ++Fout2; + ++Fout3; + ++Fout4; + } + } + + /* perform the butterfly for one stage of a mixed radix FFT */ + void kf_bfly_generic(cpx_type* Fout, const size_t fstride, int m, int p) + { + int u; + int k; + int q1; + int q; + cpx_type* twiddles = &_twiddles[0]; + cpx_type t; + int Norig = _nfft; + cpx_type* scratchbuf = new cpx_type[p]; + + for(u = 0; u < m; ++u) { + k = u; + for(q1 = 0; q1 < p; ++q1) { + scratchbuf[q1] = Fout[k]; + C_FIXDIV(scratchbuf[q1], p); + k += m; + } + + k = u; + for(q1 = 0; q1 < p; ++q1) { + int twidx = 0; + Fout[k] = scratchbuf[0]; + for(q = 1; q < p; ++q) { + twidx += fstride * k; + if(twidx >= Norig) + twidx -= Norig; + C_MUL(t, scratchbuf[q], twiddles[twidx]); + C_ADDTO(Fout[k], t); + } + k += m; + } + } + + delete[] scratchbuf; + } + + int _nfft; + bool _inverse; + std::vector _twiddles; + std::vector _stageRadix; + std::vector _stageRemainder; + traits_type _traits; +}; +#endif diff --git a/include/dsp/samplefifo.h b/include/dsp/samplefifo.h new file mode 100644 index 000000000..6fb05a748 --- /dev/null +++ b/include/dsp/samplefifo.h @@ -0,0 +1,66 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_SAMPLEFIFO_H +#define INCLUDE_SAMPLEFIFO_H + +#include +#include +#include +#include "dsp/dsptypes.h" +#include "util/export.h" + +class SDRANGELOVE_API SampleFifo : public QObject { + Q_OBJECT + +private: + QMutex m_mutex; + QTime m_msgRateTimer; + int m_suppressed; + + SampleVector m_data; + + uint m_size; + uint m_fill; + uint m_head; + uint m_tail; + + void create(uint s); + +public: + SampleFifo(QObject* parent = NULL); + SampleFifo(int size, QObject* parent = NULL); + ~SampleFifo(); + + bool setSize(int size); + inline uint fill() const { return m_fill; } + + uint write(const quint8* data, uint count); + uint write(SampleVector::const_iterator begin, SampleVector::const_iterator end); + + uint read(SampleVector::iterator begin, SampleVector::iterator end); + + uint readBegin(uint count, + SampleVector::iterator* part1Begin, SampleVector::iterator* part1End, + SampleVector::iterator* part2Begin, SampleVector::iterator* part2End); + uint readCommit(uint count); + +signals: + void dataReady(); +}; + +#endif // INCLUDE_SAMPLEFIFO_H diff --git a/include/dsp/samplesink.h b/include/dsp/samplesink.h new file mode 100644 index 000000000..1c8fb3237 --- /dev/null +++ b/include/dsp/samplesink.h @@ -0,0 +1,21 @@ +#ifndef INCLUDE_SAMPLESINK_H +#define INCLUDE_SAMPLESINK_H + +#include +#include "dsptypes.h" +#include "util/export.h" + +class Message; + +class SDRANGELOVE_API SampleSink : public QObject { +public: + SampleSink(); + virtual ~SampleSink(); + + virtual void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst) = 0; + virtual void start() = 0; + virtual void stop() = 0; + virtual bool handleMessage(Message* cmd) = 0; +}; + +#endif // INCLUDE_SAMPLESINK_H diff --git a/include/dsp/samplesource/samplesource.h b/include/dsp/samplesource/samplesource.h new file mode 100644 index 000000000..1e50c993a --- /dev/null +++ b/include/dsp/samplesource/samplesource.h @@ -0,0 +1,61 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_SAMPLESOURCE_H +#define INCLUDE_SAMPLESOURCE_H + +#include +#include "dsp/samplefifo.h" +#include "util/message.h" +#include "util/export.h" + +class PluginGUI; +class MessageQueue; + +class SDRANGELOVE_API SampleSource { +public: + struct SDRANGELOVE_API GeneralSettings { + quint64 m_centerFrequency; + + GeneralSettings(); + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + }; + + SampleSource(MessageQueue* guiMessageQueue); + virtual ~SampleSource(); + + virtual bool startInput(int device) = 0; + virtual void stopInput() = 0; + + virtual const QString& getDeviceDescription() const = 0; + virtual int getSampleRate() const = 0; + virtual quint64 getCenterFrequency() const = 0; + + virtual bool handleMessage(Message* message) = 0; + + SampleFifo* getSampleFifo() { return &m_sampleFifo; } + +protected: + SampleFifo m_sampleFifo; + MessageQueue* m_guiMessageQueue; + + GeneralSettings m_generalSettings; +}; + +#endif // INCLUDE_SAMPLESOURCE_H diff --git a/include/dsp/threadedsamplesink.h b/include/dsp/threadedsamplesink.h new file mode 100644 index 000000000..1e470fe1b --- /dev/null +++ b/include/dsp/threadedsamplesink.h @@ -0,0 +1,41 @@ +#ifndef INCLUDE_THREADEDSAMPLESINK_H +#define INCLUDE_THREADEDSAMPLESINK_H + +#include +#include "samplesink.h" +#include "dsp/samplefifo.h" +#include "util/messagequeue.h" +#include "util/export.h" + +class QThread; +class SampleSink; + +class SDRANGELOVE_API ThreadedSampleSink : public SampleSink { + Q_OBJECT + +public: + ThreadedSampleSink(SampleSink* sampleSink); + virtual ~ThreadedSampleSink(); + + MessageQueue* getMessageQueue() { return &m_messageQueue; } + + void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst); + void start(); + void stop(); + bool handleMessage(Message* cmd); + +protected: + QMutex m_mutex; + QThread* m_thread; + MessageQueue m_messageQueue; + SampleFifo m_sampleFifo; + SampleSink* m_sampleSink; + +protected slots: + void handleData(); + void handleMessages(); + void threadStarted(); + void threadFinished(); +}; + +#endif // INCLUDE_THREADEDSAMPLESINK_H diff --git a/include/gui/basicchannelsettingswidget.h b/include/gui/basicchannelsettingswidget.h new file mode 100644 index 000000000..8782bbaca --- /dev/null +++ b/include/gui/basicchannelsettingswidget.h @@ -0,0 +1,34 @@ +#ifndef INCLUDE_BASICCHANNELSETTINGSWIDGET_H +#define INCLUDE_BASICCHANNELSETTINGSWIDGET_H + +#include +#include "util/export.h" + +namespace Ui { + class BasicChannelSettingsWidget; +} + +class ChannelMarker; + +class SDRANGELOVE_API BasicChannelSettingsWidget : public QWidget { + Q_OBJECT + +public: + explicit BasicChannelSettingsWidget(ChannelMarker* marker, QWidget* parent = NULL); + ~BasicChannelSettingsWidget(); + +private slots: + void on_title_textChanged(const QString& text); + void on_colorBtn_clicked(); + void on_red_valueChanged(int value); + void on_green_valueChanged(int value); + void on_blue_valueChanged(int value); + +private: + Ui::BasicChannelSettingsWidget* ui; + ChannelMarker* m_channelMarker; + + void paintColor(); +}; + +#endif // INCLUDE_BASICCHANNELSETTINGSWIDGET_H diff --git a/include/gui/rollupwidget.h b/include/gui/rollupwidget.h new file mode 100644 index 000000000..d34085c06 --- /dev/null +++ b/include/gui/rollupwidget.h @@ -0,0 +1,42 @@ +#ifndef INCLUDE_ROLLUPWIDGET_H +#define INCLUDE_ROLLUPWIDGET_H + +#include +#include "util/export.h" + +class SDRANGELOVE_API RollupWidget : public QWidget { + Q_OBJECT + +public: + RollupWidget(QWidget* parent = NULL); + + QByteArray saveState(int version = 0) const; + bool restoreState(const QByteArray& state, int version = 0); + + void setTitleColor(const QColor& c); + +signals: + void widgetRolled(QWidget* widget, bool rollDown); + void menuDoubleClickEvent(); + +protected: + enum { + VersionMarker = 0xff + }; + + QColor m_titleColor; + + int arrangeRollups(); + + void paintEvent(QPaintEvent*); + int paintRollup(QWidget* rollup, int pos, QPainter* p, bool last, const QColor& frame); + + void resizeEvent(QResizeEvent* size); + void mousePressEvent(QMouseEvent* event); + void mouseDoubleClickEvent(QMouseEvent* event); + + bool event(QEvent* event); + bool eventFilter(QObject* object, QEvent* event); +}; + +#endif // INCLUDE_ROLLUPWIDGET_H diff --git a/include/plugin/pluginapi.h b/include/plugin/pluginapi.h new file mode 100644 index 000000000..d37a6b796 --- /dev/null +++ b/include/plugin/pluginapi.h @@ -0,0 +1,60 @@ +#ifndef INCLUDE_PLUGINAPI_H +#define INCLUDE_PLUGINAPI_H + +#include +#include "util/export.h" + +class QDockWidget; +class QAction; + +class PluginManager; +class PluginInterface; +class SampleSource; +class SampleSink; +class DSPEngine; +class AudioFifo; +class MessageQueue; +class MainWindow; +class ChannelMarker; +class PluginGUI; + +class SDRANGELOVE_API PluginAPI : public QObject { + Q_OBJECT + +public: + // MainWindow access + QDockWidget* createMainWindowDock(Qt::DockWidgetArea dockWidgetArea, const QString& title); + MessageQueue* getMainWindowMessageQueue(); + void setInputGUI(QWidget* inputGUI); + + // Channel stuff + void registerChannel(const QString& channelName, PluginInterface* plugin, QAction* action); + void registerChannelInstance(const QString& channelName, PluginGUI* pluginGUI); + void addChannelRollup(QWidget* pluginGUI); + void removeChannelInstance(PluginGUI* pluginGUI); + + void addChannelMarker(ChannelMarker* channelMarker); + void removeChannelMarker(ChannelMarker* channelMarker); + + // DSPEngine access + void setSampleSource(SampleSource* sampleSource); + void addSampleSink(SampleSink* sampleSink); + void removeSampleSink(SampleSink* sampleSink); + MessageQueue* getDSPEngineMessageQueue(); + void addAudioSource(AudioFifo* audioFifo); + void removeAudioSource(AudioFifo* audioFifo); + + // Sample Source stuff + void registerSampleSource(const QString& sourceName, PluginInterface* plugin); + +protected: + PluginManager* m_pluginManager; + MainWindow* m_mainWindow; + DSPEngine* m_dspEngine; + + PluginAPI(PluginManager* pluginManager, MainWindow* mainWindow, DSPEngine* dspEngine); + + friend class PluginManager; +}; + +#endif // INCLUDE_PLUGINAPI_H diff --git a/include/plugin/plugingui.h b/include/plugin/plugingui.h new file mode 100644 index 000000000..586e44678 --- /dev/null +++ b/include/plugin/plugingui.h @@ -0,0 +1,28 @@ +#ifndef INCLUDE_PLUGINGUI_H +#define INCLUDE_PLUGINGUI_H + +#include +#include "util/export.h" + +class Message; + +class SDRANGELOVE_API PluginGUI { +public: + PluginGUI() { }; + virtual void destroy() = 0; + + virtual void setName(const QString& name) = 0; + + virtual void resetToDefaults() = 0; + + virtual QByteArray serializeGeneral() const; + virtual bool deserializeGeneral(const QByteArray& data); + virtual quint64 getCenterFrequency() const; + + virtual QByteArray serialize() const = 0; + virtual bool deserialize(const QByteArray& data) = 0; + + virtual bool handleMessage(Message* message) = 0; +}; + +#endif // INCLUDE_PLUGINGUI_H diff --git a/include/plugin/plugininterface.h b/include/plugin/plugininterface.h new file mode 100644 index 000000000..edf3f47d9 --- /dev/null +++ b/include/plugin/plugininterface.h @@ -0,0 +1,48 @@ +#ifndef INCLUDE_PLUGININTERFACE_H +#define INCLUDE_PLUGININTERFACE_H + +#include +#include + +struct PluginDescriptor { + // general plugin description + const QString displayedName; + const QString version; + const QString copyright; + const QString website; + bool licenseIsGPL; + const QString sourceCodeURL; +}; + +class PluginAPI; +class PluginGUI; + +class PluginInterface { +public: + struct SampleSourceDevice { + QString displayedName; + QString name; + QByteArray address; + + SampleSourceDevice(const QString& _displayedName, const QString& _name, const QByteArray& _address) : + displayedName(_displayedName), + name(_name), + address(_address) + { } + }; + typedef QList SampleSourceDevices; + + virtual ~PluginInterface() { }; + + virtual const PluginDescriptor& getPluginDescriptor() const = 0; + virtual void initPlugin(PluginAPI* pluginAPI) = 0; + + virtual PluginGUI* createChannel(const QString& channelName) { return NULL; } + + virtual SampleSourceDevices enumSampleSources() { return SampleSourceDevices(); } + virtual PluginGUI* createSampleSource(const QString& sourceName, const QByteArray& address) { return NULL; } +}; + +Q_DECLARE_INTERFACE(PluginInterface, "de.maintech.SDRangelove.PluginInterface/0.1"); + +#endif // INCLUDE_PLUGININTERFACE_H diff --git a/include/util/export.h b/include/util/export.h new file mode 100644 index 000000000..2b5f36dbf --- /dev/null +++ b/include/util/export.h @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2012 by Hoernchen + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __SDRANGELOVE_EXPORT_H +#define __SDRANGELOVE_EXPORT_H + +#if defined __GNUC__ +# if __GNUC__ >= 4 +# define __SDR_EXPORT __attribute__((visibility("default"))) +# define __SDR_IMPORT __attribute__((visibility("default"))) +# else +# define __SDR_EXPORT +# define __SDR_IMPORT +# endif +#elif _MSC_VER +# define __SDR_EXPORT __declspec(dllexport) +# define __SDR_IMPORT __declspec(dllimport) +#else +# define __SDR_EXPORT +# define __SDR_IMPORT +#endif + +#ifndef sdrangelove_STATIC +# ifdef sdrangelove_EXPORTS +# define SDRANGELOVE_API __SDR_EXPORT +# else +# define SDRANGELOVE_API __SDR_IMPORT +# endif +#else +#define SDRANGELOVE_API +#endif +#endif /* __SDRANGELOVE_EXPORT_H */ diff --git a/include/util/message.h b/include/util/message.h new file mode 100644 index 000000000..8cf06b2a6 --- /dev/null +++ b/include/util/message.h @@ -0,0 +1,58 @@ +#ifndef INCLUDE_MESSAGE_H +#define INCLUDE_MESSAGE_H + +#include +#include +#include "util/export.h" + +class MessageQueue; +class QWaitCondition; +class QMutex; + +class SDRANGELOVE_API Message { +public: + Message(); + virtual ~Message(); + + virtual const char* getIdentifier() const; + virtual bool matchIdentifier(const char* identifier) const; + static bool match(Message* message); + + void* getDestination() const { return m_destination; } + + void submit(MessageQueue* queue, void* destination = NULL); + int execute(MessageQueue* queue, void* destination = NULL); + + void completed(int result = 0); + +protected: + // addressing + static const char* m_identifier; + void* m_destination; + + // stuff for synchronous messages + bool m_synchronous; + QWaitCondition* m_waitCondition; + QMutex* m_mutex; + QAtomicInt m_complete; + int m_result; +}; + +#define MESSAGE_CLASS_DECLARATION \ + public: \ + const char* getIdentifier() const; \ + bool matchIdentifier(const char* identifier) const; \ + static bool match(Message* message); \ + protected: \ + static const char* m_identifier; \ + private: + +#define MESSAGE_CLASS_DEFINITION(Name, BaseClass) \ + const char* Name::m_identifier = #Name; \ + const char* Name::getIdentifier() const { return m_identifier; } \ + bool Name::matchIdentifier(const char* identifier) const {\ + return (m_identifier == identifier) ? true : BaseClass::matchIdentifier(identifier); \ + } \ + bool Name::match(Message* message) { return message->matchIdentifier(m_identifier); } + +#endif // INCLUDE_MESSAGE_H diff --git a/include/util/messagequeue.h b/include/util/messagequeue.h new file mode 100644 index 000000000..737d2b3bf --- /dev/null +++ b/include/util/messagequeue.h @@ -0,0 +1,31 @@ +#ifndef INCLUDE_MESSAGEQUEUE_H +#define INCLUDE_MESSAGEQUEUE_H + +#include +#include +#include "spinlock.h" +#include "util/export.h" + +class Message; + +class SDRANGELOVE_API MessageQueue : public QObject { + Q_OBJECT + +public: + MessageQueue(QObject* parent = NULL); + ~MessageQueue(); + + void submit(Message* message); + Message* accept(); + + int countPending(); + +signals: + void messageEnqueued(); + +private: + Spinlock m_lock; + QQueue m_queue; +}; + +#endif // INCLUDE_MESSAGEQUEUE_H diff --git a/include/util/miniz.h b/include/util/miniz.h new file mode 100644 index 000000000..0882c06e1 --- /dev/null +++ b/include/util/miniz.h @@ -0,0 +1,7 @@ +#ifndef INCLUDE_MINIZ_H +#define INCLUDE_MINIZ_H + +#define MINIZ_HEADER_FILE_ONLY +#include "../../sdrapp/util/miniz.cpp" + +#endif // INCLUDE_MINIZ_H diff --git a/include/util/simpleserializer.h b/include/util/simpleserializer.h new file mode 100644 index 000000000..1388aa549 --- /dev/null +++ b/include/util/simpleserializer.h @@ -0,0 +1,112 @@ +#ifndef INCLUDE_SIMPLESERIALIZER_H +#define INCLUDE_SIMPLESERIALIZER_H + +#include +#include +#include "dsp/dsptypes.h" +#include "util/export.h" + +class SDRANGELOVE_API SimpleSerializer { +public: + SimpleSerializer(quint32 version); + + void writeS32(quint32 id, qint32 value); + void writeU32(quint32 id, quint32 value); + void writeS64(quint32 id, qint64 value); + void writeU64(quint32 id, quint64 value); + void writeFloat(quint32 id, float value); + void writeDouble(quint32 id, double value); + void writeReal(quint32 id, Real value) + { + if(sizeof(Real) == 4) + writeFloat(id, value); + else writeDouble(id, value); + } + void writeBool(quint32 id, bool value); + void writeString(quint32 id, const QString& value); + void writeBlob(quint32 id, const QByteArray& value); + + const QByteArray& final(); + +protected: + enum Type { + TSigned32 = 0, + TUnsigned32 = 1, + TSigned64 = 2, + TUnsigned64 = 3, + TFloat = 4, + TDouble = 5, + TBool = 6, + TString = 7, + TBlob = 8, + TVersion = 9 + }; + + QByteArray m_data; + bool m_finalized; + + bool writeTag(Type type, quint32 id, quint32 length); +}; + +class SDRANGELOVE_API SimpleDeserializer { +public: + SimpleDeserializer(const QByteArray& data); + + bool readS32(quint32 id, qint32* result, qint32 def = 0) const; + bool readU32(quint32 id, quint32* result, quint32 def = 0) const; + bool readS64(quint32 id, qint64* result, qint64 def = 0) const; + bool readU64(quint32 id, quint64* result, quint64 def = 0) const; + bool readFloat(quint32 id, float* result, float def = 0) const; + bool readDouble(quint32 id, double* result, double def = 0) const; + bool readReal(quint32 id, Real* result, Real def = 0) const; + bool readBool(quint32 id, bool* result, bool def = false) const; + bool readString(quint32 id, QString* result, const QString& def = QString::null) const; + bool readBlob(quint32 id, QByteArray* result, const QByteArray& def = QByteArray()) const; + + bool isValid() const { return m_valid; } + quint32 getVersion() const { return m_version; } + void dump() const; + +private: + enum Type { + TSigned32 = 0, + TUnsigned32 = 1, + TSigned64 = 2, + TUnsigned64 = 3, + TFloat = 4, + TDouble = 5, + TBool = 6, + TString = 7, + TBlob = 8, + TVersion = 9 + }; + + struct Element { + Type type; + quint32 ofs; + quint32 length; + + Element(Type _type, quint32 _ofs, quint32 _length) : + type(_type), + ofs(_ofs), + length(_length) + { } + }; + typedef QMap Elements; + + QByteArray m_data; + bool m_valid; + Elements m_elements; + quint32 m_version; + + bool parseAll(); + bool readTag(uint* readOfs, uint readEnd, Type* type, quint32* id, quint32* length) const; + quint8 readByte(uint* readOfs) const + { + quint8 res = m_data[*readOfs]; + (*readOfs)++; + return res; + } +}; + +#endif // INCLUDE_SIMPLESERIALIZER_H diff --git a/include/util/spinlock.h b/include/util/spinlock.h new file mode 100644 index 000000000..78af0b61a --- /dev/null +++ b/include/util/spinlock.h @@ -0,0 +1,39 @@ +#ifndef INCLUDE_SPINLOCK_H +#define INCLUDE_SPINLOCK_H + +#include + +class Spinlock { +public: + void lock() + { + while(!m_atomic.testAndSetAcquire(0, 1)) ; + } + + void unlock() + { + while(!m_atomic.testAndSetRelease(1, 0)) ; + } + +protected: + QAtomicInt m_atomic; +}; + +class SpinlockHolder { +public: + SpinlockHolder(Spinlock* spinlock) : + m_spinlock(spinlock) + { + m_spinlock->lock(); + } + + ~SpinlockHolder() + { + m_spinlock->unlock(); + } + +protected: + Spinlock* m_spinlock; +}; + +#endif // INCLUDE_SPINLOCK_H diff --git a/main.cpp b/main.cpp new file mode 100644 index 000000000..ce305f514 --- /dev/null +++ b/main.cpp @@ -0,0 +1,101 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include +#include "mainwindow.h" + +static int runQtApplication(int argc, char* argv[]) +{ + QApplication a(argc, argv); +/* + QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); +*/ + QCoreApplication::setOrganizationName("osmocom"); + QCoreApplication::setApplicationName("SDRangelove"); + +#if 1 + qApp->setStyle(QStyleFactory::create("fusion")); + + QPalette palette; + palette.setColor(QPalette::Window, QColor(53,53,53)); + palette.setColor(QPalette::WindowText, Qt::white); + palette.setColor(QPalette::Base, QColor(25,25,25)); + palette.setColor(QPalette::AlternateBase, QColor(53,53,53)); + palette.setColor(QPalette::ToolTipBase, Qt::white); + palette.setColor(QPalette::ToolTipText, Qt::black); + palette.setColor(QPalette::Text, Qt::white); + palette.setColor(QPalette::Button, QColor(0x40, 0x40, 0x40)); + palette.setColor(QPalette::ButtonText, Qt::white); + palette.setColor(QPalette::BrightText, Qt::red); + + palette.setColor(QPalette::Light, QColor(53,53,53).lighter(125).lighter()); + palette.setColor(QPalette::Mid, QColor(53,53,53).lighter(125)); + palette.setColor(QPalette::Dark, QColor(53,53,53).lighter(125).darker()); + + palette.setColor(QPalette::Link, QColor(0,0xa0,0xa0)); + palette.setColor(QPalette::LinkVisited, QColor(0,0xa0,0xa0).lighter()); + palette.setColor(QPalette::Highlight, QColor(0xff, 0x8c, 0x00)); + palette.setColor(QPalette::HighlightedText, Qt::black); + qApp->setPalette(palette); + +#if 0 + if(QFontDatabase::addApplicationFont("/tmp/Cuprum.otf") >= 0) { + QFont font("CuprumFFU"); + font.setPointSize(10); + qApp->setFont(font); + } +#endif +#if 0 + if(QFontDatabase::addApplicationFont("/tmp/PTN57F.ttf") >= 0) { + QFont font("PT Sans Narrow"); + font.setPointSize(10); + qApp->setFont(font); + } +#endif +#if 0 + if(QFontDatabase::addApplicationFont("/tmp/PTS55F.ttf") >= 0) { + QFont font("PT Sans"); + font.setPointSize(10); + qApp->setFont(font); + } +#endif +#if 0 + { + QFont font("Ubuntu Condensed"); + font.setPointSize(10); + qApp->setFont(font); + } +#endif + +#endif + MainWindow w; + w.show(); + + return a.exec(); +} + +int main(int argc, char* argv[]) +{ + int res = runQtApplication(argc, argv); + qDebug("regular program exit"); + return res; +} diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt new file mode 100644 index 000000000..aff913366 --- /dev/null +++ b/plugins/CMakeLists.txt @@ -0,0 +1,4 @@ +project(plugins) + +add_subdirectory(channel) +add_subdirectory(samplesource) diff --git a/plugins/channel/CMakeLists.txt b/plugins/channel/CMakeLists.txt new file mode 100644 index 000000000..e59574e1b --- /dev/null +++ b/plugins/channel/CMakeLists.txt @@ -0,0 +1,5 @@ +project(demod) + +add_subdirectory(nfm) +add_subdirectory(tcpsrc) +#add_subdirectory(tetra) diff --git a/plugins/channel/nfm/CMakeLists.txt b/plugins/channel/nfm/CMakeLists.txt new file mode 100644 index 000000000..feeb89116 --- /dev/null +++ b/plugins/channel/nfm/CMakeLists.txt @@ -0,0 +1,47 @@ +project(nfm) + +set(nfm_SOURCES + nfmdemod.cpp + nfmdemodgui.cpp + nfmplugin.cpp +) + +set(nfm_HEADERS + nfmdemod.h + nfmdemodgui.h + nfmplugin.h +) + +set(nfm_FORMS + nfmdemodgui.ui +) + +include_directories( + . + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include-gpl + ${OPENGL_INCLUDE_DIR} +) + +#include(${QT_USE_FILE}) +add_definitions(${QT_DEFINITIONS}) +add_definitions(-DQT_PLUGIN) +add_definitions(-DQT_SHARED) + +#qt5_wrap_cpp(nfm_HEADERS_MOC ${nfm_HEADERS}) +qt5_wrap_ui(nfm_FORMS_HEADERS ${nfm_FORMS}) + +add_library(demodnfm SHARED + ${nfm_SOURCES} + ${nfm_HEADERS_MOC} + ${nfm_FORMS_HEADERS} +) + +target_link_libraries(demodnfm + ${QT_LIBRARIES} + ${OPENGL_LIBRARIES} + sdrbase +) + +qt5_use_modules(demodnfm Core Widgets OpenGL Multimedia) \ No newline at end of file diff --git a/plugins/channel/nfm/nfmdemod.cpp b/plugins/channel/nfm/nfmdemod.cpp new file mode 100644 index 000000000..359bf090f --- /dev/null +++ b/plugins/channel/nfm/nfmdemod.cpp @@ -0,0 +1,147 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "nfmdemod.h" +#include "audio/audiooutput.h" +#include "dsp/dspcommands.h" + +MESSAGE_CLASS_DEFINITION(NFMDemod::MsgConfigureNFMDemod, Message) + +NFMDemod::NFMDemod(AudioFifo* audioFifo, SampleSink* sampleSink) : + m_sampleSink(sampleSink), + m_audioFifo(audioFifo) +{ + m_rfBandwidth = 12500; + m_volume = 2.0; + m_squelchLevel = pow(10.0, -40.0 / 20.0); + m_sampleRate = 500000; + m_frequency = 0; + m_squelchLevel *= m_squelchLevel; + + m_nco.setFreq(m_frequency, m_sampleRate); + m_interpolator.create(16, m_sampleRate, 12500); + m_sampleDistanceRemain = (Real)m_sampleRate / 44100.0; + + m_lowpass.create(21, 44100, 3000); + + m_audioBuffer.resize(256); + m_audioBufferFill = 0; + + m_movingAverage.resize(16, 0); +} + +NFMDemod::~NFMDemod() +{ +} + +void NFMDemod::configure(MessageQueue* messageQueue, Real rfBandwidth, Real afBandwidth, Real volume, Real squelch) +{ + Message* cmd = MsgConfigureNFMDemod::create(rfBandwidth, afBandwidth, volume, squelch); + cmd->submit(messageQueue, this); +} + +void NFMDemod::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst) +{ + Complex ci; + bool consumed; + + for(SampleVector::const_iterator it = begin; it < end; ++it) { + Complex c(it->real() / 32768.0, it->imag() / 32768.0); + c *= m_nco.nextIQ(); + + consumed = false; + if(m_interpolator.interpolate(&m_sampleDistanceRemain, c, &consumed, &ci)) { + m_sampleBuffer.push_back(Sample(ci.real() * 32768.0, ci.imag() * 32768.0)); + + m_movingAverage.feed(ci.real() * ci.real() + ci.imag() * ci.imag()); + + if(m_movingAverage.average() >= m_squelchLevel) + m_squelchState = m_sampleRate / 50; + + if(m_squelchState > 0) { + m_squelchState--; + Complex d = ci * conj(m_lastSample); + m_lastSample = ci; + Real demod = atan2(d.imag(), d.real()) / M_PI; + demod = m_lowpass.filter(demod); + demod *= m_volume; + qint16 sample = demod * 32767; + + m_audioBuffer[m_audioBufferFill].l = sample; + m_audioBuffer[m_audioBufferFill].r = sample; + ++m_audioBufferFill; + if(m_audioBufferFill >= m_audioBuffer.size()) { + uint res = m_audioFifo->write((const quint8*)&m_audioBuffer[0], m_audioBufferFill, 1); + /* + if(res != m_audioBufferFill) + qDebug("lost %u samples", m_audioBufferFill - res); + */ + m_audioBufferFill = 0; + } + } + + m_sampleDistanceRemain += (Real)m_sampleRate / 44100.0; + } + } + if(m_audioFifo->write((const quint8*)&m_audioBuffer[0], m_audioBufferFill, 0) != m_audioBufferFill) + ;//qDebug("lost samples"); + m_audioBufferFill = 0; + + if(m_sampleSink != NULL) + m_sampleSink->feed(m_sampleBuffer.begin(), m_sampleBuffer.end(), firstOfBurst); + m_sampleBuffer.clear(); +} + +void NFMDemod::start() +{ + m_squelchState = 0; +} + +void NFMDemod::stop() +{ +} + +bool NFMDemod::handleMessage(Message* cmd) +{ + if(DSPSignalNotification::match(cmd)) { + DSPSignalNotification* signal = (DSPSignalNotification*)cmd; + qDebug("%d samples/sec, %lld Hz offset", signal->getSampleRate(), signal->getFrequencyOffset()); + m_sampleRate = signal->getSampleRate(); + m_nco.setFreq(-signal->getFrequencyOffset(), m_sampleRate); + m_interpolator.create(16, m_sampleRate, m_rfBandwidth / 2.1); + m_sampleDistanceRemain = m_sampleRate / 44100.0; + m_squelchState = 0; + cmd->completed(); + return true; + } else if(MsgConfigureNFMDemod::match(cmd)) { + MsgConfigureNFMDemod* cfg = (MsgConfigureNFMDemod*)cmd; + m_rfBandwidth = cfg->getRFBandwidth(); + m_interpolator.create(16, m_sampleRate, m_rfBandwidth / 2.1); + m_lowpass.create(21, 44100, cfg->getAFBandwidth()); + m_squelchLevel = pow(10.0, cfg->getSquelch() / 20.0); + m_squelchLevel *= m_squelchLevel; + m_volume = cfg->getVolume(); + cmd->completed(); + return true; + } else { + if(m_sampleSink != NULL) + return m_sampleSink->handleMessage(cmd); + else return false; + } +} diff --git a/plugins/channel/nfm/nfmdemod.h b/plugins/channel/nfm/nfmdemod.h new file mode 100644 index 000000000..a312abbb3 --- /dev/null +++ b/plugins/channel/nfm/nfmdemod.h @@ -0,0 +1,104 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_NFMDEMOD_H +#define INCLUDE_NFMDEMOD_H + +#include +#include "dsp/samplesink.h" +#include "dsp/nco.h" +#include "dsp/interpolator.h" +#include "dsp/lowpass.h" +#include "dsp/movingaverage.h" +#include "audio/audiofifo.h" +#include "util/message.h" + +class AudioFifo; + +class NFMDemod : public SampleSink { +public: + NFMDemod(AudioFifo* audioFifo, SampleSink* sampleSink); + ~NFMDemod(); + + void configure(MessageQueue* messageQueue, Real rfBandwidth, Real afBandwidth, Real volume, Real squelch); + + void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst); + void start(); + void stop(); + bool handleMessage(Message* cmd); + +private: + class MsgConfigureNFMDemod : public Message { + MESSAGE_CLASS_DECLARATION + + public: + Real getRFBandwidth() const { return m_rfBandwidth; } + Real getAFBandwidth() const { return m_afBandwidth; } + Real getVolume() const { return m_volume; } + Real getSquelch() const { return m_squelch; } + + static MsgConfigureNFMDemod* create(Real rfBandwidth, Real afBandwidth, Real volume, Real squelch) + { + return new MsgConfigureNFMDemod(rfBandwidth, afBandwidth, volume, squelch); + } + + private: + Real m_rfBandwidth; + Real m_afBandwidth; + Real m_volume; + Real m_squelch; + + MsgConfigureNFMDemod(Real rfBandwidth, Real afBandwidth, Real volume, Real squelch) : + Message(), + m_rfBandwidth(rfBandwidth), + m_afBandwidth(afBandwidth), + m_volume(volume), + m_squelch(squelch) + { } + }; + + struct AudioSample { + qint16 l; + qint16 r; + }; + typedef std::vector AudioVector; + + Real m_rfBandwidth; + Real m_volume; + Real m_squelchLevel; + int m_sampleRate; + int m_frequency; + + NCO m_nco; + Interpolator m_interpolator; + Real m_sampleDistanceRemain; + Lowpass m_lowpass; + + int m_squelchState; + + Complex m_lastSample; + MovingAverage m_movingAverage; + + AudioVector m_audioBuffer; + uint m_audioBufferFill; + AudioFifo* m_audioFifo; + + SampleSink* m_sampleSink; + SampleVector m_sampleBuffer; +}; + +#endif // INCLUDE_NFMDEMOD_H diff --git a/plugins/channel/nfm/nfmdemodgui.cpp b/plugins/channel/nfm/nfmdemodgui.cpp new file mode 100644 index 000000000..53f2de0f6 --- /dev/null +++ b/plugins/channel/nfm/nfmdemodgui.cpp @@ -0,0 +1,210 @@ +#include +#include +#include "nfmdemodgui.h" +#include "ui_nfmdemodgui.h" +#include "nfmdemodgui.h" +#include "ui_nfmdemodgui.h" +#include "dsp/threadedsamplesink.h" +#include "dsp/channelizer.h" +#include "nfmdemod.h" +#include "dsp/spectrumvis.h" +#include "gui/glspectrum.h" +#include "plugin/pluginapi.h" +#include "util/simpleserializer.h" +#include "gui/basicchannelsettingswidget.h" + +const int NFMDemodGUI::m_rfBW[] = { + 5000, 6250, 8330, 10000, 12500, 15000, 20000, 25000, 40000 +}; + +NFMDemodGUI* NFMDemodGUI::create(PluginAPI* pluginAPI) +{ + NFMDemodGUI* gui = new NFMDemodGUI(pluginAPI); + return gui; +} + +void NFMDemodGUI::destroy() +{ + delete this; +} + +void NFMDemodGUI::setName(const QString& name) +{ + setObjectName(name); +} + +void NFMDemodGUI::resetToDefaults() +{ + ui->rfBW->setValue(4); + ui->afBW->setValue(3); + ui->volume->setValue(20); + ui->squelch->setValue(-40); + ui->spectrumGUI->resetToDefaults(); + applySettings(); +} + +QByteArray NFMDemodGUI::serialize() const +{ + SimpleSerializer s(1); + s.writeS32(1, m_channelMarker->getCenterFrequency()); + s.writeS32(2, ui->rfBW->value()); + s.writeS32(3, ui->afBW->value()); + s.writeS32(4, ui->volume->value()); + s.writeS32(5, ui->squelch->value()); + s.writeBlob(6, ui->spectrumGUI->serialize()); + s.writeU32(7, m_channelMarker->getColor().rgb()); + return s.final(); +} + +bool NFMDemodGUI::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { + QByteArray bytetmp; + quint32 u32tmp; + qint32 tmp; + d.readS32(1, &tmp, 0); + m_channelMarker->setCenterFrequency(tmp); + d.readS32(2, &tmp, 4); + ui->rfBW->setValue(tmp); + d.readS32(3, &tmp, 3); + ui->afBW->setValue(tmp); + d.readS32(4, &tmp, 20); + ui->volume->setValue(tmp); + d.readS32(5, &tmp, -40); + ui->squelch->setValue(tmp); + d.readBlob(6, &bytetmp); + ui->spectrumGUI->deserialize(bytetmp); + if(d.readU32(7, &u32tmp)) + m_channelMarker->setColor(u32tmp); + applySettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +bool NFMDemodGUI::handleMessage(Message* message) +{ + return false; +} + +void NFMDemodGUI::viewChanged() +{ + applySettings(); +} + +void NFMDemodGUI::on_rfBW_valueChanged(int value) +{ + ui->rfBWText->setText(QString("%1 kHz").arg(m_rfBW[value] / 1000.0)); + m_channelMarker->setBandwidth(m_rfBW[value]); + applySettings(); +} + +void NFMDemodGUI::on_afBW_valueChanged(int value) +{ + ui->afBWText->setText(QString("%1 kHz").arg(value)); + applySettings(); +} + +void NFMDemodGUI::on_volume_valueChanged(int value) +{ + ui->volumeText->setText(QString("%1").arg(value / 10.0, 0, 'f', 1)); + applySettings(); +} + +void NFMDemodGUI::on_squelch_valueChanged(int value) +{ + ui->squelchText->setText(QString("%1 dB").arg(value)); + applySettings(); +} + + +void NFMDemodGUI::onWidgetRolled(QWidget* widget, bool rollDown) +{ + /* + if((widget == ui->spectrumContainer) && (m_nfmDemod != NULL)) + m_nfmDemod->setSpectrum(m_threadedSampleSink->getMessageQueue(), rollDown); + */ +} + +void NFMDemodGUI::onMenuDoubleClicked() +{ + if(!m_basicSettingsShown) { + m_basicSettingsShown = true; + BasicChannelSettingsWidget* bcsw = new BasicChannelSettingsWidget(m_channelMarker, this); + bcsw->show(); + } +} + +NFMDemodGUI::NFMDemodGUI(PluginAPI* pluginAPI, QWidget* parent) : + RollupWidget(parent), + ui(new Ui::NFMDemodGUI), + m_pluginAPI(pluginAPI), + m_basicSettingsShown(false) +{ + ui->setupUi(this); + setAttribute(Qt::WA_DeleteOnClose, true); + connect(this, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); + connect(this, SIGNAL(menuDoubleClickEvent()), this, SLOT(onMenuDoubleClicked())); + + m_audioFifo = new AudioFifo(4, 44100 / 4); + m_spectrumVis = new SpectrumVis(ui->glSpectrum); + m_nfmDemod = new NFMDemod(m_audioFifo, m_spectrumVis); + m_channelizer = new Channelizer(m_nfmDemod); + m_threadedSampleSink = new ThreadedSampleSink(m_channelizer); + m_pluginAPI->addAudioSource(m_audioFifo); + m_pluginAPI->addSampleSink(m_threadedSampleSink); + + ui->glSpectrum->setCenterFrequency(0); + ui->glSpectrum->setSampleRate(44100); + ui->glSpectrum->setDisplayWaterfall(true); + ui->glSpectrum->setDisplayMaxHold(true); + m_spectrumVis->configure(m_threadedSampleSink->getMessageQueue(), 64, 10, FFTWindow::BlackmanHarris); + + m_channelMarker = new ChannelMarker(this); + m_channelMarker->setColor(Qt::red); + m_channelMarker->setBandwidth(12500); + m_channelMarker->setCenterFrequency(0); + m_channelMarker->setVisible(true); + connect(m_channelMarker, SIGNAL(changed()), this, SLOT(viewChanged())); + m_pluginAPI->addChannelMarker(m_channelMarker); + + ui->spectrumGUI->setBuddies(m_threadedSampleSink->getMessageQueue(), m_spectrumVis, ui->glSpectrum); + + applySettings(); +} + +NFMDemodGUI::~NFMDemodGUI() +{ + m_pluginAPI->removeChannelInstance(this); + m_pluginAPI->removeAudioSource(m_audioFifo); + m_pluginAPI->removeSampleSink(m_threadedSampleSink); + delete m_threadedSampleSink; + delete m_channelizer; + delete m_nfmDemod; + delete m_spectrumVis; + delete m_audioFifo; + delete m_channelMarker; + delete ui; +} + +void NFMDemodGUI::applySettings() +{ + setTitleColor(m_channelMarker->getColor()); + m_channelizer->configure(m_threadedSampleSink->getMessageQueue(), + 44100, + m_channelMarker->getCenterFrequency()); + m_nfmDemod->configure(m_threadedSampleSink->getMessageQueue(), + m_rfBW[ui->rfBW->value()], + ui->afBW->value() * 1000.0, + ui->volume->value() / 10.0, + ui->squelch->value()); +} diff --git a/plugins/channel/nfm/nfmdemodgui.h b/plugins/channel/nfm/nfmdemodgui.h new file mode 100644 index 000000000..edfb80860 --- /dev/null +++ b/plugins/channel/nfm/nfmdemodgui.h @@ -0,0 +1,64 @@ +#ifndef INCLUDE_NFMDEMODGUI_H +#define INCLUDE_NFMDEMODGUI_H + +#include "gui/rollupwidget.h" +#include "plugin/plugingui.h" + +class PluginAPI; +class ChannelMarker; + +class AudioFifo; +class ThreadedSampleSink; +class Channelizer; +class NFMDemod; +class SpectrumVis; + +namespace Ui { + class NFMDemodGUI; +} + +class NFMDemodGUI : public RollupWidget, public PluginGUI { + Q_OBJECT + +public: + static NFMDemodGUI* create(PluginAPI* pluginAPI); + void destroy(); + + void setName(const QString& name); + + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + + bool handleMessage(Message* message); + +private slots: + void viewChanged(); + void on_rfBW_valueChanged(int value); + void on_afBW_valueChanged(int value); + void on_volume_valueChanged(int value); + void on_squelch_valueChanged(int value); + void onWidgetRolled(QWidget* widget, bool rollDown); + void onMenuDoubleClicked(); + +private: + Ui::NFMDemodGUI* ui; + PluginAPI* m_pluginAPI; + ChannelMarker* m_channelMarker; + bool m_basicSettingsShown; + + AudioFifo* m_audioFifo; + ThreadedSampleSink* m_threadedSampleSink; + Channelizer* m_channelizer; + NFMDemod* m_nfmDemod; + SpectrumVis* m_spectrumVis; + + static const int m_rfBW[]; + + explicit NFMDemodGUI(PluginAPI* pluginAPI, QWidget* parent = NULL); + ~NFMDemodGUI(); + + void applySettings(); +}; + +#endif // INCLUDE_NFMDEMODGUI_H diff --git a/plugins/channel/nfm/nfmdemodgui.ui b/plugins/channel/nfm/nfmdemodgui.ui new file mode 100644 index 000000000..64cc44921 --- /dev/null +++ b/plugins/channel/nfm/nfmdemodgui.ui @@ -0,0 +1,250 @@ + + + NFMDemodGUI + + + + 0 + 0 + 302 + 410 + + + + NFM Demodulator + + + + + 35 + 35 + 242 + 96 + + + + Settings + + + + 2 + + + 3 + + + + + RF Bandwidth + + + + + + + 8 + + + 1 + + + 4 + + + Qt::Horizontal + + + + + + + + 50 + 0 + + + + 12.5kHz + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + AF Bandwidth + + + + + + + 1 + + + 20 + + + 1 + + + 3 + + + Qt::Horizontal + + + + + + + + 50 + 0 + + + + 3 kHz + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Volume + + + + + + + 100 + + + 20 + + + Qt::Horizontal + + + + + + + + 50 + 0 + + + + 2.0 + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Squelch + + + + + + + -100 + + + 0 + + + -40 + + + Qt::Horizontal + + + + + + + + 50 + 0 + + + + -40dB + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + 40 + 140 + 218 + 184 + + + + Channel Spectrum + + + + 2 + + + 3 + + + + + + 200 + 150 + + + + + + + + + + + + + GLSpectrum + QWidget +
gui/glspectrum.h
+ 1 +
+ + GLSpectrumGUI + QWidget +
gui/glspectrumgui.h
+ 1 +
+ + RollupWidget + QWidget +
gui/rollupwidget.h
+ 1 +
+
+ + +
diff --git a/plugins/channel/nfm/nfmplugin.cpp b/plugins/channel/nfm/nfmplugin.cpp new file mode 100644 index 000000000..57b5b9249 --- /dev/null +++ b/plugins/channel/nfm/nfmplugin.cpp @@ -0,0 +1,53 @@ +#include +#include +#include "plugin/pluginapi.h" +#include "nfmplugin.h" +#include "nfmdemodgui.h" + +const PluginDescriptor NFMPlugin::m_pluginDescriptor = { + QString("NFM Demodulator"), + QString("---"), + QString("(c) maintech GmbH (written by Christian Daniel)"), + QString("http://www.maintech.de"), + true, + QString("http://www.maintech.de") +}; + +NFMPlugin::NFMPlugin(QObject* parent) : + QObject(parent) +{ +} + +const PluginDescriptor& NFMPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void NFMPlugin::initPlugin(PluginAPI* pluginAPI) +{ + m_pluginAPI = pluginAPI; + + // register NFM demodulator + QAction* action = new QAction(tr("&NFM Demodulator"), this); + connect(action, SIGNAL(triggered()), this, SLOT(createInstanceNFM())); + m_pluginAPI->registerChannel("de.maintech.sdrangelove.channel.nfm", this, action); +} + +PluginGUI* NFMPlugin::createChannel(const QString& channelName) +{ + if(channelName == "de.maintech.sdrangelove.channel.nfm") { + NFMDemodGUI* gui = NFMDemodGUI::create(m_pluginAPI); + m_pluginAPI->registerChannelInstance("de.maintech.sdrangelove.channel.nfm", gui); + m_pluginAPI->addChannelRollup(gui); + return gui; + } else { + return NULL; + } +} + +void NFMPlugin::createInstanceNFM() +{ + NFMDemodGUI* gui = NFMDemodGUI::create(m_pluginAPI); + m_pluginAPI->registerChannelInstance("de.maintech.sdrangelove.channel.nfm", gui); + m_pluginAPI->addChannelRollup(gui); +} diff --git a/plugins/channel/nfm/nfmplugin.h b/plugins/channel/nfm/nfmplugin.h new file mode 100644 index 000000000..0cd345b8f --- /dev/null +++ b/plugins/channel/nfm/nfmplugin.h @@ -0,0 +1,29 @@ +#ifndef INCLUDE_NFMPLUGIN_H +#define INCLUDE_NFMPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class NFMPlugin : public QObject, PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID "de.maintech.sdrangelove.channel.nfm") + +public: + explicit NFMPlugin(QObject* parent = NULL); + + const PluginDescriptor& getPluginDescriptor() const; + void initPlugin(PluginAPI* pluginAPI); + + PluginGUI* createChannel(const QString& channelName); + +private: + static const PluginDescriptor m_pluginDescriptor; + + PluginAPI* m_pluginAPI; + +private slots: + void createInstanceNFM(); +}; + +#endif // INCLUDE_NFMPLUGIN_H diff --git a/plugins/channel/tcpsrc/CMakeLists.txt b/plugins/channel/tcpsrc/CMakeLists.txt new file mode 100644 index 000000000..df7c4d4da --- /dev/null +++ b/plugins/channel/tcpsrc/CMakeLists.txt @@ -0,0 +1,47 @@ +project(tcpsrc) + +set(tcpsrc_SOURCES + tcpsrc.cpp + tcpsrcgui.cpp + tcpsrcplugin.cpp +) + +set(tcpsrc_HEADERS + tcpsrc.h + tcpsrcgui.h + tcpsrcplugin.h +) + +set(tcpsrc_FORMS + tcpsrcgui.ui +) + +include_directories( + . + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include-gpl + ${OPENGL_INCLUDE_DIR} +) + +#include(${QT_USE_FILE}) +add_definitions(${QT_DEFINITIONS}) +add_definitions(-DQT_PLUGIN) +add_definitions(-DQT_SHARED) + +#qt5_wrap_cpp(tcpsrc_HEADERS_MOC ${tcpsrc_HEADERS}) +qt5_wrap_ui(tcpsrc_FORMS_HEADERS ${tcpsrc_FORMS}) + +add_library(demodtcpsrc SHARED + ${tcpsrc_SOURCES} + ${tcpsrc_HEADERS_MOC} + ${tcpsrc_FORMS_HEADERS} +) + +target_link_libraries(demodtcpsrc + ${QT_LIBRARIES} + ${OPENGL_LIBRARIES} + sdrbase +) + +qt5_use_modules(demodtcpsrc Core Widgets OpenGL Network) diff --git a/plugins/channel/tcpsrc/tcpsrc.cpp b/plugins/channel/tcpsrc/tcpsrc.cpp new file mode 100644 index 000000000..9cfee4354 --- /dev/null +++ b/plugins/channel/tcpsrc/tcpsrc.cpp @@ -0,0 +1,205 @@ +#include +#include +#include +#include "tcpsrc.h" +#include "tcpsrcgui.h" +#include "dsp/dspcommands.h" + +MESSAGE_CLASS_DEFINITION(TCPSrc::MsgTCPSrcConfigure, Message) +MESSAGE_CLASS_DEFINITION(TCPSrc::MsgTCPSrcConnection, Message) +MESSAGE_CLASS_DEFINITION(TCPSrc::MsgTCPSrcSpectrum, Message) + +TCPSrc::TCPSrc(MessageQueue* uiMessageQueue, TCPSrcGUI* tcpSrcGUI, SampleSink* spectrum) +{ + m_inputSampleRate = 100000; + m_sampleFormat = FormatS8; + m_outputSampleRate = 50000; + m_rfBandwidth = 50000; + m_tcpPort = 9999; + m_nco.setFreq(0, m_inputSampleRate); + m_interpolator.create(16, m_inputSampleRate, m_rfBandwidth / 2.1); + m_sampleDistanceRemain = m_inputSampleRate / m_outputSampleRate; + m_uiMessageQueue = uiMessageQueue; + m_tcpSrcGUI = tcpSrcGUI; + m_spectrum = spectrum; + m_spectrumEnabled = false; + m_nextS8Id = 0; + m_nextS16leId = 0; +} + +TCPSrc::~TCPSrc() +{ +} + +void TCPSrc::configure(MessageQueue* messageQueue, SampleFormat sampleFormat, Real outputSampleRate, Real rfBandwidth, int tcpPort) +{ + Message* cmd = MsgTCPSrcConfigure::create(sampleFormat, outputSampleRate, rfBandwidth, tcpPort); + cmd->submit(messageQueue, this); +} + +void TCPSrc::setSpectrum(MessageQueue* messageQueue, bool enabled) +{ + Message* cmd = MsgTCPSrcSpectrum::create(enabled); + cmd->submit(messageQueue, this); +} + +void TCPSrc::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst) +{ + Complex ci; + bool consumed; + + for(SampleVector::const_iterator it = begin; it < end; ++it) { + Complex c(it->real() / 32768.0, it->imag() / 32768.0); + c *= m_nco.nextIQ(); + + consumed = false; + if(m_interpolator.interpolate(&m_sampleDistanceRemain, c, &consumed, &ci)) { + m_sampleBuffer.push_back(Sample(ci.real() * 32768.0, ci.imag() * 32768.0)); + m_sampleDistanceRemain += m_inputSampleRate / m_outputSampleRate; + } + } + + if((m_spectrum != NULL) && (m_spectrumEnabled)) + m_spectrum->feed(m_sampleBuffer.begin(), m_sampleBuffer.end(), firstOfBurst); + + for(int i = 0; i < m_s16leSockets.count(); i++) + m_s16leSockets[i].socket->write((const char*)&m_sampleBuffer[0], m_sampleBuffer.size() * 4); + + if(m_s8Sockets.count() > 0) { + for(SampleVector::const_iterator it = m_sampleBuffer.begin(); it != m_sampleBuffer.end(); ++it) { + m_sampleBufferS8.push_back(it->real() >> 8); + m_sampleBufferS8.push_back(it->imag() >> 8); + } + for(int i = 0; i < m_s8Sockets.count(); i++) + m_s8Sockets[i].socket->write((const char*)&m_sampleBufferS8[0], m_sampleBufferS8.size()); + } + + m_sampleBuffer.clear(); + m_sampleBufferS8.clear(); +} + +void TCPSrc::start() +{ + m_tcpServer = new QTcpServer(); + connect(m_tcpServer, SIGNAL(newConnection()), this, SLOT(onNewConnection())); + m_tcpServer->listen(QHostAddress::Any, m_tcpPort); +} + +void TCPSrc::stop() +{ + closeAllSockets(&m_s8Sockets); + closeAllSockets(&m_s16leSockets); + + if(m_tcpServer->isListening()) + m_tcpServer->close(); + delete m_tcpServer; +} + +bool TCPSrc::handleMessage(Message* cmd) +{ + if(DSPSignalNotification::match(cmd)) { + DSPSignalNotification* signal = (DSPSignalNotification*)cmd; + qDebug("%d samples/sec, %lld Hz offset", signal->getSampleRate(), signal->getFrequencyOffset()); + m_inputSampleRate = signal->getSampleRate(); + m_nco.setFreq(-signal->getFrequencyOffset(), m_inputSampleRate); + m_interpolator.create(16, m_inputSampleRate, m_rfBandwidth / 2.1); + m_sampleDistanceRemain = m_inputSampleRate / m_outputSampleRate; + cmd->completed(); + return true; + } else if(DSPSignalNotification::match(cmd)) { + MsgTCPSrcConfigure* cfg = (MsgTCPSrcConfigure*)cmd; + m_sampleFormat = cfg->getSampleFormat(); + m_outputSampleRate = cfg->getOutputSampleRate(); + m_rfBandwidth = cfg->getRFBandwidth(); + if(cfg->getTCPPort() != m_tcpPort) { + m_tcpPort = cfg->getTCPPort(); + if(m_tcpServer->isListening()) + m_tcpServer->close(); + m_tcpServer->listen(QHostAddress::Any, m_tcpPort); + } + m_interpolator.create(16, m_inputSampleRate, m_rfBandwidth / 2.1); + m_sampleDistanceRemain = m_inputSampleRate / m_outputSampleRate; + cmd->completed(); + return true; + } else if(MsgTCPSrcSpectrum::match(cmd)) { + MsgTCPSrcSpectrum* spc = (MsgTCPSrcSpectrum*)cmd; + m_spectrumEnabled = spc->getEnabled(); + cmd->completed(); + return true; + } else { + if(m_spectrum != NULL) + return m_spectrum->handleMessage(cmd); + else return false; + } +} + +void TCPSrc::closeAllSockets(Sockets* sockets) +{ + for(int i = 0; i < sockets->count(); ++i) { + MsgTCPSrcConnection* msg = MsgTCPSrcConnection::create(false, sockets->at(i).id, QHostAddress(), 0); + msg->submit(m_uiMessageQueue, (PluginGUI*)m_tcpSrcGUI); + sockets->at(i).socket->close(); + } +} + +void TCPSrc::onNewConnection() +{ + while(m_tcpServer->hasPendingConnections()) { + QTcpSocket* connection = m_tcpServer->nextPendingConnection(); + connect(connection, SIGNAL(disconnected()), this, SLOT(onDisconnected())); + + switch(m_sampleFormat) { + case FormatS8: { + quint32 id = (FormatS8 << 24) | m_nextS8Id; + MsgTCPSrcConnection* msg = MsgTCPSrcConnection::create(true, id, connection->peerAddress(), connection->peerPort()); + m_nextS8Id = (m_nextS8Id + 1) & 0xffffff; + m_s8Sockets.push_back(Socket(id, connection)); + msg->submit(m_uiMessageQueue, (PluginGUI*)m_tcpSrcGUI); + break; + } + + case FormatS16LE: { + quint32 id = (FormatS16LE << 24) | m_nextS16leId; + MsgTCPSrcConnection* msg = MsgTCPSrcConnection::create(true, id, connection->peerAddress(), connection->peerPort()); + m_nextS16leId = (m_nextS16leId + 1) & 0xffffff; + m_s16leSockets.push_back(Socket(id, connection)); + msg->submit(m_uiMessageQueue, (PluginGUI*)m_tcpSrcGUI); + break; + } + + default: + delete connection; + break; + } + } +} + +void TCPSrc::onDisconnected() +{ + quint32 id; + QTcpSocket* socket = NULL; + + for(int i = 0; i < m_s8Sockets.count(); i++) { + if(m_s8Sockets[i].socket == sender()) { + id = m_s8Sockets[i].id; + socket = m_s8Sockets[i].socket; + m_s8Sockets.removeAt(i); + break; + } + } + if(socket == NULL) { + for(int i = 0; i < m_s16leSockets.count(); i++) { + if(m_s16leSockets[i].socket == sender()) { + id = m_s16leSockets[i].id; + socket = m_s16leSockets[i].socket; + m_s16leSockets.removeAt(i); + break; + } + } + } + if(socket != NULL) { + MsgTCPSrcConnection* msg = MsgTCPSrcConnection::create(false, id, QHostAddress(), 0); + msg->submit(m_uiMessageQueue, (PluginGUI*)m_tcpSrcGUI); + socket->deleteLater(); + } +} diff --git a/plugins/channel/tcpsrc/tcpsrc.h b/plugins/channel/tcpsrc/tcpsrc.h new file mode 100644 index 000000000..012a4dff2 --- /dev/null +++ b/plugins/channel/tcpsrc/tcpsrc.h @@ -0,0 +1,153 @@ +#ifndef INCLUDE_TCPSRC_H +#define INCLUDE_TCPSRC_H + +#include +#include "dsp/samplesink.h" +#include "dsp/nco.h" +#include "dsp/interpolator.h" +#include "util/message.h" + +class QTcpServer; +class QTcpSocket; +class TCPSrcGUI; + +class TCPSrc : public SampleSink { + Q_OBJECT + +public: + enum SampleFormat { + FormatS8, + FormatS16LE + }; + + TCPSrc(MessageQueue* uiMessageQueue, TCPSrcGUI* tcpSrcGUI, SampleSink* spectrum); + ~TCPSrc(); + + void configure(MessageQueue* messageQueue, SampleFormat sampleFormat, Real outputSampleRate, Real rfBandwidth, int tcpPort); + void setSpectrum(MessageQueue* messageQueue, bool enabled); + + void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst); + void start(); + void stop(); + bool handleMessage(Message* cmd); + + class MsgTCPSrcConnection : public Message { + MESSAGE_CLASS_DECLARATION + + public: + bool getConnect() const { return m_connect; } + quint32 getID() const { return m_id; } + const QHostAddress& getPeerAddress() const { return m_peerAddress; } + int getPeerPort() const { return m_peerPort; } + + static MsgTCPSrcConnection* create(bool connect, quint32 id, const QHostAddress& peerAddress, int peerPort) + { + return new MsgTCPSrcConnection(connect, id, peerAddress, peerPort); + } + + private: + bool m_connect; + quint32 m_id; + QHostAddress m_peerAddress; + int m_peerPort; + + MsgTCPSrcConnection(bool connect, quint32 id, const QHostAddress& peerAddress, int peerPort) : + Message(), + m_connect(connect), + m_id(id), + m_peerAddress(peerAddress), + m_peerPort(peerPort) + { } + }; + +protected: + class MsgTCPSrcConfigure : public Message { + MESSAGE_CLASS_DECLARATION + + public: + SampleFormat getSampleFormat() const { return m_sampleFormat; } + Real getOutputSampleRate() const { return m_outputSampleRate; } + Real getRFBandwidth() const { return m_rfBandwidth; } + int getTCPPort() const { return m_tcpPort; } + + static MsgTCPSrcConfigure* create(SampleFormat sampleFormat, Real sampleRate, Real rfBandwidth, int tcpPort) + { + return new MsgTCPSrcConfigure(sampleFormat, sampleRate, rfBandwidth, tcpPort); + } + + private: + SampleFormat m_sampleFormat; + Real m_outputSampleRate; + Real m_rfBandwidth; + int m_tcpPort; + + MsgTCPSrcConfigure(SampleFormat sampleFormat, Real outputSampleRate, Real rfBandwidth, int tcpPort) : + Message(), + m_sampleFormat(sampleFormat), + m_outputSampleRate(outputSampleRate), + m_rfBandwidth(rfBandwidth), + m_tcpPort(tcpPort) + { } + }; + class MsgTCPSrcSpectrum : public Message { + MESSAGE_CLASS_DECLARATION + + public: + bool getEnabled() const { return m_enabled; } + + static MsgTCPSrcSpectrum* create(bool enabled) + { + return new MsgTCPSrcSpectrum(enabled); + } + + private: + bool m_enabled; + + MsgTCPSrcSpectrum(bool enabled) : + Message(), + m_enabled(enabled) + { } + }; + + MessageQueue* m_uiMessageQueue; + TCPSrcGUI* m_tcpSrcGUI; + + int m_inputSampleRate; + + int m_sampleFormat; + Real m_outputSampleRate; + Real m_rfBandwidth; + int m_tcpPort; + + NCO m_nco; + Interpolator m_interpolator; + Real m_sampleDistanceRemain; + + SampleVector m_sampleBuffer; + std::vector m_sampleBufferS8; + SampleSink* m_spectrum; + bool m_spectrumEnabled; + + QTcpServer* m_tcpServer; + struct Socket { + quint32 id; + QTcpSocket* socket; + Socket(quint32 _id, QTcpSocket* _socket) : + id(_id), + socket(_socket) + { } + }; + typedef QList Sockets; + Sockets m_s8Sockets; + Sockets m_s16leSockets; + quint32 m_nextS8Id; + quint32 m_nextS16leId; + + void closeAllSockets(Sockets* sockets); + +protected slots: + void onNewConnection(); + void onDisconnected(); +}; + +#endif // INCLUDE_TCPSRC_H diff --git a/plugins/channel/tcpsrc/tcpsrcgui.cpp b/plugins/channel/tcpsrc/tcpsrcgui.cpp new file mode 100644 index 000000000..a7dcab29e --- /dev/null +++ b/plugins/channel/tcpsrc/tcpsrcgui.cpp @@ -0,0 +1,278 @@ +#include "tcpsrcgui.h" +#include "plugin/pluginapi.h" +#include "tcpsrc.h" +#include "dsp/channelizer.h" +#include "dsp/spectrumvis.h" +#include "dsp/threadedsamplesink.h" +#include "util/simpleserializer.h" +#include "gui/basicchannelsettingswidget.h" +#include "ui_tcpsrcgui.h" + +TCPSrcGUI* TCPSrcGUI::create(PluginAPI* pluginAPI) +{ + TCPSrcGUI* gui = new TCPSrcGUI(pluginAPI); + return gui; +} + +void TCPSrcGUI::destroy() +{ + delete this; +} + +void TCPSrcGUI::setName(const QString& name) +{ + setObjectName(name); +} + +void TCPSrcGUI::resetToDefaults() +{ + ui->sampleFormat->setCurrentIndex(0); + ui->sampleRate->setText("25000"); + ui->rfBandwidth->setText("20000"); + ui->tcpPort->setText("9999"); + ui->spectrumGUI->resetToDefaults(); + applySettings(); +} + +QByteArray TCPSrcGUI::serialize() const +{ + SimpleSerializer s(1); + s.writeBlob(1, saveState()); + s.writeS32(2, m_channelMarker->getCenterFrequency()); + s.writeS32(3, m_sampleFormat); + s.writeReal(4, m_outputSampleRate); + s.writeReal(5, m_rfBandwidth); + s.writeS32(6, m_tcpPort); + s.writeBlob(7, ui->spectrumGUI->serialize()); + s.writeU32(8, m_channelMarker->getColor().rgb()); + return s.final(); +} + +bool TCPSrcGUI::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { + QByteArray bytetmp; + qint32 s32tmp; + quint32 u32tmp; + Real realtmp; + d.readBlob(1, &bytetmp); + restoreState(bytetmp); + d.readS32(2, &s32tmp, 0); + m_channelMarker->setCenterFrequency(s32tmp); + d.readS32(3, &s32tmp, TCPSrc::FormatS8); + switch(s32tmp) { + case TCPSrc::FormatS8: + ui->sampleFormat->setCurrentIndex(0); + break; + case TCPSrc::FormatS16LE: + ui->sampleFormat->setCurrentIndex(1); + break; + default: + ui->sampleFormat->setCurrentIndex(0); + break; + } + d.readReal(4, &realtmp, 25000); + ui->sampleRate->setText(QString("%1").arg(realtmp, 0)); + d.readReal(5, &realtmp, 20000); + ui->rfBandwidth->setText(QString("%1").arg(realtmp, 0)); + d.readS32(6, &s32tmp, 9999); + ui->tcpPort->setText(QString("%1").arg(s32tmp)); + d.readBlob(7, &bytetmp); + ui->spectrumGUI->deserialize(bytetmp); + if(d.readU32(8, &u32tmp)) + m_channelMarker->setColor(u32tmp); + applySettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +bool TCPSrcGUI::handleMessage(Message* message) +{ + if(TCPSrc::MsgTCPSrcConnection::match(message)) { + TCPSrc::MsgTCPSrcConnection* con = (TCPSrc::MsgTCPSrcConnection*)message; + if(con->getConnect()) + addConnection(con->getID(), con->getPeerAddress(), con->getPeerPort()); + else delConnection(con->getID()); + message->completed(); + return true; + } else { + return false; + } +} + +void TCPSrcGUI::channelMarkerChanged() +{ + applySettings(); +} + +TCPSrcGUI::TCPSrcGUI(PluginAPI* pluginAPI, QWidget* parent) : + RollupWidget(parent), + ui(new Ui::TCPSrcGUI), + m_pluginAPI(pluginAPI), + m_tcpSrc(NULL), + m_basicSettingsShown(false) +{ + ui->setupUi(this); + ui->connectedClientsBox->hide(); + connect(this, SIGNAL(widgetRolled(QWidget*,bool)), this, SLOT(onWidgetRolled(QWidget*,bool))); + connect(this, SIGNAL(menuDoubleClickEvent()), this, SLOT(onMenuDoubleClicked())); + setAttribute(Qt::WA_DeleteOnClose, true); + + m_spectrumVis = new SpectrumVis(ui->glSpectrum); + m_tcpSrc = new TCPSrc(m_pluginAPI->getMainWindowMessageQueue(), this, m_spectrumVis); + m_channelizer = new Channelizer(m_tcpSrc); + m_threadedSampleSink = new ThreadedSampleSink(m_channelizer); + m_pluginAPI->addSampleSink(m_threadedSampleSink); + + ui->glSpectrum->setCenterFrequency(0); + ui->glSpectrum->setSampleRate(ui->sampleRate->text().toInt()); + ui->glSpectrum->setDisplayWaterfall(true); + ui->glSpectrum->setDisplayMaxHold(true); + m_spectrumVis->configure(m_threadedSampleSink->getMessageQueue(), 64, 10, FFTWindow::BlackmanHarris); + + m_channelMarker = new ChannelMarker(this); + m_channelMarker->setBandwidth(25000); + m_channelMarker->setCenterFrequency(0); + m_channelMarker->setVisible(true); + connect(m_channelMarker, SIGNAL(changed()), this, SLOT(channelMarkerChanged())); + m_pluginAPI->addChannelMarker(m_channelMarker); + + ui->spectrumGUI->setBuddies(m_threadedSampleSink->getMessageQueue(), m_spectrumVis, ui->glSpectrum); + + applySettings(); +} + +TCPSrcGUI::~TCPSrcGUI() +{ + m_pluginAPI->removeChannelInstance(this); + m_pluginAPI->removeSampleSink(m_threadedSampleSink); + delete m_threadedSampleSink; + delete m_channelizer; + delete m_tcpSrc; + delete m_spectrumVis; + delete m_channelMarker; + delete ui; +} + +void TCPSrcGUI::applySettings() +{ + bool ok; + + Real outputSampleRate = ui->sampleRate->text().toDouble(&ok); + if((!ok) || (outputSampleRate < 100)) + outputSampleRate = 25000; + Real rfBandwidth = ui->rfBandwidth->text().toDouble(&ok); + if((!ok) || (rfBandwidth > outputSampleRate)) + rfBandwidth = outputSampleRate; + int tcpPort = ui->tcpPort->text().toInt(&ok); + if((!ok) || (tcpPort < 1) || (tcpPort > 65535)) + tcpPort = 9999; + + setTitleColor(m_channelMarker->getColor()); + ui->sampleRate->setText(QString("%1").arg(outputSampleRate, 0)); + ui->rfBandwidth->setText(QString("%1").arg(rfBandwidth, 0)); + ui->tcpPort->setText(QString("%1").arg(tcpPort)); + m_channelMarker->disconnect(this, SLOT(channelMarkerChanged())); + m_channelMarker->setBandwidth((int)rfBandwidth); + connect(m_channelMarker, SIGNAL(changed()), this, SLOT(channelMarkerChanged())); + ui->glSpectrum->setSampleRate(outputSampleRate); + + m_channelizer->configure(m_threadedSampleSink->getMessageQueue(), + outputSampleRate, + m_channelMarker->getCenterFrequency()); + + TCPSrc::SampleFormat sampleFormat; + switch(ui->sampleFormat->currentIndex()) { + case 0: + sampleFormat = TCPSrc::FormatS8; + break; + case 1: + sampleFormat = TCPSrc::FormatS16LE; + break; + default: + sampleFormat = TCPSrc::FormatS8; + break; + } + + m_sampleFormat = sampleFormat; + m_outputSampleRate = outputSampleRate; + m_rfBandwidth = rfBandwidth; + m_tcpPort = tcpPort; + + m_tcpSrc->configure(m_threadedSampleSink->getMessageQueue(), + sampleFormat, + outputSampleRate, + rfBandwidth, + tcpPort); + + ui->applyBtn->setEnabled(false); +} + +void TCPSrcGUI::on_sampleFormat_currentIndexChanged(int index) +{ + ui->applyBtn->setEnabled(true); +} + +void TCPSrcGUI::on_sampleRate_textEdited(const QString& arg1) +{ + ui->applyBtn->setEnabled(true); +} + +void TCPSrcGUI::on_rfBandwidth_textEdited(const QString& arg1) +{ + ui->applyBtn->setEnabled(true); +} + +void TCPSrcGUI::on_tcpPort_textEdited(const QString& arg1) +{ + ui->applyBtn->setEnabled(true); +} + +void TCPSrcGUI::on_applyBtn_clicked() +{ + applySettings(); +} + +void TCPSrcGUI::onWidgetRolled(QWidget* widget, bool rollDown) +{ + if((widget == ui->spectrumBox) && (m_tcpSrc != NULL)) + m_tcpSrc->setSpectrum(m_threadedSampleSink->getMessageQueue(), rollDown); +} + +void TCPSrcGUI::onMenuDoubleClicked() +{ + if(!m_basicSettingsShown) { + m_basicSettingsShown = true; + BasicChannelSettingsWidget* bcsw = new BasicChannelSettingsWidget(m_channelMarker, this); + bcsw->show(); + } +} + +void TCPSrcGUI::addConnection(quint32 id, const QHostAddress& peerAddress, int peerPort) +{ + QStringList l; + l.append(QString("%1:%2").arg(peerAddress.toString()).arg(peerPort)); + new QTreeWidgetItem(ui->connections, l, id); + ui->connectedClientsBox->setWindowTitle(tr("Connected Clients (%1)").arg(ui->connections->topLevelItemCount())); +} + +void TCPSrcGUI::delConnection(quint32 id) +{ + for(int i = 0; i < ui->connections->topLevelItemCount(); i++) { + if(ui->connections->topLevelItem(i)->type() == id) { + delete ui->connections->topLevelItem(i); + ui->connectedClientsBox->setWindowTitle(tr("Connected Clients (%1)").arg(ui->connections->topLevelItemCount())); + return; + } + } +} diff --git a/plugins/channel/tcpsrc/tcpsrcgui.h b/plugins/channel/tcpsrc/tcpsrcgui.h new file mode 100644 index 000000000..b5a4dc0f4 --- /dev/null +++ b/plugins/channel/tcpsrc/tcpsrcgui.h @@ -0,0 +1,72 @@ +#ifndef INCLUDE_TCPSRCGUI_H +#define INCLUDE_TCPSRCGUI_H + +#include +#include "gui/rollupwidget.h" +#include "plugin/plugingui.h" +#include "tcpsrc.h" + +class PluginAPI; +class ChannelMarker; +class ThreadedSampleSink; +class Channelizer; +class TCPSrc; +class SpectrumVis; + +namespace Ui { + class TCPSrcGUI; +} + +class TCPSrcGUI : public RollupWidget, public PluginGUI { + Q_OBJECT + +public: + static TCPSrcGUI* create(PluginAPI* pluginAPI); + void destroy(); + + void setName(const QString& name); + + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + + bool handleMessage(Message* message); + +private slots: + void channelMarkerChanged(); + void on_sampleFormat_currentIndexChanged(int index); + void on_sampleRate_textEdited(const QString& arg1); + void on_rfBandwidth_textEdited(const QString& arg1); + void on_tcpPort_textEdited(const QString& arg1); + void on_applyBtn_clicked(); + void onWidgetRolled(QWidget* widget, bool rollDown); + void onMenuDoubleClicked(); + +private: + Ui::TCPSrcGUI* ui; + PluginAPI* m_pluginAPI; + ChannelMarker* m_channelMarker; + + // settings + TCPSrc::SampleFormat m_sampleFormat; + Real m_outputSampleRate; + Real m_rfBandwidth; + int m_tcpPort; + bool m_basicSettingsShown; + + // RF path + ThreadedSampleSink* m_threadedSampleSink; + Channelizer* m_channelizer; + TCPSrc* m_tcpSrc; + SpectrumVis* m_spectrumVis; + + explicit TCPSrcGUI(PluginAPI* pluginAPI, QWidget* parent = NULL); + ~TCPSrcGUI(); + + void applySettings(); + + void addConnection(quint32 id, const QHostAddress& peerAddress, int peerPort); + void delConnection(quint32 id); +}; + +#endif // INCLUDE_TCPSRCGUI_H diff --git a/plugins/channel/tcpsrc/tcpsrcgui.ui b/plugins/channel/tcpsrc/tcpsrcgui.ui new file mode 100644 index 000000000..72d2ea622 --- /dev/null +++ b/plugins/channel/tcpsrc/tcpsrcgui.ui @@ -0,0 +1,213 @@ + + + TCPSrcGUI + + + + 0 + 0 + 400 + 443 + + + + TCP Sample Source + + + + + 10 + 5 + 201 + 142 + + + + Settings + + + + 2 + + + 3 + + + + + Sample Format + + + + + + + + S8 I/Q + + + + + S16LE I/Q + + + + + + + + 20000 + + + + + + + RF Bandwidth (Hz) + + + + + + + Samplerate (Hz) + + + + + + + 25000 + + + + + + + TCP Port + + + + + + + 9999 + + + + + + + false + + + Apply + + + + + + + + + 15 + 160 + 231 + 156 + + + + Channel Spectrum + + + + 3 + + + 2 + + + + + + + + + + + + + 15 + 330 + 274 + 101 + + + + Connected Clients (0) + + + + 3 + + + 2 + + + + + + 16777215 + 100 + + + + false + + + false + + + false + + + + IP:Port + + + + + + + + + + GLSpectrum + QWidget +
gui/glspectrum.h
+ 1 +
+ + GLSpectrumGUI + QWidget +
gui/glspectrumgui.h
+ 1 +
+ + RollupWidget + QWidget +
gui/rollupwidget.h
+ 1 +
+
+ + sampleFormat + tcpPort + sampleRate + rfBandwidth + applyBtn + connections + + + +
diff --git a/plugins/channel/tcpsrc/tcpsrcplugin.cpp b/plugins/channel/tcpsrc/tcpsrcplugin.cpp new file mode 100644 index 000000000..4e347d8e0 --- /dev/null +++ b/plugins/channel/tcpsrc/tcpsrcplugin.cpp @@ -0,0 +1,53 @@ +#include +#include +#include "plugin/pluginapi.h" +#include "tcpsrcplugin.h" +#include "tcpsrcgui.h" + +const PluginDescriptor TCPSrcPlugin::m_pluginDescriptor = { + QString("TCP Channel Source"), + QString("---"), + QString("(c) maintech GmbH (written by Christian Daniel)"), + QString("http://www.maintech.de"), + true, + QString("http://www.maintech.de") +}; + +TCPSrcPlugin::TCPSrcPlugin(QObject* parent) : + QObject(parent) +{ +} + +const PluginDescriptor& TCPSrcPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void TCPSrcPlugin::initPlugin(PluginAPI* pluginAPI) +{ + m_pluginAPI = pluginAPI; + + // register TCP Channel Source + QAction* action = new QAction(tr("&TCP Source"), this); + connect(action, SIGNAL(triggered()), this, SLOT(createInstanceTCPSrc())); + m_pluginAPI->registerChannel("de.maintech.sdrangelove.channel.tcpsrc", this, action); +} + +PluginGUI* TCPSrcPlugin::createChannel(const QString& channelName) +{ + if(channelName == "de.maintech.sdrangelove.channel.tcpsrc") { + TCPSrcGUI* gui = TCPSrcGUI::create(m_pluginAPI); + m_pluginAPI->registerChannelInstance("de.maintech.sdrangelove.channel.tcpsrc", gui); + m_pluginAPI->addChannelRollup(gui); + return gui; + } else { + return NULL; + } +} + +void TCPSrcPlugin::createInstanceTCPSrc() +{ + TCPSrcGUI* gui = TCPSrcGUI::create(m_pluginAPI); + m_pluginAPI->registerChannelInstance("de.maintech.sdrangelove.channel.tcpsrc", gui); + m_pluginAPI->addChannelRollup(gui); +} diff --git a/plugins/channel/tcpsrc/tcpsrcplugin.h b/plugins/channel/tcpsrc/tcpsrcplugin.h new file mode 100644 index 000000000..984cd8fb2 --- /dev/null +++ b/plugins/channel/tcpsrc/tcpsrcplugin.h @@ -0,0 +1,29 @@ +#ifndef INCLUDE_TCPSRCPLUGIN_H +#define INCLUDE_TCPSRCPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class TCPSrcPlugin : public QObject, PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID "de.maintech.sdrangelove.demod.tcpsrc") + +public: + explicit TCPSrcPlugin(QObject* parent = NULL); + + const PluginDescriptor& getPluginDescriptor() const; + void initPlugin(PluginAPI* pluginAPI); + + PluginGUI* createChannel(const QString& channelName); + +private: + static const PluginDescriptor m_pluginDescriptor; + + PluginAPI* m_pluginAPI; + +private slots: + void createInstanceTCPSrc(); +}; + +#endif // INCLUDE_TCPSRCPLUGIN_H diff --git a/plugins/channel/tetra/CMakeLists.txt b/plugins/channel/tetra/CMakeLists.txt new file mode 100644 index 000000000..f46c2bb57 --- /dev/null +++ b/plugins/channel/tetra/CMakeLists.txt @@ -0,0 +1,47 @@ +project(tetra) + +set(tetra_SOURCES + tetrademod.cpp + tetrademodgui.cpp + tetraplugin.cpp +) + +set(tetra_HEADERS + tetrademod.h + tetrademodgui.h + tetraplugin.h +) + +set(tetra_FORMS + tetrademodgui.ui +) + +include_directories( + . + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include-gpl + ${OPENGL_INCLUDE_DIR} +) + +#include(${QT_USE_FILE}) +add_definitions(${QT_DEFINITIONS}) +add_definitions(-DQT_PLUGIN) +add_definitions(-DQT_SHARED) + +#qt5_wrap_cpp(tetra_HEADERS_MOC ${tetra_HEADERS}) +qt5_wrap_ui(tetra_FORMS_HEADERS ${tetra_FORMS}) + +add_library(demodtetra SHARED + ${tetra_SOURCES} + ${tetra_HEADERS_MOC} + ${tetra_FORMS_HEADERS} +) + +target_link_libraries(demodtetra + ${QT_LIBRARIES} + ${OPENGL_LIBRARIES} + sdrbase +) + +qt5_use_modules(demodtetra Core Widgets OpenGL Multimedia) diff --git a/plugins/channel/tetra/tetrademod.cpp b/plugins/channel/tetra/tetrademod.cpp new file mode 100644 index 000000000..f26810a70 --- /dev/null +++ b/plugins/channel/tetra/tetrademod.cpp @@ -0,0 +1,106 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include "tetrademod.h" +#include "dsp/dspcommands.h" + +MessageRegistrator TetraDemod::MsgConfigureTetraDemod::ID("MsgConfigureTetraDemod"); + +static FILE* f = NULL; + +TetraDemod::TetraDemod(SampleSink* sampleSink) : + m_sampleSink(sampleSink) +{ + m_sampleRate = 500000; + m_frequency = 0; + + m_nco.setFreq(m_frequency, m_sampleRate); + m_interpolator.create(32, 32 * m_sampleRate, 36000); + m_sampleDistanceRemain = (Real)m_sampleRate / 36000.0; +} + +TetraDemod::~TetraDemod() +{ +} + +void TetraDemod::configure(MessageQueue* messageQueue) +{ + Message* cmd = MsgConfigureTetraDemod::create(); + cmd->submit(messageQueue, this); +} + +void TetraDemod::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst) +{ + size_t count = end - begin; + + Complex ci; + bool consumed; + + for(SampleVector::const_iterator it = begin; it < end; ++it) { + Complex c(it->real() / 32768.0, it->imag() / 32768.0); + c *= m_nco.nextIQ(); + + consumed = false; + if(m_interpolator.interpolate(&m_sampleDistanceRemain, c, &consumed, &ci)) { + m_sampleBuffer.push_back(Sample(ci.real() * 32768.0, ci.imag() * 32768.0)); + + m_sampleDistanceRemain += (Real)m_sampleRate / 36000.0; + } + } + + if(f != NULL) { + fwrite(&m_sampleBuffer[0], m_sampleBuffer.size(), sizeof(m_sampleBuffer[0]), f); + } + + if(m_sampleSink != NULL) + m_sampleSink->feed(m_sampleBuffer.begin(), m_sampleBuffer.end(), firstOfBurst); + m_sampleBuffer.clear(); +} + +void TetraDemod::start() +{ +} + +void TetraDemod::stop() +{ +} + +bool TetraDemod::handleMessage(Message* cmd) +{ + if(cmd->id() == DSPSignalNotification::ID()) { + DSPSignalNotification* signal = (DSPSignalNotification*)cmd; + qDebug("%d samples/sec, %lld Hz offset", signal->getSampleRate(), signal->getFrequencyOffset()); + m_sampleRate = signal->getSampleRate(); + m_nco.setFreq(-signal->getFrequencyOffset(), m_sampleRate); + m_interpolator.create(32, m_sampleRate, 25000 / 2); + m_sampleDistanceRemain = m_sampleRate / 36000.0; + cmd->completed(); + return true; + } else if(cmd->id() == MsgConfigureTetraDemod::ID()) { + if(f == NULL) { + f = fopen("/tmp/tetra.iq", "wb"); + qDebug("started writing samples"); + } else { + fclose(f); + f = NULL; + qDebug("stopped writing samples"); + } + } else { + return false; + } +} diff --git a/plugins/channel/tetra/tetrademod.h b/plugins/channel/tetra/tetrademod.h new file mode 100644 index 000000000..a2a474b63 --- /dev/null +++ b/plugins/channel/tetra/tetrademod.h @@ -0,0 +1,67 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_TETRADEMOD_H +#define INCLUDE_TETRADEMOD_H + +#include "dsp/samplesink.h" +#include "dsp/nco.h" +#include "dsp/interpolator.h" +#include "util/message.h" + +class MessageQueue; + +class TetraDemod : public SampleSink { +public: + TetraDemod(SampleSink* sampleSink); + ~TetraDemod(); + + void configure(MessageQueue* messageQueue); + + void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst); + void start(); + void stop(); + bool handleMessage(Message* cmd); + +private: + class MsgConfigureTetraDemod : public Message { + public: + static MessageRegistrator ID; + + static MsgConfigureTetraDemod* create() + { + return new MsgConfigureTetraDemod(); + } + + private: + MsgConfigureTetraDemod() : + Message(ID()) + { } + }; + + int m_sampleRate; + int m_frequency; + + NCO m_nco; + Interpolator m_interpolator; + Real m_sampleDistanceRemain; + + SampleSink* m_sampleSink; + SampleVector m_sampleBuffer; +}; + +#endif // INCLUDE_TETRADEMOD_H diff --git a/plugins/channel/tetra/tetrademodgui.cpp b/plugins/channel/tetra/tetrademodgui.cpp new file mode 100644 index 000000000..978f4f7a3 --- /dev/null +++ b/plugins/channel/tetra/tetrademodgui.cpp @@ -0,0 +1,110 @@ +#include +#include +#include "tetrademodgui.h" +#include "ui_tetrademodgui.h" +#include "dsp/threadedsamplesink.h" +#include "dsp/channelizer.h" +#include "tetrademod.h" +#include "dsp/spectrumvis.h" +#include "gui/glspectrum.h" +#include "plugin/pluginapi.h" + +TetraDemodGUI* TetraDemodGUI::create(PluginAPI* pluginAPI) +{ + QDockWidget* dock = pluginAPI->createMainWindowDock(Qt::RightDockWidgetArea, tr("Tetra Demodulator")); + dock->setObjectName(QString::fromUtf8("Tetra Demodulator")); + TetraDemodGUI* gui = new TetraDemodGUI(pluginAPI, dock); + dock->setWidget(gui); + return gui; +} + +void TetraDemodGUI::destroy() +{ + delete m_dockWidget; +} + +void TetraDemodGUI::setWidgetName(const QString& name) +{ + m_dockWidget->setObjectName(name); +} + +void TetraDemodGUI::resetToDefaults() +{ +} + +QByteArray TetraDemodGUI::serializeGeneral() const +{ + return QByteArray(); +} + +bool TetraDemodGUI::deserializeGeneral(const QByteArray& data) +{ + return false; +} + +QByteArray TetraDemodGUI::serialize() const +{ + return QByteArray(); +} + +bool TetraDemodGUI::deserialize(const QByteArray& data) +{ + return false; +} + +bool TetraDemodGUI::handleMessage(Message* message) +{ + return false; +} + +void TetraDemodGUI::viewChanged() +{ + m_channelizer->configure(m_threadedSampleSink->getMessageQueue(), 36000, m_channelMarker->getCenterFrequency()); +} + +TetraDemodGUI::TetraDemodGUI(PluginAPI* pluginAPI, QDockWidget* dockWidget, QWidget* parent) : + PluginGUI(parent), + ui(new Ui::TetraDemodGUI), + m_pluginAPI(pluginAPI), + m_dockWidget(dockWidget) +{ + ui->setupUi(this); + + m_spectrumVis = new SpectrumVis(ui->glSpectrum); + m_tetraDemod = new TetraDemod(m_spectrumVis); + m_channelizer = new Channelizer(m_tetraDemod); + m_threadedSampleSink = new ThreadedSampleSink(m_channelizer); + m_pluginAPI->addSampleSink(m_threadedSampleSink); + + ui->glSpectrum->setCenterFrequency(0); + ui->glSpectrum->setSampleRate(36000); + ui->glSpectrum->setDisplayWaterfall(true); + ui->glSpectrum->setDisplayMaxHold(true); + m_spectrumVis->configure(m_threadedSampleSink->getMessageQueue(), 64, 10, FFTWindow::BlackmanHarris); + + m_channelMarker = new ChannelMarker(this); + m_channelMarker->setColor(Qt::darkGreen); + m_channelMarker->setBandwidth(25000); + m_channelMarker->setCenterFrequency(0); + m_channelMarker->setVisible(true); + connect(m_channelMarker, SIGNAL(changed()), this, SLOT(viewChanged())); + m_pluginAPI->addChannelMarker(m_channelMarker); + + viewChanged(); +} + +TetraDemodGUI::~TetraDemodGUI() +{ + m_pluginAPI->removeSampleSink(m_threadedSampleSink); + delete m_threadedSampleSink; + delete m_channelizer; + delete m_tetraDemod; + delete m_spectrumVis; + delete m_channelMarker; + delete ui; +} + +void TetraDemodGUI::on_test_clicked() +{ + m_tetraDemod->configure(m_threadedSampleSink->getMessageQueue()); +} diff --git a/plugins/channel/tetra/tetrademodgui.h b/plugins/channel/tetra/tetrademodgui.h new file mode 100644 index 000000000..9eacae61f --- /dev/null +++ b/plugins/channel/tetra/tetrademodgui.h @@ -0,0 +1,56 @@ +#ifndef INCLUDE_TETRADEMODGUI_H +#define INCLUDE_TETRADEMODGUI_H + +#include "plugin/plugingui.h" + +class QDockWidget; + +class PluginAPI; +class ChannelMarker; + +class ThreadedSampleSink; +class Channelizer; +class TetraDemod; +class SpectrumVis; + +namespace Ui { + class TetraDemodGUI; +} + +class TetraDemodGUI : public PluginGUI { + Q_OBJECT + +public: + static TetraDemodGUI* create(PluginAPI* pluginAPI); + void destroy(); + + void setWidgetName(const QString& name); + + void resetToDefaults(); + QByteArray serializeGeneral() const; + bool deserializeGeneral(const QByteArray& data); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + + bool handleMessage(Message* message); + +private slots: + void on_test_clicked(); + void viewChanged(); + +private: + explicit TetraDemodGUI(PluginAPI* pluginAPI, QDockWidget* dockWidget, QWidget* parent = NULL); + ~TetraDemodGUI(); + + Ui::TetraDemodGUI* ui; + PluginAPI* m_pluginAPI; + QDockWidget* m_dockWidget; + ChannelMarker* m_channelMarker; + + ThreadedSampleSink* m_threadedSampleSink; + Channelizer* m_channelizer; + TetraDemod* m_tetraDemod; + SpectrumVis* m_spectrumVis; +}; + +#endif // INCLUDE_TETRADEMODGUI_H diff --git a/plugins/channel/tetra/tetrademodgui.ui b/plugins/channel/tetra/tetrademodgui.ui new file mode 100644 index 000000000..feaef1084 --- /dev/null +++ b/plugins/channel/tetra/tetrademodgui.ui @@ -0,0 +1,56 @@ + + + TetraDemodGUI + + + + 0 + 0 + 200 + 179 + + + + Form + + + + 3 + + + 0 + + + + + + 200 + 150 + + + + + + + + + + + + + + + + + + + + GLSpectrum + QWidget +
gui/glspectrum.h
+ 1 +
+
+ + +
diff --git a/plugins/channel/tetra/tetraplugin.cpp b/plugins/channel/tetra/tetraplugin.cpp new file mode 100644 index 000000000..9dc48cc3f --- /dev/null +++ b/plugins/channel/tetra/tetraplugin.cpp @@ -0,0 +1,50 @@ +#include +#include +#include "plugin/pluginapi.h" +#include "tetraplugin.h" +#include "tetrademodgui.h" + +const PluginDescriptor TetraPlugin::m_pluginDescriptor = { + QString("Tetra Demodulator"), + QString("---"), + QString("(c) maintech GmbH (written by Christian Daniel)"), + QString("http://www.maintech.de"), + true, + QString("http://www.maintech.de") +}; + +TetraPlugin::TetraPlugin(QObject* parent) : + QObject(parent) +{ +} + +const PluginDescriptor& TetraPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void TetraPlugin::initPlugin(PluginAPI* pluginAPI) +{ + m_pluginAPI = pluginAPI; + + // register Tetra demodulator + QAction* action = new QAction(tr("&Tetra"), this); + connect(action, SIGNAL(triggered()), this, SLOT(createInstanceTetra())); + m_pluginAPI->registerDemodulator("de.maintech.sdrangelove.demod.tetra", this, action); +} + +PluginGUI* TetraPlugin::createDemod(const QString& demodName) +{ + if(demodName == "de.maintech.sdrangelove.demod.tetra") { + PluginGUI* gui = TetraDemodGUI::create(m_pluginAPI); + m_pluginAPI->registerDemodulatorInstance("de.maintech.sdrangelove.demod.tetra", gui); + return gui; + } else { + return NULL; + } +} + +void TetraPlugin::createInstanceTetra() +{ + m_pluginAPI->registerDemodulatorInstance("de.maintech.sdrangelove.demod.tetra", TetraDemodGUI::create(m_pluginAPI)); +} diff --git a/plugins/channel/tetra/tetraplugin.h b/plugins/channel/tetra/tetraplugin.h new file mode 100644 index 000000000..ec94a18c4 --- /dev/null +++ b/plugins/channel/tetra/tetraplugin.h @@ -0,0 +1,29 @@ +#ifndef INCLUDE_TETRAPLUGIN_H +#define INCLUDE_TETRAPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class TetraPlugin : public QObject, PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID "de.maintech.sdrangelove.demod.tetra") + +public: + explicit TetraPlugin(QObject* parent = NULL); + + const PluginDescriptor& getPluginDescriptor() const; + void initPlugin(PluginAPI* pluginAPI); + + PluginGUI* createDemod(const QString& demodName); + +private: + static const PluginDescriptor m_pluginDescriptor; + + PluginAPI* m_pluginAPI; + +private slots: + void createInstanceTetra(); +}; + +#endif // INCLUDE_TETRAPLUGIN_H diff --git a/plugins/samplesource/CMakeLists.txt b/plugins/samplesource/CMakeLists.txt new file mode 100644 index 000000000..31351330e --- /dev/null +++ b/plugins/samplesource/CMakeLists.txt @@ -0,0 +1,15 @@ +project(samplesource) + +find_package(LibUSB) +find_package(LibOsmoSDR) +find_package(LibRTLSDR) + +add_subdirectory(gnuradio) + +if(LIBUSB_FOUND AND LIBOSMOSDR_FOUND) + add_subdirectory(osmosdr) +endif(LIBUSB_FOUND AND LIBOSMOSDR_FOUND) + +if(LIBUSB_FOUND AND LIBRTLSDR_FOUND) + add_subdirectory(rtlsdr) +endif(LIBUSB_FOUND AND LIBRTLSDR_FOUND) diff --git a/plugins/samplesource/gnuradio/CMakeLists.txt b/plugins/samplesource/gnuradio/CMakeLists.txt new file mode 100644 index 000000000..0e08608cf --- /dev/null +++ b/plugins/samplesource/gnuradio/CMakeLists.txt @@ -0,0 +1,87 @@ +project(gnuradio) + +list(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/Modules) + +find_package(GnuradioRuntime) +find_package(GnuradioOsmosdr) + +if(UNIX AND NOT BOOST_ROOT AND EXISTS "/usr/lib64") + list(APPEND BOOST_LIBRARYDIR "/usr/lib64") #fedora 64-bit fix +endif(UNIX AND NOT BOOST_ROOT AND EXISTS "/usr/lib64") + +find_package(Boost COMPONENTS system) + +if(NOT GNURADIO_RUNTIME_FOUND AND GNURADIO_OSMOSDR_FOUND) + + message(STATUS "GNU Radio not found, assuming built-in gr-osmosdr runtime.") + + set(GNURADIO_RUNTIME_FOUND TRUE) + set(GNURADIO_RUNTIME_INCLUDE_DIRS "") + set(GNURADIO_RUNTIME_LIBRARIES "") + + FOREACH(inc ${GNURADIO_OSMOSDR_INCLUDE_DIRS}) + LIST(APPEND GNURADIO_RUNTIME_INCLUDE_DIRS "${inc}/osmosdr/runtime") + ENDFOREACH(inc) + + LIST(APPEND GNURADIO_RUNTIME_LIBRARIES ${GNURADIO_OSMOSDR_LIBRARIES}) + +endif(NOT GNURADIO_RUNTIME_FOUND AND GNURADIO_OSMOSDR_FOUND) + +if(Boost_FOUND AND GNURADIO_RUNTIME_FOUND AND GNURADIO_OSMOSDR_FOUND) + +set(gnuradio_SOURCES + gnuradiogui.cpp + gnuradioinput.cpp + gnuradioplugin.cpp + gnuradiothread.cpp +) + +set(gnuradio_HEADERS + gnuradiogui.h + gnuradioinput.h + gnuradioplugin.h + gnuradiothread.h +) + +set(gnuradio_FORMS + gnuradiogui.ui +) + +include_directories( + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include-gpl + ${Boost_INCLUDE_DIRS} + ${GNURADIO_RUNTIME_INCLUDE_DIRS} + ${GNURADIO_OSMOSDR_INCLUDE_DIRS} +) + +add_definitions(${QT_DEFINITIONS}) +add_definitions(-DQT_PLUGIN) +add_definitions(-DQT_SHARED) +add_definitions(-DBOOST_ALL_NO_LIB) + +if(MSVC) +add_definitions(-DNOMINMAX) +endif() + +qt5_wrap_ui(gnuradio_FORMS_HEADERS ${gnuradio_FORMS}) + +add_library(inputgnuradio SHARED + ${gnuradio_SOURCES} + ${gnuradio_HEADERS_MOC} + ${gnuradio_FORMS_HEADERS} +) + +target_link_libraries(inputgnuradio + ${QT_LIBRARIES} + ${Boost_LIBRARIES} + ${GNURADIO_RUNTIME_LIBRARIES} + ${GNURADIO_OSMOSDR_LIBRARIES} + sdrbase +) + +qt5_use_modules(inputgnuradio Core Widgets OpenGL Multimedia) + +endif(Boost_FOUND AND GNURADIO_RUNTIME_FOUND AND GNURADIO_OSMOSDR_FOUND) diff --git a/plugins/samplesource/gnuradio/cmake/Modules/FindGnuradioOsmosdr.cmake b/plugins/samplesource/gnuradio/cmake/Modules/FindGnuradioOsmosdr.cmake new file mode 100644 index 000000000..156a38dd3 --- /dev/null +++ b/plugins/samplesource/gnuradio/cmake/Modules/FindGnuradioOsmosdr.cmake @@ -0,0 +1,29 @@ +INCLUDE(FindPkgConfig) +PKG_CHECK_MODULES(PC_GNURADIO_OSMOSDR gnuradio-osmosdr) + +FIND_PATH( + GNURADIO_OSMOSDR_INCLUDE_DIRS + NAMES osmosdr/api.h + HINTS $ENV{GNURADIO_OSMOSDR_DIR}/include + ${PC_GNURADIO_OSMOSDR_INCLUDEDIR} + ${CMAKE_INSTALL_PREFIX}/include + PATHS /usr/local/include + /usr/include +) + +FIND_LIBRARY( + GNURADIO_OSMOSDR_LIBRARIES + NAMES gnuradio-osmosdr + HINTS $ENV{GNURADIO_OSMOSDR_DIR}/lib + ${PC_GNURADIO_OSMOSDR_LIBDIR} + ${CMAKE_INSTALL_PREFIX}/lib64 + ${CMAKE_INSTALL_PREFIX}/lib + PATHS /usr/local/lib + /usr/local/lib64 + /usr/lib + /usr/lib64 +) + +INCLUDE(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(GNURADIO_OSMOSDR DEFAULT_MSG GNURADIO_OSMOSDR_LIBRARIES GNURADIO_OSMOSDR_INCLUDE_DIRS) +MARK_AS_ADVANCED(GNURADIO_OSMOSDR_LIBRARIES GNURADIO_OSMOSDR_INCLUDE_DIRS) diff --git a/plugins/samplesource/gnuradio/cmake/Modules/FindGnuradioRuntime.cmake b/plugins/samplesource/gnuradio/cmake/Modules/FindGnuradioRuntime.cmake new file mode 100644 index 000000000..124626e52 --- /dev/null +++ b/plugins/samplesource/gnuradio/cmake/Modules/FindGnuradioRuntime.cmake @@ -0,0 +1,29 @@ +INCLUDE(FindPkgConfig) +PKG_CHECK_MODULES(PC_GNURADIO_RUNTIME gnuradio-runtime) + +FIND_PATH( + GNURADIO_RUNTIME_INCLUDE_DIRS + NAMES gnuradio/api.h + HINTS $ENV{GNURADIO_RUNTIME_DIR}/include + ${PC_GNURADIO_RUNTIME_INCLUDEDIR} + ${CMAKE_INSTALL_PREFIX}/include + PATHS /usr/local/include + /usr/include +) + +FIND_LIBRARY( + GNURADIO_RUNTIME_LIBRARIES + NAMES gnuradio-runtime + HINTS $ENV{GNURADIO_RUNTIME_DIR}/lib + ${PC_GNURADIO_RUNTIME_LIBDIR} + ${CMAKE_INSTALL_PREFIX}/lib64 + ${CMAKE_INSTALL_PREFIX}/lib + PATHS /usr/local/lib + /usr/local/lib64 + /usr/lib + /usr/lib64 +) + +INCLUDE(FindPackageHandleStandardArgs) +FIND_PACKAGE_HANDLE_STANDARD_ARGS(GNURADIO_RUNTIME DEFAULT_MSG GNURADIO_RUNTIME_LIBRARIES GNURADIO_RUNTIME_INCLUDE_DIRS) +MARK_AS_ADVANCED(GNURADIO_RUNTIME_LIBRARIES GNURADIO_RUNTIME_INCLUDE_DIRS) diff --git a/plugins/samplesource/gnuradio/gnuradiogui.cpp b/plugins/samplesource/gnuradio/gnuradiogui.cpp new file mode 100644 index 000000000..c9d3bbb43 --- /dev/null +++ b/plugins/samplesource/gnuradio/gnuradiogui.cpp @@ -0,0 +1,422 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2013 by Dimitri Stolnikov // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "gnuradiogui.h" +#include "ui_gnuradiogui.h" + +#include +#include +#include + +#include +#include +#include + +GNURadioGui::GNURadioGui(PluginAPI* pluginAPI, QWidget* parent) : + QWidget(parent), + ui(new Ui::GNURadioGui), + m_pluginAPI(pluginAPI), + m_settings(), + m_sampleSource(NULL) +{ + ui->setupUi(this); + connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(updateHardware())); + displaySettings(); + + m_sampleSource = new GNURadioInput(m_pluginAPI->getMainWindowMessageQueue()); + m_pluginAPI->setSampleSource(m_sampleSource); +} + +GNURadioGui::~GNURadioGui() +{ + delete ui; +} + +void GNURadioGui::destroy() +{ + delete this; +} + +void GNURadioGui::setName(const QString& name) +{ + setObjectName(name); +} + +void GNURadioGui::resetToDefaults() +{ + m_generalSettings.resetToDefaults(); + m_settings.resetToDefaults(); + displaySettings(); + sendSettings(); +} + +QByteArray GNURadioGui::serializeGeneral() const +{ + return m_generalSettings.serialize(); +} + +bool GNURadioGui::deserializeGeneral(const QByteArray&data) +{ + if(m_generalSettings.deserialize(data)) { + displaySettings(); + sendSettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +quint64 GNURadioGui::getCenterFrequency() const +{ + return m_generalSettings.m_centerFrequency; +} + +QByteArray GNURadioGui::serialize() const +{ + return m_settings.serialize(); +} + +bool GNURadioGui::deserialize(const QByteArray& data) +{ + if(m_settings.deserialize(data)) { + displaySettings(); + sendSettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +bool GNURadioGui::handleMessage(Message* message) +{ + if(GNURadioInput::MsgReportGNURadio::match(message)) { + GNURadioInput::MsgReportGNURadio* rep = (GNURadioInput::MsgReportGNURadio*)message; + m_namedGains = rep->getNamedGains(); + m_freqMin = rep->getFreqMin(); + m_freqMax = rep->getFreqMax(); + m_freqCorr = rep->getFreqCorr(); + m_sampRates = rep->getSampRates(); + m_antennas = rep->getAntennas(); + m_dcoffs = rep->getDCOffs(); + m_iqbals = rep->getIQBals(); + m_bandwidths = rep->getBandwidths(); + /* insert 0 which will become "Auto" in the combo box */ + m_bandwidths.insert(m_bandwidths.begin(), 0); + displaySettings(); + return true; + } else { + return false; + } +} + +void GNURadioGui::displaySettings() +{ + int oldIndex = 0; + + oldIndex = ui->cboDevices->currentIndex(); + ui->cboDevices->clear(); + + QString oldArgs = ui->txtDeviceArgs->text(); + + osmosdr::devices_t devices = osmosdr::device::find(); + + for ( int i = 0; i < devices.size(); i++ ) + { + osmosdr::device_t dev = devices[i]; + + QString label; + + if ( dev.count( "label" ) ) + { + label = QString(dev[ "label" ].c_str()); + dev.erase("label"); + } + + QPair< QString, QString > pair(label, dev.to_string().c_str()); + m_devs.append(pair); + + ui->cboDevices->addItem(label); + } + + if ( ui->cboDevices->count() && oldIndex >= 0 ) + { + if ( oldIndex > ui->cboDevices->count() - 1 ) + oldIndex = 0; + + ui->cboDevices->setCurrentIndex(oldIndex); + + if ( oldArgs.length() == 0 ) + ui->txtDeviceArgs->setText( m_devs[oldIndex].second ); + } + + if ( oldArgs.length() ) + ui->txtDeviceArgs->setText( oldArgs ); + + ui->centerFrequency->setValueRange(7, + unsigned(m_freqMin / 1000.0), + unsigned(m_freqMax / 1000.0)); + + ui->centerFrequency->setValue(m_generalSettings.m_centerFrequency / 1000); + + ui->sldFreqCorr->setRange(-100, +100); + ui->sldFreqCorr->setValue( m_freqCorr ); + ui->lblFreqCorr->setText(tr("%1").arg(ui->sldFreqCorr->value())); + + m_gainControls.clear(); + QVBoxLayout *layoutGains = ui->verticalLayoutGains; + QLayoutItem *layoutItem; + + while ( ( layoutItem = layoutGains->takeAt( 0 ) ) != NULL ) + { + QLayout *layout = layoutItem->layout(); + + if ( !layout ) + continue; + + while ( ( layoutItem = layout->takeAt( 0 ) ) != NULL ) + { + delete layoutItem->widget(); + delete layoutItem; + } + + delete layout; + } + + for ( int i = 0; i < m_namedGains.size(); i++ ) + { + std::pair< QString, std::vector > pair = m_namedGains[i]; + + QHBoxLayout *layout = new QHBoxLayout(); + QLabel *gainName = new QLabel( pair.first + " Gain" ); + QSlider *gainSlider = new QSlider(Qt::Horizontal); + QLabel *gainLabel = new QLabel("0"); + gainLabel->setMinimumWidth(30); + gainLabel->setAlignment(Qt::AlignHCenter | Qt::AlignHCenter); + + QPair< QSlider*, QLabel* > pair2( gainSlider, gainLabel ); + m_gainControls.push_back( pair2 ); + + connect(gainSlider, SIGNAL(valueChanged(int)), + this, SLOT(on_sldGain_valueChanged(int))); + + layout->addWidget(gainName); + layout->addWidget(gainSlider); + layout->addWidget(gainLabel); + + layoutGains->addLayout(layout); + + std::vector gain_values = pair.second; + + if ( gain_values.size() ) { + gainSlider->setRange(0, gain_values.size() - 1); + gainSlider->setValue(gain_values.size() / 4); + gainSlider->setEnabled(true); + } else { + gainSlider->setEnabled(false); + } + } + + oldIndex = ui->cboSampleRate->currentIndex(); + ui->cboSampleRate->clear(); + + for ( int i = 0; i < m_sampRates.size(); i++ ) + ui->cboSampleRate->addItem( QString::number(m_sampRates[i] / 1e6) ); + + if ( oldIndex > ui->cboSampleRate->count() - 1 ) + oldIndex = 0; + + if ( ui->cboSampleRate->count() && oldIndex >= 0 ) + ui->cboSampleRate->setCurrentIndex(oldIndex); + + if ( ui->cboSampleRate->count() ) { + ui->cboSampleRate->setEnabled(true); + } else { + ui->cboSampleRate->setEnabled(false); + } + + oldIndex = ui->cboAntennas->currentIndex(); + ui->cboAntennas->clear(); + + if ( m_antennas.size() ) { + for ( int i = 0; i < m_antennas.size(); i++ ) + ui->cboAntennas->addItem( m_antennas[i] ); + + if ( oldIndex > ui->cboAntennas->count() - 1 ) + oldIndex = 0; + + if ( ui->cboAntennas->count() && oldIndex >= 0 ) + ui->cboAntennas->setCurrentIndex(oldIndex); + + ui->cboAntennas->setEnabled(true); + } else { + ui->cboAntennas->setEnabled(false); + } + + oldIndex = ui->cboDCOffset->currentIndex(); + ui->cboDCOffset->clear(); + + if ( m_dcoffs.size() ) { + for ( int i = 0; i < m_dcoffs.size(); i++ ) + ui->cboDCOffset->addItem( m_dcoffs[i] ); + + if ( ui->cboDCOffset->count() && oldIndex >= 0 ) + ui->cboDCOffset->setCurrentIndex(oldIndex); + + ui->cboDCOffset->setEnabled(true); + } else { + ui->cboDCOffset->setEnabled(false); + } + + oldIndex = ui->cboIQBalance->currentIndex(); + ui->cboIQBalance->clear(); + + if ( m_iqbals.size() ) { + for ( int i = 0; i < m_iqbals.size(); i++ ) + ui->cboIQBalance->addItem( m_iqbals[i] ); + + if ( ui->cboIQBalance->count() && oldIndex >= 0 ) + ui->cboIQBalance->setCurrentIndex(oldIndex); + + ui->cboIQBalance->setEnabled(true); + } else { + ui->cboIQBalance->setEnabled(false); + } + + oldIndex = ui->cboBandwidth->currentIndex(); + ui->cboBandwidth->clear(); + + for ( int i = 0; i < m_bandwidths.size(); i++ ) + if ( 0.0 == m_bandwidths[i] ) + ui->cboBandwidth->addItem( "Auto" ); + else + ui->cboBandwidth->addItem( QString::number(m_bandwidths[i] / 1e6) ); + + if ( oldIndex > ui->cboBandwidth->count() - 1 ) + oldIndex = 0; + + if ( ui->cboBandwidth->count() && oldIndex >= 0 ) + ui->cboBandwidth->setCurrentIndex(oldIndex); + + if ( ui->cboBandwidth->count() ) { + ui->cboBandwidth->setEnabled(true); + } else { + ui->cboBandwidth->setEnabled(false); + } +} + +void GNURadioGui::sendSettings() +{ + if(!m_updateTimer.isActive()) + m_updateTimer.start(100); +} + +void GNURadioGui::updateHardware() +{ + m_updateTimer.stop(); + GNURadioInput::MsgConfigureGNURadio* msg = GNURadioInput::MsgConfigureGNURadio::create(m_generalSettings, m_settings); + msg->submit(m_pluginAPI->getDSPEngineMessageQueue()); +} + +void GNURadioGui::on_cboDevices_currentIndexChanged(int index) +{ + if ( index < 0 || index >= m_devs.count() ) + return; + + ui->txtDeviceArgs->setText( m_devs[index].second ); +} + +void GNURadioGui::on_txtDeviceArgs_textChanged(const QString &arg1) +{ + m_settings.m_args = arg1; + sendSettings(); +} + +void GNURadioGui::on_centerFrequency_changed(quint64 value) +{ + m_generalSettings.m_centerFrequency = value * 1000; + sendSettings(); +} + +void GNURadioGui::on_sldFreqCorr_valueChanged(int value) +{ + ui->lblFreqCorr->setText(tr("%1").arg(value)); + m_settings.m_freqCorr = value; + sendSettings(); +} + +void GNURadioGui::on_sldGain_valueChanged(int value) +{ + m_settings.m_namedGains.clear(); + + for ( int i = 0; i < m_gainControls.size(); i++ ) + { + QPair< QSlider*, QLabel* > controls = m_gainControls[i]; + + QSlider *slider = controls.first; + QLabel *label = controls.second; + + std::pair< QString, std::vector > named_gain = m_namedGains[ i ]; + + int index = slider->value(); + double gain = named_gain.second[index]; + label->setText(tr("%1").arg(gain)); + + QPair< QString, double > named_gain2( named_gain.first, gain ); + m_settings.m_namedGains.push_back( named_gain2 ); + } + + sendSettings(); +} + +void GNURadioGui::on_cboSampleRate_currentIndexChanged(int index) +{ + if ( index < 0 || index >= m_sampRates.size() ) + return; + + m_settings.m_sampRate = m_sampRates[index]; + sendSettings(); +} + +void GNURadioGui::on_cboAntennas_currentIndexChanged(const QString &arg1) +{ + m_settings.m_antenna = arg1; + sendSettings(); +} + +void GNURadioGui::on_cboDCOffset_currentIndexChanged(const QString &arg1) +{ + m_settings.m_dcoff = arg1; + sendSettings(); +} + +void GNURadioGui::on_cboIQBalance_currentIndexChanged(const QString &arg1) +{ + m_settings.m_iqbal = arg1; + sendSettings(); +} + +void GNURadioGui::on_cboBandwidth_currentIndexChanged(int index) +{ + if ( index < 0 || index >= m_bandwidths.size() ) + return; + + m_settings.m_bandwidth = m_bandwidths[index]; + sendSettings(); +} diff --git a/plugins/samplesource/gnuradio/gnuradiogui.h b/plugins/samplesource/gnuradio/gnuradiogui.h new file mode 100644 index 000000000..900ceba80 --- /dev/null +++ b/plugins/samplesource/gnuradio/gnuradiogui.h @@ -0,0 +1,99 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2013 by Dimitri Stolnikov // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_GNURADIOGUI_H +#define INCLUDE_GNURADIOGUI_H + +#include +#include +#include +#include +#include +#include +#include "plugin/plugingui.h" +#include "gnuradioinput.h" + +namespace Ui { +class GNURadioGui; +} + +class PluginAPI; + +class GNURadioGui : public QWidget, public PluginGUI { + Q_OBJECT + +public: + explicit GNURadioGui(PluginAPI* pluginAPI, QWidget* parent = NULL); + ~GNURadioGui(); + void destroy(); + + void setName(const QString& name); + + void resetToDefaults(); + QByteArray serializeGeneral() const; + bool deserializeGeneral(const QByteArray&data); + quint64 getCenterFrequency() const; + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + bool handleMessage(Message* message); + +private: + Ui::GNURadioGui* ui; + PluginAPI* m_pluginAPI; + SampleSource* m_sampleSource; + QList< QPair > m_devs; + std::vector< std::pair< QString, std::vector > > m_namedGains; + double m_freqMin; + double m_freqMax; + double m_freqCorr; + std::vector m_sampRates; + std::vector m_antennas; + std::vector m_dcoffs; + std::vector m_iqbals; + std::vector m_bandwidths; + + std::vector< QSlider* > m_gainSliders; + std::vector< QLabel* > m_gainLabels; + + QList< QPair< QSlider*, QLabel* > > m_gainControls; + + SampleSource::GeneralSettings m_generalSettings; + GNURadioInput::Settings m_settings; + QTimer m_updateTimer; + + void displaySettings(); + void sendSettings(); + +private slots: + void updateHardware(); + + void on_cboDevices_currentIndexChanged(int index); + void on_txtDeviceArgs_textChanged(const QString &arg1); + void on_centerFrequency_changed(quint64 value); + void on_sldFreqCorr_valueChanged(int value); + + void on_sldGain_valueChanged(int value); + + void on_cboSampleRate_currentIndexChanged(int index); + void on_cboAntennas_currentIndexChanged(const QString &arg1); + void on_cboDCOffset_currentIndexChanged(const QString &arg1); + void on_cboIQBalance_currentIndexChanged(const QString &arg1); + void on_cboBandwidth_currentIndexChanged(int index); +}; + +#endif // INCLUDE_GNURADIOGUI_H diff --git a/plugins/samplesource/gnuradio/gnuradiogui.ui b/plugins/samplesource/gnuradio/gnuradiogui.ui new file mode 100644 index 000000000..fe1aaef82 --- /dev/null +++ b/plugins/samplesource/gnuradio/gnuradiogui.ui @@ -0,0 +1,301 @@ + + + GNURadioGui + + + + 0 + 0 + 186 + 261 + + + + + 0 + 0 + + + + Gnuradio Source + + + + 3 + + + 0 + + + 2 + + + 0 + + + 2 + + + + + + + 2 + + + + + true + + + + 0 + 0 + + + + false + + + QComboBox::AdjustToMinimumContentsLength + + + + + + + true + + + + + + + + + + + Qt::Horizontal + + + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + Monospace + 20 + + + + Qt::StrongFocus + + + Tuner center frequency in kHz + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + + Qt::Horizontal + + + + + + + 3 + + + + + Freq. Corr. + + + + + + + -100 + + + 100 + + + true + + + Qt::Horizontal + + + + + + + + 30 + 0 + + + + Qt::LeftToRight + + + + + + Qt::AlignCenter + + + + + + + + + + + + 3 + + + + + Sample Rate (MHz) + + + Qt::AutoText + + + + + + + QComboBox::AdjustToMinimumContentsLength + + + + + + + + + 3 + + + + + Selected Antenna + + + + + + + true + + + + + + + + + + + DC Offset Corr. + + + + + + + + + + + + 3 + + + + + IQ Imbalance Corr. + + + + + + + + + + + + + + Bandwidth (MHz) + + + + + + + + + + + + + ValueDial + QWidget +
gui/valuedial.h
+ 1 +
+
+ + +
diff --git a/plugins/samplesource/gnuradio/gnuradioinput.cpp b/plugins/samplesource/gnuradio/gnuradioinput.cpp new file mode 100644 index 000000000..f3999e169 --- /dev/null +++ b/plugins/samplesource/gnuradio/gnuradioinput.cpp @@ -0,0 +1,332 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2013 by Dimitri Stolnikov // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "util/simpleserializer.h" +#include "gnuradioinput.h" +#include "gnuradiothread.h" +#include "gnuradiogui.h" + +MESSAGE_CLASS_DEFINITION(GNURadioInput::MsgConfigureGNURadio, Message) +MESSAGE_CLASS_DEFINITION(GNURadioInput::MsgReportGNURadio, Message) + +GNURadioInput::Settings::Settings() : + m_args(""), + m_freqCorr(0), + m_sampRate(0), + m_antenna(""), + m_dcoff(""), + m_iqbal(""), + m_bandwidth(0) +{ +} + +void GNURadioInput::Settings::resetToDefaults() +{ + m_args = ""; + m_sampRate = 0; + m_freqCorr = 0; + m_antenna = ""; + m_dcoff = ""; + m_iqbal = ""; + m_bandwidth = 0; +} + +QByteArray GNURadioInput::Settings::serialize() const +{ + SimpleSerializer s(1); +// s.writeString(1, m_args); +// s.writeDouble(2, m_freqCorr); +// s.writeDouble(3, m_sampRate); +// s.writeString(4, m_antenna); +// s.writeString(5, m_dcoff); +// s.writeString(5, m_iqbal); + return s.final(); +} + +bool GNURadioInput::Settings::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { +// d.readString(1, &m_args, ""); +// d.readDouble(2, &m_freqCorr, 0); +// d.readDouble(3, &m_sampRate, 0); +// d.readString(4, &m_antenna, ""); +// d.readString(5, &m_dcoff, ""); +// d.readString(5, &m_iqbal, ""); + return true; + } else { + resetToDefaults(); + return false; + } +} + +GNURadioInput::GNURadioInput(MessageQueue* msgQueueToGUI) : + SampleSource(msgQueueToGUI), + m_settings(), + m_GnuradioThread(NULL), + m_deviceDescription() +{ +} + +GNURadioInput::~GNURadioInput() +{ + stopInput(); +} + +bool GNURadioInput::startInput(int device) +{ + double freqMin = 0, freqMax = 0, freqCorr = 0; + std::vector< std::pair< QString, std::vector > > namedGains; + std::vector< double > sampRates; + std::vector< QString > antennas; + std::vector< double > bandwidths; + + QMutexLocker mutexLocker(&m_mutex); + + if(m_GnuradioThread != NULL) + stopInput(); + + if(!m_sampleFifo.setSize( 2 * 1024 * 1024 )) { + qCritical("Could not allocate SampleFifo"); + return false; + } + + m_deviceDescription = m_settings.m_args; + + // pass device arguments from the gui + m_GnuradioThread = new GnuradioThread(m_settings.m_args, &m_sampleFifo); + if(m_GnuradioThread == NULL) { + qFatal("out of memory"); + goto failed; + } + m_GnuradioThread->startWork(); + + mutexLocker.unlock(); + applySettings(m_generalSettings, m_settings, true); + + if(m_GnuradioThread != NULL) { + osmosdr::source::sptr radio = m_GnuradioThread->radio(); + + try { + osmosdr::freq_range_t freq_rage = radio->get_freq_range(); + freqMin = freq_rage.start(); + freqMax = freq_rage.stop(); + } catch ( std::exception &ex ) { + qDebug("%s", ex.what()); + } + + freqCorr = radio->get_freq_corr(); + + namedGains.clear(); + m_settings.m_namedGains.clear(); + std::vector< std::string > gain_names = radio->get_gain_names(); + for ( int i = 0; i < gain_names.size(); i++ ) + { + std::string gain_name = gain_names[i]; + + try { + std::vector< double > gain_values = \ + radio->get_gain_range( gain_name ).values(); + + std::pair< QString, std::vector > pair( gain_name.c_str(), + gain_values ); + + namedGains.push_back( pair ); + + QPair< QString, double > pair2( gain_name.c_str(), 0 ); + + m_settings.m_namedGains.push_back( pair2 ); + } catch ( std::exception &ex ) { + qDebug("%s", ex.what()); + } + } + + try { + sampRates = radio->get_sample_rates().values(); + } catch ( std::exception &ex ) { + qDebug("%s", ex.what()); + } + + antennas.clear(); + std::vector< std::string > ant = radio->get_antennas(); + for ( int i = 0; i < ant.size(); i++ ) + antennas.push_back( QString( ant[i].c_str() ) ); + + m_dcoffs.clear(); + m_dcoffs.push_back( "Off" ); + m_dcoffs.push_back( "Keep" ); + m_dcoffs.push_back( "Auto" ); + + m_iqbals.clear(); + m_iqbals.push_back( "Off" ); + m_iqbals.push_back( "Keep" ); + m_iqbals.push_back( "Auto" ); + + try { + bandwidths = radio->get_bandwidth_range().values(); + } catch ( std::exception &ex ) { + qDebug("%s", ex.what()); + } + } + + qDebug("GnuradioInput: start"); + MsgReportGNURadio::create(freqMin, freqMax, freqCorr, namedGains, + sampRates, antennas, m_dcoffs, m_iqbals, + bandwidths) + ->submit(m_guiMessageQueue); + + return true; + +failed: + stopInput(); + return false; +} + +void GNURadioInput::stopInput() +{ + QMutexLocker mutexLocker(&m_mutex); + + if(m_GnuradioThread != NULL) { + m_GnuradioThread->stopWork(); + delete m_GnuradioThread; + m_GnuradioThread = NULL; + } + + m_deviceDescription.clear(); +} + +const QString& GNURadioInput::getDeviceDescription() const +{ + return m_deviceDescription; +} + +int GNURadioInput::getSampleRate() const +{ + return m_settings.m_sampRate; +} + +quint64 GNURadioInput::getCenterFrequency() const +{ + return m_generalSettings.m_centerFrequency; +} + +bool GNURadioInput::handleMessage(Message* message) +{ + if(MsgConfigureGNURadio::match(message)) { + MsgConfigureGNURadio* conf = (MsgConfigureGNURadio*)message; + if(!applySettings(conf->getGeneralSettings(), conf->getSettings(), false)) + qDebug("Gnuradio config error"); + return true; + } else { + return false; + } +} + +bool GNURadioInput::applySettings(const GeneralSettings& generalSettings, + const Settings& settings, + bool force) +{ + QMutexLocker mutexLocker(&m_mutex); + + m_settings.m_args = settings.m_args; + + if ( NULL == m_GnuradioThread ) + return true; + + osmosdr::source::sptr radio = m_GnuradioThread->radio(); + + try { + + if((m_settings.m_freqCorr != settings.m_freqCorr) || force) { + m_settings.m_freqCorr = settings.m_freqCorr; + radio->set_freq_corr( m_settings.m_freqCorr ); + } + + if((m_generalSettings.m_centerFrequency != generalSettings.m_centerFrequency) || force) { + m_generalSettings.m_centerFrequency = generalSettings.m_centerFrequency; + radio->set_center_freq( m_generalSettings.m_centerFrequency ); + } + + for ( int i = 0; i < settings.m_namedGains.size(); i++ ) + { + if((m_settings.m_namedGains[i].second != settings.m_namedGains[i].second) || force) { + m_settings.m_namedGains[i].second = settings.m_namedGains[i].second; + radio->set_gain( settings.m_namedGains[i].second, + settings.m_namedGains[i].first.toStdString() ); + } + } + + if((m_settings.m_sampRate != settings.m_sampRate) || force) { + m_settings.m_sampRate = settings.m_sampRate; + radio->set_sample_rate( m_settings.m_sampRate ); + } + + if((m_settings.m_antenna != settings.m_antenna) || force) { + m_settings.m_antenna = settings.m_antenna; + radio->set_antenna( m_settings.m_antenna.toStdString() ); + } + + if((m_settings.m_dcoff != settings.m_dcoff) || force) { + m_settings.m_dcoff = settings.m_dcoff; + + for ( int i = 0; i < m_dcoffs.size(); i++ ) + { + if ( m_dcoffs[i] != m_settings.m_dcoff ) + continue; + + radio->set_dc_offset_mode( i ); + break; + } + } + + if((m_settings.m_iqbal != settings.m_iqbal) || force) { + m_settings.m_iqbal = settings.m_iqbal; + + for ( int i = 0; i < m_iqbals.size(); i++ ) + { + if ( m_iqbals[i] != m_settings.m_iqbal ) + continue; + + radio->set_iq_balance_mode( i ); + break; + } + } + + if((m_settings.m_bandwidth != settings.m_bandwidth) || + (0.0f == settings.m_bandwidth) || force) { + m_settings.m_bandwidth = settings.m_bandwidth; + /* setting the BW to 0.0 triggers automatic bandwidth + * selection when supported by device */ + radio->set_bandwidth( m_settings.m_bandwidth ); + } + + } catch ( std::exception &ex ) { + qDebug("%s", ex.what()); + return false; + } + + return true; +} diff --git a/plugins/samplesource/gnuradio/gnuradioinput.h b/plugins/samplesource/gnuradio/gnuradioinput.h new file mode 100644 index 000000000..de2da43fe --- /dev/null +++ b/plugins/samplesource/gnuradio/gnuradioinput.h @@ -0,0 +1,156 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2013 by Dimitri Stolnikov // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_GNURADIOINPUT_H +#define INCLUDE_GNURADIOINPUT_H + +#include "dsp/samplesource/samplesource.h" +#include +#include + +class GnuradioThread; + +class GNURadioInput : public SampleSource { +public: + struct Settings { + QString m_args; + double m_freqMin; + double m_freqMax; + double m_freqCorr; + QList< QPair< QString, double > > m_namedGains; + double m_sampRate; + QString m_antenna; + QString m_dcoff; + QString m_iqbal; + double m_bandwidth; + + Settings(); + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + }; + + class MsgConfigureGNURadio : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const GeneralSettings& getGeneralSettings() const { return m_generalSettings; } + const Settings& getSettings() const { return m_settings; } + + static MsgConfigureGNURadio* create(const GeneralSettings& generalSettings, const Settings& settings) + { + return new MsgConfigureGNURadio(generalSettings, settings); + } + + protected: + GeneralSettings m_generalSettings; + Settings m_settings; + + MsgConfigureGNURadio(const GeneralSettings& generalSettings, const Settings& settings) : + Message(), + m_generalSettings(generalSettings), + m_settings(settings) + { } + }; + + class MsgReportGNURadio : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const std::vector< std::pair< QString, std::vector > >& getNamedGains() const { return m_namedGains; } + const double getFreqMin() const { return m_freqMin; } + const double getFreqMax() const { return m_freqMax; } + const double getFreqCorr() const { return m_freqCorr; } + const std::vector& getSampRates() const { return m_sampRates; } + const std::vector& getAntennas() const { return m_antennas; } + const std::vector& getDCOffs() const { return m_dcoffs; } + const std::vector& getIQBals() const { return m_iqbals; } + const std::vector& getBandwidths() const { return m_bandwidths; } + + static MsgReportGNURadio* create(const double freqMin, + const double freqMax, + const double freqCorr, + const std::vector< std::pair< QString, std::vector > >& namedGains, + const std::vector& sampRates, + const std::vector& antennas, + const std::vector& dcoffs, + const std::vector& iqbals, + const std::vector& bandwidths) + { + return new MsgReportGNURadio(freqMin, freqMax, freqCorr, namedGains, sampRates, antennas, dcoffs, iqbals, bandwidths); + } + + protected: + double m_freqMin; + double m_freqMax; + double m_freqCorr; + std::vector< std::pair< QString, std::vector > > m_namedGains; + std::vector m_sampRates; + std::vector m_antennas; + std::vector m_dcoffs; + std::vector m_iqbals; + std::vector m_bandwidths; + + MsgReportGNURadio(const double freqMin, + const double freqMax, + const double freqCorr, + const std::vector< std::pair< QString, std::vector > >& namedGains, + const std::vector& sampRates, + const std::vector& antennas, + const std::vector& dcoffs, + const std::vector& iqbals, + const std::vector& bandwidths) : + Message(), + m_freqMin(freqMin), + m_freqMax(freqMax), + m_freqCorr(freqCorr), + m_namedGains(namedGains), + m_sampRates(sampRates), + m_antennas(antennas), + m_dcoffs(dcoffs), + m_iqbals(iqbals), + m_bandwidths(bandwidths) + { } + }; + + GNURadioInput(MessageQueue* msgQueueToGUI); + ~GNURadioInput(); + + bool startInput(int device); + void stopInput(); + + const QString& getDeviceDescription() const; + int getSampleRate() const; + quint64 getCenterFrequency() const; + + bool handleMessage(Message* message); + +private: + QMutex m_mutex; + Settings m_settings; + GnuradioThread* m_GnuradioThread; + QString m_deviceDescription; + std::vector< QString > m_dcoffs; + std::vector< QString > m_iqbals; + + bool applySettings(const GeneralSettings& generalSettings, + const Settings& settings, + bool force); +}; + +#endif // INCLUDE_GNURADIOINPUT_H diff --git a/plugins/samplesource/gnuradio/gnuradioplugin.cpp b/plugins/samplesource/gnuradio/gnuradioplugin.cpp new file mode 100644 index 000000000..8ad218087 --- /dev/null +++ b/plugins/samplesource/gnuradio/gnuradioplugin.cpp @@ -0,0 +1,52 @@ +#include +#include +#include "plugin/pluginapi.h" +#include "util/simpleserializer.h" +#include "gnuradioplugin.h" +#include "gnuradiogui.h" + +const PluginDescriptor GNURadioPlugin::m_pluginDescriptor = { + QString("GR-OsmoSDR Input"), + QString("1.0"), + QString("(c) Dimitri Stolnikov "), + QString("http://sdr.osmocom.org/trac/wiki/GrOsmoSDR"), + true, + QString("http://cgit.osmocom.org/cgit/gr-osmosdr") +}; + +GNURadioPlugin::GNURadioPlugin(QObject* parent) : + QObject(parent) +{ +} + +const PluginDescriptor& GNURadioPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void GNURadioPlugin::initPlugin(PluginAPI* pluginAPI) +{ + m_pluginAPI = pluginAPI; + + m_pluginAPI->registerSampleSource("org.osmocom.sdr.samplesource.gr-osmosdr", this); +} + +PluginInterface::SampleSourceDevices GNURadioPlugin::enumSampleSources() +{ + SampleSourceDevices result; + + result.append(SampleSourceDevice("GNURadio OsmoSDR Driver", "org.osmocom.sdr.samplesource.gr-osmosdr", QByteArray())); + + return result; +} + +PluginGUI* GNURadioPlugin::createSampleSource(const QString& sourceName, const QByteArray& address) +{ + if(sourceName == "org.osmocom.sdr.samplesource.gr-osmosdr") { + GNURadioGui* gui = new GNURadioGui(m_pluginAPI); + m_pluginAPI->setInputGUI(gui); + return gui; + } else { + return NULL; + } +} diff --git a/plugins/samplesource/gnuradio/gnuradioplugin.h b/plugins/samplesource/gnuradio/gnuradioplugin.h new file mode 100644 index 000000000..0ff434708 --- /dev/null +++ b/plugins/samplesource/gnuradio/gnuradioplugin.h @@ -0,0 +1,27 @@ +#ifndef INCLUDE_GNURADIOPLUGIN_H +#define INCLUDE_GNURADIOPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class GNURadioPlugin : public QObject, PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID "org.osmocom.sdr.samplesource.gr-osmosdr") + +public: + explicit GNURadioPlugin(QObject* parent = NULL); + + const PluginDescriptor& getPluginDescriptor() const; + void initPlugin(PluginAPI* pluginAPI); + + SampleSourceDevices enumSampleSources(); + PluginGUI* createSampleSource(const QString& sourceName, const QByteArray& address); + +private: + static const PluginDescriptor m_pluginDescriptor; + + PluginAPI* m_pluginAPI; +}; + +#endif // INCLUDE_GNURADIOPLUGIN_H diff --git a/plugins/samplesource/gnuradio/gnuradiothread.cpp b/plugins/samplesource/gnuradio/gnuradiothread.cpp new file mode 100644 index 000000000..9e70d3ebb --- /dev/null +++ b/plugins/samplesource/gnuradio/gnuradiothread.cpp @@ -0,0 +1,144 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2013 by Dimitri Stolnikov // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "gnuradiothread.h" +#include "dsp/samplefifo.h" + +#include +#include + +//////////////////////////////////////////////////////////////////////////////// +class gr_adaptor; + +typedef boost::shared_ptr< gr_adaptor > gr_adaptor_sptr; + +gr_adaptor_sptr make_gr_adaptor (SampleFifo* sampleFifo); + +class gr_adaptor : public gr::sync_block +{ +public: + gr_adaptor (SampleFifo* sampleFifo); + ~gr_adaptor (); + + int work (int noutput_items, + gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items); + +private: + SampleFifo *m_sampleFifo; +}; + +gr_adaptor_sptr +make_gr_adaptor (SampleFifo *sampleFifo) +{ + return gr_adaptor_sptr (new gr_adaptor (sampleFifo)); +} + +gr_adaptor::gr_adaptor (SampleFifo *sampleFifo) + : gr::sync_block("gr_adaptor", + gr::io_signature::make(1, 1, sizeof (gr_complex)), + gr::io_signature::make(0, 0, 0)), + m_sampleFifo(sampleFifo) +{ +} + +gr_adaptor::~gr_adaptor () +{ +} + +int +gr_adaptor::work (int noutput_items, + gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) +{ + const gr_complex *in = (const gr_complex *) input_items[0]; + + std::vector buffer(noutput_items * 2, 0); + std::vector::iterator it = buffer.begin(); + + for (int i = 0; i < noutput_items; i++) + { + *it++ = in[i].real() * 32000; + *it++ = in[i].imag() * 32000; + } + + // we must push at least 4 bytes into the fifo + m_sampleFifo->write((const quint8*)buffer.data(), + (it - buffer.begin()) * sizeof(qint16)); + + // Tell runtime system how many input items we consumed on + // each input stream. + consume_each(noutput_items); + + // Tell runtime system how many output items we produced. + return 0; +} + +//////////////////////////////////////////////////////////////////////////////// +GnuradioThread::GnuradioThread(QString args, SampleFifo* sampleFifo, QObject* parent) : + QThread(parent), + m_running(false), + m_args(args), + m_sampleFifo(sampleFifo) +{ +} + +GnuradioThread::~GnuradioThread() +{ + stopWork(); +} + +void GnuradioThread::startWork() +{ + m_startWaitMutex.lock(); + + start(); + while(!m_running) + m_startWaiter.wait(&m_startWaitMutex, 100); + + m_startWaitMutex.unlock(); +} + +void GnuradioThread::stopWork() +{ + m_running = false; + + m_top->stop(); + + wait(); +} + +void GnuradioThread::run() +{ + m_top = gr::make_top_block( "flowgraph" ); + m_src = osmosdr::source::make( m_args.toStdString() ); + + /* now since we've constructed our shared objects, we allow the calling + * thread to continue it's work and send some radio settings to us. */ + m_running = true; + m_startWaiter.wakeAll(); + + gr_adaptor_sptr adaptor = make_gr_adaptor(m_sampleFifo); + m_top->connect(m_src, 0, adaptor, 0); + + m_top->run(); + + m_running = false; +} diff --git a/plugins/samplesource/gnuradio/gnuradiothread.h b/plugins/samplesource/gnuradio/gnuradiothread.h new file mode 100644 index 000000000..651238d51 --- /dev/null +++ b/plugins/samplesource/gnuradio/gnuradiothread.h @@ -0,0 +1,64 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// Copyright (C) 2013 by Dimitri Stolnikov // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_GNURADIOTHREAD_H +#define INCLUDE_GNURADIOTHREAD_H + +#include +#include +#include + +#include +#include + +class SampleFifo; + +class GnuradioThread : public QThread { + Q_OBJECT + +public: + GnuradioThread(QString args, SampleFifo* sampleFifo, QObject* parent = NULL); + ~GnuradioThread(); + + void startWork(); + void stopWork(); + + osmosdr::source::sptr radio() { return m_src; } + +private: +#pragma pack(push, 1) + struct Sample { + qint16 i; + qint16 q; + }; +#pragma pack(pop) + + QMutex m_startWaitMutex; + QWaitCondition m_startWaiter; + bool m_running; + + QString m_args; + SampleFifo* m_sampleFifo; + + gr::top_block_sptr m_top; + osmosdr::source::sptr m_src; + + void run(); +}; + +#endif // INCLUDE_GNURADIOTHREAD_H diff --git a/plugins/samplesource/osmosdr/CMakeLists.txt b/plugins/samplesource/osmosdr/CMakeLists.txt new file mode 100644 index 000000000..9dc97059d --- /dev/null +++ b/plugins/samplesource/osmosdr/CMakeLists.txt @@ -0,0 +1,54 @@ +project(osmosdr) + +set(osmosdr_SOURCES + osmosdrgui.cpp + osmosdrinput.cpp + osmosdrplugin.cpp + osmosdrthread.cpp +) + +set(osmosdr_HEADERS + osmosdrgui.h + osmosdrinput.h + osmosdrplugin.h + osmosdrthread.h +) + +set(osmosdr_FORMS + osmosdrgui.ui +) + +include_directories( + . + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include-gpl + ${LIBOSMOSDR_INCLUDE_DIR} +) + +#include(${QT_USE_FILE}) +add_definitions(${QT_DEFINITIONS}) +add_definitions(-DQT_PLUGIN) +add_definitions(-DQT_SHARED) + +if(MSVC) +add_definitions(-DNOMINMAX) +endif() + +#qt4_wrap_cpp(osmosdr_HEADERS_MOC ${osmosdr_HEADERS}) +qt5_wrap_ui(osmosdr_FORMS_HEADERS ${osmosdr_FORMS}) + +add_library(inputosmosdr SHARED + ${osmosdr_SOURCES} + ${osmosdr_HEADERS_MOC} + ${osmosdr_FORMS_HEADERS} +) + +target_link_libraries(inputosmosdr + ${QT_LIBRARIES} + ${LIBOSMOSDR_LIBRARIES} + ${LIBUSB_LIBRARIES} + sdrbase +) + +qt5_use_modules(inputosmosdr Core Widgets OpenGL Multimedia) diff --git a/plugins/samplesource/osmosdr/osmosdrgui.cpp b/plugins/samplesource/osmosdr/osmosdrgui.cpp new file mode 100644 index 000000000..3ecaa355d --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrgui.cpp @@ -0,0 +1,310 @@ +#include "osmosdrgui.h" +#include "ui_osmosdrgui.h" +#include "plugin/pluginapi.h" + +OsmoSDRGui::OsmoSDRGui(PluginAPI* pluginAPI, QWidget* parent) : + QWidget(parent), + ui(new Ui::OsmoSDRGui), + m_pluginAPI(pluginAPI), + m_settings(), + m_sampleSource(NULL) +{ + ui->setupUi(this); + ui->centerFrequency->setValueRange(7, 20000U, 2200000U); + connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(updateHardware())); + displaySettings(); + + m_sampleSource = new OsmoSDRInput(m_pluginAPI->getMainWindowMessageQueue()); + m_pluginAPI->setSampleSource(m_sampleSource); +} + +OsmoSDRGui::~OsmoSDRGui() +{ + delete ui; +} + +void OsmoSDRGui::destroy() +{ + delete this; +} + +void OsmoSDRGui::setName(const QString& name) +{ + setObjectName(name); +} + +void OsmoSDRGui::resetToDefaults() +{ + m_generalSettings.resetToDefaults(); + m_settings.resetToDefaults(); + displaySettings(); + sendSettings(); +} + +QByteArray OsmoSDRGui::serializeGeneral() const +{ + return m_generalSettings.serialize(); +} + +bool OsmoSDRGui::deserializeGeneral(const QByteArray&data) +{ + if(m_generalSettings.deserialize(data)) { + displaySettings(); + sendSettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +quint64 OsmoSDRGui::getCenterFrequency() const +{ + return m_generalSettings.m_centerFrequency; +} + +QByteArray OsmoSDRGui::serialize() const +{ + return m_settings.serialize(); +} + +bool OsmoSDRGui::deserialize(const QByteArray& data) +{ + if(m_settings.deserialize(data)) { + displaySettings(); + sendSettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +bool OsmoSDRGui::handleMessage(Message* message) +{ + return false; + /* + if(message->id() == OsmoSDRInput::MsgReportOsmoSDR::ID()) { + m_gains = ((RTLSDRInput::MsgReportRTLSDR*)message)->getGains(); + displaySettings(); + message->completed(); + return true; + } else { + return false; + }*/ +} +#if 0 + +OsmoSDRGui::OsmoSDRGui(MessageQueue* msgQueue, QWidget* parent) : + SampleSourceGUI(parent), + ui(new Ui::OsmoSDRGui), + m_msgQueue(msgQueue), + m_settings() +{ + ui->setupUi(this); + ui->centerFrequency->setValueRange(7, 20000U, 2200000U); + connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(updateHardware())); + displaySettings(); +} + +OsmoSDRGui::~OsmoSDRGui() +{ + delete ui; +} + +QString OsmoSDRGui::serializeSettings() const +{ + return m_settings.serialize(); +} + +bool OsmoSDRGui::deserializeSettings(const QString& settings) +{ + if(m_settings.deserialize(settings)) { + displaySettings(); + sendSettings(); + return true; + } else { + return false; + } +} + +bool OsmoSDRGui::handleSourceMessage(DSPCmdSourceToGUI* cmd) +{ + return false; +} +#endif + +void OsmoSDRGui::displaySettings() +{ + ui->centerFrequency->setValue(m_generalSettings.m_centerFrequency / 1000); + ui->iqSwap->setChecked(m_settings.m_swapIQ); + ui->decimation->setValue(m_settings.m_decimation); + ui->e4000LNAGain->setValue(e4kLNAGainToIdx(m_settings.m_lnaGain)); + + ui->e4000MixerGain->setCurrentIndex((m_settings.m_mixerGain - 40) / 80); + if(m_settings.m_mixerEnhancement == 0) + ui->e4000MixerEnh->setCurrentIndex(0); + else ui->e4000MixerEnh->setCurrentIndex((m_settings.m_mixerEnhancement + 10) / 20); + + ui->e4000if1->setCurrentIndex((m_settings.m_if1gain + 30) / 90); + ui->e4000if2->setCurrentIndex(m_settings.m_if2gain / 30); + ui->e4000if3->setCurrentIndex(m_settings.m_if3gain / 30); + ui->e4000if4->setCurrentIndex(m_settings.m_if4gain / 10); + ui->e4000if5->setCurrentIndex(m_settings.m_if5gain / 30 - 1); + ui->e4000if6->setCurrentIndex(m_settings.m_if6gain / 30 - 1); + ui->filterI1->setValue(m_settings.m_opAmpI1); + ui->filterI2->setValue(m_settings.m_opAmpI2); + ui->filterQ1->setValue(m_settings.m_opAmpQ1); + ui->filterQ2->setValue(m_settings.m_opAmpQ2); + + ui->e4kI->setValue(m_settings.m_dcOfsI); + ui->e4kQ->setValue(m_settings.m_dcOfsQ); +} + +void OsmoSDRGui::sendSettings() +{ + if(!m_updateTimer.isActive()) + m_updateTimer.start(100); +} + +int OsmoSDRGui::e4kLNAGainToIdx(int gain) const +{ + static const quint32 gainList[13] = { + -50, -25, 0, 25, 50, 75, 100, 125, 150, 175, 200, 250, 300 + }; + for(int i = 0; i < 13; i++) { + if(gainList[i] == gain) + return i; + } + return 0; +} + +int OsmoSDRGui::e4kIdxToLNAGain(int idx) const +{ + static const quint32 gainList[13] = { + -50, -25, 0, 25, 50, 75, 100, 125, 150, 175, 200, 250, 300 + }; + if((idx < 0) || (idx >= 13)) + return -50; + else return gainList[idx]; +} + +void OsmoSDRGui::on_iqSwap_toggled(bool checked) +{ + m_settings.m_swapIQ = checked; + sendSettings(); +} + +void OsmoSDRGui::on_e4000MixerGain_currentIndexChanged(int index) +{ + m_settings.m_mixerGain = index * 80 + 40; + sendSettings(); +} + +void OsmoSDRGui::on_e4000MixerEnh_currentIndexChanged(int index) +{ + if(index == 0) + m_settings.m_mixerEnhancement = 0; + else m_settings.m_mixerEnhancement = index * 20 - 10; + sendSettings(); +} + +void OsmoSDRGui::on_e4000if1_currentIndexChanged(int index) +{ + m_settings.m_if1gain = index * 90 - 30; + sendSettings(); +} + +void OsmoSDRGui::on_e4000if2_currentIndexChanged(int index) +{ + m_settings.m_if2gain = index * 30; + sendSettings(); +} + +void OsmoSDRGui::on_e4000if3_currentIndexChanged(int index) +{ + m_settings.m_if3gain = index * 30; + sendSettings(); +} + +void OsmoSDRGui::on_e4000if4_currentIndexChanged(int index) +{ + m_settings.m_if4gain = index * 10; + sendSettings(); +} + +void OsmoSDRGui::on_e4000if5_currentIndexChanged(int index) +{ + m_settings.m_if5gain = (index + 1) * 30; + sendSettings(); +} + +void OsmoSDRGui::on_e4000if6_currentIndexChanged(int index) +{ + m_settings.m_if6gain = (index + 1) * 30; + sendSettings(); +} + +void OsmoSDRGui::on_centerFrequency_changed(quint64 value) +{ + m_generalSettings.m_centerFrequency = value * 1000; + sendSettings(); +} + +void OsmoSDRGui::on_filterI1_valueChanged(int value) +{ + m_settings.m_opAmpI1 = value; + sendSettings(); +} + +void OsmoSDRGui::on_filterI2_valueChanged(int value) +{ + m_settings.m_opAmpI2 = value; + sendSettings(); +} + +void OsmoSDRGui::on_filterQ1_valueChanged(int value) +{ + m_settings.m_opAmpQ1 = value; + sendSettings(); +} + +void OsmoSDRGui::on_filterQ2_valueChanged(int value) +{ + m_settings.m_opAmpQ2 = value; + sendSettings(); +} + +void OsmoSDRGui::on_decimation_valueChanged(int value) +{ + ui->decimationDisplay->setText(tr("1:%1").arg(1 << value)); + m_settings.m_decimation = value; + sendSettings(); +} + +void OsmoSDRGui::on_e4000LNAGain_valueChanged(int value) +{ + int gain = e4kIdxToLNAGain(value); + ui->e4000LNAGainDisplay->setText(tr("%1.%2").arg(gain / 10).arg(abs(gain % 10))); + m_settings.m_lnaGain = gain; + sendSettings(); +} + +void OsmoSDRGui::on_e4kI_valueChanged(int value) +{ + m_settings.m_dcOfsI = value; + sendSettings(); +} + +void OsmoSDRGui::on_e4kQ_valueChanged(int value) +{ + m_settings.m_dcOfsQ = value; + sendSettings(); +} + +void OsmoSDRGui::updateHardware() +{ + m_updateTimer.stop(); + Message* msg = OsmoSDRInput::MsgConfigureOsmoSDR::create(m_generalSettings, m_settings); + msg->submit(m_pluginAPI->getDSPEngineMessageQueue()); +} diff --git a/plugins/samplesource/osmosdr/osmosdrgui.h b/plugins/samplesource/osmosdr/osmosdrgui.h new file mode 100644 index 000000000..f043653ea --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrgui.h @@ -0,0 +1,70 @@ +#ifndef INCLUDE_OSMOSDRGUI_H +#define INCLUDE_OSMOSDRGUI_H + +#include +#include "plugin/plugingui.h" +#include "osmosdrinput.h" + +class PluginAPI; + +namespace Ui { + class OsmoSDRGui; +} + +class OsmoSDRGui : public QWidget, public PluginGUI { + Q_OBJECT + +public: + explicit OsmoSDRGui(PluginAPI* pluginAPI, QWidget* parent = NULL); + ~OsmoSDRGui(); + void destroy(); + + void setName(const QString& name); + + void resetToDefaults(); + QByteArray serializeGeneral() const; + bool deserializeGeneral(const QByteArray&data); + quint64 getCenterFrequency() const; + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + bool handleMessage(Message* message); + +private: + Ui::OsmoSDRGui* ui; + + PluginAPI* m_pluginAPI; + SampleSource::GeneralSettings m_generalSettings; + OsmoSDRInput::Settings m_settings; + QTimer m_updateTimer; + std::vector m_gains; + SampleSource* m_sampleSource; + + void displaySettings(); + void sendSettings(); + int e4kLNAGainToIdx(int gain) const; + int e4kIdxToLNAGain(int idx) const; + +private slots: + void on_iqSwap_toggled(bool checked); + void on_e4000MixerGain_currentIndexChanged(int index); + void on_e4000MixerEnh_currentIndexChanged(int index); + void on_e4000if1_currentIndexChanged(int index); + void on_e4000if2_currentIndexChanged(int index); + void on_e4000if3_currentIndexChanged(int index); + void on_e4000if4_currentIndexChanged(int index); + void on_e4000if5_currentIndexChanged(int index); + void on_e4000if6_currentIndexChanged(int index); + void on_centerFrequency_changed(quint64 value); + void on_filterI1_valueChanged(int value); + void on_filterI2_valueChanged(int value); + void on_filterQ1_valueChanged(int value); + void on_filterQ2_valueChanged(int value); + void on_decimation_valueChanged(int value); + void on_e4000LNAGain_valueChanged(int value); + void on_e4kI_valueChanged(int value); + void on_e4kQ_valueChanged(int value); + + void updateHardware(); +}; + +#endif // INCLUDE_OSMOSDRGUI_H diff --git a/plugins/samplesource/osmosdr/osmosdrgui.ui b/plugins/samplesource/osmosdr/osmosdrgui.ui new file mode 100644 index 000000000..e61894102 --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrgui.ui @@ -0,0 +1,770 @@ + + + OsmoSDRGui + + + + 0 + 0 + 253 + 229 + + + + + 0 + 0 + + + + OsmoSDR + + + + 3 + + + 2 + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + Monospace + 20 + + + + Qt::StrongFocus + + + Tuner center frequency in kHz + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + + Qt::Horizontal + + + + + + + 3 + + + + + Decimation + + + + + + + Signal decimation factor + + + 5 + + + 1 + + + Qt::Horizontal + + + QSlider::TicksBelow + + + + + + + + 40 + 0 + + + + 1:1 + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + Qt::Horizontal + + + + + + + 3 + + + + + + 0 + 0 + + + + LNA + + + + + + + LNA amplification + + + 12 + + + 1 + + + Qt::Horizontal + + + + + + + + 40 + 0 + + + + -5.0 + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + 10 + + + + + + 0 + 0 + + + + Mix + + + + + + + Tuner mixer amplification + + + QComboBox::AdjustToMinimumContentsLength + + + + 4 + + + + + 12 + + + + + + + + Qt::Vertical + + + + + + + + 0 + 0 + + + + Enh. + + + + + + + Tuner LNA amplification enhancement + + + QComboBox::AdjustToMinimumContentsLength + + + + off + + + + + 1 + + + + + 3 + + + + + 5 + + + + + 7 + + + + + + + + Qt::Vertical + + + + + + + Swap IQ + + + true + + + + + + + + + 0 + + + 3 + + + + + Tuner IF 2 amplification + + + QComboBox::AdjustToContents + + + + 0 + + + + + 3 + + + + + 6 + + + + + 9 + + + + + + + + Tuner IF 4 amplification + + + QComboBox::AdjustToContents + + + + 0 + + + + + 1 + + + + + 2 + + + + + + + + + 0 + 0 + + + + IF4 + + + + + + + + 0 + 0 + + + + IF5 + + + + + + + Tuner IF 5 amplification + + + QComboBox::AdjustToContents + + + + 3 + + + + + 6 + + + + + 9 + + + + + 12 + + + + + 15 + + + + + + + + + 0 + 0 + + + + IF6 + + + + + + + Tuner IF 3 amplification + + + QComboBox::AdjustToContents + + + + 0 + + + + + 3 + + + + + 6 + + + + + 9 + + + + + + + + + 0 + 0 + + + + IF2 + + + + + + + Tuner IF 6 amplification + + + QComboBox::AdjustToContents + + + + 3 + + + + + 6 + + + + + 9 + + + + + 12 + + + + + 15 + + + + + + + + + 0 + 0 + + + + IF3 + + + + + + + Tuner IF 1 amplification + + + QComboBox::AdjustToContents + + + + -3 + + + + + 6 + + + + + + + + + 0 + 0 + + + + IF1 + + + + + + + + + Qt::Horizontal + + + + + + + 3 + + + + + Poti 2 + + + + + + + I + + + + + + + + 0 + 0 + + + + I DC offset adjustment + + + 255 + + + 1 + + + Qt::Horizontal + + + + + + + + 0 + 0 + + + + I path amplification + + + 255 + + + 1 + + + Qt::Horizontal + + + + + + + + 0 + 0 + + + + Q path amplification + + + 255 + + + 1 + + + Qt::Horizontal + + + + + + + + 0 + 0 + + + + Q DC offset adjustment + + + 255 + + + 1 + + + Qt::Horizontal + + + + + + + + 0 + 0 + + + + Q DC offset adjustment + + + 255 + + + 1 + + + Qt::Horizontal + + + + + + + E4000 + + + + + + + Q + + + + + + + Poti 1 + + + + + + + + 0 + 0 + + + + Q path amplification + + + 255 + + + 1 + + + Qt::Horizontal + + + + + + + + + + ValueDial + QWidget +
gui/valuedial.h
+ 1 +
+
+ + +
diff --git a/plugins/samplesource/osmosdr/osmosdrinput.cpp b/plugins/samplesource/osmosdr/osmosdrinput.cpp new file mode 100644 index 000000000..989eb09ed --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrinput.cpp @@ -0,0 +1,479 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "osmosdrinput.h" +#include "osmosdrthread.h" +#include "osmosdrgui.h" +#include "util/simpleserializer.h" + +MESSAGE_CLASS_DEFINITION(OsmoSDRInput::MsgConfigureOsmoSDR, Message) + +OsmoSDRInput::Settings::Settings() : + m_swapIQ(false), + m_decimation(3), + m_lnaGain(-50), + m_mixerGain(40), + m_mixerEnhancement(0), + m_if1gain(-30), + m_if2gain(0), + m_if3gain(0), + m_if4gain(0), + m_if5gain(30), + m_if6gain(30), + m_opAmpI1(0), + m_opAmpI2(0), + m_opAmpQ1(0), + m_opAmpQ2(0), + m_dcOfsI(0), + m_dcOfsQ(0) +{ +} + +void OsmoSDRInput::Settings::resetToDefaults() +{ + m_swapIQ = false; + m_decimation = 3; + m_lnaGain = -50; + m_mixerGain = 40; + m_mixerEnhancement = 0; + m_if1gain = -30; + m_if2gain = 0; + m_if3gain = 0; + m_if4gain = 0; + m_if5gain = 30; + m_if6gain = 30; + m_opAmpI1 = 0; + m_opAmpI2 = 0; + m_opAmpQ1 = 0; + m_opAmpQ2 = 0; + m_dcOfsI = 0; + m_dcOfsQ = 0; +} + +QByteArray OsmoSDRInput::Settings::serialize() const +{ + SimpleSerializer s(1); + s.writeBool(1, m_swapIQ); + s.writeS32(2, m_decimation); + s.writeS32(3, m_lnaGain); + s.writeS32(4, m_mixerGain); + s.writeS32(5, m_mixerEnhancement); + s.writeS32(6, m_if1gain); + s.writeS32(7, m_if2gain); + s.writeS32(8, m_if3gain); + s.writeS32(9, m_if4gain); + s.writeS32(10, m_if5gain); + s.writeS32(11, m_if6gain); + s.writeS32(12, m_opAmpI1); + s.writeS32(13, m_opAmpI2); + s.writeS32(14, m_opAmpQ1); + s.writeS32(15, m_opAmpQ2); + s.writeS32(16, m_dcOfsI); + s.writeS32(17, m_dcOfsQ); + return s.final(); +} + +bool OsmoSDRInput::Settings::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { + d.readBool(1, &m_swapIQ, false); + d.readS32(2, &m_decimation, 3); + d.readS32(3, &m_lnaGain, -50); + d.readS32(4, &m_mixerGain, 40); + d.readS32(5, &m_mixerEnhancement, 0); + d.readS32(6, &m_if1gain, -30); + d.readS32(7, &m_if2gain, 0); + d.readS32(8, &m_if3gain, 0); + d.readS32(9, &m_if4gain, 0); + d.readS32(10, &m_if5gain, 30); + d.readS32(11, &m_if6gain, 30); + d.readS32(12, &m_opAmpI1, 0); + d.readS32(13, &m_opAmpI2, 0); + d.readS32(14, &m_opAmpQ1, 0); + d.readS32(15, &m_opAmpQ2, 0); + d.readS32(16, &m_dcOfsI, 0); + d.readS32(17, &m_dcOfsQ, 0); + return true; + } else { + resetToDefaults(); + return false; + } +} +#if 0 +OsmoSDRInput::Settings::Settings() : +{ +} + +QString OsmoSDRInput::Settings::serialize() const +{ + return QString("osmosdr:a:%1:%2:%3:%4:%5:%6:%7:%8:%9:%10:%11:%12:%13:%14:%15:%16:%17:%18") + .arg(centerFrequency) + .arg(swapIQ ? 1 : 0) + .arg(decimation) + .arg(lnaGain) + .arg(mixerGain) + .arg(mixerEnhancement) + .arg(if1gain) + .arg(if2gain) + .arg(if3gain) + .arg(if4gain) + .arg(if5gain) + .arg(if6gain) + .arg(opAmpI1) + .arg(opAmpI2) + .arg(opAmpQ1) + .arg(opAmpQ2) + .arg(dcOfsI) + .arg(dcOfsQ); +} + +bool OsmoSDRInput::Settings::deserialize(const QString& settings) +{ + QStringList list = settings.split(":"); + if(list.size() < 2) + return false; + if(list[0] != "osmosdr") + return false; + + if(list[1] == "a") { + bool ok; + if(list.size() != 20) + return false; + centerFrequency = list[2].toLongLong(&ok); + if(!ok) + return false; + swapIQ = (list[3].toInt(&ok) != 0) ? true : false; + if(!ok) + return false; + decimation = list[4].toInt(&ok); + if(!ok) + return false; + lnaGain = list[5].toInt(&ok); + if(!ok) + return false; + mixerGain = list[6].toInt(&ok); + if(!ok) + return false; + mixerEnhancement = list[7].toInt(&ok); + if(!ok) + return false; + if1gain = list[8].toInt(&ok); + if(!ok) + return false; + if2gain = list[9].toInt(&ok); + if(!ok) + return false; + if3gain = list[10].toInt(&ok); + if(!ok) + return false; + if4gain = list[11].toInt(&ok); + if(!ok) + return false; + if5gain = list[12].toInt(&ok); + if(!ok) + return false; + if6gain = list[13].toInt(&ok); + if(!ok) + return false; + opAmpI1 = list[14].toInt(&ok); + if(!ok) + return false; + opAmpI2 = list[15].toInt(&ok); + if(!ok) + return false; + opAmpQ1 = list[16].toInt(&ok); + if(!ok) + return false; + opAmpQ2 = list[17].toInt(&ok); + if(!ok) + return false; + dcOfsI = list[18].toInt(&ok); + if(!ok) + return false; + dcOfsQ = list[19].toInt(&ok); + if(!ok) + return false; + return true; + } else { + return false; + } +} + +MessageRegistrator OsmoSDRInput::MsgConfigureSourceOsmoSDR::ID("MsgConfigureSourceOsmoSDR"); +#endif +OsmoSDRInput::OsmoSDRInput(MessageQueue* msgQueueToGUI) : + SampleSource(msgQueueToGUI), + m_settings(), + m_dev(NULL), + m_osmoSDRThread(NULL), + m_deviceDescription() +{ +} + +OsmoSDRInput::~OsmoSDRInput() +{ + stopInput(); +} + +bool OsmoSDRInput::startInput(int device) +{ + QMutexLocker mutexLocker(&m_mutex); + + if(m_dev != NULL) + stopInput(); + + char vendor[256]; + char product[256]; + char serial[256]; + int res; + + if(!m_sampleFifo.setSize(524288)) { + qCritical("Could not allocate SampleFifo"); + return false; + } + + if((res = osmosdr_open(&m_dev, device)) < 0) { + qCritical("could not open OsmoSDR #%d: %s", device, strerror(errno)); + return false; + } + + vendor[0] = '\0'; + product[0] = '\0'; + serial[0] = '\0'; + if((res = osmosdr_get_usb_strings(m_dev, vendor, product, serial)) < 0) { + qCritical("error accessing USB device"); + goto failed; + } + qDebug("OsmoSDRInput open: %s %s, SN: %s", vendor, product, serial); + m_deviceDescription = QString("%1 (SN %2)").arg(product).arg(serial); + + if((res = osmosdr_set_tuner_gain_mode(m_dev, 1)) < 0) { + qCritical("error setting tuner gain mode"); + goto failed; + } + + if((res = osmosdr_reset_buffer(m_dev)) < 0) { + qCritical("could not reset USB EP buffers: %s", strerror(errno)); + goto failed; + } + + if((m_osmoSDRThread = new OsmoSDRThread(m_dev, &m_sampleFifo)) == NULL) { + qFatal("out of memory"); + goto failed; + } + m_osmoSDRThread->startWork(); + + mutexLocker.unlock(); + applySettings(m_generalSettings, m_settings, true); + + qDebug("OsmoSDRInput: start"); + + return true; + +failed: + stopInput(); + return false; +} + +void OsmoSDRInput::stopInput() +{ + QMutexLocker mutexLocker(&m_mutex); + + if(m_osmoSDRThread != NULL) { + m_osmoSDRThread->stopWork(); + delete m_osmoSDRThread; + m_osmoSDRThread = NULL; + } + if(m_dev != NULL) { + osmosdr_close(m_dev); + m_dev = NULL; + } + m_deviceDescription.clear(); +} + +const QString& OsmoSDRInput::getDeviceDescription() const +{ + return m_deviceDescription; +} + +int OsmoSDRInput::getSampleRate() const +{ + return 4000000 / (1 << m_settings.m_decimation); +} + +quint64 OsmoSDRInput::getCenterFrequency() const +{ + return m_generalSettings.m_centerFrequency; +} + +bool OsmoSDRInput::handleMessage(Message* message) +{ + if(MsgConfigureOsmoSDR::match(message)) { + MsgConfigureOsmoSDR* conf = (MsgConfigureOsmoSDR*)message; + if(!applySettings(conf->getGeneralSettings(), conf->getSettings(), false)) + qDebug("OsmoSDR config error"); + message->completed(); + return true; + } else { + return false; + } + + /* + if(cmd->sourceType() != DSPCmdConfigureSourceOsmoSDR::SourceType) + return false; + if(!applySettings(((DSPCmdConfigureSourceOsmoSDR*)cmd)->getSettings(), false)) + qDebug("OsmoSDR config error"); + cmd->completed(); + return true; + */ + return false; +} + +bool OsmoSDRInput::applySettings(const GeneralSettings& generalSettings, const Settings& settings, bool force) +{ + QMutexLocker mutexLocker(&m_mutex); + + if((m_generalSettings.m_centerFrequency != generalSettings.m_centerFrequency) || force) { + m_generalSettings.m_centerFrequency = generalSettings.m_centerFrequency; + if(m_dev != NULL) { + if(osmosdr_set_center_freq(m_dev, m_generalSettings.m_centerFrequency) != 0) + qDebug("osmosdr_set_center_freq(%lld) failed", m_generalSettings.m_centerFrequency); + } + } + + if((m_settings.m_swapIQ != settings.m_swapIQ) || force) { + m_settings.m_swapIQ = settings.m_swapIQ; + if(m_dev != NULL) { + if(osmosdr_set_fpga_iq_swap(m_dev, m_settings.m_swapIQ ? 1 : 0) == 0) + qDebug("osmosdr_set_fpga_iq_swap() failed"); + } + } + + if((m_settings.m_decimation != settings.m_decimation) || force) { + m_settings.m_decimation = settings.m_decimation; + if(m_dev != NULL) { + if(!osmosdr_set_fpga_decimation(m_dev, m_settings.m_decimation)) + qDebug("osmosdr_set_fpga_decimation() failed"); + } + } + + if((m_settings.m_lnaGain != settings.m_lnaGain) || force) { + m_settings.m_lnaGain = settings.m_lnaGain; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_lna_gain(m_dev, m_settings.m_lnaGain)) + qDebug("osmosdr_set_tuner_lna_gain() failed"); + } + } + + if((m_settings.m_mixerGain != settings.m_mixerGain) || force) { + m_settings.m_mixerGain = settings.m_mixerGain; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_mixer_gain(m_dev, m_settings.m_mixerGain)) + qDebug("osmosdr_set_tuner_mixer_gain() failed"); + } + } + + if((m_settings.m_mixerEnhancement != settings.m_mixerEnhancement) || force) { + m_settings.m_mixerEnhancement = settings.m_mixerEnhancement; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_mixer_enh(m_dev, m_settings.m_mixerEnhancement)) + qDebug("osmosdr_set_tuner_mixer_enh() failed"); + } + } + + if((m_settings.m_if1gain != settings.m_if1gain) || force) { + m_settings.m_if1gain = settings.m_if1gain; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_if_gain(m_dev, 1, m_settings.m_if1gain)) + qDebug("osmosdr_set_tuner_if_gain(1) failed"); + } + } + + if((m_settings.m_if2gain != settings.m_if2gain) || force) { + m_settings.m_if2gain = settings.m_if2gain; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_if_gain(m_dev, 2, m_settings.m_if2gain)) + qDebug("osmosdr_set_tuner_if_gain(2) failed"); + } + } + + if((m_settings.m_if3gain != settings.m_if3gain) || force) { + m_settings.m_if3gain = settings.m_if3gain; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_if_gain(m_dev, 3, m_settings.m_if3gain)) + qDebug("osmosdr_set_tuner_if_gain(3) failed"); + } + } + + if((m_settings.m_if4gain != settings.m_if4gain) || force) { + m_settings.m_if4gain = settings.m_if4gain; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_if_gain(m_dev, 4, m_settings.m_if4gain)) + qDebug("osmosdr_set_tuner_if_gain(4) failed"); + } + } + + if((m_settings.m_if5gain != settings.m_if5gain) || force) { + m_settings.m_if5gain = settings.m_if5gain; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_if_gain(m_dev, 5, m_settings.m_if5gain)) + qDebug("osmosdr_set_tuner_if_gain(5) failed"); + } + } + + if((m_settings.m_if6gain != settings.m_if6gain) || force) { + m_settings.m_if6gain = settings.m_if6gain; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_if_gain(m_dev, 6, m_settings.m_if6gain)) + qDebug("osmosdr_set_tuner_if_gain(6) failed"); + } + } + + if((m_settings.m_opAmpI1 != settings.m_opAmpI1) || (m_settings.m_opAmpI2 != settings.m_opAmpI2) || + (m_settings.m_opAmpQ1 != settings.m_opAmpQ1) || (m_settings.m_opAmpQ2 != settings.m_opAmpQ2) || + force) { + m_settings.m_opAmpI1 = settings.m_opAmpI1; + m_settings.m_opAmpI2 = settings.m_opAmpI2; + m_settings.m_opAmpQ1 = settings.m_opAmpQ1; + m_settings.m_opAmpQ2 = settings.m_opAmpQ2; + if(m_dev != NULL) { + if(!osmosdr_set_iq_amp(m_dev, m_settings.m_opAmpI1, m_settings.m_opAmpI2, m_settings.m_opAmpQ1, m_settings.m_opAmpQ2)) + qDebug("osmosdr_set_iq_amp(1) failed"); + } + } + + if((m_settings.m_dcOfsI != settings.m_dcOfsI) || (m_settings.m_dcOfsQ != settings.m_dcOfsQ) || + force) { + m_settings.m_dcOfsI = settings.m_dcOfsI; + m_settings.m_dcOfsQ = settings.m_dcOfsQ; + if(m_dev != NULL) { + if(!osmosdr_set_tuner_dc_offset(m_dev, m_settings.m_dcOfsI, m_settings.m_dcOfsQ)) + qDebug("osmosdr_set_tuner_dc_offset() failed"); + } + } + + return true; +} diff --git a/plugins/samplesource/osmosdr/osmosdrinput.h b/plugins/samplesource/osmosdr/osmosdrinput.h new file mode 100644 index 000000000..dd832caad --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrinput.h @@ -0,0 +1,99 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_OSMOSDRINPUT_H +#define INCLUDE_OSMOSDRINPUT_H + +#include "dsp/samplesource/samplesource.h" +#include +#include + +class OsmoSDRThread; + +class OsmoSDRInput : public SampleSource { +public: + struct Settings { + bool m_swapIQ; + qint32 m_decimation; + qint32 m_lnaGain; + qint32 m_mixerGain; + qint32 m_mixerEnhancement; + qint32 m_if1gain; + qint32 m_if2gain; + qint32 m_if3gain; + qint32 m_if4gain; + qint32 m_if5gain; + qint32 m_if6gain; + qint32 m_opAmpI1; + qint32 m_opAmpI2; + qint32 m_opAmpQ1; + qint32 m_opAmpQ2; + qint32 m_dcOfsI; + qint32 m_dcOfsQ; + + Settings(); + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + }; + + class MsgConfigureOsmoSDR : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const GeneralSettings& getGeneralSettings() const { return m_generalSettings; } + const Settings& getSettings() const { return m_settings; } + + static MsgConfigureOsmoSDR* create(const GeneralSettings& generalSettings, const Settings& settings) + { + return new MsgConfigureOsmoSDR(generalSettings, settings); + } + + protected: + GeneralSettings m_generalSettings; + Settings m_settings; + + MsgConfigureOsmoSDR(const GeneralSettings& generalSettings, const Settings& settings) : + Message(), + m_generalSettings(generalSettings), + m_settings(settings) + { } + }; + + OsmoSDRInput(MessageQueue* msgQueueToGUI); + ~OsmoSDRInput(); + + bool startInput(int device); + void stopInput(); + + const QString& getDeviceDescription() const; + int getSampleRate() const; + quint64 getCenterFrequency() const; + + bool handleMessage(Message* message); + +private: + QMutex m_mutex; + Settings m_settings; + osmosdr_dev_t* m_dev; + OsmoSDRThread* m_osmoSDRThread; + QString m_deviceDescription; + + bool applySettings(const GeneralSettings& generalSettings, const Settings& settings, bool force); +}; + +#endif // INCLUDE_OSMOSDRINPUT_H diff --git a/plugins/samplesource/osmosdr/osmosdrplugin.cpp b/plugins/samplesource/osmosdr/osmosdrplugin.cpp new file mode 100644 index 000000000..183642d19 --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrplugin.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include "plugin/pluginapi.h" +#include "util/simpleserializer.h" +#include "osmosdrplugin.h" +#include "osmosdrgui.h" + +const PluginDescriptor OsmoSDRPlugin::m_pluginDescriptor = { + QString("OsmoSDR Input"), + QString("---"), + QString("(c) Christian Daniel"), + QString("http://sdr.osmocom.org/trac/wiki/osmo-sdr"), + true, + QString("http://cgit.osmocom.org/cgit/osmo-sdr") +}; + +OsmoSDRPlugin::OsmoSDRPlugin(QObject* parent) : + QObject(parent) +{ +} + +const PluginDescriptor& OsmoSDRPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void OsmoSDRPlugin::initPlugin(PluginAPI* pluginAPI) +{ + m_pluginAPI = pluginAPI; + + m_pluginAPI->registerSampleSource("org.osmocom.sdr.samplesource.osmo-sdr", this); +} + +PluginInterface::SampleSourceDevices OsmoSDRPlugin::enumSampleSources() +{ + SampleSourceDevices result; + int count = osmosdr_get_device_count(); + char vendor[256]; + char product[256]; + char serial[256]; + + for(int i = 0; i < count; i++) { + vendor[0] = '\0'; + product[0] = '\0'; + serial[0] = '\0'; + + if(osmosdr_get_device_usb_strings(i, vendor, product, serial) != 0) + continue; + QString displayedName(QString("OsmoSDR #%1 (#%2)").arg(i + 1).arg(serial)); + qDebug("found %s", qPrintable(displayedName)); + SimpleSerializer s(1); + s.writeS32(1, i); + result.append(SampleSourceDevice(displayedName, "org.osmocom.sdr.samplesource.osmo-sdr", s.final())); + } + + return result; +} + +PluginGUI* OsmoSDRPlugin::createSampleSource(const QString& sourceName, const QByteArray& address) +{ + if(sourceName == "org.osmocom.sdr.samplesource.osmo-sdr") { + OsmoSDRGui* gui = new OsmoSDRGui(m_pluginAPI); + m_pluginAPI->setInputGUI(gui); + return gui; + } else { + return NULL; + } +} diff --git a/plugins/samplesource/osmosdr/osmosdrplugin.h b/plugins/samplesource/osmosdr/osmosdrplugin.h new file mode 100644 index 000000000..47f04e72a --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrplugin.h @@ -0,0 +1,27 @@ +#ifndef INCLUDE_OSMOSDRPLUGIN_H +#define INCLUDE_OSMOSDRPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class OsmoSDRPlugin : public QObject, PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID "org.osmocom.sdr.samplesource.osmo-sdr") + +public: + explicit OsmoSDRPlugin(QObject* parent = NULL); + + const PluginDescriptor& getPluginDescriptor() const; + void initPlugin(PluginAPI* pluginAPI); + + SampleSourceDevices enumSampleSources(); + PluginGUI* createSampleSource(const QString& sourceName, const QByteArray& address); + +private: + static const PluginDescriptor m_pluginDescriptor; + + PluginAPI* m_pluginAPI; +}; + +#endif // INCLUDE_OSMOSDRPLUGIN_H diff --git a/plugins/samplesource/osmosdr/osmosdrthread.cpp b/plugins/samplesource/osmosdr/osmosdrthread.cpp new file mode 100644 index 000000000..25fcfdbea --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrthread.cpp @@ -0,0 +1,116 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "osmosdrthread.h" +#include "dsp/samplefifo.h" + +OsmoSDRThread::OsmoSDRThread(osmosdr_dev_t* dev, SampleFifo* sampleFifo, QObject* parent) : + QThread(parent), + m_running(false), + m_dev(dev), + m_sampleFifo(sampleFifo) +{ +} + +OsmoSDRThread::~OsmoSDRThread() +{ + stopWork(); +} + +void OsmoSDRThread::startWork() +{ + m_startWaitMutex.lock(); + start(); + while(!m_running) + m_startWaiter.wait(&m_startWaitMutex, 100); + m_startWaitMutex.unlock(); +} + +void OsmoSDRThread::stopWork() +{ + m_running = false; + wait(); +} + +void OsmoSDRThread::run() +{ + int res; + + m_running = true; + m_startWaiter.wakeAll(); + + //m_f = fopen("/tmp/samples.bin", "wb"); + + while(m_running) { + if((res = osmosdr_read_async(m_dev, &OsmoSDRThread::callbackHelper, this, 16, sizeof(Sample) * 8192 * 2)) < 0) { + qCritical("OsmoSDRThread: async error: %s", strerror(errno)); + break; + } + } + + m_running = false; +} + +void OsmoSDRThread::checkData(const quint8* buf, qint32 len) +{ + const Sample* s = (const Sample*)buf; + len /= sizeof(Sample); + + while(len) { + if((s->i != m_nextI) || (s->q != m_nextQ)) { + qDebug("continuity error after %llu samples", m_samplePos); + m_samplePos = 0; + m_nextI = s->i - 1; + m_nextQ = s->q + 1; + } else { + m_nextI--; + m_nextQ++; + m_samplePos++; + } + len--; + s++; + } +} + +void OsmoSDRThread::callback(const quint8* buf, qint32 len) +{ + /* + qDebug("%d", len); +*/ + /* + for(int i = 0; i < len / 2; i += 2) { + ((qint16*)buf)[i] = sin((float)(cntr) * 1024* 2.0 * M_PI / 65536.0) * 32000.0; + ((qint16*)buf)[i + 1] = -cos((float)(cntr++) * 1024*2.0 * M_PI / 65536.0) * 32000.0; + } + */ + + //m_sampleFifo->write((SampleVector::const_iterator)((Sample*)buf), (SampleVector::const_iterator)((Sample*)(buf + len))); + //fwrite(buf, 1, len, m_f); + //checkData(buf, len); + + m_sampleFifo->write(buf, len); + if(!m_running) + osmosdr_cancel_async(m_dev); +} + +void OsmoSDRThread::callbackHelper(unsigned char* buf, uint32_t len, void* ctx) +{ + OsmoSDRThread* thread = (OsmoSDRThread*)ctx; + thread->callback(buf, len); +} diff --git a/plugins/samplesource/osmosdr/osmosdrthread.h b/plugins/samplesource/osmosdr/osmosdrthread.h new file mode 100644 index 000000000..0aa014240 --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrthread.h @@ -0,0 +1,66 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_OSMOSDRTHREAD_H +#define INCLUDE_OSMOSDRTHREAD_H + +#include +#include +#include +#include + +class SampleFifo; + +class OsmoSDRThread : public QThread { + Q_OBJECT + +public: + OsmoSDRThread(osmosdr_dev_t* dev, SampleFifo* sampleFifo, QObject* parent = NULL); + ~OsmoSDRThread(); + + void startWork(); + void stopWork(); + +private: +#pragma pack(push, 1) + struct Sample { + qint16 i; + qint16 q; + }; +#pragma pack(pop) + + qint16 m_nextI; + qint16 m_nextQ; + quint64 m_samplePos; + + QMutex m_startWaitMutex; + QWaitCondition m_startWaiter; + bool m_running; + FILE* m_f; + + osmosdr_dev_t* m_dev; + SampleFifo* m_sampleFifo; + + void run(); + + void checkData(const quint8* buf, qint32 len); + void callback(const quint8* buf, qint32 len); + + static void callbackHelper(unsigned char* buf, uint32_t len, void* ctx); +}; + +#endif // INCLUDE_OSMOSDRTHREAD_H diff --git a/plugins/samplesource/osmosdr/osmosdrupgrade.cpp b/plugins/samplesource/osmosdr/osmosdrupgrade.cpp new file mode 100644 index 000000000..bba600bf1 --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrupgrade.cpp @@ -0,0 +1,518 @@ +#include +#include +#include +#include +#include +#include "osmosdrupgrade.h" +#include "ui_osmosdrupgrade.h" + +#define OSMOSDR_USB_VID 0x16c0 +#define OSMOSDR_USB_PID 0x0763 + +// DFU commands +#define DFU_DETACH 0x00 +#define DFU_DNLOAD 0x01 +#define DFU_UPLOAD 0x02 +#define DFU_GETSTATUS 0x03 +#define DFU_CLRSTATUS 0x04 +#define DFU_GETSTATE 0x05 +#define DFU_ABORT 0x06 + +// DFU states +#define ST_appIDLE 0 +#define ST_appDETACH 1 +#define ST_dfuIDLE 2 +#define ST_dfuDNLOAD_SYNC 3 +#define ST_dfuDNBUSY 4 +#define ST_dfuDNLOAD_IDLE 5 +#define ST_dfuMANIFEST_SYNC 6 +#define ST_dfuMANIFEST 7 +#define ST_dfuMANIFEST_WAIT_RST 8 +#define ST_dfuUPLOAD_IDLE 9 +#define ST_dfuERROR 10 + +#define DFU_PACKETSIZE 512 + +#pragma pack(push, 1) +struct dfu_getstatus { + quint8 bStatus; + quint8 bwPollTimeout[3]; + quint8 bState; + quint8 iString; +}; +#pragma pack(pop) + + +OsmoSDRUpgrade::OsmoSDRUpgrade(QWidget* parent) : + QDialog(parent), + ui(new Ui::OsmoSDRUpgrade), + m_usb(NULL) +{ + ui->setupUi(this); + connect(&m_searchDeviceTimer, SIGNAL(timeout()), this, SLOT(searchDeviceTick())); +} + +OsmoSDRUpgrade::~OsmoSDRUpgrade() +{ + delete ui; +} + +void OsmoSDRUpgrade::on_browse_clicked() +{ + QString filename = QFileDialog::getOpenFileName(this, tr("OsmoSDR Firmware File"), QString(), tr("OsmoSDR Firmware (*.ofw);;All Files (*)")); + if(filename.isEmpty()) + return; + + QFile file(filename); + if(file.size() > 10 * 1024 * 1024) { + QMessageBox::critical(this, tr("File Open Error"), tr("File is too big to be a firmware update for OsmoSDR.")); + return; + } + + QByteArray dfuApp; + QByteArray radioApp; + QByteArray fpgaBin; + mz_zip_archive zip; + memset(&zip, 0x00, sizeof(zip)); + + if(!mz_zip_reader_init_file(&zip, qPrintable(filename), 0)) { + mz_zip_reader_end(&zip); + QMessageBox::critical(this, tr("File Open Error"), tr("File is not a valid OsmoSDR update.")); + return; + } + + int dfuAppIndex = mz_zip_reader_locate_file(&zip, "dfuapp.bin", NULL, 0); + int radioAppIndex = mz_zip_reader_locate_file(&zip, "radioapp.bin", NULL, 0); + int fpgaIndex = mz_zip_reader_locate_file(&zip, "fpga.bin", NULL, 0); + + if((dfuAppIndex < 0) && (radioAppIndex < 0) && (fpgaIndex < 0)) { + mz_zip_reader_end(&zip); + QMessageBox::critical(this, tr("File Open Error"), tr("File is not a valid OsmoSDR update.")); + return; + } + + if(!mz_zip_reader_extract_to_callback(&zip, dfuAppIndex, zipHelper, &dfuApp, 0)) { + mz_zip_reader_end(&zip); + QMessageBox::critical(this, tr("File Open Error"), tr("File is not a valid OsmoSDR update.")); + return; + } + + if(!mz_zip_reader_extract_to_callback(&zip, radioAppIndex, zipHelper, &radioApp, 0)) { + mz_zip_reader_end(&zip); + QMessageBox::critical(this, tr("File Open Error"), tr("File is not a valid OsmoSDR update.")); + return; + } + + if(!mz_zip_reader_extract_to_callback(&zip, fpgaIndex, zipHelper, &fpgaBin, 0)) { + mz_zip_reader_end(&zip); + QMessageBox::critical(this, tr("File Open Error"), tr("File is not a valid OsmoSDR update.")); + return; + } + + mz_zip_reader_end(&zip); + m_dfuApp = dfuApp; + m_radioApp = radioApp; + m_fpgaBin = fpgaBin; + + if(dfuAppIndex >= 0) { + ui->dfu->setEnabled(true); + ui->dfuSize->setText(tr("%1").arg(m_dfuApp.size())); + } else { + ui->dfu->setEnabled(false); + ui->dfuSize->setText(tr("-")); + } + if(radioAppIndex >= 0) { + ui->radio->setEnabled(true); + ui->radioSize->setText(tr("%1").arg(m_radioApp.size())); + } else { + ui->radio->setEnabled(false); + ui->dfuSize->setText(tr("-")); + } + if(fpgaIndex >= 0) { + ui->fpga->setEnabled(true); + ui->fpgaSize->setText(tr("%1").arg(m_fpgaBin.size())); + } else { + ui->fpga->setEnabled(false); + ui->fpgaSize->setText(tr("-")); + } + + + if((dfuAppIndex >= 0) && (radioAppIndex < 0) && (fpgaIndex < 0)) { + ui->dfu->setChecked(true); + ui->radio->setChecked(false); + ui->fpga->setChecked(false); + } else { + ui->dfu->setChecked(false); + ui->radio->setChecked(radioAppIndex >= 0); + ui->fpga->setChecked(fpgaIndex >= 0); + } + + ui->fwBox->setEnabled(true); + ui->progressBox->setEnabled(true); + + QFileInfo fi(file.fileName()); + ui->filename->setText(fi.fileName()); +} + +void OsmoSDRUpgrade::on_dfu_toggled(bool checked) +{ + updateFlashButton(); +} + +void OsmoSDRUpgrade::on_radio_toggled(bool checked) +{ + updateFlashButton(); +} + +void OsmoSDRUpgrade::on_fpga_toggled(bool checked) +{ + updateFlashButton(); +} + +void OsmoSDRUpgrade::updateFlashButton() +{ + if(ui->dfu->isChecked() || ui->radio->isChecked() || ui->fpga->isChecked()) + ui->progressBox->setEnabled(true); + else ui->progressBox->setEnabled(false); +} + +void OsmoSDRUpgrade::on_start_clicked() +{ + ui->close->setEnabled(false); + ui->start->setEnabled(false); + QApplication::setOverrideCursor(Qt::WaitCursor); + + ui->log->clear(); + log(tr("Starting flash operation...")); + + if(libusb_init(&m_usb) < 0) { + fail(tr("Could not initialize libusb.")); + return; + } + + switchToDFU(); + + m_searchTries = 0; + m_searchDeviceTimer.start(250); +} + +void OsmoSDRUpgrade::searchDeviceTick() +{ + m_searchTries++; + log(tr("Searching device (try %1)").arg(m_searchTries)); + + libusb_device_handle* device = libusb_open_device_with_vid_pid(m_usb, OSMOSDR_USB_VID, OSMOSDR_USB_PID); + if(device == NULL) { + if(m_searchTries >= 10) { + m_searchDeviceTimer.stop(); + finish(); + } + return; + } + + m_searchDeviceTimer.stop(); + + libusb_device_descriptor deviceDescriptor; + + if(libusb_get_descriptor(device, LIBUSB_DT_DEVICE, 0, (unsigned char*)&deviceDescriptor, sizeof(deviceDescriptor)) < 0) { + libusb_close(device); + fail(tr("Could not read device descriptor.")); + return; + } + + char sn[64]; + memset(sn, 0x00, sizeof(sn)); + libusb_get_string_descriptor_ascii(device, deviceDescriptor.iSerialNumber, (unsigned char*)sn, sizeof(sn)); + sn[sizeof(sn) - 1] = '\0'; + + log(tr("OsmoSDR found (SN %1)").arg(sn)); + + quint8 buffer[255]; + if(libusb_get_descriptor(device, LIBUSB_DT_CONFIG, 0, buffer, sizeof(buffer)) < 16) { + libusb_close(device); + fail(tr("Could not get a configuration descriptor")); + return; + } + + if(buffer[15] != 1) { + libusb_close(device); + fail(tr("Device not in DFU mode as it should be")); + return; + } + + quint8 state; + + if(dfuGetState(device, &state) < 0) { + libusb_reset_device(device); + if(dfuGetState(device, &state) < 0) { + libusb_close(device); + fail(tr("Cannot get device DFU state")); + return; + } + } + if((state != ST_dfuIDLE) && (state != ST_dfuDNLOAD_IDLE)) { + dfuGetStatus(device); + libusb_close(device); + fail(tr("Device is not in dfuIDLE or dfuDNLOAD_IDLE state")); + return; + } + + if(libusb_claim_interface(device, 0) < 0) { + libusb_close(device); + fail(tr("Could not claim interface")); + return; + } + + QByteArray* image; + int altSetting; + + while(true) { + if(ui->dfu->isChecked()) { + log(tr("Starting download of DFU application")); + image = &m_dfuApp; + altSetting = 1; + } else if(ui->radio->isChecked()) { + log(tr("Starting download of radio application")); + image = &m_radioApp; + altSetting = 0; + } else if(ui->fpga->isChecked()) { + log(tr("Starting download of FPGA image")); + image = &m_fpgaBin; + altSetting = 2; + } else { + log(tr("Switching back to radio application mode")); + dfuDetach(device); + break; + } + + if(libusb_set_interface_alt_setting(device, 0, altSetting) < 0) { + libusb_close(device); + fail(tr("Could not set alternate interface setting to %1").arg(altSetting)); + return; + } + + ui->progress->setMaximum((image->size() / DFU_PACKETSIZE) + ((image->size() % DFU_PACKETSIZE) ? 1 : 0)); + + int blocknum = 0; + while((state == ST_dfuIDLE) || (state == ST_dfuDNLOAD_IDLE)) { + int offset = blocknum * DFU_PACKETSIZE; + int blocklen = (int)image->size() - offset; + if(blocklen < 0) + blocklen = 0; + if(blocklen > DFU_PACKETSIZE) + blocklen = DFU_PACKETSIZE; + if(dfuDownloadBlock(device, blocknum, (const quint8*)(image->data() + offset), blocklen) < 0) { + if(dfuGetState(device, &state) < 0) { + if(ui->dfu->isChecked()) + break; + libusb_close(device); + fail(tr("Cannot get device DFU state")); + return; + } + dfuGetStatus(device); + libusb_close(device); + fail(tr("Error downloading block %1").arg(blocknum)); + return; + } + dfuGetStatus(device); + if(blocklen == 0) + break; + blocknum++; + ui->progress->setValue(blocknum); + QApplication::processEvents(); + } + log(tr("Download complete (state %1)").arg(state)); + + do { + if(dfuGetState(device, &state) < 0) { + if(ui->dfu->isChecked()) { + break; + } else { + libusb_close(device); + fail(tr("Cannot get device DFU state")); + return; + } + } + dfuGetStatus(device); + } while(state == ST_dfuMANIFEST); + + if(ui->dfu->isChecked()) { + ui->dfu->setChecked(false); + m_searchTries = 0; + m_searchDeviceTimer.start(250); + libusb_close(device); + return; + } else if(ui->radio->isChecked()) { + ui->radio->setChecked(false); + } else if(ui->fpga->isChecked()) { + ui->fpga->setChecked(false); + } + + QApplication::processEvents(); + } + + log(tr("Upgrade finished successfully")); + libusb_close(device); + finish(); +} + +void OsmoSDRUpgrade::switchToDFU() +{ + libusb_device_handle* device = libusb_open_device_with_vid_pid(m_usb, OSMOSDR_USB_VID, OSMOSDR_USB_PID); + if(device == NULL) { + log(tr("No OsmoSDR VID:PID %1:%2 found").arg(OSMOSDR_USB_VID, 4, 16, QChar('0')).arg(OSMOSDR_USB_PID, 4, 16, QChar('0'))); + return; + } + + quint8 buffer[255]; + if(libusb_get_descriptor(device, LIBUSB_DT_CONFIG, 0, buffer, sizeof(buffer)) < 16) { + log(tr("Could not get a valid configuration descriptor")); + libusb_close(device); + return; + } + + if(buffer[15] != 1) { + if(libusb_claim_interface(device, 0) < 0) { + log(tr("Could not claim interface")); + libusb_close(device); + return; + } + + log(tr("Switching device to DFU mode")); + libusb_control_transfer(device, LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_ENDPOINT_OUT, 0x07, 0x0003, 0, NULL, 0, 50); + libusb_release_interface(device, 0); + } else { + log(tr("Device is already in DFU mode")); + } + + libusb_close(device); +} + +int OsmoSDRUpgrade::dfuGetState(libusb_device_handle* device, quint8* state) +{ + int res; + + res = libusb_control_transfer( + device, + 0xa1, + DFU_GETSTATE, + 0, + 0, + (unsigned char*)state, + 1, + 1000); + + return res; +} + +int OsmoSDRUpgrade::dfuGetStatus(libusb_device_handle* device) +{ + int res; + struct dfu_getstatus getstatus; +/* + static const char* statedesc[] = { + "appIDLE", + "appDETACH", + "dfuIDLE", + "dfuDNLOAD-SYNC", + "dfuDNBUSY", + "dfuDNLOAD-IDLE", + "dfuMANIFEST-SYNC", + "dfuMANIFEST", + "dfuMANIFEST-WAIT-RESET", + "dfuUPLOAD-IDLE", + "dfuERROR" + }; +*/ + + res = libusb_control_transfer( + device, + 0xa1, + DFU_GETSTATUS, + 0, + 0, + (unsigned char*)&getstatus, + sizeof(getstatus), + 1000); +/* + if(res >= 0) + log(tr("OsmoSDR bStatus: %1, bState: %2 (%3)").arg(getstatus.bStatus).arg(statedesc[getstatus.bState]).arg(getstatus.bState)); +*/ + return res; +} + +int OsmoSDRUpgrade::dfuClrStatus(libusb_device_handle* device) +{ + return libusb_control_transfer( + device, + 0x21, + DFU_CLRSTATUS, + 0, + 0, + NULL, + 0, + 1000); +} + +int OsmoSDRUpgrade::dfuDownloadBlock(libusb_device_handle* device, quint16 block, const quint8* data, quint16 len) +{ + return libusb_control_transfer( + device, + 0x21, + DFU_DNLOAD, + block, + 0, + (unsigned char*)data, + len, + 10000); +} + +int OsmoSDRUpgrade::dfuDetach(libusb_device_handle* device) +{ + return libusb_control_transfer( + device, + 0x21, + DFU_DETACH, + 0, + 0, + NULL, + 0, + 1000); +} + +void OsmoSDRUpgrade::fail(const QString& msg) +{ + log(tr("Fatal error: %1").arg(msg)); + QMessageBox::critical(this, tr("OsmoSDR Upgrade Failed"), msg); + finish(); +} + +void OsmoSDRUpgrade::finish() +{ + if(m_usb != NULL) { + libusb_exit(m_usb); + m_usb = NULL; + } + QApplication::restoreOverrideCursor(); + ui->start->setEnabled(true); + ui->close->setEnabled(true); +} + +void OsmoSDRUpgrade::log(const QString& msg) +{ + ui->log->appendPlainText(msg); + ui->log->moveCursor(QTextCursor::End); +} + +void OsmoSDRUpgrade::reject() +{ + if(ui->close->isEnabled()) + return QDialog::reject(); +} + +size_t OsmoSDRUpgrade::zipHelper(void* pOpaque, mz_uint64 file_ofs, const void* pBuf, size_t n) +{ + QByteArray* bytes = (QByteArray*)pOpaque; + bytes->append((const char*)pBuf, n); + return n; +} diff --git a/plugins/samplesource/osmosdr/osmosdrupgrade.h b/plugins/samplesource/osmosdr/osmosdrupgrade.h new file mode 100644 index 000000000..efd930bce --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrupgrade.h @@ -0,0 +1,60 @@ +#ifndef INCLUDE_OSMOSDRUPGRADE_H +#define INCLUDE_OSMOSDRUPGRADE_H + +#include +#include +#include "util/miniz.h" + +typedef struct libusb_context libusb_context; +typedef struct libusb_device_handle libusb_device_handle; + +namespace Ui { + class OsmoSDRUpgrade; +} + +class OsmoSDRUpgrade : public QDialog { + Q_OBJECT + +public: + explicit OsmoSDRUpgrade(QWidget* parent = NULL); + ~OsmoSDRUpgrade(); + +private slots: + void on_browse_clicked(); + void on_dfu_toggled(bool checked); + void on_radio_toggled(bool checked); + void on_fpga_toggled(bool checked); + void on_start_clicked(); + void searchDeviceTick(); + +private: + Ui::OsmoSDRUpgrade* ui; + + libusb_context* m_usb; + + QByteArray m_dfuApp; + QByteArray m_radioApp; + QByteArray m_fpgaBin; + + int m_searchTries; + QTimer m_searchDeviceTimer; + + void updateFlashButton(); + + void switchToDFU(); + int dfuGetState(libusb_device_handle* device, quint8* state); + int dfuGetStatus(libusb_device_handle* device); + int dfuClrStatus(libusb_device_handle* device); + int dfuDownloadBlock(libusb_device_handle* device, quint16 block, const quint8* data, quint16 len); + int dfuDetach(libusb_device_handle* device); + + void fail(const QString& msg); + void finish(); + void log(const QString& msg); + + void reject(); + + static size_t zipHelper(void* pOpaque, mz_uint64 file_ofs, const void* pBuf, size_t n); +}; + +#endif // INCLUDE_OSMOSDRUPGRADE_H diff --git a/plugins/samplesource/osmosdr/osmosdrupgrade.ui b/plugins/samplesource/osmosdr/osmosdrupgrade.ui new file mode 100644 index 000000000..fbb293939 --- /dev/null +++ b/plugins/samplesource/osmosdr/osmosdrupgrade.ui @@ -0,0 +1,213 @@ + + + OsmoSDRUpgrade + + + + 0 + 0 + 382 + 503 + + + + OsmoSDR Firmware Upgrade + + + true + + + + + + Firmware Archive + + + + + + + 0 + 0 + + + + + 256 + 0 + + + + + + + Qt::PlainText + + + + + + + Browse... + + + + + + + + + + false + + + Firmware + + + + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + Size (Bytes) + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + DFU Application + + + + + + + Radio Application + + + + + + + FPGA Image + + + + + + + + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + + false + + + Progress + + + + + + + + 0 + + + + + + + Flash! + + + + + + + + + true + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Close + + + + + + + + + + + close + clicked() + OsmoSDRUpgrade + reject() + + + 331 + 247 + + + 190 + 134 + + + + + diff --git a/plugins/samplesource/rtlsdr/CMakeLists.txt b/plugins/samplesource/rtlsdr/CMakeLists.txt new file mode 100644 index 000000000..35c408111 --- /dev/null +++ b/plugins/samplesource/rtlsdr/CMakeLists.txt @@ -0,0 +1,50 @@ +project(rtlsdr) + +set(rtlsdr_SOURCES + rtlsdrgui.cpp + rtlsdrinput.cpp + rtlsdrplugin.cpp + rtlsdrthread.cpp +) + +set(rtlsdr_HEADERS + rtlsdrgui.h + rtlsdrinput.h + rtlsdrplugin.h + rtlsdrthread.h +) + +set(rtlsdr_FORMS + rtlsdrgui.ui +) + +include_directories( + . + ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_SOURCE_DIR}/include + ${CMAKE_SOURCE_DIR}/include-gpl + ${LIBRTLSDR_INCLUDE_DIR} +) + +#include(${QT_USE_FILE}) +add_definitions(${QT_DEFINITIONS}) +add_definitions(-DQT_PLUGIN) +add_definitions(-DQT_SHARED) + +#qt4_wrap_cpp(rtlsdr_HEADERS_MOC ${rtlsdr_HEADERS}) +qt5_wrap_ui(rtlsdr_FORMS_HEADERS ${rtlsdr_FORMS}) + +add_library(inputrtlsdr SHARED + ${rtlsdr_SOURCES} + ${rtlsdr_HEADERS_MOC} + ${rtlsdr_FORMS_HEADERS} +) + +target_link_libraries(inputrtlsdr + ${QT_LIBRARIES} + ${LIBRTLSDR_LIBRARIES} + ${LIBUSB_LIBRARIES} + sdrbase +) + +qt5_use_modules(inputrtlsdr Core Widgets OpenGL Multimedia) diff --git a/plugins/samplesource/rtlsdr/rtlsdrgui.cpp b/plugins/samplesource/rtlsdr/rtlsdrgui.cpp new file mode 100644 index 000000000..57065653f --- /dev/null +++ b/plugins/samplesource/rtlsdr/rtlsdrgui.cpp @@ -0,0 +1,154 @@ +#include "rtlsdrgui.h" +#include "ui_rtlsdrgui.h" +#include "plugin/pluginapi.h" + +RTLSDRGui::RTLSDRGui(PluginAPI* pluginAPI, QWidget* parent) : + QWidget(parent), + ui(new Ui::RTLSDRGui), + m_pluginAPI(pluginAPI), + m_settings(), + m_sampleSource(NULL) +{ + ui->setupUi(this); + ui->centerFrequency->setValueRange(7, 20000U, 2200000U); + connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(updateHardware())); + displaySettings(); + + m_sampleSource = new RTLSDRInput(m_pluginAPI->getMainWindowMessageQueue()); + m_pluginAPI->setSampleSource(m_sampleSource); +} + +RTLSDRGui::~RTLSDRGui() +{ + delete ui; +} + +void RTLSDRGui::destroy() +{ + delete this; +} + +void RTLSDRGui::setName(const QString& name) +{ + setObjectName(name); +} + +void RTLSDRGui::resetToDefaults() +{ + m_generalSettings.resetToDefaults(); + m_settings.resetToDefaults(); + displaySettings(); + sendSettings(); +} + +QByteArray RTLSDRGui::serializeGeneral() const +{ + return m_generalSettings.serialize(); +} + +bool RTLSDRGui::deserializeGeneral(const QByteArray&data) +{ + if(m_generalSettings.deserialize(data)) { + displaySettings(); + sendSettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +quint64 RTLSDRGui::getCenterFrequency() const +{ + return m_generalSettings.m_centerFrequency; +} + +QByteArray RTLSDRGui::serialize() const +{ + return m_settings.serialize(); +} + +bool RTLSDRGui::deserialize(const QByteArray& data) +{ + if(m_settings.deserialize(data)) { + displaySettings(); + sendSettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +bool RTLSDRGui::handleMessage(Message* message) +{ + if(RTLSDRInput::MsgReportRTLSDR::match(message)) { + m_gains = ((RTLSDRInput::MsgReportRTLSDR*)message)->getGains(); + displaySettings(); + message->completed(); + return true; + } else { + return false; + } +} + +void RTLSDRGui::displaySettings() +{ + ui->centerFrequency->setValue(m_generalSettings.m_centerFrequency / 1000); + ui->decimation->setValue(m_settings.m_decimation); + + if(m_gains.size() > 0) { + int dist = abs(m_settings.m_gain - m_gains[0]); + int pos = 0; + for(uint i = 1; i < m_gains.size(); i++) { + if(abs(m_settings.m_gain - m_gains[i]) < dist) { + dist = abs(m_settings.m_gain - m_gains[i]); + pos = i; + } + } + ui->gainText->setText(tr("%1.%2").arg(m_gains[pos] / 10).arg(abs(m_gains[pos] % 10))); + ui->gain->setMaximum(m_gains.size() - 1); + ui->gain->setEnabled(true); + ui->gain->setValue(pos); + } else { + ui->gain->setMaximum(0); + ui->gain->setEnabled(false); + ui->gain->setValue(0); + } +} + +void RTLSDRGui::sendSettings() +{ + if(!m_updateTimer.isActive()) + m_updateTimer.start(100); +} + +void RTLSDRGui::on_centerFrequency_changed(quint64 value) +{ + m_generalSettings.m_centerFrequency = value * 1000; + sendSettings(); +} + +void RTLSDRGui::on_gain_valueChanged(int value) +{ + if(value > (int)m_gains.size()) + return; + int gain = m_gains[value]; + ui->gainText->setText(tr("%1.%2").arg(gain / 10).arg(abs(gain % 10))); + m_settings.m_gain = gain; + sendSettings(); +} + +void RTLSDRGui::on_decimation_valueChanged(int value) +{ + ui->decimationText->setText(tr("1:%1").arg(1 << value)); + m_settings.m_decimation = value; + sendSettings(); +} + +void RTLSDRGui::updateHardware() +{ + RTLSDRInput::MsgConfigureRTLSDR* message = RTLSDRInput::MsgConfigureRTLSDR::create(m_generalSettings, m_settings); + message->submit(m_pluginAPI->getDSPEngineMessageQueue()); + m_updateTimer.stop(); +} diff --git a/plugins/samplesource/rtlsdr/rtlsdrgui.h b/plugins/samplesource/rtlsdr/rtlsdrgui.h new file mode 100644 index 000000000..46b248bd1 --- /dev/null +++ b/plugins/samplesource/rtlsdr/rtlsdrgui.h @@ -0,0 +1,53 @@ +#ifndef INCLUDE_RTLSDRGUI_H +#define INCLUDE_RTLSDRGUI_H + +#include +#include "plugin/plugingui.h" +#include "rtlsdrinput.h" + +class PluginAPI; + +namespace Ui { + class RTLSDRGui; +} + +class RTLSDRGui : public QWidget, public PluginGUI { + Q_OBJECT + +public: + explicit RTLSDRGui(PluginAPI* pluginAPI, QWidget* parent = NULL); + ~RTLSDRGui(); + void destroy(); + + void setName(const QString& name); + + void resetToDefaults(); + QByteArray serializeGeneral() const; + bool deserializeGeneral(const QByteArray&data); + quint64 getCenterFrequency() const; + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + bool handleMessage(Message* message); + +private: + Ui::RTLSDRGui* ui; + + PluginAPI* m_pluginAPI; + SampleSource::GeneralSettings m_generalSettings; + RTLSDRInput::Settings m_settings; + QTimer m_updateTimer; + std::vector m_gains; + SampleSource* m_sampleSource; + + void displaySettings(); + void sendSettings(); + +private slots: + void on_centerFrequency_changed(quint64 value); + void on_gain_valueChanged(int value); + void on_decimation_valueChanged(int value); + + void updateHardware(); +}; + +#endif // INCLUDE_RTLSDRGUI_H diff --git a/plugins/samplesource/rtlsdr/rtlsdrgui.ui b/plugins/samplesource/rtlsdr/rtlsdrgui.ui new file mode 100644 index 000000000..ce2ea4c98 --- /dev/null +++ b/plugins/samplesource/rtlsdr/rtlsdrgui.ui @@ -0,0 +1,229 @@ + + + RTLSDRGui + + + + 0 + 0 + 132 + 82 + + + + + 0 + 0 + + + + RTL-SDR + + + + 3 + + + 2 + + + 2 + + + 2 + + + 2 + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + 0 + 0 + + + + + 32 + 16 + + + + + Monospace + 20 + + + + Qt::StrongFocus + + + Tuner center frequency in kHz + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + + Qt::Horizontal + + + + + + + 3 + + + + + Signal decimation factor + + + 4 + + + 1 + + + Qt::Horizontal + + + + + + + + 0 + 0 + + + + Decimation + + + + + + + + 40 + 0 + + + + 1:1 + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + Qt::Horizontal + + + + + + + 3 + + + + + + 0 + 0 + + + + Gain + + + + + + + false + + + LNA amplification + + + 0 + + + 1 + + + Qt::Horizontal + + + + + + + + 40 + 0 + + + + --- + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + + + + + + + + ValueDial + QWidget +
gui/valuedial.h
+ 1 +
+
+ + +
diff --git a/plugins/samplesource/rtlsdr/rtlsdrinput.cpp b/plugins/samplesource/rtlsdr/rtlsdrinput.cpp new file mode 100644 index 000000000..a5d1d953d --- /dev/null +++ b/plugins/samplesource/rtlsdr/rtlsdrinput.cpp @@ -0,0 +1,230 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "rtlsdrinput.h" +#include "rtlsdrthread.h" +#include "rtlsdrgui.h" +#include "util/simpleserializer.h" + +MESSAGE_CLASS_DEFINITION(RTLSDRInput::MsgConfigureRTLSDR, Message) +MESSAGE_CLASS_DEFINITION(RTLSDRInput::MsgReportRTLSDR, Message) + +RTLSDRInput::Settings::Settings() : + m_gain(0), + m_decimation(0) +{ +} + +void RTLSDRInput::Settings::resetToDefaults() +{ + m_gain = 0; + m_decimation = 0; +} + +QByteArray RTLSDRInput::Settings::serialize() const +{ + SimpleSerializer s(1); + s.writeS32(1, m_gain); + s.writeS32(2, m_decimation); + return s.final(); +} + +bool RTLSDRInput::Settings::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { + d.readS32(1, &m_gain, 0); + d.readS32(2, &m_decimation, 0); + return true; + } else { + resetToDefaults(); + return false; + } +} + +RTLSDRInput::RTLSDRInput(MessageQueue* msgQueueToGUI) : + SampleSource(msgQueueToGUI), + m_settings(), + m_dev(NULL), + m_rtlSDRThread(NULL), + m_deviceDescription() +{ +} + +RTLSDRInput::~RTLSDRInput() +{ + stopInput(); +} + +bool RTLSDRInput::startInput(int device) +{ + QMutexLocker mutexLocker(&m_mutex); + + if(m_dev != NULL) + stopInput(); + + char vendor[256]; + char product[256]; + char serial[256]; + int res; + int numberOfGains; + + if(!m_sampleFifo.setSize(524288)) { + qCritical("Could not allocate SampleFifo"); + return false; + } + + if((res = rtlsdr_open(&m_dev, device)) < 0) { + qCritical("could not open RTLSDR #%d: %s", device, strerror(errno)); + return false; + } + + vendor[0] = '\0'; + product[0] = '\0'; + serial[0] = '\0'; + if((res = rtlsdr_get_usb_strings(m_dev, vendor, product, serial)) < 0) { + qCritical("error accessing USB device"); + goto failed; + } + qDebug("RTLSDRInput open: %s %s, SN: %s", vendor, product, serial); + m_deviceDescription = QString("%1 (SN %2)").arg(product).arg(serial); + + if((res = rtlsdr_set_sample_rate(m_dev, 2000000)) < 0) { + qCritical("could not set sample rate: %s", strerror(errno)); + goto failed; + } + + if((res = rtlsdr_set_tuner_gain_mode(m_dev, 1)) < 0) { + qCritical("error setting tuner gain mode"); + goto failed; + } + if((res = rtlsdr_set_agc_mode(m_dev, 0)) < 0) { + qCritical("error setting agc mode"); + goto failed; + } + + numberOfGains = rtlsdr_get_tuner_gains(m_dev, NULL); + if(numberOfGains < 0) { + qCritical("error getting number of gain values supported"); + goto failed; + } + m_gains.resize(numberOfGains); + if(rtlsdr_get_tuner_gains(m_dev, &m_gains[0]) < 0) { + qCritical("error getting gain values"); + goto failed; + } + if((res = rtlsdr_reset_buffer(m_dev)) < 0) { + qCritical("could not reset USB EP buffers: %s", strerror(errno)); + goto failed; + } + + if((m_rtlSDRThread = new RTLSDRThread(m_dev, &m_sampleFifo)) == NULL) { + qFatal("out of memory"); + goto failed; + } + m_rtlSDRThread->startWork(); + + mutexLocker.unlock(); + applySettings(m_generalSettings, m_settings, true); + + qDebug("RTLSDRInput: start"); + MsgReportRTLSDR::create(m_gains)->submit(m_guiMessageQueue); + + return true; + +failed: + stopInput(); + return false; +} + +void RTLSDRInput::stopInput() +{ + QMutexLocker mutexLocker(&m_mutex); + + if(m_rtlSDRThread != NULL) { + m_rtlSDRThread->stopWork(); + delete m_rtlSDRThread; + m_rtlSDRThread = NULL; + } + if(m_dev != NULL) { + rtlsdr_close(m_dev); + m_dev = NULL; + } + m_deviceDescription.clear(); +} + +const QString& RTLSDRInput::getDeviceDescription() const +{ + return m_deviceDescription; +} + +int RTLSDRInput::getSampleRate() const +{ + return 2000000 / (1 << m_settings.m_decimation); +} + +quint64 RTLSDRInput::getCenterFrequency() const +{ + return m_generalSettings.m_centerFrequency; +} + +bool RTLSDRInput::handleMessage(Message* message) +{ + if(MsgConfigureRTLSDR::match(message)) { + MsgConfigureRTLSDR* conf = (MsgConfigureRTLSDR*)message; + if(!applySettings(conf->getGeneralSettings(), conf->getSettings(), false)) + qDebug("RTLSDR config error"); + message->completed(); + return true; + } else { + return false; + } +} + +bool RTLSDRInput::applySettings(const GeneralSettings& generalSettings, const Settings& settings, bool force) +{ + QMutexLocker mutexLocker(&m_mutex); + + if((m_generalSettings.m_centerFrequency != generalSettings.m_centerFrequency) || force) { + m_generalSettings.m_centerFrequency = generalSettings.m_centerFrequency; + if(m_dev != NULL) { + if(rtlsdr_set_center_freq(m_dev, m_generalSettings.m_centerFrequency) != 0) + qDebug("osmosdr_set_center_freq(%lld) failed", m_generalSettings.m_centerFrequency); + } + } + if((m_settings.m_gain != settings.m_gain) || force) { + m_settings.m_gain = settings.m_gain; + if(m_dev != NULL) { + if(rtlsdr_set_tuner_gain(m_dev, m_settings.m_gain) != 0) + qDebug("rtlsdr_set_tuner_gain() failed"); + } + } + if((m_settings.m_decimation != settings.m_decimation) || force) { + m_settings.m_decimation = settings.m_decimation; + if(m_dev != NULL) + m_rtlSDRThread->setDecimation(m_settings.m_decimation); + } + return true; +} diff --git a/plugins/samplesource/rtlsdr/rtlsdrinput.h b/plugins/samplesource/rtlsdr/rtlsdrinput.h new file mode 100644 index 000000000..d171af1ad --- /dev/null +++ b/plugins/samplesource/rtlsdr/rtlsdrinput.h @@ -0,0 +1,105 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_RTLSDRINPUT_H +#define INCLUDE_RTLSDRINPUT_H + +#include "dsp/samplesource/samplesource.h" +#include +#include + +class RTLSDRThread; + +class RTLSDRInput : public SampleSource { +public: + struct Settings { + qint32 m_gain; + qint32 m_decimation; + + Settings(); + void resetToDefaults(); + QByteArray serialize() const; + bool deserialize(const QByteArray& data); + }; + + class MsgConfigureRTLSDR : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const GeneralSettings& getGeneralSettings() const { return m_generalSettings; } + const Settings& getSettings() const { return m_settings; } + + static MsgConfigureRTLSDR* create(const GeneralSettings& generalSettings, const Settings& settings) + { + return new MsgConfigureRTLSDR(generalSettings, settings); + } + + private: + GeneralSettings m_generalSettings; + Settings m_settings; + + MsgConfigureRTLSDR(const GeneralSettings& generalSettings, const Settings& settings) : + Message(), + m_generalSettings(generalSettings), + m_settings(settings) + { } + }; + + class MsgReportRTLSDR : public Message { + MESSAGE_CLASS_DECLARATION + + public: + const std::vector& getGains() const { return m_gains; } + + static MsgReportRTLSDR* create(const std::vector& gains) + { + return new MsgReportRTLSDR(gains); + } + + protected: + std::vector m_gains; + + MsgReportRTLSDR(const std::vector& gains) : + Message(), + m_gains(gains) + { } + }; + + RTLSDRInput(MessageQueue* msgQueueToGUI); + ~RTLSDRInput(); + + bool startInput(int device); + void stopInput(); + + const QString& getDeviceDescription() const; + int getSampleRate() const; + quint64 getCenterFrequency() const; + + bool handleMessage(Message* message); + +private: + QMutex m_mutex; + Settings m_settings; + rtlsdr_dev_t* m_dev; + RTLSDRThread* m_rtlSDRThread; + QString m_deviceDescription; + std::vector m_gains; + + bool applySettings(const GeneralSettings& generalSettings, const Settings& settings, bool force); +}; + +#endif // INCLUDE_RTLSDRINPUT_H diff --git a/plugins/samplesource/rtlsdr/rtlsdrplugin.cpp b/plugins/samplesource/rtlsdr/rtlsdrplugin.cpp new file mode 100644 index 000000000..785aa2d7f --- /dev/null +++ b/plugins/samplesource/rtlsdr/rtlsdrplugin.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +#include "plugin/pluginapi.h" +#include "util/simpleserializer.h" +#include "rtlsdrplugin.h" +#include "rtlsdrgui.h" + +const PluginDescriptor RTLSDRPlugin::m_pluginDescriptor = { + QString("RTL-SDR Input"), + QString("---"), + QString("(c) librtlsdr Authors (see source URL)"), + QString("http://sdr.osmocom.org/trac/wiki/rtl-sdr"), + true, + QString("http://cgit.osmocom.org/cgit/rtl-sdr") +}; + +RTLSDRPlugin::RTLSDRPlugin(QObject* parent) : + QObject(parent) +{ +} + +const PluginDescriptor& RTLSDRPlugin::getPluginDescriptor() const +{ + return m_pluginDescriptor; +} + +void RTLSDRPlugin::initPlugin(PluginAPI* pluginAPI) +{ + m_pluginAPI = pluginAPI; + + m_pluginAPI->registerSampleSource("org.osmocom.sdr.samplesource.rtl-sdr", this); +} + +PluginInterface::SampleSourceDevices RTLSDRPlugin::enumSampleSources() +{ + SampleSourceDevices result; + int count = rtlsdr_get_device_count(); + char vendor[256]; + char product[256]; + char serial[256]; + + for(int i = 0; i < count; i++) { + vendor[0] = '\0'; + product[0] = '\0'; + serial[0] = '\0'; + + if(rtlsdr_get_device_usb_strings(i, vendor, product, serial) != 0) + continue; + QString displayedName(QString("RTL-SDR #%1 (%2 #%3)").arg(i + 1).arg(product).arg(serial)); + SimpleSerializer s(1); + s.writeS32(1, i); + result.append(SampleSourceDevice(displayedName, "org.osmocom.sdr.samplesource.rtl-sdr", s.final())); + } + return result; +} + +PluginGUI* RTLSDRPlugin::createSampleSource(const QString& sourceName, const QByteArray& address) +{ + if(sourceName == "org.osmocom.sdr.samplesource.rtl-sdr") { + RTLSDRGui* gui = new RTLSDRGui(m_pluginAPI); + m_pluginAPI->setInputGUI(gui); + return gui; + } else { + return NULL; + } +} diff --git a/plugins/samplesource/rtlsdr/rtlsdrplugin.h b/plugins/samplesource/rtlsdr/rtlsdrplugin.h new file mode 100644 index 000000000..bd6b9072c --- /dev/null +++ b/plugins/samplesource/rtlsdr/rtlsdrplugin.h @@ -0,0 +1,27 @@ +#ifndef INCLUDE_RTLSDRPLUGIN_H +#define INCLUDE_RTLSDRPLUGIN_H + +#include +#include "plugin/plugininterface.h" + +class RTLSDRPlugin : public QObject, PluginInterface { + Q_OBJECT + Q_INTERFACES(PluginInterface) + Q_PLUGIN_METADATA(IID "org.osmocom.sdr.samplesource.rtl-sdr") + +public: + explicit RTLSDRPlugin(QObject* parent = NULL); + + const PluginDescriptor& getPluginDescriptor() const; + void initPlugin(PluginAPI* pluginAPI); + + SampleSourceDevices enumSampleSources(); + PluginGUI* createSampleSource(const QString& sourceName, const QByteArray& address); + +private: + static const PluginDescriptor m_pluginDescriptor; + + PluginAPI* m_pluginAPI; +}; + +#endif // INCLUDE_RTLSDRPLUGIN_H diff --git a/plugins/samplesource/rtlsdr/rtlsdrthread.cpp b/plugins/samplesource/rtlsdr/rtlsdrthread.cpp new file mode 100644 index 000000000..8c8a17c42 --- /dev/null +++ b/plugins/samplesource/rtlsdr/rtlsdrthread.cpp @@ -0,0 +1,172 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "rtlsdrthread.h" +#include "dsp/samplefifo.h" + +#define BLOCKSIZE 16384 + +RTLSDRThread::RTLSDRThread(rtlsdr_dev_t* dev, SampleFifo* sampleFifo, QObject* parent) : + QThread(parent), + m_running(false), + m_dev(dev), + m_convertBuffer(BLOCKSIZE), + m_sampleFifo(sampleFifo), + m_decimation(1) +{ +} + +RTLSDRThread::~RTLSDRThread() +{ + stopWork(); +} + +void RTLSDRThread::startWork() +{ + m_startWaitMutex.lock(); + start(); + while(!m_running) + m_startWaiter.wait(&m_startWaitMutex, 100); + m_startWaitMutex.unlock(); +} + +void RTLSDRThread::stopWork() +{ + m_running = false; + wait(); +} + +void RTLSDRThread::setDecimation(int decimation) +{ + m_decimation = decimation; +} + +void RTLSDRThread::run() +{ + int res; + + m_running = true; + m_startWaiter.wakeAll(); + + while(m_running) { + if((res = rtlsdr_read_async(m_dev, &RTLSDRThread::callbackHelper, this, 16, 2 * BLOCKSIZE)) < 0) { + qCritical("RTLSDRThread: async error: %s", strerror(errno)); + break; + } + } + + m_running = false; +} + +void RTLSDRThread::decimate2(SampleVector::iterator* it, const quint8* buf, qint32 len) +{ + for(int pos = 0; pos < len; pos += 2) { + Sample s((((qint8)buf[pos]) - 128) << 8, (((qint8)buf[pos + 1]) - 128) << 8); + if(m_decimator2.workDecimateCenter(&s)) { + **it = s; + ++(*it); + } + } +} + +void RTLSDRThread::decimate4(SampleVector::iterator* it, const quint8* buf, qint32 len) +{ + for(int pos = 0; pos < len; pos += 2) { + Sample s((((qint8)buf[pos]) - 128) << 8, (((qint8)buf[pos + 1]) - 128) << 8); + if(m_decimator2.workDecimateCenter(&s)) { + if(m_decimator4.workDecimateCenter(&s)) { + **it = s; + ++(*it); + } + } + } +} + +void RTLSDRThread::decimate8(SampleVector::iterator* it, const quint8* buf, qint32 len) +{ + for(int pos = 0; pos < len; pos += 2) { + Sample s((((qint8)buf[pos]) - 128) << 8, (((qint8)buf[pos + 1]) - 128) << 8); + if(m_decimator2.workDecimateCenter(&s)) { + if(m_decimator4.workDecimateCenter(&s)) { + if(m_decimator8.workDecimateCenter(&s)) { + **it = s; + ++(*it); + } + } + } + } +} + +void RTLSDRThread::decimate16(SampleVector::iterator* it, const quint8* buf, qint32 len) +{ + for(int pos = 0; pos < len; pos += 2) { + Sample s((((qint8)buf[pos]) - 128) << 8, (((qint8)buf[pos + 1]) - 128) << 8); + if(m_decimator2.workDecimateCenter(&s)) { + if(m_decimator4.workDecimateCenter(&s)) { + if(m_decimator8.workDecimateCenter(&s)) { + if(m_decimator16.workDecimateCenter(&s)) { + **it = s; + ++(*it); + } + } + } + } + } +} + +void RTLSDRThread::callback(const quint8* buf, qint32 len) +{ + SampleVector::iterator it = m_convertBuffer.begin(); + + switch(m_decimation) { + case 0: // 1:1 = no decimation + for(int pos = 0; pos < len; pos += 2) { + *it = Sample((((qint8)buf[pos]) - 128) << 8, (((qint8)buf[pos + 1]) - 128) << 8); + ++it; + } + break; + + case 1: // 1:2 + decimate2(&it, buf, len); + break; + + case 2: // 1:4 + decimate4(&it, buf, len); + break; + + case 3: // 1:8 + decimate8(&it, buf, len); + break; + + case 4: // 1:16 + decimate16(&it, buf, len); + break; + } + + m_sampleFifo->write(m_convertBuffer.begin(), it); + + if(!m_running) + rtlsdr_cancel_async(m_dev); +} + +void RTLSDRThread::callbackHelper(unsigned char* buf, uint32_t len, void* ctx) +{ + RTLSDRThread* thread = (RTLSDRThread*)ctx; + thread->callback(buf, len); +} diff --git a/plugins/samplesource/rtlsdr/rtlsdrthread.h b/plugins/samplesource/rtlsdr/rtlsdrthread.h new file mode 100644 index 000000000..08837effa --- /dev/null +++ b/plugins/samplesource/rtlsdr/rtlsdrthread.h @@ -0,0 +1,67 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#ifndef INCLUDE_RTLSDRTHREAD_H +#define INCLUDE_RTLSDRTHREAD_H + +#include +#include +#include +#include +#include "dsp/samplefifo.h" +#include "dsp/inthalfbandfilter.h" + +class RTLSDRThread : public QThread { + Q_OBJECT + +public: + RTLSDRThread(rtlsdr_dev_t* dev, SampleFifo* sampleFifo, QObject* parent = NULL); + ~RTLSDRThread(); + + void startWork(); + void stopWork(); + + void setDecimation(int decimation); + +private: + QMutex m_startWaitMutex; + QWaitCondition m_startWaiter; + bool m_running; + + rtlsdr_dev_t* m_dev; + SampleVector m_convertBuffer; + SampleFifo* m_sampleFifo; + + int m_decimation; + + IntHalfbandFilter m_decimator2; + IntHalfbandFilter m_decimator4; + IntHalfbandFilter m_decimator8; + IntHalfbandFilter m_decimator16; + + void run(); + + void decimate2(SampleVector::iterator* it, const quint8* buf, qint32 len); + void decimate4(SampleVector::iterator* it, const quint8* buf, qint32 len); + void decimate8(SampleVector::iterator* it, const quint8* buf, qint32 len); + void decimate16(SampleVector::iterator* it, const quint8* buf, qint32 len); + void callback(const quint8* buf, qint32 len); + + static void callbackHelper(unsigned char* buf, uint32_t len, void* ctx); +}; + +#endif // INCLUDE_RTLSDRTHREAD_H diff --git a/sdrbase/audio/audiodeviceinfo.cpp b/sdrbase/audio/audiodeviceinfo.cpp new file mode 100644 index 000000000..e422878ed --- /dev/null +++ b/sdrbase/audio/audiodeviceinfo.cpp @@ -0,0 +1,28 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "audio/audiodeviceinfo.h" + +AudioDeviceInfo::AudioDeviceInfo() +{ +} + +int AudioDeviceInfo::match(const QString& api, const QString device) const +{ + // nothing found - fall back to default + return 0; +} diff --git a/sdrbase/audio/audiofifo.cpp b/sdrbase/audio/audiofifo.cpp new file mode 100644 index 000000000..dd475caa6 --- /dev/null +++ b/sdrbase/audio/audiofifo.cpp @@ -0,0 +1,218 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "audio/audiofifo.h" + +#define MIN(x, y) ((x) < (y) ? (x) : (y)) + +AudioFifo::AudioFifo() : + m_fifo(NULL) +{ + m_size = 0; + m_fill = 0; + m_head = 0; + m_tail = 0; +} + +AudioFifo::AudioFifo(uint sampleSize, uint numSamples) : + m_fifo(NULL) +{ + QMutexLocker mutexLocker(&m_mutex); + + create(sampleSize, numSamples); +} + +AudioFifo::~AudioFifo() +{ + QMutexLocker mutexLocker(&m_mutex); + + if(m_fifo != NULL) { + delete[] m_fifo; + m_fifo = NULL; + } + + m_writeWaitCondition.wakeOne(); + m_readWaitCondition.wakeOne(); + + m_size = 0; +} + +bool AudioFifo::setSize(uint sampleSize, uint numSamples) +{ + QMutexLocker mutexLocker(&m_mutex); + + return create(sampleSize, numSamples); +} + +uint AudioFifo::write(const quint8* data, uint numSamples, int timeout) +{ + QTime time; + uint total; + uint remaining; + uint copyLen; + + if(m_fifo == NULL) + return 0; + + time.start(); + m_mutex.lock(); + + if(timeout == 0) + total = MIN(numSamples, m_size - m_fill); + else total = numSamples; + + remaining = total; + while(remaining > 0) { + if(isFull()) { + if(time.elapsed() < timeout) { + m_writeWaitLock.lock(); + m_mutex.unlock(); + int ms = timeout - time.elapsed(); + if(ms < 1) + ms = 1; + bool ok = m_writeWaitCondition.wait(&m_writeWaitLock, ms); + m_writeWaitLock.unlock(); + if(!ok) + return total - remaining; + m_mutex.lock(); + if(m_fifo == NULL) { + m_mutex.unlock(); + return 0; + } + } else { + m_mutex.unlock(); + return total - remaining; + } + } + copyLen = MIN(remaining, m_size - m_fill); + copyLen = MIN(copyLen, m_size - m_tail); + memcpy(m_fifo + (m_tail * m_sampleSize), data, copyLen * m_sampleSize); + m_tail += copyLen; + m_tail %= m_size; + m_fill += copyLen; + data += copyLen * m_sampleSize; + remaining -= copyLen; + m_readWaitCondition.wakeOne(); + } + + m_mutex.unlock(); + return total; +} + +uint AudioFifo::read(quint8* data, uint numSamples, int timeout) +{ + QTime time; + uint total; + uint remaining; + uint copyLen; + + if(m_fifo == NULL) + return 0; + + time.start(); + m_mutex.lock(); + + if(timeout == 0) + total = MIN(numSamples, m_fill); + else total = numSamples; + + remaining = total; + while(remaining > 0) { + if(isEmpty()) { + if(time.elapsed() < timeout) { + m_readWaitLock.lock(); + m_mutex.unlock(); + int ms = timeout - time.elapsed(); + if(ms < 1) + ms = 1; + bool ok = m_readWaitCondition.wait(&m_readWaitLock, ms); + m_readWaitLock.unlock(); + if(!ok) + return total - remaining; + m_mutex.lock(); + if(m_fifo == NULL) { + m_mutex.unlock(); + return 0; + } + } else { + m_mutex.unlock(); + return total - remaining; + } + } + + copyLen = MIN(remaining, m_fill); + copyLen = MIN(copyLen, m_size - m_head); + memcpy(data, m_fifo + (m_head * m_sampleSize), copyLen * m_sampleSize); + m_head += copyLen; + m_head %= m_size; + m_fill -= copyLen; + data += copyLen * m_sampleSize; + remaining -= copyLen; + m_writeWaitCondition.wakeOne(); + } + + m_mutex.unlock(); + return total; +} + +uint AudioFifo::drain(uint numSamples) +{ + QMutexLocker mutexLocker(&m_mutex); + + if(numSamples > m_fill) + numSamples = m_fill; + m_head = (m_head + numSamples) % m_size; + m_fill -= numSamples; + + m_writeWaitCondition.wakeOne(); + return numSamples; +} + +void AudioFifo::clear() +{ + QMutexLocker mutexLocker(&m_mutex); + + m_fill = 0; + m_head = 0; + m_tail = 0; + + m_writeWaitCondition.wakeOne(); +} + +bool AudioFifo::create(uint sampleSize, uint numSamples) +{ + if(m_fifo != NULL) { + delete[] m_fifo; + m_fifo = NULL; + } + + m_sampleSize = sampleSize; + m_size = 0; + m_fill = 0; + m_head = 0; + m_tail = 0; + + if((m_fifo = new qint8[numSamples * m_sampleSize]) == NULL) { + qDebug("out of memory"); + return false; + } + + m_size = numSamples; + return true; +} diff --git a/sdrbase/audio/audiooutput.cpp b/sdrbase/audio/audiooutput.cpp new file mode 100644 index 000000000..455241a0b --- /dev/null +++ b/sdrbase/audio/audiooutput.cpp @@ -0,0 +1,172 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include "audio/audiooutput.h" +#include "audio/audiofifo.h" + +AudioOutput::AudioOutput() : + m_mutex(), + m_audioOutput(NULL), + m_audioFifos() +{ +} + +AudioOutput::~AudioOutput() +{ + stop(); + + QMutexLocker mutexLocker(&m_mutex); + for(AudioFifos::iterator it = m_audioFifos.begin(); it != m_audioFifos.end(); ++it) + delete *it; + m_audioFifos.clear(); +} + +bool AudioOutput::start(int device, int rate) +{ + QMutexLocker mutexLocker(&m_mutex); + + Q_UNUSED(device); + Q_UNUSED(rate); + + QAudioFormat format; + QAudioDeviceInfo devInfo(QAudioDeviceInfo::defaultOutputDevice()); + + format.setSampleRate(41000); + format.setChannelCount(2); + format.setSampleSize(16); + format.setCodec("audio/pcm"); + format.setByteOrder(QAudioFormat::LittleEndian); + format.setSampleType(QAudioFormat::SignedInt); + + if(!devInfo.isFormatSupported(format)) { + qDebug("default format not supported - try to use nearest"); + format = devInfo.nearestFormat(format); + } + + if(format.sampleSize() != 16) { + qDebug("audio device doesn't support 16 bit samples (%s)", qPrintable(devInfo.defaultOutputDevice().deviceName())); + return false; + } + + m_audioOutput = new QAudioOutput(format); + + QIODevice::open(QIODevice::ReadOnly); + + m_audioOutput->start(this); + + return true; + +} + +void AudioOutput::stop() +{ + QMutexLocker mutexLocker(&m_mutex); + + if(m_audioOutput != NULL) { + m_audioOutput->stop(); + delete m_audioOutput; + m_audioOutput = NULL; + } + QIODevice::close(); +} + +void AudioOutput::addFifo(AudioFifo* audioFifo) +{ + QMutexLocker mutexLocker(&m_mutex); + + m_audioFifos.push_back(audioFifo); +} + +void AudioOutput::removeFifo(AudioFifo* audioFifo) +{ + QMutexLocker mutexLocker(&m_mutex); + + m_audioFifos.remove(audioFifo); +} + +bool AudioOutput::open(OpenMode mode) +{ + Q_UNUSED(mode); + return false; +} + +qint64 AudioOutput::readData(char* data, qint64 maxLen) +{ + if(maxLen == 0) + return 0; + + QMutexLocker mutexLocker(&m_mutex); + + maxLen -= maxLen % 4; + int framesPerBuffer = maxLen / 4; + + if((int)m_mixBuffer.size() < framesPerBuffer * 2) { + m_mixBuffer.resize(framesPerBuffer * 2); // allocate 2 qint32 per frame (stereo) + if(m_mixBuffer.size() != framesPerBuffer * 2) + return 0; + } + memset(&m_mixBuffer[0], 0x00, 2 * framesPerBuffer * sizeof(m_mixBuffer[0])); // start with silence + + // sum up a block from all fifos + for(AudioFifos::iterator it = m_audioFifos.begin(); it != m_audioFifos.end(); ++it) { + // use outputBuffer as temp - yes, one memcpy could be saved + uint samples = (*it)->read((quint8*)data, framesPerBuffer, 1); + const qint16* src = (const qint16*)data; + std::vector::iterator dst = m_mixBuffer.begin(); + for(uint i = 0; i < samples; i++) { + *dst += *src; + ++src; + ++dst; + *dst += *src; + ++src; + ++dst; + } + } + + // convert to int16 + std::vector::const_iterator src = m_mixBuffer.begin(); + qint16* dst = (qint16*)data; + for(int i = 0; i < framesPerBuffer; ++i) { + // left channel + qint32 s = *src++; + if(s < -32768) + s = -32768; + else if(s > 32767) + s = 32767; + *dst++ = s; + // right channel + s = *src++; + if(s < -32768) + s = -32768; + else if(s > 32767) + s = 32767; + *dst++ = s; + } + + return framesPerBuffer * 4; +} + +qint64 AudioOutput::writeData(const char* data, qint64 len) +{ + Q_UNUSED(data); + Q_UNUSED(len); + return 0; +} diff --git a/sdrbase/dsp/channelizer.cpp b/sdrbase/dsp/channelizer.cpp new file mode 100644 index 000000000..2028a0fca --- /dev/null +++ b/sdrbase/dsp/channelizer.cpp @@ -0,0 +1,328 @@ +#include "dsp/channelizer.h" +#include "dsp/inthalfbandfilter.h" +#include "dsp/dspcommands.h" + +Channelizer::Channelizer(SampleSink* sampleSink) : + m_sampleSink(sampleSink), + m_inputSampleRate(100000), + m_requestedOutputSampleRate(100000), + m_requestedCenterFrequency(0), + m_currentOutputSampleRate(100000), + m_currentCenterFrequency(0) +{ +} + +Channelizer::~Channelizer() +{ + freeFilterChain(); +} + +void Channelizer::configure(MessageQueue* messageQueue, int sampleRate, int centerFrequency) +{ + Message* cmd = DSPConfigureChannelizer::create(sampleRate, centerFrequency); + cmd->submit(messageQueue, this); +} + +void Channelizer::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst) +{ + for(SampleVector::const_iterator sample = begin; sample != end; ++sample) { + Sample s(*sample); + FilterStages::iterator stage = m_filterStages.begin(); + while(stage != m_filterStages.end()) { + if(!(*stage)->work(&s)) + break; + ++stage; + } + if(stage == m_filterStages.end()) + m_sampleBuffer.push_back(s); + } + + if(m_sampleSink != NULL) + m_sampleSink->feed(m_sampleBuffer.begin(), m_sampleBuffer.end(), firstOfBurst); + + m_sampleBuffer.clear(); +} + +void Channelizer::start() +{ + if(m_sampleSink != NULL) + m_sampleSink->start(); +} + +void Channelizer::stop() +{ + if(m_sampleSink != NULL) + m_sampleSink->stop(); +} + +bool Channelizer::handleMessage(Message* cmd) +{ + if(DSPSignalNotification::match(cmd)) { + DSPSignalNotification* signal = (DSPSignalNotification*)cmd; + m_inputSampleRate = signal->getSampleRate(); + applyConfiguration(); + cmd->completed(); + if(m_sampleSink != NULL) { + signal = DSPSignalNotification::create(m_currentOutputSampleRate, m_currentCenterFrequency); + if(!m_sampleSink->handleMessage(signal)) + signal->completed(); + } + return true; + } else if(DSPConfigureChannelizer::match(cmd)) { + DSPConfigureChannelizer* chan = (DSPConfigureChannelizer*)cmd; + m_requestedOutputSampleRate = chan->getSampleRate(); + m_requestedCenterFrequency = chan->getCenterFrequency(); + applyConfiguration(); + cmd->completed(); + if(m_sampleSink != NULL) { + DSPSignalNotification* signal = DSPSignalNotification::create(m_currentOutputSampleRate, m_currentCenterFrequency); + if(!m_sampleSink->handleMessage(signal)) + signal->completed(); + } + return true; + } else { + if(m_sampleSink != NULL) + return m_sampleSink->handleMessage(cmd); + else return false; + } +} + +void Channelizer::applyConfiguration() +{ + freeFilterChain(); + m_currentCenterFrequency = createFilterChain( + m_inputSampleRate / -2, m_inputSampleRate / 2, + m_requestedCenterFrequency - m_requestedOutputSampleRate / 2, m_requestedCenterFrequency + m_requestedOutputSampleRate / 2); + m_currentOutputSampleRate = m_inputSampleRate / (1 << m_filterStages.size()); +} + +Channelizer::FilterStage::FilterStage(Mode mode) : + m_filter(new IntHalfbandFilter), + m_workFunction(NULL) +{ + switch(mode) { + case ModeCenter: + m_workFunction = &IntHalfbandFilter::workDecimateCenter; + break; + + case ModeLowerHalf: + m_workFunction = &IntHalfbandFilter::workDecimateLowerHalf; + break; + + case ModeUpperHalf: + m_workFunction = &IntHalfbandFilter::workDecimateUpperHalf; + break; + } +} + +Channelizer::FilterStage::~FilterStage() +{ + delete m_filter; +} + +bool Channelizer::signalContainsChannel(Real sigStart, Real sigEnd, Real chanStart, Real chanEnd) const +{ + //qDebug(" testing signal [%f, %f], channel [%f, %f]", sigStart, sigEnd, chanStart, chanEnd); + if(sigEnd <= sigStart) + return false; + if(chanEnd <= chanStart) + return false; + return (sigStart <= chanStart) && (sigEnd >= chanEnd); +} + +Real Channelizer::createFilterChain(Real sigStart, Real sigEnd, Real chanStart, Real chanEnd) +{ + Real sigBw = sigEnd - sigStart; + Real safetyMargin = sigBw / 20; + Real rot = sigBw / 4; + + safetyMargin = 0; + + //qDebug("Signal [%f, %f] (BW %f), Channel [%f, %f], Rot %f, Safety %f", sigStart, sigEnd, sigBw, chanStart, chanEnd, rot, safetyMargin); +#if 1 + // check if it fits into the left half + if(signalContainsChannel(sigStart + safetyMargin, sigStart + sigBw / 2.0 - safetyMargin, chanStart, chanEnd)) { + //qDebug("-> take left half (rotate by +1/4 and decimate by 2)"); + m_filterStages.push_back(new FilterStage(FilterStage::ModeLowerHalf)); + return createFilterChain(sigStart, sigStart + sigBw / 2.0, chanStart, chanEnd); + } + + // check if it fits into the right half + if(signalContainsChannel(sigEnd - sigBw / 2.0f + safetyMargin, sigEnd - safetyMargin, chanStart, chanEnd)) { + //qDebug("-> take right half (rotate by -1/4 and decimate by 2)"); + m_filterStages.push_back(new FilterStage(FilterStage::ModeUpperHalf)); + return createFilterChain(sigEnd - sigBw / 2.0f, sigEnd, chanStart, chanEnd); + } + + // check if it fits into the center + if(signalContainsChannel(sigStart + rot + safetyMargin, sigStart + rot + sigBw / 2.0f - safetyMargin, chanStart, chanEnd)) { + //qDebug("-> take center half (decimate by 2)"); + m_filterStages.push_back(new FilterStage(FilterStage::ModeCenter)); + return createFilterChain(sigStart + rot, sigStart + sigBw / 2.0f + rot, chanStart, chanEnd); + } +#endif + Real ofs = ((chanEnd - chanStart) / 2.0 + chanStart) - ((sigEnd - sigStart) / 2.0 + sigStart); + qDebug("-> complete (final BW %f, frequency offset %f)", sigBw, ofs); + return ofs; +} + +void Channelizer::freeFilterChain() +{ + for(FilterStages::iterator it = m_filterStages.begin(); it != m_filterStages.end(); ++it) + delete *it; + m_filterStages.clear(); +} + +#if 0 + +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "channelizer.h" +#include "hardware/audiooutput.h" + +Channelizer::Channelizer() +{ +#if 0 + m_spectrum.configure(128 , 25, FFTWindow::Bartlett); + m_buffer.resize(2048); + m_bufferFill = 0; + m_nco.setFreq(-100000, 500000); + m_interpolator.create(51, 32, 32 * 500000, 150000 / 2); + m_distance = 500000.0 / 176400.0; + + m_interpolator2.create(19, 8, 8 * 176400, 15000 / 2); + m_distance2 = 4; + + m_audioFifo.setSize(4, 44100 / 2 * 4); + m_audioOutput = new AudioOutput; + m_audioOutput->start(0, 44100, &m_audioFifo); + m_resampler = 1.0; + + m_resamplerCtrl.setup(0.00001, 0, -0.00001); +#endif +} + +Channelizer::~Channelizer() +{ +#if 0 + m_audioOutput->stop(); + delete m_audioOutput; +#endif +} + +#if 0 +void Channelizer::setGLSpectrum(GLSpectrum* glSpectrum) +{ + m_spectrum.setGLSpectrum(glSpectrum); +} +#endif + +size_t Channelizer::workUnitSize() +{ +#if 0 + return m_buffer.size(); +#endif + return 0; +} + +size_t Channelizer::work(SampleVector::const_iterator begin, SampleVector::const_iterator end) +{ +#if 0 + int buffered = m_audioOutput->bufferedSamples(); + + if(m_audioFifo.fill() < (m_audioFifo.size() / 6)) { + while(m_audioFifo.fill() < (m_audioFifo.size() / 2)) { + quint32 d = 0; + m_audioFifo.write((quint8*)&d, 4); + } + qDebug("underflow - fill %d (vs %d)", m_audioFifo.fill(), m_audioFifo.size() / 4 / 2); + } + + buffered = m_audioOutput->bufferedSamples(); + int fill = m_audioFifo.fill() / 4 + buffered; + float err = (float)fill / ((m_audioFifo.size() / 4) / 2); + + float ctrl = m_resamplerCtrl.feed(err); + //float resamplerRate = (ctrl / 1.0); + float resamplerRate = err; + + if(resamplerRate < 0.9999) + resamplerRate = 0.9999; + else if(resamplerRate > 1.0001) + resamplerRate = 1.0001; + m_resampler = m_resampler * 0.99 + resamplerRate * 0.01; + //m_resampler = resamplerRate; + + if(m_resampler < 0.995) + m_resampler = 0.995; + else if(m_resampler > 1.005) + m_resampler = 1.005; + + //qDebug("%lld %5d %f %f %f", QDateTime::currentMSecsSinceEpoch(), fill, ctrl, m_resampler, err); + + struct AudioSample { + qint16 l; + qint16 r; + }; + + size_t count = end - begin; + Complex ci; + bool consumed; + bool consumed2; + + for(SampleVector::const_iterator it = begin; it < end; it++) { + Complex c(it->real() / 32768.0, it->imag() / 32768.0); + c *= m_nco.nextIQ(); + + consumed = false; + if(m_interpolator.interpolate(&m_distance, c, &consumed, &ci)) { + + Complex d = ci * conj(m_lastSample); + m_lastSample = ci; + //Complex demod(atan2(d.imag(), d.real()) * 0.5, 0); + Real demod = atan2(d.imag(), d.real()) / M_PI; + + consumed2 = false; + c = Complex(demod, 0); + while(!consumed2) { + if(m_interpolator2.interpolate(&m_distance2, c, &consumed2, &ci)) { + m_buffer[m_bufferFill++] = Sample(ci.real() * 32767.0, 0.0); + + AudioSample s; + s.l = ci.real() * 32767.0; + s.r = s.l; + m_audioFifo.write((quint8*)&s, 4, 1); + + if(m_bufferFill >= m_buffer.size()) { + m_spectrum.feed(m_buffer.begin(), m_buffer.end()); + m_bufferFill = 0; + } + m_distance2 += 4.0 * m_resampler; + } + } + m_distance += 500000 / 176400.0; + } + } + + return count; +#endif +} + +#endif diff --git a/sdrbase/dsp/channelmarker.cpp b/sdrbase/dsp/channelmarker.cpp new file mode 100644 index 000000000..97d1e73ff --- /dev/null +++ b/sdrbase/dsp/channelmarker.cpp @@ -0,0 +1,68 @@ +#include "dsp/channelmarker.h" + +QRgb ChannelMarker::m_colorTable[] = { + qRgb(0xc0, 0x00, 0x00), + qRgb(0x00, 0xc0, 0x00), + qRgb(0x00, 0x00, 0xc0), + + qRgb(0xc0, 0xc0, 0x00), + qRgb(0xc0, 0x00, 0xc0), + qRgb(0x00, 0xc0, 0xc0), + + qRgb(0xc0, 0x60, 0x00), + qRgb(0xc0, 0x00, 0x60), + qRgb(0x60, 0x00, 0xc0), + + qRgb(0x60, 0x00, 0x00), + qRgb(0x00, 0x60, 0x00), + qRgb(0x00, 0x00, 0x60), + + qRgb(0x60, 0x60, 0x00), + qRgb(0x60, 0x00, 0x60), + qRgb(0x00, 0x60, 0x60), + + 0 +}; +int ChannelMarker::m_nextColor = 0; + +ChannelMarker::ChannelMarker(QObject* parent) : + QObject(parent), + m_centerFrequency(0), + m_bandwidth(0), + m_visible(false), + m_color(m_colorTable[m_nextColor]) +{ + ++m_nextColor; + if(m_colorTable[m_nextColor] == 0) + m_nextColor = 0; +} + +void ChannelMarker::setTitle(const QString& title) +{ + m_title = title; + emit changed(); +} + +void ChannelMarker::setCenterFrequency(int centerFrequency) +{ + m_centerFrequency = centerFrequency; + emit changed(); +} + +void ChannelMarker::setBandwidth(int bandwidth) +{ + m_bandwidth = bandwidth; + emit changed(); +} + +void ChannelMarker::setVisible(bool visible) +{ + m_visible = visible; + emit changed(); +} + +void ChannelMarker::setColor(const QColor& color) +{ + m_color = color; + emit changed(); +} diff --git a/sdrbase/dsp/dspcommands.cpp b/sdrbase/dsp/dspcommands.cpp new file mode 100644 index 000000000..21bdddc4d --- /dev/null +++ b/sdrbase/dsp/dspcommands.cpp @@ -0,0 +1,19 @@ +#include "dsp/dspcommands.h" + +MESSAGE_CLASS_DEFINITION(DSPPing, Message) +MESSAGE_CLASS_DEFINITION(DSPExit, Message) +MESSAGE_CLASS_DEFINITION(DSPAcquisitionStart, Message) +MESSAGE_CLASS_DEFINITION(DSPAcquisitionStop, Message) +MESSAGE_CLASS_DEFINITION(DSPGetDeviceDescription, Message) +MESSAGE_CLASS_DEFINITION(DSPGetErrorMessage, Message) +MESSAGE_CLASS_DEFINITION(DSPSetSource, Message) +MESSAGE_CLASS_DEFINITION(DSPAddSink, Message) +MESSAGE_CLASS_DEFINITION(DSPRemoveSink, Message) +MESSAGE_CLASS_DEFINITION(DSPAddAudioSource, Message) +MESSAGE_CLASS_DEFINITION(DSPRemoveAudioSource, Message) +MESSAGE_CLASS_DEFINITION(DSPConfigureSpectrumVis, Message) +MESSAGE_CLASS_DEFINITION(DSPConfigureCorrection, Message) +MESSAGE_CLASS_DEFINITION(DSPEngineReport, Message) +MESSAGE_CLASS_DEFINITION(DSPConfigureScopeVis, Message) +MESSAGE_CLASS_DEFINITION(DSPSignalNotification, Message) +MESSAGE_CLASS_DEFINITION(DSPConfigureChannelizer, Message) diff --git a/sdrbase/dsp/dspengine.cpp b/sdrbase/dsp/dspengine.cpp new file mode 100644 index 000000000..369403f39 --- /dev/null +++ b/sdrbase/dsp/dspengine.cpp @@ -0,0 +1,517 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include "dsp/dspengine.h" +#include "dsp/channelizer.h" +#include "dsp/samplefifo.h" +#include "dsp/samplesink.h" +#include "dsp/dspcommands.h" +#include "dsp/samplesource/samplesource.h" + +DSPEngine::DSPEngine(MessageQueue* reportQueue, QObject* parent) : + QThread(parent), + m_messageQueue(), + m_reportQueue(reportQueue), + m_state(StNotStarted), + m_sampleSource(NULL), + m_sampleSinks(), + m_sampleRate(0), + m_centerFrequency(0), + m_dcOffsetCorrection(false), + m_iqImbalanceCorrection(false), + m_iOffset(0), + m_qOffset(0), + m_iRange(1 << 16), + m_qRange(1 << 16), + m_imbalance(65536) +{ + moveToThread(this); +} + +DSPEngine::~DSPEngine() +{ + wait(); +} + +void DSPEngine::start() +{ + DSPPing cmd; + QThread::start(); + cmd.execute(&m_messageQueue); +} + +void DSPEngine::stop() +{ + DSPExit cmd; + cmd.execute(&m_messageQueue); +} + +bool DSPEngine::startAcquisition() +{ + DSPAcquisitionStart cmd; + return cmd.execute(&m_messageQueue) == StRunning; +} + +void DSPEngine::stopAcquistion() +{ + DSPAcquisitionStop cmd; + cmd.execute(&m_messageQueue); +} + +void DSPEngine::setSource(SampleSource* source) +{ + DSPSetSource cmd(source); + cmd.execute(&m_messageQueue); +} + +void DSPEngine::addSink(SampleSink* sink) +{ + DSPAddSink cmd(sink); + cmd.execute(&m_messageQueue); +} + +void DSPEngine::removeSink(SampleSink* sink) +{ + DSPRemoveSink cmd(sink); + cmd.execute(&m_messageQueue); +} + +void DSPEngine::addAudioSource(AudioFifo* audioFifo) +{ + DSPAddAudioSource cmd(audioFifo); + cmd.execute(&m_messageQueue); +} + +void DSPEngine::removeAudioSource(AudioFifo* audioFifo) +{ + DSPRemoveAudioSource cmd(audioFifo); + cmd.execute(&m_messageQueue); +} + +void DSPEngine::configureCorrections(bool dcOffsetCorrection, bool iqImbalanceCorrection) +{ + Message* cmd = DSPConfigureCorrection::create(dcOffsetCorrection, iqImbalanceCorrection); + cmd->submit(&m_messageQueue); +} + +QString DSPEngine::errorMessage() +{ + DSPGetErrorMessage cmd; + cmd.execute(&m_messageQueue); + return cmd.getErrorMessage(); +} + +QString DSPEngine::deviceDescription() +{ + DSPGetDeviceDescription cmd; + cmd.execute(&m_messageQueue); + return cmd.getDeviceDescription(); +} + +void DSPEngine::run() +{ + connect(&m_messageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleMessages()), Qt::QueuedConnection); + + m_state = StIdle; + + handleMessages(); + exec(); +} + +void DSPEngine::dcOffset(SampleVector::iterator begin, SampleVector::iterator end) +{ + int count = end - begin; + int io = 0; + int qo = 0; + + // sum all sample components + for(SampleVector::iterator it = begin; it < end; it++) { + io += it->real(); + qo += it->imag(); + } + + // build a sliding average (el cheapo style) + m_iOffset = (m_iOffset * 3 + io / count) >> 2; + m_qOffset = (m_qOffset * 3 + qo / count) >> 2; + + // correct samples + Sample corr(m_iOffset, m_qOffset); + for(SampleVector::iterator it = begin; it < end; it++) + *it -= corr; +} + +void DSPEngine::imbalance(SampleVector::iterator begin, SampleVector::iterator end) +{ + int iMin = 0; + int iMax = 0; + int qMin = 0; + int qMax = 0; + + // find value ranges for both I and Q + // both intervals should be same same size (for a perfect circle) + for(SampleVector::iterator it = begin; it < end; it++) { + if(it != begin) { + if(it->real() < iMin) + iMin = it->real(); + else if(it->real() > iMax) + iMax = it->real(); + if(it->imag() < qMin) + qMin = it->imag(); + else if(it->imag() > qMax) + qMax = it->imag(); + + } else { + iMin = it->real(); + iMax = it->real(); + qMin = it->imag(); + qMax = it->imag(); + } + } + + // sliding average (el cheapo again) + m_iRange = (m_iRange * 15 + (iMax - iMin)) >> 4; + m_qRange = (m_qRange * 15 + (qMax - qMin)) >> 4; + + // calculate imbalance as Q15.16 + if(m_qRange != 0) + m_imbalance = ((uint)m_iRange << 16) / (uint)m_qRange; + + // correct imbalance and convert back to signed int 16 + for(SampleVector::iterator it = begin; it < end; it++) + it->m_imag = (it->m_imag * m_imbalance) >> 16; +} + +void DSPEngine::work() +{ + SampleFifo* sampleFifo = m_sampleSource->getSampleFifo(); + size_t samplesDone = 0; + bool firstOfBurst = true; + + while((sampleFifo->fill() > 0) && (m_messageQueue.countPending() == 0) && (samplesDone < m_sampleRate)) { + SampleVector::iterator part1begin; + SampleVector::iterator part1end; + SampleVector::iterator part2begin; + SampleVector::iterator part2end; + + size_t count = sampleFifo->readBegin(sampleFifo->fill(), &part1begin, &part1end, &part2begin, &part2end); + + // first part of FIFO data + if(part1begin != part1end) { + // correct stuff + if(m_dcOffsetCorrection) + dcOffset(part1begin, part1end); + if(m_iqImbalanceCorrection) + imbalance(part1begin, part1end); + // feed data to handlers + for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++) + (*it)->feed(part1begin, part1end, firstOfBurst); + firstOfBurst = false; + } + // second part of FIFO data (used when block wraps around) + if(part2begin != part2end) { + // correct stuff + if(m_dcOffsetCorrection) + dcOffset(part2begin, part2end); + if(m_iqImbalanceCorrection) + imbalance(part2begin, part2end); + // feed data to handlers + for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++) + (*it)->feed(part2begin, part2end, firstOfBurst); + firstOfBurst = false; + } + + // adjust FIFO pointers + sampleFifo->readCommit(count); + samplesDone += count; + } + +#if 0 + size_t wus; + size_t maxWorkUnitSize = 0; + size_t samplesDone = 0; + + wus = m_spectrum.workUnitSize(); + if(wus > maxWorkUnitSize) + maxWorkUnitSize = wus; + for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++) { + wus = (*it)->workUnitSize(); + if(wus > maxWorkUnitSize) + maxWorkUnitSize = wus; + } + + while((m_sampleFifo.fill() > maxWorkUnitSize) && (m_commandQueue.countPending() == 0) && (samplesDone < m_sampleRate)) { + SampleVector::iterator part1begin; + SampleVector::iterator part1end; + SampleVector::iterator part2begin; + SampleVector::iterator part2end; + + size_t count = m_sampleFifo.readBegin(m_sampleFifo.fill(), &part1begin, &part1end, &part2begin, &part2end); + + // first part of FIFO data + if(part1begin != part1end) { + // correct stuff + if(m_settings.dcOffsetCorrection()) + dcOffset(part1begin, part1end); + if(m_settings.iqImbalanceCorrection()) + imbalance(part1begin, part1end); + // feed data to handlers + m_spectrum.feed(part1begin, part1end); + for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++) + (*it)->feed(part1begin, part1end); + } + // second part of FIFO data (used when block wraps around) + if(part2begin != part2end) { + // correct stuff + if(m_settings.dcOffsetCorrection()) + dcOffset(part2begin, part2end); + if(m_settings.iqImbalanceCorrection()) + imbalance(part2begin, part2end); + // feed data to handlers + m_spectrum.feed(part2begin, part2end); + for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++) + (*it)->feed(part1begin, part1end); + } + + // adjust FIFO pointers + m_sampleFifo.readCommit(count); + samplesDone += count; + } + + // check if the center frequency has changed (has to be responsive) + if(m_settings.isModifiedCenterFreq()) + m_sampleSource->setCenterFrequency(m_settings.centerFreq()); + // check if decimation has changed (needed to be done here, because to high a sample rate can clog the switch) + if(m_settings.isModifiedDecimation()) { + m_sampleSource->setDecimation(m_settings.decimation()); + m_sampleRate = 4000000 / (1 << m_settings.decimation()); + qDebug("New rate: %d", m_sampleRate); + } +#endif +} + +DSPEngine::State DSPEngine::gotoIdle() +{ + switch(m_state) { + case StNotStarted: + return StNotStarted; + + case StIdle: + case StError: + return StIdle; + + case StRunning: + break; + } + + if(m_sampleSource == NULL) + return StIdle; + + for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++) + (*it)->stop(); + m_sampleSource->stopInput(); + m_deviceDescription.clear(); + m_audioOutput.stop(); + m_sampleRate = 0; + + return StIdle; +} + +DSPEngine::State DSPEngine::gotoRunning() +{ + switch(m_state) { + case StNotStarted: + return StNotStarted; + + case StRunning: + return StRunning; + + case StIdle: + case StError: + break; + } + + if(m_sampleSource == NULL) + return gotoError("No sample source configured"); + + m_iOffset = 0; + m_qOffset = 0; + m_iRange = 1 << 16; + m_qRange = 1 << 16; + + if(!m_sampleSource->startInput(0)) + return gotoError("Could not start sample source"); + m_deviceDescription = m_sampleSource->getDeviceDescription(); + + m_audioOutput.start(0, 44100); + for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++) + (*it)->start(); + m_sampleRate = 0; // make sure, report is sent + generateReport(); + + return StRunning; +} + +DSPEngine::State DSPEngine::gotoError(const QString& errorMessage) +{ + m_errorMessage = errorMessage; + m_deviceDescription.clear(); + m_state = StError; + return StError; +} + +void DSPEngine::handleSetSource(SampleSource* source) +{ + gotoIdle(); + if(m_sampleSource != NULL) + disconnect(m_sampleSource->getSampleFifo(), SIGNAL(dataReady()), this, SLOT(handleData())); + m_sampleSource = source; + if(m_sampleSource != NULL) + connect(m_sampleSource->getSampleFifo(), SIGNAL(dataReady()), this, SLOT(handleData()), Qt::QueuedConnection); + generateReport(); +} + +void DSPEngine::generateReport() +{ + bool needReport = false; + int sampleRate; + quint64 centerFrequency; + + if(m_sampleSource != NULL) { + sampleRate = m_sampleSource->getSampleRate(); + centerFrequency = m_sampleSource->getCenterFrequency(); + } else { + sampleRate = 100000; + centerFrequency = 100000000; + } + + if(sampleRate != m_sampleRate) { + m_sampleRate = sampleRate; + needReport = true; + for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++) { + DSPSignalNotification* signal = DSPSignalNotification::create(m_sampleRate, 0); + signal->submit(&m_messageQueue, *it); + } + } + if(centerFrequency != m_centerFrequency) { + m_centerFrequency = centerFrequency; + needReport = true; + } + + if(needReport) { + Message* rep = DSPEngineReport::create(m_sampleRate, m_centerFrequency); + rep->submit(m_reportQueue); + } +} + +bool DSPEngine::distributeMessage(Message* message) +{ + if(m_sampleSource != NULL) { + if((message->getDestination() == NULL) || (message->getDestination() == m_sampleSource)) { + if(m_sampleSource->handleMessage(message)) { + generateReport(); + return true; + } + } + } + for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++) { + if((message->getDestination() == NULL) || (message->getDestination() == *it)) { + if((*it)->handleMessage(message)) + return true; + } + } + return false; +} + +void DSPEngine::handleData() +{ + if(m_state == StRunning) + work(); +} + +void DSPEngine::handleMessages() +{ + Message* message; + while((message = m_messageQueue.accept()) != NULL) { + qDebug("Message: %s", message->getIdentifier()); + + if(DSPPing::match(message)) { + message->completed(m_state); + } else if(DSPExit::match(message)) { + gotoIdle(); + m_state = StNotStarted; + exit(); + message->completed(m_state); + } else if(DSPAcquisitionStart::match(message)) { + m_state = gotoIdle(); + if(m_state == StIdle) + m_state = gotoRunning(); + message->completed(m_state); + } else if(DSPAcquisitionStop::match(message)) { + m_state = gotoIdle(); + message->completed(m_state); + } else if(DSPGetDeviceDescription::match(message)) { + ((DSPGetDeviceDescription*)message)->setDeviceDescription(m_deviceDescription); + message->completed(); + } else if(DSPGetErrorMessage::match(message)) { + ((DSPGetErrorMessage*)message)->setErrorMessage(m_errorMessage); + message->completed(); + } else if(DSPSetSource::match(message)) { + handleSetSource(((DSPSetSource*)message)->getSampleSource()); + message->completed(); + } else if(DSPAddSink::match(message)) { + SampleSink* sink = ((DSPAddSink*)message)->getSampleSink(); + if(m_state == StRunning) { + DSPSignalNotification* signal = DSPSignalNotification::create(m_sampleRate, 0); + signal->submit(&m_messageQueue, sink); + sink->start(); + } + m_sampleSinks.push_back(sink); + message->completed(); + } else if(DSPRemoveSink::match(message)) { + SampleSink* sink = ((DSPAddSink*)message)->getSampleSink(); + if(m_state == StRunning) + sink->stop(); + m_sampleSinks.remove(sink); + message->completed(); + } else if(DSPAddAudioSource::match(message)) { + m_audioOutput.addFifo(((DSPAddAudioSource*)message)->getAudioFifo()); + message->completed(); + } else if(DSPRemoveAudioSource::match(message)) { + m_audioOutput.removeFifo(((DSPAddAudioSource*)message)->getAudioFifo()); + message->completed(); + } else if(DSPConfigureCorrection::match(message)) { + DSPConfigureCorrection* conf = (DSPConfigureCorrection*)message; + m_iqImbalanceCorrection = conf->getIQImbalanceCorrection(); + if(m_dcOffsetCorrection != conf->getDCOffsetCorrection()) { + m_dcOffsetCorrection = conf->getDCOffsetCorrection(); + m_iOffset = 0; + m_qOffset = 0; + } + if(m_iqImbalanceCorrection != conf->getIQImbalanceCorrection()) { + m_iqImbalanceCorrection = conf->getIQImbalanceCorrection(); + m_iRange = 1 << 16; + m_qRange = 1 << 16; + m_imbalance = 65536; + } + message->completed(); + } else { + if(!distributeMessage(message)) + message->completed(); + } + } +} diff --git a/sdrbase/dsp/fftengine.cpp b/sdrbase/dsp/fftengine.cpp new file mode 100644 index 000000000..fe431b165 --- /dev/null +++ b/sdrbase/dsp/fftengine.cpp @@ -0,0 +1,26 @@ +#include "dsp/fftengine.h" +#ifdef USE_KISSFFT +#include "dsp/kissengine.h" +#endif +#ifdef USE_FFTW +#include "dsp/fftwengine.h" +#endif // USE_FFTW + +FFTEngine::~FFTEngine() +{ +} + +FFTEngine* FFTEngine::create() +{ +#ifdef USE_FFTW + qDebug("FFT: using FFTW engine"); + return new FFTWEngine; +#endif // USE_FFTW +#ifdef USE_KISSFFT + qDebug("FFT: using KissFFT engine"); + return new KissEngine; +#endif // USE_KISSFFT + + qCritical("FFT: no engine built"); + return NULL; +} diff --git a/sdrbase/dsp/fftwengine.cpp b/sdrbase/dsp/fftwengine.cpp new file mode 100644 index 000000000..76b189ead --- /dev/null +++ b/sdrbase/dsp/fftwengine.cpp @@ -0,0 +1,69 @@ +#include +#include "dsp/fftwengine.h" + +FFTWEngine::FFTWEngine() : + m_plans(), + m_currentPlan(NULL) +{ +} + +FFTWEngine::~FFTWEngine() +{ + freeAll(); +} + +void FFTWEngine::configure(int n, bool inverse) +{ + for(Plans::const_iterator it = m_plans.begin(); it != m_plans.end(); ++it) { + if(((*it)->n == n) && ((*it)->inverse == inverse)) { + m_currentPlan = *it; + return; + } + } + + m_currentPlan = new Plan; + m_currentPlan->n = n; + m_currentPlan->inverse = inverse; + m_currentPlan->in = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * n); + m_currentPlan->out = (fftwf_complex*)fftwf_malloc(sizeof(fftwf_complex) * n); + QTime t; + t.start(); + m_globalPlanMutex.lock(); + m_currentPlan->plan = fftwf_plan_dft_1d(n, m_currentPlan->in, m_currentPlan->out, inverse ? FFTW_BACKWARD : FFTW_FORWARD, FFTW_PATIENT); + m_globalPlanMutex.unlock(); + qDebug("FFT: creating FFTW plan (n=%d,%s) took %dms", n, inverse ? "inverse" : "forward", t.elapsed()); + m_plans.push_back(m_currentPlan); +} + +void FFTWEngine::transform() +{ + if(m_currentPlan != NULL) + fftwf_execute(m_currentPlan->plan); +} + +Complex* FFTWEngine::in() +{ + if(m_currentPlan != NULL) + return reinterpret_cast(m_currentPlan->in); + else return NULL; +} + +Complex* FFTWEngine::out() +{ + if(m_currentPlan != NULL) + return reinterpret_cast(m_currentPlan->out); + else return NULL; +} + +QMutex FFTWEngine::m_globalPlanMutex; + +void FFTWEngine::freeAll() +{ + for(Plans::iterator it = m_plans.begin(); it != m_plans.end(); ++it) { + fftwf_destroy_plan((*it)->plan); + fftwf_free((*it)->in); + fftwf_free((*it)->out); + delete *it; + } + m_plans.clear(); +} diff --git a/sdrbase/dsp/fftwindow.cpp b/sdrbase/dsp/fftwindow.cpp new file mode 100644 index 000000000..b363b21c9 --- /dev/null +++ b/sdrbase/dsp/fftwindow.cpp @@ -0,0 +1,73 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "dsp/fftwindow.h" + +void FFTWindow::create(Function function, int n) +{ + Real (*wFunc)(Real n, Real i); + + m_window.clear(); + + switch(function) { + case Flattop: + wFunc = flatTop; + break; + + case Bartlett: + wFunc = bartlett; + break; + + case BlackmanHarris: + wFunc = blackmanHarris; + break; + + case Hamming: + wFunc = hamming; + break; + + case Hanning: + wFunc = hanning; + break; + + case Rectangle: + default: + wFunc = rectangle; + break; + } + + for(int i = 0; i < n; i++) + m_window.push_back(wFunc(n, i)); +} + +void FFTWindow::apply(const std::vector& in, std::vector* out) +{ + for(size_t i = 0; i < m_window.size(); i++) + (*out)[i] = in[i] * m_window[i]; +} + +void FFTWindow::apply(const std::vector& in, std::vector* out) +{ + for(size_t i = 0; i < m_window.size(); i++) + (*out)[i] = in[i] * m_window[i]; +} + +void FFTWindow::apply(const Complex* in, Complex* out) +{ + for(size_t i = 0; i < m_window.size(); i++) + out[i] = in[i] * m_window[i]; +} diff --git a/sdrbase/dsp/interpolator.cpp b/sdrbase/dsp/interpolator.cpp new file mode 100644 index 000000000..781864bee --- /dev/null +++ b/sdrbase/dsp/interpolator.cpp @@ -0,0 +1,120 @@ +#define _USE_MATH_DEFINES +#include +#include +#include "dsp/interpolator.h" + +static std::vector createPolyphaseLowPass( + int phaseSteps, + double gain, + double sampleRateHz, + double cutoffFreqHz, + double transitionWidthHz, + double oobAttenuationdB) +{ + int ntaps = (int)(oobAttenuationdB * sampleRateHz / (22.0 * transitionWidthHz)); + if((ntaps % 2) != 0) + ntaps++; + ntaps *= phaseSteps; + + std::vector taps(ntaps); + std::vector window(ntaps); + + for(int n = 0; n < ntaps; n++) + window[n] = 0.54 - 0.46 * cos ((2 * M_PI * n) / (ntaps - 1)); + + int M = (ntaps - 1) / 2; + double fwT0 = 2 * M_PI * cutoffFreqHz / sampleRateHz; + for(int n = -M; n <= M; n++) { + if(n == 0) taps[n + M] = fwT0 / M_PI * window[n + M]; + else taps[n + M] = sin (n * fwT0) / (n * M_PI) * window[n + M]; + } + + double max = taps[0 + M]; + for(int n = 1; n <= M; n++) + max += 2.0 * taps[n + M]; + + gain /= max; + + for(int i = 0; i < ntaps; i++) + taps[i] *= gain; + + return taps; +} + +Interpolator::Interpolator() : + m_taps(NULL), + m_alignedTaps(NULL) +{ +} + +Interpolator::~Interpolator() +{ + free(); +} + +void Interpolator::create(int phaseSteps, double sampleRate, double cutoff) +{ + free(); + + std::vector taps = createPolyphaseLowPass( + phaseSteps, // number of polyphases + 1.0, // gain + phaseSteps * sampleRate, // sampling frequency + cutoff, // hz beginning of transition band + sampleRate / 5.0, // hz width of transition band + 20.0); // out of band attenuation + + // init state + m_ptr = 0; + m_nTaps = taps.size() / phaseSteps; + m_phaseSteps = phaseSteps; + m_samples.resize(m_nTaps + 2); + for(int i = 0; i < m_nTaps + 2; i++) + m_samples[i] = 0; + + // reorder into polyphase + std::vector polyphase(taps.size()); + for(int phase = 0; phase < phaseSteps; phase++) { + for(int i = 0; i < m_nTaps; i++) + polyphase[phase * m_nTaps + i] = taps[i * phaseSteps + phase]; + } + + // normalize phase filters + for(int phase = 0; phase < phaseSteps; phase++) { + Real sum = 0; + for(int i = phase * m_nTaps; i < phase * m_nTaps + m_nTaps; i++) + sum += polyphase[i]; + for(int i = phase * m_nTaps; i < phase * m_nTaps + m_nTaps; i++) + polyphase[i] /= sum; + } + + // move taps around to match sse storage requirements + m_taps = new float[2 * taps.size() + 8]; + for(int i = 0; i < 2 * taps.size() + 8; ++i) + m_taps[i] = 0; + m_alignedTaps = (float*)((((quint64)m_taps) + 15) & ~15); + for(int i = 0; i < taps.size(); ++i) { + m_alignedTaps[2 * i + 0] = polyphase[i]; + m_alignedTaps[2 * i + 1] = polyphase[i]; + } + m_taps2 = new float[2 * taps.size() + 8]; + for(int i = 0; i < 2 * taps.size() + 8; ++i) + m_taps2[i] = 0; + m_alignedTaps2 = (float*)((((quint64)m_taps2) + 15) & ~15); + for(int i = 1; i < taps.size(); ++i) { + m_alignedTaps2[2 * (i - 1) + 0] = polyphase[i]; + m_alignedTaps2[2 * (i - 1) + 1] = polyphase[i]; + } +} + +void Interpolator::free() +{ + if(m_taps != NULL) { + delete[] m_taps; + m_taps = NULL; + m_alignedTaps = NULL; + delete[] m_taps2; + m_taps2 = NULL; + m_alignedTaps2 = NULL; + } +} diff --git a/sdrbase/dsp/inthalfbandfilter.cpp b/sdrbase/dsp/inthalfbandfilter.cpp new file mode 100644 index 000000000..db41dc996 --- /dev/null +++ b/sdrbase/dsp/inthalfbandfilter.cpp @@ -0,0 +1,11 @@ +#include "dsp/inthalfbandfilter.h" + +IntHalfbandFilter::IntHalfbandFilter() +{ + for(int i = 0; i < HB_FILTERORDER + 1; i++) { + m_samples[i][0] = 0; + m_samples[i][1] = 0; + } + m_ptr = 0; + m_state = 0; +} diff --git a/sdrbase/dsp/kissengine.cpp b/sdrbase/dsp/kissengine.cpp new file mode 100644 index 000000000..5649128ed --- /dev/null +++ b/sdrbase/dsp/kissengine.cpp @@ -0,0 +1,25 @@ +#include "dsp/kissengine.h" + +void KissEngine::configure(int n, bool inverse) +{ + m_fft.configure(n, inverse); + if(n > m_in.size()) + m_in.resize(n); + if(n > m_out.size()) + m_out.resize(n); +} + +void KissEngine::transform() +{ + m_fft.transform(&m_in[0], &m_out[0]); +} + +Complex* KissEngine::in() +{ + return &m_in[0]; +} + +Complex* KissEngine::out() +{ + return &m_out[0]; +} diff --git a/sdrbase/dsp/lowpass.cpp b/sdrbase/dsp/lowpass.cpp new file mode 100644 index 000000000..1b8d9f263 --- /dev/null +++ b/sdrbase/dsp/lowpass.cpp @@ -0,0 +1,6 @@ +#include +#include +#define _USE_MATH_DEFINES +#include +#include +#include "dsp/lowpass.h" diff --git a/sdrbase/dsp/movingaverage.cpp b/sdrbase/dsp/movingaverage.cpp new file mode 100644 index 000000000..dcf8d5599 --- /dev/null +++ b/sdrbase/dsp/movingaverage.cpp @@ -0,0 +1 @@ +#include "dsp/movingaverage.h" diff --git a/sdrbase/dsp/nco.cpp b/sdrbase/dsp/nco.cpp new file mode 100644 index 000000000..1143cf89f --- /dev/null +++ b/sdrbase/dsp/nco.cpp @@ -0,0 +1,70 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#define _USE_MATH_DEFINES +#include +#include "dsp/nco.h" + +Real NCO::m_table[NCO::TableSize]; +bool NCO::m_tableInitialized = false; + +void NCO::initTable() +{ + if(m_tableInitialized) + return; + + for(int i = 0; i < TableSize; i++) + m_table[i] = cos((2.0 * M_PI * i) / TableSize); + + m_tableInitialized = true; +} + +NCO::NCO() +{ + initTable(); + m_phase = 0; +} + +void NCO::setFreq(Real freq, Real sampleRate) +{ + m_phaseIncrement = (freq * TableSize) / sampleRate; + qDebug("NCO phase inc %d", m_phaseIncrement); +} + +float NCO::next() +{ + m_phase += m_phaseIncrement; + while(m_phase >= TableSize) + m_phase -= TableSize; + while(m_phase < 0) + m_phase += TableSize; + + return m_table[m_phase]; +} + +Complex NCO::nextIQ() +{ + m_phase += m_phaseIncrement; + while(m_phase >= TableSize) + m_phase -= TableSize; + while(m_phase < 0) + m_phase += TableSize; + + return Complex(m_table[m_phase], -m_table[(m_phase + TableSize / 4) % TableSize]); +} diff --git a/sdrbase/dsp/pidcontroller.cpp b/sdrbase/dsp/pidcontroller.cpp new file mode 100644 index 000000000..8b015f6b7 --- /dev/null +++ b/sdrbase/dsp/pidcontroller.cpp @@ -0,0 +1,17 @@ +#include "pidcontroller.h" + +PIDController::PIDController() : + m_p(0.0), + m_i(0.0), + m_d(0.0), + m_int(0.0), + m_diff(0.0) +{ +} + +void PIDController::setup(Real p, Real i, Real d) +{ + m_p = p; + m_i = i; + m_d = d; +} diff --git a/sdrbase/dsp/pidcontroller.h b/sdrbase/dsp/pidcontroller.h new file mode 100644 index 000000000..7b96793fa --- /dev/null +++ b/sdrbase/dsp/pidcontroller.h @@ -0,0 +1,28 @@ +#ifndef INCLUDE_PIDCONTROLLER_H +#define INCLUDE_PIDCONTROLLER_H + +#include "dsp/dsptypes.h" + +class PIDController { +private: + Real m_p; + Real m_i; + Real m_d; + Real m_int; + Real m_diff; + +public: + PIDController(); + + void setup(Real p, Real i, Real d); + + Real feed(Real v) + { + m_int += v * m_i; + Real d = m_d * (m_diff - v); + m_diff = v; + return (v * m_p) + m_int + d; + } +}; + +#endif // INCLUDE_PIDCONTROLLER_H diff --git a/sdrbase/dsp/samplefifo.cpp b/sdrbase/dsp/samplefifo.cpp new file mode 100644 index 000000000..caa49693d --- /dev/null +++ b/sdrbase/dsp/samplefifo.cpp @@ -0,0 +1,231 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "dsp/samplefifo.h" + +#define MIN(x, y) (((x) < (y)) ? (x) : (y)) + +void SampleFifo::create(uint s) +{ + m_size = 0; + m_fill = 0; + m_head = 0; + m_tail = 0; + + m_data.resize(s); + m_size = m_data.size(); + + if(m_size != s) + qCritical("SampleFifo: out of memory"); +} + +SampleFifo::SampleFifo(QObject* parent) : + QObject(parent), + m_data() +{ + m_suppressed = -1; + m_size = 0; + m_fill = 0; + m_head = 0; + m_tail = 0; +} + +SampleFifo::SampleFifo(int size, QObject* parent) : + QObject(parent), + m_data() +{ + m_suppressed = -1; + + create(size); +} + +SampleFifo::~SampleFifo() +{ + QMutexLocker mutexLocker(&m_mutex); + + m_size = 0; +} + +bool SampleFifo::setSize(int size) +{ + create(size); + + return m_data.size() == (uint)size; +} + +uint SampleFifo::write(const quint8* data, uint count) +{ + QMutexLocker mutexLocker(&m_mutex); + uint total; + uint remaining; + uint len; + const Sample* begin = (const Sample*)data; + count /= 4; + + total = MIN(count, m_size - m_fill); + if(total < count) { + if(m_suppressed < 0) { + m_suppressed = 0; + m_msgRateTimer.start(); + qCritical("SampleFifo: overflow - dropping %u samples", count - total); + } else { + if(m_msgRateTimer.elapsed() > 2500) { + qCritical("SampleFifo: %u messages dropped", m_suppressed); + qCritical("SampleFifo: overflow - dropping %u samples", count - total); + m_suppressed = -1; + } else { + m_suppressed++; + } + } + } + + remaining = total; + while(remaining > 0) { + len = MIN(remaining, m_size - m_tail); + std::copy(begin, begin + len, m_data.begin() + m_tail); + m_tail += len; + m_tail %= m_size; + m_fill += len; + begin += len; + remaining -= len; + } + + if(m_fill > 0) + emit dataReady(); + + return total; +} + +uint SampleFifo::write(SampleVector::const_iterator begin, SampleVector::const_iterator end) +{ + QMutexLocker mutexLocker(&m_mutex); + uint count = end - begin; + uint total; + uint remaining; + uint len; + + total = MIN(count, m_size - m_fill); + if(total < count) { + if(m_suppressed < 0) { + m_suppressed = 0; + m_msgRateTimer.start(); + qCritical("SampleFifo: overflow - dropping %u samples", count - total); + } else { + if(m_msgRateTimer.elapsed() > 2500) { + qCritical("SampleFifo: %u messages dropped", m_suppressed); + qCritical("SampleFifo: overflow - dropping %u samples", count - total); + m_suppressed = -1; + } else { + m_suppressed++; + } + } + } + + remaining = total; + while(remaining > 0) { + len = MIN(remaining, m_size - m_tail); + std::copy(begin, begin + len, m_data.begin() + m_tail); + m_tail += len; + m_tail %= m_size; + m_fill += len; + begin += len; + remaining -= len; + } + + if(m_fill > 0) + emit dataReady(); + + return total; +} + +uint SampleFifo::read(SampleVector::iterator begin, SampleVector::iterator end) +{ + QMutexLocker mutexLocker(&m_mutex); + uint count = end - begin; + uint total; + uint remaining; + uint len; + + total = MIN(count, m_fill); + if(total < count) + qCritical("SampleFifo: underflow - missing %u samples", count - total); + + remaining = total; + while(remaining > 0) { + len = MIN(remaining, m_size - m_head); + std::copy(m_data.begin() + m_head, m_data.begin() + m_head + len, begin); + m_head += len; + m_head %= m_size; + m_fill -= len; + begin += len; + remaining -= len; + } + + return total; +} + +uint SampleFifo::readBegin(uint count, + SampleVector::iterator* part1Begin, SampleVector::iterator* part1End, + SampleVector::iterator* part2Begin, SampleVector::iterator* part2End) +{ + QMutexLocker mutexLocker(&m_mutex); + uint total; + uint remaining; + uint len; + uint head = m_head; + + total = MIN(count, m_fill); + if(total < count) + qCritical("SampleFifo: underflow - missing %u samples", count - total); + + remaining = total; + if(remaining > 0) { + len = MIN(remaining, m_size - head); + *part1Begin = m_data.begin() + head; + *part1End = m_data.begin() + head + len; + head += len; + head %= m_size; + remaining -= len; + } else { + *part1Begin = m_data.end(); + *part1End = m_data.end(); + } + if(remaining > 0) { + len = MIN(remaining, m_size - head); + *part2Begin = m_data.begin() + head; + *part2End = m_data.begin() + head + len; + } else { + *part2Begin = m_data.end(); + *part2End = m_data.end(); + } + + return total; +} + +uint SampleFifo::readCommit(uint count) +{ + QMutexLocker mutexLocker(&m_mutex); + + if(count > m_fill) { + qCritical("SampleFifo: cannot commit more than available samples"); + count = m_fill; + } + m_head = (m_head + count) % m_size; + m_fill -= count; + + return count; +} diff --git a/sdrbase/dsp/samplesink.cpp b/sdrbase/dsp/samplesink.cpp new file mode 100644 index 000000000..5ff0dd144 --- /dev/null +++ b/sdrbase/dsp/samplesink.cpp @@ -0,0 +1,66 @@ +#include "dsp/samplesink.h" + +SampleSink::SampleSink() +{ +} + +SampleSink::~SampleSink() +{ +} + +#if 0 +#include "samplesink.h" + +SampleSink::SampleSink() : + m_sinkBuffer(), + m_sinkBufferFill(0) +{ +} + +void SampleSink::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end) +{ + size_t wus = workUnitSize(); + + // make sure our buffer is big enough for at least one work unit + if(m_sinkBuffer.size() < wus) + m_sinkBuffer.resize(wus); + + while(begin < end) { + // if the buffer contains something, keep filling it until it contains one complete work unit + if((m_sinkBufferFill > 0) && (m_sinkBufferFill < wus)) { + // check number if missing samples, but don't copy more than we have + size_t len = wus - m_sinkBufferFill; + if(len > (size_t)(end - begin)) + len = end - begin; + // copy + std::copy(begin, begin + len, m_sinkBuffer.begin() + m_sinkBufferFill); + // adjust pointers + m_sinkBufferFill += len; + begin += len; + } + + // if one complete work unit is in the buffer, feed it to the worker + if(m_sinkBufferFill >= wus) { + size_t done = 0; + while(m_sinkBufferFill - done >= wus) + done += work(m_sinkBuffer.begin() + done, m_sinkBuffer.begin() + done + wus); + // now copy the remaining data to the front of the buffer (should be zero) + if(m_sinkBufferFill - done > 0) { + qDebug("error in SampleSink buffer management"); + std::copy(m_sinkBuffer.begin() + done, m_sinkBuffer.begin() + m_sinkBufferFill, m_sinkBuffer.begin()); + } + m_sinkBufferFill -= done; + } + + // if no remainder from last run is buffered and we have at least one work unit left, feed the data to the worker + if(m_sinkBufferFill == 0) { + while((size_t)(end - begin) > wus) + begin += work(begin, begin + wus); + // copy any remaining data to the buffer + std::copy(begin, end, m_sinkBuffer.begin()); + m_sinkBufferFill = end - begin; + begin += m_sinkBufferFill; + } + } +} +#endif diff --git a/sdrbase/dsp/samplesource/samplesource.cpp b/sdrbase/dsp/samplesource/samplesource.cpp new file mode 100644 index 000000000..dda41d060 --- /dev/null +++ b/sdrbase/dsp/samplesource/samplesource.cpp @@ -0,0 +1,64 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "dsp/samplesource/samplesource.h" +#include "util/simpleserializer.h" + +SampleSource::GeneralSettings::GeneralSettings() : + m_centerFrequency(100000000) +{ +} + +void SampleSource::GeneralSettings::resetToDefaults() +{ + m_centerFrequency = 100000000; +} + +QByteArray SampleSource::GeneralSettings::serialize() const +{ + SimpleSerializer s(1); + s.writeU64(1, m_centerFrequency); + return s.final(); +} + +bool SampleSource::GeneralSettings::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { + d.readU64(1, &m_centerFrequency, 100000000); + return true; + } else { + resetToDefaults(); + return false; + } +} + +SampleSource::SampleSource(MessageQueue* guiMessageQueue) : + m_sampleFifo(), + m_guiMessageQueue(guiMessageQueue) +{ +} + +SampleSource::~SampleSource() +{ +} diff --git a/sdrbase/dsp/scopevis.cpp b/sdrbase/dsp/scopevis.cpp new file mode 100644 index 000000000..0dc8e23ee --- /dev/null +++ b/sdrbase/dsp/scopevis.cpp @@ -0,0 +1,141 @@ +#include "dsp/scopevis.h" +#include "gui/glscope.h" +#include "dsp/dspcommands.h" +#include "util/messagequeue.h" + +ScopeVis::ScopeVis(GLScope* glScope) : + m_glScope(glScope), + m_trace(100000), + m_fill(0), + m_triggerState(Untriggered), + m_triggerChannel(TriggerFreeRun), + m_triggerLevelHigh(0.01 * 32768), + m_triggerLevelLow(0.01 * 32768 - 1024), + m_sampleRate(0) +{ +} + +void ScopeVis::configure(MessageQueue* msgQueue, TriggerChannel triggerChannel, Real triggerLevelHigh, Real triggerLevelLow) +{ + Message* cmd = DSPConfigureScopeVis::create(triggerChannel, triggerLevelHigh, triggerLevelLow); + cmd->submit(msgQueue, this); +} + +void ScopeVis::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst) +{ + while(begin < end) { + if(m_triggerChannel == TriggerChannelI) { + if(m_triggerState == Untriggered) { + while(begin < end) { + if(begin->real() >= m_triggerLevelHigh) { + m_triggerState = Triggered; + break; + } + ++begin; + } + } + if(m_triggerState == Triggered) { + int count = end - begin; + if(count > (int)(m_trace.size() - m_fill)) + count = m_trace.size() - m_fill; + std::vector::iterator it = m_trace.begin() + m_fill; + for(int i = 0; i < count; ++i) { + *it++ = Complex(begin->real() / 32768.0, begin->imag() / 32768.0); + ++begin; + } + m_fill += count; + if(m_fill >= m_trace.size()) { + m_glScope->newTrace(m_trace, m_sampleRate); + m_fill = 0; + m_triggerState = WaitForReset; + } + } + if(m_triggerState == WaitForReset) { + while(begin < end) { + if(begin->real() < m_triggerLevelLow) { + m_triggerState = Untriggered; + break; + } + ++begin; + } + } + } else if(m_triggerChannel == TriggerChannelQ) { + if(m_triggerState == Untriggered) { + while(begin < end) { + if(begin->imag() >= m_triggerLevelHigh) { + m_triggerState = Triggered; + break; + } + ++begin; + } + } + if(m_triggerState == Triggered) { + int count = end - begin; + if(count > (int)(m_trace.size() - m_fill)) + count = m_trace.size() - m_fill; + std::vector::iterator it = m_trace.begin() + m_fill; + for(int i = 0; i < count; ++i) { + *it++ = Complex(begin->real() / 32768.0, begin->imag() / 32768.0); + ++begin; + } + m_fill += count; + if(m_fill >= m_trace.size()) { + m_glScope->newTrace(m_trace, m_sampleRate); + m_fill = 0; + m_triggerState = WaitForReset; + } + } + if(m_triggerState == WaitForReset) { + while(begin < end) { + if(begin->imag() < m_triggerLevelLow) { + m_triggerState = Untriggered; + break; + } + ++begin; + } + } + } else { + int count = end - begin; + if(count > (int)(m_trace.size() - m_fill)) + count = m_trace.size() - m_fill; + std::vector::iterator it = m_trace.begin() + m_fill; + for(int i = 0; i < count; ++i) { + *it++ = Complex(begin->real() / 32768.0, begin->imag() / 32768.0); + ++begin; + } + m_fill += count; + if(m_fill >= m_trace.size()) { + m_glScope->newTrace(m_trace, m_sampleRate); + m_fill = 0; + } + } + } +} + +void ScopeVis::start() +{ +} + +void ScopeVis::stop() +{ +} + +bool ScopeVis::handleMessage(Message* message) +{ + if(DSPSignalNotification::match(message)) { + DSPSignalNotification* signal = (DSPSignalNotification*)message; + m_sampleRate = signal->getSampleRate(); + message->completed(); + return true; + } else if(DSPConfigureScopeVis::match(message)) { + DSPConfigureScopeVis* conf = (DSPConfigureScopeVis*)message; + m_triggerState = Untriggered; + m_triggerChannel = (TriggerChannel)conf->getTriggerChannel(); + m_triggerLevelHigh = conf->getTriggerLevelHigh() * 32767; + m_triggerLevelLow = conf->getTriggerLevelLow() * 32767; + message->completed(); + return true; + } else { + return false; + } +} diff --git a/sdrbase/dsp/spectrumvis.cpp b/sdrbase/dsp/spectrumvis.cpp new file mode 100644 index 000000000..01c7dbe31 --- /dev/null +++ b/sdrbase/dsp/spectrumvis.cpp @@ -0,0 +1,125 @@ +#include "dsp/spectrumvis.h" +#include "gui/glspectrum.h" +#include "dsp/dspcommands.h" +#include "util/messagequeue.h" + +#define MAX_FFT_SIZE 4096 + +#ifdef _WIN32 +double log2f(double n) +{ + return log(n) / log(2.0); +} +#endif + +SpectrumVis::SpectrumVis(GLSpectrum* glSpectrum) : + SampleSink(), + m_fft(FFTEngine::create()), + m_fftBuffer(MAX_FFT_SIZE), + m_logPowerSpectrum(MAX_FFT_SIZE), + m_fftBufferFill(0), + m_glSpectrum(glSpectrum) +{ + handleConfigure(1024, 10, FFTWindow::BlackmanHarris); +} + +SpectrumVis::~SpectrumVis() +{ + delete m_fft; +} + +void SpectrumVis::configure(MessageQueue* msgQueue, int fftSize, int overlapPercent, FFTWindow::Function window) +{ + Message* cmd = DSPConfigureSpectrumVis::create(fftSize, overlapPercent, window); + cmd->submit(msgQueue, this); +} + +void SpectrumVis::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst) +{ + // if no visualisation is set, send the samples to /dev/null + if(m_glSpectrum == NULL) + return; + + while(begin < end) { + size_t todo = end - begin; + size_t samplesNeeded = m_refillSize - m_fftBufferFill; + + if(todo >= samplesNeeded) { + // fill up the buffer + std::vector::iterator it = m_fftBuffer.begin() + m_fftBufferFill; + for(size_t i = 0; i < samplesNeeded; ++i, ++begin) + *it++ = Complex(begin->real() / 32768.0, begin->imag() / 32768.0); + + // apply fft window (and copy from m_fftBuffer to m_fftIn) + m_window.apply(&m_fftBuffer[0], m_fft->in()); + + // calculate FFT + m_fft->transform(); + + // extract power spectrum and reorder buckets + Real ofs = 20.0f * log10f(1.0f / m_fftSize); + Real mult = (10.0f / log2f(10.0f)); + const Complex* fftOut = m_fft->out(); + for(size_t i = 0; i < m_fftSize; i++) { + Complex c = fftOut[((i + (m_fftSize >> 1)) & (m_fftSize - 1))]; + Real v = c.real() * c.real() + c.imag() * c.imag(); + v = mult * log2f(v) + ofs; + m_logPowerSpectrum[i] = v; + } + + // send new data to visualisation + m_glSpectrum->newSpectrum(m_logPowerSpectrum, m_fftSize); + + // advance buffer respecting the fft overlap factor + std::copy(m_fftBuffer.begin() + m_refillSize, m_fftBuffer.end(), m_fftBuffer.begin()); + + // start over + m_fftBufferFill = m_overlapSize; + } else { + // not enough samples for FFT - just fill in new data and return + for(std::vector::iterator it = m_fftBuffer.begin() + m_fftBufferFill; begin < end; ++begin) + *it++ = Complex(begin->real() / 32768.0, begin->imag() / 32768.0); + m_fftBufferFill += todo; + } + } +} + +void SpectrumVis::start() +{ +} + +void SpectrumVis::stop() +{ +} + +bool SpectrumVis::handleMessage(Message* message) +{ + if(DSPConfigureSpectrumVis::match(message)) { + DSPConfigureSpectrumVis* conf = (DSPConfigureSpectrumVis*)message; + handleConfigure(conf->getFFTSize(), conf->getOverlapPercent(), conf->getWindow()); + message->completed(); + return true; + } else { + return false; + } +} + +void SpectrumVis::handleConfigure(int fftSize, int overlapPercent, FFTWindow::Function window) +{ + if(fftSize > MAX_FFT_SIZE) + fftSize = MAX_FFT_SIZE; + else if(fftSize < 64) + fftSize = 64; + if(overlapPercent > 100) + m_overlapPercent = 100; + else if(overlapPercent < 0) + m_overlapPercent = 0; + + m_fftSize = fftSize; + m_overlapPercent = overlapPercent; + m_fft->configure(m_fftSize, false); + m_window.create(window, m_fftSize); + m_overlapSize = (m_fftSize * m_overlapPercent) / 100; + m_refillSize = m_fftSize - m_overlapSize; + m_fftBufferFill = m_overlapSize; +} diff --git a/sdrbase/dsp/threadedsamplesink.cpp b/sdrbase/dsp/threadedsamplesink.cpp new file mode 100644 index 000000000..ad157b9ff --- /dev/null +++ b/sdrbase/dsp/threadedsamplesink.cpp @@ -0,0 +1,111 @@ +#include +#include "dsp/threadedsamplesink.h" +#include "util/message.h" + +ThreadedSampleSink::ThreadedSampleSink(SampleSink* sampleSink) : + m_thread(new QThread), + m_sampleSink(sampleSink) +{ + moveToThread(m_thread); + connect(m_thread, SIGNAL(started()), this, SLOT(threadStarted())); + connect(m_thread, SIGNAL(finished()), this, SLOT(threadFinished())); + + m_messageQueue.moveToThread(m_thread); + connect(&m_messageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleMessages())); + + m_sampleFifo.moveToThread(m_thread); + connect(&m_sampleFifo, SIGNAL(dataReady()), this, SLOT(handleData())); + m_sampleFifo.setSize(262144); + + sampleSink->moveToThread(m_thread); +} + +ThreadedSampleSink::~ThreadedSampleSink() +{ + m_thread->exit(); + m_thread->wait(); + delete m_thread; +} + +void ThreadedSampleSink::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst) +{ + Q_UNUSED(firstOfBurst); + m_sampleFifo.write(begin, end); +} + +void ThreadedSampleSink::start() +{ + m_thread->start(); +} + +void ThreadedSampleSink::stop() +{ + m_thread->exit(); + m_thread->wait(); + m_sampleFifo.readCommit(m_sampleFifo.fill()); +} + +bool ThreadedSampleSink::handleMessage(Message* cmd) +{ + // called from other thread + m_messageQueue.submit(cmd); + return true; +} + +void ThreadedSampleSink::handleData() +{ + bool firstOfBurst = true; + + while((m_sampleFifo.fill() > 0) && (m_messageQueue.countPending() == 0)) { + SampleVector::iterator part1begin; + SampleVector::iterator part1end; + SampleVector::iterator part2begin; + SampleVector::iterator part2end; + + size_t count = m_sampleFifo.readBegin(m_sampleFifo.fill(), &part1begin, &part1end, &part2begin, &part2end); + + // first part of FIFO data + if(part1begin != part1end) { + // handle data + if(m_sampleSink != NULL) + m_sampleSink->feed(part1begin, part1end, firstOfBurst); + firstOfBurst = false; + } + // second part of FIFO data (used when block wraps around) + if(part2begin != part2end) { + // handle data + if(m_sampleSink != NULL) + m_sampleSink->feed(part1begin, part1end, firstOfBurst); + firstOfBurst = false; + } + + // adjust FIFO pointers + m_sampleFifo.readCommit(count); + } +} + +void ThreadedSampleSink::handleMessages() +{ + Message* message; + while((message = m_messageQueue.accept()) != NULL) { + qDebug("CMD: %s", message->getIdentifier()); + if(m_sampleSink != NULL) { + if(!m_sampleSink->handleMessage(message)) + message->completed(); + } else { + message->completed(); + } + } +} + +void ThreadedSampleSink::threadStarted() +{ + if(m_sampleSink != NULL) + m_sampleSink->start(); +} + +void ThreadedSampleSink::threadFinished() +{ + if(m_sampleSink != NULL) + m_sampleSink->stop(); +} diff --git a/sdrbase/gui/aboutdialog.cpp b/sdrbase/gui/aboutdialog.cpp new file mode 100644 index 000000000..1c6f87bbd --- /dev/null +++ b/sdrbase/gui/aboutdialog.cpp @@ -0,0 +1,14 @@ +#include "gui/aboutdialog.h" +#include "ui_aboutdialog.h" + +AboutDialog::AboutDialog(QWidget* parent) : + QDialog(parent), + ui(new Ui::AboutDialog) +{ + ui->setupUi(this); +} + +AboutDialog::~AboutDialog() +{ + delete ui; +} diff --git a/sdrbase/gui/aboutdialog.ui b/sdrbase/gui/aboutdialog.ui new file mode 100644 index 000000000..0e0c18208 --- /dev/null +++ b/sdrbase/gui/aboutdialog.ui @@ -0,0 +1,161 @@ + + + AboutDialog + + + + 0 + 0 + 484 + 503 + + + + About SDRangelove + + + + QLayout::SetFixedSize + + + + + 0 + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + 0 + 0 + + + + QFrame::Panel + + + QFrame::Sunken + + + + + + :/logo.png + + + Qt::AlignCenter + + + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + + <p>Copyright (C) 2013 maintech GmbH, Otto-Hahn-Str. 15, 97204 Höchberg, Germany<br> +Written by Christian Daniel.</p> +<p>Many thanks to the osmocom developer team - especially horizon, Hoernchen &amp; tnt.</p> +<p>SDRangelove itself is licensed as "GPL2+" with the added exception, that plugins using only header files from the "include"-subdirectory and not from the "include-gpl"-subdirectory do not count as derived works.</p> +<p>The following rules apply to the SDRangelove main application and libsdrbase:<br> +This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. +This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +You should have received a copy of the GNU General Public License along with this program. If not, see <a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>.</p> +<p>For the license of installed plugins, look into the plugin list.</p> + + + true + + + true + + + + + + + Qt::Vertical + + + + 0 + 0 + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Ok + + + + + + + + + + + buttonBox + accepted() + AboutDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + AboutDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/sdrbase/gui/addpresetdialog.cpp b/sdrbase/gui/addpresetdialog.cpp new file mode 100644 index 000000000..c4d037bed --- /dev/null +++ b/sdrbase/gui/addpresetdialog.cpp @@ -0,0 +1,26 @@ +#include "gui/addpresetdialog.h" +#include "ui_addpresetdialog.h" + +AddPresetDialog::AddPresetDialog(const QStringList& groups, const QString& group, QWidget* parent) : + QDialog(parent), + ui(new Ui::AddPresetDialog) +{ + ui->setupUi(this); + ui->group->addItems(groups); + ui->group->lineEdit()->setText(group); +} + +AddPresetDialog::~AddPresetDialog() +{ + delete ui; +} + +QString AddPresetDialog::group() const +{ + return ui->group->lineEdit()->text(); +} + +QString AddPresetDialog::description() const +{ + return ui->description->text(); +} diff --git a/sdrbase/gui/addpresetdialog.ui b/sdrbase/gui/addpresetdialog.ui new file mode 100644 index 000000000..cbd6b5f5c --- /dev/null +++ b/sdrbase/gui/addpresetdialog.ui @@ -0,0 +1,121 @@ + + + AddPresetDialog + + + + 0 + 0 + 324 + 204 + + + + Dialog + + + + + + Preset Description + + + + + + &Group + + + group + + + + + + + true + + + + + + + &Description + + + description + + + + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + description + buttonBox + group + + + + + buttonBox + accepted() + AddPresetDialog + accept() + + + 257 + 194 + + + 157 + 203 + + + + + buttonBox + rejected() + AddPresetDialog + reject() + + + 314 + 194 + + + 286 + 203 + + + + + diff --git a/sdrbase/gui/basicchannelsettingswidget.cpp b/sdrbase/gui/basicchannelsettingswidget.cpp new file mode 100644 index 000000000..77f607e8f --- /dev/null +++ b/sdrbase/gui/basicchannelsettingswidget.cpp @@ -0,0 +1,77 @@ +#include +#include +#include "gui/basicchannelsettingswidget.h" +#include "dsp/channelmarker.h" +#include "ui_basicchannelsettingswidget.h" + +BasicChannelSettingsWidget::BasicChannelSettingsWidget(ChannelMarker* marker, QWidget* parent) : + QWidget(parent), + ui(new Ui::BasicChannelSettingsWidget), + m_channelMarker(marker) +{ + ui->setupUi(this); + ui->title->setText(m_channelMarker->getTitle()); + paintColor(); + ui->red->setValue(m_channelMarker->getColor().red()); + ui->green->setValue(m_channelMarker->getColor().green()); + ui->blue->setValue(m_channelMarker->getColor().blue()); +} + +BasicChannelSettingsWidget::~BasicChannelSettingsWidget() +{ + delete ui; +} + +void BasicChannelSettingsWidget::on_title_textChanged(const QString& text) +{ + m_channelMarker->setTitle(text); +} + +void BasicChannelSettingsWidget::on_colorBtn_clicked() +{ + QColor c = m_channelMarker->getColor(); + c = QColorDialog::getColor(c, this, tr("Select Color for Channel")); + if(c.isValid()) { + m_channelMarker->setColor(c); + paintColor(); + ui->red->setValue(m_channelMarker->getColor().red()); + ui->green->setValue(m_channelMarker->getColor().green()); + ui->blue->setValue(m_channelMarker->getColor().blue()); + } +} + +void BasicChannelSettingsWidget::paintColor() +{ + QColor c(m_channelMarker->getColor()); + QPixmap pm(24, 24); + pm.fill(c); + ui->colorBtn->setIcon(pm); + ui->color->setText(tr("#%1%2%3") + .arg(c.red(), 2, 16, QChar('0')) + .arg(c.green(), 2, 16, QChar('0')) + .arg(c.blue(), 2, 16, QChar('0'))); +} + +void BasicChannelSettingsWidget::on_red_valueChanged(int value) +{ + QColor c(m_channelMarker->getColor()); + c.setRed(value); + m_channelMarker->setColor(c); + paintColor(); +} + +void BasicChannelSettingsWidget::on_green_valueChanged(int value) +{ + QColor c(m_channelMarker->getColor()); + c.setGreen(value); + m_channelMarker->setColor(c); + paintColor(); +} + +void BasicChannelSettingsWidget::on_blue_valueChanged(int value) +{ + QColor c(m_channelMarker->getColor()); + c.setBlue(value); + m_channelMarker->setColor(c); + paintColor(); +} diff --git a/sdrbase/gui/basicchannelsettingswidget.ui b/sdrbase/gui/basicchannelsettingswidget.ui new file mode 100644 index 000000000..d8c61ff18 --- /dev/null +++ b/sdrbase/gui/basicchannelsettingswidget.ui @@ -0,0 +1,107 @@ + + + BasicChannelSettingsWidget + + + + 0 + 0 + 149 + 116 + + + + Title & Color + + + + 2 + + + 3 + + + + + + 0 + 0 + + + + Title + + + + + + + + + + + 0 + 0 + + + + Color + + + + + + + + + + + + + + #ff0000 + + + + + + + 255 + + + Qt::Horizontal + + + + + + + 255 + + + Qt::Horizontal + + + + + + + 255 + + + Qt::Horizontal + + + + + + + title + colorBtn + red + green + blue + + + + diff --git a/sdrbase/gui/buttonswitch.cpp b/sdrbase/gui/buttonswitch.cpp new file mode 100644 index 000000000..88d0bd5d4 --- /dev/null +++ b/sdrbase/gui/buttonswitch.cpp @@ -0,0 +1,21 @@ +#include +#include "gui/buttonswitch.h" + +ButtonSwitch::ButtonSwitch(QWidget* parent) : + QToolButton(parent) +{ + setCheckable(true); + m_originalPalette = palette(); + connect(this, SIGNAL(toggled(bool)), this, SLOT(onToggled(bool))); +} + +void ButtonSwitch::onToggled(bool checked) +{ + if(checked) { + QPalette p = m_originalPalette; + p.setColor(QPalette::Button, QColor(0x80, 0x46, 0x00)); + setPalette(p); + } else { + setPalette(m_originalPalette); + } +} diff --git a/sdrbase/gui/channelwindow.cpp b/sdrbase/gui/channelwindow.cpp new file mode 100644 index 000000000..2849bf75f --- /dev/null +++ b/sdrbase/gui/channelwindow.cpp @@ -0,0 +1,36 @@ +#include +#include +#include +#include +#include "gui/channelwindow.h" +#include "gui/rollupwidget.h" + +ChannelWindow::ChannelWindow(QWidget* parent) : + QScrollArea(parent) +{ + m_container = new QWidget(this); + m_layout = new QBoxLayout(QBoxLayout::TopToBottom, m_container); + setWidget(m_container); + setWidgetResizable(true); + setBackgroundRole(QPalette::Base); + m_layout->setMargin(3); + m_layout->setSpacing(3); +} + +void ChannelWindow::addRollupWidget(QWidget* rollupWidget) +{ + rollupWidget->setParent(m_container); + m_container->layout()->addWidget(rollupWidget); +} + +void ChannelWindow::resizeEvent(QResizeEvent* event) +{ + if(event->size().height() > event->size().width()) { + m_layout->setDirection(QBoxLayout::TopToBottom); + m_layout->setAlignment(Qt::AlignTop); + } else { + m_layout->setDirection(QBoxLayout::LeftToRight); + m_layout->setAlignment(Qt::AlignLeft); + } + QScrollArea::resizeEvent(event); +} diff --git a/sdrbase/gui/glscope.cpp b/sdrbase/gui/glscope.cpp new file mode 100644 index 000000000..73c0d6202 --- /dev/null +++ b/sdrbase/gui/glscope.cpp @@ -0,0 +1,478 @@ +#include +#include +#include "gui/glscope.h" +#include "dsp/dspengine.h" + +#ifdef _WIN32 +static double log2f(double n) +{ + return log(n) / log(2.0); +} +#endif + +GLScope::GLScope(QWidget* parent) : + QGLWidget(parent), + m_dataChanged(false), + m_configChanged(true), + m_mode(ModeIQ), + m_orientation(Qt::Horizontal), + m_displayTrace(&m_rawTrace), + m_oldTraceSize(-1), + m_sampleRate(0), + m_dspEngine(NULL), + m_scopeVis(NULL), + m_amp(1.0), + m_timeBase(1), + m_timeOfsProMill(0), + m_triggerChannel(ScopeVis::TriggerFreeRun) +{ + setAttribute(Qt::WA_OpaquePaintEvent); + connect(&m_timer, SIGNAL(timeout()), this, SLOT(tick())); + m_timer.start(50); +} + +GLScope::~GLScope() +{ + if(m_dspEngine != NULL) { + m_dspEngine->removeSink(m_scopeVis); + delete m_scopeVis; + } +} + +void GLScope::setDSPEngine(DSPEngine* dspEngine) +{ + if((m_dspEngine == NULL) && (dspEngine != NULL)) { + m_dspEngine = dspEngine; + m_scopeVis = new ScopeVis(this); + m_dspEngine->addSink(m_scopeVis); + } +} + +void GLScope::setAmp(Real amp) +{ + m_amp = amp; + update(); +} + +void GLScope::setTimeBase(int timeBase) +{ + m_timeBase = timeBase; + update(); +} + +void GLScope::setTimeOfsProMill(int timeOfsProMill) +{ + m_timeOfsProMill = timeOfsProMill; + update(); +} + +void GLScope::setMode(Mode mode) +{ + m_mode = mode; + m_dataChanged = true; + update(); +} + +void GLScope::setOrientation(Qt::Orientation orientation) +{ + m_orientation = orientation; + m_configChanged = true; + update(); +} + +void GLScope::newTrace(const std::vector& trace, int sampleRate) +{ + if(!m_mutex.tryLock(2)) + return; + if(m_dataChanged) { + m_mutex.unlock(); + return; + } + + m_rawTrace = trace; + + m_sampleRate = sampleRate; + m_dataChanged = true; + + m_mutex.unlock(); +} + +void GLScope::initializeGL() +{ + glDisable(GL_DEPTH_TEST); +} + +void GLScope::resizeGL(int width, int height) +{ + glViewport(0, 0, width, height); + m_configChanged = true; +} + +void GLScope::paintGL() +{ + if(!m_mutex.tryLock(2)) + return; + + if(m_configChanged) + applyConfig(); + + handleMode(); + + if(m_displayTrace->size() != m_oldTraceSize) { + m_oldTraceSize = m_displayTrace->size(); + emit traceSizeChanged(m_displayTrace->size()); + } + + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + glClear(GL_COLOR_BUFFER_BIT); + + glPushMatrix(); + glScalef(2.0, -2.0, 1.0); + glTranslatef(-0.50, -0.5, 0); + + // I + + // draw rect around + glPushMatrix(); + glTranslatef(m_glScopeRect1.x(), m_glScopeRect1.y(), 0); + glScalef(m_glScopeRect1.width(), m_glScopeRect1.height(), 1); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glLineWidth(1.0f); + glColor4f(1, 1, 1, 0.5); + glBegin(GL_LINE_LOOP); + glVertex2f(1, 1); + glVertex2f(0, 1); + glVertex2f(0, 0); + glVertex2f(1, 0); + glEnd(); + glDisable(GL_BLEND); + // paint grid + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glLineWidth(1.0f); + glColor4f(1, 1, 1, 0.05f); + for(int i = 1; i < 10; i++) { + glBegin(GL_LINE_LOOP); + glVertex2f(0, i * 0.1); + glVertex2f(1, i * 0.1); + glEnd(); + } + for(int i = 1; i < 10; i++) { + glBegin(GL_LINE_LOOP); + glVertex2f(i * 0.1, 0); + glVertex2f(i * 0.1, 1); + glEnd(); + } + glPopMatrix(); + + if(m_triggerChannel == ScopeVis::TriggerChannelI) { + glPushMatrix(); + glTranslatef(m_glScopeRect1.x(), m_glScopeRect1.y() + m_glScopeRect1.height() / 2.0, 0); + glScalef(m_glScopeRect1.width(), -(m_glScopeRect1.height() / 2) * m_amp1, 1); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glEnable(GL_LINE_SMOOTH); + glLineWidth(1.0f); + glColor4f(0, 1, 0, 0.3f); + glBegin(GL_LINE_LOOP); + glVertex2f(0, m_triggerLevelHigh); + glVertex2f(1, m_triggerLevelHigh); + glEnd(); + glColor4f(0, 0.8f, 0.0, 0.3f); + glBegin(GL_LINE_LOOP); + glVertex2f(0, m_triggerLevelLow); + glVertex2f(1, m_triggerLevelLow); + glEnd(); + glDisable(GL_LINE_SMOOTH); + glPopMatrix(); + } + + if(m_displayTrace->size() > 0) { + glPushMatrix(); + glTranslatef(m_glScopeRect1.x(), m_glScopeRect1.y() + m_glScopeRect1.height() / 2.0, 0); + glScalef(m_glScopeRect1.width() * (float)m_timeBase / (float)(m_displayTrace->size() - 1), -(m_glScopeRect1.height() / 2) * m_amp1, 1); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glEnable(GL_LINE_SMOOTH); + glLineWidth(1.0f); + glColor4f(1, 1, 0, 0.4f); + int start = m_timeOfsProMill * (m_displayTrace->size() - (m_displayTrace->size() / m_timeBase)) / 1000; + int end = start + m_displayTrace->size() / m_timeBase; + if(end - start < 2) + start--; + float posLimit = 1.0 / m_amp1; + float negLimit = -1.0 / m_amp1; + glBegin(GL_LINE_STRIP); + for(int i = start; i < end; i++) { + float v = (*m_displayTrace)[i].real() + m_ofs1; + if(v > posLimit) + v = posLimit; + else if(v < negLimit) + v = negLimit; + glVertex2f(i - start, v); + } + glEnd(); + glDisable(GL_LINE_SMOOTH); + glPopMatrix(); + } + + // Q + + // draw rect around + glPushMatrix(); + glTranslatef(m_glScopeRect2.x(), m_glScopeRect2.y(), 0); + glScalef(m_glScopeRect2.width(), m_glScopeRect2.height(), 1); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glLineWidth(1.0f); + glColor4f(1, 1, 1, 0.5); + glBegin(GL_LINE_LOOP); + glVertex2f(1, 1); + glVertex2f(0, 1); + glVertex2f(0, 0); + glVertex2f(1, 0); + glEnd(); + glDisable(GL_BLEND); + // paint grid + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glLineWidth(1.0f); + glColor4f(1, 1, 1, 0.05f); + for(int i = 1; i < 10; i++) { + glBegin(GL_LINE_LOOP); + glVertex2f(0, i * 0.1); + glVertex2f(1, i * 0.1); + glEnd(); + } + for(int i = 1; i < 10; i++) { + glBegin(GL_LINE_LOOP); + glVertex2f(i * 0.1, 0); + glVertex2f(i * 0.1, 1); + glEnd(); + } + glPopMatrix(); + + if(m_triggerChannel == ScopeVis::TriggerChannelQ) { + glPushMatrix(); + glTranslatef(m_glScopeRect2.x(), m_glScopeRect2.y() + m_glScopeRect2.height() / 2.0, 0); + glScalef(m_glScopeRect2.width(), -(m_glScopeRect2.height() / 2) * m_amp2, 1); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glEnable(GL_LINE_SMOOTH); + glLineWidth(1.0f); + glColor4f(0, 1, 0, 0.3f); + glBegin(GL_LINE_LOOP); + glVertex2f(0, m_triggerLevelHigh); + glVertex2f(1, m_triggerLevelHigh); + glEnd(); + glColor4f(0, 0.8f, 0.0, 0.3f); + glBegin(GL_LINE_LOOP); + glVertex2f(0, m_triggerLevelLow); + glVertex2f(1, m_triggerLevelLow); + glEnd(); + glDisable(GL_LINE_SMOOTH); + glPopMatrix(); + } + + if(m_displayTrace->size() > 0) { + glPushMatrix(); + glTranslatef(m_glScopeRect2.x(), m_glScopeRect2.y() + m_glScopeRect2.height() / 2.0, 0); + glScalef(m_glScopeRect2.width() * (float)m_timeBase / (float)(m_displayTrace->size() - 1), -(m_glScopeRect2.height() / 2) * m_amp2, 1); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glEnable(GL_LINE_SMOOTH); + glLineWidth(1.0f); + glColor4f(1, 1, 0, 0.4f); + int start = m_timeOfsProMill * (m_displayTrace->size() - (m_displayTrace->size() / m_timeBase)) / 1000; + int end = start + m_displayTrace->size() / m_timeBase; + if(end - start < 2) + start--; + float posLimit = 1.0 / m_amp2; + float negLimit = -1.0 / m_amp2; + glBegin(GL_LINE_STRIP); + for(int i = start; i < end; i++) { + float v = (*m_displayTrace)[i].imag(); + if(v > posLimit) + v = posLimit; + else if(v < negLimit) + v = negLimit; + glVertex2f(i - start, v); + } + glEnd(); + glDisable(GL_LINE_SMOOTH); + glPopMatrix(); + } + + glPopMatrix(); + m_dataChanged = false; + m_mutex.unlock(); +} + +void GLScope::mousePressEvent(QMouseEvent* event) +{ +#if 0 + int x = event->x() - 10; + int y = event->y() - 10; + Real time; + Real amplitude; + ScopeVis::TriggerChannel channel; + if((x < 0) || (x >= width() - 20)) + return; + if((y < 0) || (y >= height() - 20)) + return; + + if((m_sampleRate != 0) && (m_timeBase != 0) && (width() > 20)) + time = ((Real)x * (Real)m_displayTrace->size()) / ((Real)m_sampleRate * (Real)m_timeBase * (Real)(width() - 20)); + else time = -1.0; + + if(y < (height() - 30) / 2) { + channel = ScopeVis::TriggerChannelI; + if((m_amp != 0) && (height() > 30)) + amplitude = 2.0 * ((height() - 30) * 0.25 - (Real)y) / (m_amp * (height() - 30) / 2.0); + else amplitude = -1; + } else if(y > (height() - 30) / 2 + 10) { + y -= 10 + (height() - 30) / 2; + channel = ScopeVis::TriggerChannelQ; + if((m_amp != 0) && (height() > 30)) + amplitude = 2.0 * ((height() - 30) * 0.25 - (Real)y) / (m_amp * (height() - 30) / 2.0); + else amplitude = -1; + } else { + channel = ScopeVis::TriggerFreeRun; + } + + if(m_dspEngine != NULL) { + qDebug("amp %f", amplitude); + m_triggerLevelHigh = amplitude + 0.01 / m_amp; + m_triggerLevelLow = amplitude - 0.01 / m_amp; + if(m_triggerLevelHigh > 1.0) + m_triggerLevelHigh = 1.0; + else if(m_triggerLevelHigh < -1.0) + m_triggerLevelHigh = -1.0; + if(m_triggerLevelLow > 1.0) + m_triggerLevelLow = 1.0; + else if(m_triggerLevelLow < -1.0) + m_triggerLevelLow = -1.0; + m_scopeVis->configure(m_dspEngine->getMessageQueue(), channel, m_triggerLevelHigh, m_triggerLevelLow); + m_triggerChannel = channel; + m_changed = true; + update(); + } +#endif +} + +void GLScope::handleMode() +{ + switch(m_mode) { + case ModeIQ: + m_displayTrace = &m_rawTrace; + m_amp1 = m_amp; + m_amp2 = m_amp; + m_ofs1 = 0.0; + m_ofs2 = 0.0; + break; + + case ModeMagLinPha: { + m_mathTrace.resize(m_rawTrace.size()); + std::vector::iterator dst = m_mathTrace.begin(); + for(std::vector::const_iterator src = m_rawTrace.begin(); src != m_rawTrace.end(); ++src) + *dst++ = Complex(abs(*src), arg(*src) / M_PI); + m_displayTrace = &m_mathTrace; + m_amp1 = m_amp; + m_amp2 = 1.0; + m_ofs1 = -1.0 / m_amp1; + m_ofs2 = 0.0; + break; + } + + case ModeMagdBPha: { + m_mathTrace.resize(m_rawTrace.size()); + std::vector::iterator dst = m_mathTrace.begin(); + Real mult = (10.0f / log2f(10.0f)); + for(std::vector::const_iterator src = m_rawTrace.begin(); src != m_rawTrace.end(); ++src) { + Real v = src->real() * src->real() + src->imag() * src->imag(); + v = (96.0 + (mult * log2f(v))) / 96.0; + *dst++ = Complex(v, arg(*src) / M_PI); + } + m_displayTrace = &m_mathTrace; + m_amp1 = 2.0 * m_amp; + m_amp2 = 1.0; + m_ofs1 = -1.0 / m_amp1; + m_ofs2 = 0.0; + break; + } + + case ModeDerived12: { + if(m_rawTrace.size() > 3) { + m_mathTrace.resize(m_rawTrace.size() - 3); + std::vector::iterator dst = m_mathTrace.begin(); + for(uint i = 3; i < m_rawTrace.size() ; i++) { + *dst++ = Complex( + abs(m_rawTrace[i] - m_rawTrace[i - 1]), + abs(m_rawTrace[i] - m_rawTrace[i - 1]) - abs(m_rawTrace[i - 2] - m_rawTrace[i - 3])); + } + m_displayTrace = &m_mathTrace; + m_amp1 = m_amp; + m_amp2 = m_amp; + m_ofs1 = -1.0 / m_amp1; + m_ofs2 = 0.0; + } + break; + } + + case ModeCyclostationary: { + if(m_rawTrace.size() > 2) { + m_mathTrace.resize(m_rawTrace.size() - 2); + std::vector::iterator dst = m_mathTrace.begin(); + for(uint i = 2; i < m_rawTrace.size() ; i++) + *dst++ = Complex(abs(m_rawTrace[i] - conj(m_rawTrace[i - 1])), 0); + m_displayTrace = &m_mathTrace; + m_amp1 = m_amp; + m_amp2 = m_amp; + m_ofs1 = -1.0 / m_amp1; + m_ofs2 = 0.0; + } + break; + } + + } +} + +void GLScope::applyConfig() +{ + m_configChanged = false; + + if(m_orientation == Qt::Vertical) { + m_glScopeRect1 = QRectF( + (float)10 / (float)width(), + (float)10 / (float)height(), + (float)(width() - 10 - 10) / (float)width(), + (float)((height() - 10 - 10 - 10) / 2) / (float)height() + ); + m_glScopeRect2 = QRectF( + (float)10 / (float)width(), + (float)(10 + 10 + (height() - 10 - 10 - 10) / 2) / (float)height(), + (float)(width() - 10 - 10) / (float)width(), + (float)((height() - 10 - 10 - 10) / 2) / (float)height() + ); + } else { + m_glScopeRect1 = QRectF( + (float)10 / (float)width(), + (float)10 / (float)height(), + (float)((width() - 10 - 10 - 10) / 2) / (float)width(), + (float)(height() - 10 - 10) / (float)height() + ); + m_glScopeRect2 = QRectF( + (float)(10 + 10 + ((width() - 10 - 10 - 10) / 2)) / (float)width(), + (float)10 / (float)height(), + (float)((width() - 10 - 10 - 10) / 2) / (float)width(), + (float)(height() - 10 - 10) / (float)height() + ); + } +} + +void GLScope::tick() +{ + if(m_dataChanged) + update(); +} diff --git a/sdrbase/gui/glspectrum.cpp b/sdrbase/gui/glspectrum.cpp new file mode 100644 index 000000000..560f33cf7 --- /dev/null +++ b/sdrbase/gui/glspectrum.cpp @@ -0,0 +1,1278 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include "gui/glspectrum.h" + +GLSpectrum::GLSpectrum(QWidget* parent) : + QGLWidget(parent), + m_cursorState(CSNormal), + m_mouseInside(false), + m_changesPending(true), + m_centerFrequency(100000000), + m_referenceLevel(0), + m_powerRange(100), + m_decay(0), + m_sampleRate(500000), + m_fftSize(512), + m_displayGrid(true), + m_invertedWaterfall(false), + m_displayMaxHold(false), + m_leftMarginTextureAllocated(false), + m_frequencyTextureAllocated(false), + m_waterfallBuffer(NULL), + m_waterfallTextureAllocated(false), + m_waterfallTextureHeight(-1), + m_displayWaterfall(true), + m_histogramBuffer(NULL), + m_histogram(NULL), + m_histogramHoldoff(NULL), + m_histogramTextureAllocated(false), + m_displayHistogram(true), + m_displayChanged(false) +{ + setAutoFillBackground(false); + setAttribute(Qt::WA_OpaquePaintEvent, true); + setAttribute(Qt::WA_NoSystemBackground, true); + setMouseTracking(true); + + setMinimumSize(200, 200); + + m_waterfallShare = 0.66; + + for(int i = 0; i <= 239; i++) { + QColor c; + c.setHsv(239 - i, 255, 15 + i); + ((quint8*)&m_waterfallPalette[i])[0] = c.red(); + ((quint8*)&m_waterfallPalette[i])[1] = c.green(); + ((quint8*)&m_waterfallPalette[i])[2] = c.blue(); + ((quint8*)&m_waterfallPalette[i])[3] = c.alpha(); + } + m_waterfallPalette[239] = 0xffffffff; + + m_histogramPalette[0] = m_waterfallPalette[0]; + for(int i = 1; i < 240; i++) { + QColor c; + c.setHsv(239 - i, 255 - ((i < 200) ? 0 : (i - 200) * 3), 150 + ((i < 100) ? i : 100)); + ((quint8*)&m_histogramPalette[i])[0] = c.red(); + ((quint8*)&m_histogramPalette[i])[1] = c.green(); + ((quint8*)&m_histogramPalette[i])[2] = c.blue(); + ((quint8*)&m_histogramPalette[i])[3] = c.alpha(); + } + for(int i = 1; i < 16; i++) { + QColor c; + c.setHsv(270, 128, 48 + i * 4); + ((quint8*)&m_histogramPalette[i])[0] = c.red(); + ((quint8*)&m_histogramPalette[i])[1] = c.green(); + ((quint8*)&m_histogramPalette[i])[2] = c.blue(); + ((quint8*)&m_histogramPalette[i])[3] = c.alpha(); + } + m_histogramHoldoffBase = 4; + m_histogramHoldoffCount = m_histogramHoldoffBase; + m_histogramLateHoldoff = 20; + + m_timeScale.setFont(font()); + m_timeScale.setOrientation(Qt::Vertical); + m_timeScale.setRange(Unit::Time, 0, 1); + m_powerScale.setFont(font()); + m_powerScale.setOrientation(Qt::Vertical); + m_frequencyScale.setFont(font()); + m_frequencyScale.setOrientation(Qt::Horizontal); + + connect(&m_timer, SIGNAL(timeout()), this, SLOT(tick())); + m_timer.start(50); +} + +GLSpectrum::~GLSpectrum() +{ + QMutexLocker mutexLocker(&m_mutex); + + m_changesPending = true; + + if(m_waterfallBuffer != NULL) { + delete m_waterfallBuffer; + m_waterfallBuffer = NULL; + } + if(m_waterfallTextureAllocated) { + makeCurrent(); + deleteTexture(m_waterfallTexture); + m_waterfallTextureAllocated = false; + } + if(m_histogramBuffer != NULL) { + delete m_histogramBuffer; + m_histogramBuffer = NULL; + } + if(m_histogram != NULL) { + delete[] m_histogram; + m_histogram = NULL; + } + if(m_histogramHoldoff != NULL) { + delete[] m_histogramHoldoff; + m_histogramHoldoff = NULL; + } + if(m_histogramTextureAllocated) { + makeCurrent(); + deleteTexture(m_histogramTexture); + m_histogramTextureAllocated = false; + } + if(m_leftMarginTextureAllocated) { + deleteTexture(m_leftMarginTexture); + m_leftMarginTextureAllocated = false; + } + if(m_frequencyTextureAllocated) { + deleteTexture(m_frequencyTexture); + m_frequencyTextureAllocated = false; + } +} + +void GLSpectrum::setCenterFrequency(quint64 frequency) +{ + m_centerFrequency = frequency; + m_changesPending = true; + update(); +} + +void GLSpectrum::setReferenceLevel(Real referenceLevel) +{ + m_referenceLevel = referenceLevel; + m_changesPending = true; + update(); +} + +void GLSpectrum::setPowerRange(Real powerRange) +{ + m_powerRange = powerRange; + m_changesPending = true; + update(); +} + +void GLSpectrum::setDecay(int decay) +{ + m_decay = decay; + if(m_decay < -2) + m_decay = -2; + else if(m_decay > 2) + m_decay = 2; +} + +void GLSpectrum::setSampleRate(qint32 sampleRate) +{ + m_sampleRate = sampleRate; + m_changesPending = true; + update(); +} + +void GLSpectrum::setDisplayWaterfall(bool display) +{ + m_displayWaterfall = display; + m_changesPending = true; + stopDrag(); + update(); +} + +void GLSpectrum::setInvertedWaterfall(bool inv) +{ + m_invertedWaterfall = inv; + m_changesPending = true; + stopDrag(); + update(); +} + +void GLSpectrum::setDisplayMaxHold(bool display) +{ + m_displayMaxHold = display; + m_changesPending = true; + stopDrag(); + update(); +} + +void GLSpectrum::setDisplayHistogram(bool display) +{ + m_displayHistogram = display; + m_changesPending = true; + stopDrag(); + update(); +} + +void GLSpectrum::setDisplayGrid(bool display) +{ + m_displayGrid = display; + update(); +} + +void GLSpectrum::addChannelMarker(ChannelMarker* channelMarker) +{ + QMutexLocker mutexLocker(&m_mutex); + + connect(channelMarker, SIGNAL(changed()), this, SLOT(channelMarkerChanged())); + connect(channelMarker, SIGNAL(destroyed(QObject*)), this, SLOT(channelMarkerDestroyed(QObject*))); + m_channelMarkerStates.append(new ChannelMarkerState(channelMarker)); + m_changesPending = true; + stopDrag(); + update(); +} + +void GLSpectrum::removeChannelMarker(ChannelMarker* channelMarker) +{ + QMutexLocker mutexLocker(&m_mutex); + + for(int i = 0; i < m_channelMarkerStates.size(); ++i) { + if(m_channelMarkerStates[i]->m_channelMarker == channelMarker) { + channelMarker->disconnect(this); + delete m_channelMarkerStates.takeAt(i); + m_changesPending = true; + stopDrag(); + update(); + return; + } + } +} + +void GLSpectrum::newSpectrum(const std::vector& spectrum, int fftSize) +{ + QMutexLocker mutexLocker(&m_mutex); + + m_displayChanged = true; + + if(m_changesPending) { + m_fftSize = fftSize; + return; + } + + if(fftSize != m_fftSize) { + m_fftSize = fftSize; + m_changesPending = true; + return; + } + + updateWaterfall(spectrum); + updateHistogram(spectrum); +} + +void GLSpectrum::updateWaterfall(const std::vector& spectrum) +{ + if(m_waterfallBufferPos < m_waterfallBuffer->height()) { + quint32* pix = (quint32*)m_waterfallBuffer->scanLine(m_waterfallBufferPos); + + for(int i = 0; i < m_fftSize; i++) { + Real vr = (int)((spectrum[i] - m_referenceLevel) * 2.4 * 100.0 / m_powerRange + 240.0); + int v = (int)vr; + + if(v > 239) + v = 239; + else if(v < 0) + v = 0; + + *pix++ = m_waterfallPalette[(int)v]; + } + + m_waterfallBufferPos++; + } +} + +void GLSpectrum::updateHistogram(const std::vector& spectrum) +{ + quint8* b = m_histogram; + quint8* h = m_histogramHoldoff; + int sub = 1; + + if(m_decay > 0) + sub += m_decay; + + m_histogramHoldoffCount--; + if(m_histogramHoldoffCount <= 0) { + for(int i = 0; i < 100 * m_fftSize; i++) { + if(*b > 20) { + *b = *b - sub; + } else if(*b > 0) { + if(*h >= sub) { + *h = *h - sub; + } else if(*h > 0) { + *h = *h - 1; + } else { + *b = *b - 1; + *h = m_histogramLateHoldoff; + } + } + b++; + h++; + } + m_histogramHoldoffCount = m_histogramHoldoffBase; + } + +//#define NO_AVX +#ifdef NO_AVX + for(int i = 0; i < m_fftSize; i++) { + int v = (int)((spectrum[i] - m_referenceLevel) * 100.0 / m_powerRange + 100.0); + + if((v >= 0) && (v <= 99)) { + b = m_histogram + i * 100 + v; + if(*b < 220) + *b += 4; + else if(*b < 239) + *b += 1; + } + } +#else + if(m_decay >= 0) { // normal + const __m128 refl = {m_referenceLevel, m_referenceLevel, m_referenceLevel, m_referenceLevel}; + const __m128 power = {m_powerRange, m_powerRange, m_powerRange, m_powerRange}; + const __m128 mul = {100.0f, 100.0f, 100.0f, 100.0f}; + + for(int i = 0; i < m_fftSize; i += 4) { + __m128 abc = _mm_loadu_ps (&spectrum[i]); + abc = _mm_sub_ps(abc, refl); + abc = _mm_mul_ps(abc, mul); + abc = _mm_div_ps(abc, power); + abc = _mm_add_ps(abc, mul); + __m128i result = _mm_cvtps_epi32(abc); + + for(int j = 0; j < 4; j++) { + int v = ((int*)&result)[j]; + if((v >= 0) && (v <= 99)) { + b = m_histogram + (i + j) * 100 + v; + if(*b < 220) + *b += 4; + else if(*b < 239) + *b += 1; + } + } + } + } else { // draw double pixels + int add = -m_decay * 4; + const __m128 refl = {m_referenceLevel, m_referenceLevel, m_referenceLevel, m_referenceLevel}; + const __m128 power = {m_powerRange, m_powerRange, m_powerRange, m_powerRange}; + const __m128 mul = {100.0f, 100.0f, 100.0f, 100.0f}; + + for(int i = 0; i < m_fftSize; i += 4) { + __m128 abc = _mm_loadu_ps (&spectrum[i]); + abc = _mm_sub_ps(abc, refl); + abc = _mm_mul_ps(abc, mul); + abc = _mm_div_ps(abc, power); + abc = _mm_add_ps(abc, mul); + __m128i result = _mm_cvtps_epi32(abc); + + for(int j = 0; j < 4; j++) { + int v = ((int*)&result)[j]; + if((v >= 1) && (v <= 98)) { + b = m_histogram + (i + j) * 100 + v; + if(b[-1] < 220) + b[-1] += add; + else if(b[-1] < 239) + b[-1] += 1; + if(b[0] < 220) + b[0] += add; + else if(b[0] < 239) + b[0] += 1; + if(b[1] < 220) + b[1] += add; + else if(b[1] < 239) + b[1] += 1; + } else if((v >= 0) && (v <= 99)) { + b = m_histogram + (i + j) * 100 + v; + if(*b < 220) + *b += add; + else if(*b < 239) + *b += 1; + } + } + } + } +#endif +} + +void GLSpectrum::initializeGL() +{ + glDisable(GL_DEPTH_TEST); +} + +void GLSpectrum::resizeGL(int width, int height) +{ + glViewport(0, 0, width, height); + + m_changesPending = true; +} + +void GLSpectrum::paintGL() +{ + if(!m_mutex.tryLock(2)) + return; + + if(m_changesPending) + applyChanges(); + + if(m_fftSize <= 0) { + m_mutex.unlock(); + return; + } + + glClearColor(0.0f, 0.0f, 0.0f, 0.0f); + glClear(GL_COLOR_BUFFER_BIT); + + glPushMatrix(); + glScalef(2.0, -2.0, 1.0); + glTranslatef(-0.50, -0.5, 0); + + // paint waterfall + if(m_displayWaterfall) { + glPushMatrix(); + glTranslatef(m_glWaterfallRect.x(), m_glWaterfallRect.y(), 0); + glScalef(m_glWaterfallRect.width(), m_glWaterfallRect.height(), 1); + + glBindTexture(GL_TEXTURE_2D, m_waterfallTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + for(int i = 0; i < m_waterfallBufferPos; i++) { + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, m_waterfallTexturePos, m_fftSize, 1, GL_RGBA, GL_UNSIGNED_BYTE, m_waterfallBuffer->scanLine(i)); + m_waterfallTexturePos = (m_waterfallTexturePos + 1) % m_waterfallTextureHeight; + } + m_waterfallBufferPos = 0; + float prop_y = m_waterfallTexturePos / (m_waterfallTextureHeight - 1.0); + float off = 1.0 / (m_waterfallTextureHeight - 1.0); + glEnable(GL_TEXTURE_2D); + glBegin(GL_QUADS); + glTexCoord2f(0, prop_y + 1 - off); + glVertex2f(0, m_invertedWaterfall ? 0 : 1); + glTexCoord2f(1, prop_y + 1 - off); + glVertex2f(1, m_invertedWaterfall ? 0 : 1); + glTexCoord2f(1, prop_y); + glVertex2f(1, m_invertedWaterfall ? 1 : 0); + glTexCoord2f(0, prop_y); + glVertex2f(0, m_invertedWaterfall ? 1 : 0); + glEnd(); + glDisable(GL_TEXTURE_2D); + + // paint channels + if(m_mouseInside) { + for(int i = 0; i < m_channelMarkerStates.size(); ++i) { + ChannelMarkerState* dv = m_channelMarkerStates[i]; + if(dv->m_channelMarker->getVisible()) { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(dv->m_channelMarker->getColor().redF(), dv->m_channelMarker->getColor().greenF(), dv->m_channelMarker->getColor().blueF(), 0.3f); + glPushMatrix(); + glTranslatef(dv->m_glRect.x(), dv->m_glRect.y(), 0); + glScalef(dv->m_glRect.width(), dv->m_glRect.height(), 1); + glBegin(GL_QUADS); + glVertex2f(0, 0); + glVertex2f(1, 0); + glVertex2f(1, 1); + glVertex2f(0, 1); + glEnd(); + glDisable(GL_BLEND); + glPopMatrix(); + } + } + } + + // draw rect around + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glLineWidth(1.0f); + glColor4f(1, 1, 1, 0.5); + glBegin(GL_LINE_LOOP); + glVertex2f(1, 1); + glVertex2f(0, 1); + glVertex2f(0, 0); + glVertex2f(1, 0); + glEnd(); + glDisable(GL_BLEND); + + glPopMatrix(); + } + + // paint histogram + if(m_displayHistogram || m_displayMaxHold) { + glPushMatrix(); + glTranslatef(m_glHistogramRect.x(), m_glHistogramRect.y(), 0); + glScalef(m_glHistogramRect.width(), m_glHistogramRect.height(), 1); + if(m_displayHistogram) { + // import new lines into the texture + quint32* pix; + quint8* bs = m_histogram; + for(int y = 0; y < 100; y++) { + quint8* b = bs; + pix = (quint32*)m_histogramBuffer->scanLine(99 - y); + for(int x = 0; x < m_fftSize; x++) { + *pix = m_histogramPalette[*b]; + pix++; + b += 100; + } + bs++; + } + + // draw texture + glBindTexture(GL_TEXTURE_2D, m_histogramTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_fftSize, 100, GL_RGBA, GL_UNSIGNED_BYTE, m_histogramBuffer->scanLine(0)); + glEnable(GL_TEXTURE_2D); + glBegin(GL_QUADS); + glTexCoord2f(0, 0); + glVertex2f(0, 0); + glTexCoord2f(1, 0); + glVertex2f(1, 0); + glTexCoord2f(1, 1); + glVertex2f(1, 1); + glTexCoord2f(0, 1); + glVertex2f(0, 1); + glEnd(); + glDisable(GL_TEXTURE_2D); + } + + // paint channels + if(m_mouseInside) { + for(int i = 0; i < m_channelMarkerStates.size(); ++i) { + ChannelMarkerState* dv = m_channelMarkerStates[i]; + if(dv->m_channelMarker->getVisible()) { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(dv->m_channelMarker->getColor().redF(), dv->m_channelMarker->getColor().greenF(), dv->m_channelMarker->getColor().blueF(), 0.3f); + glPushMatrix(); + glTranslatef(dv->m_glRect.x(), dv->m_glRect.y(), 0); + glScalef(dv->m_glRect.width(), dv->m_glRect.height(), 1); + glBegin(GL_QUADS); + glVertex2f(0, 0); + glVertex2f(1, 0); + glVertex2f(1, 1); + glVertex2f(0, 1); + glEnd(); + glDisable(GL_BLEND); + glColor3f(0.8f, 0.8f, 0.6f); + glBegin(GL_LINE_LOOP); + glVertex2f(0.5, 0); + glVertex2f(0.5, 1); + glEnd(); + glPopMatrix(); + } + } + } + + // draw rect around + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glLineWidth(1.0f); + glColor4f(1, 1, 1, 0.5); + glBegin(GL_LINE_LOOP); + glVertex2f(1, 1); + glVertex2f(0, 1); + glVertex2f(0, 0); + glVertex2f(1, 0); + glEnd(); + glDisable(GL_BLEND); + glPopMatrix(); + } + + // paint left scales (time and power) + if(m_displayWaterfall || m_displayMaxHold || m_displayHistogram ) { + glBindTexture(GL_TEXTURE_2D, m_leftMarginTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + + glPushMatrix(); + glTranslatef(m_glLeftScaleRect.x(), m_glLeftScaleRect.y(), 0); + glScalef(m_glLeftScaleRect.width(), m_glLeftScaleRect.height(), 1); + + glEnable(GL_TEXTURE_2D); + glBegin(GL_QUADS); + glTexCoord2f(0, 1); + glVertex2f(0, 1); + glTexCoord2f(1, 1); + glVertex2f(1, 1); + glTexCoord2f(1, 0); + glVertex2f(1, 0); + glTexCoord2f(0, 0); + glVertex2f(0, 0); + glEnd(); + glDisable(GL_TEXTURE_2D); + glPopMatrix(); + } + + // paint frequency scale + if(m_displayWaterfall || m_displayMaxHold || m_displayHistogram ) { + glBindTexture(GL_TEXTURE_2D, m_frequencyTexture); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + glPushMatrix(); + glTranslatef(m_glFrequencyScaleRect.x(), m_glFrequencyScaleRect.y(), 0); + glScalef(m_glFrequencyScaleRect.width(), m_glFrequencyScaleRect.height(), 1); + + glEnable(GL_TEXTURE_2D); + glBegin(GL_QUADS); + glTexCoord2f(0, 1); + glVertex2f(0, 1); + glTexCoord2f(1, 1); + glVertex2f(1, 1); + glTexCoord2f(1, 0); + glVertex2f(1, 0); + glTexCoord2f(0, 0); + glVertex2f(0, 0); + glEnd(); + glDisable(GL_TEXTURE_2D); + glPopMatrix(); + + // paint channels + glPushMatrix(); + glTranslatef(m_glWaterfallRect.x(), m_glFrequencyScaleRect.y(), 0); + glScalef(m_glWaterfallRect.width(), m_glFrequencyScaleRect.height(), 1); + for(int i = 0; i < m_channelMarkerStates.size(); ++i) { + ChannelMarkerState* dv = m_channelMarkerStates[i]; + if(dv->m_channelMarker->getVisible()) { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glColor4f(dv->m_channelMarker->getColor().redF(), dv->m_channelMarker->getColor().greenF(), dv->m_channelMarker->getColor().blueF(), 0.5f); + glPushMatrix(); + glTranslatef(dv->m_glRect.x(), dv->m_glRect.y(), 0); + glScalef(dv->m_glRect.width(), dv->m_glRect.height(), 1); + glBegin(GL_QUADS); + glVertex2f(0, 0); + glVertex2f(1, 0); + glVertex2f(1, 1); + glVertex2f(0, 1); + glEnd(); + glDisable(GL_BLEND); + glPopMatrix(); + } + } + glPopMatrix(); + } + + // paint max hold lines on top of histogram + if(m_displayMaxHold) { + if(m_maxHold.size() < m_fftSize) + m_maxHold.resize(m_fftSize); + for(int i = 0; i < m_fftSize; i++) { + int j; + quint8* bs = m_histogram + i * 100; + for(j = 99; j > 1; j--) { + if(bs[j] > 0) + break; + } + // TODO: ((bs[j] * (float)j) + (bs[j + 1] * (float)(j + 1))) / (bs[j] + bs[j + 1]) + j = j - 99; + m_maxHold[i] = (j * m_powerRange) / 99.0 + m_referenceLevel; + } + + glPushMatrix(); + glTranslatef(m_glHistogramRect.x(), m_glHistogramRect.y(), 0); + glScalef(m_glHistogramRect.width() / (float)(m_fftSize - 1), -m_glHistogramRect.height() / m_powerRange, 1); + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glEnable(GL_LINE_SMOOTH); + glLineWidth(1.0f); + glColor3f(1, 0, 0); + Real bottom = -m_powerRange; + glBegin(GL_LINE_STRIP); + for(int i = 0; i < m_fftSize; i++) { + Real v = m_maxHold[i] - m_referenceLevel; + if(v > 0) + v = 0; + else if(v < bottom) + v = bottom; + glVertex2f(i, v); + } + glEnd(); + glDisable(GL_LINE_SMOOTH); + glPopMatrix(); + } + + // paint waterfall grid + if(m_displayWaterfall && m_displayGrid) { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glLineWidth(1.0f); + glColor4f(1, 1, 1, 0.05f); + + glPushMatrix(); + glTranslatef(m_glWaterfallRect.x(), m_glWaterfallRect.y(), 0); + glScalef(m_glWaterfallRect.width(), m_glWaterfallRect.height(), 1); + + const ScaleEngine::TickList* tickList; + const ScaleEngine::Tick* tick; + + tickList = &m_timeScale.getTickList(); + for(int i= 0; i < tickList->count(); i++) { + tick = &(*tickList)[i]; + if(tick->major) { + if(tick->textSize > 0) { + float y = tick->pos / m_timeScale.getSize(); + glBegin(GL_LINE_LOOP); + glVertex2f(0, y); + glVertex2f(1, y); + glEnd(); + } + } + } + + tickList = &m_frequencyScale.getTickList(); + for(int i= 0; i < tickList->count(); i++) { + tick = &(*tickList)[i]; + if(tick->major) { + if(tick->textSize > 0) { + float x = tick->pos / m_frequencyScale.getSize(); + glBegin(GL_LINE_LOOP); + glVertex2f(x, 0); + glVertex2f(x, 1); + glEnd(); + } + } + } + + glPopMatrix(); + } + + // paint histogram grid + if((m_displayHistogram || m_displayMaxHold) && (m_displayGrid)) { + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + glLineWidth(1.0f); + glColor4f(1, 1, 1, 0.05f); + + glPushMatrix(); + glTranslatef(m_glHistogramRect.x(), m_glHistogramRect.y(), 0); + glScalef(m_glHistogramRect.width(), m_glHistogramRect.height(), 1); + + const ScaleEngine::TickList* tickList; + const ScaleEngine::Tick* tick; + + tickList = &m_powerScale.getTickList(); + for(int i= 0; i < tickList->count(); i++) { + tick = &(*tickList)[i]; + if(tick->major) { + if(tick->textSize > 0) { + float y = tick->pos / m_powerScale.getSize(); + glBegin(GL_LINE_LOOP); + glVertex2f(0, y); + glVertex2f(1, y); + glEnd(); + } + } + } + + tickList = &m_frequencyScale.getTickList(); + for(int i= 0; i < tickList->count(); i++) { + tick = &(*tickList)[i]; + if(tick->major) { + if(tick->textSize > 0) { + float x = tick->pos / m_frequencyScale.getSize(); + glBegin(GL_LINE_LOOP); + glVertex2f(x, 0); + glVertex2f(x, 1); + glEnd(); + } + } + } + + glPopMatrix(); + } + + glPopMatrix(); + + m_mutex.unlock(); +} + +void GLSpectrum::stopDrag() +{ + if(m_cursorState != CSNormal) { + if((m_cursorState == CSSplitterMoving) || (m_cursorState == CSChannelMoving)) + releaseMouse(); + setCursor(Qt::ArrowCursor); + m_cursorState = CSNormal; + } +} + +void GLSpectrum::applyChanges() +{ + m_changesPending = false; + + if(m_fftSize <= 0) + return; + + QFontMetrics fm(font()); + int M = fm.width("-"); + + int topMargin = fm.ascent() * 1.5; + int bottomMargin = fm.ascent() * 1.5; + + int waterfallHeight; + int waterfallTop; + int frequencyScaleHeight = fm.height() * 2; + int frequencyScaleTop; + int histogramTop; + int histogramHeight; + int leftMargin; + int rightMargin = fm.width("000"); + + if(m_displayWaterfall && (m_displayHistogram | m_displayMaxHold)) { + waterfallHeight = height() * m_waterfallShare - 1; + if(waterfallHeight < 0) + waterfallHeight = 0; + if(!m_invertedWaterfall) { + waterfallTop = topMargin; + frequencyScaleTop = waterfallTop + waterfallHeight + 1; + histogramTop = waterfallTop + waterfallHeight + frequencyScaleHeight + 1; + histogramHeight = height() - topMargin - waterfallHeight - frequencyScaleHeight - bottomMargin; + } else { + histogramTop = topMargin; + histogramHeight = height() - topMargin - waterfallHeight - frequencyScaleHeight - bottomMargin; + waterfallTop = histogramTop + histogramHeight + frequencyScaleHeight + 1; + frequencyScaleTop = histogramTop + histogramHeight + 1; + } + + m_timeScale.setSize(waterfallHeight); + if(m_sampleRate > 0) { + if(!m_invertedWaterfall) + m_timeScale.setRange(Unit::Time, (waterfallHeight * m_fftSize) / (float)m_sampleRate, 0); + else m_timeScale.setRange(Unit::Time, 0, (waterfallHeight * m_fftSize) / (float)m_sampleRate); + } else { + m_timeScale.setRange(Unit::Time, 0, 1); + } + m_powerScale.setSize(histogramHeight); + m_powerScale.setRange(Unit::Decibel, m_referenceLevel - m_powerRange, m_referenceLevel); + leftMargin = m_timeScale.getScaleWidth(); + if(m_powerScale.getScaleWidth() > leftMargin) + leftMargin = m_powerScale.getScaleWidth(); + leftMargin += 2 * M; + + m_frequencyScale.setSize(width() - leftMargin - rightMargin); + m_frequencyScale.setRange(Unit::Frequency, m_centerFrequency - m_sampleRate / 2, m_centerFrequency + m_sampleRate / 2); + + m_glWaterfallRect = QRectF( + (float)leftMargin / (float)width(), + (float)waterfallTop / (float)height(), + (float)(width() - leftMargin - rightMargin) / (float)width(), + (float)waterfallHeight / (float)height() + ); + + m_glHistogramRect = QRectF( + (float)leftMargin / (float)width(), + (float)histogramTop / (float)height(), + (float)(width() - leftMargin - rightMargin) / (float)width(), + (float)histogramHeight / (float)height() + ); + + m_frequencyScaleRect = QRect( + 0, + frequencyScaleTop, + width(), + frequencyScaleHeight + ); + m_glFrequencyScaleRect = QRectF( + (float)0, + (float)frequencyScaleTop / (float)height(), + (float)1, + (float)frequencyScaleHeight / (float)height() + ); + + m_glLeftScaleRect = QRectF( + (float)0, + (float)0, + (float)(leftMargin - 1) / (float)width(), + (float)1 + ); + } else if(m_displayWaterfall) { + bottomMargin = frequencyScaleHeight; + waterfallTop = topMargin; + waterfallHeight = height() - topMargin - frequencyScaleHeight; + frequencyScaleTop = topMargin + waterfallHeight + 1; + histogramTop = 0; + + m_timeScale.setSize(waterfallHeight); + if(m_sampleRate > 0) { + if(!m_invertedWaterfall) + m_timeScale.setRange(Unit::Time, (waterfallHeight * m_fftSize) / (float)m_sampleRate, 0); + else m_timeScale.setRange(Unit::Time, 0, (waterfallHeight * m_fftSize) / (float)m_sampleRate); + } else { + if(!m_invertedWaterfall) + m_timeScale.setRange(Unit::Time, 10, 0); + else m_timeScale.setRange(Unit::Time, 0, 10); + } + leftMargin = m_timeScale.getScaleWidth(); + leftMargin += 2 * M; + + m_frequencyScale.setSize(width() - leftMargin - rightMargin); + m_frequencyScale.setRange(Unit::Frequency, m_centerFrequency - m_sampleRate / 2.0, m_centerFrequency + m_sampleRate / 2.0); + + m_glWaterfallRect = QRectF( + (float)leftMargin / (float)width(), + (float)topMargin / (float)height(), + (float)(width() - leftMargin - rightMargin) / (float)width(), + (float)waterfallHeight / (float)height() + ); + + m_frequencyScaleRect = QRect( + 0, + frequencyScaleTop, + width(), + frequencyScaleHeight + ); + m_glFrequencyScaleRect = QRectF( + (float)0, + (float)frequencyScaleTop / (float)height(), + (float)1, + (float)frequencyScaleHeight / (float)height() + ); + + m_glLeftScaleRect = QRectF( + (float)0, + (float)0, + (float)(leftMargin - 1) / (float)width(), + (float)1 + ); + } else if(m_displayHistogram || m_displayMaxHold) { + bottomMargin = frequencyScaleHeight; + frequencyScaleTop = height() - bottomMargin; + histogramTop = topMargin - 1; + waterfallHeight = 0; + histogramHeight = height() - topMargin - frequencyScaleHeight; + + m_powerScale.setSize(histogramHeight); + m_powerScale.setRange(Unit::Decibel, m_referenceLevel - m_powerRange, m_referenceLevel); + leftMargin = m_powerScale.getScaleWidth(); + leftMargin += 2 * M; + + m_frequencyScale.setSize(width() - leftMargin - rightMargin); + m_frequencyScale.setRange(Unit::Frequency, m_centerFrequency - m_sampleRate / 2, m_centerFrequency + m_sampleRate / 2); + + m_glHistogramRect = QRectF( + (float)leftMargin / (float)width(), + (float)histogramTop / (float)height(), + (float)(width() - leftMargin - rightMargin) / (float)width(), + (float)(height() - topMargin - frequencyScaleHeight) / (float)height() + ); + + m_frequencyScaleRect = QRect( + 0, + frequencyScaleTop, + width(), + frequencyScaleHeight + ); + m_glFrequencyScaleRect = QRectF( + (float)0, + (float)frequencyScaleTop / (float)height(), + (float)1, + (float)frequencyScaleHeight / (float)height() + ); + + m_glLeftScaleRect = QRectF( + (float)0, + (float)0, + (float)(leftMargin - 1) / (float)width(), + (float)1 + ); + } else { + leftMargin = 2; + waterfallHeight = 0; + } + + // channel overlays + for(int i = 0; i < m_channelMarkerStates.size(); ++i) { + ChannelMarkerState* dv = m_channelMarkerStates[i]; + dv->m_glRect.setRect( + m_frequencyScale.getPosFromValue(m_centerFrequency + dv->m_channelMarker->getCenterFrequency() - dv->m_channelMarker->getBandwidth() / 2) / (float)(width() - leftMargin - rightMargin), + 0, + (dv->m_channelMarker->getBandwidth() / (float)m_sampleRate), + 1); + if(m_displayHistogram || m_displayMaxHold || m_displayWaterfall) { + dv->m_rect.setRect(m_frequencyScale.getPosFromValue(m_centerFrequency + dv->m_channelMarker->getCenterFrequency()) + leftMargin - 1, + topMargin, + 5, + height() - topMargin - bottomMargin); + } + } + + // prepare left scales (time and power) + { + m_leftMarginPixmap = QPixmap(leftMargin - 1, height()); + m_leftMarginPixmap.fill(Qt::black); + { + QPainter painter(&m_leftMarginPixmap); + painter.setPen(QColor(0xf0, 0xf0, 0xff)); + const ScaleEngine::TickList* tickList; + const ScaleEngine::Tick* tick; + if(m_displayWaterfall) { + tickList = &m_timeScale.getTickList(); + for(int i = 0; i < tickList->count(); i++) { + tick = &(*tickList)[i]; + if(tick->major) { + if(tick->textSize > 0) + painter.drawText(QPointF(leftMargin - M - tick->textSize, waterfallTop + fm.ascent() + tick->textPos), tick->text); + } + } + } + if(m_displayHistogram || m_displayMaxHold) { + tickList = &m_powerScale.getTickList(); + for(int i = 0; i < tickList->count(); i++) { + tick = &(*tickList)[i]; + if(tick->major) { + if(tick->textSize > 0) + painter.drawText(QPointF(leftMargin - M - tick->textSize, histogramTop + histogramHeight - tick->textPos - 1), tick->text); + } + } + } + } + if(m_leftMarginTextureAllocated) + deleteTexture(m_leftMarginTexture); + m_leftMarginTexture = bindTexture(m_leftMarginPixmap, + GL_TEXTURE_2D, + GL_RGBA, + QGLContext::LinearFilteringBindOption | + QGLContext::MipmapBindOption); + m_leftMarginTextureAllocated = true; + } + // prepare frequency scale + if(m_displayWaterfall || m_displayHistogram || m_displayMaxHold){ + m_frequencyPixmap = QPixmap(width(), frequencyScaleHeight); + m_frequencyPixmap.fill(Qt::transparent); + { + QPainter painter(&m_frequencyPixmap); + painter.setPen(Qt::NoPen); + painter.setBrush(Qt::black); + painter.setBrush(Qt::transparent); + painter.drawRect(leftMargin, 0, width() - leftMargin, frequencyScaleHeight); + painter.setPen(QColor(0xf0, 0xf0, 0xff)); + const ScaleEngine::TickList* tickList = &m_frequencyScale.getTickList(); + const ScaleEngine::Tick* tick; + for(int i = 0; i < tickList->count(); i++) { + tick = &(*tickList)[i]; + if(tick->major) { + if(tick->textSize > 0) + painter.drawText(QPointF(leftMargin + tick->textPos, fm.height() + fm.ascent() / 2 - 1), tick->text); + } + } + + } + if(m_frequencyTextureAllocated) + deleteTexture(m_frequencyTexture); + m_frequencyTexture = bindTexture(m_frequencyPixmap, + GL_TEXTURE_2D, + GL_RGBA, + QGLContext::LinearFilteringBindOption | + QGLContext::MipmapBindOption); + m_frequencyTextureAllocated = true; + } + + if(!m_waterfallTextureAllocated) { + glGenTextures(1, &m_waterfallTexture); + m_waterfallTextureAllocated = true; + } + if(!m_histogramTextureAllocated) { + glGenTextures(1, &m_histogramTexture); + m_histogramTextureAllocated = true; + } + + bool fftSizeChanged = true; + if(m_waterfallBuffer != NULL) + fftSizeChanged = m_waterfallBuffer->width() != m_fftSize; + bool windowSizeChanged = m_waterfallTextureHeight != waterfallHeight; + + if(fftSizeChanged) { + if(m_waterfallBuffer != NULL) { + delete m_waterfallBuffer; + m_waterfallBuffer = NULL; + } + m_waterfallBuffer = new QImage(m_fftSize, 256, QImage::Format_ARGB32); + if(m_waterfallBuffer != NULL) { + m_waterfallBuffer->fill(qRgb(0x00, 0x00, 0x00)); + m_waterfallBufferPos = 0; + } else { + m_fftSize = 0; + m_changesPending = true; + return; + } + + if(m_histogramBuffer != NULL) { + delete m_histogramBuffer; + m_histogramBuffer = NULL; + } + if(m_histogram != NULL) { + delete[] m_histogram; + m_histogram = NULL; + } + if(m_histogramHoldoff != NULL) { + delete[] m_histogramHoldoff; + m_histogramHoldoff = NULL; + } + + m_histogramBuffer = new QImage(m_fftSize, 100, QImage::Format_RGB32); + if(m_histogramBuffer != NULL) { + m_histogramBuffer->fill(qRgb(0x00, 0x00, 0x00)); + } else { + m_fftSize = 0; + m_changesPending = true; + return; + } + + m_histogram = new quint8[100 * m_fftSize]; + memset(m_histogram, 0x00, 100 * m_fftSize); + m_histogramHoldoff = new quint8[100 * m_fftSize]; + memset(m_histogramHoldoff, 0x07, 100 * m_fftSize); + + quint8* data = new quint8[m_fftSize * 100 * 4]; + memset(data, 0x00, m_fftSize * 100 * 4); + glBindTexture(GL_TEXTURE_2D, m_histogramTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_fftSize, 100, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + delete[] data; + } + + if(fftSizeChanged || windowSizeChanged) { + m_waterfallTextureHeight = waterfallHeight; + quint8* data = new quint8[m_fftSize * m_waterfallTextureHeight * 4]; + memset(data, 0x00, m_fftSize * m_waterfallTextureHeight * 4); + glBindTexture(GL_TEXTURE_2D, m_waterfallTexture); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_fftSize, m_waterfallTextureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + delete[] data; + m_waterfallTexturePos = 0; + } +} + +void GLSpectrum::mouseMoveEvent(QMouseEvent* event) +{ + if(m_displayWaterfall && (m_displayWaterfall || m_displayHistogram || m_displayMaxHold)) { + if(m_frequencyScaleRect.contains(event->pos())) { + if(m_cursorState == CSNormal) { + setCursor(Qt::SizeVerCursor); + m_cursorState = CSSplitter; + return; + } + } else { + if(m_cursorState == CSSplitter) { + setCursor(Qt::ArrowCursor); + m_cursorState = CSNormal; + return; + } + } + } + + if(m_cursorState == CSSplitterMoving) { + float newShare; + if(!m_invertedWaterfall) + newShare = (float)(event->y() - m_frequencyScaleRect.height()) / (float)height(); + else newShare = 1.0 - (float)(event->y() + m_frequencyScaleRect.height()) / (float)height(); + if(newShare < 0.1) + newShare = 0.1f; + else if(newShare > 0.8) + newShare = 0.8f; + m_waterfallShare = newShare; + m_changesPending = true; + update(); + return; + } else if(m_cursorState == CSChannelMoving) { + Real freq = m_frequencyScale.getValueFromPos(event->x() - m_leftMarginPixmap.width() - 1) - m_centerFrequency; + m_channelMarkerStates[m_cursorChannel]->m_channelMarker->setCenterFrequency(freq); + } + + if(m_displayWaterfall || m_displayHistogram || m_displayMaxHold) { + for(int i = 0; i < m_channelMarkerStates.size(); ++i) { + if(m_channelMarkerStates[i]->m_rect.contains(event->pos())) { + if(m_cursorState == CSNormal) { + setCursor(Qt::SizeHorCursor); + m_cursorState = CSChannel; + m_cursorChannel = i; + return; + } else if(m_cursorState == CSChannel) { + return; + } + } + } + } + if(m_cursorState == CSChannel) { + setCursor(Qt::ArrowCursor); + m_cursorState = CSNormal; + return; + } +} + +void GLSpectrum::mousePressEvent(QMouseEvent* event) +{ + if(event->button() != 1) + return; + + if(m_cursorState == CSSplitter) { + grabMouse(); + m_cursorState = CSSplitterMoving; + return; + } else if(m_cursorState == CSChannel) { + grabMouse(); + m_cursorState = CSChannelMoving; + return; + } else if((m_cursorState == CSNormal) && (m_channelMarkerStates.size() == 1)) { + grabMouse(); + setCursor(Qt::SizeHorCursor); + m_cursorState = CSChannelMoving; + m_cursorChannel = 0; + Real freq = m_frequencyScale.getValueFromPos(event->x() - m_leftMarginPixmap.width() - 1) - m_centerFrequency; + m_channelMarkerStates[m_cursorChannel]->m_channelMarker->setCenterFrequency(freq); + return; + } +} + +void GLSpectrum::mouseReleaseEvent(QMouseEvent*) +{ + if(m_cursorState == CSSplitterMoving) { + releaseMouse(); + m_cursorState = CSSplitter; + } else if(m_cursorState == CSChannelMoving) { + releaseMouse(); + m_cursorState = CSChannel; + } +} + +void GLSpectrum::enterEvent(QEvent* event) +{ + m_mouseInside = true; + update(); + QGLWidget::enterEvent(event); +} + +void GLSpectrum::leaveEvent(QEvent* event) +{ + m_mouseInside = false; + update(); + QGLWidget::enterEvent(event); +} + +void GLSpectrum::tick() +{ + if(m_displayChanged) { + m_displayChanged = false; + update(); + } +} + +void GLSpectrum::channelMarkerChanged() +{ + m_changesPending = true; + update(); +} + +void GLSpectrum::channelMarkerDestroyed(QObject* object) +{ + removeChannelMarker((ChannelMarker*)object); +} diff --git a/sdrbase/gui/glspectrumgui.cpp b/sdrbase/gui/glspectrumgui.cpp new file mode 100644 index 000000000..1fbaaf2ee --- /dev/null +++ b/sdrbase/gui/glspectrumgui.cpp @@ -0,0 +1,210 @@ +#include "gui/glspectrumgui.h" +#include "dsp/fftwindow.h" +#include "dsp/spectrumvis.h" +#include "gui/glspectrum.h" +#include "util/simpleserializer.h" +#include "ui_glspectrumgui.h" + +GLSpectrumGUI::GLSpectrumGUI(QWidget* parent) : + QWidget(parent), + ui(new Ui::GLSpectrumGUI), + m_messageQueue(NULL), + m_spectrumVis(NULL), + m_glSpectrum(NULL), + m_fftSize(1024), + m_fftOverlap(10), + m_fftWindow(FFTWindow::Hamming), + m_refLevel(0), + m_powerRange(100), + m_decay(0), + m_displayWaterfall(false), + m_invertedWaterfall(false), + m_displayMaxHold(true), + m_displayHistogram(true), + m_displayGrid(true), + m_invert(false) +{ + ui->setupUi(this); + for(int ref = 0; ref >= -95; ref -= 5) + ui->refLevel->addItem(QString("%1").arg(ref)); + for(int range = 100; range >= 5; range -= 5) + ui->levelRange->addItem(QString("%1").arg(range)); +} + +GLSpectrumGUI::~GLSpectrumGUI() +{ + delete ui; +} + +void GLSpectrumGUI::setBuddies(MessageQueue* messageQueue, SpectrumVis* spectrumVis, GLSpectrum* glSpectrum) +{ + m_messageQueue = messageQueue; + m_spectrumVis = spectrumVis; + m_glSpectrum = glSpectrum; + applySettings(); +} + +void GLSpectrumGUI::resetToDefaults() +{ + m_fftSize = 1024; + m_fftOverlap = 10; + m_fftWindow = FFTWindow::Hamming; + m_refLevel = 0; + m_powerRange = 100; + m_decay = 0; + m_displayWaterfall = false; + m_invertedWaterfall = false; + m_displayMaxHold = true; + m_displayHistogram = true; + m_displayGrid = true; + m_invert = false; + applySettings(); +} + +QByteArray GLSpectrumGUI::serialize() const +{ + SimpleSerializer s(1); + s.writeS32(1, m_fftSize); + s.writeS32(2, m_fftOverlap); + s.writeS32(3, m_fftWindow); + s.writeReal(4, m_refLevel); + s.writeReal(5, m_powerRange); + s.writeBool(6, m_displayWaterfall); + s.writeBool(7, m_invertedWaterfall); + s.writeBool(8, m_displayMaxHold); + s.writeBool(9, m_displayHistogram); + s.writeS32(10, m_decay); + s.writeBool(11, m_displayGrid); + s.writeBool(12, m_invert); + return s.final(); +} + +bool GLSpectrumGUI::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { + d.readS32(1, &m_fftSize, 1024); + d.readS32(2, &m_fftOverlap, 10); + d.readS32(3, &m_fftWindow, FFTWindow::Hamming); + d.readReal(4, &m_refLevel, 0); + d.readReal(5, &m_powerRange, 100); + d.readBool(6, &m_displayWaterfall, true); + d.readBool(7, &m_invertedWaterfall, false); + d.readBool(8, &m_displayMaxHold, false); + d.readBool(9, &m_displayHistogram, true); + d.readS32(10, &m_decay, 0); + d.readBool(11, &m_displayGrid, true); + d.readBool(12, &m_invert, false); + applySettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +void GLSpectrumGUI::applySettings() +{ + ui->fftWindow->setCurrentIndex(m_fftWindow); + for(int i = 0; i < 6; i++) { + if(m_fftSize == (1 << (i + 7))) { + ui->fftSize->setCurrentIndex(i); + break; + } + } + ui->refLevel->setCurrentIndex(-m_refLevel / 5); + ui->levelRange->setCurrentIndex((100 - m_powerRange) / 5); + ui->decay->setCurrentIndex(m_decay + 2); + ui->waterfall->setChecked(m_displayWaterfall); + ui->maxHold->setChecked(m_displayMaxHold); + ui->histogram->setChecked(m_displayHistogram); + ui->invert->setChecked(m_invert); + ui->grid->setChecked(m_displayGrid); + + m_glSpectrum->setDisplayWaterfall(m_displayWaterfall); + m_glSpectrum->setInvertedWaterfall(m_invertedWaterfall); + m_glSpectrum->setDisplayMaxHold(m_displayMaxHold); + m_glSpectrum->setDisplayHistogram(m_displayHistogram); + m_glSpectrum->setDecay(m_decay); + m_glSpectrum->setInvertedWaterfall(m_invert); + m_glSpectrum->setDisplayGrid(m_displayGrid); + + m_spectrumVis->configure(m_messageQueue, m_fftSize, m_fftOverlap, (FFTWindow::Function)m_fftWindow); +} + +void GLSpectrumGUI::on_fftWindow_currentIndexChanged(int index) +{ + m_fftWindow = index; + if(m_spectrumVis == NULL) + return; + m_spectrumVis->configure(m_messageQueue, m_fftSize, m_fftOverlap, (FFTWindow::Function)m_fftWindow); +} + +void GLSpectrumGUI::on_fftSize_currentIndexChanged(int index) +{ + m_fftSize = 1 << (7 + index); + if(m_spectrumVis != NULL) + m_spectrumVis->configure(m_messageQueue, m_fftSize, m_fftOverlap, (FFTWindow::Function)m_fftWindow); +} + +void GLSpectrumGUI::on_refLevel_currentIndexChanged(int index) +{ + m_refLevel = 0 - index * 5; + if(m_glSpectrum != NULL) + m_glSpectrum->setReferenceLevel(m_refLevel); +} + +void GLSpectrumGUI::on_levelRange_currentIndexChanged(int index) +{ + m_powerRange = 100 - index * 5; + if(m_glSpectrum != NULL) + m_glSpectrum->setPowerRange(m_powerRange); +} + +void GLSpectrumGUI::on_decay_currentIndexChanged(int index) +{ + m_decay = index - 2; + if(m_glSpectrum != NULL) + m_glSpectrum->setDecay(m_decay); +} + +void GLSpectrumGUI::on_waterfall_toggled(bool checked) +{ + m_displayWaterfall = checked; + if(m_glSpectrum != NULL) + m_glSpectrum->setDisplayWaterfall(m_displayWaterfall); +} + +void GLSpectrumGUI::on_histogram_toggled(bool checked) +{ + m_displayHistogram = checked; + if(m_glSpectrum != NULL) + m_glSpectrum->setDisplayHistogram(m_displayHistogram); +} + +void GLSpectrumGUI::on_maxHold_toggled(bool checked) +{ + m_displayMaxHold = checked; + if(m_glSpectrum != NULL) + m_glSpectrum->setDisplayMaxHold(m_displayMaxHold); +} + +void GLSpectrumGUI::on_invert_toggled(bool checked) +{ + m_invert = checked; + if(m_glSpectrum != NULL) + m_glSpectrum->setInvertedWaterfall(m_invert); +} + +void GLSpectrumGUI::on_grid_toggled(bool checked) +{ + m_displayGrid = checked; + if(m_glSpectrum != NULL) + m_glSpectrum->setDisplayGrid(m_displayGrid); +} diff --git a/sdrbase/gui/glspectrumgui.ui b/sdrbase/gui/glspectrumgui.ui new file mode 100644 index 000000000..2a9babe02 --- /dev/null +++ b/sdrbase/gui/glspectrumgui.ui @@ -0,0 +1,476 @@ + + + GLSpectrumGUI + + + + 0 + 0 + 215 + 94 + + + + Oscilloscope + + + + 2 + + + 3 + + + + + + 0 + 0 + + + + Window + + + + + + + + 0 + 0 + + + + FFT Size + + + + + + + + 0 + 0 + + + + Ref (dB) + + + + + + + + 0 + 0 + + + + Range (dB) + + + + + + + + 0 + 0 + + + + FFT window function + + + QComboBox::AdjustToContents + + + + Bartlett + + + + + Blackman-Harris + + + + + Flat Top + + + + + Hamming + + + + + Hanning + + + + + Rectangle + + + + + + + + + 0 + 0 + + + + FFT window function + + + QComboBox::AdjustToContents + + + + 128 + + + + + 256 + + + + + 512 + + + + + 1024 + + + + + 2048 + + + + + 4096 + + + + + + + + + 0 + 0 + + + + FFT window function + + + QComboBox::AdjustToContents + + + + + + + + 0 + 0 + + + + FFT window function + + + QComboBox::AdjustToContents + + + + + + + + 0 + 0 + + + + Decay + + + + + + + + 0 + 0 + + + + FFT window function + + + 0 + + + QComboBox::AdjustToContents + + + + -2 + + + + + -1 + + + + + normal + + + + + +1 + + + + + +2 + + + + + + + + 3 + + + + + Qt::Horizontal + + + + 0 + 0 + + + + + + + + + 0 + 0 + + + + + 24 + 24 + + + + Display waterfall + + + Waterfall + + + + :/waterfall.png:/waterfall.png + + + + 16 + 16 + + + + true + + + + + + + + 0 + 0 + + + + + 24 + 24 + + + + Display phosphor effect spectrum + + + Histogram + + + + :/histogram.png:/histogram.png + + + + 16 + 16 + + + + true + + + + + + + + 0 + 0 + + + + + 24 + 24 + + + + Display live spectrum + + + Max Hold + + + + :/maxhold.png:/maxhold.png + + + + 16 + 16 + + + + true + + + + + + + + 0 + 0 + + + + + 24 + 24 + + + + Exchange waterfall and histogram + + + Inv + + + + :/invertspectrum.png:/invertspectrum.png + + + + 16 + 16 + + + + true + + + + + + + + 0 + 0 + + + + + 24 + 24 + + + + Toggle the scale grid + + + Grid + + + + :/grid.png:/grid.png + + + + 16 + 16 + + + + true + + + + + + + + + + ButtonSwitch + QToolButton +
gui/buttonswitch.h
+
+
+ + fftWindow + fftSize + refLevel + levelRange + decay + waterfall + histogram + maxHold + invert + grid + + + + + +
diff --git a/sdrbase/gui/indicator.cpp b/sdrbase/gui/indicator.cpp new file mode 100644 index 000000000..d303578d2 --- /dev/null +++ b/sdrbase/gui/indicator.cpp @@ -0,0 +1,56 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include "gui/indicator.h" + +void Indicator::paintEvent(QPaintEvent*) +{ + QPainter painter(this); + + painter.setPen(Qt::black); + painter.setBrush(m_color); + + painter.drawRect(0, 0, 18, 15); + painter.drawText(0, 0, 19, 16, Qt::AlignCenter | Qt::AlignHCenter, m_text); +} + +QSize Indicator::sizeHint() const +{ + return QSize(20, 16); +} + +Indicator::Indicator(const QString& text, QWidget* parent) : + QWidget(parent), + m_color(Qt::gray), + m_text(text) +{ + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + + QFont f = font(); + f.setBold(true); + f.setPixelSize(8); + setFont(f); +} + +void Indicator::setColor(const QColor& color) +{ + if(m_color != color) { + m_color = color; + update(); + } +} diff --git a/sdrbase/gui/pluginsdialog.cpp b/sdrbase/gui/pluginsdialog.cpp new file mode 100644 index 000000000..551456ff2 --- /dev/null +++ b/sdrbase/gui/pluginsdialog.cpp @@ -0,0 +1,42 @@ +#include "gui/pluginsdialog.h" +#include "mainwindow.h" +#include "ui_pluginsdialog.h" + +PluginsDialog::PluginsDialog(PluginManager* pluginManager, QWidget* parent) : + QDialog(parent), + ui(new Ui::PluginsDialog) +{ + ui->setupUi(this); + + const PluginManager::Plugins& plugins = pluginManager->getPlugins(); + for(PluginManager::Plugins::const_iterator it = plugins.constBegin(); it != plugins.constEnd(); ++it) { + QStringList sl; + const PluginDescriptor& desc = it->plugin->getPluginDescriptor(); + sl.append(desc.displayedName); + sl.append(desc.version); + if(desc.licenseIsGPL) + sl.append(tr("YES")); + else sl.append("no"); + QTreeWidgetItem* pluginItem = new QTreeWidgetItem(ui->tree, sl); + sl.clear(); + sl.append(tr("Copyright: %1").arg(desc.copyright)); + QTreeWidgetItem* item = new QTreeWidgetItem(pluginItem, sl); + item->setFirstColumnSpanned(true); + sl.clear(); + sl.append(tr("Website: %1").arg(desc.website)); + item = new QTreeWidgetItem(pluginItem, sl); + item->setFirstColumnSpanned(true); + sl.clear(); + sl.append(tr("Source Code: %1").arg(desc.sourceCodeURL)); + item = new QTreeWidgetItem(pluginItem, sl); + item->setFirstColumnSpanned(true); + } + ui->tree->resizeColumnToContents(0); + ui->tree->resizeColumnToContents(1); + ui->tree->resizeColumnToContents(2); +} + +PluginsDialog::~PluginsDialog() +{ + delete ui; +} diff --git a/sdrbase/gui/pluginsdialog.ui b/sdrbase/gui/pluginsdialog.ui new file mode 100644 index 000000000..de2ad4976 --- /dev/null +++ b/sdrbase/gui/pluginsdialog.ui @@ -0,0 +1,67 @@ + + + PluginsDialog + + + + 0 + 0 + 400 + 300 + + + + Loaded Plugins + + + + + + + Name + + + + + Version + + + + + GPL + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Ok + + + + + + + + + buttonBox + accepted() + PluginsDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + diff --git a/sdrbase/gui/preferencesdialog.cpp b/sdrbase/gui/preferencesdialog.cpp new file mode 100644 index 000000000..077ef451b --- /dev/null +++ b/sdrbase/gui/preferencesdialog.cpp @@ -0,0 +1,55 @@ +#include +#include "gui/preferencesdialog.h" +#include "ui_preferencesdialog.h" +#include "audio/audiodeviceinfo.h" + +PreferencesDialog::PreferencesDialog(AudioDeviceInfo* audioDeviceInfo, QWidget* parent) : + QDialog(parent), + ui(new Ui::PreferencesDialog), + m_audioDeviceInfo(audioDeviceInfo) +{ + ui->setupUi(this); + + const AudioDeviceInfo::Devices& devices = audioDeviceInfo->getDevices(); + + QTreeWidgetItem* api; + QStringList sl; + sl.append(tr("Default (use first suitable device)")); + api = new QTreeWidgetItem(ui->audioTree, sl, ATDefault); + api->setFirstColumnSpanned(true); + for(AudioDeviceInfo::Devices::const_iterator it = devices.begin(); it != devices.end(); ++it) { + int apiIndex; + sl.clear(); + + for(apiIndex = 0; apiIndex < ui->audioTree->topLevelItemCount(); ++apiIndex) { + if(ui->audioTree->topLevelItem(apiIndex)->text(0) == it->api) + break; + } + if(apiIndex >= ui->audioTree->topLevelItemCount()) { + sl.append(it->api); + api = new QTreeWidgetItem(ui->audioTree, sl, ATInterface); + api->setExpanded(true); + api->setFirstColumnSpanned(true); + sl.clear(); + } else { + api = ui->audioTree->topLevelItem(apiIndex); + } + + sl.append(it->name); + new QTreeWidgetItem(api, sl, ATDevice); + } + if(ui->audioTree->currentItem() == NULL) + ui->audioTree->setCurrentItem(ui->audioTree->topLevelItem(0)); + + ui->tabWidget->setCurrentIndex(0); +} + +PreferencesDialog::~PreferencesDialog() +{ + delete ui; +} + +void PreferencesDialog::accept() +{ + QDialog::accept(); +} diff --git a/sdrbase/gui/preferencesdialog.ui b/sdrbase/gui/preferencesdialog.ui new file mode 100644 index 000000000..054593132 --- /dev/null +++ b/sdrbase/gui/preferencesdialog.ui @@ -0,0 +1,109 @@ + + + PreferencesDialog + + + + 0 + 0 + 400 + 300 + + + + Dialog + + + + + + 0 + + + + Receiver Hardware + + + + + + + 1 + + + + + + + + + Audio Output + + + + + + + Device + + + + + + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + buttonBox + tabWidget + treeWidget + audioTree + + + + + buttonBox + accepted() + PreferencesDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + PreferencesDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/sdrbase/gui/presetitem.cpp b/sdrbase/gui/presetitem.cpp new file mode 100644 index 000000000..4f8f49f55 --- /dev/null +++ b/sdrbase/gui/presetitem.cpp @@ -0,0 +1,29 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "gui/presetitem.h" + +PresetItem::PresetItem(QTreeWidgetItem* parent, const QStringList& strings, quint64 frequency, int type) : + QTreeWidgetItem(parent, strings, type), + m_frequency(frequency) +{ +} + +bool PresetItem::operator<(const QTreeWidgetItem& other) const +{ + return m_frequency < ((const PresetItem&)other).m_frequency; +} diff --git a/sdrbase/gui/rollupwidget.cpp b/sdrbase/gui/rollupwidget.cpp new file mode 100644 index 000000000..dafe315ea --- /dev/null +++ b/sdrbase/gui/rollupwidget.cpp @@ -0,0 +1,348 @@ +#include +#include +#include +#include "gui/rollupwidget.h" +#include "ui_glspectrumgui.h" + +RollupWidget::RollupWidget(QWidget* parent) : + QWidget(parent) +{ + setMinimumSize(250, 150); + setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + setBackgroundRole(QPalette::Window); + + setAutoFillBackground(false); + setAttribute(Qt::WA_OpaquePaintEvent, true); + + m_titleColor = palette().highlight().color(); +} + +QByteArray RollupWidget::saveState(int version) const +{ + QByteArray state; + QDataStream stream(&state, QIODevice::WriteOnly); + int count = 0; + + for(int i = 0; i < children().count(); ++i) { + QWidget* r = qobject_cast(children()[i]); + if(r != NULL) + count++; + } + + stream << VersionMarker; + stream << version; + stream << count; + + for(int i = 0; i < children().count(); ++i) { + QWidget* r = qobject_cast(children()[i]); + if(r != NULL) { + stream << r->objectName(); + if(r->isHidden()) + stream << (int)0; + else stream << (int)1; + } + } + + return state; +} + +bool RollupWidget::restoreState(const QByteArray& state, int version) +{ + if(state.isEmpty()) + return false; + QByteArray sd = state; + QDataStream stream(&sd, QIODevice::ReadOnly); + int marker, v; + stream >> marker; + stream >> v; + if((stream.status() != QDataStream::Ok) || (marker != VersionMarker) || (v != version)) + return false; + + int count; + stream >> count; + + if(stream.status() != QDataStream::Ok) + return false; + for(int i = 0; i < count; ++i) { + QString name; + int visible; + + stream >> name; + stream >> visible; + + if(stream.status() != QDataStream::Ok) + return false; + + for(int j = 0; j < children().count(); ++j) { + QWidget* r = qobject_cast(children()[j]); + if(r != NULL) { + if(r->objectName() == name) { + if(visible) + r->show(); + else r->hide(); + break; + } + } + } + } + + return true; +} + +void RollupWidget::setTitleColor(const QColor& c) +{ + m_titleColor = c; + update(); +} + +int RollupWidget::arrangeRollups() +{ + QFontMetrics fm(font()); + int pos = fm.height() + 4; + + for(int i = 0; i < children().count(); ++i) { + QWidget* r = qobject_cast(children()[i]); + if(r != NULL) { + pos += fm.height() + 2; + if(!r->isHidden()) { + r->move(2, pos + 3); + int h = 0; + if(r->hasHeightForWidth()) + h = r->heightForWidth(width() - 4); + else h = r->sizeHint().height(); + r->resize(width() - 4, h); + pos += r->height() + 5; + } + } + } + setMinimumHeight(pos); + setMaximumHeight(pos); + return pos; +} + +void RollupWidget::paintEvent(QPaintEvent*) +{ + QPainter p(this); + QColor frame = palette().highlight().color(); + + // Eigenbau + QFontMetrics fm(font()); + + p.setRenderHint(QPainter::Antialiasing, true); + + // Ecken + p.setPen(Qt::NoPen); + p.setBrush(palette().base()); + p.drawRect(0, 0, 5, 5); + p.drawRect(width() - 5, 0, 5, 5); + p.drawRect(0, height() - 5, 5, 5); + p.drawRect(width() - 5, height() - 5, 5, 5); + + // Rahmen + p.setPen(frame); + p.setBrush(palette().window()); + QRectF r(rect()); + r.adjust(0.5, 0.5, -0.5, -0.5); + p.drawRoundedRect(r, 3.0, 3.0, Qt::AbsoluteSize); + + // Titel-Hintergrund + p.setPen(Qt::NoPen); + p.setBrush(m_titleColor); + QPainterPath path; + path.moveTo(1.5, fm.height() + 2.5); + path.lineTo(width() - 1.5, fm.height() + 2.5); + path.lineTo(width() - 1.5, 3.5); + path.arcTo(QRectF(width() - 3.5, 0, 2.5, 2.5), 270, -90); + path.lineTo(3.5, 1.5); + path.arcTo(QRectF(1.5, 2.5, 2.5, 2.5), 90, 90); + p.drawPath(path); + + // Titel-Abschlusslinie + p.setPen(frame); + p.drawLine(QPointF(0.5, 2 + fm.height() + 1.5), QPointF(width() - 1.5, 2 + fm.height() + 1.5)); + + // Aktiv-Button links + p.setPen(QPen(palette().windowText().color(), 1.0)); + p.setBrush(palette().light()); + p.drawRoundedRect(QRectF(3.5, 3.5, fm.ascent(), fm.ascent()), 2.0, 2.0, Qt::AbsoluteSize); + + // Schließen-Button rechts + p.setRenderHint(QPainter::Antialiasing, true); + p.setPen(QPen(palette().windowText().color(), 1.0)); + p.setBrush(palette().light()); + r = QRectF(width() - 3.5 - fm.ascent(), 3.5, fm.ascent(), fm.ascent()); + p.drawRoundedRect(r, 2.0, 2.0, Qt::AbsoluteSize); + p.setPen(QPen(palette().windowText().color(), 1.5)); + p.drawLine(r.topLeft() + QPointF(1, 1), r.bottomRight() + QPointF(-1, -1)); + p.drawLine(r.bottomLeft() + QPointF(1, -1), r.topRight() + QPointF(-1, 1)); + + // Titel + p.setPen(palette().highlightedText().color()); + p.drawText(QRect(2 + fm.height(), 2, width() - 4 - 2 * fm.height(), fm.height()), + fm.elidedText(windowTitle(), Qt::ElideMiddle, width() - 4 - 2 * fm.height(), 0)); + + // Rollups + int pos = fm.height() + 4; + + const QObjectList& c = children(); + QObjectList::ConstIterator w = c.begin(); + QObjectList::ConstIterator n = c.begin(); + + for(n = c.begin(); n != c.end(); ++n) { + if(qobject_cast(*n) != NULL) + break; + } + for(w = n; w != c.end(); w = n) { + if(n != c.end()) + ++n; + for(; n != c.end(); ++n) { + if(qobject_cast(*n) != NULL) + break; + } + pos += paintRollup(qobject_cast(*w), pos, &p, n == c.end(), frame); + } +} + +int RollupWidget::paintRollup(QWidget* rollup, int pos, QPainter* p, bool last, const QColor& frame) +{ + QFontMetrics fm(font()); + int height = 1; + + // Titel-Abschlusslinie + if(!rollup->isHidden()) { + p->setPen(palette().dark().color()); + p->drawLine(QPointF(1.5, pos + fm.height() + 1.5), QPointF(width() - 1.5, pos + fm.height() + 1.5)); + p->setPen(palette().light().color()); + p->drawLine(QPointF(1.5, pos + fm.height() + 2.5), QPointF(width() - 1.5, pos + fm.height() + 2.5)); + height += 2; + } else { + if(!last) { + p->setPen(frame); + p->drawLine(QPointF(1.5, pos + fm.height() + 1.5), QPointF(width() - 1.5, pos + fm.height() + 1.5)); + height++; + } + } + + // Titel + p->setPen(palette().windowText().color()); + p->drawText(QRect(2 + fm.height(), pos, width() - 4 - fm.height(), fm.height()), + fm.elidedText(rollup->windowTitle(), Qt::ElideMiddle, width() - 4 - fm.height(), 0)); + height += fm.height(); + + // Ausklapp-Icon + p->setPen(palette().windowText().color()); + p->setBrush(palette().windowText()); + if(!rollup->isHidden()) { + QPolygonF a; + a.append(QPointF(3.5, pos + 2)); + a.append(QPointF(3.5 + fm.ascent(), pos + 2)); + a.append(QPointF(3.5 + fm.ascent() / 2.0, pos + fm.height() - 2)); + p->drawPolygon(a); + } else { + QPolygonF a; + a.append(QPointF(3.5, pos + 2)); + a.append(QPointF(3.5, pos + fm.height() - 2)); + a.append(QPointF(3.5 + fm.ascent(), pos + fm.height() / 2)); + p->drawPolygon(a); + } + + // Inhalt + if(!rollup->isHidden() && (!last)) { + // Rollup-Abschlusslinie + p->setPen(frame); + p->drawLine(QPointF(1.5, pos + fm.height() + rollup->height() + 6.5), + QPointF(width() - 1.5, pos + fm.height() + rollup->height() + 6.5)); + height += rollup->height() + 4; + } + + return height; +} + +void RollupWidget::resizeEvent(QResizeEvent* size) +{ + arrangeRollups(); + QWidget::resizeEvent(size); +} + +void RollupWidget::mousePressEvent(QMouseEvent* event) +{ + QFontMetrics fm(font()); + + // menu box left + if(QRectF(3.5, 3.5, fm.ascent(), fm.ascent()).contains(event->pos())) { + emit customContextMenuRequested(event->pos()); + return; + } + + // close button right + if(QRectF(width() - 3.5 - fm.ascent(), 3.5, fm.ascent(), fm.ascent()).contains(event->pos())) { + close(); + return; + } + + // check if we need to change a rollup widget + int pos = fm.height() + 4; + for(int i = 0; i < children().count(); ++i) { + QWidget* r = qobject_cast(children()[i]); + if(r != NULL) { + if((event->y() >= pos) && (event->y() < (pos + fm.height() + 3))) { + if(r->isHidden()) { + r->show(); + //emit widgetRolled(r, true); + } else { + r->hide(); + //emit widgetRolled(r, false); + } + arrangeRollups(); + repaint(); + return; + } else { + pos += fm.height() + 2; + if(!r->isHidden()) + pos += r->height() + 5; + } + } + } +} + +void RollupWidget::mouseDoubleClickEvent(QMouseEvent* event) +{ + QFontMetrics fm(font()); + + // menu box left + if(QRectF(3.5, 3.5, fm.ascent(), fm.ascent()).contains(event->pos())) { + emit menuDoubleClickEvent(); + return; + } +} + +bool RollupWidget::event(QEvent* event) +{ + if(event->type() == QEvent::ChildAdded) { + ((QChildEvent*)event)->child()->installEventFilter(this); + arrangeRollups(); + } else if(event->type() == QEvent::ChildRemoved) { + ((QChildEvent*)event)->child()->removeEventFilter(this); + arrangeRollups(); + } + return QWidget::event(event); +} + +bool RollupWidget::eventFilter(QObject* object, QEvent* event) +{ + if(event->type() == QEvent::Show) { + if(children().contains(object)) { + arrangeRollups(); + emit widgetRolled(qobject_cast(object), true); + } + } else if(event->type() == QEvent::Hide) { + if(children().contains(object)) { + arrangeRollups(); + emit widgetRolled(qobject_cast(object), false); + } + } else if(event->type() == QEvent::WindowTitleChange) { + if(children().contains(object)) + repaint(); + } + return QWidget::eventFilter(object, event); +} diff --git a/sdrbase/gui/scale.cpp b/sdrbase/gui/scale.cpp new file mode 100644 index 000000000..5e456bacd --- /dev/null +++ b/sdrbase/gui/scale.cpp @@ -0,0 +1,129 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include "gui/scale.h" + +Scale::Scale(QWidget* parent) : + QWidget(parent) +{ +} + +void Scale::setOrientation(Qt::Orientation orientation) +{ + m_orientation = orientation; + m_scaleEngine.setOrientation(orientation); + m_scaleEngine.setFont(font()); + QFontMetrics fm(font()); + switch(m_orientation) { + case Qt::Horizontal: + m_scaleEngine.setSize(width()); + setMinimumWidth(0); + setMaximumWidth(QWIDGETSIZE_MAX); + setMinimumHeight(3 + fontMetrics().ascent()); + setMaximumHeight(3 + fontMetrics().ascent()); + break; + case Qt::Vertical: + m_scaleEngine.setSize(height()); + setMinimumWidth(30); + setMaximumWidth(30); + setMinimumHeight(0); + setMaximumHeight(QWIDGETSIZE_MAX); + break; + } +} + +void Scale::setRange(Unit::Physical physicalUnit, float rangeMin, float rangeMax) +{ + m_scaleEngine.setRange(physicalUnit, rangeMin, rangeMax); + update(); +} + +void Scale::paintEvent(QPaintEvent*) +{ + QPainter painter(this); + const ScaleEngine::TickList& tickList = m_scaleEngine.getTickList(); + QFontMetricsF fontMetrics(font()); + const ScaleEngine::Tick* tick; + int i; + float bottomLine; + + switch(m_orientation) { + case Qt::Horizontal: { + painter.setPen(Qt::black); + + // Zwischenlinien für x-Achse zeichnen + for(i = 0; i < tickList.count(); i++) { + tick = &tickList[i]; + if(!tick->major) + painter.drawLine(QLineF(tick->pos, 0, tick->pos, 1)); + } + + // Skala am Rand zeichnen + painter.drawLine(QLineF(0, 0, width() - 1, 0)); + + // Hauptlinien und Beschriftung für x-Achse zeichnen + for(i = 0; i < tickList.count(); i++) { + tick = &tickList[i]; + if(tick->major) { + painter.drawLine(QLineF(tick->pos - 1, 0, tick->pos - 1, 3)); + if(tick->textSize > 0) { + painter.drawText(QPointF(tick->textPos, 3 + fontMetrics.ascent()), tick->text); + } + } + } + break; + } + case Qt::Vertical: { + bottomLine = height() - 1; + painter.setPen(Qt::black); + + // Zwischenlinien für y-Achse zeichnen + for(i = 0; i < tickList.count(); i++) { + tick = &tickList[i]; + if(!tick->major) + painter.drawLine(QLineF(width() - 2, bottomLine - tick->pos, width() - 1, bottomLine - tick->pos)); + } + + // Skala am Rand zeichnen + painter.drawLine(QLineF(width() - 1, 0, width() - 1, height() - 1)); + + // Hauptlinien und Beschriftung für y-Achse zeichnen + for(i = 0; i < tickList.count(); i++) { + tick = &tickList[i]; + if(tick->major) { + painter.drawLine(QLineF(width() - 4, bottomLine - tick->pos, width() - 1, bottomLine - tick->pos)); + if(tick->textSize > 0) + painter.drawText(QPointF(width() - 4 - tick->textSize, bottomLine - tick->textPos), tick->text); + } + } + + } + } +} + +void Scale::resizeEvent(QResizeEvent*) +{ + switch(m_orientation) { + case Qt::Horizontal: + m_scaleEngine.setSize(width()); + break; + case Qt::Vertical: + m_scaleEngine.setSize(height()); + break; + } +} diff --git a/sdrbase/gui/scaleengine.cpp b/sdrbase/gui/scaleengine.cpp new file mode 100644 index 000000000..06bde3647 --- /dev/null +++ b/sdrbase/gui/scaleengine.cpp @@ -0,0 +1,569 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include "gui/scaleengine.h" + +/* +static double trunc(double d) +{ + return (d > 0) ? floor(d) : ceil(d); +} +*/ + +QString ScaleEngine::formatTick(double value, int decimalPlaces, bool fancyTime) +{ + if((m_physicalUnit != Unit::Time) || (!fancyTime) || 1) { + return QString("%1").arg(value, 0, 'f', decimalPlaces); + } else { + QString str; + double orig = fabs(value); + double tmp; + + if(orig >= 86400.0) { + tmp = floor(value / 86400.0); + str = QString("%1.").arg(tmp, 0, 'f', 0); + value -= tmp * 86400.0; + if(value < 0.0) + value *= -1.0; + } + + if(orig >= 3600.0) { + tmp = floor(value / 3600.0); + str += QString("%1:").arg(tmp, 2, 'f', 0, QChar('0')); + value -= tmp * 3600.0; + if(value < 0.0) + value *= -1.0; + } + + if(orig >= 60.0) { + tmp = floor(value / 60.0); + str += QString("%1:").arg(tmp, 2, 'f', 0, QChar('0')); + value -= tmp * 60.0; + if(value < 0.0) + value *= -1.0; + } + + tmp = value; + str += QString("%1").arg(tmp, 2, 'f', decimalPlaces, QChar('0')); + + return str; + } +} + +void ScaleEngine::calcCharSize() +{ + QFontMetricsF fontMetrics(m_font); + + if(m_orientation == Qt::Vertical) { + m_charSize = fontMetrics.height(); + } else { + QString str("012345679.,-"); + int i; + float size; + float max = 0.0f; + for(i = 0; i < str.length(); i++) { + size = fontMetrics.width(QString(str[i])); + if(size > max) + max = size; + } + m_charSize = max; + } +} + +void ScaleEngine::calcScaleFactor() +{ + double median; + + median = ((m_rangeMax - m_rangeMin) / 2.0) + m_rangeMin; + m_scale = 1.0; + + switch(m_physicalUnit) { + case Unit::None: + m_unitStr.clear(); + break; + + case Unit::Frequency: + if(median < 1000.0) { + m_unitStr = QObject::tr("Hz"); + } else if(median < 1000000.0) { + m_unitStr = QObject::tr("kHz"); + m_scale = 1000.0; + } else if(median < 1000000000.0) { + m_unitStr = QObject::tr("MHz"); + m_scale = 1000000.0; + } else if(median < 1000000000000.0){ + m_unitStr = QObject::tr("GHz"); + m_scale = 1000000000.0; + } else { + m_unitStr = QObject::tr("THz"); + m_scale = 1000000000000.0; + } + break; + + case Unit::Information: + if(median < 1024.0) { + m_unitStr = QObject::tr("Bytes"); + } else if(median < 1048576.0) { + m_unitStr = QObject::tr("KiBytes"); + m_scale = 1024.0; + } else if(median < 1073741824.0) { + m_unitStr = QObject::tr("MiBytes"); + m_scale = 1048576.0; + } else if(median < 1099511627776.0) { + m_unitStr = QObject::tr("GiBytes"); + m_scale = 1073741824.0; + } else if(median < 1125899906842624.0) { + m_unitStr = QObject::tr("TiBytes"); + m_scale = 1099511627776.0; + } else { + m_unitStr = QObject::tr("PiBytes"); + m_scale = 1125899906842624.0; + } + break; + + case Unit::Percent: + m_unitStr = QString("%"); + break; + + case Unit::Decibel: + m_unitStr = QString("dB"); + break; + + case Unit::DecibelMilliWatt: + m_unitStr = QString("dBm"); + break; + + case Unit::DecibelMicroVolt: + m_unitStr = QString("dBµV"); + break; + + case Unit::AngleDegrees: + m_unitStr = QString("°"); + + case Unit::Time: + if(median < 0.001) { + m_unitStr = QString("µs"); + m_scale = 0.000001; + } else if(median < 1.0) { + m_unitStr = QString("ms"); + m_scale = 0.001; + } else { + m_unitStr = QString("s"); + } + break; + } +} + +double ScaleEngine::calcMajorTickUnits(double distance, int* retDecimalPlaces) +{ + double sign; + double log10x; + double exponent; + double base; + int decimalPlaces; + + if(distance == 0.0) + return 0.0; + + sign = (distance > 0.0) ? 1.0 : -1.0; + log10x = log10(fabs(distance)); + exponent = floor(log10x); + base = pow(10.0, log10x - exponent); + decimalPlaces = (int)(-exponent); +/* + if((m_physicalUnit == Unit::Time) && (distance >= 1.0)) { + if(retDecimalPlaces != NULL) + *retDecimalPlaces = 0; + if(distance < 1.0) + return 1.0; + else if(distance < 5.0) + return 5.0; + else if(distance < 10.0) + return 10.0; + else if(distance < 15.0) + return 15.0; + else if(distance < 30.0) + return 30.0; + else if(distance < 60.0) + return 60.0; + else if(distance < 5.0 * 60.0) + return 5.0 * 60.0; + else if(distance < 10.0 * 60.0) + return 10.0 * 60.0; + else if(distance < 15.0 * 60.0) + return 15.0 * 60.0; + else if(distance < 30.0 * 60.0) + return 30.0 * 60.0; + else if(distance < 3600.0) + return 3600.0; + else if(distance < 2.0 * 3600.0) + return 2.0 * 3600.0; + else if(distance < 3.0 * 3600.0) + return 3.0 * 3600.0; + else if(distance < 6.0 * 3600.0) + return 6.0 * 3600.0; + else if(distance < 12.0 * 3600.0) + return 12.0 * 3600.0; + else if(distance < 86000.0) + return 86000.0; + else if(distance < 2.0 * 86000.0) + return 2.0 * 86000.0; + else if(distance < 7.0 * 86000.0) + return 7.0 * 86000.0; + else if(distance < 10.0 * 86000.0) + return 10.0 * 86000.0; + else if(distance < 30.0 * 86000.0) + return 30.0 * 86000.0; + else return 90.0 * 86000.0; + } else {*/ + if(base <= 1.0) { + base = 1.0; + } else if(base <= 2.0) { + base = 2.0; + } else if(base <= 2.5) { + base = 2.5; + if(decimalPlaces >= 0) + decimalPlaces++; + } else if(base <= 5.0) { + base = 5.0; + } else { + base = 10.0; + }/* + }*/ + + if(retDecimalPlaces != NULL) { + if(decimalPlaces < 0) + decimalPlaces = 0; + *retDecimalPlaces = decimalPlaces; + } + + return sign * base * pow(10.0, exponent); +} + +int ScaleEngine::calcTickTextSize() +{ + int tmp; + int tickLen; + int decimalPlaces; + + tickLen = 1; + tmp = formatTick(m_rangeMin / m_scale, 0).length(); + if(tmp > tickLen) + tickLen = tmp; + tmp = formatTick(m_rangeMax / m_scale, 0).length(); + if(tmp > tickLen) + tickLen = tmp; + + calcMajorTickUnits((m_rangeMax - m_rangeMin) / m_scale, &decimalPlaces); + + return tickLen + decimalPlaces + 1; +} + +void ScaleEngine::forceTwoTicks() +{ + Tick tick; + QFontMetricsF fontMetrics(m_font); + + m_tickList.clear(); + tick.major = true; + + tick.pos = getPosFromValue(m_rangeMin); + tick.text = formatTick(m_rangeMin / m_scale, m_decimalPlaces); + tick.textSize = fontMetrics.boundingRect(tick.text).width(); + if(m_orientation == Qt::Vertical) + tick.textPos = tick.pos - fontMetrics.ascent() / 2; + else tick.textPos = tick.pos - fontMetrics.boundingRect(tick.text).width() / 2; + m_tickList.append(tick); + + tick.pos = getPosFromValue(m_rangeMax); + tick.text = formatTick(m_rangeMax / m_scale, m_decimalPlaces); + tick.textSize = fontMetrics.boundingRect(tick.text).width(); + if(m_orientation == Qt::Vertical) + tick.textPos = tick.pos - fontMetrics.ascent() / 2; + else tick.textPos = tick.pos - fontMetrics.boundingRect(tick.text).width() / 2; + m_tickList.append(tick); +} + +void ScaleEngine::reCalc() +{ + float majorTickSize; + double rangeMinScaled; + double rangeMaxScaled; + int maxNumMajorTicks; + int numMajorTicks; + int step; + int skip; + double value; + double value2; + int i; + int j; + Tick tick; + float pos; + QString str; + QFontMetricsF fontMetrics(m_font); + float endPos; + float lastEndPos; + bool done; + + if(!m_recalc) + return; + m_recalc = false; + + m_tickList.clear(); + + calcScaleFactor(); + rangeMinScaled = m_rangeMin / m_scale; + rangeMaxScaled = m_rangeMax / m_scale; + + if(m_orientation == Qt::Vertical) { + maxNumMajorTicks = (int)(m_size / (fontMetrics.lineSpacing() * 1.3f)); + } else { + majorTickSize = (calcTickTextSize() + 2) * m_charSize; + if(majorTickSize != 0.0) + maxNumMajorTicks = (int)(m_size / majorTickSize); + else maxNumMajorTicks = 20; + } + + m_majorTickValueDistance = calcMajorTickUnits((rangeMaxScaled - rangeMinScaled) / maxNumMajorTicks, &m_decimalPlaces); + numMajorTicks = (int)((rangeMaxScaled - rangeMinScaled) / m_majorTickValueDistance); + + if(numMajorTicks == 0) { + forceTwoTicks(); + return; + } + + if(maxNumMajorTicks > 0) + m_numMinorTicks = (int)(m_size / (maxNumMajorTicks * fontMetrics.height())); + else m_numMinorTicks = 0; + if(m_numMinorTicks < 1) + m_numMinorTicks = 0; + else if(m_numMinorTicks < 2) + m_numMinorTicks = 1; + else if(m_numMinorTicks < 5) + m_numMinorTicks = 2; + else if(m_numMinorTicks < 10) + m_numMinorTicks = 5; + else m_numMinorTicks = 10; + + m_firstMajorTickValue = floor(rangeMinScaled / m_majorTickValueDistance) * m_majorTickValueDistance; + + skip = 0; + + if(rangeMinScaled == rangeMaxScaled) + return; + + while(true) { + m_tickList.clear(); + + step = 0; + lastEndPos = -100000000; + done = true; + + for(i = 0; true; i++) { + value = majorTickValue(i); + + for(j = 1; j < m_numMinorTicks; j++) { + value2 = value + minorTickValue(j); + if(value2 < rangeMinScaled) + continue; + if(value2 > rangeMaxScaled) + break; + pos = getPosFromValue((value + minorTickValue(j)) * m_scale); + if((pos >= 0) && (pos < m_size)) { + tick.pos = pos; + tick.major = false; + tick.textPos = -1; + tick.textSize = -1; + tick.text.clear(); + } + m_tickList.append(tick); + } + + pos = getPosFromValue(value * m_scale); + if(pos < 0.0) + continue; + if(pos >= m_size) + break; + + tick.pos = pos; + tick.major = true; + tick.textPos = -1; + tick.textSize = -1; + tick.text.clear(); + + if(step % (skip + 1) != 0) { + m_tickList.append(tick); + step++; + continue; + } + step++; + + str = formatTick(value, m_decimalPlaces); + tick.text = str; + tick.textSize = fontMetrics.boundingRect(tick.text).width(); + if(m_orientation == Qt::Vertical) { + tick.textPos = pos - fontMetrics.ascent() / 2; + endPos = tick.textPos + fontMetrics.ascent(); + } else { + tick.textPos = pos - fontMetrics.boundingRect(tick.text).width() / 2; + endPos = tick.textPos + tick.textSize; + } + + if(lastEndPos >= tick.textPos) { + done = false; + break; + } else { + lastEndPos = endPos; + } + + m_tickList.append(tick); + } + if(done) + break; + skip++; + } + + // make sure we have at least two major ticks with numbers + numMajorTicks = 0; + for(i = 0; i < m_tickList.count(); i++) { + tick = m_tickList.at(i); + if(tick.major) + numMajorTicks++; + } + if(numMajorTicks < 2) + forceTwoTicks(); +} + +double ScaleEngine::majorTickValue(int tick) +{ + return m_firstMajorTickValue + (tick * m_majorTickValueDistance); +} + +double ScaleEngine::minorTickValue(int tick) +{ + if(m_numMinorTicks < 1) + return 0.0; + return (m_majorTickValueDistance * tick) / m_numMinorTicks; +} + +ScaleEngine::ScaleEngine() : + m_orientation(Qt::Horizontal), + m_physicalUnit(Unit::None), + m_rangeMin(-1.0), + m_rangeMax(1.0), + m_recalc(true) +{ +} + +void ScaleEngine::setOrientation(Qt::Orientation orientation) +{ + m_orientation = orientation; + m_recalc = true; +} + +void ScaleEngine::setFont(const QFont& font) +{ + m_font = font; + m_recalc = true; + calcCharSize(); +} + +void ScaleEngine::setSize(float size) +{ + if(size > 0.0f) { + m_size = size; + } else { + m_size = 1.0f; + } + m_recalc = true; +} + +void ScaleEngine::setRange(Unit::Physical physicalUnit, float rangeMin, float rangeMax) +{ + double tmpRangeMin; + double tmpRangeMax; +/* + if(rangeMin < rangeMax) { + tmpRangeMin = rangeMin; + tmpRangeMax = rangeMax; + } else if(rangeMin > rangeMax) { + tmpRangeMin = rangeMax; + tmpRangeMax = rangeMin; + } else { + tmpRangeMin = rangeMin * 0.99; + tmpRangeMax = rangeMin * 1.01 + 0.01; + } +*/ + tmpRangeMin = rangeMin; + tmpRangeMax = rangeMax; + + if((tmpRangeMin != m_rangeMin) || (tmpRangeMax != m_rangeMax) || (m_physicalUnit != physicalUnit)) { + m_physicalUnit = physicalUnit; + m_rangeMin = tmpRangeMin; + m_rangeMax = tmpRangeMax; + m_recalc = true; + } +} + +float ScaleEngine::getPosFromValue(double value) +{ + return ((value - m_rangeMin) / (m_rangeMax - m_rangeMin)) * (m_size - 1.0); +} + +float ScaleEngine::getValueFromPos(double pos) +{ + return ((pos * (m_rangeMax - m_rangeMin)) / (m_size - 1.0)) + m_rangeMin; +} + +const ScaleEngine::TickList& ScaleEngine::getTickList() +{ + reCalc(); + return m_tickList; +} + +QString ScaleEngine::getRangeMinStr() +{ + if(m_unitStr.length() > 0) + return QString("%1 %2").arg(formatTick(m_rangeMin / m_scale, m_decimalPlaces, false)).arg(m_unitStr); + else return QString("%1").arg(formatTick(m_rangeMin / m_scale, m_decimalPlaces, false)); +} + +QString ScaleEngine::getRangeMaxStr() +{ + if(m_unitStr.length() > 0) + return QString("%1 %2").arg(formatTick(m_rangeMax / m_scale, m_decimalPlaces, false)).arg(m_unitStr); + else return QString("%1").arg(formatTick(m_rangeMax / m_scale, m_decimalPlaces, false)); +} + +float ScaleEngine::getScaleWidth() +{ + float max; + float len; + int i; + + reCalc(); + max = 0.0f; + for(i = 0; i < m_tickList.count(); i++) { + len = m_tickList[i].textSize; + if(len > max) + max = len; + } + return max; +} diff --git a/sdrbase/gui/scopewindow.cpp b/sdrbase/gui/scopewindow.cpp new file mode 100644 index 000000000..2f6200f19 --- /dev/null +++ b/sdrbase/gui/scopewindow.cpp @@ -0,0 +1,185 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include "gui/scopewindow.h" +#include "ui_scopewindow.h" +#include "util/simpleserializer.h" + +ScopeWindow::ScopeWindow(DSPEngine* dspEngine, QWidget* parent) : + QWidget(parent), + ui(new Ui::ScopeWindow), + m_sampleRate(0), + m_timeBase(1) +{ + ui->setupUi(this); + ui->scope->setDSPEngine(dspEngine); +} + +ScopeWindow::~ScopeWindow() +{ + delete ui; +} + +void ScopeWindow::setSampleRate(int sampleRate) +{ + m_sampleRate = sampleRate; + on_scope_traceSizeChanged(0); +} + +void ScopeWindow::resetToDefaults() +{ + m_displayData = GLScope::ModeIQ; + m_displayOrientation = Qt::Horizontal; + m_timeBase = 1; + m_timeOffset = 0; + m_amplification = 0; + applySettings(); +} + +QByteArray ScopeWindow::serialize() const +{ + SimpleSerializer s(1); + s.writeS32(1, m_displayData); + s.writeS32(2, m_displayOrientation); + s.writeS32(3, m_timeBase); + s.writeS32(4, m_timeOffset); + s.writeS32(5, m_amplification); + return s.final(); +} + +bool ScopeWindow::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { + d.readS32(1, &m_displayData, GLScope::ModeIQ); + d.readS32(2, &m_displayOrientation, Qt::Horizontal); + d.readS32(3, &m_timeBase, 1); + d.readS32(4, &m_timeOffset, 0); + d.readS32(5, &m_amplification, 0); + if(m_timeBase < 0) + m_timeBase = 1; + applySettings(); + return true; + } else { + resetToDefaults(); + return false; + } +} + +void ScopeWindow::on_amp_valueChanged(int value) +{ + static qreal amps[11] = { 0.2, 0.1, 0.05, 0.02, 0.01, 0.005, 0.002, 0.001, 0.0005, 0.0002, 0.0001 }; + ui->ampText->setText(tr("%1\n/div").arg(amps[value], 0, 'f', 4)); + ui->scope->setAmp(0.2 / amps[value]); + m_amplification = value; +} + +void ScopeWindow::on_scope_traceSizeChanged(int) +{ + qreal t = (ui->scope->getTraceSize() * 0.1 / m_sampleRate) / (qreal)m_timeBase; + if(t < 0.000001) + ui->timeText->setText(tr("%1\nns/div").arg(t * 1000000000.0)); + else if(t < 0.001) + ui->timeText->setText(tr("%1\nµs/div").arg(t * 1000000.0)); + else if(t < 1.0) + ui->timeText->setText(tr("%1\nms/div").arg(t * 1000.0)); + else ui->timeText->setText(tr("%1\ns/div").arg(t * 1.0)); +} + +void ScopeWindow::on_time_valueChanged(int value) +{ + m_timeBase = value; + on_scope_traceSizeChanged(0); + ui->scope->setTimeBase(m_timeBase); +} + +void ScopeWindow::on_timeOfs_valueChanged(int value) +{ + m_timeOffset = value; + ui->scope->setTimeOfsProMill(value); +} + +void ScopeWindow::on_displayMode_currentIndexChanged(int index) +{ + m_displayData = index; + switch(index) { + case 0: // i+q + ui->scope->setMode(GLScope::ModeIQ); + break; + case 1: // mag(lin)+pha + ui->scope->setMode(GLScope::ModeMagLinPha); + break; + case 2: // mag(dB)+pha + ui->scope->setMode(GLScope::ModeMagdBPha); + break; + case 3: // derived1+derived2 + ui->scope->setMode(GLScope::ModeDerived12); + break; + case 4: // clostationary + ui->scope->setMode(GLScope::ModeCyclostationary); + break; + + default: + break; + } +} + +void ScopeWindow::on_horizView_clicked() +{ + m_displayOrientation = Qt::Horizontal; + if(ui->horizView->isChecked()) { + ui->vertView->setChecked(false); + ui->scope->setOrientation(Qt::Horizontal); + } else { + ui->horizView->setChecked(true); + } +} + +void ScopeWindow::on_vertView_clicked() +{ + m_displayOrientation = Qt::Vertical; + if(ui->vertView->isChecked()) { + ui->horizView->setChecked(false); + ui->scope->setOrientation(Qt::Vertical); + } else { + ui->vertView->setChecked(true); + ui->scope->setOrientation(Qt::Vertical); + } +} + +void ScopeWindow::applySettings() +{ + ui->displayMode->setCurrentIndex(m_displayData); + if(m_displayOrientation == Qt::Horizontal) { + ui->scope->setOrientation(Qt::Horizontal); + ui->horizView->setChecked(true); + ui->vertView->setChecked(false); + } else { + ui->scope->setOrientation(Qt::Vertical); + ui->horizView->setChecked(false); + ui->vertView->setChecked(true); + } + ui->time->setValue(m_timeBase); + ui->timeOfs->setValue(m_timeOffset); + ui->amp->setValue(m_amplification); +} diff --git a/sdrbase/gui/scopewindow.ui b/sdrbase/gui/scopewindow.ui new file mode 100644 index 000000000..d521af357 --- /dev/null +++ b/sdrbase/gui/scopewindow.ui @@ -0,0 +1,320 @@ + + + ScopeWindow + + + + 0 + 0 + 798 + 149 + + + + Oscilloscope + + + + 3 + + + 0 + + + + + + 0 + 0 + + + + + 32 + 32 + + + + + + + + 3 + + + 2 + + + + + Data + + + + + + + + 0 + 0 + + + + QComboBox::AdjustToContentsOnFirstShow + + + + I+Q Level (linear) + + + + + Magnitude (linear) + Phase + + + + + Magnitude (dB) + Phase + + + + + Derived 1st + 2nd order + + + + + Cyclostationary + + + + + + + + Qt::Vertical + + + + + + + 0 + + + + + Horizontal display arrangement + + + + + + + :/horizontal.png:/horizontal.png + + + + 16 + 16 + + + + true + + + true + + + + + + + Vertical display arrangement + + + + + + + :/vertical.png:/vertical.png + + + + 16 + 16 + + + + true + + + + + + + + + Qt::Vertical + + + + + + + Time + + + + + + + + 0 + 0 + + + + 1 + + + 100 + + + 5 + + + Qt::Horizontal + + + QSlider::TicksBelow + + + 5 + + + + + + + + 40 + 0 + + + + 0.1000 +/div + + + Qt::AlignCenter + + + + + + + + 0 + 0 + + + + 0 + + + 1000 + + + 10 + + + Qt::Horizontal + + + QSlider::NoTicks + + + 50 + + + + + + + Qt::Vertical + + + + + + + Amp + + + + + + + + 0 + 0 + + + + 0 + + + 8 + + + 1 + + + 0 + + + Qt::Horizontal + + + QSlider::TicksBelow + + + 1 + + + + + + + + 40 + 0 + + + + 0.2000 +/div + + + Qt::AlignCenter + + + + + + + + + + GLScope + QWidget +
gui/glscope.h
+ 1 +
+
+ + + + +
diff --git a/sdrbase/gui/valuedial.cpp b/sdrbase/gui/valuedial.cpp new file mode 100644 index 000000000..79268fc79 --- /dev/null +++ b/sdrbase/gui/valuedial.cpp @@ -0,0 +1,427 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include +#include "gui/valuedial.h" + +ValueDial::ValueDial(QWidget* parent) : + QWidget(parent), + m_animationState(0) +{ + setAutoFillBackground(false); + setAttribute(Qt::WA_OpaquePaintEvent, true); + setAttribute(Qt::WA_NoSystemBackground, true); + setMouseTracking(true); + setFocusPolicy(Qt::StrongFocus); + + m_background.setStart(0, 0); + m_background.setFinalStop(0, 1); + m_background.setCoordinateMode(QGradient::ObjectBoundingMode); + + m_background.setColorAt(0.0, QColor(0x40, 0x40, 0x40)); + m_background.setColorAt(0.1, QColor(0xc0, 0xc0, 0xc0)); + m_background.setColorAt(0.2, QColor(0xf0, 0xf0, 0xf0)); + m_background.setColorAt(0.5, QColor(0xff, 0xff, 0xff)); + m_background.setColorAt(0.8, QColor(0xd0, 0xd0, 0xd0)); + m_background.setColorAt(0.9, QColor(0xa0, 0xa0, 0xa0)); + m_background.setColorAt(1.0, QColor(0x40, 0x40, 0x40)); + + m_value = 0; + m_valueMin = 0; + m_valueMax = 2200000; + m_numDigits = 7; + m_numDecimalPoints = m_numDigits / 3; + m_cursor = -1; + + m_hightlightedDigit = -1; + m_text = formatText(m_value); + m_cursorState = false; + + connect(&m_animationTimer, SIGNAL(timeout()), this, SLOT(animate())); + connect(&m_blinkTimer, SIGNAL(timeout()), this, SLOT(blink())); +} + +void ValueDial::setFont(const QFont& font) +{ + QWidget::setFont(font); + + QFontMetrics fm(font); + m_digitWidth = fm.width('0'); + m_digitHeight = fm.ascent(); + if(m_digitWidth < m_digitHeight) + m_digitWidth = m_digitHeight; + setFixedWidth((m_numDigits + m_numDecimalPoints) * m_digitWidth + 2); + setFixedHeight(m_digitHeight * 2 + 2); +} + +void ValueDial::setValue(quint64 value) +{ + m_valueNew = value; + if(m_valueNew < m_valueMin) + m_valueNew = m_valueMin; + else if(m_valueNew > m_valueMax) + m_valueNew = m_valueMax; + if(m_valueNew < m_value) + m_animationState = 1; + else if(m_valueNew > m_value) + m_animationState = -1; + else return; + m_animationTimer.start(20); + m_textNew = formatText(m_valueNew); +} + +void ValueDial::setValueRange(uint numDigits, quint64 min, quint64 max) +{ + m_numDigits = numDigits; + m_numDecimalPoints = m_numDigits / 3; + + m_valueMin = min; + m_valueMax = max; + + if(m_value < min) + setValue(min); + else if(m_value > max) + setValue(max); + setFixedWidth((m_numDigits + m_numDecimalPoints) * m_digitWidth + 2); +} + +quint64 ValueDial::findExponent(int digit) +{ + quint64 e = 1; + int d = (m_numDigits + m_numDecimalPoints) - digit; + d = d - (d / 4) - 1; + for(int i = 0; i < d; i++) + e *= 10; + return e; +} + +QChar ValueDial::digitNeigh(QChar c, bool dir) +{ + if(dir) { + if(c == QChar('0')) + return QChar('9'); + else return QChar::fromLatin1(c.toLatin1() - 1); + } else { + if(c == QChar('9')) + return QChar('0'); + else return QChar::fromLatin1(c.toLatin1() + 1); + } +} + +QString ValueDial::formatText(quint64 value) +{ + QString str = QString("%1").arg(value, m_numDigits, 10, QChar('0')); + for(int i = 0; i < m_numDecimalPoints; i++) + str.insert(m_numDigits - 3 - 3 * i, "."); + return str; +} + +void ValueDial::paintEvent(QPaintEvent*) +{ + QPainter painter(this); + + painter.setPen(Qt::black); + painter.setBrush(m_background); + + painter.drawRect(0, 0, width() - 1, height() - 1); + + painter.setPen(QColor(0x20, 0x20, 0x20)); + painter.setBrush(Qt::NoBrush); + for(int i = 1; i < m_numDigits + m_numDecimalPoints; i++) { + painter.setPen(QColor(0x20, 0x20, 0x20)); + painter.drawLine(1 + i * m_digitWidth, 1, 1 + i * m_digitWidth, height() - 1); + painter.setPen(QColor(0x00, 0x00, 0x00, 0x20)); + painter.drawLine(0 + i * m_digitWidth, 1, 0 + i * m_digitWidth, height() - 1); + painter.drawLine(2 + i * m_digitWidth, 1, 2 + i * m_digitWidth, height() - 1); + } + painter.setPen(QColor(0x00, 0x00, 0x00, 0x20)); + painter.drawLine(1, 1, 1, height() - 1); + painter.drawLine(width() - 2, 1, width() - 2, height() - 1); + + if(m_hightlightedDigit >= 0) { + painter.setPen(Qt::NoPen); + painter.setBrush(QColor(0xff, 0x00, 0x00, 0x20)); + painter.drawRect(2 + m_hightlightedDigit * m_digitWidth, 1, m_digitWidth - 1, height() - 1); + } + + if(m_animationState == 0) { + for(int i = 0; i < m_text.length(); i++) { + painter.setClipRect(1 + i * m_digitWidth, 1, m_digitWidth, m_digitHeight * 2); + painter.setPen(QColor(0x10, 0x10, 0x10)); + painter.drawText(QRect(1 + i * m_digitWidth, m_digitHeight * 0.6, m_digitWidth, m_digitHeight), Qt::AlignCenter, m_text.mid(i, 1)); + if(m_text[i] != QChar('.')) { + painter.setPen(QColor(0x00, 0x00, 0x00)); + painter.drawText(QRect(1 + i * m_digitWidth, m_digitHeight * -0.7, m_digitWidth, m_digitHeight), Qt::AlignCenter, digitNeigh(m_text[i], true)); + painter.drawText(QRect(1 + i * m_digitWidth, m_digitHeight * 1.9, m_digitWidth, m_digitHeight), Qt::AlignCenter, digitNeigh(m_text[i], false)); + } + } + painter.setClipping(false); + if((m_cursor >= 0) && (m_cursorState)) { + painter.setPen(Qt::NoPen); + painter.setBrush(QColor(0x10, 0x10, 0x10)); + painter.drawRect(4 + m_cursor * m_digitWidth, 1 + m_digitHeight * 1.5, m_digitWidth - 5, m_digitHeight / 6); + } + } else { + if(m_animationState != 0) { + for(int i = 0; i < m_text.length(); i++) { + if(m_text[i] == m_textNew[i]) { + painter.setClipRect(1 + i * m_digitWidth, 1, m_digitWidth, m_digitHeight * 2); + painter.setPen(QColor(0x10, 0x10, 0x10)); + painter.drawText(QRect(1 + i * m_digitWidth, m_digitHeight * 0.6, m_digitWidth, m_digitHeight), Qt::AlignCenter, m_text.mid(i, 1)); + if(m_text[i] != QChar('.')) { + painter.setPen(QColor(0x00, 0x00, 0x00)); + painter.drawText(QRect(1 + i * m_digitWidth, m_digitHeight * -0.7, m_digitWidth, m_digitHeight), Qt::AlignCenter, digitNeigh(m_text[i], true)); + painter.drawText(QRect(1 + i * m_digitWidth, m_digitHeight * 1.9, m_digitWidth, m_digitHeight), Qt::AlignCenter, digitNeigh(m_text[i], false)); + } + } else { + int h = m_digitHeight * 0.6 + m_digitHeight * m_animationState / 2.0; + painter.setClipRect(1 + i * m_digitWidth, 1, m_digitWidth, m_digitHeight * 2); + painter.setPen(QColor(0x10, 0x10, 0x10)); + painter.drawText(QRect(1 + i * m_digitWidth, h, m_digitWidth, m_digitHeight), Qt::AlignCenter, m_text.mid(i, 1)); + if(m_text[i] != QChar('.')) { + painter.setPen(QColor(0x00, 0x00, 0x00)); + painter.drawText(QRect(1 + i * m_digitWidth, h + m_digitHeight * -0.7, m_digitWidth, m_digitHeight), Qt::AlignCenter, digitNeigh(m_text[i], true)); + painter.drawText(QRect(1 + i * m_digitWidth, h + m_digitHeight * 1.9, m_digitWidth, m_digitHeight), Qt::AlignCenter, digitNeigh(m_text[i], false)); + } + } + } + } + } +} + +void ValueDial::mousePressEvent(QMouseEvent* event) +{ + int i; + + i = (event->x() - 1) / m_digitWidth; + if(m_text[i] == QChar('.')) { + i++; + if(i > m_numDigits + m_numDecimalPoints) + return; + } + m_cursor = i; + m_cursorState = true; + m_blinkTimer.start(400); + update(); +} + +void ValueDial::mouseMoveEvent(QMouseEvent* event) +{ + int i; + + i = (event->x() - 1) / m_digitWidth; + if(m_text[i] == QChar('.')) + i = -1; + + if(i != m_hightlightedDigit) { + m_hightlightedDigit = i; + update(); + } +} + +void ValueDial::wheelEvent(QWheelEvent* event) +{ + int i; + + i = (event->x() - 1) / m_digitWidth; + if(m_text[i] != QChar('.')) + m_hightlightedDigit = i; + else + return; + + if(m_cursor >= 0) { + m_cursor = -1; + m_blinkTimer.stop(); + update(); + } + quint64 e = findExponent(m_hightlightedDigit); + + if(m_animationState == 0) { + if(event->delta() < 0) { + if(event->modifiers() & Qt::ShiftModifier) + e *= 5; + if(m_value < e) + m_valueNew = m_valueMin; + else m_valueNew = m_value - e; + } else { + if(event->modifiers() & Qt::ShiftModifier) + e *= 5; + if(m_valueMax - m_value < e) + m_valueNew = m_valueMax; + else m_valueNew = m_value + e; + } + setValue(m_valueNew); + emit changed(m_valueNew); + } +} + +void ValueDial::leaveEvent(QEvent*) +{ + if(m_hightlightedDigit != -1) { + m_hightlightedDigit = -1; + update(); + } +} + +void ValueDial::keyPressEvent(QKeyEvent* value) +{ + if(m_cursor >= 0) { + if((value->key() == Qt::Key_Return) || (value->key() == Qt::Key_Enter) || (value->key() == Qt::Key_Escape)) { + m_cursor = -1; + m_cursorState = false; + m_blinkTimer.stop(); + update(); + return; + } + } + + if((m_cursor < 0) && (m_hightlightedDigit >= 0)) { + m_cursor = m_hightlightedDigit; + if(m_text[m_cursor] == QChar('.')) + m_cursor++; + if(m_cursor >= m_numDigits + m_numDecimalPoints) + return; + m_cursorState = true; + m_blinkTimer.start(400); + update(); + } + + if(m_cursor < 0) + return; + + if((value->key() == Qt::Key_Left) || (value->key() == Qt::Key_Backspace)) { + if(m_cursor > 0) { + m_cursor--; + if(m_text[m_cursor] == QChar('.')) + m_cursor--; + if(m_cursor < 0) + m_cursor++; + m_cursorState = true; + update(); + return; + } + } else if(value->key() == Qt::Key_Right) { + if(m_cursor < m_numDecimalPoints + m_numDigits) { + m_cursor++; + if(m_text[m_cursor] == QChar('.')) + m_cursor++; + if(m_cursor >= m_numDecimalPoints + m_numDigits) + m_cursor--; + m_cursorState = true; + update(); + return; + } + } else if(value->key() == Qt::Key_Up) { + quint64 e = findExponent(m_cursor); + if(value->modifiers() & Qt::ShiftModifier) + e *= 5; + if(m_animationState != 0) + m_value = m_valueNew; + if(m_valueMax - m_value < e) + m_valueNew = m_valueMax; + else m_valueNew = m_value + e; + setValue(m_valueNew); + emit changed(m_valueNew); + } else if(value->key() == Qt::Key_Down) { + quint64 e = findExponent(m_cursor); + if(value->modifiers() & Qt::ShiftModifier) + e *= 5; + if(m_animationState != 0) + m_value = m_valueNew; + if(m_value < e) + m_valueNew = m_valueMin; + else m_valueNew = m_value - e; + setValue(m_valueNew); + emit changed(m_valueNew); + } + + if(value->text().length() != 1) + return; + QChar c = value->text()[0]; + + if(c >= QChar('0') && (c <= QChar('9'))) { + int d = c.toLatin1() - '0'; + quint64 e = findExponent(m_cursor); + quint64 v = (m_value / e) % 10; + if(m_animationState != 0) + m_value = m_valueNew; + v = m_value - v * e; + v += d * e; + setValue(v); + emit changed(m_valueNew); + m_cursor++; + if(m_text[m_cursor] == QChar('.')) + m_cursor++; + if(m_cursor >= m_numDigits + m_numDecimalPoints) { + m_cursor = -1; + m_blinkTimer.stop(); + } else { + m_cursorState = true; + } + update(); + } +} + +void ValueDial::focusInEvent(QFocusEvent*) +{ + if(m_cursor == -1) { + m_cursor = 0; + m_cursorState = true; + m_blinkTimer.start(400); + update(); + } +} + +void ValueDial::focusOutEvent(QFocusEvent*) +{ + m_cursor = -1; + m_blinkTimer.stop(); + update(); +} + +void ValueDial::animate() +{ + update(); + + if(m_animationState > 0) + m_animationState++; + else if(m_animationState < 0) + m_animationState--; + else { + m_animationTimer.stop(); + m_animationState = 0; + return; + } + + if(abs(m_animationState) >= 4) { + m_animationState = 0; + m_animationTimer.stop(); + m_value = m_valueNew; + m_text = m_textNew; + } +} + +void ValueDial::blink() +{ + if(m_cursor >= 0) { + m_cursorState = !m_cursorState; + update(); + } +} diff --git a/sdrbase/mainwindow.cpp b/sdrbase/mainwindow.cpp new file mode 100644 index 000000000..9cbfb0fb1 --- /dev/null +++ b/sdrbase/mainwindow.cpp @@ -0,0 +1,526 @@ +/////////////////////////////////////////////////////////////////////////////////// +// Copyright (C) 2012 maintech GmbH, Otto-Hahn-Str. 15, 97204 Hoechberg, Germany // +// written by Christian Daniel // +// // +// This program is free software; you can redistribute it and/or modify // +// it under the terms of the GNU General Public License as published by // +// the Free Software Foundation as version 3 of the License, or // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU General Public License V3 for more details. // +// // +// You should have received a copy of the GNU General Public License // +// along with this program. If not, see . // +/////////////////////////////////////////////////////////////////////////////////// + +#include +#include +#include +#include "mainwindow.h" +#include "ui_mainwindow.h" +#include "audio/audiodeviceinfo.h" +#include "gui/indicator.h" +#include "gui/presetitem.h" +#include "gui/scopewindow.h" +#include "gui/addpresetdialog.h" +#include "gui/pluginsdialog.h" +#include "gui/preferencesdialog.h" +#include "gui/aboutdialog.h" +#include "gui/rollupwidget.h" +#include "dsp/dspengine.h" +#include "dsp/spectrumvis.h" +#include "dsp/dspcommands.h" +#include "plugin/plugingui.h" +#include "plugin/pluginapi.h" +#include "plugin/plugingui.h" + +MainWindow::MainWindow(QWidget* parent) : + QMainWindow(parent), + ui(new Ui::MainWindow), + m_audioDeviceInfo(new AudioDeviceInfo), + m_messageQueue(new MessageQueue), + m_settings(), + m_dspEngine(new DSPEngine(m_messageQueue)), + m_lastEngineState((DSPEngine::State)-1), + m_startOsmoSDRUpdateAfterStop(false), + m_scopeWindow(NULL), + m_inputGUI(NULL), + m_sampleRate(0), + m_centerFrequency(0), + m_pluginManager(new PluginManager(this, m_dspEngine)) +{ + ui->setupUi(this); + delete ui->mainToolBar; + createStatusBar(); + + setCorner(Qt::TopLeftCorner, Qt::LeftDockWidgetArea); + setCorner(Qt::BottomLeftCorner, Qt::LeftDockWidgetArea); + setCorner(Qt::TopRightCorner, Qt::RightDockWidgetArea); + setCorner(Qt::BottomRightCorner, Qt::RightDockWidgetArea); + + // work around broken Qt dock widget ordering + removeDockWidget(ui->inputDock); + removeDockWidget(ui->processingDock); + removeDockWidget(ui->presetDock); + removeDockWidget(ui->channelDock); + addDockWidget(Qt::LeftDockWidgetArea, ui->inputDock); + addDockWidget(Qt::LeftDockWidgetArea, ui->processingDock); + addDockWidget(Qt::LeftDockWidgetArea, ui->presetDock); + addDockWidget(Qt::RightDockWidgetArea, ui->channelDock); + ui->inputDock->show(); + ui->processingDock->show(); + ui->presetDock->show(); + ui->channelDock->show(); + + ui->menu_Window->addAction(ui->inputDock->toggleViewAction()); + ui->menu_Window->addAction(ui->processingDock->toggleViewAction()); + ui->menu_Window->addAction(ui->presetDock->toggleViewAction()); + ui->menu_Window->addAction(ui->channelDock->toggleViewAction()); + + connect(m_messageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleMessages()), Qt::QueuedConnection); + + connect(&m_statusTimer, SIGNAL(timeout()), this, SLOT(updateStatus())); + m_statusTimer.start(500); + + m_pluginManager->loadPlugins(); + bool sampleSourceSignalsBlocked = ui->sampleSource->blockSignals(true); + m_pluginManager->fillSampleSourceSelector(ui->sampleSource); + ui->sampleSource->blockSignals(sampleSourceSignalsBlocked); + + m_dspEngine->start(); + + m_spectrumVis = new SpectrumVis(ui->glSpectrum); + m_dspEngine->addSink(m_spectrumVis); + + ui->glSpectrumGUI->setBuddies(m_dspEngine->getMessageQueue(), m_spectrumVis, ui->glSpectrum); + + loadSettings(); + + int sampleSourceIndex = m_pluginManager->selectSampleSource(m_settings.getCurrent()->getSource()); // select SampleSource from settings + if(sampleSourceIndex >= 0) { + bool sampleSourceSignalsBlocked = ui->sampleSource->blockSignals(true); + ui->sampleSource->setCurrentIndex(sampleSourceIndex); + ui->sampleSource->blockSignals(sampleSourceSignalsBlocked); + } + + loadSettings(m_settings.getCurrent()); + + applySettings(); + updatePresets(); +} + +MainWindow::~MainWindow() +{ + m_dspEngine->stopAcquistion(); + + saveSettings(); + + m_pluginManager->freeAll(); + + m_dspEngine->removeSink(m_spectrumVis); + delete m_spectrumVis; + + if(m_scopeWindow != NULL) { + delete m_scopeWindow; + m_scopeWindow = NULL; + } + + delete m_pluginManager; + + m_dspEngine->stop(); + + delete m_dspEngine; + delete m_messageQueue; + delete ui; +} + +void MainWindow::addChannelCreateAction(QAction* action) +{ + ui->menu_Channels->addAction(action); +} + +void MainWindow::addChannelRollup(QWidget* widget) +{ + ((ChannelWindow*)ui->channelDock->widget())->addRollupWidget(widget); + ui->channelDock->show(); + ui->channelDock->raise(); +} + +void MainWindow::addViewAction(QAction* action) +{ + ui->menu_Window->addAction(action); +} + +void MainWindow::addChannelMarker(ChannelMarker* channelMarker) +{ + ui->glSpectrum->addChannelMarker(channelMarker); +} + +void MainWindow::removeChannelMarker(ChannelMarker* channelMarker) +{ + ui->glSpectrum->removeChannelMarker(channelMarker); +} + +void MainWindow::setInputGUI(QWidget* gui) +{ + if(m_inputGUI != NULL) + ui->inputDock->widget()->layout()->removeWidget(m_inputGUI); + if(gui != NULL) + ui->inputDock->widget()->layout()->addWidget(gui); + m_inputGUI = gui; +} + +void MainWindow::loadSettings() +{ + m_settings.load(); + + for(int i = 0; i < m_settings.getPresetCount(); ++i) + addPresetToTree(m_settings.getPreset(i)); + + Preset* current = m_settings.getCurrent(); + + loadSettings(current); +} + +void MainWindow::loadSettings(const Preset* preset) +{ + if(preset->getShowScope()) { + on_action_Oscilloscope_triggered(); + m_scopeWindow->deserialize(preset->getScopeConfig()); + } + ui->glSpectrumGUI->deserialize(preset->getSpectrumConfig()); + ui->dcOffset->setChecked(preset->getDCOffsetCorrection()); + ui->iqImbalance->setChecked(preset->getIQImbalanceCorrection()); + + m_pluginManager->loadSettings(preset); + + // has to be last step + restoreState(preset->getLayout()); +} + +void MainWindow::saveSettings() +{ + saveSettings(m_settings.getCurrent()); + m_settings.save(); +} + +void MainWindow::saveSettings(Preset* preset) +{ + preset->setSpectrumConfig(ui->glSpectrumGUI->serialize()); + if(preset->getShowScope()) + preset->setScopeConfig(m_scopeWindow->serialize()); + else preset->setScopeConfig(QByteArray()); + + preset->clearChannels(); + m_pluginManager->saveSettings(preset); + + preset->setLayout(saveState()); +} + +void MainWindow::createStatusBar() +{ + m_sampleRateWidget = new QLabel(tr("Rate: 0 kHz"), this); + m_sampleRateWidget->setToolTip(tr("Sample Rate")); + statusBar()->addPermanentWidget(m_sampleRateWidget); + + m_engineIdle = new Indicator(tr("Idle"), this); + m_engineIdle->setToolTip(tr("DSP engine is idle")); + statusBar()->addPermanentWidget(m_engineIdle); + + m_engineRunning = new Indicator(tr("Run"), this); + m_engineRunning->setToolTip(tr("DSP engine is running")); + statusBar()->addPermanentWidget(m_engineRunning); + + m_engineError = new Indicator(tr("Err"), this); + m_engineError->setToolTip(tr("DSP engine failed")); + statusBar()->addPermanentWidget(m_engineError); +} + +void MainWindow::closeEvent(QCloseEvent*) +{ +} + +void MainWindow::updateCenterFreqDisplay() +{ + ui->glSpectrum->setCenterFrequency(m_centerFrequency); +} + +void MainWindow::updateSampleRate() +{ + ui->glSpectrum->setSampleRate(m_sampleRate); + m_sampleRateWidget->setText(tr("Rate: %1 kHz").arg((float)m_sampleRate / 1000)); + if(m_scopeWindow != NULL) + m_scopeWindow->setSampleRate(m_sampleRate); +} + +void MainWindow::updatePresets() +{ + ui->presetTree->resizeColumnToContents(0); + if(ui->presetTree->currentItem() != NULL) { + ui->presetDelete->setEnabled(true); + ui->presetLoad->setEnabled(true); + } else { + ui->presetDelete->setEnabled(false); + ui->presetLoad->setEnabled(false); + } +} + +QTreeWidgetItem* MainWindow::addPresetToTree(const Preset* preset) +{ + QTreeWidgetItem* group = NULL; + for(int i = 0; i < ui->presetTree->topLevelItemCount(); i++) { + if(ui->presetTree->topLevelItem(i)->text(0) == preset->getGroup()) { + group = ui->presetTree->topLevelItem(i); + break; + } + } + if(group == NULL) { + QStringList sl; + sl.append(preset->getGroup()); + group = new QTreeWidgetItem(ui->presetTree, sl, PGroup); + group->setFirstColumnSpanned(true); + group->setExpanded(true); + ui->presetTree->sortByColumn(0, Qt::AscendingOrder); + } + QStringList sl; + sl.append(QString("%1 kHz").arg(preset->getCenterFrequency() / 1000)); + sl.append(preset->getDescription()); + PresetItem* item = new PresetItem(group, sl, preset->getCenterFrequency(), PItem); + item->setTextAlignment(0, Qt::AlignRight); + item->setData(0, Qt::UserRole, qVariantFromValue(preset)); + ui->presetTree->resizeColumnToContents(0); + + updatePresets(); + return item; +} + +void MainWindow::applySettings() +{ + updateCenterFreqDisplay(); + updateSampleRate(); +} + +void MainWindow::handleMessages() +{ + Message* message; + while((message = m_messageQueue->accept()) != NULL) { + qDebug("Message: %s", message->getIdentifier()); + if(DSPEngineReport::match(message)) { + DSPEngineReport* rep = (DSPEngineReport*)message; + m_sampleRate = rep->getSampleRate(); + m_centerFrequency = rep->getCenterFrequency(); + qDebug("SampleRate:%d, CenterFrequency:%llu", rep->getSampleRate(), rep->getCenterFrequency()); + updateCenterFreqDisplay(); + updateSampleRate(); + message->completed(); + } else { + if(!m_pluginManager->handleMessage(message)) + message->completed(); + } + } +} + +void MainWindow::updateStatus() +{ + int state = m_dspEngine->state(); + if(m_lastEngineState != state) { + switch(state) { + case DSPEngine::StNotStarted: + m_engineIdle->setColor(Qt::gray); + m_engineRunning->setColor(Qt::gray); + m_engineError->setColor(Qt::gray); + statusBar()->clearMessage(); + break; + + case DSPEngine::StIdle: + m_engineIdle->setColor(Qt::cyan); + m_engineRunning->setColor(Qt::gray); + m_engineError->setColor(Qt::gray); + statusBar()->clearMessage(); + if(m_startOsmoSDRUpdateAfterStop) + on_actionOsmoSDR_Firmware_Upgrade_triggered(); + break; + + case DSPEngine::StRunning: + m_engineIdle->setColor(Qt::gray); + m_engineRunning->setColor(Qt::green); + m_engineError->setColor(Qt::gray); + statusBar()->showMessage(tr("Sampling from %1").arg(m_dspEngine->deviceDescription())); + break; + + case DSPEngine::StError: + m_engineIdle->setColor(Qt::gray); + m_engineRunning->setColor(Qt::gray); + m_engineError->setColor(Qt::red); + statusBar()->showMessage(tr("Error: %1").arg(m_dspEngine->errorMessage())); + if(m_startOsmoSDRUpdateAfterStop) + on_actionOsmoSDR_Firmware_Upgrade_triggered(); + break; + } + m_lastEngineState = state; + } +} + +void MainWindow::scopeWindowDestroyed() +{ + ui->action_Oscilloscope->setChecked(false); + m_settings.getCurrent()->setShowScope(false); + m_scopeWindow = NULL; +} + +void MainWindow::on_action_Start_triggered() +{ + m_dspEngine->startAcquisition(); +} + +void MainWindow::on_action_Stop_triggered() +{ + m_dspEngine->stopAcquistion(); +} + +void MainWindow::on_dcOffset_toggled(bool checked) +{ + m_settings.getCurrent()->setDCOffsetCorrection(checked); + m_dspEngine->configureCorrections(m_settings.getCurrent()->getDCOffsetCorrection(), m_settings.getCurrent()->getIQImbalanceCorrection()); +} + +void MainWindow::on_iqImbalance_toggled(bool checked) +{ + m_settings.getCurrent()->setIQImbalanceCorrection(checked); + m_dspEngine->configureCorrections(m_settings.getCurrent()->getDCOffsetCorrection(), m_settings.getCurrent()->getIQImbalanceCorrection()); +} + +void MainWindow::on_action_View_Fullscreen_toggled(bool checked) +{ + if(checked) + showFullScreen(); + else showNormal(); +} + +void MainWindow::on_actionOsmoSDR_Firmware_Upgrade_triggered() +{ + DSPEngine::State engineState = m_dspEngine->state(); + if((engineState != DSPEngine::StIdle) && (engineState != DSPEngine::StError)) { + m_startOsmoSDRUpdateAfterStop = true; + m_dspEngine->stopAcquistion(); + return; + } + m_startOsmoSDRUpdateAfterStop = false; +/* TODO: osmosdr upgrade + OsmoSDRUpgrade osmoSDRUpgrade; + osmoSDRUpgrade.exec(); + */ +} + +void MainWindow::on_presetSave_clicked() +{ + QStringList groups; + QString group; + for(int i = 0; i < ui->presetTree->topLevelItemCount(); i++) + groups.append(ui->presetTree->topLevelItem(i)->text(0)); + + QTreeWidgetItem* item = ui->presetTree->currentItem(); + if(item != NULL) { + if(item->type() == PGroup) + group = item->text(0); + else if(item->type() == PItem) + group = item->parent()->text(0); + } + + AddPresetDialog dlg(groups, group, this); + + if(dlg.exec() == QDialog::Accepted) { + Preset* preset = m_settings.newPreset(dlg.group(), dlg.description()); + saveSettings(preset); + + ui->presetTree->setCurrentItem(addPresetToTree(preset)); + } +} + +void MainWindow::on_presetLoad_clicked() +{ + QTreeWidgetItem* item = ui->presetTree->currentItem(); + if(item == NULL) { + updatePresets(); + return; + } + const Preset* preset = qvariant_cast(item->data(0, Qt::UserRole)); + if(preset == NULL) + return; + + loadSettings(preset); + applySettings(); +} + +void MainWindow::on_presetDelete_clicked() +{ + QTreeWidgetItem* item = ui->presetTree->currentItem(); + if(item == NULL) { + updatePresets(); + return; + } + const Preset* preset = qvariant_cast(item->data(0, Qt::UserRole)); + if(preset == NULL) + return; + + if(QMessageBox::question(this, tr("Delete Preset"), tr("Do you want to delete preset '%1'?").arg(preset->getDescription()), QMessageBox::No | QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) { + delete item; + m_settings.deletePreset(preset); + } +} + +void MainWindow::on_presetTree_currentItemChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) +{ + updatePresets(); +} + +void MainWindow::on_presetTree_itemActivated(QTreeWidgetItem *item, int column) +{ + on_presetLoad_clicked(); +} + +void MainWindow::on_action_Oscilloscope_triggered() +{ + if(m_scopeWindow != NULL) { + ((QWidget*)m_scopeWindow->parent())->raise(); + return; + } + + QDockWidget* dock = new QDockWidget(tr("Signalscope"), this); + dock->setObjectName(QString::fromUtf8("scopeDock")); + m_scopeWindow = new ScopeWindow(m_dspEngine); + connect(m_scopeWindow, SIGNAL(destroyed()), this, SLOT(scopeWindowDestroyed())); + m_scopeWindow->setSampleRate(m_sampleRate); + dock->setWidget(m_scopeWindow); + dock->setAllowedAreas(Qt::AllDockWidgetAreas); + addDockWidget(Qt::BottomDockWidgetArea, dock); + dock->setAttribute(Qt::WA_DeleteOnClose); + m_settings.getCurrent()->setShowScope(true); +} + +void MainWindow::on_action_Loaded_Plugins_triggered() +{ + PluginsDialog pluginsDialog(m_pluginManager, this); + + pluginsDialog.exec(); +} + +void MainWindow::on_action_Preferences_triggered() +{ + PreferencesDialog preferencesDialog(m_audioDeviceInfo, this); + + preferencesDialog.exec(); +} + +void MainWindow::on_sampleSource_currentIndexChanged(int index) +{ + m_pluginManager->selectSampleSource(ui->sampleSource->currentIndex()); +} + +void MainWindow::on_action_About_triggered() +{ + AboutDialog dlg(this); + dlg.exec(); +} diff --git a/sdrbase/mainwindow.ui b/sdrbase/mainwindow.ui new file mode 100644 index 000000000..60e2c431e --- /dev/null +++ b/sdrbase/mainwindow.ui @@ -0,0 +1,483 @@ + + + MainWindow + + + + 0 + 0 + 1012 + 706 + + + + SDRangelove + + + + :/appicon.png:/appicon.png + + + true + + + + + 0 + + + + + + 0 + 0 + + + + + + + + + + 0 + 0 + 1012 + 23 + + + + + &File + + + + + + &Options + + + + + + + + &Acquisition + + + + + + + &View + + + + + + + + &Help + + + + + + + + + + + &Channels + + + + + &Window + + + + + + + + + + + + + TopToolBarArea + + + false + + + + + + Presets + + + 1 + + + + + 2 + + + 3 + + + + + Save current settings as preset + + + ... + + + + :/preset-save.png:/preset-save.png + + + + 16 + 16 + + + + + + + + Load selected preset + + + ... + + + + :/preset-load.png:/preset-load.png + + + + 16 + 16 + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + Delete selected preset + + + ... + + + + :/preset-delete.png:/preset-delete.png + + + + 16 + 16 + + + + + + + + true + + + + Frequency + + + + + Description + + + + + + + + + + Processing and Display + + + 1 + + + + + 0 + 0 + + + + + 3 + + + 2 + + + + + 3 + + + + + + 0 + 0 + + + + Compensate DC offset + + + DC Offset Corr + + + + + + + + 0 + 0 + + + + Compensate I/Q imbalance + + + I/Q Imbal. Corr + + + + + + + + + + + + + + Sample Source + + + 1 + + + + + 0 + 0 + + + + + 3 + + + 2 + + + + + QComboBox::AdjustToMinimumContentsLength + + + + + + + + + Channels + + + 2 + + + + + 3 + + + 2 + + + + + + + E&xit + + + Ctrl+Q + + + + + &Start + + + F5 + + + + + &Stop + + + F6 + + + + + true + + + &Fullscreen + + + F11 + + + + + OsmoSDR &Firmware Upgrade... + + + + + true + + + &Oscilloscope + + + F8 + + + + + &About SDRangelove... + + + + + &Open Website + + + + + Check for &Update... + + + + + &Preferences... + + + + + N&FM + + + + + &Tetra + + + + + Loaded &Plugins... + + + presetDock + channelDock + + + + + ButtonSwitch + QToolButton +
gui/buttonswitch.h
+
+ + GLSpectrum + QWidget +
gui/glspectrum.h
+ 1 +
+ + GLSpectrumGUI + QWidget +
gui/glspectrumgui.h
+ 1 +
+ + ChannelWindow + QWidget +
gui/channelwindow.h
+ 1 +
+
+ + presetTree + presetSave + presetDelete + presetLoad + dcOffset + iqImbalance + + + + + + + action_Exit + triggered() + MainWindow + close() + + + -1 + -1 + + + 462 + 332 + + + + +
diff --git a/sdrbase/plugin/pluginapi.cpp b/sdrbase/plugin/pluginapi.cpp new file mode 100644 index 000000000..b3a842dfc --- /dev/null +++ b/sdrbase/plugin/pluginapi.cpp @@ -0,0 +1,99 @@ +#include +#include "plugin/pluginapi.h" +#include "plugin/pluginmanager.h" +#include "mainwindow.h" +#include "dsp/dspengine.h" + +QDockWidget* PluginAPI::createMainWindowDock(Qt::DockWidgetArea dockWidgetArea, const QString& title) +{ + QDockWidget* dock = new QDockWidget(title, m_mainWindow); + dock->setAllowedAreas(Qt::AllDockWidgetAreas); + dock->setAttribute(Qt::WA_DeleteOnClose); + m_mainWindow->addDockWidget(dockWidgetArea, dock); + m_mainWindow->addViewAction(dock->toggleViewAction()); + return dock; +} + +MessageQueue* PluginAPI::getMainWindowMessageQueue() +{ + return m_mainWindow->getMessageQueue(); +} + +void PluginAPI::setInputGUI(QWidget* inputGUI) +{ + m_mainWindow->setInputGUI(inputGUI); +} + +void PluginAPI::registerChannel(const QString& channelName, PluginInterface* plugin, QAction* action) +{ + m_pluginManager->registerChannel(channelName, plugin, action); +} + +void PluginAPI::registerChannelInstance(const QString& channelName, PluginGUI* pluginGUI) +{ + m_pluginManager->registerChannelInstance(channelName, pluginGUI); +} + +void PluginAPI::addChannelRollup(QWidget* pluginGUI) +{ + m_pluginManager->addChannelRollup(pluginGUI); +} + +void PluginAPI::removeChannelInstance(PluginGUI* pluginGUI) +{ + m_pluginManager->removeChannelInstance(pluginGUI); +} + +void PluginAPI::addChannelMarker(ChannelMarker* channelMarker) +{ + m_mainWindow->addChannelMarker(channelMarker); +} + +void PluginAPI::removeChannelMarker(ChannelMarker* channelMarker) +{ + m_mainWindow->removeChannelMarker(channelMarker); +} + +void PluginAPI::setSampleSource(SampleSource* sampleSource) +{ + m_dspEngine->stopAcquistion(); + m_dspEngine->setSource(sampleSource); +} + +void PluginAPI::addSampleSink(SampleSink* sampleSink) +{ + m_dspEngine->addSink(sampleSink); +} + +void PluginAPI::removeSampleSink(SampleSink* sampleSink) +{ + m_dspEngine->removeSink(sampleSink); +} + +MessageQueue* PluginAPI::getDSPEngineMessageQueue() +{ + return m_dspEngine->getMessageQueue(); +} + +void PluginAPI::addAudioSource(AudioFifo* audioFifo) +{ + m_dspEngine->addAudioSource(audioFifo); +} + +void PluginAPI::removeAudioSource(AudioFifo* audioFifo) +{ + m_dspEngine->removeAudioSource(audioFifo); +} + +void PluginAPI::registerSampleSource(const QString& sourceName, PluginInterface* plugin) +{ + m_pluginManager->registerSampleSource(sourceName, plugin); +} + +PluginAPI::PluginAPI(PluginManager* pluginManager, MainWindow* mainWindow, DSPEngine* dspEngine) : + QObject(mainWindow), + m_pluginManager(pluginManager), + m_mainWindow(mainWindow), + m_dspEngine(dspEngine) +{ +} diff --git a/sdrbase/plugin/plugingui.cpp b/sdrbase/plugin/plugingui.cpp new file mode 100644 index 000000000..63ddcce79 --- /dev/null +++ b/sdrbase/plugin/plugingui.cpp @@ -0,0 +1,16 @@ +#include "plugin/plugingui.h" + +QByteArray PluginGUI::serializeGeneral() const +{ + return QByteArray(); +} + +bool PluginGUI::deserializeGeneral(const QByteArray& data) +{ + return false; +} + +quint64 PluginGUI::getCenterFrequency() const +{ + return 0; +} diff --git a/sdrbase/plugin/plugininterface.cpp b/sdrbase/plugin/plugininterface.cpp new file mode 100644 index 000000000..1b564ab70 --- /dev/null +++ b/sdrbase/plugin/plugininterface.cpp @@ -0,0 +1 @@ +#include "plugin/plugininterface.h" diff --git a/sdrbase/plugin/pluginmanager.cpp b/sdrbase/plugin/pluginmanager.cpp new file mode 100644 index 000000000..3338c01fa --- /dev/null +++ b/sdrbase/plugin/pluginmanager.cpp @@ -0,0 +1,280 @@ +#include +#include +#include +#include "plugin/pluginmanager.h" +#include "plugin/plugingui.h" +#include "settings/preset.h" +#include "mainwindow.h" +#include "dsp/dspengine.h" +#include "dsp/samplesource/samplesource.h" + +PluginManager::PluginManager(MainWindow* mainWindow, DSPEngine* dspEngine, QObject* parent) : + QObject(parent), + m_pluginAPI(this, mainWindow, dspEngine), + m_mainWindow(mainWindow), + m_dspEngine(dspEngine), + m_sampleSource(), + m_sampleSourceInstance(NULL) +{ +} + +PluginManager::~PluginManager() +{ + freeAll(); +} + +void PluginManager::loadPlugins() +{ + QDir pluginsDir = QDir(QApplication::instance()->applicationDirPath()); + + loadPlugins(pluginsDir); + + qSort(m_plugins); + + for(Plugins::const_iterator it = m_plugins.begin(); it != m_plugins.end(); ++it) + it->plugin->initPlugin(&m_pluginAPI); + + updateSampleSourceDevices(); +} + +void PluginManager::registerChannel(const QString& channelName, PluginInterface* plugin, QAction* action) +{ + m_channelRegistrations.append(ChannelRegistration(channelName, plugin)); + m_mainWindow->addChannelCreateAction(action); +} + +void PluginManager::registerChannelInstance(const QString& channelName, PluginGUI* pluginGUI) +{ + m_channelInstanceRegistrations.append(ChannelInstanceRegistration(channelName, pluginGUI)); + renameChannelInstances(); +} + +void PluginManager::addChannelRollup(QWidget* pluginGUI) +{ + m_mainWindow->addChannelRollup(pluginGUI); +} + +void PluginManager::removeChannelInstance(PluginGUI* pluginGUI) +{ + for(ChannelInstanceRegistrations::iterator it = m_channelInstanceRegistrations.begin(); it != m_channelInstanceRegistrations.end(); ++it) { + if(it->m_gui == pluginGUI) { + m_channelInstanceRegistrations.erase(it); + break; + } + } + renameChannelInstances(); +} + +void PluginManager::registerSampleSource(const QString& sourceName, PluginInterface* plugin) +{ + m_sampleSourceRegistrations.append(SampleSourceRegistration(sourceName, plugin)); +} + +void PluginManager::loadSettings(const Preset* preset) +{ + qDebug("-------- [%s | %s] --------", qPrintable(preset->getGroup()), qPrintable(preset->getDescription())); + + // copy currently open channels and clear list + ChannelInstanceRegistrations openChannels = m_channelInstanceRegistrations; + m_channelInstanceRegistrations.clear(); + + for(int i = 0; i < preset->getChannelCount(); i++) { + const Preset::ChannelConfig& channelConfig = preset->getChannelConfig(i); + ChannelInstanceRegistration reg; + // if we have one instance available already, use it + for(int i = 0; i < openChannels.count(); i++) { + qDebug("compare [%s] vs [%s]", qPrintable(openChannels[i].m_channelName), qPrintable(channelConfig.m_channel)); + if(openChannels[i].m_channelName == channelConfig.m_channel) { + qDebug("channel [%s] found", qPrintable(openChannels[i].m_channelName)); + reg = openChannels.takeAt(i); + m_channelInstanceRegistrations.append(reg); + break; + } + } + // if we haven't one already, create one + if(reg.m_gui == NULL) { + for(int i = 0; i < m_channelRegistrations.count(); i++) { + if(m_channelRegistrations[i].m_channelName == channelConfig.m_channel) { + qDebug("creating new channel [%s]", qPrintable(channelConfig.m_channel)); + reg = ChannelInstanceRegistration(channelConfig.m_channel, m_channelRegistrations[i].m_plugin->createChannel(channelConfig.m_channel)); + break; + } + } + } + if(reg.m_gui != NULL) + reg.m_gui->deserialize(channelConfig.m_config); + } + + // everything, that is still "available" is not needed anymore + for(int i = 0; i < openChannels.count(); i++) { + qDebug("destroying spare channel [%s]", qPrintable(openChannels[i].m_channelName)); + openChannels[i].m_gui->destroy(); + } + + renameChannelInstances(); + + if(m_sampleSourceInstance != NULL) { + m_sampleSourceInstance->deserializeGeneral(preset->getSourceGeneralConfig()); + if(m_sampleSource == preset->getSource()) { + m_sampleSourceInstance->deserialize(preset->getSourceConfig()); + } + } +} + +void PluginManager::saveSettings(Preset* preset) const +{ + if(m_sampleSourceInstance != NULL) { + preset->setSourceConfig(m_sampleSource, m_sampleSourceInstance->serializeGeneral(), m_sampleSourceInstance->serialize()); + preset->setCenterFrequency(m_sampleSourceInstance->getCenterFrequency()); + } else { + preset->setSourceConfig(QString::null, QByteArray(), QByteArray()); + } + for(int i = 0; i < m_channelInstanceRegistrations.count(); i++) + preset->addChannel(m_channelInstanceRegistrations[i].m_channelName, m_channelInstanceRegistrations[i].m_gui->serialize()); +} + +void PluginManager::freeAll() +{ + m_dspEngine->stopAcquistion(); + + while(!m_channelInstanceRegistrations.isEmpty()) { + ChannelInstanceRegistration reg(m_channelInstanceRegistrations.takeLast()); + reg.m_gui->destroy(); + } + + if(m_sampleSourceInstance != NULL) { + m_dspEngine->setSource(NULL); + m_sampleSourceInstance->destroy(); + m_sampleSourceInstance = NULL; + m_sampleSource.clear(); + } +} + +bool PluginManager::handleMessage(Message* message) +{ + if(m_sampleSourceInstance != NULL) { + if((message->getDestination() == NULL) || (message->getDestination() == m_sampleSourceInstance)) { + if(m_sampleSourceInstance->handleMessage(message)) + return true; + } + } + + for(ChannelInstanceRegistrations::iterator it = m_channelInstanceRegistrations.begin(); it != m_channelInstanceRegistrations.end(); ++it) { + if((message->getDestination() == NULL) || (message->getDestination() == it->m_gui)) { + if(it->m_gui->handleMessage(message)) + return true; + } + } + return false; +} + +void PluginManager::updateSampleSourceDevices() +{ + m_sampleSourceDevices.clear(); + for(int i = 0; i < m_sampleSourceRegistrations.count(); ++i) { + PluginInterface::SampleSourceDevices ssd = m_sampleSourceRegistrations[i].m_plugin->enumSampleSources(); + for(int j = 0; j < ssd.count(); ++j) + m_sampleSourceDevices.append(SampleSourceDevice(m_sampleSourceRegistrations[i].m_plugin, ssd[j].displayedName, ssd[j].name, ssd[j].address)); + } +} + +void PluginManager::fillSampleSourceSelector(QComboBox* comboBox) +{ + comboBox->clear(); + for(int i = 0; i < m_sampleSourceDevices.count(); i++) + comboBox->addItem(m_sampleSourceDevices[i].m_displayName, i); +} + +int PluginManager::selectSampleSource(int index) +{ + m_dspEngine->stopAcquistion(); + + if(m_sampleSourceInstance != NULL) { + m_dspEngine->stopAcquistion(); + m_dspEngine->setSource(NULL); + m_sampleSourceInstance->destroy(); + m_sampleSourceInstance = NULL; + m_sampleSource.clear(); + } + + if(index == -1) { + if(!m_sampleSource.isEmpty()) { + for(int i = 0; i < m_sampleSourceDevices.count(); i++) { + if(m_sampleSourceDevices[i].m_sourceName == m_sampleSource) { + index = i; + break; + } + } + } + if(index == -1) { + if(m_sampleSourceDevices.count() > 0) + index = 0; + } + } + if(index == -1) + return -1; + + m_sampleSource = m_sampleSourceDevices[index].m_sourceName; + m_sampleSourceInstance = m_sampleSourceDevices[index].m_plugin->createSampleSource(m_sampleSource, m_sampleSourceDevices[index].m_address); + return index; +} + +int PluginManager::selectSampleSource(const QString& source) +{ + int index = -1; + + m_dspEngine->stopAcquistion(); + + if(m_sampleSourceInstance != NULL) { + m_dspEngine->stopAcquistion(); + m_dspEngine->setSource(NULL); + m_sampleSourceInstance->destroy(); + m_sampleSourceInstance = NULL; + m_sampleSource.clear(); + } + + qDebug("finding sample source [%s]", qPrintable(source)); + for(int i = 0; i < m_sampleSourceDevices.count(); i++) { + qDebug("*** %s vs %s", qPrintable(m_sampleSourceDevices[i].m_sourceName), qPrintable(source)); + if(m_sampleSourceDevices[i].m_sourceName == source) { + index = i; + break; + } + } + if(index == -1) { + if(m_sampleSourceDevices.count() > 0) + index = 0; + } + if(index == -1) + return -1; + + m_sampleSource = m_sampleSourceDevices[index].m_sourceName; + m_sampleSourceInstance = m_sampleSourceDevices[index].m_plugin->createSampleSource(m_sampleSource, m_sampleSourceDevices[index].m_address); + return index; +} + +void PluginManager::loadPlugins(const QDir& dir) +{ + QDir pluginsDir(dir); + foreach(QString fileName, pluginsDir.entryList(QDir::Files)) { + QPluginLoader* loader = new QPluginLoader(pluginsDir.absoluteFilePath(fileName)); + PluginInterface* plugin = qobject_cast(loader->instance()); + if(loader->isLoaded()) + qDebug("loaded plugin %s", qPrintable(fileName)); + if(plugin != NULL) { + m_plugins.append(Plugin(fileName, loader, plugin)); + } else { + loader->unload(); + delete loader; + } + } + foreach(QString dirName, pluginsDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot)) + loadPlugins(pluginsDir.absoluteFilePath(dirName)); +} + +void PluginManager::renameChannelInstances() +{ + for(int i = 0; i < m_channelInstanceRegistrations.count(); i++) { + m_channelInstanceRegistrations[i].m_gui->setName(QString("%1:%2").arg(m_channelInstanceRegistrations[i].m_channelName).arg(i)); + } +} diff --git a/sdrbase/resources/appicon.ico b/sdrbase/resources/appicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..f2c769281734de405d3bae38ef342c6dc6fe8ae1 GIT binary patch literal 9062 zcmeHMJxc>Y5S?6-`%05i3n7*GFOte$YwM6MV6CLl%2a}a|KL(7Nn@8P0l_lOft6yR z1PdXULR|OVT_l@a2<`Nnin4O)S-6hIUj!GqxZHc@h(LPbsx5=}KKIFHe z1oX8W(e?JEZ&NK#^s_^>2aZHV0>29+YQj$Vd>D?zr9adHxUb!=cx*JZ04{9rc6=>> z3)?qDS^$^rv;R5%c>d|c0Oudhze(4hwAbI>)3>;|A8P?z-}gnk-PQuQu)THssReLh zyIQSk0bI7v{^$7P`KJ>DoPRj~CS8BhUVo?00@8R_&ne{L1|(|2PWZ$ck9|JsEzDKa z>+n6!5HJr>i=&=^KT%Uj7K44jF|Z*qP_Pv#n1&*zom0d%GKv_iUvK{`8(-H_#C7tD zI965>OCEzyOP=-X?Vn}iJ3W|byrWK$S1!R#%HMrTOr3HzcoRqc=U713tJg)lT#f~F z;4V6ggbv(A_Z`qNKbilMj^D}cmpHf@#R59d^F*`Rj0JSyF4~Ji2kxTtF6fw_%zsJ8 zFKKR4^GuXrjQM|^?1ws)is;L{G1(Ix${0Dl8_PWK62wZY)e`4}cdmmsqz;ymz+=fi x5K+Bc$cEdXtR0ralYNh|>i(=f%M8SFoj_bO++LVYn5vvr_h;?RXT<+~`2{$Wfx!R( literal 0 HcmV?d00001 diff --git a/sdrbase/resources/appicon.png b/sdrbase/resources/appicon.png new file mode 100644 index 0000000000000000000000000000000000000000..c481cc3fa78e85c7bc873a6af48da1935895036f GIT binary patch literal 326 zcmeAS@N?(olHy`uVBq!ia0vp^3LwnE1SJ1Ryj={W7>k44ofy`glX(f`u%tWsIx;Y9 z?C1WI$O=-K>=ES4z)+>ez|hdb!0-zw)bN6Vq11qZ;Z*_ygVhWM2JwP9y8>;15>h3u z5hcO-X(i=}MX3w{iJ5sNdVa1U3T4K6rh0}3249L60#(iPba4#v@J{|y{QSjy>*Ep~ z%sN_O<^Q|x?5Uh=@s#J)t5-bsWhM1mlN5v)Me}cM(d^A&2(igx{C7c$SE*@brb&le zGsorzsVS*~8+Nem>h@p>;n7*$xN^1!gVv4x`z(Jxd#0i!81V7mU;o#y&kJ-mbV)Y2 z-M_QOO@&E|P3r6cgUKE&K|u5FJph@PiEQ55?rerG?I}&-kL*7IUCQ9;>gTe~DWM4f D46tt- literal 0 HcmV?d00001 diff --git a/sdrbase/resources/grid.png b/sdrbase/resources/grid.png new file mode 100644 index 0000000000000000000000000000000000000000..e384a539401ac789e4510fab076550c6200f90dc GIT binary patch literal 259 zcmeAS@N?(olHy`uVBq!ia0vp^5+KaM1SIoCSFHz9oCO|{#S9GG!XV7ZFl!D-1$&97 zuPggqPH8?a6%{_S_duaVo-U3d7N?(v?B--u6eyW49@(6bz%2G4ttml8B6=(9jZ@q# zm3xABTJyX!o_OZfn>Bn!+Zw;m>veRAm9rLkC;7Jo53 zrl9o4fg^G4+I7NcgbM2ZT@rGS+hy5V*a}34<}vN3nx$FT zz<^*~pcV(hw9CiH|B_9BvFVe|{5~`UT?x^b+GAA60Ugcwcf)XfXs98HT(43~9nGHX zT{?3`63g9<4=%lT;Pe-g=2KH|c&7cI5-~!YiC6lg2R(Noan$0?vG_02VCwhZ4kg0X z%F74${Gh3afvk;oyuvfRT^C@fL2qR7hcQYNfm~jgOk@UH#}Q9+7B+sCdh>~RDwW!} zXJO`LnKy_-&`w|xt|?_YCIo@NsD(5bpB^cVwf*`gPrTm`9>+6Mk)Dd%A+j!nL?D>f zOp4et;WDg*7`LOun=nfvUX7D*qxHwKDIuA{9_bb^;lLv3Nidq%oswRL(1;`$fiHw( zcQX5Omb2-0|9~_zQo*isvgDwXpcaDy38s@@()Ak@0t(PTGl9oi#p6cd0HSAl>+Q_vp8l8Y?d4~)cE;cKQeCHDF+>V&384%r^2ti1 zqqfqd{;hDHhhxFv08lig)Y)zO*iuE9AABB^o8!y z43ai9^}=ecvlzs|qyMS3wm3)dkb8#&EcnVhu{>T}emnKuN1wfVcYO-Z6npnP`+72a zZtcvCPhZom5E5n8kd5#C?m{dQN+|%PR3suP<6OED7$q3Qt%%RlpS*r2d9!jW`(ic9 zQC|7x!_~VbL;^%2(M0L-xVq50FO}N#rh=e0-ur3I*$bum)oeAty)?2gVf8NGu`iof znV&t2I6)`?0)@2dr8+n3&3i!{0OV03tu+A0uso()x#MZ&54y&+wf!GA<}%ZRT%lL= a2Y&<61p;msq)SHt0000?x%u=fFGvOgg(OQ{BTAg}b8}PkN*J7rQWHy3QxwWG zOEMJPJ$(bh8~Mb6ij+NF978NlCnrd-_VDoV{MR&nV$W!~=abKrTXtCtQx_F3VP^O} Wjg4LX=#gNcat2RVKbLh*2~7YisWMmq literal 0 HcmV?d00001 diff --git a/sdrbase/resources/invertspectrum.png b/sdrbase/resources/invertspectrum.png new file mode 100644 index 0000000000000000000000000000000000000000..cd8e61cf70c73ade068cc06fbcbe13c37d4e6e36 GIT binary patch literal 1272 zcmV&*RrKhAktTxV3m8W%lq;Nige|DVtQ zQR^QY6_DeG-xg@05Cc_f%mM*tUT^msz)fB;}*uC+=0a* z&<0u_&bJ6fu(nuzl;=Xd-dY>M`az+WgU?D7C5wpyTr~u*p{*e~ot?p2=M!`nGKzK^+h9BYgt&jW}Byux?O;4{GX z%VZ5?j(%hMCIbBnb^XS(nT-2O8@asYSx(e;;!6Px8>~cK@dWJtHAK~=21ZOO!V^EC(mOWOR3};is2jBw`LBbr;00JPi zh<6CW^z<|UhY!Dta|LA^^3)T1+5Pk!=c}jq{HMKKxiEomwkc;z47Dy`BR7aoa(eX| zVp1fukXeX<%plefYT?+CH`u>_|7sQ=y!JkmTQ}3b?=D{YU1%x>&=s~hfIcYOK z*v5Dt9Q9uC-rx4j&VI-6aLle#uy#5|U5lmL0?ECtm9AYyt1xgh}w!rS3dY;L@ zPII!oK>jaz96EGl)j#^qN0=Z4tNU7|9B2(Fc8D;aTv(JWDpb(rr5YirMgV5nqq@t3q`^=`SzVK)R3@|$No5mZbql#2qGQ$(Y#8Ciht9JjE;xDiJYSqS2S9D(-CS!Gki_ud z1{l5m0hM|XbK5(ESUs+_E(Dg*@N;72iFlU#0?^nC9#%+UEk9HCzbCS0cX&947!(*BO+$LfhmFednPgz(VL(L-Yr z;wl#|I_&VLp1@a$2ZAnfljYDw&D56JB$19InEAIC#IEd^(e*s5_T&uq1p3hQq%I2< zRp}1`8hy3!*d*-ey_p%sqv)YYHZnHL=#FFS$;3c*!Aem*uk zX1gA`#Q=kstVFPTs$porC4nT_!@#|ke+DWJ?D8Q_{~qNP2p`6 zk18O}L`IUM4NGPEJo7~tii;dVN)-B3l;{{5yAP(N53>ydeHR)^jP3`FlQH{lFwRd% zN%BuPfz5gN$-&jev}JH^d6--wJdXITK_Cg)IWC3!AHgt+}fAo2$JG6@jmM6*b1y195)_g-ts-+ z!iD6U#IVQV2PhEJ;5I@v5;PJm#PNp_499#csn@O&SSCJ;LLG9h`)7uGh$RSfzN=z8L>*@Lt%x<7(Q9Pl$8 zb_`-osH`}{H|G4rS!q5%8^BYH3hVBN(x78OU|YDh+!x6&%EZ(?)GD&(R6O)SRG;lW zU(n`IY*BQRCyhy)qC0=lQP>u@rvZN6q3u=4W6)-Rp}WS>WL%_kWzbjgEcv0urGBff zUzJ{~o$o2>B>T4<%WzCKvU*TOw^+T`Mssv{V?5wI)ag&2(NE1D7R8)?9lYFjx?6?yy zJxM;%9Q5(YEyvThC$}d-4Q35xjh<7QC7vb5irS^aGOx0~OY)2BOVW$m<(!Ltiwldb z*NW-re#-z<#J zSIi3(-l=ERT;%6ebW1#k-WQ>1j3~ zaC#4Wt9XZbUwDIW5ucb|sa{E*x}VhG1mHfy!NOI;wW9tFXBxm6FbIDQuZ@j~{T{=E z??xcRp~;EHHqC3#-D4xpr))5r^8uVg3Uh?pXoggxw> zieR3_Q^FIEhKnXrz*q)17AyVMb=|WCH3CXbcr4^vlYQ^)?^$^Z2`LO2&7b-< zKi9`TSHJuhE_xWr#Lhg&LtM~{zuH~k@OF8vU+3I+_3_iE57BK+- z8@39@TyJ29@mO#wY%N7M#RSEbWQL?%fp;NpA$CDlq0xxvNb-oRN%eQFVZ*3}AJ~I# zBPPEKe`oENetKfsYROCl zi;u>iG-fM`E4{VOYFTuJdWIdQf|^5{t!x75npl`vecM^g4U`i!=Q0cG@BGj7qH&|7 zhIo0}Y|A!&tkbRXwOL)3R49@GJgGkcssW7hI}V5TJr5~US}8_;>xoTfb(8tFGn$i{ zd&_4Vo2?{tS}ZfHWE-Rn-7fGZGGlRRf@$YnU%zRov_{tf8UVTk`fCPeUz?jx{oLg5 zWMj1yeX7kbO4e68y*g{p|E?}*mTG9}g6(UKuco|vpQhmo!=wDt{rI0rd8B#o1E!uj z+T{w%n@$G&_xw+Sen9(8#Z65yXEK{rJ60CC-5CGspV;vXSlAl2t#l}DO(TVhpo$<3 z$a=WA8xV`|iLZ-m^0Rm_u!C|mj(lfwPQd3PUfXvs z^~lqo;tWj<&O81%mb>)%=lzC%CKG@offI}%j_6<&G`J+l<@McaNZ0#B;ou zAAL#KJ5yP4*p_Yk+&$L$c&zzUebnk=KeMUh^2x9DPwsqo)N>}7$e-)A-r$s6NcdDp z;M%x9M9^fjo>s){{no$h`19kpq0nhb5aou<2#p^ttBB!)=ZoBOQby^J2;;l{^W>j3 zk6zCg4mMmt?l=A0mxbCaqq5%B_xVe+E7#TAS1p2CbHlVQl>nDr<}=Oq&EQPR7&G00rb5ALAqOCQ(+VQbYZxsF_J&LuVzhtg)oRz0Vr6ku z>9S{HK(LoJ)w-`s3ROfPB=>=m7|qR?G(F5d0ljPVZgC4)q*f&j-GV1Mm4TP1>u1&A z=hI5-ouWi}hVr6@wS9*(lz-bVjIu~2<^MGGL{-@osZ-Qd*Ps%Etv-4sj^q8rQBafn z_^lVFj^dB5$)2 z=!)CtPznLy&KiB)q1oddS3;AEa?@G|Co#?Dc*Bi zCNt}qu+d!a$P`5VuXJWvW1+tO?q&z|Q&Va!Zc02x|Jk}F0|hl$hLLfEi`U^S=6?&m z#uMy*1>Xl|EKfPm#Ehh`~FBNB=cUz{%@Dl!89XrZSqQ<(0z9_Xrg|_-U}Pe%N;fG>sT+m)ahi_TONoeXkO5kS(yGfww_t zVYy`%47RmX3_cml^>D}V9ZP?*-`T$WZ^GiF#l`gS@Z9Sri>B%dj<8^QMw{N>&-Z8! zpZ`W*(c>BIE7iC0WeJrvyIB*vcd?701-JUXCx!h2^E8s{sr;w0!00Ex_YG832bg{_ zzvoPD8;VVZg3=>{z2|2_7d#J`1bv7+o0ZcO2jsAUjrH)>W)hRhrt4S>A%}MM0Nz7v zvARl%zpwtoT}YhVhroja_|~S?vR^B-p~5dScPF6!;o++bzD)oBe46PqlM>HigIGvU zr|p`=$TwZDfdr%ih=t|NA4LSHt>^j5tUS&qGFMR_!4E@OYx1R2y z_jVCEUvV`vHVkNDyyyEQLGH>57~Rg!fLK5rmFtkR2l%&ZY-#DaN}Ij801BnMvS1%v zsTJMo4;{mEI6XdYQ&IW8yy}_EuH1H>l9rViTdFriTp#q`=K9{($&E2EF28!flFLh* z_Ux-T#a~_hZl_>}QFULXz)>;fi|)Y5s}YqlBD)Xd#kZIj8L zHCIStf9&y7F0bCIY`I4=3D?pz{A&1iI~W-u@@P7ozI1TVYimcnddqIYl6DCkQX=uKcRUpj^d_kz;HP4Q$f*F8EtE#Pan5n)(2X{SPm>UKBYsM%Y zeL8)U$u(wXEax2yX8C;f-Fvz3<)aYc^K=SDe7d zvKrmpVI?< zdrM)5ib@M^o_lcDW+FBEFkpR+B;VAsPCL*d46 z^zfLR&*9dxaf0PAmbY)gDTy}A3smJy0+VLZXcMwao}24Q;c*IHv#5Q04R~k-8q}Fj z{d~RWBzyYV{%Bt53R+n*F)RkQLREhC25Krh?!z z;mMlzX81=Gvdo2_R6r3T+LvPsomV`-m!hF%VZX_A_IotQn)YE|aOb^u>lV{nje(6A zsN>8Q#b!BOhOD_AavX9HnT4(QndJ69s1)cQC^)`!Jh!9MRyPc~tf}g1EIEu?P_FfP z*n4Nd$>llRdAj$roXW&A=`o*FZdKtf`6uWJHv4XZQhl}y*4KZJ#Pinn+V5R0sxim- zUxyr)WHEK>_iPfo#1Qb$zr2AD{jNCGO4nBcc`if3ue{=QnnustOTC`$&PbY#gEEA- zu;xD**8L643gl>eoC(Mz;G8r|(=k4%_Peh~#DxC!dgIJ#n+|Kg`;Z^OR9Eo4;}p>h z7ucfulHm0FRI6G5y&`J{sHTV9GEK^Dy>c+IV`uwfV)EO1h7mpZ+eQt|e_pOTebZ%h zf8hh$$7`M3oD{5|rvLrUN&An1hYpU0JJ4^&COd#71>9~oC_ zt8{$J?AXkTVdElJ9*nliOTSLC_pH~Uf{j2r*H|XPk5VHM&^&+#qN%lb=)4uk4^oJ( zFlL_8*2u7-yISLxt|5fM?UK`eT{y}UNAB@FEoEiHYjHS}9OUD~Ml zA2~I|d#Ay${V8nn*G@O4HiIyDATQ*cyd@nAsYR?8sH;Fg`GqLyW)jd*!7)iB*lCI~ z57Y>3&U}u-bw5CAc)Xc7R0B55BD#gu>xu!)u26ABaS+M1 zJ%nqj0Z(e6?yC&5iF0e*GF=_3{0w7CY3+^6Wcs`I?B)zZ=P_iFr@2prgjFf2oAz%1 zCJ^rOf4lU8cV$fukDNK(cebDy$-`>=o=)(TabGC*6etn$&`>> ztyS0hCVSj!|VpiKKx$N+HhmAq_jl%2D7yd7IwL4K8)d{$VFfYN%?Agd|IZ0C$Zx> z&;zB7O~g*-Q&n6uHI=%7#kq@S7}9Rcj<1Nn>-pwugU5G>4*~%<6sEJSOj7w%BtJ2c zAFhE8FLdej&%N{l$gKZ80T#v_O;}iPy2u}n`-1KucJ_xfEh1>gF%VINz}ZW;kZm42 z%@Z;&wKY7z#~8oUh&-nqze7f&dI(|C4V=mUQM}K*`Z@h`fe_M-8a#~7$@DZ ziB9)b9`+X>ah_K}ik^Z0jaa@TO$a7deKHl^ALPEDIx{+a_`y)At zhT)!8#Hx13Yh+&NZDl2EsgikDT;);3B2KD?8gSn5cG;KO4gn(>+e_`YBOL`d?*2u^U{pna!5peJRx?g0Gwp!&J(_A{snJIvu_i&0)na_R@&U%a%t|0O^JN*V&O2*)Js!30 zPrs6&Dny{vBZ=Q+OJbA8{~!!Tnl1i1cZ*0;WH~8NW0h4j`?Cy1p+cw%f&-O7n1yW=f5mT~fU#4H-pI4DgO@KSg|8wziVi0F%r`&!zu?z@l8I*`)?H1w@6 zz~0Fa{5}X*eVR|6?V@C-v9t?xuP3s*uS4C?7L)Kl5*&yv&tx|V`Q@NO(Ei!6SJCXU zOvM^`1~hE1K(_G~-7?m27ww*WB&4sy|EH`l{N<20bvEB^?onmnBW?uO_E^`W7-RuK zM|z^6Zoz6WNv&VNL)ZkaqNI+)0SJ^GB*(+DK?Tn2mb0?SvbW-fl9=BtXZMf8*w%Qr z>te8A6A&K9U@ZX*KfgK$zbP@03mT78vh0?+9Ij3h2l)OmhJXplg`pXkRc&yc6?319 zkuim9qCV8WJPCrHvA6W>`E>eIv$ABAq!^japu_d#e67*vGj!JH5n>bK#Q7)%%O*eC zm58AxnWO9lEUc0ppR4Nfax3EsSMjEgIAV@$cK5u~`!r#6x!Ydm>$=r*&WAtih5eHs5;8QA7UIWkxQlg7&0lu*_Po(#=slJx zW8}X^1DPLAz7xOV5eT1{T+aLNuJ(dyY|kky9h|xp!@AC?vB9?ly-)4>AGK6 zj0|mQf4Rwbb3>)}OB)0I9k~byT?;QyX}MB5R!uY79`e%#4-*xhUBs-ECd#WqEC7k! zwO#qJA>hmU&y_^B&=>;|^Kj1opyLv``W)aAK|DauHRuS&?NV!)**)qQIq)+r z&TFSfDn&uL*LI8xY){DhpHNAWx{?X#Z>UAB%iRi$_>r+ z{B_AC^jETTflPmyl=%%LP%D};%|D`qPMdxGw9><4&8T^f234Y-lvE1b{*}P_%)T|( zEl}FLmpHjpGW7EUM3D-I?PmV;AC15ZS$^&46RpOE_%?AA zi9CyOYirlM!Y1~(Js~xgZb^;z61I(n%Nu0AwL-bQA6)h$DE&YisT&p*QcX1Vxyy52 z?mk$Ak0}P11;wfxq;v*1p||<|a&*DiCr}*7G!XG|y(n-oAbB+0^ZHGHrCGj80;7;L zaooKpm>Sa1a1!KBJU;pg+2VxdTz2gE zP0^>jQ+Dt9G)e6%^wmjyP5*H5=Zih+Ykd<6CK`xGF&8rK@$Usp=YPbk zcN)xi>V#dy@e{S%Irc}d&#d;ezOr`BzKjHD#}kSYqX~N5yw>)38@hm6TcwvSfBXw| z*(Rd!9umdIzVlfAq_z)uO1je!r-zH_{gi0yt)FA$Sk4FBQ;=S&S2EW9Ew-*dRnShbDgje^f2i73by zD>UxKOB4dfAPZ#60+%9d05}{!l}ZZ`;xJuZ#PX4MwlJx_Brcr&{H%gc;q`auenA03 zO$YG-+u$H2gOeFCtTK^{*Gy=(P%3(IFtR_Hev;xY%gFC62}hx|AltiQ3r2Ck1FtUhbopmR|MzKP=aeVQrpGPG)Wi`!h8sq$sHDGPfO??05VWb+kw%acU zeJc*`cl8|U^5XGtS}f{o@xMtbvsbw#*V#gBmLZ6IDHY)cZ+Ff~WpNDIBdxO^%tl2G zea~?eVrHDvIQG0HW*3tIgqcC9iOT;;er^g5Vfd@~7Oi_K#a~9auA@jvqMpNmiW| zfK;LfpiycXNxox}A+Sl!(iGpNr=yvwVL9YRYUwni!^qC5jdKs?qWjS>quW*s1-Bj<0apDtA54 z1?f3SZFoJQ=~&Ka3fTT{z8lzmM)-mHg_b(s+s-)zt84VzOR8-9G#|$e|Ixj#4Hc6d zoet(Mala?XL|l1wEXgP8TOY)8$_QgEQ}_GhOznupS<}M$3Va8)-xufZ0%d?|RIGs7 zP22Ad$@!WCfKh|-1>6RagSK?7B0ZXhAab@=gLAQ)l*0Hho*lft198@j2p(yHtzhJf z^a&Oew~Q1ZQ^DdgC?;4|Yj3!zaiZvlF%2{oD=`e?T+vf))(xbnkcViMR#Wyt3_8MW zIlicJCg~3kOJR#RgB$U+OfJN`02Lk|QNTnpvs#$Y7#c#!M)kAG41r12&5F)3*FZ$p z`y&|uKn+i#j#MI-zth(xA6ox6jCB>7TpuNe+6&wLF>7ZPO^brHdr<#S?B1G_xUP{ihGQ^EK4lv*>4v)q+6Y-p|kOuwKy7!!uj%8*K%4WE>^UZqhD| z8lh*Wwy}`B(Szy&`_$@S!rmva)- z_w{S>n0_=cGr}A=FS;!=ZD?J!kKnm1mchHU&+zgX)=OE}$*hU>aq+WB$NV@K+(?1= zQPaJZc^HoH3X$@0DR6*S^ULuqgsFa6x7p}#n!w+jDxm>=B#chk^)5}KV_*T&UgX=r zxesXQ?#5-07s;tlhPIF3I3qa~5438sj03>R8K4vm>BBi}-tjk3MnO}^!H%D(NZO`b zzyCa-t7imh?@FVlkz#O@E67WcJ1pq~GNX0-0Vm79(51JzQdl%n_BH0`FP;7xLmZ%n z@vD~jbW2{Lx`8nipM$2!dU=^)LK*l}X{RT(xI?WH^Jy%ScHOV0bu$>wB|vJ3<|2L5 z@0aS3Z}s&pp0y40TY&oQUe;M)Kg$!S%Pg7iJC)GkD4OxBlQPs=VvG zG7O1Ycy0&@q&Il~g>_86)@W2}*ErEOzowxnSDO2Gbn{XsA_iPg`aiXgme$4qe7acJ}Jsf|=rqO0A z4)@q#*0uI{NLidEVdo-AakaSQBB?I0haD4A?2yR74>o&J(4?_M;8YC9VP>{EE7H(H z(fS0X239A9t?ebvP)q0r8@^0({zeYl-iB`u2|W27ulI6lzZZ5I!twI7avxelI!(8x zI?ste7xjlKrJ7Z)@k9(>%0!TU>*V31+IQgPfr4+0xSQ* zIReYOsnMaOMViNk{?56`!@C;M&ntVOjkYc(7!?=vMUCgTYuABZKGD(U zz=Xa@R)(mwdG5gyIlsSZtt_G(`>niwWJC$ktS!=&1L&* zMAOaC1$HoUq-)&|49C0EV+`&+%C8fQztn!JD`=LbErKHzk4y#Jwg+d+-v=d{Zg6oi zCV1pc#6FAJkuEK_ur6ck&9_J4420aRM>fu;3fe3;&A_0k9@sq%VjuQFAAv8P-%=P$ z@10Sv_>8T^oAzrZdtS_<8xt?5_jVe@d!1ySLaul>F$`uh&4fBWJildl5UbG&OJN6; zd#_QV2)#futCX3%C&p$nn}={{da#)48(Ec&m3ulV)JjanQ*o8x$gE1gP%5e!k=Ul; zkEx8E#Ss=hHHDcT^}UecE%6Pl2OU3+FLDx_+zpKXmS1IY1Oi3Fsn@PGSdB17tx zsQK=r=1#|Up-SpqMxt;hmR?Oi^99?D6`Rz`dy0E2yr^5`8uF||IYJ3-Vp!Uz=|Zzk z$(BU!@@oAlH$Bhd!#^vHnnj$OT*nd>^?xYi*;NK4`Ei;xT=f=H9yhlrF(cNw8fKoy zPZJ}~2iX`~9znu}6}8&DcQ)Bl%#j4Dg2Vi%f$vUdD!P*UBI@e2KdtGFVz9)Kklpp( zq*7roxhg@NZfL46p*5#HjZN0RR)nIR4%SawTD{&w)vfpL)K?G2@*4IM`DB5mePxIu z27=!uSL(|AoMlLs+^8&a%)p=*WQ5FSLA>SkV+kugHGJ7=TY+!l@V_{$R9#gX;(CJ` zW`sA|EVF3g)z!Ny4jis=&KFF7njS+@isC6y;r|#O#Y#WT#!Pm4D+~`wU)N`>pxdZ~ zSkIB7pi9CnmMm-J)`V39EwQmT05mhHi01II>VE8OPl3$N2LplO1x;EAJbN9B=Cr+W8eIeE@+9$8PtD~v@- zf3VYkx!>i}UYNSkKDRd(D0Yd+FKW~%O+wmBKsqJD=Xg@IYDU`N$b`Bn$+u0M<>=e1 zvwDo;DDdiSdyRNs-ryl#_qy7iN41i5OI=*)5ioUr3ryMG0Hx;*5W!9RnoNUZ;Kig9EXY%`PftVT5&B|8GEdWhcn9MY$4=5Tv|j{2`#QwZnHZ zCKHO_j3Ug-pEzNQ^QnC~Hb2!7+xu8%3c7Vmv8)t_Bi$R`-`EyHy;m6%gHKX1W$ZUC%W_8DAT$DwPG>KB}q)eyLuU`q51GosH_YM;poN z8C#j2SY6pVq7H2wqwob=$wSr9Gwnd`F=f^*PQHOrFWsZW)zR%qx5 z@CJWu!9fmvlJ!Llk_dv=BtJL-kfR->!NcoO63$p*EK zGcd3D6iesofKiE3bCc`dulq1U4{z*K$M-kP)sr4`KQEdSM|;Q&kYggk%^yYTxu=vK zo(c(tn8+99_TQF;!pzhW4A`9qbRzaTa`9ic4;b?N6z%gT(=ETr19RQmsfQ{mEV*OU zNquLT^zJ*3?(QvsYHV9rzZ{FRa-G7vNd*?sc2^8Hmc7;^%?=eRotGC^Z8D6gknx(H z%dQmWXVRBkCk#BAjp!h9n}|*K)vh4QaT%GO5S}|WFS6$+wx)f=9aD2ViqD*L>+ z-YFtW0N{g%fVzDCkqr<1)NgV!S35#Z(a%%PMXWRqu1J(XPt27|OmqP#R?X4!t|Nyf zskCcUeXkE8`*B`zBhLNzCPW{+6;3B(J|yR61l(3bQz4!a@^}NypkGa0rMW_ugutWM zxI9m_`dDrIICykuYG^E7EAa#MG)oR|#>a=3mts-U?&VGY&gTD>8Jc7%lu7frF>sSX zdF<)c(@Mc!T$#~GS|C&U;&f~Dp6UDKZf2(DE42Sp;)x3NPkvJzVKZCLrJ4qJfeF@- zt-F%1fuUg!fVY~HHc6%D)wacj#$x16&#>3uq%$(Vs75}wC5G@o3BQ_H!1d3tN8#tY7*DWZ?)0y-~vxkQXl+u#h&zIRaN3aKUbqmM1)%ax_u@z;mGJ2(4*w;}m(6ho& z?X@joMyYs7OC`{%ix%ZdBHah*0S{kYTuM<-vM8E#o4W|H=3&!WJ^)R3bogXDEpY>2 zK+kh?OHWU9_6VoN>~cwI@wegF#_g?oCP_I3QsBA@QkZya3iMw@A&}nvs>ywY28q(P ze#4+a&qwXd9l1&vdW}9wc457_SdOoFI5A||o)cpRGR(Ipn$2d}Qo{7BfsjwUkb+Db z>sWYYC0e3r>tXkOrs6^GU+ES86D9o@v015?$SD&C)3mLIt-v*HW=8jT(Y_}J67Mk<+T4sIj7TUD->lIGQK=qWHLH%|0x%1-QH7kX& zP~xI2LZz@uWy#evPh8-$aUy`GwwaD9heQ&3!t$WqMG)U2hvjNpV-l?j7oRRUVG;j# zPw_FW4R?+Kj>28qIa`uLtnF9m(l1bjTa+i>f97Ng?UV+?OMowj zgam>oMaSO1V9vCAJe_=a@b|`EdAh0o^phOE2fSNE>p&foJ+FFyhd4iOc2&f#Fahs4 zZ1G^TEwV)8Wz6`R7rLZ>N&6!~*5ECW^z}zCaBy4aKXo`xkBkQt|QVtxL zSa<`-TN|{wz5JmX8K>g}P+%cqLDcbg!%tzqu(9kCZxba3g&w*08p`<$gvVCYMvg6qV+f17|0m+J5eE^G zoA5-qE%1V4GM0CJE7X47m{i`LnvLk*iJ9VYeWk#rfN*IF>cqS7lp|tx48Y2*bRiWR z#a+(QHD=#lOiSBXw5C1}iro4WQDETjb?f31)$%%4CccOJkg3Pwk=fk%B{eX!2ozK& zH1O5Ad|bx_uv&>GazU&yrVL+#bZ)%ZU3qnu5sI9aT}E}2H$NOOVjA0SH(vx0AS38G zFolOygBu3-SUl1v_eh!=grB`0%bbb$e}8li7)$&$n@?hoH&E-;{aEtKrZi(jyNq$6 zL~bAB_&~x*RhOc!Oz!%TUy8JGI29C&j6uqsvNd>Y*C*3Hws%}|T>nBoLzDy2>0k;gZ;S+44}JX`YrfPv#Lk@MIR&H$q{+2}<$Sr{#g zfP-RSHc*m338s;=tHZ4bi?Kp5lApj(_B7eAJ5gcr5tus23SUmO?_vZDQAY!$SBa1F z0&+_+K(_ZO`4V!*eBPtsn%l!;A0Ro+pO~}aSc7p$c&dO4_ieAN?*;39NvgfCcF!xt zlUWub0-v?V`n^ktI@S+L ztUvL!pILR=woXvj{?VJP72B66y=>DklZe(bedg_DFU@_5w{=&o^}F{Pf&7O@X!hI8 zV@B_bb5U42EzlO8#3NbGLf?gamEcf-$fCofN(gXM%`$~dv!|#5Rmf6}1s%)?m}dth zg(BW*;bdlJru6hG|I3;hr;*LMVkKrHZ-^CmDsgjc{lrNx)c4(jvRN;L!K>*rJlNHL zV$0*XA(8A3Ade-NGxp2tT<}XuTy2?nYu%^kTY@bcTJq9=u;};k24xJU#UM)6RM-*$ z+onMw!v@6YEh6V8gLyUXN6n)@*sOqccglxS^((N<^xGI-)~OC@!EL^T3m>GXSi z>zGuK^ZYc-KJ|xj+W+)L+7yeCWXM{&R z-B9GpVx>>N)BP(wBJ>eNR3NqyXD+w}sUsBq1)lUM+IoGHN0nj^q zJxY|vhMy|kl`1E$g=7kt+M#P)*SSFBJ`?<qem1^)cNU*l+dv|B&i?JKS zMyxLnLhfBxe~(BtBW`Ey(Z#-3h9mtuI;Bj@)sF?kd5y|-4|n(Bs>?5_i48%rtz$rv z^UrUn`Nbu_dGC^we774y=L$bPzvXtjU>G5l2*$Pv-Id#-H;nyZ+{8d!f2Bdt)zhox zJgmHA^YufeN61A9-U{hMhw4nY{Y};yvHl~9hg(OXyu3cSx>HeJXjPi`%S@I^#}rmt zO}2#wrvTh+=!i#C3(KhajuD;0McClKY@_Xz*O>PHbP2(2-_3MDZ2j|#AaMU1mSG09 zUZD8kmpM>sbJH!nf{+92j2B5@9_s8u zkQMP!zL;ao)qBg=hw!6U76eioyD&!cC$Nb5!MLEV9y%f0?jA0qai+t=n@{lW?)Z3o zt$|==70N#U49H(w%|#plNMesySNAO}Ijk4-4>!l*wubA(YZS5_h}C(GmRs)hR!{2UEa2<9Z>&rP-u5n_7=8Pw3aKKu#(&t! zZ*FD_d2CK}o15f(6X^s7(v_@crwWu__L=v;V*`*axXeH87-7JieYq-KJ3n}QF4>G?UuGJRBP-q`vF6l-R-gAlCG(#i!iI(a_Rta(vm;q9!x$k3=fOi6=wlL-ER zSeE#wrlQ9uX2|#);l{#R=43vW6$j=6;{rJILc;HXW6wf%FEKPIXa5iyF3%c+@L=XJ zC%W_Y>;ZEAqssffxWs?;Tc>lghGzI(mQjfA6Q}__4Ze?xii#q#iAuYSJwXc9!kfD4?jgDMG1PlYFK=$at?PFPE3+rwRB#fmF12Fw5!!K-U zdJFSV_a7|jg)dhiNwZ0^*miCrSGSra0GcJs;T`?MQ^j8uF@fBXzs=jj-b zo0;8tRHLIV7|;)``+58Jn(v@_L{c1!g}Au9wy!ovj5vf8*Ch45(j#fH@UpL zY^u2YXK~#j2rz&rg2F}UWbB88CZ`Q+YnL0nh!MGCJ@2+QXM`p-bU4xxXJ2TDKXdBo zRXVr726cV^dm;{rwZi+sLeaPr{gJhll2UDE2Cb*tQ}1q9AlnUQLo1cARYz=eBb688cuL=JL8E@G}K>AuXmMOn_mg>bTsb=PEXs*fKMeq z*ys9{#5J&ME00TiewGEFRq;=uB6$9t7Q{0{XmK`cf;Xb&x5KtEKVnU`6?39hZ+`$x ze#-RcvJrkN6WZkyuDa@$2>%)@dW2w7!eoF{XCAU^Atq|Dv&EjU_e}_V{&k5vUD$4t z!$i1&o*H0=EH_qvwDFb4WwCulFuv?hey>15y5S|-mS}tl82%pSf#{1v`Vs2X!Ktop zDolUwx4<+#-J4vnt}G&aQwwS4M0etp;r!xlj(AX(%;KVYwZ0eB-11^}i~UxuuI{N{ zfGJ>N-my?r0ZWtV(xG=z#WQ4wyfhh1e2BKgX z4{*c62m)4WW$g`Am$J#OFPfqWEy4+3@;#?O{^i)KssvSAO>JsZZI!XC95@Axt+>%a zaz>$WeB3y}(L+xU$n!3o8G;N9!b_`dqhJ-8?YpilzW^zlGy35eL=Z^ahLLlA)f7!o zPRsc8xf5TFU>!}^V)D@-bhTstK*r>4$;>?e+RTJ>byAzBOU?buB(a7^4?Azz3YgHv z+4HZ@%(H-Q^%q1V{ zEhPxLx6}E+?DcsEhONEuG}!pVHe_777p?sK4^X`}W_DxC^lt z*uuKl(w+5A_EoMKFuaw)c>q7L_+@WW_2^#84k)#aYy-2bXJ`THD0|f%)NY|EPzlvO zzd)9OI^AfO>}$3)iqL_(Nkt4l`=)<{FBgJ6xNG3cRb$vMx|uA(7JvrNa}RkN6VO4T z8cnTqCKmiEhz#4{D$UcWmG9WjZV_&9kxu^5bH#f7x}c{^h!i$X&bI+7DU9^lt`GaQ z@q!+#r!qDWGj;P?EOu>VXZP`^5f^!k7<|6#{H01T3yvWZ<3{t>2QI#i+8u5U4Q%AF zgN(_}q5ZkxKkMuE0pKm0@rjM)8oP1RI5Oevmn+~5ulF|e+WAyU%2lv@eviJ8b@FrW zb5m55m42raF5!xM$iWaf$G6!$v@9Izz)XcCZ-9KOoNv0CDE&t92C^i6{pT%6_`6b| zqjt587~7qY%Fp0zE?$}G`*G5?$QxnTvhLmyQuArztfvTJ)0z3+TUAh{(VAx*-!FS} z%60-yio(x0OSV`wcMv5)_U2p1q26)sh5HI{%dohz%qsPhyb5lBG-*X?&LJaw;xfZ; zwwyT}uE)Rc+|&JO5b#rIHMQQW%1{1$&DSA%Y7%;m4@fRr!{ubgt3BTUfA|-rb9>bn zIN7Y>-I=wzF<_6K9hOmpz1^z?#+P$1Ac}xrwoNy8qNy~=KotuP-Ogy@Mbla3T3U?P zc6y^gSTFS-z6kH_aq@K2$y?F_M~C(_!(4%ba3$tLfPK#?|lPa+6%) zCk;jzFCstkkGg4pp#Lubs6bc0c7&TSCJTk}#=IN^aIsfhmKe`mx3oYNv#>MIyC4Yq zOQ&mVo8Q{{pXKG(nD`K#zI|;Y=JRmgE9oD`Ow|W-xM*&^4+dIQ_0#6&(}JMP^J;_O ze?9O1%F1vk+4m1*@Go%vIYr zvx__m6J?qJyl5bW7vL(Me*L0rf}wiLV@aQtm%k@10#;H{VxYvc&pu|)J?*!qiT1z) z4I_5qL^EcL{e~bRc}l4V4>pr0+ZcGt&$G_5aRRjfD{mcty#3NOrB;NiRz)@e+S=_^ z-zeDx_o-g>UESEgDsu9KY$l$&@3w1tZ@y_Oiu%_`R0D;pc~2CJ^d&~Y*g|2c??2I} z&uhivm-G4BLZNREJneaVz4TH^nq7eD@2abRT3!9Vwze~xo9C35|Gcd1?3FA1AXwme zqXV1AOc1>8d0uPl#Z^^Mk|PR*m7X`Ywe^>|Ty0B>{d`?{`P@QbtRO(fFIq7y#w=qF zDKGyp>Yh}*Ao_eZxbtU*R(bg)g#u3}OQZ3;@vRmH7+M#QAhak5J`x0zjrq1Q6J765 zEIxc9TrrsJ`~3@r{)wuD;@$51Hx>#qd^Cpz8C3$NB~HA)kBa(|=bc?B3=Vgmyxh`q zVP)kE%A)MKv846HZ1%&&;@1m>iItVZo0}i={eFeQB+q*@2o9>QUL%#QtgNb~#XA6ZPbX^#n?}IO+eZPsS_WiLp7UKQBy;m}@7J@3B@g|8X&Hf8a=^BNoBXqBO5@Snc_ z1<$)HpJyg~2@XhBjcIIdUK=t~wCM(tgE=-gqwM^t#VSSr$Y#%MZoVy-``my5vz9L1 zFWhpo(D&zLv#8;_=ku#VlM~qbWS>44H#NQG`>Q?g$2B!SrUQiC^d1I$Jo8tVmF>N5 z-9ara@A&>V`}e;wJbmNt^78KkG=jX4FB}7Kl$BkJO1pC9L%#n|c(B_;)IU)rzwZ|B z#l9k3eoDck6)UWcxp=X~P*ip9fTsW@9FxBV3oKmL)kR;K)~WbIhM4!f z$3}A8aTc0KkGARd?{86(q`9WLcq%oPoX7|O38ivm925s~__D3s>9@J4L8+g2-Z2Ls zY|ks8o~ay~X}8_%X{YJ{%ssJp#1&MyQz_coX5?}oY;OK^P0iKK&7bMh=jFHGhTOc8 zNTF+HN|GO?$7C|suU>s_L&JH422IK3S{E()uK@$T7n+tD-+HSo2yV(`b`NK*T?&Qo z_3e96Vz|Se3>zOg}PyN zp>VwC-HTEN#s$Io+3b5;T3#wE8{+#dLGZ3I7s56hH?^fNG!UbW ze%te2^}O?qS!&FAK`w21a@+cq$4F+5+x4%C-lHYc5AKNd~ZjU8*l&!2B$lxX+f+dTN7 z-TK)#G*BIRq=n|k9<$&}Fs@NfbwVgPcSnVivCsr;uYp%;TN4a;O42~HHan>*H1X_I zU|Ql-t4{LPTV}!p%kgPG>UQ2dJD*WeT=Rd;nn>$cC5!Ea+S}DtRaet+g~A>E`qfob zT>q_ay>ih-$<(?4)4_uW*U|Q2AH8w-@Kx*9z0#*ooiQI9G2-P+rp~_Pe`V;hz z`TX6U_i}kTTHcdoW##MEErUNA^WJ>^&t+x%qD{B7oK`5T^1PEFXr6}xcvod*Yq8jt z$)HqzBOD21LO8yns_Glf%`1H$LN~Fs_4+~q@VY1n=KB6$v)LPSxoa954=EJp`Tk|) z<%j0;_m`C&md{Tt7Qw7Fp7%~JcUEib+DvAb(7-V|oBeJ`5|8ZH@3J*(=xfiEm7Si? zLvTj*?+@*I&iAXs{G6Q0e2QM^`#)N{7SO-S^S)nM`ODR-7pf`?1r$t(+v%;XekSvc zOy(=i%|9pAxFbL*kGM` zdEU3yt^4uXwSUiMZ?3J)ty}kJxPRWQ!ZQE>AOJ~3K~z4!M?U|D%F2ahWlt50b)NUb zfddCrR4mA5r-hU7`E6}g+3c4`jRHXTDi-%|ZT)pc1ye{}2nv5G7Ap#c#pUI7L2%iq zQ4N_)Ip|+r{@D>Dh8BynJ+DsKR4jgN_;4z@Z?QNvTzYQrnt~p2^RUCTGEp`JifxR5+*GgQDwf*Mk^1*t-3;EC}dwScFfp+*iYlKbRJ+zn-! z_#q&SA24y+G;{2+=IN)+e*2kScQt$MWoFK_m4cI^>{1)jAe7Azgs!($%YH z(;l)S`Tlg8EmT;nn{+(w&(`{&8!+KG`LeqXqAv@=n2v2}sn29iZf-ti=+NhuE&KL> z0hS4d-XW8hFYglsAkOe0_)fomXRcUr6tlE3Uu$gq)Y`REv)M!P`LS(nUmrARb~bxu zOUngKO%GO9euK;e!AFM-*{`+r@-=JjsHm8g&3>+-0g5-!m>05HhWHoz^@APPH8tHg zckbPlmHXxM|Ix4Cb*omLiway<_uSiWKTuu{Q9W?QiUG#_EzB*m_VEJ-Ji2VzJ*d58 zDWCt?;K5&Cwdy}n(11lMH{?*mSFiq5W8>xh`~O;pLdJgJGnOqob-;l7@Onj4(^V^1 zqPqTsaiSMB4AM1s1HlFRW8aM82y)FcF85YYk@t&WU zFwRb%k|_)&E&8RipUAzOo*izKHV%0i|L?vVv0Ygkxk=BSGski_G6o;y#aCW2r<`KZ zVb&}Q6R5^qFIi#^I>^2b7b84WK&Z5IsfDeVUNT1?ZNX71xr}h4qFG6c82A%;vCkZNqY-^x~ z`<*Q85}|Akswj&bY$!oFr#ZY-UG_-%2ct7ko z28kGTIL5~FGtA}ptE<274g-&&`S!}n+e0stYv_gKB$Jt1Uj7pq6$=&#T_ZcpFBO??i%_4ogvOogtjp)jUbYqr^wZU@~LzyKU%0U;m3LC%JSFY zCS8u2=O_IH%EnWmje-D${GrJb4~jGK@M!YnXx)b7;Ed#i`4uoltp?+WXU{$D2$B5@ zU}Yp6e6Woij>#kbC=sYiua@KCs8KcpB&3fcxuOX``6)YtLplmVU{z5_I85koAI*+r zTj8m8vf)~mzq-2ipX!`)ic&AtDI{ui(IO2xiCc{nhLR}dA}|n1RN=03`^UTj-19C^ zp+wWCN1g*E8!mS?(JZbp3$oE$s4Id6Mpg(mI)n8J2Dq z)P8N}x~Nhsbq2qzoPr7TP-bc1Pdo^K`{zHSI^kUcFmKZbk zeA7~0K;hO~%?T&imO_Vp`swIf$0~)Be|b}BXHgAM$<)T}x0?@qz^Xg+UV5VjBOOw` zg}Ig{W*(vyzVa3GzynqpI{a`u6Z5XXkQbe;KOx;PQ(EzybE5MR7*2Fnv?>ylLWk}k z*1&+d?KX4r$=0U(;)^x_eHsEq3^X%$oM(ytyW|~`3J8*4^yWS>pt9*LL6}gFGPrKx zUUwr$U0krDIAuYLJzydz6lo%oklwa0Xvo*k`6{^%CoEHJF^P^y1pjFa7l|Vs`nl__ zwp!fzJ?hg`tUMeTy^I!!6*VTO4W**o${?r|$t~@t+SAI6)H+2g0;s{P@YIrQg<69a z=aSyaxOJ{M5JUP0FY?DYeD8bhunfY(_Njk>jJ(N2NVB4Z()qX$>mg2N^~WE#IQ8<& zcGA{yM28+~^=>c=S(o4%$W8WSE_N+45b>VYRsz(iHB0C@#F1_3{@s4 z6HbRfhPIF%c%TIZ2)pJX6*k$old?0cN2wv`+xOmU&OhH)n*1M_a;P++q|hU@H`>5- zV`wauLsz7e)3|i+nKNyx$wHNoZuaJr2GgC~uK)$2pvwZCw2*8-j3|bjP!HG!HHeyE zPz+g}$g%Vk3c!d$lVX_3UJg3P4v+Q~XBiONVib`UBb+;26QNiD<5@;A(1#c09RfN? zTYT*`BMqG}p;o>S1-Xxa7k%STy;8c+dD9Mcs+G5tVRB3S^6O$eOG_mlv;z`F z~scq_>$vZscl zi8W`?phQJm5Qa!-2%3YM)CxGU$<846BNN+vg>>pg>Ny$)LC`*Ny5%oN|C9cb0w!f! z5b1O#_m(a+jR^!@oI)klm~*#M5?W9aBI~=Dn(XzK2C#E`B>(c#mz%1IRem>dGTf*` z+L1X%%9++MWW?a93ZhL=Qa%UU`FwQ4W zj;uDI8@-AiAVb0X-e(?u*bZ+R9@cOW5f{7fZmUbgnVd^Eq4J5!d4MBYp{Ar%5j6nN zQ^0A{B4-^KBCn&%a81)F9tJI{-+AZR1sRIK*aQ1WPE(rrFZ~G+BqzK@Hn@Mj6CIO0*!hI2Q}QuSD_m)Rhwlp?X=Nt0&xnp^eHJ>WC&(KN>aGU z2OuKSK|BW^Y`YW+oz{yO{A7p`OMjwNAO$E4mQhr43?^!W9bNzEqwP49Q57HqaEX?L z2u945lZ0gU`uBggPw9V09%(bfq|JDCs`t}R+xQ9jm9IqOMCFn?tVLC7N+)u|AIT(e z37`;$45%JYJvCY*)`~DU$qb3|E~o_Lop6FBQ}Vr#1rzO6RF2dyywDC9;7J*yXw)Ro zCe0TvM*QL_YEcFZLjAn|{n7qH?tq~bjU?W9!=f8g3+g$z!*C)eC!QE>aRKjm1u!Dp z1ZH$m)gTmlF+ZtEeiDW_X(O?6@6;V}9VBV6U zR*Uj7MVZ(ZtaWfM81rP9pJc#UpBecSM7Bt3Nv@Gnv|XPBJ5W}bMCJ4@sFFS*B|wIL z=@!I8xrmU=kWYO)UERrHrE;Zf*@BgS-X)XN5`m@VQ2%s>viRsyiYB}h3d>q89b92} zk!E%FHAXMPRpW)}mdYf;vT$=fEl57Oqoq-%MolDihN)BSyVNQi;!l6F#y3I|ttJLi zWR7RVQH{?&Ys*5dKJtj2HMRVuq-D=d#Vt!v$<&g*fK5fgQW+6Y92os^$Ju@ouTe+l zGIb~6fM$LAr@CcAx<7(1({UMEv$1ofPNt--ATnRdQ%_o zKw#;8>T2S= zD7C7Z@KTetFhyVyH;q8qNu}e{pEQqZeTK|PiBWTC02>pn(g?N$VX}v6?TDT##FT#H z-0bAMLP+&pDZjFTPzeMOHfhOAgj7TiY^8m{Ca$G!OQDu+k<3#r^-L8I(Py2FTn{Buz zs|;GmCS-zgF&m+^aEG$+l`OVMyfEt;slNNw>fvy+-(*$+S=SZq?hwXEI86rcd)oW+tr(xW#AaxMYRh^9RxqU2KFjENGZ*D_Q@ zu@UVZWF!*?el0p9M;W4m>j~mza}b$AwBjrkSO}s!sxB=AQv^*sQU$2e0Ry6J5IIAd zpYpO4=xY|y+#`EA`H@;mhP`-?zfeG?8#s~9C6iB*j>QzHIsHTJrHWPQ+}cht_BIu+ zsmQ8c)pnuKej2gP?9di+nF8JNv{Rh5FvuTWT&8)VB8O6nX)jWT*wO?9pav*D%z~UV z!!a#^CgfbpFPhtUk@<}K!~=?XUUV)Aceo%z1_^;RJ(D7EObpCY%xZ+;;>jm%RPyJa zKHcVxrlj7a`^!U~oXE@#+A`#zkUS-rN=+CLdBOyn`Bz@CN$6Xl5LM=2qT(i5RaYlh zs6Ka zIuvNCbYi1!4v@V@D;2Kx$cdJE$ruoRJ4BHqEOrc;3iJAfw`D6#RAQ(x7w#LZhE}T;!izg4f^-rZ?P4GlKKzE?Y_Ik zqvxKpMn>_+-~ZlX7OaqL6DO1eD#}l?L=FK&P?*9}oV)L~#r)?#Z57eP*Ij251=C4X z7I_hT3ZexK;PQ<(BA$rsx~r`>g28cA$t0xBRF6L%r3gyWcH~eSTgksT6!GXV6kZ35 z39Jc5oQ9%lEKnS>>U`QX8N1=5KC?3{)~{Eb^N-x6sTP@%sVh1a^>*8B(NQwYNwf$g z44FFBT35KE0Zuh8TxhjDcetX9zUx#qc|r$7AKbE|G3|PH(v?J9RSeG2RXvguVu@R2 zS^Rw~EyXGo4Neo95wwP*J6?S9Vw$7GDt-Xw{bvO2M2N%AvyTlbRR zc+euO)~^wrgl1xU1!1U12Bd>{xg5E)cwOrWuGuoN%VcNPa!arj9-1%+~xa!!uABlhRwl!qO`D309gMDd6L#-trYy#CBHwg!L| z0)q}flJsTb0ZOO`!ZXf65Dqd-SHL|<@RT^E@AFekP$Nyt zN^*b`MI|%R&DDG)O)<5>fw!nDvP5{oXi&(3L569q@{4A=#WxeHcM`W`FL5VzI!^=V zufCIuTY{6l+v&=xaP>yIkTfJ}jQ+1(8-OgMfc^$!rMV#r0PBX@OnFCuMc3yw8I?5f zgqU<|o$sJc(EN$NFd%7Kab}^I38b3u}B80KC?q%p+6!E`RIcOQIU;_=$Op> zWLu;|#6cTiq&~OBhZwn1Gk|%K781BS+#~?yRm=oq&V*yib5P6K!gmHUX;F5vfl4Tb zOT%fy961*{5CeAzARQb`)CD2om;w=yQHn4L@ro8e$TNXybb^sIH)U;yr)A z1+Zu=O2;Fu5y`!g=A#_k&KK8%^)_lPQ_j#8FB}IxR$2BUAERi1&oLc3l4xA@2Mb=OF47ln)@=T)CS^!Yn=`1v-O>0+@$bmCca!0zPj7##E)&Vh^6!}S7jyWc=Qe7o^ z>{Bsu&Wl6_E0geBkZ2kRI-V4jN-;isR>Z}`V_B%8?IGF-L+4a0(*Z!$x;lHGcGPed zZgiBcz!ZW&N2F5{*yfg7tf#Ad9$$JXvdap*=#kplf+9wrmirOxgCRu1 z^d~KFlR5cmqWd_acUG}W^3MoA>n!^d6gcXr$Sg}jqNTjfs2e#la)r^9 zAVprS#aP{Mzi3Mjxzg$r$!T^GX370Px`q^C?vOo^JDHVrVjE=yQ%D`OqFqrl(LN?m zju!o2dBxsj)Nw%)pg#d9oem`;Dk9`5h(G}0EUkRZF*bhS=2yS6E&Ie17Qc==&UPK3 zhy0L#bs()@L0ZWYxqbLyduRG|i^A`HuXUCnJb5EI@=p`<7R+()z3sa+8R5wW9Rub1 zf(z_qNfWC$$`UW$e!DFQ#i0VVP5$}kZ7tCgNEc0C^PFs*l!e-(jnv~Quevzp0=qS1 z$v&esJ>r+~gnp})cex^|rKnPR9Z0RoQl@#ek;uMSww$2VdE_oC0}=n_l`OvF#mBg) zFOdPahs}$31enmxSr?8>s252+GKo#bVyVt779=(So7fiTmKL1#x!Z?xV5J@sTG&bns(is^)>Kv4T@di)kEygfW0soZb(MPS@O%U#MW~515 zMCsFq7&WDXqzn}zXJo=e7`+U_!w$1Ch+WF+53Z37d9yPHwDkYrgI0M2BNz+-2bomf z;1^_uS|cPQfe85z<poqa=$RzKcaDw^U-=a@Ps4+C0c*;%S zfHojk2)We}ZPIXwL{0*r2`vHIg2hw_0l*9Gb<>G(+8?R&;)sfDP!9yAPPk?&0`Gu; z8*Z>AJ?J3I=I*$|@~is7#*H1!*iP=2Qi5X%SpI1xS>nof(%V zBMebdB0!LvA_XLBO#5zEEoYII3D+%YCaEbTsz!H4BodX{!6Pr;eJAG!FW$N)McXL> zT8@)p#Karkq@8FB)k(JagL>h_|zzq*a56jD#&w(4`nj#1k+i5)PJ0dtFol~ zQuDP`sHbk}DM>;L?WfE{iMq|lZS7}qZWadp%ZMx<#n}18tvS02m;FtT=+D!pMg4@? z{ki8XKmkG8)CV|#ejTMNFx8SG4ZlLx7a7CgcuXmGH#r$f5MY1Ws(=ihTr(2$i!R>&wS$%M4phEekrMz)I_Ldd7x)dvAo57 z>XytCUZ!eiv8BDpgARHSH6uJ_gfNl{Pi2j9daJ5}n_Lqo_w{86>HF$S{1KvlaQt%0gWx3M^%IDRDwPmTb}DI$n>Sc+7-RY&DSKOG+w z*eP$auSpllv>&DuWmU+V$#g(8c*0>x3=TM4W_otl z-+83iaeG@?{JAYxldiFNM7L)wx5cM|(GPXpiQAm5EvE_T3QW~0g$_>90GPz=7$L?) zK1Te9(JiW+0C{ zye?N$(3bHD|D}N7IOGv{J>(Eu7NCk;Npa9NT;NY=LMgx_?OP>j=0mQ9R@wzbBxD=? zfC{0ym?y~+(}0+MG4xTV&hNV~YHwkkH#rQsud|V7u0d5f*i*gWxGaoXQIY*r zDy_Db%69^!7QZ6{LP_~Ki1(2Y4IyI_^}t2an?m>{HOkR3vdv6D%tBj-l_G|us}t-c z^l3tBqpfqR62C~UXSxMLfvi*IWF1Ssq7RD5^TDC5<9cp=)!~s+ahtD%_(^M~gEkde zRwidC?`#q+LBLGBgG=?}40FZAd9OjILno4P%J!uIsYg^&g7~0lr)_9@ORh9(?$NOu zvgwNhQIia0#u}VP8$eK}I!ZSSP-+Gul4qj2ekR=c4i?Bp%NTp%1xwr*Fj{?*QpPm{ zm@sruncfM^9g0Cnt#xW;)`TZi>A)Llj`H>g5l~=3BCv+Q{MW!HPR1&T<9wk>iy|@J zw67F|A^-)J3nxg#A8AdTXo<5nO@W?&{&TY~7r){)1|Fzd_ zNHABnJbB&_3Avy?wevc32uy-ddw6qAK=_IG)exMNHO;$Gr79%m0# zUy@Ir7au&Ph zf?v`=rP^zFQ$i4y@vL;k3q;gG6Y{2^HcY==%F};3*y>Z>=u`lGr3#+m%{6X+jZ34WeZjr2`TK;%t@Z*9xH`f_341a zi%-TgCh~c3cp;`Kw35q?S}o}@BWQC!wQlCLSGQ~;Xb>d17n3B>#GYqK(xlXj@o^ze z^6?2EZYjns-I&Bl{tnJeylCK{r!BE7#Pwe1g_c}iP#sE~2cAP}fw=Q!cB_c46na;y zLr(j4z~_1GV^2vJiyf-h71KrKE|Q9T38Z=*kE~3FlsE%lCeuD4xks*nOuC>SOIcZa zHJ12AnAq(y8-JfhUEL(yJ&lQ$4Rpp(N9hJk1)V0bFHm!-Tryp6bF^953fP(W>`r-X zXl8bsj+8CIjRvG%5sYeGqAflmh)42;l1-Cn0k|MO>6WJi)4n4UuG7Iig;1h$S{zsQ zv{hM~aGP5FNim4O(&0vta-x0lir)?Fw)l%i#F@=@ zNG=~Aag+opeHPq#=1SF7J-EZigtJM@qoicc*BYHkK%o~O)+_XJhlv#9@7Xy=H}&S^ zGK<8q30FXq(AV19I#5)TV0_8fUHv3`ekOJhc5UGb>nF~@b@=X<*GL+V!Vjq*jy&wM<|yyFaE-9 zl1?g1+M=!o($^QHt^4t@t$JNeX<`EC^hyUYh4_fMwzl?8=4^!~-q_|KFP}J!&Y1Q? z=^aq2KM0gt;!lew`I@tBDU~2TvD?9)vgckb(W4#aX5!s$Y8^juqON|r)iBpO#m#AA|bGa(v{yGmV6^V9~xgM4D zj&Nhs5k!-i#odWhaxzWMvaxhyGc9SwLgEufNew8ISg*`vI^d2I=S|`;I=Sn~n8+|B zfNqQZ@SQQS5T7{dycSG66w4Cl_Y~q?w@IB;2%Cw|YEe`UEKFh#t1|`aksRZ7W<(Hg zTT0F`s#!03H z1e2hUUSgX@i7xENr-Qr5T~v-=w8kGkND@QGOihed$-e4}qsTq4{Y967WHq*RJio$; zAD=UA5>{ZRU7FYmkyPoNuH(2;l7qV#T$9OyL?27StG9FSD|N+BwncKPbCj-RVlxS2 zR5#KMm?m`x6E~#kXvA?{un-?fdb% z2g9W8PvGky(wO$K?eriw-jWPo-h$3nqCAM)mGnQSHAl4=$0NLGi=8c!^Gb4@7vmM4 zWP~n^ODn16ITfK8pLdniUXx+myKS*EkbCOl&vg9As3W{3lW5ZJDRDYxNhw@EDJ$zD z2A7a4f*bRlOA*AbPMJ(;Z}t+-=MKu?ED;xfXCB(Qu8OhS zyy=Lou24?d_d2=IyXml4Y;WJ>>m@Z~634bC?<==Si;A?6RGb7s`=~5wiy%IbB-t%X zc&q7TFZ%!Oo!zeN#&JfAoY7riLl%x@K(~29J%^DeJhz4s#Fh;^7nV2KOrO12Yl_X8 z69o}0Ct^VmX3yb}&Hnki>Z|IiBG15dp7()wCA*U!ewr@As+84VMTw_#O9vL+*a1G% z;?>2;eVonJazuHQI*hVZ_!2Ws{UVa^GO?ooJ*BtqcH1kgF-1)R?FF)_2(kXN+cQ!THKH9h9sSe8c%VO_Lshxt8V+2A{>(z5Q0 z?{X{k4SlXnsz~ZKF!aE1nR}|FggcPiSY1}F9EP4UpP}h;G(5G*{2>&F=~*Lo?vD{NN2aoa$Ot)eww-Wd^9qDk_+r4B<^vf-) zK}fKQL@uE^u4fH}+e$@65^Aj2NFVW%sm9iIPu?R~s4UX}nKJBXmtuVccyZ4pQd(HG zH~f_w0GojuhF~foc+XN-Q(^HUmyl2K{!`MXem>iSbpdaw^4o#S@|Z5h0}Y)lcj4kc z@4CZ2T5S|NVO<}SB#zo>#WGXJOPD&ToS=0?qL@1ZoD*q4$*H7+(F3a$9L0#+w#Q8N z4o_9`NNvDCnZd4)0)l5_OQ#$xJOLPWbE-WyXZ07-XE+wP{??K-lKa>*m}s~V=%Rbp z?{k;>nFHt`2Kgbw8f28046_4L4c$HCK#><8eUT+IF$y}{ z_86L{&`{OG3fWuo&XoX(lk28-og0R)963dYM-Q9ga0jC)#LCtlDlG_02L5bq}kuWCle8R-6@T$8j8bce^u987BkZ4s0cQ#_i|aVE@$t-Lj}ScfgG~ zXG{fO8jHd_^jIx}qAOXKK(%HtynN8MJ>pWLI0pJX$p|q`yASFT1+s3-qi)9hO{KKE zo;@eOaYwI~%)7jHKt&v;l=`iUv!Wh+mT5+-=ym|?NGn%Yj@xXM2~iib7+RTATWB1j zkBg({MAvrJC|&SVQg|do8&F1qOyMd4-WOKUU z&O1{Sl=tlhr8v?bqKE2?6vOqhE9R&k;yU>GT%zy>Ex4+6>#_Rx;00oGKlKbmnGcaL z%A@aD-S({%YFECLAZ_TT>b&wJ`_GQ314JdO;TBVwA^#Ez%bQoKZ2mc3fZuYbMo zPuu(PBIBu3(@u-Ph+xrFI(23q;SZTGvgW6j`q;|q~y ztdLe2QVY7I67bEJUw%5=yloGYKg!uK%G_>Al907_njQ=(zoNKgyw^1VN$K7`C4M?@ z{x_%ko&OX<>^40a89iNzQI6yzXU&EQ`QgLA^sYY26EOXcKm6e%seM}U09Fo58K$xd z&XUP-t8s_S#~9{1*CP(g(u=DW8OLQ=b)SgCimHgY9Z1iQoLFBo7k$Lx5w3yS!oh^E zq)9s-q7XN0cbRfxAWsc2*z!cCro?$T*Yy#kg$g$4gApHp_q&6dxnv20iV=}6HOJID zRGQL7%R}dRf3<2hX);%9Y%Doq)cdw=N6fk*k+YmLb!0Z+q}-fmk;&44PRi?ZC1;VV{r0-f^5xLmMH!lx*csr-c2waI#VpxeNj#LIvj&WcHWaB_VXU@;UaP?@$g=6Oo`X5 zCEaobBkus*xG!#5<9;j5Ndvg2g(G3Zrs;9KjSn0o zi`dI>(P=e&rL_mg$Js6Ll&+v*9doI_z}EYdBI!S`P~%qUSn`}3IV9;`O@v$Kh=?-n z&$icdFlEi?YK)R0{3)63msAsR0XyB5s?g0PphO_^RODDyr(E^>4|ndR2_dRyj!J2pLX3`0)1+KvN8?kkO`$3 zEKwCSYb?7P`E+?$;6Uew8lR-3BUMLd;D}o?-KhD~v{&?V?B>j#V@Q+mYTh|8s3S{c z)fs0RGoIV(n(rU1cy8)@#=7In?Y5_ng7~Hk4BHZgcEBUO;UtJ5v#s684=tqwk=ojx zUBQq$8q)#2D~!F_9F66gc*k@ecf0M`-bnk)>)cBs!Twt~P~OOuOyUdq5Nf{8?*%on z_i2Estu9g6Yw1I3)RRn-p=62@tBXw#g{hyWmoWG;pJ`;+<9u}2ZpFE|rH8s|X9CB7 z8gNY8k+d3A-SaySAF518=TDWh_qMeIQrAD#`+PN(!AO&HdgfnlZC_NPk}avaYBlx; zmyt%g-m`%{7r#b}cwlZt2Oq)Mu~646p1PFd zzoKwG8PQ5nBh_%ztPmGLG$ohGQEV9{Dl`DNIJl!^xsS3%MeJH6N+rML8!!u_p{09) zhGG3}+rtzWb^!PJl2_B&U@*T& z4eN|$P&_C7V%h(!g&h&5oBa$+9~X2awy-(Lc5X)=?3p|RQ_KqZGUC@%TbKvTfG9dt z%cBBJVjZ$-(X=}K-a2UBUkEkge+ap0@zai~` zd;l4pawO;i<<+lM2?=#-nW@X1ry>_K9E`(6W6@%XxAs7MRw;>i7_xqi(FLt!El^RF z|CzH)4jF2=n8SPhvjtQnxGx#RKItDA8b5!LHJ{BEf_*uqX9)ACVn~r^V5+--x!WxW zm>QFQlCNLrf&X4IAyW<9gQx%QyHAS^kadZ&bS?XiofWb3P~eWc{hCEajpLg#j|(Z5 zTjn=ImgRwck*dm)XF99WZvC>zmBTAgp1u`+WX&klB`cuy3)Vb6BEf%$?9BYP8fh6h9eVMKsVrUg4H@Q3e6`oaos3<|g6v<$#ara_uV zHtUvLEe@RCs;|D<(WhVBU%&q=J1ZGm*c+IL)3k%;mWlq{{4uNl^ryWh9S9g%E4#N1 zUka%L!M=6f>mg#@yV3Fp=8VCBJcS*)-5mA7D^nojLJC4ixW_I3AfBv3Aixl)YMQhSO#SO1P*YU%1BPr z?vcc75%`?*P=>e^08JR+bItAG5EGL;n2kb3VD?+-lTR@PnS&-7i763Hk zO_!2UB?`-iO-*NNdx}Yucy|xATI86^V3iBT`oDCJQ z>+`4o$y3zV=J)ck0KMdFB%80+jPj1&$3xjEnQ4r>Q<2yApNK{x!U-d3&NB3C9@DOz zKCZcHakr8vdM-XszhS3m5ecUEEOk}aWM%E$kB85$mpBGuSKRa|7h(ETYL_xSm~0Gg zOA=2TqE9EX>to7*3Coicx-UYb)J9o3__nZ~pqapO9oEoTU??_A$A}LfcGs#=%3J0P z1&JuQ)PK^~3|1AAkqWK5m|l35N0x649`J2mHVNdyZJZ6!*_xf4x(I%X?;iD!)P& zZzV?&P{j?ckHiq7m9X&WRZ7^idGu=tRBZ2TUH_iFM=uAX7O@u*z!H}(yxn%nf{DW1 zVpGAti8mRO8OL$Ij9M}vDOxQPv^NjsF5ZnM>aT#dKr^$G0U-z8_`&M;p^QRg6#bOx zwFo4Vpl``J>Sm=GSkwH;CLO2Le`NCJjj9Xct^!STE&aBc9%*4Rf=J zc(|n0aQRbTho)OKQ+#({-^UTH#hkn!Yvg)Q{L&_}a|L+h9a`C+^z5~xY^!W|0vFG>Y3VhEQ z24DlQ7L6lmnf-y{Mb1uC162}!?va&Na&T2WWy%;SlqMo_u}Rri;BX~X)s9(#HAaU{ z?=ON@!Wv%Jhcg$|zCVKS9n>QI32XooIyNRsW_vs~>dvi%SSld%E zw90T<1zg)aC`uQM{!5uN3T=%_(=eq_Ks38t zX+RqcJ!;OfJSZyPgw`8FCrePL0#u!IR1-KdSY*y4dNRD)SyM@U#8WW1&>iH8YIV3HAj_% z_hsytv5d&Gc64EMeE+tmwFaqT!5`t%u)4 zRgQR^Z0X;3&H0ai{Pd-6Q(8u85Fum9C}k|-mXrdEP@Ya~>erC>LG6!T@PH;-7=~)R z>)O2~{r{w;5b=StjzQhDr*b`5!xP~{^%2t>?jMwl$B7j2h^Rm{gSuYx7*)i6b2Uxh z%Tt??zLZES)n?Cm?Dc*>V10ec-;a69WxDFK&Of}6^oPi>|7oKr zz@4Vvk~KH)PmuG4X6kllILll@KDm+5$@ewtEs|J7pgTRihZlIxa+|lT&8a_Ro*!_- z>IH&<9)ldQqw&~i9@1L5FyV=Y^_G17_2HDxEziRDRuSK$b;$+3ApPDO_T`s5x#>%_ zWGcnAw=8!ow?a6&O@bNF^wULS0VuZ+d{)&L*GeT7^}A&`sH?Q6t|(lB-7x34BzOk| zxc@~WcoeG>H5`yKE)Vhnz=}B7{)4UBjxHLbjOk~Y0j=p}IXqnsw`y~PN@%lncKgt3 zRJF9zBQ;0gMUr=r3Vg!_OQx3|)c>Eqk& zp&tow97*PefWn%ovA7AoEF3=iGzg#Kp7b3~r^r-KkrYYf0VEJmwVxZd40om3ys0%g zB6B9n%z}gX!~w*&tkNz4XPS&#sfXe6(_dt4lM1F_WS2TEaMb7_X{Cmp`=y<8FSQxO zwKtHukHFv{+IG}(5tS>X1p8=7ZrICXIhD&YIYf; z6R`(iu6ZEc>)GUi!a0LF;S>3x&ZYZ(SBq*6-7Qnzf_>Zeu*-a5BGqxipuv5A%xuQm z<1A2(ohE%DH-`WvDChQG018JQx-Cv>9I~Lc&L8R|N9H~2KjA!575=FewgqC;Ge|}k z(poAl>kyyQgTb2b>Lg8yl94MCwGE}*G9QxB?={2~;MQH^h9?A6gE|UKXnsaKMtoTw z-Xy`)>Bw!*;G#z9mxH-_MmoDFl6@Mmc#x-NudiGmEl54J?$6j-`)#;Y{mD}$v?WV3 zpnUC_S5Nozph15|7rx|wD(-gYF0J3-bcs`8sCRh+rvLu?-~ZchfBU1h^pZ<1x#a)3 zJOR^hzy0*r^{0MS^=_Qw3a>F@mF$5nhPWte_T^b3zZ5gRBIPOMChNO^pDU%L=aq@x;b^};?O}C z2caOSldGGh4nm=5O9pE}TB?=QV$wK-E0?N?$!EIf`#ksNd7gWo?~zcJDaJ@?Q?XdA zR4O_uoiwho#2TND1f|ouDKkDk-g+uC&pdB@az39A!!QVfu0&(hz!X&` z+e?e0sE5*8#uh8w?yk6(sWQ?xD2PG$!twq|!dF`xj_vXb2G{HW_7~lLQnvMV(@)^faFj>-Dpl%wFg35V4mqr>Rni&0B>+ zHHy|)=-Q(ri}aISF2&}>AlOc)Uoi2XD{`nG>?GDLLzbZ9l&1eWIN#agG8kr*6;`QH z=?V0ek6ZyaxWIj0fxC&Y6Wn7s2^wo}c8%ru0=P+yD(f6@JrVYRN4#X>5OjyP?Wr~> z@tR2V8IhIgFiaqFEq_WvmUJWH&$uFAw;KXPYZ gO4OM<+Rjq>lD*ylh07*qoM6N<$f?{U>GXMYp literal 0 HcmV?d00001 diff --git a/sdrbase/resources/preset-delete.png b/sdrbase/resources/preset-delete.png new file mode 100644 index 0000000000000000000000000000000000000000..d14155230a769c8ffd5dd970d2647918b53173ce GIT binary patch literal 731 zcmV<10wn#3P)(TTv9ofA^WZrzSp4)yDrVgxaAM929J!o$S)hqAqoGC>A=oxpa{(Iu<$z zPMs>mRZ6K-K`JQPf+_w3F%4FeXOf$jm*lR7G;kG=IXS5x92j8#_!#Lp*p5TKPyiron$#EuA;aKqQxgY!d-Z7!(_^-eTOq`8^KXq3kGc9iS#=kSoDWRl}lik(CP$F|eg06^9)ms_*xG-caHo}7@{ z-9<`?loDG?3WWltVi6%k)^E}-0|0~&R8>_GibQxkJj~P4(X&i64Iu;oN~s$Grx$^G z9*>5GNNsPEPNmKup%6D|uT20@ZJHFaSq?Tg+27c}v2DsyUI_nd!KkmNv9ptvcpQLY zHp{ogMV^d|fTsQ1f)L^qpgJ6;Z*UNG?$^)7sHx#zfBzNj6@X8@-POhV@-oVGQA(kd zLa(hQv9?B2ON+mBH%?#yY_G1;-PgzSi3wu;{oLy4;KiFaboci1eQC*0*}7>D7Jx}r zF1LP}pC=RwVHgHdN14@c85dZ`}usH zTt1huEbG^4KDQZk)!e&yJbMiwgwTQNOJx8-K%Cj83^+jXylkaZFEuI&gOI*7&LdVGPYhUZqr>Cx* zX&2UKe`mKkSU~;Xm5qljzdreFwdER5um2={k(HV!#izZntSve`x4nPfy*HW5Zcb5J zd$rfN_FvW6rXoK9#GP8V&Ny-%0BHYnR9P%^UaCdyTcnr8A4wR z2BsKE#`W%1jMsRy*WKmAy~)}456zn!JLP#hXGp{MO?IY7E>!Ii-*QdHwnSlRLg}lX zg;}wG^;;G?2V|_RG&DMQC`obYg3XJk*6uD}SlV{sSJi=-eNMrj<~(GdJmXaOt;0fr z5o+7+JG2z+YP`6S%}VHaiKSEaTsD*Kxyv_ioS4Hbakl@qK(>LIm4SiKroI1AH00)| zWTsW(){y+3)d{G<3}k~(W^!s?aVkSbNlAf~zCPHl%(B$v{M_99ykfolqICTnh>~Lc zq)Of5M15mD1O3D|>jQx%NP`iXS8=u65Tjw&KZe|XykP|f7yZz=JDR=1{*mx?A!M3@dJhTcXt(U|C*uGa5SpfFk!`~kBfDi z7Hs~XR{i^hlEbVedzU^{JvVp1!{p-*swQmNyw@7Gwq0KzXCT#EWy}<+`htbUU995Y zyWrW2?07_v_8!!9VF~?vw`s+rIftWm)V)+;OH;X5edYT0s!4l}Shkz+hKLF#&Jqnh z8vp1N<9o-w>x2H%q%zY*)L>|!Yha{n zWDsIxY-MC-WoQb~z-ArOh@v4kKP5A*5~=}cgJFn)rInG1m9Ygx!__Z)x_}zeK~D0? zOis-!PG!g_DJihh*9Y5`S(cidpPQSXSFD#`l&+rxQBtg*RH<8>sBf%ips$c$q(F=g zANK$seIq?X{pfz1WSAQv&O-_X17lr7%Me2YD^nvYQ=lKsfT3_x{@W&?21$?`gY(l$ z$`gxH8OqDc^)mCai<1)zQbA6e{mw=Ts7M&1sI(|KmBGKFGCeg + + appicon.png + histogram.png + waterfall.png + preset-load.png + preset-save.png + preset-delete.png + horizontal.png + vertical.png + logo.png + maxhold.png + grid.png + invertspectrum.png + + diff --git a/sdrbase/resources/sdrangelove.rc b/sdrbase/resources/sdrangelove.rc new file mode 100644 index 000000000..b943fc309 --- /dev/null +++ b/sdrbase/resources/sdrangelove.rc @@ -0,0 +1 @@ +IDI_ICON1 ICON DISCARDABLE "appicon.ico" diff --git a/sdrbase/resources/vertical.png b/sdrbase/resources/vertical.png new file mode 100644 index 0000000000000000000000000000000000000000..ad78f34222ee1a9bd7ee1185fee4957a568e30bd GIT binary patch literal 195 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`Y)RhkE)4%caKYZ?lYt_f1s;*b zKw2Gy8MQbk`U4s4C7!;n?01>?x%t^c>l$7Gg(OQ{BTAg}b8}PkN*J7rQWHy3QxwWG zOEMJPJ$(bh8~Mb6inKjl978NlC#M`>`7il_*^TK_1@D0g$w>w6L6h% f@ympWCCm&uH`%4mt-EUj)W+cH>gTe~DWM4fW@tDc literal 0 HcmV?d00001 diff --git a/sdrbase/resources/waterfall.png b/sdrbase/resources/waterfall.png new file mode 100644 index 0000000000000000000000000000000000000000..9e520906ef20fec2ba0d96487a7ab85cb2dd6887 GIT binary patch literal 1368 zcmV-e1*iInP)QSei3Kfz1S?*G1w04ufy9CxYlMW5kPt!*Vu2bcNT-riWwztt z`uh4#=NuM%kMN1)r$1(TiLSW%&>Xyz+xYb5zkhOU{<7rfV?J6={yKU14W-vPUuS*AWzM=` zGMe9RDVH^K&DNt`6Ep}#t0i$u+eHc+$k{q-cKwYt&QTZ|iE2a~P&*QhXS!Jtn(c_* zj&Mg6U^PxNx3ogyS0bL_=R%udnzMo}jq>{6s9S|Ti2f>Qjq;zOx; ze#$bXW3ZaK>!nXcckP^hmD;UOYNF#ZZ(=McA?BN?qQUwYMOYvd3rFPBNJ-oCF7cAf zqSn)T*O`~{Z(n}p`E-6OqF=4^U-*2Z#~(^Q-D_2M`>%Ouac*&f6YQQS`}AwY!81aS z%%h0JR~IteX;r^Gny*E_p4Ab2B@mZ@Q0GxUhV_HO4WQqj%mKeBg&aXJ|b>Xfj+ zD6&3#5A=<;d+}r=Ty)Q|8UJvcrT0T&cPk21UXpIY4?o(-QM0K~vAX^b+c zKl|h;e;#vH^0N{Cf?s-UHn9@?`ip&6C0|}o^Z%TZ%*<}gJt!;bRsDlh9Q57g+ z$!D;&{3&Iu*v-T)!aSrIV9{s4fL0jR^)|GwZZ?@E5}3BTA=}h!Dzar#+Qr*dTa-Dy zE4-HZl$FDDQ9^RLB`N6aP}Z5i)LkbVEh#NKi*f{(&)*G&Kz6h3`W9E literal 0 HcmV?d00001 diff --git a/sdrbase/settings/preferences.cpp b/sdrbase/settings/preferences.cpp new file mode 100644 index 000000000..c649cda42 --- /dev/null +++ b/sdrbase/settings/preferences.cpp @@ -0,0 +1,46 @@ +#include "settings/preferences.h" +#include "util/simpleserializer.h" + +Preferences::Preferences() +{ + resetToDefaults(); +} + +void Preferences::resetToDefaults() +{ + m_sourceType.clear(); + m_sourceDevice.clear(); + m_audioType.clear(); + m_audioDevice.clear(); +} + +QByteArray Preferences::serialize() const +{ + SimpleSerializer s(1); + s.writeString(1, m_sourceType); + s.writeString(2, m_sourceDevice); + s.writeString(3, m_audioType); + s.writeString(4, m_audioDevice); + return s.final(); +} + +bool Preferences::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { + d.readString(1, &m_sourceType); + d.readString(2, &m_sourceDevice); + d.readString(3, &m_audioType); + d.readString(4, &m_audioDevice); + return true; + } else { + resetToDefaults(); + return false; + } +} diff --git a/sdrbase/settings/preset.cpp b/sdrbase/settings/preset.cpp new file mode 100644 index 000000000..6680caa6a --- /dev/null +++ b/sdrbase/settings/preset.cpp @@ -0,0 +1,88 @@ +#include "util/simpleserializer.h" +#include "settings/preset.h" + +Preset::Preset() +{ + resetToDefaults(); +} + +void Preset::resetToDefaults() +{ + m_group = "default"; + m_description = "no name"; + m_centerFrequency = 0; + m_spectrumConfig.clear(); + m_scopeConfig.clear(); + m_dcOffsetCorrection = true; + m_iqImbalanceCorrection = true; + m_showScope = true; + m_layout.clear(); + m_spectrumConfig.clear(); + m_channelConfigs.clear(); + m_source.clear(); + m_sourceConfig.clear(); +} + +QByteArray Preset::serialize() const +{ + SimpleSerializer s(1); + s.writeString(1, m_group); + s.writeString(2, m_description); + s.writeU64(3, m_centerFrequency); + s.writeBool(4, m_showScope); + s.writeBlob(5, m_layout); + s.writeBlob(6, m_spectrumConfig); + s.writeBool(7, m_dcOffsetCorrection); + s.writeBool(8, m_iqImbalanceCorrection); + s.writeBlob(9, m_scopeConfig); + s.writeString(10, m_source); + s.writeBlob(11, m_sourceGeneralConfig); + s.writeBlob(12, m_sourceConfig); + + s.writeS32(100, m_channelConfigs.size()); + for(int i = 0; i < m_channelConfigs.size(); i++) { + s.writeString(101 + i * 2, m_channelConfigs[i].m_channel); + s.writeBlob(102 + i * 2, m_channelConfigs[i].m_config); + } + + return s.final(); +} + +bool Preset::deserialize(const QByteArray& data) +{ + SimpleDeserializer d(data); + + if(!d.isValid()) { + resetToDefaults(); + return false; + } + + if(d.getVersion() == 1) { + d.readString(1, &m_group, "default"); + d.readString(2, &m_description, "no name"); + d.readU64(3, &m_centerFrequency, 0); + d.readBool(4, &m_showScope, true); + d.readBlob(5, &m_layout); + d.readBlob(6, &m_spectrumConfig); + d.readBool(7, &m_dcOffsetCorrection, true); + d.readBool(8, &m_iqImbalanceCorrection, true); + d.readBlob(9, &m_scopeConfig); + d.readString(10, &m_source); + d.readBlob(11, &m_sourceGeneralConfig); + d.readBlob(12, &m_sourceConfig); + + qint32 channelCount = 0; + d.readS32(100, &channelCount, 0); + for(int i = 0; i < channelCount; i++) { + QString channel; + QByteArray config; + d.readString(101 + i * 2, &channel, "unknown-channel"); + d.readBlob(102 + i * 2, &config); + m_channelConfigs.append(ChannelConfig(channel, config)); + } + return true; + } else { + resetToDefaults(); + return false; + } +} diff --git a/sdrbase/settings/settings.cpp b/sdrbase/settings/settings.cpp new file mode 100644 index 000000000..b7012bc55 --- /dev/null +++ b/sdrbase/settings/settings.cpp @@ -0,0 +1,76 @@ +#include +#include +#include "settings/settings.h" + +Settings::Settings() +{ + resetToDefaults(); +} + +Settings::~Settings() +{ + for(int i = 0; i < m_presets.count(); ++i) + delete m_presets[i]; +} + +void Settings::load() +{ + QSettings s; + + m_preferences.deserialize(qUncompress(QByteArray::fromBase64(s.value("preferences").toByteArray()))); + m_current.deserialize(qUncompress(QByteArray::fromBase64(s.value("current").toByteArray()))); + + QStringList groups = s.childGroups(); + for(int i = 0; i < groups.size(); ++i) { + if(groups[i].startsWith("preset")) { + s.beginGroup(groups[i]); + Preset* preset = new Preset; + if(preset->deserialize(qUncompress(QByteArray::fromBase64(s.value("data").toByteArray())))) + m_presets.append(preset); + else delete preset; + s.endGroup(); + } + } +} + +void Settings::save() const +{ + QSettings s; + + s.setValue("preferences", qCompress(m_preferences.serialize()).toBase64()); + s.setValue("current", qCompress(m_current.serialize()).toBase64()); + + QStringList groups = s.childGroups(); + for(int i = 0; i < groups.size(); ++i) { + if(groups[i].startsWith("preset")) + s.remove(groups[i]); + } + + for(int i = 0; i < m_presets.count(); ++i) { + QString group = QString("preset-%1").arg(i + 1); + s.beginGroup(group); + s.setValue("data", qCompress(m_presets[i]->serialize()).toBase64()); + s.endGroup(); + } +} + +void Settings::resetToDefaults() +{ + m_preferences.resetToDefaults(); + m_current.resetToDefaults(); +} + +Preset* Settings::newPreset(const QString& group, const QString& description) +{ + Preset* preset = new Preset(); + preset->setGroup(group); + preset->setDescription(description); + m_presets.append(preset); + return preset; +} + +void Settings::deletePreset(const Preset* preset) +{ + m_presets.removeAll((Preset*)preset); + delete (Preset*)preset; +} diff --git a/sdrbase/util/message.cpp b/sdrbase/util/message.cpp new file mode 100644 index 000000000..8431ca7b1 --- /dev/null +++ b/sdrbase/util/message.cpp @@ -0,0 +1,79 @@ +#include +#include +#include "util/message.h" +#include "util/messagequeue.h" + +const char* Message::m_identifier = "Message"; + +Message::Message() : + m_destination(NULL), + m_synchronous(false), + m_waitCondition(NULL), + m_mutex(NULL), + m_complete(0) +{ +} + +Message::~Message() +{ + if(m_waitCondition != NULL) + delete m_waitCondition; + if(m_mutex != NULL) + delete m_mutex; +} + +const char* Message::getIdentifier() const +{ + return m_identifier; +} + +bool Message::matchIdentifier(const char* identifier) const +{ + return m_identifier == identifier; +} + +bool Message::match(Message* message) +{ + return message->matchIdentifier(m_identifier); +} + +void Message::submit(MessageQueue* queue, void* destination) +{ + m_destination = destination; + m_synchronous = false; + queue->submit(this); +} + +int Message::execute(MessageQueue* queue, void* destination) +{ + m_destination = destination; + m_synchronous = true; + + if(m_waitCondition == NULL) + m_waitCondition = new QWaitCondition; + if(m_mutex == NULL) + m_mutex = new QMutex; + + m_mutex->lock(); + m_complete.testAndSetAcquire(0, 1); + queue->submit(this); + while(!m_complete.testAndSetAcquire(0, 1)) + ((QWaitCondition*)m_waitCondition)->wait(m_mutex, 100); + m_complete = 0; + int result = m_result; + m_mutex->unlock(); + return result; +} + +void Message::completed(int result) +{ + if(m_synchronous) { + m_result = result; + m_complete = 0; + if(m_waitCondition == NULL) + qFatal("wait condition is NULL"); + m_waitCondition->wakeAll(); + } else { + delete this; + } +} diff --git a/sdrbase/util/messagequeue.cpp b/sdrbase/util/messagequeue.cpp new file mode 100644 index 000000000..53bd3e3d4 --- /dev/null +++ b/sdrbase/util/messagequeue.cpp @@ -0,0 +1,40 @@ +#include "util/messagequeue.h" +#include "util/message.h" + +MessageQueue::MessageQueue(QObject* parent) : + QObject(parent), + m_lock(), + m_queue() +{ +} + +MessageQueue::~MessageQueue() +{ + Message* cmd; + while((cmd = accept()) != NULL) + cmd->completed(); +} + +void MessageQueue::submit(Message* message) +{ + m_lock.lock(); + m_queue.append(message); + m_lock.unlock(); + emit messageEnqueued(); +} + +Message* MessageQueue::accept() +{ + SpinlockHolder spinlockHolder(&m_lock); + + if(m_queue.isEmpty()) + return NULL; + else return m_queue.takeFirst(); +} + +int MessageQueue::countPending() +{ + SpinlockHolder spinlockHolder(&m_lock); + + return m_queue.size(); +} diff --git a/sdrbase/util/miniz.cpp b/sdrbase/util/miniz.cpp new file mode 100644 index 000000000..bc995688e --- /dev/null +++ b/sdrbase/util/miniz.cpp @@ -0,0 +1,4835 @@ +/* miniz.c v1.14 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated May 20, 2012 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Change History + 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include (thanks fermtect). + 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. + Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. + Eliminated a bunch of warnings when compiling with GCC 32-bit/64. + Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly + "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). + Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. + Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. + Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. + Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) + Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). + 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. + level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. + 5/28/11 v1.11 - Added statement from unlicense.org + 5/27/11 v1.10 - Substantial compressor optimizations: + Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a + Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). + Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. + Refactored the compression code for better readability and maintainability. + Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large + drop in throughput on some files). + 5/15/11 v1.09 - Initial stable release. + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 +*/ + +#ifndef MINIZ_HEADER_INCLUDED +#define MINIZ_HEADER_INCLUDED + +#include +#include + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +// Defines to completely disable specific portions of miniz.c: +// If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. + +// Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. +//#define MINIZ_NO_STDIO + +// If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or +// get/set file times. +//#define MINIZ_NO_TIME + +// Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. +//#define MINIZ_NO_ARCHIVE_APIS + +// Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. +//#define MINIZ_NO_ARCHIVE_WRITING_APIS + +// Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. +//#define MINIZ_NO_ZLIB_APIS + +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. +//#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +// Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. +// Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc +// callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user +// functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. +//#define MINIZ_NO_MALLOC + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +// MINIZ_X86_OR_X64_CPU is only used to help set the below macros. +#define MINIZ_X86_OR_X64_CPU 1 +#endif + +#if (__BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +// Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if MINIZ_X86_OR_X64_CPU +// Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +// Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// ------------------- zlib-style API Definitions. + +// For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! +typedef unsigned long mz_ulong; + +// mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. +void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +// mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +// mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +// Compression strategies. +enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; + +// Method +#define MZ_DEFLATED 8 + +#ifndef MINIZ_NO_ZLIB_APIS + +// Heap allocation callbacks. +// Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +#define MZ_VERSION "9.1.14" +#define MZ_VERNUM 0x91E0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 14 +#define MZ_VER_SUBREVISION 0 + +// Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). +enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; + +// Return status codes. MZ_PARAM_ERROR is non-standard. +enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; + +// Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. +enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; + +// Window bits +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +// Compression/decompression stream struct. +typedef struct mz_stream_s +{ + const unsigned char *next_in; // pointer to next byte to read + unsigned int avail_in; // number of bytes available at next_in + mz_ulong total_in; // total number of bytes consumed so far + + unsigned char *next_out; // pointer to next byte to write + unsigned int avail_out; // number of bytes that can be written to next_out + mz_ulong total_out; // total number of bytes produced so far + + char *msg; // error msg (unused) + struct mz_internal_state *state; // internal state, allocated by zalloc/zfree + + mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) + mz_free_func zfree; // optional heap free function (defaults to free) + void *opaque; // heap alloc function user pointer + + int data_type; // data_type (unused) + mz_ulong adler; // adler32 of the source or uncompressed data + mz_ulong reserved; // not used +} mz_stream; + +typedef mz_stream *mz_streamp; + +// Returns the version string of miniz.c. +const char *mz_version(void); + +// mz_deflateInit() initializes a compressor with default options: +// Parameters: +// pStream must point to an initialized mz_stream struct. +// level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. +// level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. +// (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if the input parameters are bogus. +// MZ_MEM_ERROR on out of memory. +int mz_deflateInit(mz_streamp pStream, int level); + +// mz_deflateInit2() is like mz_deflate(), except with more control: +// Additional parameters: +// method must be MZ_DEFLATED +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) +// mem_level must be between [1, 9] (it's checked but ignored by miniz.c) +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +// Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). +int mz_deflateReset(mz_streamp pStream); + +// mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. +// Return values: +// MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). +// MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) +int mz_deflate(mz_streamp pStream, int flush); + +// mz_deflateEnd() deinitializes a compressor: +// Return values: +// MZ_OK on success. +// MZ_STREAM_ERROR if the stream is bogus. +int mz_deflateEnd(mz_streamp pStream); + +// mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +// Single-call compression functions mz_compress() and mz_compress2(): +// Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +// mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). +mz_ulong mz_compressBound(mz_ulong source_len); + +// Initializes a decompressor. +int mz_inflateInit(mz_streamp pStream); + +// mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: +// window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +// Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. +// Parameters: +// pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. +// flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. +// On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). +// MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. +// Return values: +// MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. +// MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. +// MZ_STREAM_ERROR if the stream is bogus. +// MZ_DATA_ERROR if the deflate stream is invalid. +// MZ_PARAM_ERROR if one of the parameters is invalid. +// MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again +// with more input data, or with more room in the output buffer (except when using single call decompression, described above). +int mz_inflate(mz_streamp pStream, int flush); + +// Deinitializes a decompressor. +int mz_inflateEnd(mz_streamp pStream); + +// Single-call decompression. +// Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +// Returns a string description of the specified error code, or NULL if the error code is invalid. +const char *mz_error(int err); + +// Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. +// Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + typedef unsigned char Byte; + typedef unsigned int uInt; + typedef mz_ulong uLong; + typedef Byte Bytef; + typedef uInt uIntf; + typedef char charf; + typedef int intf; + typedef void *voidpf; + typedef uLong uLongf; + typedef void *voidp; + typedef void *const voidpc; + #define Z_NULL 0 + #define Z_NO_FLUSH MZ_NO_FLUSH + #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH + #define Z_SYNC_FLUSH MZ_SYNC_FLUSH + #define Z_FULL_FLUSH MZ_FULL_FLUSH + #define Z_FINISH MZ_FINISH + #define Z_BLOCK MZ_BLOCK + #define Z_OK MZ_OK + #define Z_STREAM_END MZ_STREAM_END + #define Z_NEED_DICT MZ_NEED_DICT + #define Z_ERRNO MZ_ERRNO + #define Z_STREAM_ERROR MZ_STREAM_ERROR + #define Z_DATA_ERROR MZ_DATA_ERROR + #define Z_MEM_ERROR MZ_MEM_ERROR + #define Z_BUF_ERROR MZ_BUF_ERROR + #define Z_VERSION_ERROR MZ_VERSION_ERROR + #define Z_PARAM_ERROR MZ_PARAM_ERROR + #define Z_NO_COMPRESSION MZ_NO_COMPRESSION + #define Z_BEST_SPEED MZ_BEST_SPEED + #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION + #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION + #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY + #define Z_FILTERED MZ_FILTERED + #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY + #define Z_RLE MZ_RLE + #define Z_FIXED MZ_FIXED + #define Z_DEFLATED MZ_DEFLATED + #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS + #define alloc_func mz_alloc_func + #define free_func mz_free_func + #define internal_state mz_internal_state + #define z_stream mz_stream + #define deflateInit mz_deflateInit + #define deflateInit2 mz_deflateInit2 + #define deflateReset mz_deflateReset + #define deflate mz_deflate + #define deflateEnd mz_deflateEnd + #define deflateBound mz_deflateBound + #define compress mz_compress + #define compress2 mz_compress2 + #define compressBound mz_compressBound + #define inflateInit mz_inflateInit + #define inflateInit2 mz_inflateInit2 + #define inflate mz_inflate + #define inflateEnd mz_inflateEnd + #define uncompress mz_uncompress + #define crc32 mz_crc32 + #define adler32 mz_adler32 + #define MAX_WBITS 15 + #define MAX_MEM_LEVEL 9 + #define zError mz_error + #define ZLIB_VERSION MZ_VERSION + #define ZLIB_VERNUM MZ_VERNUM + #define ZLIB_VER_MAJOR MZ_VER_MAJOR + #define ZLIB_VER_MINOR MZ_VER_MINOR + #define ZLIB_VER_REVISION MZ_VER_REVISION + #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION + #define zlibVersion mz_version + #define zlib_version mz_version() +#endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES + +#endif // MINIZ_NO_ZLIB_APIS + +// ------------------- Types and macros + +typedef uint8_t mz_uint8; +typedef int16_t mz_int16; +typedef uint16_t mz_uint16; +typedef uint32_t mz_uint32; +typedef unsigned int mz_uint; +typedef int64_t mz_int64; +typedef uint64_t mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +// Works around MSVC's spammy "warning C4127: conditional expression is constant" message. +#ifdef _MSC_VER + #define MZ_MACRO_END while (0, 0) +#else + #define MZ_MACRO_END while (0) +#endif + +// ------------------- ZIP archive reading/writing + +#ifndef MINIZ_NO_ARCHIVE_APIS + +enum +{ + MZ_ZIP_MAX_IO_BUF_SIZE = 64*1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 +}; + +typedef struct +{ + mz_uint32 m_file_index; + mz_uint32 m_central_dir_ofs; + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; +#ifndef MINIZ_NO_TIME + time_t m_time; +#endif + mz_uint32 m_crc32; + mz_uint64 m_comp_size; + mz_uint64 m_uncomp_size; + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + mz_uint64 m_local_header_ofs; + mz_uint32 m_comment_size; + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum +{ + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef struct +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + mz_uint m_total_files; + mz_zip_mode m_zip_mode; + + mz_uint m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +typedef enum +{ + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 +} mz_zip_flags; + +// ZIP archive reading + +// Inits a ZIP archive reader. +// These functions read and validate the archive's central directory. +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +#endif + +// Returns the total number of files in the archive. +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +// Returns detailed information about an archive file entry. +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +// Determines if an archive file entry is a directory entry. +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +// Retrieves the filename of an archive file entry. +// Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +// Attempts to locates a file in the archive's central directory. +// Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH +// Returns -1 if the file cannot be found. +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + +// Extracts a archive file to a memory buffer using no memory allocation. +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +// Extracts a archive file to a memory buffer. +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +// Extracts a archive file to a dynamically allocated heap buffer. +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +// Extracts a archive file using a callback function to output the file's data. +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +// Extracts a archive file to a disk file and sets its last accessed and modified times. +// This function only extracts files, not archive directory records. +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); +#endif + +// Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +// ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +// Inits a ZIP archive writer. +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +#endif + +// Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. +// For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. +// For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). +// Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. +// Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before +// the archive is finalized the file's central directory will be hosed. +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); + +// Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. +// To add a directory entry, call this method with an archive name ending in a forwardslash with empty buffer. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +#ifndef MINIZ_NO_STDIO +// Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +#endif + +// Adds a file to an archive by fully cloning the data from another archive. +// This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data, and comment fields. +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); + +// Finalizes the archive by writing the central directory records followed by the end of central directory record. +// After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). +// An archive must be manually finalized by calling this function for it to be valid. +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); + +// Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. +// Note for the archive to be valid, it must have been finalized before ending. +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +// Misc. high-level helper functions: + +// mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. +// level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +// Reads a single file from an archive into a heap block. +// Returns NULL on failure. +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +// ------------------- Low-level Decompression API Definitions + +// Decompression flags used by tinfl_decompress(). +// TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. +// TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. +// TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). +// TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +// High level decompression functions: +// tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. +// On return: +// Function returns a pointer to the decompressed data, or NULL on failure. +// *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must call mz_free() on the returned block when it's no longer needed. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. +// Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. +// Returns 1 on success or 0 on failure. +typedef int (*tinfl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; + +// Max size of LZ dictionary. +#define TINFL_LZ_DICT_SIZE 32768 + +// Return status. +typedef enum +{ + TINFL_STATUS_BAD_PARAM = -3, + TINFL_STATUS_ADLER32_MISMATCH = -2, + TINFL_STATUS_FAILED = -1, + TINFL_STATUS_DONE = 0, + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +// Initializes the decompressor to its initial state. +#define tinfl_init(r) do { (r)->m_state = 0; } MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +// Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. +// This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +// Internal/private bits follow. +enum +{ + TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS + #define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF + typedef mz_uint64 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (64) +#else + typedef mz_uint32 tinfl_bit_buf_t; + #define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +// ------------------- Low-level Compression API Definitions + +// Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). +#define TDEFL_LESS_MEMORY 0 + +// tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): +// TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). +enum +{ + TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +// TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. +// TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). +// TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. +// TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). +// TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) +// TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. +// TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. +// TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +// High level compression functions: +// tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). +// On entry: +// pSrc_buf, src_buf_len: Pointer and size of source block to compress. +// flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. +// The caller must free() the returned block when it's no longer needed. +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +// tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. +// Returns 0 on failure. +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +// Compresses an image to a compressed PNG file in memory. +// On entry: +// pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. +// The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. +// On return: +// Function returns a pointer to the compressed data, or NULL on failure. +// *pLen_out will be set to the size of the PNG image file. +// The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +// Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void* pBuf, int len, void *pUser); + +// tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; + +// TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). +#if TDEFL_LESS_MEMORY +enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#else +enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13 ) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; +#endif + +// The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. +typedef enum +{ + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1, +} tdefl_status; + +// Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums +typedef enum +{ + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +// tdefl's compression state structure. +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +// Initializes the compressor. +// There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. +// pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. +// If pBut_buf_func is NULL the user should always call the tdefl_compress() API. +// flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +// Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +// tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. +// tdefl_compress_buffer() always consumes the entire input buffer. +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +// Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. +#ifndef MINIZ_NO_ZLIB_APIS +// Create tdefl_compress() flags given zlib-style compression parameters. +// level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) +// window_bits may be -15 (raw deflate) or 15 (zlib) +// strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); +#endif // #ifndef MINIZ_NO_ZLIB_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_INCLUDED + +// ------------------- End of Header: Implementation follows. (If you only want the header, define MINIZ_HEADER_FILE_ONLY.) + +#ifndef MINIZ_HEADER_FILE_ONLY + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16)==2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32)==4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64)==8 ? 1 : -1]; + +#include +#include + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC + #define MZ_MALLOC(x) NULL + #define MZ_FREE(x) (void)x, ((void)0) + #define MZ_REALLOC(p, x) NULL +#else + #define MZ_MALLOC(x) malloc(x) + #define MZ_FREE(x) free(x) + #define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a,b) (((a)>(b))?(a):(b)) +#define MZ_MIN(a,b) (((a)<(b))?(a):(b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) + #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else + #define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) + #define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#ifdef _MSC_VER + #define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) + #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) +#else + #define MZ_FORCEINLINE +#endif + +#ifdef __cplusplus + extern "C" { +#endif + +// ------------------- zlib-style API's + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) +{ + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; + if (!ptr) return MZ_ADLER32_INIT; + while (buf_len) { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { + s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + } + for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + } + return (s2 << 16) + s1; +} + +// Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) return MZ_CRC32_INIT; + crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } + return ~crcu32; +} + +void mz_free(void *p) +{ + MZ_FREE(p); +} + +#ifndef MINIZ_NO_ZLIB_APIS + +static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } +static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } +static void *def_realloc_func(void *opaque, void *address, size_t items, size_t size) { (void)opaque, (void)address, (void)items, (void)size; return MZ_REALLOC(address, items * size); } + +const char *mz_version(void) +{ + return MZ_VERSION; +} + +int mz_deflateInit(mz_streamp pStream, int level) +{ + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) +{ + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) pStream->zalloc = def_alloc_func; + if (!pStream->zfree) pStream->zfree = def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) +{ + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor*)pStream->state, NULL, NULL, ((tdefl_compressor*)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) +{ + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; + if (!pStream->avail_out) return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor*)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; + for ( ; ; ) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor*)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor*)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; // Can't make forward progress without some input. + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) +{ + if (!pStream) return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) +{ + (void)pStream; + // This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) +{ + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) +{ + return mz_deflateBound(NULL, source_len); +} + +typedef struct +{ + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) +{ + inflate_state *pDecomp; + if (!pStream) return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) pStream->zalloc = def_alloc_func; + if (!pStream->zfree) pStream->zfree = def_free_func; + + pDecomp = (inflate_state*)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) +{ + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflate(mz_streamp pStream, int flush) +{ + inflate_state* pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + + pState = (inflate_state*)pStream->state; + if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; pState->m_first_call = 0; + if (pState->m_last_status < 0) return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + // MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + // flush != MZ_FINISH then we must assume there's more input. + if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; + pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for ( ; ; ) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; + pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; // Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; // Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. + else if (flush == MZ_FINISH) + { + // The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + // In case mz_ulong is 64-bits (argh I hate longs). + if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32)*pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +const char *mz_error(int err) +{ + static struct { int m_err; const char *m_pDesc; } s_error_descs[] = + { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, + { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif //MINIZ_NO_ZLIB_APIS + +// ------------------- Low-level Decompression (completely independent from all compression API's) + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN switch(r->m_state) { case 0: +#define TINFL_CR_RETURN(state_index, result) do { status = result; r->m_state = state_index; goto common_exit; case state_index:; } MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) do { for ( ; ; ) { TINFL_CR_RETURN(state_index, result); } } MZ_MACRO_END +#define TINFL_CR_FINISH } + +// TODO: If the caller has indicated that there's no more input, and we attempt to read beyond the input buf, then something is wrong with the input because the inflator never +// reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of the stream with 0's in this scenario. +#define TINFL_GET_BYTE(state_index, c) do { \ + if (pIn_buf_cur >= pIn_buf_end) { \ + for ( ; ; ) { \ + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ + TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ + if (pIn_buf_cur < pIn_buf_end) { \ + c = *pIn_buf_cur++; \ + break; \ + } \ + } else { \ + c = 0; \ + break; \ + } \ + } \ + } else c = *pIn_buf_cur++; } MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) do { mz_uint c; TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) do { if (num_bits < (mz_uint)(n)) { TINFL_NEED_BITS(state_index, n); } b = bit_buf & ((1 << (n)) - 1); bit_buf >>= (n); num_bits -= (n); } MZ_MACRO_END + +// TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. +// It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a +// Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the +// bit buffer contains >=15 bits (deflate's max. Huffman code size). +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); if (temp >= 0) break; \ + } TINFL_GET_BYTE(state_index, c); bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); num_bits += 8; \ + } while (num_bits < 15); + +// TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read +// beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully +// decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. +// The slow path is only executed at the very end of the input buffer. +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) do { \ + int temp; mz_uint code_len, c; \ + if (num_bits < 15) { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } else { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); pIn_buf_cur += 2; num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else { \ + code_len = TINFL_FAST_LOOKUP_BITS; do { temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; } while (temp < 0); \ + } sym = temp; bit_buf >>= code_len; num_bits -= code_len; } MZ_MACRO_END + +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) +{ + static const int s_length_base[31] = { 3,4,5,6,7,8,9,10,11,13, 15,17,19,23,27,31,35,43,51,59, 67,83,99,115,131,163,195,227,258,0,0 }; + static const int s_length_extra[31]= { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + static const int s_dist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + static const int s_dist_extra[32] = { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + static const mz_uint8 s_length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + // Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } + + num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } + while (pIn_buf_cur >= pIn_buf_end) + { + if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) + { + TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); + } + else + { + TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); + } + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; + r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for ( i = 0; i <= 143; ++i) *p++ = 8; for ( ; i <= 255; ++i) *p++ = 9; for ( ; i <= 279; ++i) *p++ = 7; for ( ; i <= 287; ++i) *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } + r->m_table_sizes[2] = 19; + } + for ( ; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; + cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } + if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]); ) + { + mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for ( ; ; ) + { + mz_uint8 *pSrc; + for ( ; ; ) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } +#else + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + counter = sym2; bit_buf >>= code_len; num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); + } + bit_buf >>= code_len; num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) break; + + num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; + if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + do + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; pSrc += 3; + } while ((int)(counter -= 3) > 2); + if ((int)counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if ((int)counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + TINFL_CR_FINISH + +common_exit: + r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; + } + for ( ; i < block_len; ++i) s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +// Higher level helper functions. +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8*)pBuf, pBuf ? (mz_uint8*)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) break; + new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); *pOut_len = 0; return NULL; + } + pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8*)pSrc_buf, &src_buf_len, (mz_uint8*)pOut_buf, (mz_uint8*)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8*)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for ( ; ; ) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8*)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +// ------------------- Low-level Compression (independent from all decompression API's) + +// Purposely making these tables static for faster init and thread safety. +static const mz_uint16 s_tdefl_len_sym[256] = { + 257,258,259,260,261,262,263,264,265,265,266,266,267,267,268,268,269,269,269,269,270,270,270,270,271,271,271,271,272,272,272,272, + 273,273,273,273,273,273,273,273,274,274,274,274,274,274,274,274,275,275,275,275,275,275,275,275,276,276,276,276,276,276,276,276, + 277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,277,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278,278, + 279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,279,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280,280, + 281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281,281, + 282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282,282, + 283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283,283, + 284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,284,285 }; + +static const mz_uint8 s_tdefl_len_extra[256] = { + 0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, + 4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,0 }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = { + 0,1,2,3,4,4,5,5,6,6,6,6,7,7,7,7,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11, + 11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13, + 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,14,14,14,14,14,14,14,14,14,14,14,14, + 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14, + 14,14,14,14,14,14,14,14,14,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15, + 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16, + 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17, + 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17 }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = { + 0,0,0,0,1,1,1,1,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5, + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, + 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, + 7,7,7,7,7,7,7,7 }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = { + 0,0,18,19,20,20,21,21,22,22,22,22,23,23,23,23,24,24,24,24,24,24,24,24,25,25,25,25,25,25,25,25,26,26,26,26,26,26,26,26,26,26,26,26, + 26,26,26,26,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,27,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28, + 28,28,28,28,28,28,28,28,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29 }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = { + 0,0,8,8,9,9,9,9,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12, + 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13, + 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13 }; + +// Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. +typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; +static tdefl_sym_freq* tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq* pSyms0, tdefl_sym_freq* pSyms1) +{ + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32* pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } + for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { tdefl_sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } + } + return pCur_syms; +} + +// tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) +{ + int root, leaf, next, avbl, used, dpth; + if (n==0) return; else if (n==1) { A[0].m_key = 1; return; } + A[0].m_key += A[1].m_key; root = 0; leaf = 2; + for (next=1; next < n-1; next++) + { + if (leaf>=n || A[root].m_key=n || (root=0; next--) A[next].m_key = A[A[next].m_key].m_key+1; + avbl = 1; used = dpth = 0; root = n-2; next = n-1; + while (avbl>0) + { + while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; } + while (avbl>used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } + avbl = 2*used; dpth++; used = 0; + } +} + +// Limits canonical Huffman code table's max code size. +enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) +{ + int i; mz_uint32 total = 0; if (code_list_len <= 1) return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) +{ + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; + code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) do { \ + mz_uint bits = b; mz_uint len = l; MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); d->m_bits_in += len; \ + while (d->m_bits_in >= 8) { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ +} MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() { if (rle_repeat_count) { \ + if (rle_repeat_count < 3) { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } else { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); packed_code_sizes[num_packed_code_sizes++] = 16; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ +} rle_repeat_count = 0; } } + +#define TDEFL_RLE_ZERO_CODE_SIZE() { if (rle_z_count) { \ + if (rle_z_count < 3) { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ + } else if (rle_z_count <= 10) { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); packed_code_sizes[num_packed_code_sizes++] = 17; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } else { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); packed_code_sizes[num_packed_code_sizes++] = 18; packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ +} rle_z_count = 0; } } + +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor *d) +{ + int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes; ) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor *d) +{ + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) *p++ = 8; + for ( ; i <= 255; ++i) *p++ = 9; + for ( ; i <= 279; ++i) *p++ = 7; + for ( ; i <= 287; ++i) *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) { bit_buffer |= (((mz_uint64)(b)) << bits_in); bits_in += (l); } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + // This sequence coaxes MSVC into using cmov's vs. jmp's. + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64*)pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS + +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) +{ + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static int tdefl_flush_block(tdefl_compressor *d, int flush) +{ + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + // If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. + if ( ((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size) ) + { + mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + // Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } + } + else + { + mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16*)(p) +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16*)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; + for ( ; ; ) + { + for ( ; ; ) + { + if (--num_probes_left == 0) return; + #define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) break; + TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + } + if (!dist) break; q = (const mz_uint16*)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; + do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); + if (!probe_len) + { + *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8*)p == *(const mz_uint8*)q)) > match_len) + { + *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; + for ( ; ; ) + { + for ( ; ; ) + { + if (--num_probes_left == 0) return; + #define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) break; + TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; + } + if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; + if (probe_len > match_len) + { + *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; + c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN +static mz_bool tdefl_compress_fast(tdefl_compressor *d) +{ + // Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0) ); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) +{ + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) +{ + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + + if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor *d) +{ + const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + // Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + // Simple lazy/greedy parsing state machine. + len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U*1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; + } + // Move the lookahead forward by len_to_move bytes. + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, TDEFL_LZ_DICT_SIZE); + // Check if it's time to flush the current LZ codes to the internal output buffer. + if ( (d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ( (d->m_total_lz_bytes > 31*1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) ) + { + int n; + d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) +{ + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) +{ + if (!d) + { + if (pIn_buf_size) *pIn_buf_size = 0; + if (pOut_buf_size) *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if ( ((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf) ) + { + if (pIn_buf_size) *pIn_buf_size = 0; + if (pOut_buf_size) *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) +{ + MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; + d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) +{ + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) +{ + return d->m_adler32; +} + +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; + pComp = (tdefl_compressor*)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); return succeeded; +} + +typedef struct +{ + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) +{ + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; + do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); + pNew_buf = (mz_uint8*)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; + p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; + } + memcpy((mz_uint8*)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; + return MZ_TRUE; +} + +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; + *pOut_len = out_buf.m_size; return out_buf.m_pBuf; +} + +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) return 0; + out_buf.m_pBuf = (mz_uint8*)pOut_buf; out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; + return out_buf.m_size; +} + +#ifndef MINIZ_NO_ZLIB_APIS +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +// level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) +{ + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} +#endif //MINIZ_NO_ZLIB_APIS + +#ifdef _MSC_VER +#pragma warning (push) +#pragma warning (disable:4204) // nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) +#endif + +// Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at +// http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) +{ + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; + if (!pComp) return NULL; + MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57+MZ_MAX(64, (1+bpl)*h); if (NULL == (out_buf.m_pBuf = (mz_uint8*)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } + // write dummy header + for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); + // compress image data + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, TDEFL_DEFAULT_MAX_PROBES | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8*)pImage + y * bpl, bpl, TDEFL_NO_FLUSH); } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } + // write real header + *pLen_out = out_buf.m_size-41; + { + mz_uint8 pnghdr[41]={0x89,0x50,0x4e,0x47,0x0d,0x0a,0x1a,0x0a,0x00,0x00,0x00,0x0d,0x49,0x48,0x44,0x52, + 0,0,(mz_uint8)(w>>8),(mz_uint8)w,0,0,(mz_uint8)(h>>8),(mz_uint8)h,8,"\0\0\04\02\06"[num_chans],0,0,0,0,0,0,0, + (mz_uint8)(*pLen_out>>24),(mz_uint8)(*pLen_out>>16),(mz_uint8)(*pLen_out>>8),(mz_uint8)*pLen_out,0x49,0x44,0x41,0x54}; + c=(mz_uint32)mz_crc32(MZ_CRC32_INIT,pnghdr+12,17); for (i=0; i<4; ++i, c<<=8) ((mz_uint8*)(pnghdr+29))[i]=(mz_uint8)(c>>24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + // write footer (IDAT CRC-32, followed by IEND chunk) + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT,out_buf.m_pBuf+41-4, *pLen_out+4); for (i=0; i<4; ++i, c<<=8) (out_buf.m_pBuf+out_buf.m_size-16)[i] = (mz_uint8)(c >> 24); + // compute final size of file, grab compressed data buffer and return + *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; +} + +#ifdef _MSC_VER +#pragma warning (pop) +#endif + +// ------------------- .ZIP archive reading + +#ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef MINIZ_NO_STDIO + #define MZ_FILE void * +#else + #include + #include + + #if defined(_MSC_VER) + static FILE *mz_fopen(const char *pFilename, const char *pMode) + { + FILE* pFile = NULL; + fopen_s(&pFile, pFilename, pMode); + return pFile; + } + static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) + { + FILE* pFile = NULL; + if (freopen_s(&pFile, pPath, pMode, pStream)) + return NULL; + return pFile; + } + #else + static FILE *mz_fopen(const char *pFilename, const char *pMode) + { + return fopen(pFilename, pMode); + } + static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) + { + return freopen(pPath, pMode, pStream); + } + #endif // #if defined(_MSC_VER) + + #if defined(_MSC_VER) || defined(__MINGW64__) + #ifndef MINIZ_NO_TIME + #include + #endif + #define MZ_FILE FILE + #define MZ_FOPEN mz_fopen + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 _ftelli64 + #define MZ_FSEEK64 _fseeki64 + #define MZ_FILE_STAT_STRUCT _stat + #define MZ_FILE_STAT _stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN mz_freopen + #define MZ_DELETE_FILE remove + #elif defined(__MINGW32__) + #ifndef MINIZ_NO_TIME + #include + #endif + #define MZ_FILE FILE + #define MZ_FOPEN mz_fopen + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 ftello64 + #define MZ_FSEEK64 fseeko64 + #define MZ_FILE_STAT_STRUCT _stat + #define MZ_FILE_STAT _stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN mz_freopen + #define MZ_DELETE_FILE remove + #elif defined(__TINYC__) + #ifndef MINIZ_NO_TIME + #include + #endif + #define MZ_FILE FILE + #define MZ_FOPEN mz_fopen + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 ftell + #define MZ_FSEEK64 fseek + #define MZ_FILE_STAT_STRUCT stat + #define MZ_FILE_STAT stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN mz_freopen + #define MZ_DELETE_FILE remove + #else + #ifndef MINIZ_NO_TIME + #include + #endif + #define MZ_FILE FILE + #define MZ_FOPEN mz_fopen + #define MZ_FCLOSE fclose + #define MZ_FREAD fread + #define MZ_FWRITE fwrite + #define MZ_FTELL64 ftello + #define MZ_FSEEK64 fseeko + #define MZ_FILE_STAT_STRUCT stat + #define MZ_FILE_STAT stat + #define MZ_FFLUSH fflush + #define MZ_FREOPEN mz_freopen + #define MZ_DELETE_FILE remove + #endif // #ifdef _MSC_VER +#endif // #ifdef MINIZ_NO_STDIO + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +// Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. +enum +{ + // ZIP archive identifiers and record sizes + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + // Central directory header record offsets + MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + // Local directory header offsets + MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + // End of central directory offsets + MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, +}; + +typedef struct +{ + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; +} mz_zip_array; + +struct mz_zip_internal_state_tag +{ + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + MZ_FILE *m_pFile; + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; +}; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) +{ + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) +{ + void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; + if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; + pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) +{ + if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) +{ + if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) +{ + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) +{ + size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; + memcpy((mz_uint8*)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) +{ + struct tm tm; + memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef _MSC_VER + struct tm tm_struct; + struct tm *tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) + { + *pDOS_date = 0; *pDOS_time = 0; + return; + } +#else + struct tm *tm = localtime(&time); +#endif + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} +#endif + +#ifndef MINIZ_NO_STDIO +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef MINIZ_NO_TIME + (void)pFilename; *pDOS_date = *pDOS_time = 0; +#else + struct MZ_FILE_STAT_STRUCT file_stat; if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; + mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); +#endif // #ifdef MINIZ_NO_TIME + return MZ_TRUE; +} + +static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) +{ +#ifndef MINIZ_NO_TIME + struct utimbuf t; t.actime = access_time; t.modtime = modified_time; + return !utime(pFilename, &t); +#else + (void)pFilename, (void)access_time, (void)modified_time; + return MZ_TRUE; +#endif // #ifndef MINIZ_NO_TIME +} +#endif + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) +{ + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return MZ_FALSE; + + if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return MZ_FALSE; + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) do { mz_uint32 t = a; a = b; b = t; } MZ_MACRO_END + +// Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) +static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const int size = pZip->m_total_files; + int start = (size - 2) >> 1, end; + while (start >= 0) + { + int child, root = start; + for ( ; ; ) + { + if ((child = (root << 1) + 1) >= size) + break; + child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + } + start--; + } + + end = size - 1; + while (end > 0) + { + int child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for ( ; ; ) + { + if ((child = (root << 1) + 1) >= end) + break; + child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) +{ + mz_uint cdir_size, num_this_disk, cdir_disk_index; + mz_uint64 cdir_ofs; + mz_int64 cur_file_ofs; + const mz_uint8 *p; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + // Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + // Find the end of central directory record by scanning the file from the end towards the beginning. + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for ( ; ; ) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + for (i = n - 4; i >= 0; --i) + if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + break; + if (i >= 0) + { + cur_file_ofs += i; + break; + } + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return MZ_FALSE; + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + // Read and verify the end of central directory record. + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || + ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) + return MZ_FALSE; + + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return MZ_FALSE; + + if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return MZ_FALSE; + + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return MZ_FALSE; + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + // Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and another to hold the sorted indices. + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return MZ_FALSE; + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return MZ_FALSE; + + // Now create an index into the central directory file records, do some basic sanity checking on each record, and check for zip64 entries (which are not yet supported). + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, comp_size, decomp_size, disk_index; + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return MZ_FALSE; + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) + return MZ_FALSE; + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index != num_this_disk) && (disk_index != 1)) + return MZ_FALSE; + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return MZ_FALSE; + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return MZ_FALSE; + n -= total_header_size; p += total_header_size; + } + } + + if ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) +{ + if ((!pZip) || (!pZip->m_pRead)) + return MZ_FALSE; + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + pZip->m_archive_size = size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) +{ + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pMem = (void *)pMem; + pZip->m_pState->m_mem_size = size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) +{ + mz_uint64 file_size; + MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return MZ_FALSE; + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + return MZ_FALSE; + file_size = MZ_FTELL64(pFile); + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end(pZip); + return MZ_FALSE; + } + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_total_files : 0; +} + +static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh(mz_zip_archive *pZip, mz_uint file_index) +{ + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) + return MZ_FALSE; + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & 1); +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint filename_len, internal_attr, external_attr; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) + return MZ_FALSE; + + internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((!internal_attr) && ((external_attr & 0x10) != 0)) + return MZ_TRUE; + + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + return MZ_FALSE; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if ((!p) || (!pStat)) + return MZ_FALSE; + + // Unpack the central directory record. + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + // Copy as much of the filename and comment as possible. + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; + + return MZ_TRUE; +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) +{ + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int mz_zip_reader_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const int size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + int l = 0, h = size - 1; + while (l <= h) + { + int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + return file_index; + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + return -1; +} + +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) +{ + mz_uint file_index; size_t name_len, comment_len; + if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return -1; + if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_p)) + return mz_zip_reader_locate_file_binary_search(pZip, pName); + name_len = strlen(pName); if (name_len > 0xFFFF) return -1; + comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) + return file_index; + } + return -1; +} + +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((buf_size) && (!pBuf)) + return MZ_FALSE; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Ensure supplied output buffer is large enough. + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return MZ_FALSE; + return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); + } + + // Decompress the file either directly from memory or from a file input buffer. + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + // Read directly from the archive in memory. + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + // Use a user provided read buffer. + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_uncomp_size; + } + else + { + // Temporarily allocate a read buffer. + read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) +#endif + return MZ_FALSE; + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); +} + +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); +} + +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +} + +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) +{ + mz_uint64 comp_size, uncomp_size, alloc_size; + const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); + void *pBuf; + + if (pSize) + *pSize = 0; + if (!p) + return NULL; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) +#endif + return NULL; + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + return NULL; + + if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) *pSize = (size_t)alloc_size; + return pBuf; +} + +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + { + if (pSize) *pSize = 0; + return MZ_FALSE; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if (!file_stat.m_comp_size) + return MZ_TRUE; + + // Encryption and patch files are not supported. + if (file_stat.m_bit_flag & (1 | 32)) + return MZ_FALSE; + + // This function only supports stored and deflate. + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return MZ_FALSE; + + // Read and parse the local directory entry. + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return MZ_FALSE; + + // Decompress the file either directly from memory or from a file input buffer. + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return MZ_FALSE; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + // The file is stored or the caller has requested the compressed data. + if (pZip->m_pState->m_pMem) + { +#ifdef _MSC_VER + if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) +#else + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) +#endif + return MZ_FALSE; + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + status = TINFL_STATUS_FAILED; + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + status = TINFL_STATUS_FAILED; + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + status = TINFL_STATUS_FAILED; + break; + } + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + // Make sure the entire file was decompressed, and check its CRC. + if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) + status = TINFL_STATUS_FAILED; + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) +{ + (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE*)pOpaque); +} + +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) +{ + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return MZ_FALSE; + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + if (MZ_FCLOSE(pFile) == EOF) + return MZ_FALSE; +#ifndef MINIZ_NO_TIME + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + return status; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE(pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) +{ + int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); + if (file_index < 0) + return MZ_FALSE; + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} +#endif + +// ------------------- .ZIP archive writing + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } +static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) + +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) +{ + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return MZ_FALSE; + + if (pZip->m_file_offset_alignment) + { + // Ensure user specified file offset alignment is a power of 2. + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return MZ_FALSE; + } + + if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; + if (!pZip->m_pFree) pZip->m_pFree = def_free_func; + if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return MZ_FALSE; + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + return MZ_TRUE; +} + +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); +#ifdef _MSC_VER + if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) +#else + if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) +#endif + return 0; + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + return 0; + pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) +{ + pZip->m_pWrite = mz_zip_heap_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) +{ + MZ_FILE *pFile; + pZip->m_pWrite = mz_zip_file_write_func; + pZip->m_pIO_opaque = pZip; + if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) + return MZ_FALSE; + if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + pZip->m_pState->m_pFile = pFile; + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return MZ_FALSE; + } + cur_ofs += n; size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) +{ + mz_zip_internal_state *pState; + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return MZ_FALSE; + // No sense in trying to write to an archive that's already at the support max size + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + pFilename; return MZ_FALSE; +#else + // Archive is being read from stdio - try to reopen as writable. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + if (!pFilename) + return MZ_FALSE; + pZip->m_pWrite = mz_zip_file_write_func; + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + // The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. + mz_zip_reader_end(pZip); + return MZ_FALSE; + } +#endif // #ifdef MINIZ_NO_STDIO + } + else if (pState->m_pMem) + { + // Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. + if (pZip->m_pIO_opaque != pZip) + return MZ_FALSE; + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + } + // Archive is being read via a user provided read function - make sure the user has specified a write function too. + else if (!pZip->m_pWrite) + return MZ_FALSE; + + // Start writing new files at the archive's current central directory location. + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + pZip->m_central_directory_file_ofs = 0; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) +{ + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +} + +typedef struct +{ + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void* pBuf, int len, void *pUser) +{ + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + // No zip64 support yet + if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return MZ_FALSE; + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + // Try to push the central directory array back into its original state. + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) +{ + // Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. + if (*pArchive_name == '/') + return MZ_FALSE; + while (*pArchive_name) + { + if ((*pArchive_name == '\\') || (*pArchive_name == ':')) + return MZ_FALSE; + pArchive_name++; + } + return MZ_TRUE; +} + +static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) +{ + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) +{ + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return MZ_FALSE; + cur_file_ofs += s; n -= s; + } + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) +{ + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + + pState = pZip->m_pState; + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return MZ_FALSE; + // No zip64 support yet + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + +#ifndef MINIZ_NO_TIME + { + time_t cur_time; time(&cur_time); + mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif // #ifndef MINIZ_NO_TIME + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + // Set DOS Subdirectory attribute bit. + ext_attributes |= 0x10; + // Subdirectories cannot contain data. + if ((buf_size) || (uncomp_size)) + return MZ_FALSE; + } + + // Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return MZ_FALSE; + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return MZ_FALSE; + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + + MZ_CLEAR_OBJ(local_dir_header); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8*)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + method = MZ_DEFLATED; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + MZ_FILE *pSrc_file = NULL; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > 0xFFFF) + return MZ_FALSE; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) + return MZ_FALSE; + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return MZ_FALSE; + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + if (uncomp_size > 0xFFFFFFFF) + { + // No zip64 support yet + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + if (uncomp_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) + return MZ_FALSE; + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); + + MZ_CLEAR_OBJ(local_dir_header); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + cur_archive_file_ofs += archive_name_size; + + if (uncomp_size) + { + mz_uint64 uncomp_remaining = uncomp_size; + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + if (!level) + { + while (uncomp_remaining) + { + mz_uint n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); + if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + uncomp_remaining -= n; + cur_archive_file_ofs += n; + } + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + for ( ; ; ) + { + size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, MZ_ZIP_MAX_IO_BUF_SIZE); + tdefl_status status; + + if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) + break; + + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); + uncomp_remaining -= in_buf_size; + + status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + break; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + MZ_FCLOSE(pSrc_file); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + + method = MZ_DEFLATED; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + MZ_FCLOSE(pSrc_file); pSrc_file = NULL; + + // no zip64 support yet + if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) + return MZ_FALSE; + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) + return MZ_FALSE; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return MZ_FALSE; + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} +#endif // #ifndef MINIZ_NO_STDIO + +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) +{ + mz_uint n, bit_flags, num_alignment_padding_bytes; + mz_uint64 comp_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; const mz_uint8 *pSrc_central_header; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) + return MZ_FALSE; + pState = pZip->m_pState; + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + // no zip64 support yet + if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + cur_dst_file_ofs = pZip->m_archive_size; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return MZ_FALSE; + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + cur_dst_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return MZ_FALSE; + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) + return MZ_FALSE; + + while (comp_bytes_remaining) + { + n = (mz_uint)MZ_MIN(MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + cur_dst_file_ofs += n; + + comp_bytes_remaining -= n; + } + + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + // Copy data descriptor + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return MZ_FALSE; + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + // no zip64 support yet + if (cur_dst_file_ofs > 0xFFFFFFFF) + return MZ_FALSE; + + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return MZ_FALSE; + + n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + if (pState->m_central_dir.m_size > 0xFFFFFFFF) + return MZ_FALSE; + n = (mz_uint32)pState->m_central_dir.m_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return MZ_FALSE; + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return MZ_FALSE; + + pState = pZip->m_pState; + + // no zip64 support yet + if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) + return MZ_FALSE; + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + // Write central directory + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return MZ_FALSE; + pZip->m_archive_size += central_dir_size; + } + + // Write end of central directory record + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) + return MZ_FALSE; +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return MZ_FALSE; +#endif // #ifndef MINIZ_NO_STDIO + + pZip->m_archive_size += sizeof(hdr); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) +{ + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) + return MZ_FALSE; + if (pZip->m_pWrite != mz_zip_heap_write_func) + return MZ_FALSE; + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *pBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + return MZ_FALSE; + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + MZ_FCLOSE(pState->m_pFile); + pState->m_pFile = NULL; + } +#endif // #ifndef MINIZ_NO_STDIO + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + MZ_CLEAR_OBJ(zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + return MZ_FALSE; + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return MZ_FALSE; + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + // Create a new archive. + if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) + return MZ_FALSE; + created_new_archive = MZ_TRUE; + } + else + { + // Append to an existing archive. + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return MZ_FALSE; + if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) + { + mz_zip_reader_end(&zip_archive); + return MZ_FALSE; + } + } + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + // Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) + if (!mz_zip_writer_finalize_archive(&zip_archive)) + status = MZ_FALSE; + if (!mz_zip_writer_end(&zip_archive)) + status = MZ_FALSE; + if ((!status) && (created_new_archive)) + { + // It's a new archive and something went wrong, so just delete it. + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + return status; +} + +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) +{ + int file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + return NULL; + + MZ_CLEAR_OBJ(zip_archive); + if (!mz_zip_reader_init_file(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) + return NULL; + + if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + + mz_zip_reader_end(&zip_archive); + return p; +} + +#endif // #ifndef MINIZ_NO_STDIO + +#endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +#endif // #ifndef MINIZ_NO_ARCHIVE_APIS + +#ifdef __cplusplus +} +#endif + +#endif // MINIZ_HEADER_FILE_ONLY + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ diff --git a/sdrbase/util/simpleserializer.cpp b/sdrbase/util/simpleserializer.cpp new file mode 100644 index 000000000..4230aa7d1 --- /dev/null +++ b/sdrbase/util/simpleserializer.cpp @@ -0,0 +1,704 @@ +#include +#include "util/simpleserializer.h" + +#if __WORDSIZE == 64 +#define PRINTF_FORMAT_S32 "%d" +#define PRINTF_FORMAT_U32 "%u" +#define PRINTF_FORMAT_S64 "%d" +#define PRINTF_FORMAT_U64 "%u" +#else +#define PRINTF_FORMAT_S32 "%d" +#define PRINTF_FORMAT_U32 "%u" +#define PRINTF_FORMAT_S64 "%lld" +#define PRINTF_FORMAT_U64 "%llu" +#endif + +template struct Assert { }; +typedef Assert<(bool(sizeof(float) == 4))> float_must_be_32_bits[bool(sizeof(float) == 4) ? 1 : -1]; +typedef Assert<(bool(sizeof(double) == 8))> double_must_be_64_bits[bool(sizeof(double) == 8) ? 1 : -1]; + +SimpleSerializer::SimpleSerializer(uint version) : + m_data(), + m_finalized(false) +{ + m_data.reserve(100); + + // write version information + int length; + if(version >= (1 << 24)) + length = 4; + else if(version >= (1 << 16)) + length = 3; + else if(version >= (1 << 8)) + length = 2; + else if(version > 0) + length = 1; + else length = 0; + if(!writeTag(TVersion, 0, length)) + return; + length--; + for(int i = length; i >= 0; i--) + m_data.push_back((char)((version >> (i * 8)) & 0xff)); +} + +void SimpleSerializer::writeS32(quint32 id, qint32 value) +{ + int length; + + if(id == 0) { + qCritical("SimpleSerializer: ID 0 is not allowed"); + return; + } + + if((value < -(1 << 23)) || (value >= (1 << 23))) + length = 4; + else if((value < -(1 << 15)) || (value >= (1 << 15))) + length = 3; + else if((value < -(1 << 7)) || (value >= (1 << 7))) + length = 2; + else if(value != 0) + length = 1; + else length = 0; + + if(!writeTag(TSigned32, id, length)) + return; + + length--; + for(int i = length; i >= 0; i--) + m_data.push_back((char)((value >> (i * 8)) & 0xff)); +} + +void SimpleSerializer::writeU32(quint32 id, quint32 value) +{ + int length; + + if(id == 0) { + qCritical("SimpleSerializer: ID 0 is not allowed"); + return; + } + + if(value >= (1 << 24)) + length = 4; + else if(value >= (1 << 16)) + length = 3; + else if(value >= (1 << 8)) + length = 2; + else if(value > 0) + length = 1; + else length = 0; + + if(!writeTag(TUnsigned32, id, length)) + return; + + length--; + for(int i = length; i >= 0; i--) + m_data.push_back((char)((value >> (i * 8)) & 0xff)); +} + +void SimpleSerializer::writeS64(quint32 id, qint64 value) +{ + int length; + + if(id == 0) { + qCritical("SimpleSerializer: ID 0 is not allowed"); + return; + } + + if((value < -(1ll << 55)) || (value >= (1ll << 55))) + length = 8; + else if((value < -(1ll << 47)) || (value >= (1ll << 47))) + length = 7; + else if((value < -(1ll << 39)) || (value >= (1ll << 39))) + length = 6; + else if((value < -(1ll << 31)) || (value >= (1ll << 31))) + length = 5; + else if((value < -(1ll << 23)) || (value >= (1ll << 23))) + length = 4; + else if((value < -(1ll << 15)) || (value >= (1ll << 15))) + length = 3; + else if((value < -(1ll << 7)) || (value >= (1ll << 7))) + length = 2; + else if(value != 0) + length = 1; + else length = 0; + + if(!writeTag(TSigned64, id, length)) + return; + + length--; + for(int i = length; i >= 0; i--) + m_data.push_back((char)((value >> (i * 8)) & 0xff)); +} + +void SimpleSerializer::writeU64(quint32 id, quint64 value) +{ + int length; + + if(id == 0) { + qCritical("SimpleSerializer: ID 0 is not allowed"); + return; + } + + if(value >= (1ll << 56)) + length = 8; + else if(value >= (1ll << 48)) + length = 7; + else if(value >= (1ll << 40)) + length = 6; + else if(value >= (1ll << 32)) + length = 5; + else if(value >= (1ll << 24)) + length = 4; + else if(value >= (1ll << 16)) + length = 3; + else if(value >= (1ll << 8)) + length = 2; + else if(value > 0) + length = 1; + else length = 0; + + if(!writeTag(TUnsigned64, id, length)) + return; + + length--; + for(int i = length; i >= 0; i--) + m_data.push_back((char)((value >> (i * 8)) & 0xff)); +} + +void SimpleSerializer::writeFloat(quint32 id, float value) +{ + if(id == 0) { + qCritical("SimpleSerializer: ID 0 is not allowed"); + return; + } + + if(!writeTag(TFloat, id, 4)) + return; + + quint32 tmp = *((quint32*)&value); + m_data.push_back((char)((tmp >> 24) & 0xff)); + m_data.push_back((char)((tmp >> 16) & 0xff)); + m_data.push_back((char)((tmp >> 8) & 0xff)); + m_data.push_back((char)(tmp & 0xff)); +} + +void SimpleSerializer::writeDouble(quint32 id, double value) +{ + if(id == 0) { + qCritical("SimpleSerializer: ID 0 is not allowed"); + return; + } + + if(!writeTag(TDouble, id, 8)) + return; + + quint64 tmp = *((quint64*)&value); + m_data.push_back((char)((tmp >> 56) & 0xff)); + m_data.push_back((char)((tmp >> 48) & 0xff)); + m_data.push_back((char)((tmp >> 40) & 0xff)); + m_data.push_back((char)((tmp >> 32) & 0xff)); + m_data.push_back((char)((tmp >> 24) & 0xff)); + m_data.push_back((char)((tmp >> 16) & 0xff)); + m_data.push_back((char)((tmp >> 8) & 0xff)); + m_data.push_back((char)(tmp & 0xff)); +} + +void SimpleSerializer::writeBool(quint32 id, bool value) +{ + if(id == 0) { + qCritical("SimpleSerializer: ID 0 is not allowed"); + return; + } + + if(!writeTag(TBool, id, 1)) + return; + if(value) + m_data.push_back((char)0x01); + else m_data.push_back((char)0x00); +} + +void SimpleSerializer::writeString(quint32 id, const QString& value) +{ + if(id == 0) { + qCritical("SimpleSerializer: ID 0 is not allowed"); + return; + } + + QByteArray utf8 = value.toUtf8(); + if(!writeTag(TString, id, utf8.size())) + return; + m_data.append(utf8); +} + +void SimpleSerializer::writeBlob(quint32 id, const QByteArray& value) +{ + if(id == 0) { + qCritical("SimpleSerializer: ID 0 is not allowed"); + return; + } + + if(!writeTag(TBlob, id, value.size())) + return; + m_data.append(value); +} + +const QByteArray& SimpleSerializer::final() +{ + m_finalized = true; + return m_data; +} + +bool SimpleSerializer::writeTag(Type type, quint32 id, quint32 length) +{ + if(m_finalized) { + qCritical("SimpleSerializer: config has already been finalized (id %u)", id); + return false; + } + + int idLen; + int lengthLen; + + if(id < (1 << 8)) + idLen = 0; + else if(id < (1 << 16)) + idLen = 1; + else if(id < (1 << 24)) + idLen = 2; + else idLen = 3; + + if(length < (1 << 8)) + lengthLen = 0; + else if(length < (1 << 16)) + lengthLen = 1; + else if(length < (1 << 24)) + lengthLen = 2; + else lengthLen = 3; + + m_data.push_back((char)((type << 4) | (idLen << 2) | lengthLen)); + for(int i = idLen; i >= 0; i--) + m_data.push_back((char)((id >> (i * 8)) & 0xff)); + for(int i = lengthLen; i >= 0; i--) + m_data.push_back((char)((length >> (i * 8)) & 0xff)); + return true; +} + +SimpleDeserializer::SimpleDeserializer(const QByteArray& data) : + m_data(data) +{ + m_valid = parseAll(); + + // read version information + uint readOfs; + Elements::const_iterator it = m_elements.constFind(0); + if(it == m_elements.constEnd()) + goto setInvalid; + if(it->type != TVersion) + goto setInvalid; + if(it->length > 4) + goto setInvalid; + + readOfs = it->ofs; + m_version = 0; + for(uint i = 0; i < it->length; i++) + m_version = (m_version << 8) | readByte(&readOfs); + return; + +setInvalid: + m_valid = false; +} + +bool SimpleDeserializer::readS32(quint32 id, qint32* result, qint32 def) const +{ + uint readOfs; + qint32 tmp; + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault; + if(it->type != TSigned32) + goto returnDefault; + if(it->length > 4) + goto returnDefault; + + readOfs = it->ofs; + tmp = 0; + for(uint i = 0; i < it->length; i++) { + quint8 byte = readByte(&readOfs); + if((i == 0) && (byte & 0x80)) + tmp = -1; + tmp = (tmp << 8) | byte; + } + *result = tmp; + return true; + +returnDefault: + *result = def; + return false; +} + +bool SimpleDeserializer::readU32(quint32 id, quint32* result, quint32 def) const +{ + uint readOfs; + quint32 tmp; + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault; + if(it->type != TUnsigned32) + goto returnDefault; + if(it->length > 4) + goto returnDefault; + + readOfs = it->ofs; + tmp = 0; + for(uint i = 0; i < it->length; i++) + tmp = (tmp << 8) | readByte(&readOfs); + *result = tmp; + return true; + +returnDefault: + *result = def; + return false; +} + +bool SimpleDeserializer::readS64(quint32 id, qint64* result, qint64 def) const +{ + uint readOfs; + qint64 tmp; + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault; + if(it->type != TSigned64) + goto returnDefault; + if(it->length > 8) + goto returnDefault; + + readOfs = it->ofs; + tmp = 0; + for(uint i = 0; i < it->length; i++) { + quint8 byte = readByte(&readOfs); + if((i == 0) && (byte & 0x80)) + tmp = -1; + tmp = (tmp << 8) | byte; + } + *result = tmp; + return true; + +returnDefault: + *result = def; + return false; +} + +bool SimpleDeserializer::readU64(quint32 id, quint64* result, quint64 def) const +{ + uint readOfs; + quint64 tmp; + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault; + if(it->type != TUnsigned64) + goto returnDefault; + if(it->length > 8) + goto returnDefault; + + readOfs = it->ofs; + tmp = 0; + for(uint i = 0; i < it->length; i++) + tmp = (tmp << 8) | readByte(&readOfs); + *result = tmp; + return true; + +returnDefault: + *result = def; + return false; +} + +bool SimpleDeserializer::readFloat(quint32 id, float* result, float def) const +{ + uint readOfs; + quint32 tmp; + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault; + if(it->type != TFloat) + goto returnDefault; + if(it->length != 4) + goto returnDefault; + + readOfs = it->ofs; + tmp = 0; + for(int i = 0; i < 4; i++) + tmp = (tmp << 8) | readByte(&readOfs); + *result = *((float*)&tmp); + return true; + +returnDefault: + *result = def; + return false; +} + +bool SimpleDeserializer::readDouble(quint32 id, double* result, double def) const +{ + uint readOfs; + quint64 tmp; + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault; + if(it->type != TDouble) + goto returnDefault; + if(it->length != 8) + goto returnDefault; + + readOfs = it->ofs; + tmp = 0; + for(int i = 0; i < 8; i++) + tmp = (tmp << 8) | readByte(&readOfs); + *result = *((double*)&tmp); + return true; + +returnDefault: + *result = def; + return false; +} + +bool SimpleDeserializer::readReal(quint32 id, Real* result, Real def) const +{ + if(sizeof(Real) == 4) { + uint readOfs; + quint32 tmp; + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault32; + if(it->type != TFloat) + goto returnDefault32; + if(it->length != 4) + goto returnDefault32; + + readOfs = it->ofs; + tmp = 0; + for(int i = 0; i < 4; i++) + tmp = (tmp << 8) | readByte(&readOfs); + *result = *((Real*)&tmp); + return true; + + returnDefault32: + *result = def; + return false; + } else { + uint readOfs; + quint64 tmp; + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault64; + if(it->type != TDouble) + goto returnDefault64; + if(it->length != 8) + goto returnDefault64; + + readOfs = it->ofs; + tmp = 0; + for(int i = 0; i < 8; i++) + tmp = (tmp << 8) | readByte(&readOfs); + *result = *((Real*)&tmp); + return true; + + returnDefault64: + *result = def; + return false; + } +} + +bool SimpleDeserializer::readBool(quint32 id, bool* result, bool def) const +{ + uint readOfs; + quint8 tmp; + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault; + if(it->type != TBool) + goto returnDefault; + if(it->length != 1) + goto returnDefault; + + readOfs = it->ofs; + tmp = readByte(&readOfs); + if(tmp == 0x00) + *result = false; + else *result = true; + return true; + +returnDefault: + *result = def; + return false; +} + +bool SimpleDeserializer::readString(quint32 id, QString* result, const QString& def) const +{ + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault; + if(it->type != TString) + goto returnDefault; + + *result = QString::fromUtf8(m_data.data() + it->ofs, it->length); + return true; + +returnDefault: + *result = def; + return false; +} + +bool SimpleDeserializer::readBlob(quint32 id, QByteArray* result, const QByteArray& def) const +{ + Elements::const_iterator it = m_elements.constFind(id); + if(it == m_elements.constEnd()) + goto returnDefault; + if(it->type != TBlob) + goto returnDefault; + + *result = QByteArray(m_data.data() + it->ofs, it->length); + return true; + +returnDefault: + *result = def; + return false; +} + +void SimpleDeserializer::dump() const +{ + if(!m_valid) { + qDebug("SimpleDeserializer dump: data invalid"); + return; + } else { + qDebug("SimpleDeserializer dump: version %u", m_version); + } + + for(Elements::const_iterator it = m_elements.constBegin(); it != m_elements.constEnd(); ++it) { + switch(it->type) { + case TSigned32: { + qint32 tmp; + readS32(it.key(), &tmp); + qDebug("id %d, S32, len %d: " PRINTF_FORMAT_S32, it.key(), it->length, tmp); + break; + } + case TUnsigned32: { + quint32 tmp; + readU32(it.key(), &tmp); + qDebug("id %d, U32, len %d: " PRINTF_FORMAT_U32, it.key(), it->length, tmp); + break; + } + case TSigned64: { + qint64 tmp; + readS64(it.key(), &tmp); + qDebug("id %d, S64, len %d: " PRINTF_FORMAT_S64, it.key(), it->length, (int)tmp); + break; + } + case TUnsigned64: { + quint64 tmp; + readU64(it.key(), &tmp); + qDebug("id %d, U64, len %d: " PRINTF_FORMAT_U64, it.key(), it->length, (uint)tmp); + break; + } + case TFloat: { + float tmp; + readFloat(it.key(), &tmp); + qDebug("id %d, FLOAT, len %d: %f", it.key(), it->length, tmp); + break; + } + case TDouble: { + double tmp; + readDouble(it.key(), &tmp); + qDebug("id %d, DOUBLE, len %d: %f", it.key(), it->length, tmp); + break; + } + case TBool: { + bool tmp; + readBool(it.key(), &tmp); + qDebug("id %d, BOOL, len %d: %s", it.key(), it->length, tmp ? "true" : "false"); + break; + } + case TString: { + QString tmp; + readString(it.key(), &tmp); + qDebug("id %d, STRING, len %d: \"%s\"", it.key(), it->length, qPrintable(tmp)); + break; + } + case TBlob: { + QByteArray tmp; + readBlob(it.key(), &tmp); + qDebug("id %d, BLOB, len %d", it.key(), it->length); + break; + } + case TVersion: { + qDebug("id %d, VERSION, len %d", it.key(), it->length); + break; + } + default: { + qDebug("id %d, UNKNOWN TYPE 0x%02x, len %d", it.key(), it->type, it->length); + break; + } + } + } +} + +bool SimpleDeserializer::parseAll() +{ + uint readOfs = 0; + Type type; + quint32 id; + quint32 length; + + /* + QString hex; + for(int i = 0; i < m_data.size(); i++) + hex.append(QString("%1 ").arg((quint8)m_data[i], 2, 16, QChar('0'))); + qDebug("%s", qPrintable(hex)); + qDebug("=="); + */ + + while(readOfs < (uint)m_data.size()) { + if(!readTag(&readOfs, m_data.size(), &type, &id, &length)) + return false; + + //qDebug("-- id %d, TYPE 0x%02x, len %d", id, type, length); + + if(m_elements.contains(id)) { + qDebug("SimpleDeserializer: same ID found twice (id %u)", id); + return false; + } + + m_elements.insert(id, Element(type, readOfs, length)); + + readOfs += length; + + if(readOfs == m_data.size()) + return true; + } + return false; +} + +bool SimpleDeserializer::readTag(uint* readOfs, uint readEnd, Type* type, quint32* id, quint32* length) const +{ + quint8 tag = readByte(readOfs); + + *type = (Type)(tag >> 4); + int idLen = ((tag >> 2) & 0x03) + 1; + int lengthLen = (tag & 0x03) + 1; + + // make sure we have enough header bytes left + if(((*readOfs) + idLen + lengthLen) > readEnd) + return false; + + quint32 tmp = 0; + for(int i = 0; i < idLen; i++) + tmp = (tmp << 8) | readByte(readOfs); + *id = tmp; + tmp = 0; + for(int i = 0; i < lengthLen; i++) + tmp = (tmp << 8) | readByte(readOfs); + *length = tmp; + + // check if payload fits the buffer + if(((*readOfs) + (*length)) > readEnd) + return false; + else return true; +} + diff --git a/sdrbase/util/spinlock.cpp b/sdrbase/util/spinlock.cpp new file mode 100644 index 000000000..f923ba4d9 --- /dev/null +++ b/sdrbase/util/spinlock.cpp @@ -0,0 +1 @@ +#include "util/spinlock.h"