summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CMakeLists.txt323
-rw-r--r--cmake/Modules/FindPortaudio.cmake20
-rw-r--r--dsp/channelizer.cpp153
-rw-r--r--dsp/channelizer.h49
-rw-r--r--dsp/dspcommands.cpp143
-rw-r--r--dsp/dspcommands.h242
-rw-r--r--dsp/inthalfbandfilter.h149
-rw-r--r--gui/scalecalc.cpp551
-rw-r--r--gui/scalecalc.h95
-rw-r--r--gui/spectrohistogram.cpp268
-rw-r--r--gui/spectrohistogram.h61
-rw-r--r--gui/waterfall.cpp217
-rw-r--r--gui/waterfall.h96
-rw-r--r--hardware/osmosdr/osmosdrgui.cpp214
-rw-r--r--hardware/rtlsdr/rtlsdrgui.cpp105
-rw-r--r--hardware/samplesourcegui.cpp6
-rw-r--r--hardware/samplesourcegui.h19
-rw-r--r--include-gpl/audio/audiodeviceinfo.h (renamed from hardware/soundcardinfo.h)34
-rw-r--r--include-gpl/audio/audiofifo.h (renamed from hardware/audiofifo.h)1
-rw-r--r--include-gpl/audio/audiooutput.h (renamed from hardware/audiooutput.h)31
-rw-r--r--include-gpl/audio/portaudioholder.h13
-rw-r--r--include-gpl/dsp/channelizer.h108
-rw-r--r--include-gpl/dsp/dspcommands.h270
-rw-r--r--include-gpl/dsp/dspengine.h (renamed from dsp/dspengine.h)18
-rw-r--r--include-gpl/dsp/fftengine.h (renamed from dsp/fftengine.h)2
-rw-r--r--include-gpl/dsp/fftwengine.h (renamed from dsp/fftwengine.h)2
-rw-r--r--include-gpl/dsp/fftwindow.h (renamed from dsp/fftwindow.h)2
-rw-r--r--include-gpl/dsp/interpolator.h (renamed from dsp/interpolator.h)2
-rw-r--r--include-gpl/dsp/inthalfbandfilter.h306
-rw-r--r--include-gpl/dsp/kissengine.h (renamed from dsp/kissengine.h)4
-rw-r--r--include-gpl/dsp/lowpass.h (renamed from dsp/lowpass.h)2
-rw-r--r--include-gpl/dsp/nco.h (renamed from dsp/nco.h)2
-rw-r--r--include-gpl/dsp/scopevis.h (renamed from dsp/scopevis.h)5
-rw-r--r--include-gpl/dsp/spectrumvis.h (renamed from dsp/spectrumvis.h)7
-rw-r--r--include-gpl/gui/addpresetdialog.h30
-rw-r--r--include-gpl/gui/glscope.h (renamed from gui/glscope.h)6
-rw-r--r--include-gpl/gui/glspectrum.h (renamed from gui/glspectrum.h)35
-rw-r--r--include-gpl/gui/glspectrumgui.h58
-rw-r--r--include-gpl/gui/indicator.h (renamed from gui/indicator.h)0
-rw-r--r--include-gpl/gui/physicalunit.h (renamed from gui/physicalunit.h)0
-rw-r--r--include-gpl/gui/pluginsdialog.h22
-rw-r--r--include-gpl/gui/preferencesdialog.h34
-rw-r--r--include-gpl/gui/presetitem.h (renamed from gui/presetitem.h)2
-rw-r--r--include-gpl/gui/scale.h (renamed from gui/scale.h)2
-rw-r--r--include-gpl/gui/scaleengine.h (renamed from gui/scaleengine.h)0
-rw-r--r--include-gpl/gui/scopewindow.h (renamed from gui/scopewindow.h)15
-rw-r--r--include-gpl/gui/valuedial.h (renamed from gui/valuedial.h)0
-rw-r--r--include-gpl/mainwindow.h (renamed from mainwindow.h)68
-rw-r--r--include-gpl/plugin/pluginmanager.h127
-rw-r--r--include-gpl/settings/preferences.h32
-rw-r--r--include-gpl/settings/preset.h98
-rw-r--r--include-gpl/settings/settings.h32
-rw-r--r--include/dsp/channelmarker.h39
-rw-r--r--include/dsp/dsptypes.h (renamed from dsp/dsptypes.h)3
-rw-r--r--include/dsp/kissfft.h (renamed from dsp/kissfft.h)0
-rw-r--r--include/dsp/samplefifo.h (renamed from hardware/samplefifo.h)22
-rw-r--r--include/dsp/samplesink.h (renamed from dsp/samplesink.h)3
-rw-r--r--include/dsp/samplesource/samplesource.h (renamed from hardware/samplesource.h)43
-rw-r--r--include/dsp/threadedsamplesink.h40
-rw-r--r--include/plugin/pluginapi.h56
-rw-r--r--include/plugin/plugingui.h29
-rw-r--r--include/plugin/plugininterface.h48
-rw-r--r--include/util/message.h50
-rw-r--r--include/util/messagequeue.h (renamed from util/messagequeue.h)0
-rw-r--r--include/util/miniz.h (renamed from util/miniz.h)2
-rw-r--r--include/util/simpleserializer.h111
-rw-r--r--include/util/spinlock.h (renamed from util/spinlock.h)0
-rw-r--r--main.cpp33
-rw-r--r--mainwindow.cpp556
-rw-r--r--mainwindow.ui774
-rw-r--r--plugins/CMakeLists.txt4
-rw-r--r--plugins/demod/CMakeLists.txt4
-rw-r--r--plugins/demod/nfm/CMakeLists.txt44
-rw-r--r--plugins/demod/nfm/nfmdemod.cpp (renamed from dsp/nfmdemod.cpp)93
-rw-r--r--plugins/demod/nfm/nfmdemod.h102
-rw-r--r--plugins/demod/nfm/nfmdemodgui.cpp179
-rw-r--r--plugins/demod/nfm/nfmdemodgui.h64
-rw-r--r--plugins/demod/nfm/nfmdemodgui.ui211
-rw-r--r--plugins/demod/nfm/nfmplugin.cpp52
-rw-r--r--plugins/demod/nfm/nfmplugin.h28
-rw-r--r--plugins/demod/tetra/CMakeLists.txt44
-rw-r--r--plugins/demod/tetra/tetrademod.cpp106
-rw-r--r--plugins/demod/tetra/tetrademod.h (renamed from dsp/nfmdemod.h)59
-rw-r--r--plugins/demod/tetra/tetrademodgui.cpp110
-rw-r--r--plugins/demod/tetra/tetrademodgui.h56
-rw-r--r--plugins/demod/tetra/tetrademodgui.ui56
-rw-r--r--plugins/demod/tetra/tetraplugin.cpp52
-rw-r--r--plugins/demod/tetra/tetraplugin.h28
-rw-r--r--plugins/samplesource/CMakeLists.txt7
-rw-r--r--plugins/samplesource/osmosdr/CMakeLists.txt47
-rw-r--r--plugins/samplesource/osmosdr/osmosdrgui.cpp305
-rw-r--r--plugins/samplesource/osmosdr/osmosdrgui.h (renamed from hardware/osmosdr/osmosdrgui.h)31
-rw-r--r--plugins/samplesource/osmosdr/osmosdrgui.ui (renamed from hardware/osmosdr/osmosdrgui.ui)0
-rw-r--r--plugins/samplesource/osmosdr/osmosdrinput.cpp (renamed from hardware/osmosdr/osmosdrinput.cpp)253
-rw-r--r--plugins/samplesource/osmosdr/osmosdrinput.h (renamed from hardware/osmosdr/osmosdrinput.h)91
-rw-r--r--plugins/samplesource/osmosdr/osmosdrplugin.cpp67
-rw-r--r--plugins/samplesource/osmosdr/osmosdrplugin.h26
-rw-r--r--plugins/samplesource/osmosdr/osmosdrthread.cpp (renamed from hardware/osmosdr/osmosdrthread.cpp)2
-rw-r--r--plugins/samplesource/osmosdr/osmosdrthread.h (renamed from hardware/osmosdr/osmosdrthread.h)0
-rw-r--r--plugins/samplesource/osmosdr/osmosdrupgrade.cpp (renamed from hardware/osmosdr/osmosdrupgrade.cpp)0
-rw-r--r--plugins/samplesource/osmosdr/osmosdrupgrade.h (renamed from hardware/osmosdr/osmosdrupgrade.h)0
-rw-r--r--plugins/samplesource/osmosdr/osmosdrupgrade.ui (renamed from hardware/osmosdr/osmosdrupgrade.ui)0
-rw-r--r--plugins/samplesource/rtlsdr/CMakeLists.txt47
-rw-r--r--plugins/samplesource/rtlsdr/rtlsdrgui.cpp149
-rw-r--r--plugins/samplesource/rtlsdr/rtlsdrgui.h (renamed from hardware/rtlsdr/rtlsdrgui.h)24
-rw-r--r--plugins/samplesource/rtlsdr/rtlsdrgui.ui (renamed from hardware/rtlsdr/rtlsdrgui.ui)15
-rw-r--r--plugins/samplesource/rtlsdr/rtlsdrinput.cpp (renamed from hardware/rtlsdr/rtlsdrinput.cpp)113
-rw-r--r--plugins/samplesource/rtlsdr/rtlsdrinput.h (renamed from hardware/rtlsdr/rtlsdrinput.h)104
-rw-r--r--plugins/samplesource/rtlsdr/rtlsdrplugin.cpp67
-rw-r--r--plugins/samplesource/rtlsdr/rtlsdrplugin.h26
-rw-r--r--plugins/samplesource/rtlsdr/rtlsdrthread.cpp (renamed from hardware/rtlsdr/rtlsdrthread.cpp)42
-rw-r--r--plugins/samplesource/rtlsdr/rtlsdrthread.h (renamed from hardware/rtlsdr/rtlsdrthread.h)3
-rw-r--r--preset.cpp25
-rw-r--r--preset.h35
-rw-r--r--sdrbase/audio/audiodeviceinfo.cpp (renamed from hardware/soundcardinfo.cpp)171
-rw-r--r--sdrbase/audio/audiofifo.cpp (renamed from hardware/audiofifo.cpp)13
-rw-r--r--sdrbase/audio/audiooutput.cpp (renamed from hardware/audiooutput.cpp)166
-rw-r--r--sdrbase/audio/portaudioholder.cpp26
-rw-r--r--sdrbase/dsp/channelizer.cpp326
-rw-r--r--sdrbase/dsp/channelmarker.cpp40
-rw-r--r--sdrbase/dsp/dspcommands.cpp19
-rw-r--r--sdrbase/dsp/dspengine.cpp (renamed from dsp/dspengine.cpp)231
-rw-r--r--sdrbase/dsp/fftengine.cpp (renamed from dsp/fftengine.cpp)6
-rw-r--r--sdrbase/dsp/fftwengine.cpp (renamed from dsp/fftwengine.cpp)6
-rw-r--r--sdrbase/dsp/fftwindow.cpp (renamed from dsp/fftwindow.cpp)2
-rw-r--r--sdrbase/dsp/interpolator.cpp (renamed from dsp/interpolator.cpp)2
-rw-r--r--sdrbase/dsp/inthalfbandfilter.cpp (renamed from dsp/inthalfbandfilter.cpp)4
-rw-r--r--sdrbase/dsp/kissengine.cpp (renamed from dsp/kissengine.cpp)2
-rw-r--r--sdrbase/dsp/lowpass.cpp (renamed from dsp/lowpass.cpp)2
-rw-r--r--sdrbase/dsp/nco.cpp (renamed from dsp/nco.cpp)2
-rw-r--r--sdrbase/dsp/pidcontroller.cpp (renamed from dsp/pidcontroller.cpp)0
-rw-r--r--sdrbase/dsp/pidcontroller.h (renamed from dsp/pidcontroller.h)2
-rw-r--r--sdrbase/dsp/samplefifo.cpp (renamed from hardware/samplefifo.cpp)63
-rw-r--r--sdrbase/dsp/samplesink.cpp (renamed from dsp/samplesink.cpp)2
-rw-r--r--sdrbase/dsp/samplesource/samplesource.cpp (renamed from hardware/samplesource.cpp)42
-rw-r--r--sdrbase/dsp/scopevis.cpp (renamed from dsp/scopevis.cpp)46
-rw-r--r--sdrbase/dsp/spectrumvis.cpp (renamed from dsp/spectrumvis.cpp)30
-rw-r--r--sdrbase/dsp/threadedsamplesink.cpp109
-rw-r--r--sdrbase/gui/addpresetdialog.cpp26
-rw-r--r--sdrbase/gui/addpresetdialog.ui121
-rw-r--r--sdrbase/gui/glscope.cpp (renamed from gui/glscope.cpp)50
-rw-r--r--sdrbase/gui/glspectrum.cpp (renamed from gui/glspectrum.cpp)231
-rw-r--r--sdrbase/gui/glspectrumgui.cpp165
-rw-r--r--sdrbase/gui/glspectrumgui.ui418
-rw-r--r--sdrbase/gui/indicator.cpp (renamed from gui/indicator.cpp)2
-rw-r--r--sdrbase/gui/pluginsdialog.cpp42
-rw-r--r--sdrbase/gui/pluginsdialog.ui67
-rw-r--r--sdrbase/gui/preferencesdialog.cpp55
-rw-r--r--sdrbase/gui/preferencesdialog.ui109
-rw-r--r--sdrbase/gui/presetitem.cpp (renamed from gui/presetitem.cpp)6
-rw-r--r--sdrbase/gui/scale.cpp (renamed from gui/scale.cpp)2
-rw-r--r--sdrbase/gui/scaleengine.cpp (renamed from gui/scaleengine.cpp)1138
-rw-r--r--sdrbase/gui/scopewindow.cpp (renamed from gui/scopewindow.cpp)80
-rw-r--r--sdrbase/gui/scopewindow.ui (renamed from gui/scopewindow.ui)0
-rw-r--r--sdrbase/gui/valuedial.cpp (renamed from gui/valuedial.cpp)2
-rw-r--r--sdrbase/mainwindow.cpp506
-rw-r--r--sdrbase/mainwindow.ui495
-rw-r--r--sdrbase/plugin/pluginapi.cpp84
-rw-r--r--sdrbase/plugin/plugingui.cpp26
-rw-r--r--sdrbase/plugin/plugininterface.cpp1
-rw-r--r--sdrbase/plugin/pluginmanager.cpp242
-rw-r--r--sdrbase/resources/appicon.ico (renamed from resources/appicon.ico)bin9062 -> 9062 bytes
-rw-r--r--sdrbase/resources/appicon.png (renamed from resources/appicon.png)bin326 -> 326 bytes
-rw-r--r--sdrbase/resources/histogram.png (renamed from resources/histogram.png)bin1364 -> 1364 bytes
-rw-r--r--sdrbase/resources/horizontal.png (renamed from resources/horizontal.png)bin187 -> 187 bytes
-rw-r--r--sdrbase/resources/livespectrum.png (renamed from resources/livespectrum.png)bin1093 -> 1093 bytes
-rw-r--r--sdrbase/resources/preset-delete.png (renamed from resources/preset-delete.png)bin731 -> 731 bytes
-rw-r--r--sdrbase/resources/preset-load.png (renamed from resources/preset-load.png)bin925 -> 925 bytes
-rw-r--r--sdrbase/resources/preset-save.png (renamed from resources/preset-save.png)bin996 -> 996 bytes
-rw-r--r--sdrbase/resources/res.qrc (renamed from resources/res.qrc)0
-rw-r--r--sdrbase/resources/sdrangelove.rc (renamed from resources/sdrangelove.rc)0
-rw-r--r--sdrbase/resources/vertical.png (renamed from resources/vertical.png)bin195 -> 195 bytes
-rw-r--r--sdrbase/resources/waterfall.png (renamed from resources/waterfall.png)bin1362 -> 1362 bytes
-rw-r--r--sdrbase/settings/preferences.cpp46
-rw-r--r--sdrbase/settings/preset.cpp88
-rw-r--r--sdrbase/settings/settings.cpp76
-rw-r--r--sdrbase/util/message.cpp113
-rw-r--r--sdrbase/util/messagequeue.cpp (renamed from util/messagequeue.cpp)11
-rw-r--r--sdrbase/util/miniz.cpp (renamed from util/miniz.cpp)9670
-rw-r--r--sdrbase/util/simpleserializer.cpp704
-rw-r--r--sdrbase/util/spinlock.cpp1
-rw-r--r--settings.cpp101
-rw-r--r--settings.h85
-rw-r--r--util/message.cpp57
-rw-r--r--util/message.h32
-rw-r--r--util/spinlock.cpp1
186 files changed, 14268 insertions, 10558 deletions
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 672e04b..850338f 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -11,163 +11,178 @@ find_package(Qt4 REQUIRED)
find_package(OpenGL REQUIRED)
find_package(PkgConfig)
-find_package(LibOsmoSDR REQUIRED)
-find_package(LibRTLSDR REQUIRED)
find_package(Portaudio REQUIRED)
find_package(LibUSB REQUIRED)
find_package(FFTW3F)
-set(sdrangelove_SOURCES
- main.cpp
- mainwindow.cpp
- preset.cpp
- settings.cpp
-
- dsp/channelizer.cpp
- dsp/dspcommands.cpp
- dsp/dspengine.cpp
- dsp/fftengine.cpp
- dsp/fftwindow.cpp
- dsp/interpolator.cpp
- dsp/inthalfbandfilter.cpp
- dsp/lowpass.cpp
- dsp/nco.cpp
- dsp/nfmdemod.cpp
- dsp/pidcontroller.cpp
- dsp/samplesink.cpp
- dsp/scopevis.cpp
- dsp/spectrumvis.cpp
-
- gui/glscope.cpp
- gui/glspectrum.cpp
- gui/indicator.cpp
- gui/presetitem.cpp
- gui/scale.cpp
- gui/scaleengine.cpp
- gui/scopewindow.cpp
- gui/valuedial.cpp
-
- hardware/audiofifo.cpp
- hardware/audiooutput.cpp
- hardware/samplefifo.cpp
- hardware/samplesource.cpp
- hardware/samplesourcegui.cpp
- hardware/soundcardinfo.cpp
-
- hardware/osmosdr/osmosdrgui.cpp
- hardware/osmosdr/osmosdrinput.cpp
- hardware/osmosdr/osmosdrthread.cpp
- hardware/osmosdr/osmosdrupgrade.cpp
-
- hardware/rtlsdr/rtlsdrgui.cpp
- hardware/rtlsdr/rtlsdrinput.cpp
- hardware/rtlsdr/rtlsdrthread.cpp
-
- util/message.cpp
- util/messagequeue.cpp
- util/miniz.cpp
- util/spinlock.cpp
-)
+##############################################################################
+
+include(${QT_USE_FILE})
+add_definitions(${QT_DEFINITIONS})
-set(sdrangelove_HEADERS
- mainwindow.h
- preset.h
- settings.h
-
- dsp/channelizer.h
- dsp/dspcommands.h
- dsp/dspengine.h
- dsp/dsptypes.h
- dsp/fftengine.h
- dsp/fftwindow.h
- dsp/interpolator.h
- dsp/inthalfbandfilter.h
- dsp/lowpass.h
- dsp/nco.h
- dsp/nfmdemod.h
- dsp/pidcontroller.h
- dsp/samplesink.h
- dsp/scopevis.h
- dsp/spectrumvis.h
-
- gui/glscope.h
- gui/glspectrum.h
- gui/indicator.h
- gui/physicalunit.h
- gui/presetitem.h
- gui/scale.h
- gui/scaleengine.h
- gui/scopewindow.h
- gui/valuedial.h
-
- hardware/audiofifo.h
- hardware/audiooutput.h
- hardware/samplefifo.h
- hardware/samplesource.h
- hardware/samplesourcegui.h
- hardware/soundcardinfo.h
-
- hardware/osmosdr/osmosdrgui.h
- hardware/osmosdr/osmosdrinput.h
- hardware/osmosdr/osmosdrthread.h
- hardware/osmosdr/osmosdrupgrade.h
-
- hardware/rtlsdr/rtlsdrgui.h
- hardware/rtlsdr/rtlsdrinput.h
- hardware/rtlsdr/rtlsdrthread.h
-
- util/message.h
- util/messagequeue.h
- util/miniz.h
- util/spinlock.h
+##############################################################################
+
+set(sdrbase_SOURCES
+ sdrbase/mainwindow.cpp
+
+ sdrbase/audio/audiodeviceinfo.cpp
+ sdrbase/audio/audiofifo.cpp
+ sdrbase/audio/audiooutput.cpp
+ sdrbase/audio/portaudioholder.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/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/addpresetdialog.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/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(sdrangelove_FORMS
- mainwindow.ui
+set(sdrbase_HEADERS
+ include-gpl/mainwindow.h
+
+ include-gpl/audio/audiodeviceinfo.h
+ include-gpl/audio/audiofifo.h
+ include-gpl/audio/audiooutput.h
+ include-gpl/audio/portaudioholder.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/fftwindow.h
+ include-gpl/dsp/interpolator.h
+ include-gpl/dsp/inthalfbandfilter.h
+ include-gpl/dsp/lowpass.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/addpresetdialog.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-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/message.h
+ include/util/messagequeue.h
+ include/util/miniz.h
+ include/util/simpleserializer.h
+ include/util/spinlock.h
+)
- gui/scopewindow.ui
+set(sdrbase_SOURCES
+ ${sdrbase_SOURCES}
+ ${sdrbase_HEADERS}
+)
- hardware/osmosdr/osmosdrgui.ui
- hardware/osmosdr/osmosdrupgrade.ui
+set(sdrbase_FORMS
+ sdrbase/mainwindow.ui
- hardware/rtlsdr/rtlsdrgui.ui
+ sdrbase/gui/addpresetdialog.ui
+ sdrbase/gui/glspectrumgui.ui
+ sdrbase/gui/pluginsdialog.ui
+ sdrbase/gui/preferencesdialog.ui
+ sdrbase/gui/scopewindow.ui
)
-set(sdrangelove_RESOURCES
- resources/res.qrc
+set(sdrbase_RESOURCES
+ sdrbase/resources/res.qrc
)
include_directories(
- .
- portaudio/include
${CMAKE_CURRENT_BINARY_DIR}
+ ${CMAKE_SOURCE_DIR}/include
+ ${CMAKE_SOURCE_DIR}/include-gpl
${OPENGL_INCLUDE_DIR}
- ${LIBOSMOSDR_INCLUDE_DIR}
- ${LIBRTLSDR_INCLUDE_DIR}
${PORTAUDIO_INCLUDE_DIRS}
- ${LIBUSB_INCLUDE_DIR}
)
if(FFTW3F_FOUND)
- set(sdrangelove_SOURCES
- ${sdrangelove_SOURCES}
- dsp/fftwengine.cpp
+ set(sdrbase_SOURCES
+ ${sdrbase_SOURCES}
+ sdrbase/dsp/fftwengine.cpp
)
- set(sdrangelove_HEADERS
- ${sdrangelove_HEADERS}
- dsp/fftwengine.h
+ set(sdrbase_HEADERS
+ ${sdrbase_HEADERS}
+ include-gpl/dsp/fftwengine.h
)
add_definitions(-DUSE_FFTW)
include_directories(${FFTW3F_INCLUDE_DIRS})
else(FFTW3F_FOUND)
- set(sdrangelove_SOURCES
- ${sdrangelove_SOURCES}
- dsp/kissengine.cpp
- dsp/kissfft.h
+ set(sdrbase_SOURCES
+ ${sdrbase_SOURCES}
+ sdrbase/dsp/kissengine.cpp
+ include/dsp/kissfft.h
)
- set(sdrangelove_HEADERS
- ${sdrangelove_HEADERS}
- dsp/kissengine.h
+ set(sdrbase_HEADERS
+ ${sdrbase_HEADERS}
+ include-gpl/dsp/kissengine.h
)
add_definitions(-DUSE_KISSFFT)
endif(FFTW3F_FOUND)
@@ -175,34 +190,52 @@ endif(FFTW3F_FOUND)
include(${QT_USE_FILE})
add_definitions(${QT_DEFINITIONS})
-qt4_wrap_cpp(sdrangelove_HEADERS_MOC ${sdrangelove_HEADERS})
-qt4_wrap_ui(sdrangelove_FORMS_HEADERS ${sdrangelove_FORMS})
-qt4_add_resources(sdrangelove_RESOURCES_RCC ${sdrangelove_RESOURCES})
+qt4_wrap_cpp(sdrbase_HEADERS_MOC ${sdrbase_HEADERS})
+qt4_wrap_ui(sdrbase_FORMS_HEADERS ${sdrbase_FORMS})
+qt4_add_resources(sdrbase_RESOURCES_RCC ${sdrbase_RESOURCES})
if(WIN32)
- SET(sdrangelove_SOURCES ${sdrangelove_SOURCES} resources/sdrangelove.rc)
+ SET(sdrbase_SOURCES ${sdrbase_SOURCES} resources/sdrbase.rc)
endif(WIN32)
-add_executable(sdrangelove
- ${sdrangelove_SOURCES}
- ${sdrangelove_HEADERS_MOC}
- ${sdrangelove_FORMS_HEADERS}
- ${sdrangelove_RESOURCES_RCC}
+add_library(sdrbase SHARED
+ ${sdrbase_SOURCES}
+ ${sdrbase_HEADERS_MOC}
+ ${sdrbase_FORMS_HEADERS}
+ ${sdrbase_RESOURCES_RCC}
)
-target_link_libraries(sdrangelove
+target_link_libraries(sdrbase
${QT_LIBRARIES}
${OPENGL_LIBRARIES}
- ${LIBOSMOSDR_LIBRARIES}
- ${LIBRTLSDR_LIBRARIES}
${PORTAUDIO_LIBRARIES}
${LIBUSB_LIBRARIES}
)
if(FFTW3F_FOUND)
- target_link_libraries(sdrangelove ${FFTW3F_LIBRARIES})
+ target_link_libraries(sdrbase ${FFTW3F_LIBRARIES})
endif(FFTW3F_FOUND)
+##############################################################################
+
+set(sdrangelove_SOURCES
+ main.cpp
+)
+
+if(WIN32)
+ SET(sdrangelove_SOURCES ${sdrangelove_SOURCES} 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")
@@ -211,3 +244,7 @@ if(WIN32)
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)
+
+##############################################################################
+
+add_subdirectory(plugins)
diff --git a/cmake/Modules/FindPortaudio.cmake b/cmake/Modules/FindPortaudio.cmake
index 61e4ae2..3f23a9c 100644
--- a/cmake/Modules/FindPortaudio.cmake
+++ b/cmake/Modules/FindPortaudio.cmake
@@ -6,27 +6,27 @@
# PORTAUDIO_LIBRARIES - Link these to use Portaudio
include(FindPkgConfig)
-pkg_check_modules(PC_PORTAUDIO portaudio)
+pkg_check_modules(PC_PORTAUDIO portaudio-2.0)
find_path(PORTAUDIO_INCLUDE_DIRS
NAMES
- portaudio.h
+ portaudio.h
PATHS
- /usr/local/include
- /usr/include
+ /usr/local/include
+ /usr/include
HINTS
- ${PC_PORTAUDIO_INCLUDE_DIR}
+ ${PC_PORTAUDIO_INCLUDE_DIR}
)
find_library(PORTAUDIO_LIBRARIES
NAMES
- portaudio
+ portaudio
PATHS
- /usr/local/lib
- /usr/lib
- /usr/lib64
+ /usr/local/lib
+ /usr/lib
+ /usr/lib64
HINTS
- ${PC_PORTAUDIO_LIBDIR}
+ ${PC_PORTAUDIO_LIBDIR}
)
mark_as_advanced(PORTAUDIO_INCLUDE_DIRS PORTAUDIO_LIBRARIES)
diff --git a/dsp/channelizer.cpp b/dsp/channelizer.cpp
deleted file mode 100644
index 5a7e07f..0000000
--- a/dsp/channelizer.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-#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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include <QTime>
-#include <stdio.h>
-#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/dsp/channelizer.h b/dsp/channelizer.h
deleted file mode 100644
index 22682cf..0000000
--- a/dsp/channelizer.h
+++ /dev/null
@@ -1,49 +0,0 @@
-#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/dsp/dspcommands.cpp b/dsp/dspcommands.cpp
deleted file mode 100644
index 39c71c0..0000000
--- a/dsp/dspcommands.cpp
+++ /dev/null
@@ -1,143 +0,0 @@
-#include "dspcommands.h"
-
-int DSPCmdPing::type() const
-{
- return Type;
-}
-
-const char* DSPCmdPing::name() const
-{
- return "Ping";
-}
-
-int DSPCmdExit::type() const
-{
- return Type;
-}
-
-const char* DSPCmdExit::name() const
-{
- return "Exit";
-}
-
-int DSPCmdAcquisitionStart::type() const
-{
- return Type;
-}
-
-const char* DSPCmdAcquisitionStart::name() const
-{
- return "AcquisitionStart";
-}
-
-int DSPCmdAcquisitionStop::type() const
-{
- return Type;
-}
-
-const char* DSPCmdAcquisitionStop::name() const
-{
- return "AcquisitionStop";
-}
-
-int DSPCmdGetDeviceDescription::type() const
-{
- return Type;
-}
-
-const char* DSPCmdGetDeviceDescription::name() const
-{
- return "GetDeviceDescription";
-}
-
-void DSPCmdGetDeviceDescription::setDeviceDescription(const QString& text)
-{
- m_deviceDescription = text;
- m_deviceDescription.detach();
-}
-
-int DSPCmdGetErrorMessage::type() const
-{
- return Type;
-}
-
-const char* DSPCmdGetErrorMessage::name() const
-{
- return "GetErrorMessage";
-}
-
-void DSPCmdGetErrorMessage::setErrorMessage(const QString& text)
-{
- m_errorMessage = text;
- m_errorMessage.detach();
-}
-
-int DSPCmdSetSource::type() const
-{
- return Type;
-}
-
-const char* DSPCmdSetSource::name() const
-{
- return "SetSource";
-}
-
-int DSPCmdAddSink::type() const
-{
- return Type;
-}
-
-const char* DSPCmdAddSink::name() const
-{
- return "AddSink";
-}
-
-int DSPCmdRemoveSink::type() const
-{
- return Type;
-}
-
-const char* DSPCmdRemoveSink::name() const
-{
- return "RemoveSink";
-}
-
-int DSPCmdConfigureSpectrumVis::type() const
-{
- return Type;
-}
-
-const char* DSPCmdConfigureSpectrumVis::name() const
-{
- return "ConfigureSpectrumVis";
-}
-
-int DSPCmdConfigureCorrection::type() const
-{
- return Type;
-}
-
-const char* DSPCmdConfigureCorrection::name() const
-{
- return "ConfigureCorrection";
-}
-
-int DSPRepEngineReport::type() const
-{
- return Type;
-}
-
-const char* DSPRepEngineReport::name() const
-{
- return "EngineReport";
-}
-
-int DSPCmdConfigureScopeVis::type() const
-{
- return Type;
-}
-
-const char* DSPCmdConfigureScopeVis::name() const
-{
- return "ConfigureScopeVis";
-}
diff --git a/dsp/dspcommands.h b/dsp/dspcommands.h
deleted file mode 100644
index bc3d13b..0000000
--- a/dsp/dspcommands.h
+++ /dev/null
@@ -1,242 +0,0 @@
-#ifndef INCLUDE_DSPCOMMANDS_H
-#define INCLUDE_DSPCOMMANDS_H
-
-#include <QString>
-#include "../util/message.h"
-#include "fftwindow.h"
-
-class SampleSource;
-class SampleSink;
-
-class DSPCmdPing : public Message {
-public:
- enum {
- Type = 1
- };
-
- DSPCmdPing() { }
- int type() const;
- const char* name() const;
-};
-
-class DSPCmdExit : public Message {
-public:
- enum {
- Type = 2
- };
-
- DSPCmdExit() { }
- int type() const;
- const char* name() const;
-};
-
-class DSPCmdAcquisitionStart : public Message {
-public:
- enum {
- Type = 3
- };
- DSPCmdAcquisitionStart() { }
- int type() const;
- const char* name() const;
-};
-
-class DSPCmdAcquisitionStop : public Message {
-public:
- enum {
- Type = 4
- };
- DSPCmdAcquisitionStop() { }
- int type() const;
- const char* name() const;
-};
-
-class DSPCmdGetDeviceDescription : public Message {
-public:
- enum {
- Type = 5
- };
- DSPCmdGetDeviceDescription() { }
- int type() const;
- const char* name() const;
-
- void setDeviceDescription(const QString& text);
- const QString& getDeviceDescription() const { return m_deviceDescription; }
-
-private:
- QString m_deviceDescription;
-};
-
-class DSPCmdGetErrorMessage : public Message {
-public:
- enum {
- Type = 6
- };
- DSPCmdGetErrorMessage() { }
- int type() const;
- const char* name() const;
-
- void setErrorMessage(const QString& text);
- const QString& getErrorMessage() const { return m_errorMessage; }
-
-private:
- QString m_errorMessage;
-};
-
-class DSPCmdSetSource : public Message {
-public:
- enum {
- Type = 7
- };
- DSPCmdSetSource(SampleSource* source) : m_source(source) { }
- int type() const;
- const char* name() const;
-
- SampleSource* getSource() const { return m_source; }
-
-private:
- SampleSource* m_source;
-};
-
-class DSPCmdAddSink : public Message {
-public:
- enum {
- Type = 8
- };
- DSPCmdAddSink(SampleSink* sink) : m_sink(sink) { }
- int type() const;
- const char* name() const;
-
- SampleSink* getSink() const { return m_sink; }
-
-private:
- SampleSink* m_sink;
-};
-
-class DSPCmdRemoveSink : public Message {
-public:
- enum {
- Type = 9
- };
- DSPCmdRemoveSink(SampleSink* sink) : m_sink(sink) { }
- int type() const;
- const char* name() const;
-
- SampleSink* getSink() const { return m_sink; }
-
-private:
- SampleSink* m_sink;
-};
-
-class DSPCmdConfigureSpectrumVis : public Message {
-public:
- enum {
- Type = 10
- };
- int type() const;
- const char* name() const;
-
- int getFFTSize() const { return m_fftSize; }
- int getOverlapPercent() const { return m_overlapPercent; }
- FFTWindow::Function getWindow() const { return m_window; }
-
- static DSPCmdConfigureSpectrumVis* create(int fftSize, int overlapPercent, FFTWindow::Function window)
- {
- return new DSPCmdConfigureSpectrumVis(fftSize, overlapPercent, window);
- }
-
-private:
- int m_fftSize;
- int m_overlapPercent;
- FFTWindow::Function m_window;
-
- DSPCmdConfigureSpectrumVis(int fftSize, int overlapPercent, FFTWindow::Function window) :
- Message(),
- m_fftSize(fftSize),
- m_overlapPercent(overlapPercent),
- m_window(window)
- { }
-};
-
-class DSPCmdConfigureCorrection : public Message {
-public:
- enum {
- Type = 11
- };
- int type() const;
- const char* name() const;
-
- bool getDCOffsetCorrection() const { return m_dcOffsetCorrection; }
- bool getIQImbalanceCorrection() const { return m_iqImbalanceCorrection; }
-
- static DSPCmdConfigureCorrection* create(bool dcOffsetCorrection, bool iqImbalanceCorrection)
- {
- return new DSPCmdConfigureCorrection(dcOffsetCorrection, iqImbalanceCorrection);
- }
-
-private:
- bool m_dcOffsetCorrection;
- bool m_iqImbalanceCorrection;
-
- DSPCmdConfigureCorrection(bool dcOffsetCorrection, bool iqImbalanceCorrection) :
- m_dcOffsetCorrection(dcOffsetCorrection),
- m_iqImbalanceCorrection(iqImbalanceCorrection)
- { }
-};
-
-class DSPRepEngineReport : public Message {
-public:
- enum {
- Type = 12
- };
- int type() const;
- const char* name() const;
-
- int getSampleRate() const { return m_sampleRate; }
- quint64 getCenterFrequency() const { return m_centerFrequency; }
-
- static DSPRepEngineReport* create(int sampleRate, quint64 centerFrequency) { return new DSPRepEngineReport(sampleRate, centerFrequency); }
-
-private:
- int m_sampleRate;
- quint64 m_centerFrequency;
-
- DSPRepEngineReport(int sampleRate, quint64 centerFrequency) :
- m_sampleRate(sampleRate),
- m_centerFrequency(centerFrequency)
- { }
-};
-
-// Type == 13 -> DSPCmdGUIToSource (defined in samplesource.h)
-// Type == 14 -> DSPCmdSourceToGUI (defined in samplesource.h)
-
-class DSPCmdConfigureScopeVis : public Message {
-public:
- enum {
- Type = 15
- };
- int type() const;
- const char* name() const;
-
- int getTriggerChannel() const { return m_triggerChannel; }
- Real getTriggerLevelHigh() const { return m_triggerLevelHigh; }
- Real getTriggerLevelLow() const { return m_triggerLevelLow; }
-
- static DSPCmdConfigureScopeVis* create(int triggerChannel, Real triggerLevelHigh, Real triggerLevelLow)
- {
- return new DSPCmdConfigureScopeVis(triggerChannel, triggerLevelHigh, triggerLevelLow);
- }
-
-private:
- int m_triggerChannel;
- Real m_triggerLevelHigh;
- Real m_triggerLevelLow;
-
- DSPCmdConfigureScopeVis(int triggerChannel, Real triggerLevelHigh, Real triggerLevelLow) :
- Message(),
- m_triggerChannel(triggerChannel),
- m_triggerLevelHigh(triggerLevelHigh),
- m_triggerLevelLow(triggerLevelLow)
- { }
-};
-
-#endif // INCLUDE_DSPCOMMANDS_H
diff --git a/dsp/inthalfbandfilter.h b/dsp/inthalfbandfilter.h
deleted file mode 100644
index 629a1e3..0000000
--- a/dsp/inthalfbandfilter.h
+++ /dev/null
@@ -1,149 +0,0 @@
-#ifndef INCLUDE_INTHALFBANDFILTER_H
-#define INCLUDE_INTHALFBANDFILTER_H
-
-#include <QtGlobal>
-
-// uses Q1.14 format internally, input and output are S16
-
-/*
- * supported filter orders: 64, 48, 32
- */
-#define FILTERORDER 48
-
-#define SHIFT 14
-
-class IntHalfbandFilter {
-public:
- IntHalfbandFilter();
-
- // process one sample
- bool workDecimate(qint16* i, qint16* q)
- {
- // insert sample into ring-buffer
- m_samples[m_ptr][0] = *i;
- m_samples[m_ptr][1] = *q;
-
- if(m_state == 0) {
- m_state = 1;
-
- // save result
- doFIR(i, q);
-
- // advance write-pointer
- m_ptr = (m_ptr + FILTERORDER);
- if(m_ptr >= (FILTERORDER + 1))
- m_ptr -= (FILTERORDER + 1);
-
- // tell caller we have a new sample
- return true;
- } else {
- m_state = 0;
-
- // advance write-pointer
- m_ptr = (m_ptr + FILTERORDER);
- if(m_ptr >= (FILTERORDER + 1))
- m_ptr -= (FILTERORDER + 1);
-
- return false;
- }
- }
-
-protected:
- qint16 m_samples[FILTERORDER + 1][2];
- int m_ptr;
- int m_state;
-
- void doFIR(qint16* iResult, qint16* qResult)
- {
- // coefficents
-
-#if FILTERORDER == 64
- static const qint32 COEFF[16] = {
- -0.001114417441601693505720538368564120901 * (1 << SHIFT),
- 0.001268007827185253051302527005361753254 * (1 << SHIFT),
- -0.001959831378850490895410230152151598304 * (1 << SHIFT),
- 0.002878308307661380308073439948657323839 * (1 << SHIFT),
- -0.004071361818258721100571850826099762344 * (1 << SHIFT),
- 0.005597288494657440618973431867289036745 * (1 << SHIFT),
- -0.007532345003308904551886371336877346039 * (1 << SHIFT),
- 0.009980346844667375288961963519795972388 * (1 << SHIFT),
- -0.013092614174300500062830820979797863401 * (1 << SHIFT),
- 0.01710934914871829748417297878404497169 * (1 << SHIFT),
- -0.022443558692997273018576720460259821266 * (1 << SHIFT),
- 0.029875811511593811098386197500076377764 * (1 << SHIFT),
- -0.041086352085710403647667021687084343284 * (1 << SHIFT),
- 0.060465467462665789533104998554335907102 * (1 << SHIFT),
- -0.104159517495977321788203084906854201108 * (1 << SHIFT),
- 0.317657589850154464805598308885237202048 * (1 << SHIFT),
- };
-#elif FILTERORDER == 48
- static const qint32 COEFF[12] = {
- -0.004102576237611492253332112767338912818 * (1 << SHIFT),
- 0.003950551047979387886410762575906119309 * (1 << SHIFT),
- -0.005807875789391703583164350277456833282 * (1 << SHIFT),
- 0.00823497890520805998770814682075069868 * (1 << SHIFT),
- -0.011372226513199541059195851744334504474 * (1 << SHIFT),
- 0.015471557140973646315984524335362948477 * (1 << SHIFT),
- -0.020944996398689276484450516591095947661 * (1 << SHIFT),
- 0.028568078132034283034279553703527199104 * (1 << SHIFT),
- -0.040015143905614086738964374490024056286 * (1 << SHIFT),
- 0.059669519431831075095828964549582451582 * (1 << SHIFT),
- -0.103669138691865420076609893840213771909 * (1 << SHIFT),
- 0.317491986549921390015072120149852707982 * (1 << SHIFT)
- };
-#elif FILTERORDER == 32
- static const qint32 COEFF[8] = {
- -0.015956912844043127236437484839370881673 * (1 << SHIFT),
- 0.013023031678944928940522274274371739011 * (1 << SHIFT),
- -0.01866942273717486777684371190844103694 * (1 << SHIFT),
- 0.026550887571157304190005987720724078827 * (1 << SHIFT),
- -0.038350314277854319344740474662103224546 * (1 << SHIFT),
- 0.058429248652825838128421764849917963147 * (1 << SHIFT),
- -0.102889802028955756885153505209018476307 * (1 << SHIFT),
- 0.317237706405931241260276465254719369113 * (1 << SHIFT)
- };
-#else
-#error unsupported filter order
-#endif
-
-
- // init read-pointer
- int a = (m_ptr + 1);
- if(a >= (FILTERORDER + 1))
- a -= (FILTERORDER + 1);
- int b = (m_ptr + (FILTERORDER - 1));
- if(b >= (FILTERORDER + 1))
- b -= (FILTERORDER + 1);
-
- // go through samples in buffer
- qint32 iAcc = 0;
- qint32 qAcc = 0;
- for(int i = 0; i < 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);
- if(a >= (FILTERORDER + 1))
- a -= (FILTERORDER + 1);
- b = b + (FILTERORDER - 1);
- if(b >= (FILTERORDER + 1))
- b -= (FILTERORDER + 1);
- }
-
- a = (a + FILTERORDER);
- if(a >= (FILTERORDER + 1))
- a -= (FILTERORDER + 1);
- iAcc += m_samples[a][0] * (qint32)(0.5 * (1 << SHIFT));
- qAcc += m_samples[a][1] * (qint32)(0.5 * (1 << SHIFT));
-
- // done, save result
- *iResult = iAcc >> SHIFT;
- *qResult = qAcc >> SHIFT;
- }
-};
-
-#endif // INCLUDE_INTHALFBANDFILTER_H
diff --git a/gui/scalecalc.cpp b/gui/scalecalc.cpp
deleted file mode 100644
index b4348b3..0000000
--- a/gui/scalecalc.cpp
+++ /dev/null
@@ -1,551 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include <math.h>
-#include <QFontMetrics>
-#include <QDataStream>
-#include "scalecalc.h"
-
-QString ScaleCalc::formatTick(double value, int decimalPlaces, bool fancyTime)
-{
- if((m_physicalUnit != Unit::Time) || (!fancyTime)) {
- return QString("%1").arg(value, 0, 'f', decimalPlaces);
- } else {
- QString str;
- double orig = fabs(value);
- double tmp;
-
- if(orig >= 86400.0) {
- tmp = trunc(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 = trunc(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 = trunc(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 ScaleCalc::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 ScaleCalc::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:
- m_unitStr = QString("s");
- break;
- }
-}
-
-double ScaleCalc::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 ScaleCalc::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 ScaleCalc::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 ScaleCalc::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.0f));
- } 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 ScaleCalc::majorTickValue(int tick)
-{
- return m_firstMajorTickValue + (tick * m_majorTickValueDistance);
-}
-
-double ScaleCalc::minorTickValue(int tick)
-{
- if(m_numMinorTicks < 1)
- return 0.0;
- return (m_majorTickValueDistance * tick) / m_numMinorTicks;
-}
-
-ScaleCalc::ScaleCalc() :
- m_orientation(Qt::Horizontal),
- m_physicalUnit(Unit::None),
- m_rangeMin(-1.0),
- m_rangeMax(1.0),
- m_recalc(true)
-{
-}
-
-void ScaleCalc::setOrientation(Qt::Orientation orientation)
-{
- m_orientation = orientation;
- m_recalc = true;
-}
-
-void ScaleCalc::setFont(const QFont& font)
-{
- m_font = font;
- m_recalc = true;
- calcCharSize();
-}
-
-void ScaleCalc::setSize(float size)
-{
- if(size > 0.0f) {
- m_size = size;
- } else {
- m_size = 0.0f;
- }
- m_recalc = true;
-}
-
-void ScaleCalc::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;
- }
-
- if((tmpRangeMin != m_rangeMin) || (tmpRangeMax != m_rangeMax) || (m_physicalUnit != physicalUnit)) {
- m_physicalUnit = physicalUnit;
- m_rangeMin = tmpRangeMin;
- m_rangeMax = tmpRangeMax;
- m_recalc = true;
- }
-}
-
-float ScaleCalc::getPosFromValue(double value)
-{
- return ((value - m_rangeMin) / (m_rangeMax - m_rangeMin)) * (m_size - 1.0);
-}
-
-float ScaleCalc::getValueFromPos(double pos)
-{
- return ((pos * (m_rangeMax - m_rangeMin)) / (m_size - 1.0)) + m_rangeMin;
-}
-
-const ScaleCalc::TickList& ScaleCalc::getTickList()
-{
- reCalc();
- return m_tickList;
-}
-
-QString ScaleCalc::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 ScaleCalc::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 ScaleCalc::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/gui/scalecalc.h b/gui/scalecalc.h
deleted file mode 100644
index 56f0591..0000000
--- a/gui/scalecalc.h
+++ /dev/null
@@ -1,95 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#ifndef INCLUDE_SCALECALC_H
-#define INCLUDE_SCALECALC_H
-
-#include <QFont>
-#include <QString>
-#include <QList>
-#include "physicalunit.h"
-
-class ScaleCalc {
-public:
- struct Tick {
- float pos;
- bool major;
- float textPos;
- float textSize;
- QString text;
- };
- typedef QList<Tick> 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:
- ScaleCalc();
-
- void setOrientation(Qt::Orientation orientation);
- void setFont(const QFont& font);
- void setSize(float 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();
-/*
- inline const QFont& getFont() { return m_font; }
- inline const Quantity& getRangeMin() { return m_rangeMin; }
- inline const Quantity& getRangeMax() { return m_rangeMax; }
- inline QString getUnitStr() { return m_unitStr; }
- inline const Unit& getUnit() { return m_rangeMin.getUnit(); }
-*/
-};
-
-#endif // INCLUDE_SCALECALC_H
diff --git a/gui/spectrohistogram.cpp b/gui/spectrohistogram.cpp
deleted file mode 100644
index ee8be2f..0000000
--- a/gui/spectrohistogram.cpp
+++ /dev/null
@@ -1,268 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include <QPainter>
-#include <GL/glu.h>
-#include "spectrohistogram.h"
-
-SpectroHistogram::SpectroHistogram(QWidget* parent) :
- QGLWidget(parent),
- m_fftSize(512),
- m_image(NULL),
- m_histo(NULL),
- m_histoHoldoff(NULL),
- m_textureAllocated(false)
-{
- // no background painting
- setAutoFillBackground(false);
- setAttribute(Qt::WA_OpaquePaintEvent, true);
- setAttribute(Qt::WA_NoSystemBackground, true);
- setMinimumHeight(100);
-
- m_palette[0] = 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_palette[i])[0] = c.red();
- ((quint8*)&m_palette[i])[1] = c.green();
- ((quint8*)&m_palette[i])[2] = c.blue();
- ((quint8*)&m_palette[i])[3] = c.alpha();
- }
- for(int i = 1; i < 16; i++) {
- QColor c;
- c.setHsv(270, 128, 48 + i * 4);
- ((quint8*)&m_palette[i])[0] = c.red();
- ((quint8*)&m_palette[i])[1] = c.green();
- ((quint8*)&m_palette[i])[2] = c.blue();
- ((quint8*)&m_palette[i])[3] = c.alpha();
- }
-
- connect(&m_timer, SIGNAL(timeout()), this, SLOT(refresh()));
- m_timer.start(50);
-
- createImage();
- m_holdOff = 4;
- m_holdOffCount = m_holdOff;
- m_lateHoldOff = 20;
- m_resizeTexture = true;
-}
-
-SpectroHistogram::~SpectroHistogram()
-{
- QMutexLocker mutexLocker(&m_mutex);
-
- if(m_image != NULL) {
- delete m_image;
- m_image = NULL;
- }
- if(m_histo != NULL) {
- delete[] m_histo;
- m_histo = NULL;
- }
- if(m_histoHoldoff != NULL) {
- delete[] m_histoHoldoff;
- m_histoHoldoff = NULL;
- }
- if(m_textureAllocated) {
- glDeleteTextures(1, &m_texture);
- m_textureAllocated = false;
- }
-}
-
-void SpectroHistogram::newSpectrum(const std::vector<Real>& spectrum)
-{
- if(!m_mutex.tryLock())
- return;
-
- if(m_image == NULL) {
- m_mutex.unlock();
- return;
- }
- if(m_image->width() != (int)spectrum.size()) {
- m_fftSize = spectrum.size();
- m_mutex.unlock();
- return;
- }
-
- quint8* b = m_histo;
- quint8* h = m_histoHoldoff;
-
- m_holdOffCount--;
- if(m_holdOffCount <= 0) {
- for(int i = 0; i < 100 * m_fftSize; i++) {
- if(*b > 20) {
- *b = *b - 1;
- } else if(*b > 0) {
- if(*h > 0) {
- *h = *h - 1;
- } else {
- *h = m_lateHoldOff;
- *b = *b - 1;
- }
- }
- b++;
- h++;
- }
- m_holdOffCount = m_holdOff;
- }
-
- b = m_histo;
- h = m_histoHoldoff;
- for(size_t i = 0; i < spectrum.size(); i++) {
- Real vr = spectrum[i] + 96.0;
- int v = (int)vr;
-
- if((v >= 0) && (v <= 99)) {
- if(*(b + v) < 220)
- (*(b + v)) += 4;
- else if(*(b + v) < 239)
- (*(b + v)) += 1;
- //*h = m_lateHoldOff;
- }
-
- b += 100;
- h += 100;
- }
-
- m_mutex.unlock();
-}
-
-void SpectroHistogram::createImage()
-{
- if(m_image != NULL) {
- delete m_image;
- m_image = NULL;
- }
- if(m_histo != NULL) {
- delete[] m_histo;
- m_histo = NULL;
- }
- if(m_histoHoldoff != NULL) {
- delete[] m_histoHoldoff;
- m_histoHoldoff = NULL;
- }
-
- m_image = new QImage(m_fftSize, 100, QImage::Format_RGB32);
- if(m_image != NULL)
- m_image->fill(qRgb(0x00, 0x00, 0x00));
-
- m_histo = new quint8[100 * m_fftSize];
- memset(m_histo, 0x00, 100 * m_fftSize);
- m_histoHoldoff = new quint8[100 * m_fftSize];
- memset(m_histoHoldoff, 0x07, 100 * m_fftSize);
-
- m_resizeTexture = true;
-}
-
-void SpectroHistogram::initializeGL()
-{
- glGenTextures(1, &m_texture);
- m_textureAllocated = true;
-}
-
-void SpectroHistogram::resizeGL(int width, int height)
-{
- glViewport(0, 0, width, height);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- gluOrtho2D(0, width, height, 0);
- glMatrixMode(GL_MODELVIEW);
- glLoadIdentity();
- m_resizeTexture = true;
-}
-
-void SpectroHistogram::paintGL()
-{
- if(!m_mutex.tryLock())
- return;
-
- if(m_image == NULL) {
- m_mutex.unlock();
- return;
- }
-
- quint32* pix;
- quint8* bs = m_histo;
- for(int y = 0; y < 100; y++) {
- quint8* b = bs;
- pix = (quint32*)m_image->scanLine(99 - y);
- for(int x = 0; x < m_fftSize; x++) {
- *pix = m_palette[*b];
- pix++;
- b += 100;
- }
- bs++;
- }
-
- resizeTexture();
- glBindTexture(GL_TEXTURE_2D, m_texture);
- 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);
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, m_fftSize, 100, GL_RGBA, GL_UNSIGNED_BYTE, m_image->scanLine(0));
- m_mutex.unlock();
- glEnable(GL_TEXTURE_2D);
- glPushMatrix();
- glTranslatef(0, 0, 0);
- glScalef(width(), height(), 1.0);
- glBegin(GL_QUADS);
- float prop_y = 0.0;
- float prop_x = 1.0;
- float off = 1.0 / (100 - 1);
- glTexCoord2f(0, prop_y + 1 - off);
- glVertex2f(0, 1);
- glTexCoord2f(prop_x, prop_y + 1 - off);
- glVertex2f(1, 1);
- glTexCoord2f(prop_x, prop_y);
- glVertex2f(1, 0);
- glTexCoord2f(0, prop_y);
- glVertex2f(0, 0);
- glEnd();
- glPopMatrix();
- glDisable(GL_TEXTURE_2D);
-}
-
-void SpectroHistogram::resizeTexture()
-{
- if(!m_resizeTexture)
- return;
- m_resizeTexture = false;
-
- if(!m_textureAllocated) {
- glGenTextures(1, &m_texture);
- m_textureAllocated = true;
- }
-
- quint8* data = new quint8[m_fftSize * 100 * 4];
- memset(data, 0x00, m_fftSize * 100 * 4);
- glBindTexture(GL_TEXTURE_2D, m_texture);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_fftSize, 100, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
- delete[] data;
-}
-
-void SpectroHistogram::refresh()
-{
- QMutexLocker mutexLocker(&m_mutex);
-
- if((m_image == NULL) || (m_fftSize != m_image->width())) {
- createImage();
- resizeGL(width(), height());
- }
-
- update();
-}
diff --git a/gui/spectrohistogram.h b/gui/spectrohistogram.h
deleted file mode 100644
index 897dbd0..0000000
--- a/gui/spectrohistogram.h
+++ /dev/null
@@ -1,61 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#ifndef INCLUDE_SPECTROHISTOGRAM_H
-#define INCLUDE_SPECTROHISTOGRAM_H
-
-#include <QGLWidget>
-#include <QMutex>
-#include <QTimer>
-#include "dsp/dsptypes.h"
-
-class SpectroHistogram : public QGLWidget {
- Q_OBJECT
-
-public:
- SpectroHistogram(QWidget* parent = NULL);
- ~SpectroHistogram();
-
- void newSpectrum(const std::vector<Real>& spectrum);
-
-private:
- QTimer m_timer;
- QMutex m_mutex;
- int m_fftSize;
- QRgb m_palette[240];
- QImage* m_image;
- quint8* m_histo;
- quint8* m_histoHoldoff;
- int m_holdOff;
- int m_lateHoldOff;
- int m_holdOffCount;
- bool m_textureAllocated;
- GLuint m_texture;
- bool m_resizeTexture;
-
- void createImage();
-
- void initializeGL();
- void resizeGL(int width, int height);
- void paintGL();
- void resizeTexture();
-
-private slots:
- void refresh();
-};
-
-#endif // INCLUDE_SPECTROHISTOGRAM_H
diff --git a/gui/waterfall.cpp b/gui/waterfall.cpp
deleted file mode 100644
index f471ac4..0000000
--- a/gui/waterfall.cpp
+++ /dev/null
@@ -1,217 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include <stdio.h>
-#include <QPainter>
-#include <GL/glu.h>
-#include "waterfall.h"
-
-Waterfall::Waterfall(QWidget* parent) :
- QGLWidget(parent),
- m_fftSize(1),
- m_image(NULL),
- m_textureAllocated(false)
-{
- // no background painting
-
- setAutoFillBackground(false);
- setAttribute(Qt::WA_OpaquePaintEvent, true);
- setAttribute(Qt::WA_NoSystemBackground, true);
- setMinimumHeight(128);
-/*
- m_palette[0] = 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));
- m_palette[i] = c.rgb();
- }
-*/
- for(int i = 0; i <= 239; i++) {
- QColor c;
- c.setHsv(239 - i, 255, 15 + i);
- ((quint8*)&m_palette[i])[0] = c.red();
- ((quint8*)&m_palette[i])[1] = c.green();
- ((quint8*)&m_palette[i])[2] = c.blue();
- ((quint8*)&m_palette[i])[3] = c.alpha();
- }
-
- createImage();
-
- connect(&m_timer, SIGNAL(timeout()), this, SLOT(refresh()));
- m_timer.start(50);
-}
-
-Waterfall::~Waterfall()
-{
- QMutexLocker mutexLocker(&m_mutex);
- if(m_image != NULL) {
- delete m_image;
- m_image = NULL;
- }
- if(m_textureAllocated) {
- glDeleteTextures(1, &m_texture);
- m_textureAllocated = false;
- }
-}
-
-void Waterfall::newSpectrum(const std::vector<Real>& spectrum)
-{
- if(!m_mutex.tryLock())
- return;
-
- if(m_image == NULL) {
- m_mutex.unlock();
- return;
- }
- if(m_image->height() == 0) {
- m_mutex.unlock();
- return;
- }
- if(m_pos >= m_image->height()) {
- m_mutex.unlock();
- return;
- }
-
- m_fftSize = spectrum.size();
-
- int w = spectrum.size();
- if(w > m_image->width())
- w = m_image->width();
-
- quint32* pix = (quint32*)m_image->scanLine(m_pos);
-
- for(int i = 0; i < w; i++) {
- Real vr = 2.4 * (spectrum[i] + 96.0);
- int v = (int)vr;
-
- if(v > 239)
- v = 239;
- else if(v < 0)
- v = 0;
-
- *pix++ = m_palette[(int)v];
- }
-
- m_pos++;
-
- m_mutex.unlock();
-}
-
-void Waterfall::createImage()
-{
- if(m_image != NULL) {
- if(m_image->width() == m_fftSize)
- return;
- delete m_image;
- m_image = NULL;
- }
-
- m_image = new QImage(m_fftSize, 1024, QImage::Format_ARGB32);
- if(m_image != NULL) {
- m_image->fill(qRgb(0x00, 0x00, 0x00));
- m_pos = 0;
- }
- m_resizeTexture = true;
-}
-
-void Waterfall::initializeGL()
-{
- glGenTextures(1, &m_texture);
- m_textureAllocated = true;
-}
-
-void Waterfall::resizeGL(int width, int height)
-{
- glViewport(0, 0, width, height);
- glMatrixMode(GL_PROJECTION);
- glLoadIdentity();
- gluOrtho2D(0, width, height, 0); // set origin to bottom left corner
- glMatrixMode(GL_MODELVIEW);
- glLoadIdentity();
- m_resizeTexture = true;
-}
-
-void Waterfall::paintGL()
-{
- QMutexLocker mutexLocker(&m_mutex);
- if(m_image == NULL)
- return;
-
- resizeTexture();
- glBindTexture(GL_TEXTURE_2D, m_texture);
- 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_pos; i++) {
- glTexSubImage2D(GL_TEXTURE_2D, 0, 0, m_texPos, m_fftSize, 1, GL_RGBA, GL_UNSIGNED_BYTE, m_image->scanLine(i));
- m_texPos = (m_texPos + 1) % m_textureHeight;
- }
- m_pos = 0;
-
- glEnable(GL_TEXTURE_2D);
- glPushMatrix();
- glTranslatef(0, 0, 0);
- glScalef(width(), height(), 1.0);
- glBegin(GL_QUADS);
- float prop_y = m_texPos / (m_textureHeight - 1.0);
- float prop_x = 1.0;
- float off = 1.0 / (m_textureHeight - 1);
- glTexCoord2f(0, prop_y + 1 - off);
- glVertex2f(0, 1);
- glTexCoord2f(prop_x, prop_y + 1 - off);
- glVertex2f(1, 1);
- glTexCoord2f(prop_x, prop_y);
- glVertex2f(1, 0);
- glTexCoord2f(0, prop_y);
- glVertex2f(0, 0);
- glEnd();
- glPopMatrix();
- glDisable(GL_TEXTURE_2D);
-}
-
-void Waterfall::resizeTexture()
-{
- if(!m_resizeTexture)
- return;
- m_resizeTexture = false;
-
- if(!m_textureAllocated) {
- glGenTextures(1, &m_texture);
- m_textureAllocated = true;
- }
-
- m_textureHeight = height();
- quint8* data = new quint8[m_fftSize * m_textureHeight * 4];
- memset(data, 0x00, m_fftSize * m_textureHeight * 4);
- glBindTexture(GL_TEXTURE_2D, m_texture);
- glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_fftSize, m_textureHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
- delete[] data;
- m_texPos = 0;
-}
-
-void Waterfall::refresh()
-{
- QMutexLocker mutexLocker(&m_mutex);
-
- if((m_image == NULL) || (m_fftSize != m_image->width())) {
- createImage();
- resizeGL(width(), height());
- }
- update();
-}
diff --git a/gui/waterfall.h b/gui/waterfall.h
deleted file mode 100644
index eaab036..0000000
--- a/gui/waterfall.h
+++ /dev/null
@@ -1,96 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#ifndef INCLUDE_WATERFALL_H
-#define INCLUDE_WATERFALL_H
-
-#if 0
-#include <QWidget>
-#include <QMutex>
-#include <QTimer>
-#include "dsp/dsptypes.h"
-
-class Waterfall : public QWidget {
- Q_OBJECT
-
-public:
- Waterfall(QWidget* parent = NULL);
- ~Waterfall();
-
- void newSpectrum(const std::vector<Real>& spectrum);
-
-private:
- QTimer m_timer;
- QMutex m_mutex;
- int m_fftSize;
- QImage* m_image;
- QRgb m_palette[240];
- int m_pos;
-
- void createImage();
-
- void paintEvent(QPaintEvent*);
- void resizeEvent(QResizeEvent*);
-
-private slots:
- void refresh();
-};
-#endif
-
-#include <QGLWidget>
-#include <QMutex>
-#include <QTimer>
-#include "dsp/dsptypes.h"
-
-class Waterfall : public QGLWidget {
- Q_OBJECT
-
-public:
- Waterfall(QWidget* parent = NULL);
- ~Waterfall();
-
- void newSpectrum(const std::vector<Real>& spectrum);
-
-private:
- QTimer m_timer;
- QMutex m_mutex;
- int m_fftSize;
- QImage* m_image;
- QRgb m_palette[240];
- int m_pos;
-
- bool m_textureAllocated;
- GLuint m_texture;
- int m_textureHeight;
- bool m_resizeTexture;
- int m_texPos;
-
- void createImage();
-
-// void paintEvent(QPaintEvent*);
-// void resizeEvent(QResizeEvent*);
-
- void initializeGL();
- void resizeGL(int width, int height);
- void paintGL();
- void resizeTexture();
-
-private slots:
- void refresh();
-};
-
-#endif // INCLUDE_WATERFALL_H
diff --git a/hardware/osmosdr/osmosdrgui.cpp b/hardware/osmosdr/osmosdrgui.cpp
deleted file mode 100644
index 957af81..0000000
--- a/hardware/osmosdr/osmosdrgui.cpp
+++ /dev/null
@@ -1,214 +0,0 @@
-#include "osmosdrgui.h"
-#include "ui_osmosdrgui.h"
-
-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;
- }
-}
-
-void OsmoSDRGui::handleSourceMessage(DSPCmdSourceToGUI* cmd)
-{
-}
-
-void OsmoSDRGui::displaySettings()
-{
- ui->centerFrequency->setValue(m_settings.centerFrequency / 1000);
- ui->iqSwap->setChecked(m_settings.swapIQ);
- ui->decimation->setValue(m_settings.decimation);
- ui->e4000LNAGain->setValue(e4kLNAGainToIdx(m_settings.lnaGain));
-
- ui->e4000MixerGain->setCurrentIndex((m_settings.mixerGain - 40) / 80);
- if(m_settings.mixerEnhancement == 0)
- ui->e4000MixerEnh->setCurrentIndex(0);
- else ui->e4000MixerEnh->setCurrentIndex((m_settings.mixerEnhancement + 10) / 20);
-
- ui->e4000if1->setCurrentIndex((m_settings.if1gain + 30) / 90);
- ui->e4000if2->setCurrentIndex(m_settings.if2gain / 30);
- ui->e4000if3->setCurrentIndex(m_settings.if3gain / 30);
- ui->e4000if4->setCurrentIndex(m_settings.if4gain / 10);
- ui->e4000if5->setCurrentIndex(m_settings.if5gain / 30 - 1);
- ui->e4000if6->setCurrentIndex(m_settings.if6gain / 30 - 1);
- ui->filterI1->setValue(m_settings.opAmpI1);
- ui->filterI2->setValue(m_settings.opAmpI2);
- ui->filterQ1->setValue(m_settings.opAmpQ1);
- ui->filterQ2->setValue(m_settings.opAmpQ2);
-
- ui->e4kI->setValue(m_settings.dcOfsI);
- ui->e4kQ->setValue(m_settings.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.swapIQ = checked;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4000MixerGain_currentIndexChanged(int index)
-{
- m_settings.mixerGain = index * 80 + 40;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4000MixerEnh_currentIndexChanged(int index)
-{
- if(index == 0)
- m_settings.mixerEnhancement = 0;
- else m_settings.mixerEnhancement = index * 20 - 10;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4000if1_currentIndexChanged(int index)
-{
- m_settings.if1gain = index * 90 - 30;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4000if2_currentIndexChanged(int index)
-{
- m_settings.if2gain = index * 30;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4000if3_currentIndexChanged(int index)
-{
- m_settings.if3gain = index * 30;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4000if4_currentIndexChanged(int index)
-{
- m_settings.if4gain = index * 10;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4000if5_currentIndexChanged(int index)
-{
- m_settings.if5gain = (index + 1) * 30;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4000if6_currentIndexChanged(int index)
-{
- m_settings.if6gain = (index + 1) * 30;
- sendSettings();
-}
-
-void OsmoSDRGui::on_centerFrequency_changed(quint64 value)
-{
- m_settings.centerFrequency = value * 1000;
- sendSettings();
-}
-
-void OsmoSDRGui::on_filterI1_valueChanged(int value)
-{
- m_settings.opAmpI1 = value;
- sendSettings();
-}
-
-void OsmoSDRGui::on_filterI2_valueChanged(int value)
-{
- m_settings.opAmpI2 = value;
- sendSettings();
-}
-
-void OsmoSDRGui::on_filterQ1_valueChanged(int value)
-{
- m_settings.opAmpQ1 = value;
- sendSettings();
-}
-
-void OsmoSDRGui::on_filterQ2_valueChanged(int value)
-{
- m_settings.opAmpQ2 = value;
- sendSettings();
-}
-
-void OsmoSDRGui::on_decimation_valueChanged(int value)
-{
- ui->decimationDisplay->setText(tr("1:%1").arg(1 << value));
- m_settings.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.lnaGain = gain;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4kI_valueChanged(int value)
-{
- m_settings.dcOfsI = value;
- sendSettings();
-}
-
-void OsmoSDRGui::on_e4kQ_valueChanged(int value)
-{
- m_settings.dcOfsQ = value;
- sendSettings();
-}
-
-void OsmoSDRGui::updateHardware()
-{
- DSPCmdConfigureSourceOsmoSDR* cmd = DSPCmdConfigureSourceOsmoSDR::create(m_settings);
- cmd->submit(m_msgQueue);
- m_updateTimer.stop();
-}
diff --git a/hardware/rtlsdr/rtlsdrgui.cpp b/hardware/rtlsdr/rtlsdrgui.cpp
deleted file mode 100644
index 67fb320..0000000
--- a/hardware/rtlsdr/rtlsdrgui.cpp
+++ /dev/null
@@ -1,105 +0,0 @@
-#include "rtlsdrgui.h"
-#include "ui_rtlsdrgui.h"
-
-RTLSDRGui::RTLSDRGui(MessageQueue* msgQueue, QWidget* parent) :
- SampleSourceGUI(parent),
- ui(new Ui::RTLSDRGui),
- m_msgQueue(msgQueue),
- m_settings()
-{
- ui->setupUi(this);
- ui->centerFrequency->setValueRange(7, 20000U, 2200000U);
- connect(&m_updateTimer, SIGNAL(timeout()), this, SLOT(updateHardware()));
- displaySettings();
-}
-
-RTLSDRGui::~RTLSDRGui()
-{
- delete ui;
-}
-
-QString RTLSDRGui::serializeSettings() const
-{
- return m_settings.serialize();
-}
-
-bool RTLSDRGui::deserializeSettings(const QString& settings)
-{
- if(m_settings.deserialize(settings)) {
- displaySettings();
- sendSettings();
- return true;
- } else {
- return false;
- }
-}
-
-void RTLSDRGui::handleSourceMessage(DSPCmdSourceToGUI* cmd)
-{
- if(cmd->sourceType() != DSPCmdGUIInfoRTLSDR::SourceType)
- return;
-
- m_gains = ((DSPCmdGUIInfoRTLSDR*)cmd)->getGains();
- displaySettings();
-}
-
-void RTLSDRGui::displaySettings()
-{
- ui->centerFrequency->setValue(m_settings.centerFrequency / 1000);
- ui->decimation->setValue(m_settings.decimation);
-
- if(m_gains.size() > 0) {
- int dist = abs(m_settings.gain - m_gains[0]);
- int pos = 0;
- for(uint i = 1; i < m_gains.size(); i++) {
- if(abs(m_settings.gain - m_gains[i]) < dist) {
- dist = abs(m_settings.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_settings.centerFrequency = value * 1000;
- sendSettings();
-}
-
-void RTLSDRGui::on_gain_valueChanged(int value)
-{
- if(value > m_gains.size())
- return;
- int gain = m_gains[value];
- ui->gainText->setText(tr("%1.%2").arg(gain / 10).arg(abs(gain % 10)));
- m_settings.gain = gain;
- sendSettings();
-}
-
-void RTLSDRGui::on_decimation_valueChanged(int value)
-{
- ui->decimationText->setText(tr("1:%1").arg(1 << value));
- m_settings.decimation = value;
- sendSettings();
-}
-
-void RTLSDRGui::updateHardware()
-{
- DSPCmdConfigureSourceRTLSDR* cmd = DSPCmdConfigureSourceRTLSDR::create(m_settings);
- cmd->submit(m_msgQueue);
- m_updateTimer.stop();
-}
diff --git a/hardware/samplesourcegui.cpp b/hardware/samplesourcegui.cpp
deleted file mode 100644
index 6b10fcc..0000000
--- a/hardware/samplesourcegui.cpp
+++ /dev/null
@@ -1,6 +0,0 @@
-#include "samplesourcegui.h"
-
-SampleSourceGUI::SampleSourceGUI(QWidget* parent) :
- QWidget(parent)
-{
-}
diff --git a/hardware/samplesourcegui.h b/hardware/samplesourcegui.h
deleted file mode 100644
index 6251fe8..0000000
--- a/hardware/samplesourcegui.h
+++ /dev/null
@@ -1,19 +0,0 @@
-#ifndef INCLUDE_SAMPLESOURCEGUI_H
-#define INCLUDE_SAMPLESOURCEGUI_H
-
-#include <QWidget>
-#include "samplesource.h"
-
-class SampleSourceGUI : public QWidget {
- Q_OBJECT
-
-public:
- SampleSourceGUI(QWidget* parent = NULL);
-
- virtual QString serializeSettings() const = 0;
- virtual bool deserializeSettings(const QString& settings) = 0;
-
- virtual void handleSourceMessage(DSPCmdSourceToGUI* cmd) = 0;
-};
-
-#endif // INCLUDE_SAMPLESOURCEGUI_H
diff --git a/hardware/soundcardinfo.h b/include-gpl/audio/audiodeviceinfo.h
index b8b9b91..7b88870 100644
--- a/hardware/soundcardinfo.h
+++ b/include-gpl/audio/audiodeviceinfo.h
@@ -15,22 +15,34 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
-#ifndef INCLUDE_SOUNDCARDINFO_H
-#define INCLUDE_SOUNDCARDINFO_H
+#ifndef INCLUDE_AUDIODEVICEINFO_H
+#define INCLUDE_AUDIODEVICEINFO_H
#include <QStringList>
-class SoundcardInfo {
-private:
- QStringList m_devices;
-
+class AudioDeviceInfo {
public:
- SoundcardInfo();
+ 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<Device> Devices;
- inline const QStringList& getDevices() { return m_devices; }
+ AudioDeviceInfo();
- inline const QString& getDevice(int idx) { return m_devices.at(idx); }
- inline int getDeviceCount() { return m_devices.count(); }
+ int match(const QString& api, const QString device) const;
+
+ const Devices& getDevices() const { return m_devices; }
+
+private:
+ Devices m_devices;
};
-#endif // INCLUDE_SOUNDCARDINFO_H
+#endif // INCLUDE_AUDIODEVICEINFO_H
diff --git a/hardware/audiofifo.h b/include-gpl/audio/audiofifo.h
index 826a92a..8a06e99 100644
--- a/hardware/audiofifo.h
+++ b/include-gpl/audio/audiofifo.h
@@ -33,6 +33,7 @@ public:
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; }
diff --git a/hardware/audiooutput.h b/include-gpl/audio/audiooutput.h
index 98fb319..347c246 100644
--- a/hardware/audiooutput.h
+++ b/include-gpl/audio/audiooutput.h
@@ -19,17 +19,35 @@
#define INCLUDE_AUDIOOUTPUT_H
#include <QMutex>
+#include <list>
+#include <vector>
#include "portaudio.h"
class AudioFifo;
class AudioOutput {
+public:
+ AudioOutput();
+ ~AudioOutput();
+
+ bool start(int device, int rate);
+ void stop();
+
+ void addFifo(AudioFifo* audioFifo);
+ void removeFifo(AudioFifo* audioFifo);
+
+ //int bufferedSamples();
+
private:
+ QMutex m_mutex;
PaStream* m_stream;
- AudioFifo* m_audioFifo;
+ //AudioFifo* m_audioFifo;
+ typedef std::list<AudioFifo*> AudioFifos;
+ AudioFifos m_audioFifos;
+ std::vector<qint32> m_mixBuffer;
int m_sampleRate;
- PaTime m_streamStartTime;
+ //PaTime m_streamStartTime;
static int callbackHelper(
const void* inputBuffer,
@@ -45,15 +63,6 @@ private:
unsigned long framesPerBuffer,
const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags);
-
-public:
- AudioOutput();
- ~AudioOutput();
-
- bool start(int device, int rate, AudioFifo* audioFifo);
- void stop();
-
- int bufferedSamples();
};
#endif // INCLUDE_AUDIOOUTPUT_H
diff --git a/include-gpl/audio/portaudioholder.h b/include-gpl/audio/portaudioholder.h
new file mode 100644
index 0000000..9f6bd50
--- /dev/null
+++ b/include-gpl/audio/portaudioholder.h
@@ -0,0 +1,13 @@
+#ifndef INCLUDE_PORTAUDIOHOLDER_H
+#define INCLUDE_PORTAUDIOHOLDER_H
+
+class PortAudioHolder {
+public:
+ PortAudioHolder();
+ ~PortAudioHolder();
+
+private:
+ bool m_initialized;
+};
+
+#endif // INCLUDE_PORTAUDIOHOLDER_H
diff --git a/include-gpl/dsp/channelizer.h b/include-gpl/dsp/channelizer.h
new file mode 100644
index 0000000..223625e
--- /dev/null
+++ b/include-gpl/dsp/channelizer.h
@@ -0,0 +1,108 @@
+#ifndef INCLUDE_CHANNELIZER_H
+#define INCLUDE_CHANNELIZER_H
+
+#include <list>
+#include "dsp/samplesink.h"
+
+class MessageQueue;
+class IntHalfbandFilter;
+
+class 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<FilterStage*> 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 0000000..7377324
--- /dev/null
+++ b/include-gpl/dsp/dspcommands.h
@@ -0,0 +1,270 @@
+#ifndef INCLUDE_DSPCOMMANDS_H
+#define INCLUDE_DSPCOMMANDS_H
+
+#include <QString>
+#include "util/message.h"
+#include "fftwindow.h"
+
+class SampleSource;
+class SampleSink;
+class AudioFifo;
+
+class DSPPing : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPPing() : Message(ID()) { }
+};
+
+class DSPExit : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPExit() : Message(ID()) { }
+};
+
+class DSPAcquisitionStart : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPAcquisitionStart() : Message(ID()) { }
+};
+
+class DSPAcquisitionStop : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPAcquisitionStop() : Message(ID()) { }
+};
+
+class DSPGetDeviceDescription : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPGetDeviceDescription() : Message(ID()) { }
+
+ void setDeviceDescription(const QString& text) { m_deviceDescription = text; }
+ const QString& getDeviceDescription() const { return m_deviceDescription; }
+
+private:
+ QString m_deviceDescription;
+};
+
+class DSPGetErrorMessage : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPGetErrorMessage() : Message(ID()) { }
+
+ void setErrorMessage(const QString& text) { m_errorMessage = text; }
+ const QString& getErrorMessage() const { return m_errorMessage; }
+
+private:
+ QString m_errorMessage;
+};
+
+class DSPSetSource : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPSetSource(SampleSource* sampleSource) : Message(ID()), m_sampleSource(sampleSource) { }
+
+ SampleSource* getSampleSource() const { return m_sampleSource; }
+
+private:
+ SampleSource* m_sampleSource;
+};
+
+class DSPAddSink : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPAddSink(SampleSink* sampleSink) : Message(ID()), m_sampleSink(sampleSink) { }
+
+ SampleSink* getSampleSink() const { return m_sampleSink; }
+
+private:
+ SampleSink* m_sampleSink;
+};
+
+class DSPRemoveSink : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPRemoveSink(SampleSink* sampleSink) : Message(ID()), m_sampleSink(sampleSink) { }
+
+ SampleSink* getSampleSink() const { return m_sampleSink; }
+
+private:
+ SampleSink* m_sampleSink;
+};
+
+class DSPAddAudioSource : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPAddAudioSource(AudioFifo* audioFifo) : Message(ID()), m_audioFifo(audioFifo) { }
+
+ AudioFifo* getAudioFifo() const { return m_audioFifo; }
+
+private:
+ AudioFifo* m_audioFifo;
+};
+
+class DSPRemoveAudioSource : public Message {
+public:
+ static MessageRegistrator ID;
+
+ DSPRemoveAudioSource(AudioFifo* audioFifo) : Message(ID()), m_audioFifo(audioFifo) { }
+
+ AudioFifo* getAudioFifo() const { return m_audioFifo; }
+
+private:
+ AudioFifo* m_audioFifo;
+};
+
+class DSPConfigureSpectrumVis : public Message {
+public:
+ static MessageRegistrator ID;
+
+ 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(ID()),
+ m_fftSize(fftSize),
+ m_overlapPercent(overlapPercent),
+ m_window(window)
+ { }
+};
+
+class DSPConfigureCorrection : public Message {
+public:
+ static MessageRegistrator ID;
+
+ 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(ID()),
+ m_dcOffsetCorrection(dcOffsetCorrection),
+ m_iqImbalanceCorrection(iqImbalanceCorrection)
+ { }
+};
+
+class DSPEngineReport : public Message {
+public:
+ static MessageRegistrator ID;
+
+ 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(ID()),
+ m_sampleRate(sampleRate),
+ m_centerFrequency(centerFrequency)
+ { }
+};
+
+class DSPConfigureScopeVis : public Message {
+public:
+ static MessageRegistrator ID;
+
+ 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(ID()),
+ m_triggerChannel(triggerChannel),
+ m_triggerLevelHigh(triggerLevelHigh),
+ m_triggerLevelLow(triggerLevelLow)
+ { }
+};
+
+class DSPSignalNotification : public Message {
+public:
+ static MessageRegistrator ID;
+
+ 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(ID()),
+ m_sampleRate(samplerate),
+ m_frequencyOffset(frequencyOffset)
+ { }
+};
+
+class DSPConfigureChannelizer : public Message {
+public:
+ static MessageRegistrator ID;
+
+ 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(ID()),
+ m_sampleRate(sampleRate),
+ m_centerFrequency(centerFrequency)
+ { }
+};
+
+#endif // INCLUDE_DSPCOMMANDS_H
diff --git a/dsp/dspengine.h b/include-gpl/dsp/dspengine.h
index 6725064..1c3fd42 100644
--- a/dsp/dspengine.h
+++ b/include-gpl/dsp/dspengine.h
@@ -22,15 +22,15 @@
#include <QTimer>
#include <QMutex>
#include <QWaitCondition>
-#include "dsptypes.h"
-#include "kissfft.h"
-#include "fftwindow.h"
-#include "settings.h"
-#include "hardware/samplefifo.h"
-#include "../util/messagequeue.h"
+#include "dsp/dsptypes.h"
+#include "dsp/fftwindow.h"
+#include "dsp/samplefifo.h"
+#include "audio/audiooutput.h"
+#include "util/messagequeue.h"
class SampleSource;
class SampleSink;
+class AudioFifo;
class DSPEngine : public QThread {
Q_OBJECT
@@ -59,6 +59,9 @@ public:
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; }
@@ -80,6 +83,8 @@ private:
typedef std::list<SampleSink*> SampleSinks;
SampleSinks m_sampleSinks;
+ AudioOutput m_audioOutput;
+
int m_sampleRate;
quint64 m_centerFrequency;
@@ -103,6 +108,7 @@ private:
void handleSetSource(SampleSource* source);
void generateReport();
+ bool distributeMessage(Message* message);
private slots:
void handleData();
diff --git a/dsp/fftengine.h b/include-gpl/dsp/fftengine.h
index 2b30fed..1139059 100644
--- a/dsp/fftengine.h
+++ b/include-gpl/dsp/fftengine.h
@@ -1,7 +1,7 @@
#ifndef INCLUDE_FFTENGINE_H
#define INCLUDE_FFTENGINE_H
-#include "dsptypes.h"
+#include "dsp/dsptypes.h"
class FFTEngine {
public:
diff --git a/dsp/fftwengine.h b/include-gpl/dsp/fftwengine.h
index bb4b4e9..2da5317 100644
--- a/dsp/fftwengine.h
+++ b/include-gpl/dsp/fftwengine.h
@@ -3,7 +3,7 @@
#include <fftw3.h>
#include <list>
-#include "fftengine.h"
+#include "dsp/fftengine.h"
class FFTWEngine : public FFTEngine {
public:
diff --git a/dsp/fftwindow.h b/include-gpl/dsp/fftwindow.h
index d1d7221..179a0b7 100644
--- a/dsp/fftwindow.h
+++ b/include-gpl/dsp/fftwindow.h
@@ -21,7 +21,7 @@
#include <vector>
#define _USE_MATH_DEFINES
#include <math.h>
-#include "dsptypes.h"
+#include "dsp/dsptypes.h"
class FFTWindow {
public:
diff --git a/dsp/interpolator.h b/include-gpl/dsp/interpolator.h
index c32aa33..22541cb 100644
--- a/dsp/interpolator.h
+++ b/include-gpl/dsp/interpolator.h
@@ -1,7 +1,7 @@
#ifndef INCLUDE_INTERPOLATOR_H
#define INCLUDE_INTERPOLATOR_H
-#include "dsptypes.h"
+#include "dsp/dsptypes.h"
class Interpolator {
public:
diff --git a/include-gpl/dsp/inthalfbandfilter.h b/include-gpl/dsp/inthalfbandfilter.h
new file mode 100644
index 0000000..ae49793
--- /dev/null
+++ b/include-gpl/dsp/inthalfbandfilter.h
@@ -0,0 +1,306 @@
+#ifndef INCLUDE_INTHALFBANDFILTER_H
+#define INCLUDE_INTHALFBANDFILTER_H
+
+#include <QtGlobal>
+#include "dsp/dsptypes.h"
+
+// uses Q1.14 format internally, input and output are S16
+
+/*
+ * supported filter orders: 64, 48, 32
+ */
+#define HB_FILTERORDER 48
+#define HB_SHIFT 14
+
+class 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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(m_ptr >= (HB_FILTERORDER + 1))
+ m_ptr -= (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);
+ if(a >= (HB_FILTERORDER + 1))
+ a -= (HB_FILTERORDER + 1);
+ int b = (m_ptr + (HB_FILTERORDER - 1));
+ if(b >= (HB_FILTERORDER + 1))
+ b -= (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);
+ if(a >= (HB_FILTERORDER + 1))
+ a -= (HB_FILTERORDER + 1);
+ b = b + (HB_FILTERORDER - 1);
+ if(b >= (HB_FILTERORDER + 1))
+ b -= (HB_FILTERORDER + 1);
+ }
+
+ a = (a + HB_FILTERORDER);
+ if(a >= (HB_FILTERORDER + 1))
+ a -= (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/dsp/kissengine.h b/include-gpl/dsp/kissengine.h
index bf101f6..ad8e53c 100644
--- a/dsp/kissengine.h
+++ b/include-gpl/dsp/kissengine.h
@@ -1,8 +1,8 @@
#ifndef INCLUDE_KISSENGINE_H
#define INCLUDE_KISSENGINE_H
-#include "fftengine.h"
-#include "kissfft.h"
+#include "dsp/fftengine.h"
+#include "dsp/kissfft.h"
class KissEngine : public FFTEngine {
public:
diff --git a/dsp/lowpass.h b/include-gpl/dsp/lowpass.h
index 99e20fe..a9ed168 100644
--- a/dsp/lowpass.h
+++ b/include-gpl/dsp/lowpass.h
@@ -1,7 +1,7 @@
#ifndef INCLUDE_LOWPASS_H
#define INCLUDE_LOWPASS_H
-#include "dsptypes.h"
+#include "dsp/dsptypes.h"
template <class Type> class Lowpass {
public:
diff --git a/dsp/nco.h b/include-gpl/dsp/nco.h
index d14bf57..7bc9f01 100644
--- a/dsp/nco.h
+++ b/include-gpl/dsp/nco.h
@@ -18,7 +18,7 @@
#ifndef INCLUDE_NCO_H
#define INCLUDE_NCO_H
-#include "dsptypes.h"
+#include "dsp/dsptypes.h"
class NCO {
private:
diff --git a/dsp/scopevis.h b/include-gpl/dsp/scopevis.h
index 07717e2..5631a58 100644
--- a/dsp/scopevis.h
+++ b/include-gpl/dsp/scopevis.h
@@ -1,7 +1,7 @@
#ifndef INCLUDE_SCOPEVIS_H
#define INCLUDE_SCOPEVIS_H
-#include "samplesink.h"
+#include "dsp/samplesink.h"
class GLScope;
class MessageQueue;
@@ -21,8 +21,7 @@ public:
void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst);
void start();
void stop();
- void setSampleRate(int sampleRate);
- void handleMessage(Message* cmd);
+ bool handleMessage(Message* message);
private:
enum TriggerState {
diff --git a/dsp/spectrumvis.h b/include-gpl/dsp/spectrumvis.h
index 11df32c..0b13c6c 100644
--- a/dsp/spectrumvis.h
+++ b/include-gpl/dsp/spectrumvis.h
@@ -1,8 +1,8 @@
#ifndef INCLUDE_SPECTRUMVIS_H
#define INCLUDE_SPECTRUMVIS_H
-#include "samplesink.h"
-#include "fftengine.h"
+#include "dsp/samplesink.h"
+#include "dsp/fftengine.h"
#include "fftwindow.h"
class GLSpectrum;
@@ -18,8 +18,7 @@ public:
void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst);
void start();
void stop();
- void setSampleRate(int sampleRate);
- void handleMessage(Message* cmd);
+ bool handleMessage(Message* message);
private:
FFTEngine* m_fft;
diff --git a/include-gpl/gui/addpresetdialog.h b/include-gpl/gui/addpresetdialog.h
new file mode 100644
index 0000000..8d3a7ee
--- /dev/null
+++ b/include-gpl/gui/addpresetdialog.h
@@ -0,0 +1,30 @@
+#ifndef INCLUDE_ADDPRESETDIALOG_H
+#define INCLUDE_ADDPRESETDIALOG_H
+
+#include <QDialog>
+
+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/gui/glscope.h b/include-gpl/gui/glscope.h
index 3432046..00a3acb 100644
--- a/gui/glscope.h
+++ b/include-gpl/gui/glscope.h
@@ -23,7 +23,7 @@
#include <QTimer>
#include <QMutex>
#include "dsp/dsptypes.h"
-#include "../dsp/scopevis.h"
+#include "dsp/scopevis.h"
class DSPEngine;
class ScopeVis;
@@ -44,7 +44,7 @@ public:
void setDSPEngine(DSPEngine* dspEngine);
void setAmp(Real amp);
- void setTimeStep(int timeStep);
+ void setTimeBase(int timeBase);
void setTimeOfsProMill(int timeOfsProMill);
void setMode(Mode mode);
void setOrientation(Qt::Orientation orientation);
@@ -82,7 +82,7 @@ private:
// config
Real m_amp;
- int m_timeStep;
+ int m_timeBase;
int m_timeOfsProMill;
ScopeVis::TriggerChannel m_triggerChannel;
Real m_triggerLevelHigh;
diff --git a/gui/glspectrum.h b/include-gpl/gui/glspectrum.h
index 7d48745..d1b07f5 100644
--- a/gui/glspectrum.h
+++ b/include-gpl/gui/glspectrum.h
@@ -22,7 +22,8 @@
#include <QTimer>
#include <QMutex>
#include "dsp/dsptypes.h"
-#include "scaleengine.h"
+#include "gui/scaleengine.h"
+#include "dsp/channelmarker.h"
class GLSpectrum : public QGLWidget {
Q_OBJECT
@@ -39,24 +40,41 @@ public:
void setInvertedWaterfall(bool inv);
void setDisplayLiveSpectrum(bool display);
void setDisplayHistogram(bool display);
- void setDisplayChannel(bool display, quint64 centerFrequency, quint64 bandwidth);
+
+ void addChannelMarker(ChannelMarker* channelMarker);
+ void removeChannelMarker(ChannelMarker* channelMarker);
void newSpectrum(const std::vector<Real>& spectrum, int fftSize);
private:
+ struct ChannelMarkerState {
+ ChannelMarker* m_channelMarker;
+ QRectF m_glRect;
+ QRect m_rect;
+
+ ChannelMarkerState(ChannelMarker* channelMarker) :
+ m_channelMarker(channelMarker),
+ m_glRect()
+ { }
+ };
+ QList<ChannelMarkerState*> m_channelMarkerStates;
+
enum CursorState {
CSNormal,
CSSplitter,
- CSSplitterMoving
+ CSSplitterMoving,
+ CSChannel,
+ CSChannelMoving
};
CursorState m_cursorState;
+ int m_cursorChannel;
QTimer m_timer;
QMutex m_mutex;
bool m_changesPending;
- quint64 m_centerFrequency;
+ qint64 m_centerFrequency;
Real m_referenceLevel;
Real m_powerRange;
quint32 m_sampleRate;
@@ -106,11 +124,6 @@ private:
QRectF m_glHistogramRect;
bool m_displayHistogram;
- bool m_displayChannel;
- quint64 m_channelCenterFrequency;
- quint64 m_channelBandwidth;
- QRectF m_glChannelRect;
-
bool m_displayChanged;
void updateWaterfall(const std::vector<Real>& spectrum);
@@ -120,7 +133,7 @@ private:
void resizeGL(int width, int height);
void paintGL();
- void stopSplitterMove();
+ void stopDrag();
void applyChanges();
void mouseMoveEvent(QMouseEvent* event);
@@ -129,6 +142,8 @@ private:
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 0000000..0a274dc
--- /dev/null
+++ b/include-gpl/gui/glspectrumgui.h
@@ -0,0 +1,58 @@
+#ifndef INCLUDE_GLSPECTRUMGUI_H
+#define INCLUDE_GLSPECTRUMGUI_H
+
+#include <QWidget>
+#include "dsp/dsptypes.h"
+
+namespace Ui {
+ class GLSpectrumGUI;
+}
+
+class MessageQueue;
+class SpectrumVis;
+class GLSpectrum;
+
+class 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;
+ bool m_displayWaterfall;
+ bool m_invertedWaterfall;
+ bool m_displayLiveSpectrum;
+ bool m_displayHistogram;
+
+ void applySettings();
+
+private slots:
+ void on_fftSize_valueChanged(int value);
+ void on_fftWindow_currentIndexChanged(int index);
+ void on_refLevel_valueChanged(int value);
+ void on_levelRange_valueChanged(int value);
+ void on_decay_valueChanged(int value);
+ void on_waterfall_toggled(bool checked);
+ void on_histogram_toggled(bool checked);
+ void on_liveSpectrum_toggled(bool checked);
+};
+
+#endif // INCLUDE_GLSPECTRUMGUI_H
diff --git a/gui/indicator.h b/include-gpl/gui/indicator.h
index a451469..a451469 100644
--- a/gui/indicator.h
+++ b/include-gpl/gui/indicator.h
diff --git a/gui/physicalunit.h b/include-gpl/gui/physicalunit.h
index e8eda2b..e8eda2b 100644
--- a/gui/physicalunit.h
+++ b/include-gpl/gui/physicalunit.h
diff --git a/include-gpl/gui/pluginsdialog.h b/include-gpl/gui/pluginsdialog.h
new file mode 100644
index 0000000..d0f7305
--- /dev/null
+++ b/include-gpl/gui/pluginsdialog.h
@@ -0,0 +1,22 @@
+#ifndef INCLUDE_PLUGINSDIALOG_H
+#define INCLUDE_PLUGINSDIALOG_H
+
+#include <QDialog>
+#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 0000000..86247f3
--- /dev/null
+++ b/include-gpl/gui/preferencesdialog.h
@@ -0,0 +1,34 @@
+#ifndef INCLUDE_PREFERENCESDIALOG_H
+#define INCLUDE_PREFERENCESDIALOG_H
+
+#include <QDialog>
+
+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/gui/presetitem.h b/include-gpl/gui/presetitem.h
index 80a6133..fa45543 100644
--- a/gui/presetitem.h
+++ b/include-gpl/gui/presetitem.h
@@ -19,7 +19,7 @@
class PresetItem : public QTreeWidgetItem {
public:
- PresetItem(QTreeWidget* parent, const QStringList& strings, quint64 frequency);
+ PresetItem(QTreeWidgetItem* parent, const QStringList& strings, quint64 frequency, int type);
bool operator<(const QTreeWidgetItem& other) const;
private:
diff --git a/gui/scale.h b/include-gpl/gui/scale.h
index 9be2c43..b9c3b34 100644
--- a/gui/scale.h
+++ b/include-gpl/gui/scale.h
@@ -16,7 +16,7 @@
///////////////////////////////////////////////////////////////////////////////////
#include <QWidget>
-#include "scaleengine.h"
+#include "gui/scaleengine.h"
class Scale : public QWidget {
Q_OBJECT
diff --git a/gui/scaleengine.h b/include-gpl/gui/scaleengine.h
index 3774116..3774116 100644
--- a/gui/scaleengine.h
+++ b/include-gpl/gui/scaleengine.h
diff --git a/gui/scopewindow.h b/include-gpl/gui/scopewindow.h
index 66d19cb..281a848 100644
--- a/gui/scopewindow.h
+++ b/include-gpl/gui/scopewindow.h
@@ -19,7 +19,7 @@
#define INCLUDE_SCOPEWINDOW_H
#include <QWidget>
-#include "../dsp/dsptypes.h"
+#include "dsp/dsptypes.h"
class DSPEngine;
@@ -36,6 +36,10 @@ public:
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);
@@ -49,7 +53,14 @@ private slots:
private:
Ui::ScopeWindow *ui;
int m_sampleRate;
- int m_timeStep;
+
+ qint32 m_displayData;
+ qint32 m_displayOrientation;
+ qint32 m_timeBase;
+ qint32 m_timeOffset;
+ qint32 m_amplification;
+
+ void applySettings();
};
#endif // INCLUDE_SCOPEWINDOW_H
diff --git a/gui/valuedial.h b/include-gpl/gui/valuedial.h
index 8e660b9..8e660b9 100644
--- a/gui/valuedial.h
+++ b/include-gpl/gui/valuedial.h
diff --git a/mainwindow.h b/include-gpl/mainwindow.h
index dd8d3f9..9848962 100644
--- a/mainwindow.h
+++ b/include-gpl/mainwindow.h
@@ -20,19 +20,25 @@
#include <QMainWindow>
#include <QTimer>
-#include "settings.h"
-#include "preset.h"
-#include "dsp/dspengine.h"
-#include "util/messagequeue.h"
+#include "audio/portaudioholder.h"
+#include "settings/settings.h"
class QLabel;
+class QTreeWidgetItem;
+class QDir;
+
+class AudioDeviceInfo;
class DSPEngine;
class Indicator;
class ScopeWindow;
class SpectrumVis;
-class SampleSourceGUI;
-
-class QTreeWidgetItem;
+class SampleSource;
+class PluginAPI;
+class PluginGUI;
+class ChannelMarker;
+class MessageQueue;
+class PluginManager;
+class PluginInterface;
namespace Ui {
class MainWindow;
@@ -45,23 +51,37 @@ public:
explicit MainWindow(QWidget* parent = NULL);
~MainWindow();
+ MessageQueue* getMessageQueue() { return m_messageQueue; }
+
+ void addDemodCreateAction(QAction* action);
+ void addViewAction(QAction* action);
+
+ void addChannelMarker(ChannelMarker* channelMarker);
+ void removeChannelMarker(ChannelMarker* channelMarker);
+
+ void setInputGUI(QWidget* gui);
+
private:
+ enum {
+ PGroup,
+ PItem
+ };
+
Ui::MainWindow *ui;
- MessageQueue m_messageQueue;
+ PortAudioHolder m_portAudioHolder;
+ AudioDeviceInfo* m_audioDeviceInfo;
+
+ MessageQueue* m_messageQueue;
- QSettings m_settingsStorage;
- PresetList m_presetList;
Settings m_settings;
SpectrumVis* m_spectrumVis;
- SampleSource* m_sampleSource;
- SampleSourceGUI* m_sampleSourceGUI;
- DSPEngine m_dspEngine;
+ DSPEngine* m_dspEngine;
QTimer m_statusTimer;
- DSPEngine::State m_lastEngineState;
+ int m_lastEngineState;
QLabel* m_sampleRateWidget;
Indicator* m_engineIdle;
@@ -71,11 +91,16 @@ private:
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();
@@ -83,6 +108,7 @@ private:
void updateCenterFreqDisplay();
void updateSampleRate();
void updatePresets();
+ QTreeWidgetItem* addPresetToTree(const Preset* preset);
void applySettings();
private slots:
@@ -91,27 +117,19 @@ private slots:
void scopeWindowDestroyed();
void on_action_Start_triggered();
void on_action_Stop_triggered();
- void on_fftWindow_currentIndexChanged(int index);
- void on_action_Debug_triggered();
void on_dcOffset_toggled(bool checked);
void on_iqImbalance_toggled(bool checked);
- void on_action_View_Waterfall_toggled(bool checked);
- void on_action_View_Histogram_toggled(bool checked);
- void on_action_View_LiveSpectrum_toggled(bool checked);
void on_action_View_Fullscreen_toggled(bool checked);
void on_actionOsmoSDR_Firmware_Upgrade_triggered();
- void on_fftSize_valueChanged(int value);
- void on_waterfall_toggled(bool checked);
- void on_histogram_toggled(bool checked);
- void on_liveSpectrum_toggled(bool checked);
- void on_refLevel_valueChanged(int value);
- void on_levelRange_valueChanged(int value);
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);
};
#endif // INCLUDE_MAINWINDOW_H
diff --git a/include-gpl/plugin/pluginmanager.h b/include-gpl/plugin/pluginmanager.h
new file mode 100644
index 0000000..50f39f3
--- /dev/null
+++ b/include-gpl/plugin/pluginmanager.h
@@ -0,0 +1,127 @@
+#ifndef INCLUDE_PLUGINMANAGER_H
+#define INCLUDE_PLUGINMANAGER_H
+
+#include <QObject>
+#include <QDir>
+#include "plugin/plugininterface.h"
+#include "plugin/pluginapi.h"
+
+class QAction;
+class QComboBox;
+class Preset;
+class MainWindow;
+class SampleSource;
+class Message;
+
+class PluginManager : public QObject {
+ Q_OBJECT
+
+public:
+ struct Plugin {
+ QString filename;
+ PluginInterface* plugin;
+ Plugin(const QString& _filename, PluginInterface* _plugin) :
+ filename(_filename),
+ plugin(_plugin)
+ { }
+ };
+ typedef QList<Plugin> Plugins;
+
+ explicit PluginManager(MainWindow* mainWindow, DSPEngine* dspEngine, QObject* parent = NULL);
+ ~PluginManager();
+ void loadPlugins();
+
+ const Plugins& getPlugins() const { return m_plugins; }
+
+ void registerDemodulator(const QString& demodName, PluginInterface* plugin, QAction* action);
+ void registerDemodulatorInstance(const QString& demodName, 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);
+
+private slots:
+ void demodInstanceDestroyed(QObject* object);
+
+private:
+ struct DemodRegistration {
+ QString m_demodName;
+ PluginInterface* m_plugin;
+ DemodRegistration(const QString& demodName, PluginInterface* plugin) :
+ m_demodName(demodName),
+ m_plugin(plugin)
+ { }
+ };
+ typedef QList<DemodRegistration> DemodRegistrations;
+
+ struct DemodInstanceRegistration {
+ QString m_demodName;
+ PluginGUI* m_gui;
+ DemodInstanceRegistration() :
+ m_demodName(),
+ m_gui(NULL)
+ { }
+ DemodInstanceRegistration(const QString& demodName, PluginGUI* pluginGUI) :
+ m_demodName(demodName),
+ m_gui(pluginGUI)
+ { }
+ };
+ typedef QList<DemodInstanceRegistration> DemodInstanceRegistrations;
+
+ struct SampleSourceRegistration {
+ QString m_sourceName;
+ PluginInterface* m_plugin;
+ SampleSourceRegistration(const QString& sourceName, PluginInterface* plugin) :
+ m_sourceName(sourceName),
+ m_plugin(plugin)
+ { }
+ };
+ typedef QList<SampleSourceRegistration> 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<SampleSourceDevice> SampleSourceDevices;
+
+ PluginAPI m_pluginAPI;
+ MainWindow* m_mainWindow;
+ DSPEngine* m_dspEngine;
+ Plugins m_plugins;
+
+ DemodRegistrations m_demodRegistrations;
+ DemodInstanceRegistrations m_demodInstanceRegistrations;
+ SampleSourceRegistrations m_sampleSourceRegistrations;
+ SampleSourceDevices m_sampleSourceDevices;
+
+ QString m_sampleSource;
+ PluginGUI* m_sampleSourceInstance;
+
+ void loadPlugins(const QDir& dir);
+ void renameDemodInstances();
+};
+
+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 0000000..74de287
--- /dev/null
+++ b/include-gpl/settings/preferences.h
@@ -0,0 +1,32 @@
+#ifndef INCLUDE_PREFERENCES_H
+#define INCLUDE_PREFERENCES_H
+
+#include <QString>
+
+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 0000000..f872941
--- /dev/null
+++ b/include-gpl/settings/preset.h
@@ -0,0 +1,98 @@
+#ifndef INCLUDE_PRESET_H
+#define INCLUDE_PRESET_H
+
+#include <QString>
+#include <QList>
+#include <QMetaType>
+
+class Preset {
+public:
+ struct DemodConfig {
+ QString m_demod;
+ QByteArray m_config;
+
+ DemodConfig(const QString& demod, const QByteArray& config) :
+ m_demod(demod),
+ m_config(config)
+ { }
+ };
+ typedef QList<DemodConfig> DemodConfigs;
+
+ 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 clearDemods() { m_demodConfigs.clear(); }
+ void addDemod(const QString& demod, const QByteArray& config) { m_demodConfigs.append(DemodConfig(demod, config)); }
+ int getDemodCount() const { return m_demodConfigs.count(); }
+ const DemodConfig& getDemodConfig(int index) const { return m_demodConfigs.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;
+
+ // demodulators and configurations
+ DemodConfigs m_demodConfigs;
+
+ // 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 0000000..a6cf04f
--- /dev/null
+++ b/include-gpl/settings/settings.h
@@ -0,0 +1,32 @@
+#ifndef INCLUDE_SETTINGS_H
+#define INCLUDE_SETTINGS_H
+
+#include <QString>
+#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<Preset*> 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 0000000..229e7f1
--- /dev/null
+++ b/include/dsp/channelmarker.h
@@ -0,0 +1,39 @@
+#ifndef INCLUDE_CHANNELMARKER_H
+#define INCLUDE_CHANNELMARKER_H
+
+#include <QObject>
+#include <QColor>
+
+class 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:
+ 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/dsp/dsptypes.h b/include/dsp/dsptypes.h
index 5fac3fd..b6bbf67 100644
--- a/dsp/dsptypes.h
+++ b/include/dsp/dsptypes.h
@@ -38,6 +38,9 @@ struct Sample {
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; }
diff --git a/dsp/kissfft.h b/include/dsp/kissfft.h
index ba1256c..ba1256c 100644
--- a/dsp/kissfft.h
+++ b/include/dsp/kissfft.h
diff --git a/hardware/samplefifo.h b/include/dsp/samplefifo.h
index ae5d210..2ab3110 100644
--- a/hardware/samplefifo.h
+++ b/include/dsp/samplefifo.h
@@ -33,12 +33,12 @@ private:
SampleVector m_data;
- size_t m_size;
- size_t m_fill;
- size_t m_head;
- size_t m_tail;
+ uint m_size;
+ uint m_fill;
+ uint m_head;
+ uint m_tail;
- void create(size_t s);
+ void create(uint s);
public:
SampleFifo(QObject* parent = NULL);
@@ -49,17 +49,17 @@ public:
SampleFifo& operator=(const SampleFifo&);
bool setSize(int size);
- inline size_t fill() const { return m_fill; }
+ inline uint fill() const { return m_fill; }
- size_t write(const quint8* data, size_t count);
- size_t write(SampleVector::const_iterator begin, SampleVector::const_iterator end);
+ uint write(const quint8* data, uint count);
+ uint write(SampleVector::const_iterator begin, SampleVector::const_iterator end);
- size_t read(SampleVector::iterator begin, SampleVector::iterator end);
+ uint read(SampleVector::iterator begin, SampleVector::iterator end);
- size_t readBegin(size_t count,
+ uint readBegin(uint count,
SampleVector::iterator* part1Begin, SampleVector::iterator* part1End,
SampleVector::iterator* part2Begin, SampleVector::iterator* part2End);
- size_t readCommit(size_t count);
+ uint readCommit(uint count);
signals:
void dataReady();
diff --git a/dsp/samplesink.h b/include/dsp/samplesink.h
index 4e38134..8a02bc8 100644
--- a/dsp/samplesink.h
+++ b/include/dsp/samplesink.h
@@ -13,8 +13,7 @@ public:
virtual void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst) = 0;
virtual void start() = 0;
virtual void stop() = 0;
- virtual void setSampleRate(int sampleRate) = 0;
- virtual void handleMessage(Message* cmd) = 0;
+ virtual bool handleMessage(Message* cmd) = 0;
};
#endif // INCLUDE_SAMPLESINK_H
diff --git a/hardware/samplesource.h b/include/dsp/samplesource/samplesource.h
index 026d44e..0328a90 100644
--- a/hardware/samplesource.h
+++ b/include/dsp/samplesource/samplesource.h
@@ -19,39 +19,24 @@
#define INCLUDE_SAMPLESOURCE_H
#include <QtGlobal>
-#include "samplefifo.h"
-#include "../util/message.h"
+#include "dsp/samplefifo.h"
+#include "util/message.h"
-class SampleSourceGUI;
+class PluginGUI;
class MessageQueue;
-class DSPCmdGUIToSource : public Message {
+class SampleSource {
public:
- enum {
- Type = 13
- };
-
- DSPCmdGUIToSource() { }
- int type() const;
- const char* name() const;
- virtual int sourceType() const = 0;
-};
+ struct GeneralSettings {
+ quint64 m_centerFrequency;
-class DSPCmdSourceToGUI : public Message {
-public:
- enum {
- Type = 14
+ GeneralSettings();
+ void resetToDefaults();
+ QByteArray serialize() const;
+ bool deserialize(const QByteArray& data);
};
- DSPCmdSourceToGUI() { }
- int type() const;
- const char* name() const;
- virtual int sourceType() const = 0;
-};
-
-class SampleSource {
-public:
- SampleSource(MessageQueue* msgQueueToGUI);
+ SampleSource(MessageQueue* guiMessageQueue);
virtual ~SampleSource();
virtual bool startInput(int device) = 0;
@@ -61,15 +46,15 @@ public:
virtual int getSampleRate() const = 0;
virtual quint64 getCenterFrequency() const = 0;
- virtual SampleSourceGUI* createGUI(MessageQueue* msgQueueToEngine, QWidget* parent = NULL) const = 0;
-
- virtual void handleGUIMessage(DSPCmdGUIToSource* cmd) = 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 0000000..f7e704e
--- /dev/null
+++ b/include/dsp/threadedsamplesink.h
@@ -0,0 +1,40 @@
+#ifndef INCLUDE_THREADEDSAMPLESINK_H
+#define INCLUDE_THREADEDSAMPLESINK_H
+
+#include <QMutex>
+#include "samplesink.h"
+#include "dsp/samplefifo.h"
+#include "util/messagequeue.h"
+
+class QThread;
+class SampleSink;
+
+class ThreadedSampleSink : public QObject, 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/plugin/pluginapi.h b/include/plugin/pluginapi.h
new file mode 100644
index 0000000..515eb0d
--- /dev/null
+++ b/include/plugin/pluginapi.h
@@ -0,0 +1,56 @@
+#ifndef INCLUDE_PLUGINAPI_H
+#define INCLUDE_PLUGINAPI_H
+
+#include <QObject>
+
+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 PluginAPI : public QObject {
+ Q_OBJECT
+
+public:
+ // MainWindow access
+ QDockWidget* createMainWindowDock(Qt::DockWidgetArea dockWidgetArea, const QString& title);
+ MessageQueue* getMainWindowMessageQueue();
+
+ // Demodulator stuff
+ void registerDemodulator(const QString& demodName, PluginInterface* plugin, QAction* action);
+ void registerDemodulatorInstance(const QString& demodName, 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 0000000..2e48079
--- /dev/null
+++ b/include/plugin/plugingui.h
@@ -0,0 +1,29 @@
+#ifndef INCLUDE_PLUGINGUI_H
+#define INCLUDE_PLUGINGUI_H
+
+#include <QWidget>
+
+class Message;
+
+class PluginGUI : public QWidget {
+ Q_OBJECT
+
+public:
+ PluginGUI(QWidget* parent = NULL);
+ virtual void destroy() = 0;
+
+ virtual void setWidgetName(const QString& name);
+
+ 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 0000000..15e3c5d
--- /dev/null
+++ b/include/plugin/plugininterface.h
@@ -0,0 +1,48 @@
+#ifndef INCLUDE_PLUGININTERFACE_H
+#define INCLUDE_PLUGININTERFACE_H
+
+#include <QtPlugin>
+#include <QString>
+
+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<SampleSourceDevice> SampleSourceDevices;
+
+ virtual ~PluginInterface() { };
+
+ virtual const PluginDescriptor& getPluginDescriptor() const = 0;
+ virtual void initPlugin(PluginAPI* pluginAPI) = 0;
+
+ virtual PluginGUI* createDemod(const QString& demodName) { 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/message.h b/include/util/message.h
new file mode 100644
index 0000000..8718496
--- /dev/null
+++ b/include/util/message.h
@@ -0,0 +1,50 @@
+#ifndef INCLUDE_MESSAGE_H
+#define INCLUDE_MESSAGE_H
+
+#include <QAtomicInt>
+#include <QStringList>
+
+class MessageQueue;
+class QWaitCondition;
+class QMutex;
+
+class MessageRegistrator {
+public:
+ MessageRegistrator(const char* name);
+ int operator()() const { return m_registeredID; }
+
+ const char* name() const;
+
+private:
+ int m_registeredID;
+};
+
+class Message {
+public:
+ virtual ~Message();
+
+ void submit(MessageQueue* queue, void* destination = NULL);
+ int execute(MessageQueue* queue, void* destination = NULL);
+
+ void completed(int result = 0);
+
+ int id() const { return m_id; }
+ const char* name() const;
+ void* destination() const { return m_destination; }
+
+protected:
+ Message(int id);
+
+ // adressing
+ int m_id;
+ void* m_destination;
+
+ // stuff for synchronous messages
+ bool m_synchronous;
+ QWaitCondition* m_waitCondition;
+ QMutex* m_mutex;
+ QAtomicInt m_complete;
+ int m_result;
+};
+
+#endif // INCLUDE_MESSAGE_H
diff --git a/util/messagequeue.h b/include/util/messagequeue.h
index bf99ea2..bf99ea2 100644
--- a/util/messagequeue.h
+++ b/include/util/messagequeue.h
diff --git a/util/miniz.h b/include/util/miniz.h
index 4779dbd..0882c06 100644
--- a/util/miniz.h
+++ b/include/util/miniz.h
@@ -2,6 +2,6 @@
#define INCLUDE_MINIZ_H
#define MINIZ_HEADER_FILE_ONLY
-#include "miniz.cpp"
+#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 0000000..3893c32
--- /dev/null
+++ b/include/util/simpleserializer.h
@@ -0,0 +1,111 @@
+#ifndef INCLUDE_SIMPLESERIALIZER_H
+#define INCLUDE_SIMPLESERIALIZER_H
+
+#include <QString>
+#include <QMap>
+#include "dsp/dsptypes.h"
+
+class 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 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<quint32, Element> 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/util/spinlock.h b/include/util/spinlock.h
index 78af0b6..78af0b6 100644
--- a/util/spinlock.h
+++ b/include/util/spinlock.h
diff --git a/main.cpp b/main.cpp
index 3383b1e..cf0872b 100644
--- a/main.cpp
+++ b/main.cpp
@@ -17,28 +17,10 @@
#include <QApplication>
#include <QTextCodec>
-#include <QMessageBox>
#include <QWindowsStyle>
#include "mainwindow.h"
-#include "portaudio.h"
-static void initPortAudio()
-{
- PaError err;
-
- if((err = Pa_Initialize()) != paNoError) {
- qCritical("PortAudio: could not initialise: %s (%d)", Pa_GetErrorText(err), err);
- QString error = QObject::tr("PortAudio could not be initialised: %1 (%2)").arg(Pa_GetErrorText(err)).arg(err);
- QMessageBox::critical(NULL, "PortAudio failure", error);
- }
-}
-
-static void cleanupPortAudio()
-{
- Pa_Terminate();
-}
-
-int main(int argc, char* argv[])
+static int runQtApplication(int argc, char* argv[])
{
QApplication a(argc, argv);
@@ -48,16 +30,15 @@ int main(int argc, char* argv[])
QCoreApplication::setOrganizationName("osmocom");
QCoreApplication::setApplicationName("SDRangelove");
- //QApplication::setStyle(new QWindowsStyle);
-
- initPortAudio();
+ QApplication::setStyle(new QWindowsStyle);
MainWindow w;
w.show();
- int res = a.exec();
-
- cleanupPortAudio();
+ return a.exec();
+}
- return res;
+int main(int argc, char* argv[])
+{
+ return runQtApplication(argc, argv);
}
diff --git a/mainwindow.cpp b/mainwindow.cpp
deleted file mode 100644
index 82f1d78..0000000
--- a/mainwindow.cpp
+++ /dev/null
@@ -1,556 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include <QInputDialog>
-#include <QMessageBox>
-#include "mainwindow.h"
-#include "ui_mainwindow.h"
-#include "gui/indicator.h"
-#include "gui/presetitem.h"
-#include "gui/scopewindow.h"
-#include "dsp/spectrumvis.h"
-#include "dsp/dspcommands.h"
-#include "dsp/nfmdemod.h"
-#include "hardware/samplesourcegui.h"
-#include "hardware/osmosdr/osmosdrinput.h"
-#include "hardware/osmosdr/osmosdrupgrade.h"
-#include "hardware/rtlsdr/rtlsdrinput.h"
-
-MainWindow::MainWindow(QWidget* parent) :
- QMainWindow(parent),
- ui(new Ui::MainWindow),
- m_messageQueue(),
- m_settings(),
- m_dspEngine(&m_messageQueue),
- m_lastEngineState((DSPEngine::State)-1),
- m_startOsmoSDRUpdateAfterStop(false),
- m_scopeWindow(NULL),
- m_sampleRate(0),
- m_centerFrequency(0)
-{
- ui->setupUi(this);
- 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);
- addDockWidget(Qt::LeftDockWidgetArea, ui->inputDock);
- addDockWidget(Qt::LeftDockWidgetArea, ui->processingDock);
- addDockWidget(Qt::LeftDockWidgetArea, ui->presetDock);
- ui->inputDock->show();
- ui->processingDock->show();
- ui->presetDock->show();
-
- connect(&m_messageQueue, SIGNAL(messageEnqueued()), this, SLOT(handleMessages()), Qt::QueuedConnection);
-
- connect(&m_statusTimer, SIGNAL(timeout()), this, SLOT(updateStatus()));
- m_statusTimer.start(500);
-
- m_dspEngine.start();
-
- loadSettings();
-
- m_sampleSource = new OsmoSDRInput(&m_messageQueue);
- //m_sampleSource = new RTLSDRInput(&m_messageQueue);
- m_dspEngine.setSource(m_sampleSource);
- m_sampleSourceGUI = m_sampleSource->createGUI(m_dspEngine.getMessageQueue());
- ui->inputDock->setWidget(m_sampleSourceGUI);
- ui->inputDock->setWindowTitle(ui->inputDock->widget()->windowTitle());
-
- m_spectrumVis = new SpectrumVis(ui->glSpectrum);
- m_dspEngine.addSink(m_spectrumVis);
-
- applySettings();
- updatePresets();
-/*
- NFMDemod* nfmDemod = new NFMDemod;
- m_dspEngine.addSink(nfmDemod);
-*/
-/*
- Channelizer* channelizer = new Channelizer;
- //channelizer->setGLSpectrum(ui->chanSpectrum);
- m_dspEngine.addChannelizer(channelizer);
- */
-}
-
-MainWindow::~MainWindow()
-{
- m_dspEngine.stopAcquistion();
-
- m_settings.setSourceSettings(m_sampleSourceGUI->serializeSettings());
- saveSettings();
-
- m_dspEngine.removeSink(m_spectrumVis);
- delete m_spectrumVis;
-
- if(m_scopeWindow != NULL) {
- delete m_scopeWindow;
- m_scopeWindow = NULL;
- }
-
- if(m_sampleSource != NULL) {
- m_dspEngine.setSource(NULL);
- delete m_sampleSource;
- m_sampleSource = NULL;
- }
-
- m_dspEngine.stop();
-
- while(!m_presetList.empty())
- delete m_presetList.takeLast();
-
- delete ui;
-}
-
-void MainWindow::loadSettings()
-{
- if(m_settingsStorage.value("version", 0).toInt() != 3) {
- m_settingsStorage.clear();
- return;
- }
-
- // load current settings
- m_settings.load(&m_settingsStorage, "");
-
- if(m_settings.displayScope())
- on_action_Oscilloscope_triggered();
-
- // local dock layout
- restoreState(QByteArray::fromBase64(m_settingsStorage.value("docklayout").toByteArray()));
-
- // load presets
- QStringList groups = m_settingsStorage.childGroups();
- for(int i = 0; i < groups.size(); ++i) {
- if(groups[i].startsWith("preset")) {
- // load preset name
- m_settingsStorage.beginGroup(groups[i]);
- QString name = m_settingsStorage.value("presetname", tr("Preset %1").arg(m_presetList.size() + 1)).toString();
- m_settingsStorage.endGroup();
-
- // load preset content
- Settings settings;
- settings.load(&m_settingsStorage, groups[i]);
-
- // create preset struct
- Preset* preset = new Preset(name, settings);
- m_presetList.append(preset);
-
- // insert into preset widget
- QStringList strings;
- strings.append(tr("%1").arg(settings.centerFrequency() / 1000));
- strings.append(name);
- PresetItem* item = new PresetItem(ui->presetTree, strings, settings.centerFrequency());
- item->setTextAlignment(0, Qt::AlignRight);
- item->setData(0, Qt::UserRole, qVariantFromValue(preset));
- }
- }
- ui->presetTree->sortItems(0, Qt::AscendingOrder);
-}
-
-void MainWindow::saveSettings()
-{
- m_settingsStorage.setValue("version", 3);
-
- // save dock layout
- m_settingsStorage.setValue("docklayout", saveState().toBase64());
-
- // save current settings
- m_settings.save(&m_settingsStorage, "");
-
- // delete all old presets
- QStringList groups = m_settingsStorage.childGroups();
- for(int i = 0; i < groups.size(); ++i) {
- if(groups[i].startsWith("preset")) {
- m_settingsStorage.remove(groups[i]);
- }
- }
-
- // save presets
- for(int i = 0; i < m_presetList.size(); ++i) {
- QString group = tr("preset%1").arg(i + 1);
- m_settingsStorage.beginGroup(group);
- m_settingsStorage.setValue("presetname", m_presetList[i]->name());
- m_settingsStorage.endGroup();
-
- m_presetList[i]->settings()->save(&m_settingsStorage, group);
- }
-}
-
-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*)
-{
- /*
- if(m_scopeWindow != NULL) {
- delete m_scopeWindow;
- m_scopeWindow = NULL;
- }
- */
-}
-
-void MainWindow::updateCenterFreqDisplay()
-{
- ui->glSpectrum->setCenterFrequency(m_centerFrequency);
- //ui->glSpectrum->setDisplayChannel(true, m_centerFrequency + 50000.0, 12500.0);
-}
-
-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);
- }
-}
-
-void MainWindow::applySettings()
-{
- for(int i = 0; i < 6; i++) {
- if(m_settings.fftSize() == (1 << (i + 7))) {
- ui->fftSize->setValue(i);
- break;
- }
- }
-
- ui->fftWindow->setCurrentIndex(m_settings.fftWindow());
-
- ui->waterfall->setChecked(m_settings.displayWaterfall());
- ui->action_View_Waterfall->setChecked(m_settings.displayWaterfall());
- ui->glSpectrum->setDisplayWaterfall(m_settings.displayWaterfall());
- ui->glSpectrum->setInvertedWaterfall(m_settings.invertedWaterfall());
- ui->liveSpectrum->setChecked(m_settings.displayLiveSpectrum());
- ui->action_View_LiveSpectrum->setChecked(m_settings.displayLiveSpectrum());
- ui->glSpectrum->setDisplayLiveSpectrum(m_settings.displayLiveSpectrum());
- ui->action_View_Histogram->setChecked(m_settings.displayHistogram());
- ui->glSpectrum->setDisplayHistogram(m_settings.displayHistogram());
- ui->histogram->setChecked(m_settings.displayHistogram());
-
- ui->dcOffset->setChecked(m_settings.dcOffsetCorrection());
- ui->iqImbalance->setChecked(m_settings.iqImbalanceCorrection());
-
- updateCenterFreqDisplay();
- updateSampleRate();
-
- m_dspEngine.configureCorrections(m_settings.dcOffsetCorrection(), m_settings.iqImbalanceCorrection());
- m_spectrumVis->configure(m_dspEngine.getMessageQueue(), m_settings.fftSize(), m_settings.fftOverlap(), (FFTWindow::Function)m_settings.fftWindow());
- m_sampleSourceGUI->deserializeSettings(m_settings.sourceSettings());
-}
-
-void MainWindow::handleMessages()
-{
- Message* cmd;
- while((cmd = m_messageQueue.accept()) != NULL) {
- qDebug("CMD: %s", cmd->name());
-
- switch(cmd->type()) {
- case DSPRepEngineReport::Type: {
- DSPRepEngineReport* rep = (DSPRepEngineReport*)cmd;
- m_sampleRate = rep->getSampleRate();
- m_centerFrequency = rep->getCenterFrequency();
- qDebug("SampleRate:%d, CenterFrequency:%llu", rep->getSampleRate(), rep->getCenterFrequency());
- updateCenterFreqDisplay();
- updateSampleRate();
- cmd->completed();
- break;
- }
-
- case DSPCmdSourceToGUI::Type:
- if(m_sampleSourceGUI != NULL)
- m_sampleSourceGUI->handleSourceMessage((DSPCmdSourceToGUI*)cmd);
- cmd->completed();
- break;
-
- default:
- cmd->completed();
- break;
- }
- }
-}
-
-void MainWindow::updateStatus()
-{
- DSPEngine::State 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.setDisplayScope(false);
-}
-
-void MainWindow::on_action_Start_triggered()
-{
- m_dspEngine.startAcquisition();
-}
-
-void MainWindow::on_action_Stop_triggered()
-{
- m_dspEngine.stopAcquistion();
-}
-
-void MainWindow::on_fftWindow_currentIndexChanged(int index)
-{
- m_settings.setFFTWindow(index);
- m_spectrumVis->configure(m_dspEngine.getMessageQueue(), m_settings.fftSize(), m_settings.fftOverlap(), (FFTWindow::Function)m_settings.fftWindow());
-}
-
-void MainWindow::on_action_Debug_triggered()
-{
-// m_dspEngine.triggerDebug();
-}
-
-void MainWindow::on_dcOffset_toggled(bool checked)
-{
- m_settings.setDCOffsetCorrection(checked);
- m_dspEngine.configureCorrections(m_settings.dcOffsetCorrection(), m_settings.iqImbalanceCorrection());
-}
-
-void MainWindow::on_iqImbalance_toggled(bool checked)
-{
- m_settings.setIQImbalanceCorrection(checked);
- m_dspEngine.configureCorrections(m_settings.dcOffsetCorrection(), m_settings.iqImbalanceCorrection());
-}
-
-void MainWindow::on_action_View_Waterfall_toggled(bool checked)
-{
- m_settings.setDisplayWaterfall(checked);
- ui->action_View_Waterfall->setChecked(checked);
- ui->glSpectrum->setDisplayWaterfall(checked);
-}
-
-void MainWindow::on_action_View_Histogram_toggled(bool checked)
-{
- m_settings.setDisplayHistogram(checked);
- ui->action_View_Histogram->setChecked(checked);
- ui->glSpectrum->setDisplayHistogram(checked);
-}
-
-void MainWindow::on_action_View_LiveSpectrum_toggled(bool checked)
-{
- m_settings.setDisplayLiveSpectrum(checked);
- ui->action_View_LiveSpectrum->setChecked(checked);
- ui->glSpectrum->setDisplayLiveSpectrum(checked);
-}
-
-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;
-
- OsmoSDRUpgrade osmoSDRUpgrade;
- osmoSDRUpgrade.exec();
-}
-
-void MainWindow::on_fftSize_valueChanged(int value)
-{
- ui->fftSizeDisplay->setText(tr("%1").arg(1 << (7 + value)));
- m_settings.setFFTSize(1 << (7 + value));
-
- m_spectrumVis->configure(m_dspEngine.getMessageQueue(), m_settings.fftSize(), m_settings.fftOverlap(), (FFTWindow::Function)m_settings.fftWindow());
-}
-
-void MainWindow::on_waterfall_toggled(bool checked)
-{
- m_settings.setDisplayWaterfall(checked);
- ui->action_View_Waterfall->setChecked(checked);
- ui->glSpectrum->setDisplayWaterfall(checked);
-}
-
-void MainWindow::on_histogram_toggled(bool checked)
-{
- m_settings.setDisplayHistogram(checked);
- ui->action_View_Histogram->setChecked(checked);
- ui->glSpectrum->setDisplayHistogram(checked);
-}
-
-void MainWindow::on_liveSpectrum_toggled(bool checked)
-{
- m_settings.setDisplayLiveSpectrum(checked);
- ui->action_View_LiveSpectrum->setChecked(checked);
- ui->glSpectrum->setDisplayLiveSpectrum(checked);
-}
-
-void MainWindow::on_refLevel_valueChanged(int value)
-{
- ui->glSpectrum->setReferenceLevel(value * 10);
- ui->refLevelDisplay->setText(tr("%1").arg(value * 10));
-}
-
-void MainWindow::on_levelRange_valueChanged(int value)
-{
- ui->glSpectrum->setPowerRange(value * 10);
- ui->levelRangeDisplay->setText(tr("%1").arg(value * 10));
-}
-
-void MainWindow::on_presetSave_clicked()
-{
- bool ok;
- QString name = QInputDialog::getText(this, tr("Save Preset"), tr("Preset name"), QLineEdit::Normal, tr(""), &ok);
- if(!ok)
- return;
-
- m_settings.setCenterFrequency(m_centerFrequency);
- m_settings.setSourceSettings(m_sampleSourceGUI->serializeSettings());
-
- Preset* preset = new Preset(name, m_settings);
- m_presetList.append(preset);
-
- QStringList strings;
- strings.append(tr("%1").arg(m_centerFrequency / 1000));
- strings.append(name);
- PresetItem* item = new PresetItem(ui->presetTree, strings, m_settings.centerFrequency());
- item->setTextAlignment(0, Qt::AlignRight);
- item->setData(0, Qt::UserRole, qVariantFromValue(preset));
- ui->presetTree->sortItems(0, Qt::AscendingOrder);
-}
-
-void MainWindow::on_presetLoad_clicked()
-{
- QTreeWidgetItem* item = ui->presetTree->currentItem();
- if(item == NULL) {
- updatePresets();
- return;
- }
- Preset* preset = qvariant_cast<Preset*>(item->data(0, Qt::UserRole));
-
- m_settings = *preset->settings();
- applySettings();
-}
-
-void MainWindow::on_presetDelete_clicked()
-{
- QTreeWidgetItem* item = ui->presetTree->currentItem();
- if(item == NULL) {
- updatePresets();
- return;
- }
- Preset* preset = qvariant_cast<Preset*>(item->data(0, Qt::UserRole));
-
- if(QMessageBox::question(this, tr("Delete Preset"), tr("Do you want to delete preset '%1'?").arg(preset->name()), QMessageBox::No | QMessageBox::Yes, QMessageBox::No) == QMessageBox::Yes) {
- delete item;
- m_presetList.removeAll(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.setDisplayScope(true);
-}
diff --git a/mainwindow.ui b/mainwindow.ui
deleted file mode 100644
index 003fbef..0000000
--- a/mainwindow.ui
+++ /dev/null
@@ -1,774 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<ui version="4.0">
- <class>MainWindow</class>
- <widget class="QMainWindow" name="MainWindow">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>1012</width>
- <height>706</height>
- </rect>
- </property>
- <property name="windowTitle">
- <string>SDRangelove</string>
- </property>
- <property name="windowIcon">
- <iconset resource="resources/res.qrc">
- <normaloff>:/appicon.png</normaloff>:/appicon.png</iconset>
- </property>
- <property name="documentMode">
- <bool>true</bool>
- </property>
- <widget class="QWidget" name="centralWidget">
- <layout class="QVBoxLayout" name="verticalLayout_2">
- <property name="margin">
- <number>0</number>
- </property>
- <item>
- <widget class="GLSpectrum" name="glSpectrum" native="true">
- <property name="sizePolicy">
- <sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- </widget>
- </item>
- </layout>
- </widget>
- <widget class="QMenuBar" name="menuBar">
- <property name="geometry">
- <rect>
- <x>0</x>
- <y>0</y>
- <width>1012</width>
- <height>21</height>
- </rect>
- </property>
- <widget class="QMenu" name="menu_File">
- <property name="title">
- <string>&amp;File</string>
- </property>
- <addaction name="action_Exit"/>
- </widget>
- <widget class="QMenu" name="menu_Options">
- <property name="title">
- <string>&amp;Options</string>
- </property>
- <addaction name="actionOsmoSDR_Firmware_Upgrade"/>
- </widget>
- <widget class="QMenu" name="menu_Acquisition">
- <property name="title">
- <string>&amp;Acquisition</string>
- </property>
- <addaction name="action_Start"/>
- <addaction name="action_Stop"/>
- <addaction name="separator"/>
- <addaction name="action_Debug"/>
- </widget>
- <widget class="QMenu" name="menu_View">
- <property name="title">
- <string>&amp;View</string>
- </property>
- <addaction name="action_View_Fullscreen"/>
- <addaction name="separator"/>
- <addaction name="action_Oscilloscope"/>
- <addaction name="separator"/>
- <addaction name="action_View_Waterfall"/>
- <addaction name="action_View_Histogram"/>
- <addaction name="action_View_LiveSpectrum"/>
- <addaction name="separator"/>
- </widget>
- <addaction name="menu_File"/>
- <addaction name="menu_Acquisition"/>
- <addaction name="menu_View"/>
- <addaction name="menu_Options"/>
- </widget>
- <widget class="QToolBar" name="mainToolBar">
- <attribute name="toolBarArea">
- <enum>TopToolBarArea</enum>
- </attribute>
- <attribute name="toolBarBreak">
- <bool>false</bool>
- </attribute>
- </widget>
- <widget class="QStatusBar" name="statusBar"/>
- <widget class="QDockWidget" name="presetDock">
- <property name="windowTitle">
- <string>Presets</string>
- </property>
- <attribute name="dockWidgetArea">
- <number>1</number>
- </attribute>
- <widget class="QWidget" name="dockWidgetContents">
- <layout class="QGridLayout" name="gridLayout_6">
- <property name="margin">
- <number>2</number>
- </property>
- <property name="spacing">
- <number>3</number>
- </property>
- <item row="5" column="1">
- <widget class="QToolButton" name="presetSave">
- <property name="toolTip">
- <string>Save current settings as preset</string>
- </property>
- <property name="text">
- <string>...</string>
- </property>
- <property name="icon">
- <iconset resource="resources/res.qrc">
- <normaloff>:/preset-save.png</normaloff>:/preset-save.png</iconset>
- </property>
- <property name="iconSize">
- <size>
- <width>16</width>
- <height>16</height>
- </size>
- </property>
- </widget>
- </item>
- <item row="5" column="5">
- <widget class="QToolButton" name="presetLoad">
- <property name="toolTip">
- <string>Load selected preset</string>
- </property>
- <property name="text">
- <string>...</string>
- </property>
- <property name="icon">
- <iconset resource="resources/res.qrc">
- <normaloff>:/preset-load.png</normaloff>:/preset-load.png</iconset>
- </property>
- <property name="iconSize">
- <size>
- <width>16</width>
- <height>16</height>
- </size>
- </property>
- </widget>
- </item>
- <item row="5" column="3" colspan="2">
- <spacer name="horizontalSpacer_3">
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="sizeHint" stdset="0">
- <size>
- <width>40</width>
- <height>20</height>
- </size>
- </property>
- </spacer>
- </item>
- <item row="5" column="2">
- <widget class="QToolButton" name="presetDelete">
- <property name="toolTip">
- <string>Delete selected preset</string>
- </property>
- <property name="text">
- <string>...</string>
- </property>
- <property name="icon">
- <iconset resource="resources/res.qrc">
- <normaloff>:/preset-delete.png</normaloff>:/preset-delete.png</iconset>
- </property>
- <property name="iconSize">
- <size>
- <width>16</width>
- <height>16</height>
- </size>
- </property>
- </widget>
- </item>
- <item row="1" column="1" rowspan="4" colspan="5">
- <widget class="QTreeWidget" name="presetTree">
- <property name="rootIsDecorated">
- <bool>false</bool>
- </property>
- <column>
- <property name="text">
- <string>Frequency</string>
- </property>
- </column>
- <column>
- <property name="text">
- <string>Description</string>
- </property>
- </column>
- </widget>
- </item>
- </layout>
- </widget>
- </widget>
- <widget class="QDockWidget" name="processingDock">
- <property name="windowTitle">
- <string>Processing and Display</string>
- </property>
- <attribute name="dockWidgetArea">
- <number>1</number>
- </attribute>
- <widget class="QWidget" name="dockWidgetContents_4">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <layout class="QGridLayout" name="gridLayout_5">
- <property name="horizontalSpacing">
- <number>3</number>
- </property>
- <property name="verticalSpacing">
- <number>0</number>
- </property>
- <property name="margin">
- <number>2</number>
- </property>
- <item row="4" column="2">
- <widget class="QLabel" name="label_5">
- <property name="text">
- <string>Reference</string>
- </property>
- </widget>
- </item>
- <item row="4" column="6">
- <widget class="QLabel" name="refLevelDisplay">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>25</width>
- <height>0</height>
- </size>
- </property>
- <property name="text">
- <string>0</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="6" column="6">
- <widget class="QLabel" name="levelRangeDisplay">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>25</width>
- <height>0</height>
- </size>
- </property>
- <property name="text">
- <string>100</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="6" column="2">
- <widget class="QLabel" name="label_6">
- <property name="text">
- <string>Range</string>
- </property>
- </widget>
- </item>
- <item row="7" column="2">
- <widget class="QLabel" name="label_7">
- <property name="text">
- <string>Decay</string>
- </property>
- </widget>
- </item>
- <item row="7" column="6">
- <widget class="QLabel" name="levelRangeDisplay_2">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="minimumSize">
- <size>
- <width>25</width>
- <height>0</height>
- </size>
- </property>
- <property name="text">
- <string>100</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="6" column="8">
- <widget class="QToolButton" name="histogram">
- <property name="minimumSize">
- <size>
- <width>24</width>
- <height>24</height>
- </size>
- </property>
- <property name="toolTip">
- <string>Display phosphor effect spectrum</string>
- </property>
- <property name="text">
- <string>Histogram</string>
- </property>
- <property name="icon">
- <iconset resource="resources/res.qrc">
- <normaloff>:/histogram.png</normaloff>:/histogram.png</iconset>
- </property>
- <property name="checkable">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="7" column="8">
- <widget class="QToolButton" name="liveSpectrum">
- <property name="minimumSize">
- <size>
- <width>24</width>
- <height>24</height>
- </size>
- </property>
- <property name="toolTip">
- <string>Display live spectrum</string>
- </property>
- <property name="text">
- <string>Live Spectrum</string>
- </property>
- <property name="icon">
- <iconset resource="resources/res.qrc">
- <normaloff>:/livespectrum.png</normaloff>:/livespectrum.png</iconset>
- </property>
- <property name="checkable">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="4" column="7" rowspan="4">
- <widget class="Line" name="line_2">
- <property name="orientation">
- <enum>Qt::Vertical</enum>
- </property>
- </widget>
- </item>
- <item row="4" column="8">
- <widget class="QToolButton" name="waterfall">
- <property name="minimumSize">
- <size>
- <width>24</width>
- <height>24</height>
- </size>
- </property>
- <property name="toolTip">
- <string>Display waterfall</string>
- </property>
- <property name="text">
- <string>Waterfall</string>
- </property>
- <property name="icon">
- <iconset resource="resources/res.qrc">
- <normaloff>:/waterfall.png</normaloff>:/waterfall.png</iconset>
- </property>
- <property name="checkable">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item row="4" column="3">
- <widget class="QSlider" name="refLevel">
- <property name="toolTip">
- <string>Spectrum reference level</string>
- </property>
- <property name="minimum">
- <number>-9</number>
- </property>
- <property name="maximum">
- <number>0</number>
- </property>
- <property name="singleStep">
- <number>1</number>
- </property>
- <property name="pageStep">
- <number>1</number>
- </property>
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="tickPosition">
- <enum>QSlider::TicksAbove</enum>
- </property>
- <property name="tickInterval">
- <number>1</number>
- </property>
- </widget>
- </item>
- <item row="6" column="3">
- <widget class="QSlider" name="levelRange">
- <property name="toolTip">
- <string>Spectrum range</string>
- </property>
- <property name="minimum">
- <number>1</number>
- </property>
- <property name="maximum">
- <number>10</number>
- </property>
- <property name="singleStep">
- <number>1</number>
- </property>
- <property name="pageStep">
- <number>1</number>
- </property>
- <property name="value">
- <number>10</number>
- </property>
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="tickPosition">
- <enum>QSlider::TicksAbove</enum>
- </property>
- <property name="tickInterval">
- <number>1</number>
- </property>
- </widget>
- </item>
- <item row="7" column="3">
- <widget class="QSlider" name="levelRange_2">
- <property name="enabled">
- <bool>false</bool>
- </property>
- <property name="toolTip">
- <string>Digital phosphor effect decay time</string>
- </property>
- <property name="maximum">
- <number>100</number>
- </property>
- <property name="singleStep">
- <number>10</number>
- </property>
- <property name="pageStep">
- <number>10</number>
- </property>
- <property name="value">
- <number>100</number>
- </property>
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="tickPosition">
- <enum>QSlider::TicksAbove</enum>
- </property>
- <property name="tickInterval">
- <number>10</number>
- </property>
- </widget>
- </item>
- <item row="0" column="2" colspan="7">
- <layout class="QGridLayout" name="gridLayout">
- <property name="margin">
- <number>2</number>
- </property>
- <property name="spacing">
- <number>3</number>
- </property>
- <item row="0" column="0">
- <widget class="QLabel" name="label_15">
- <property name="text">
- <string>FFT Size</string>
- </property>
- </widget>
- </item>
- <item row="0" column="2">
- <widget class="QLabel" name="fftSizeDisplay">
- <property name="minimumSize">
- <size>
- <width>40</width>
- <height>0</height>
- </size>
- </property>
- <property name="text">
- <string>128</string>
- </property>
- <property name="alignment">
- <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
- </property>
- </widget>
- </item>
- <item row="1" column="0">
- <widget class="QLabel" name="label_17">
- <property name="text">
- <string>Window</string>
- </property>
- </widget>
- </item>
- <item row="0" column="1">
- <widget class="QSlider" name="fftSize">
- <property name="toolTip">
- <string>FFT calculation block size</string>
- </property>
- <property name="maximum">
- <number>5</number>
- </property>
- <property name="pageStep">
- <number>1</number>
- </property>
- <property name="orientation">
- <enum>Qt::Horizontal</enum>
- </property>
- <property name="tickPosition">
- <enum>QSlider::TicksAbove</enum>
- </property>
- <property name="tickInterval">
- <number>1</number>
- </property>
- </widget>
- </item>
- <item row="1" column="1" colspan="2">
- <widget class="QComboBox" name="fftWindow">
- <property name="sizePolicy">
- <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="toolTip">
- <string>FFT window function</string>
- </property>
- <property name="sizeAdjustPolicy">
- <enum>QComboBox::AdjustToMinimumContentsLength</enum>
- </property>
- <item>
- <property name="text">
- <string>Bartlett</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>Blackman-Harris</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>Flat Top</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>Hamming</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>Hanning</string>
- </property>
- </item>
- <item>
- <property name="text">
- <string>Rectangle</string>
- </property>
- </item>
- </widget>
- </item>
- <item row="2" column="1" colspan="2">
- <layout class="QHBoxLayout" name="horizontalLayout">
- <property name="spacing">
- <number>3</number>
- </property>
- <item>
- <widget class="QToolButton" name="dcOffset">
- <property name="sizePolicy">
- <sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="toolTip">
- <string>Compensate DC offset</string>
- </property>
- <property name="text">
- <string>DC Offset</string>
- </property>
- <property name="checkable">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- <item>
- <widget class="QToolButton" name="iqImbalance">
- <property name="sizePolicy">
- <sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
- <horstretch>0</horstretch>
- <verstretch>0</verstretch>
- </sizepolicy>
- </property>
- <property name="toolTip">
- <string>Compensate I/Q imbalance</string>
- </property>
- <property name="text">
- <string>I/Q Imbal.</string>
- </property>
- <property name="checkable">
- <bool>true</bool>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- <item row="2" column="0">
- <widget class="QLabel" name="label_18">
- <property name="text">
- <string>Correct</string>
- </property>
- </widget>
- </item>
- </layout>
- </item>
- </layout>
- </widget>
- </widget>
- <widget class="QDockWidget" name="inputDock">
- <property name="windowTitle">
- <string>Input</string>
- </property>
- <attribute name="dockWidgetArea">
- <number>1</number>
- </attribute>
- <widget class="QWidget" name="dockWidgetContents_6"/>
- </widget>
- <action name="action_Exit">
- <property name="text">
- <string>E&amp;xit</string>
- </property>
- <property name="shortcut">
- <string>Ctrl+Q</string>
- </property>
- </action>
- <action name="action_Start">
- <property name="text">
- <string>&amp;Start</string>
- </property>
- <property name="shortcut">
- <string>F5</string>
- </property>
- </action>
- <action name="action_Stop">
- <property name="text">
- <string>&amp;Stop</string>
- </property>
- <property name="shortcut">
- <string>F6</string>
- </property>
- </action>
- <action name="action_Debug">
- <property name="text">
- <string>Debug</string>
- </property>
- <property name="shortcut">
- <string>F10</string>
- </property>
- </action>
- <action name="action_View_Waterfall">
- <property name="checkable">
- <bool>true</bool>
- </property>
- <property name="text">
- <string>&amp;Waterfall</string>
- </property>
- </action>
- <action name="action_View_Histogram">
- <property name="checkable">
- <bool>true</bool>
- </property>
- <property name="text">
- <string>&amp;Histogram</string>
- </property>
- </action>
- <action name="action_View_LiveSpectrum">
- <property name="checkable">
- <bool>true</bool>
- </property>
- <property name="text">
- <string>&amp;Live Spectrum</string>
- </property>
- </action>
- <action name="action_View_Fullscreen">
- <property name="checkable">
- <bool>true</bool>
- </property>
- <property name="text">
- <string>&amp;Fullscreen</string>
- </property>
- <property name="shortcut">
- <string>F11</string>
- </property>
- </action>
- <action name="actionOsmoSDR_Firmware_Upgrade">
- <property name="text">
- <string>OsmoSDR &amp;Firmware Upgrade...</string>
- </property>
- </action>
- <action name="action_Oscilloscope">
- <property name="checkable">
- <bool>true</bool>
- </property>
- <property name="text">
- <string>&amp;Oscilloscope</string>
- </property>
- <property name="shortcut">
- <string>F8</string>
- </property>
- </action>
- <zorder>presetDock</zorder>
- </widget>
- <layoutdefault spacing="6" margin="11"/>
- <customwidgets>
- <customwidget>
- <class>GLSpectrum</class>
- <extends>QWidget</extends>
- <header>gui/glspectrum.h</header>
- <container>1</container>
- </customwidget>
- </customwidgets>
- <tabstops>
- <tabstop>dcOffset</tabstop>
- <tabstop>iqImbalance</tabstop>
- <tabstop>presetTree</tabstop>
- </tabstops>
- <resources>
- <include location="resources/res.qrc"/>
- </resources>
- <connections>
- <connection>
- <sender>action_Exit</sender>
- <signal>triggered()</signal>
- <receiver>MainWindow</receiver>
- <slot>close()</slot>
- <hints>
- <hint type="sourcelabel">
- <x>-1</x>
- <y>-1</y>
- </hint>
- <hint type="destinationlabel">
- <x>462</x>
- <y>332</y>
- </hint>
- </hints>
- </connection>
- </connections>
-</ui>
diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt
new file mode 100644
index 0000000..fffde4b
--- /dev/null
+++ b/plugins/CMakeLists.txt
@@ -0,0 +1,4 @@
+project(plugins)
+
+add_subdirectory(demod)
+add_subdirectory(samplesource)
diff --git a/plugins/demod/CMakeLists.txt b/plugins/demod/CMakeLists.txt
new file mode 100644
index 0000000..78804e6
--- /dev/null
+++ b/plugins/demod/CMakeLists.txt
@@ -0,0 +1,4 @@
+project(demod)
+
+add_subdirectory(nfm)
+add_subdirectory(tetra)
diff --git a/plugins/demod/nfm/CMakeLists.txt b/plugins/demod/nfm/CMakeLists.txt
new file mode 100644
index 0000000..ee36a4d
--- /dev/null
+++ b/plugins/demod/nfm/CMakeLists.txt
@@ -0,0 +1,44 @@
+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)
+
+qt4_wrap_cpp(nfm_HEADERS_MOC ${nfm_HEADERS})
+qt4_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}
+)
diff --git a/dsp/nfmdemod.cpp b/plugins/demod/nfm/nfmdemod.cpp
index a5cbe3e..7324852 100644
--- a/dsp/nfmdemod.cpp
+++ b/plugins/demod/nfm/nfmdemod.cpp
@@ -18,39 +18,40 @@
#include <QTime>
#include <stdio.h>
#include "nfmdemod.h"
-#include "hardware/audiooutput.h"
+#include "audio/audiooutput.h"
+#include "dsp/dspcommands.h"
-static FILE* logFile = NULL;
-static int logLine = 0;
+MessageRegistrator NFMDemod::MsgConfigureNFMDemod::ID("MsgConfigureNFMDemod");
-NFMDemod::NFMDemod()
+NFMDemod::NFMDemod(AudioFifo* audioFifo, SampleSink* sampleSink) :
+ m_sampleSink(sampleSink),
+ m_audioFifo(audioFifo)
{
- m_squelchLevel = pow(10.0, -50.0 / 20.0);
+ m_rfBandwidth = 12500;
+ m_volume = 2.0;
+ m_squelchLevel = pow(10.0, -40.0 / 20.0);
m_sampleRate = 500000;
- m_frequency = -50000;
+ m_frequency = 0;
m_squelchLevel *= m_squelchLevel;
m_nco.setFreq(m_frequency, m_sampleRate);
- m_interpolator.create(51, 32, 32 * m_sampleRate, 12500 / 2);
+ m_interpolator.create(1, 32, 32 * m_sampleRate, 12500);
m_sampleDistanceRemain = (Real)m_sampleRate / 44100.0;
m_lowpass.create(21, 44100, 3000);
- m_audioFifo.setSize(4, 44100 / 4);
- m_audioOutput = new AudioOutput;
m_audioBuffer.resize(256);
m_audioBufferFill = 0;
-
- qDebug("- [%g] -", m_squelchLevel);
-
-
- //logFile = fopen("/tmp/log.txt", "wb");
}
NFMDemod::~NFMDemod()
{
- m_audioOutput->stop();
- delete m_audioOutput;
+}
+
+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)
@@ -60,19 +61,14 @@ void NFMDemod::feed(SampleVector::const_iterator begin, SampleVector::const_iter
Complex ci;
bool consumed;
- if((firstOfBurst) && (logFile != NULL)) {
- uint a = m_audioFifo.fill();
- uint b = m_audioOutput->bufferedSamples();
- fprintf(logFile, "%u %u\n", logLine++, a + b);
- fflush(logFile);
- }
-
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));
+
if((ci.real() * ci.real() + ci.imag() * ci.imag()) >= m_squelchLevel)
m_squelchState = m_sampleRate / 100;
@@ -82,14 +78,15 @@ void NFMDemod::feed(SampleVector::const_iterator begin, SampleVector::const_iter
m_lastSample = ci;
Real demod = atan2(d.imag(), d.real()) / M_PI;
demod = m_lowpass.filter(demod);
- qint16 sample = demod * 32767 * 4;
+ 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()) {
- if(m_audioFifo.write((const quint8*)&m_audioBuffer[0], m_audioBufferFill) != m_audioBufferFill)
- qDebug("lost samples");
+ if(m_audioFifo->write((const quint8*)&m_audioBuffer[0], m_audioBufferFill, 0) != m_audioBufferFill)
+ ;//qDebug("lost samples");
m_audioBufferFill = 0;
}
}
@@ -97,31 +94,47 @@ void NFMDemod::feed(SampleVector::const_iterator begin, SampleVector::const_iter
m_sampleDistanceRemain += (Real)m_sampleRate / 44100.0;
}
}
- if(m_audioFifo.write((const quint8*)&m_audioBuffer[0], m_audioBufferFill) != m_audioBufferFill)
- qDebug("lost samples");
+ 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_audioOutput->start(0, 44100, &m_audioFifo);
m_squelchState = 0;
}
void NFMDemod::stop()
{
- m_audioOutput->stop();
-}
-
-void NFMDemod::setSampleRate(int sampleRate)
-{
- m_sampleRate = sampleRate;
- m_nco.setFreq(m_frequency, m_sampleRate);
- m_interpolator.create(51, 32, 32 * m_sampleRate, 12500 / 2);
- m_sampleDistanceRemain = m_sampleRate / 44100.0;
- m_squelchState = 0;
}
-void NFMDemod::handleMessage(Message* cmd)
+bool NFMDemod::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(25, 32, 32 * m_sampleRate, m_rfBandwidth / 2.0);
+ m_sampleDistanceRemain = m_sampleRate / 44100.0;
+ m_squelchState = 0;
+ cmd->completed();
+ return true;
+ } else if(cmd->id() == MsgConfigureNFMDemod::ID()) {
+ MsgConfigureNFMDemod* cfg = (MsgConfigureNFMDemod*)cmd;
+ m_rfBandwidth = cfg->getRFBandwidth();
+ m_interpolator.create(25, 32, 32 * m_sampleRate, m_rfBandwidth / 2.0);
+ 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 {
+ return false;
+ }
}
diff --git a/plugins/demod/nfm/nfmdemod.h b/plugins/demod/nfm/nfmdemod.h
new file mode 100644
index 0000000..c3e1e6e
--- /dev/null
+++ b/plugins/demod/nfm/nfmdemod.h
@@ -0,0 +1,102 @@
+///////////////////////////////////////////////////////////////////////////////////
+// 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 <http://www.gnu.org/licenses/>. //
+///////////////////////////////////////////////////////////////////////////////////
+
+#ifndef INCLUDE_NFMDEMOD_H
+#define INCLUDE_NFMDEMOD_H
+
+#include <vector>
+#include "dsp/samplesink.h"
+#include "dsp/nco.h"
+#include "dsp/interpolator.h"
+#include "dsp/lowpass.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 {
+ public:
+ static MessageRegistrator ID;
+
+ 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(ID()),
+ m_rfBandwidth(rfBandwidth),
+ m_afBandwidth(afBandwidth),
+ m_volume(volume),
+ m_squelch(squelch)
+ { }
+ };
+
+ struct AudioSample {
+ qint16 l;
+ qint16 r;
+ };
+ typedef std::vector<AudioSample> 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<Real> m_lowpass;
+
+ int m_squelchState;
+
+ Complex m_lastSample;
+
+ AudioVector m_audioBuffer;
+ uint m_audioBufferFill;
+ AudioFifo* m_audioFifo;
+
+ SampleSink* m_sampleSink;
+ SampleVector m_sampleBuffer;
+};
+
+#endif // INCLUDE_NFMDEMOD_H
diff --git a/plugins/demod/nfm/nfmdemodgui.cpp b/plugins/demod/nfm/nfmdemodgui.cpp
new file mode 100644
index 0000000..a630dd4
--- /dev/null
+++ b/plugins/demod/nfm/nfmdemodgui.cpp
@@ -0,0 +1,179 @@
+#include <QDockWidget>
+#include <QMainWindow>
+#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"
+
+const int NFMDemodGUI::m_rfBW[] = {
+ 5000, 6250, 8330, 10000, 12500, 15000, 20000, 25000, 40000
+};
+
+NFMDemodGUI* NFMDemodGUI::create(PluginAPI* pluginAPI)
+{
+ QDockWidget* dock = pluginAPI->createMainWindowDock(Qt::RightDockWidgetArea, tr("NFM Demodulator"));
+ dock->setObjectName(QString::fromUtf8("NFM Demodulator"));
+ NFMDemodGUI* gui = new NFMDemodGUI(pluginAPI, dock);
+ dock->setWidget(gui);
+ return gui;
+}
+
+void NFMDemodGUI::destroy()
+{
+ delete m_dockWidget;
+}
+
+void NFMDemodGUI::setWidgetName(const QString& name)
+{
+ qDebug("NFM: %s", qPrintable(name));
+ m_dockWidget->setObjectName(name);
+}
+
+void NFMDemodGUI::resetToDefaults()
+{
+ ui->rfBW->setValue(4);
+ ui->afBW->setValue(3);
+ ui->volume->setValue(20);
+ ui->squelch->setValue(-40);
+ 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());
+ return s.final();
+}
+
+bool NFMDemodGUI::deserialize(const QByteArray& data)
+{
+ SimpleDeserializer d(data);
+
+ if(!d.isValid()) {
+ resetToDefaults();
+ return false;
+ }
+
+ if(d.getVersion() == 1) {
+ 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);
+ 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();
+}
+
+NFMDemodGUI::NFMDemodGUI(PluginAPI* pluginAPI, QDockWidget* dockWidget, QWidget* parent) :
+ PluginGUI(parent),
+ ui(new Ui::NFMDemodGUI),
+ m_pluginAPI(pluginAPI),
+ m_dockWidget(dockWidget)
+{
+ ui->setupUi(this);
+
+ 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->setDisplayLiveSpectrum(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);
+
+ applySettings();
+}
+
+NFMDemodGUI::~NFMDemodGUI()
+{
+ 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()
+{
+ 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/demod/nfm/nfmdemodgui.h b/plugins/demod/nfm/nfmdemodgui.h
new file mode 100644
index 0000000..1381b5a
--- /dev/null
+++ b/plugins/demod/nfm/nfmdemodgui.h
@@ -0,0 +1,64 @@
+#ifndef INCLUDE_NFMDEMODGUI_H
+#define INCLUDE_NFMDEMODGUI_H
+
+#include "plugin/plugingui.h"
+
+class QDockWidget;
+
+class PluginAPI;
+class ChannelMarker;
+
+class AudioFifo;
+class ThreadedSampleSink;
+class Channelizer;
+class NFMDemod;
+class SpectrumVis;
+
+namespace Ui {
+ class NFMDemodGUI;
+}
+
+class NFMDemodGUI : public PluginGUI {
+ Q_OBJECT
+
+public:
+ static NFMDemodGUI* create(PluginAPI* pluginAPI);
+ void destroy();
+
+ void setWidgetName(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);
+
+private:
+ Ui::NFMDemodGUI* ui;
+ PluginAPI* m_pluginAPI;
+ QDockWidget* m_dockWidget;
+ ChannelMarker* m_channelMarker;
+
+ AudioFifo* m_audioFifo;
+ ThreadedSampleSink* m_threadedSampleSink;
+ Channelizer* m_channelizer;
+ NFMDemod* m_nfmDemod;
+ SpectrumVis* m_spectrumVis;
+
+ static const QString m_demodName;
+ static const int m_rfBW[];
+
+ explicit NFMDemodGUI(PluginAPI* pluginAPI, QDockWidget* dockWidget, QWidget* parent = NULL);
+ ~NFMDemodGUI();
+
+ void applySettings();
+};
+
+#endif // INCLUDE_NFMDEMODGUI_H
diff --git a/plugins/demod/nfm/nfmdemodgui.ui b/plugins/demod/nfm/nfmdemodgui.ui
new file mode 100644
index 0000000..5087276
--- /dev/null
+++ b/plugins/demod/nfm/nfmdemodgui.ui
@@ -0,0 +1,211 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>NFMDemodGUI</class>
+ <widget class="QWidget" name="NFMDemodGUI">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>208</width>
+ <height>226</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QVBoxLayout">
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <property name="margin">
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="GLSpectrum" name="glSpectrum" native="true">
+ <property name="minimumSize">
+ <size>
+ <width>200</width>
+ <height>150</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QGridLayout" name="gridLayout">
+ <property name="margin">
+ <number>2</number>
+ </property>
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <item row="0" column="1">
+ <widget class="QSlider" name="rfBW">
+ <property name="maximum">
+ <number>8</number>
+ </property>
+ <property name="pageStep">
+ <number>1</number>
+ </property>
+ <property name="value">
+ <number>4</number>
+ </property>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>RF Bandwidth</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_2">
+ <property name="text">
+ <string>AF Bandwidth</string>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="0">
+ <widget class="QLabel" name="label_4">
+ <property name="text">
+ <string>Squelch</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="label_3">
+ <property name="text">
+ <string>Volume</string>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="2">
+ <widget class="QLabel" name="rfBWText">
+ <property name="minimumSize">
+ <size>
+ <width>50</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>12.5kHz</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QSlider" name="afBW">
+ <property name="minimum">
+ <number>1</number>
+ </property>
+ <property name="maximum">
+ <number>20</number>
+ </property>
+ <property name="pageStep">
+ <number>1</number>
+ </property>
+ <property name="value">
+ <number>3</number>
+ </property>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QSlider" name="volume">
+ <property name="maximum">
+ <number>100</number>
+ </property>
+ <property name="value">
+ <number>20</number>
+ </property>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="1">
+ <widget class="QSlider" name="squelch">
+ <property name="minimum">
+ <number>-100</number>
+ </property>
+ <property name="maximum">
+ <number>0</number>
+ </property>
+ <property name="value">
+ <number>-40</number>
+ </property>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="2">
+ <widget class="QLabel" name="afBWText">
+ <property name="minimumSize">
+ <size>
+ <width>50</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>3 kHz</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="2">
+ <widget class="QLabel" name="volumeText">
+ <property name="minimumSize">
+ <size>
+ <width>50</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>2.0</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="4" column="2">
+ <widget class="QLabel" name="squelchText">
+ <property name="minimumSize">
+ <size>
+ <width>50</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>-40dB</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>GLSpectrum</class>
+ <extends>QWidget</extends>
+ <header>gui/glspectrum.h</header>
+ <container>1</container>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/plugins/demod/nfm/nfmplugin.cpp b/plugins/demod/nfm/nfmplugin.cpp
new file mode 100644
index 0000000..6c1c063
--- /dev/null
+++ b/plugins/demod/nfm/nfmplugin.cpp
@@ -0,0 +1,52 @@
+#include <QtPlugin>
+#include <QAction>
+#include "plugin/pluginapi.h"
+#include "nfmplugin.h"
+#include "nfmdemodgui.h"
+
+const PluginDescriptor NFMPlugin::m_pluginDescriptor = {
+ displayedName: QString("NFM Demodulator"),
+ version: QString("---"),
+ copyright: QString("(c) maintech GmbH (written by Christian Daniel)"),
+ website: QString("http://www.maintech.de"),
+ licenseIsGPL: true,
+ sourceCodeURL: 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"), this);
+ connect(action, SIGNAL(triggered()), this, SLOT(createInstanceNFM()));
+ m_pluginAPI->registerDemodulator("de.maintech.sdrangelove.demod.nfm", this, action);
+}
+
+PluginGUI* NFMPlugin::createDemod(const QString& demodName)
+{
+ if(demodName == "de.maintech.sdrangelove.demod.nfm") {
+ PluginGUI* gui = NFMDemodGUI::create(m_pluginAPI);
+ m_pluginAPI->registerDemodulatorInstance("de.maintech.sdrangelove.demod.nfm", gui);
+ return gui;
+ } else {
+ return NULL;
+ }
+}
+
+void NFMPlugin::createInstanceNFM()
+{
+ m_pluginAPI->registerDemodulatorInstance("de.maintech.sdrangelove.demod.nfm", NFMDemodGUI::create(m_pluginAPI));
+}
+
+Q_EXPORT_PLUGIN2(nfmPlugin, NFMPlugin);
diff --git a/plugins/demod/nfm/nfmplugin.h b/plugins/demod/nfm/nfmplugin.h
new file mode 100644
index 0000000..18e6c40
--- /dev/null
+++ b/plugins/demod/nfm/nfmplugin.h
@@ -0,0 +1,28 @@
+#ifndef INCLUDE_NFMPLUGIN_H
+#define INCLUDE_NFMPLUGIN_H
+
+#include <QObject>
+#include "plugin/plugininterface.h"
+
+class NFMPlugin : public QObject, PluginInterface {
+ Q_OBJECT
+ Q_INTERFACES(PluginInterface)
+
+public:
+ explicit NFMPlugin(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 createInstanceNFM();
+};
+
+#endif // INCLUDE_NFMPLUGIN_H
diff --git a/plugins/demod/tetra/CMakeLists.txt b/plugins/demod/tetra/CMakeLists.txt
new file mode 100644
index 0000000..7d1612a
--- /dev/null
+++ b/plugins/demod/tetra/CMakeLists.txt
@@ -0,0 +1,44 @@
+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)
+
+qt4_wrap_cpp(tetra_HEADERS_MOC ${tetra_HEADERS})
+qt4_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}
+)
diff --git a/plugins/demod/tetra/tetrademod.cpp b/plugins/demod/tetra/tetrademod.cpp
new file mode 100644
index 0000000..4cf8ea1
--- /dev/null
+++ b/plugins/demod/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 <http://www.gnu.org/licenses/>. //
+///////////////////////////////////////////////////////////////////////////////////
+
+#include <stdio.h>
+#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(1, 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(51, 32, 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/dsp/nfmdemod.h b/plugins/demod/tetra/tetrademod.h
index 1f23e15..a2a474b 100644
--- a/dsp/nfmdemod.h
+++ b/plugins/demod/tetra/tetrademod.h
@@ -15,54 +15,53 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
-#ifndef INCLUDE_NFMDEMOD_H
-#define INCLUDE_NFMDEMOD_H
+#ifndef INCLUDE_TETRADEMOD_H
+#define INCLUDE_TETRADEMOD_H
-#include <vector>
-#include "samplesink.h"
-#include "nco.h"
-#include "interpolator.h"
-#include "lowpass.h"
-#include "pidcontroller.h"
-#include "hardware/audiofifo.h"
+#include "dsp/samplesink.h"
+#include "dsp/nco.h"
+#include "dsp/interpolator.h"
+#include "util/message.h"
-class AudioOutput;
+class MessageQueue;
-class NFMDemod : public SampleSink {
+class TetraDemod : public SampleSink {
public:
- NFMDemod();
- ~NFMDemod();
+ TetraDemod(SampleSink* sampleSink);
+ ~TetraDemod();
+
+ void configure(MessageQueue* messageQueue);
void feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst);
void start();
void stop();
- void setSampleRate(int sampleRate);
- void handleMessage(Message* cmd);
+ bool handleMessage(Message* cmd);
private:
- struct AudioSample {
- qint16 l;
- qint16 r;
+ class MsgConfigureTetraDemod : public Message {
+ public:
+ static MessageRegistrator ID;
+
+ static MsgConfigureTetraDemod* create()
+ {
+ return new MsgConfigureTetraDemod();
+ }
+
+ private:
+ MsgConfigureTetraDemod() :
+ Message(ID())
+ { }
};
- typedef std::vector<AudioSample> AudioVector;
- Real m_squelchLevel;
int m_sampleRate;
int m_frequency;
NCO m_nco;
Interpolator m_interpolator;
Real m_sampleDistanceRemain;
- Lowpass<Real> m_lowpass;
-
- int m_squelchState;
-
- Complex m_lastSample;
- AudioVector m_audioBuffer;
- uint m_audioBufferFill;
- AudioOutput* m_audioOutput;
- AudioFifo m_audioFifo;
+ SampleSink* m_sampleSink;
+ SampleVector m_sampleBuffer;
};
-#endif // INCLUDE_NFMDEMOD_H
+#endif // INCLUDE_TETRADEMOD_H
diff --git a/plugins/demod/tetra/tetrademodgui.cpp b/plugins/demod/tetra/tetrademodgui.cpp
new file mode 100644
index 0000000..a0659b5
--- /dev/null
+++ b/plugins/demod/tetra/tetrademodgui.cpp
@@ -0,0 +1,110 @@
+#include <QDockWidget>
+#include <QMainWindow>
+#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->setDisplayLiveSpectrum(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/demod/tetra/tetrademodgui.h b/plugins/demod/tetra/tetrademodgui.h
new file mode 100644
index 0000000..9eacae6
--- /dev/null
+++ b/plugins/demod/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/demod/tetra/tetrademodgui.ui b/plugins/demod/tetra/tetrademodgui.ui
new file mode 100644
index 0000000..feaef10
--- /dev/null
+++ b/plugins/demod/tetra/tetrademodgui.ui
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>TetraDemodGUI</class>
+ <widget class="QWidget" name="TetraDemodGUI">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>200</width>
+ <height>179</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Form</string>
+ </property>
+ <layout class="QVBoxLayout">
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <property name="margin">
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="GLSpectrum" name="glSpectrum" native="true">
+ <property name="minimumSize">
+ <size>
+ <width>200</width>
+ <height>150</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <item>
+ <widget class="QPushButton" name="test">
+ <property name="text">
+ <string/>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <customwidgets>
+ <customwidget>
+ <class>GLSpectrum</class>
+ <extends>QWidget</extends>
+ <header>gui/glspectrum.h</header>
+ <container>1</container>
+ </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
diff --git a/plugins/demod/tetra/tetraplugin.cpp b/plugins/demod/tetra/tetraplugin.cpp
new file mode 100644
index 0000000..fe63e98
--- /dev/null
+++ b/plugins/demod/tetra/tetraplugin.cpp
@@ -0,0 +1,52 @@
+#include <QtPlugin>
+#include <QAction>
+#include "plugin/pluginapi.h"
+#include "tetraplugin.h"
+#include "tetrademodgui.h"
+
+const PluginDescriptor TetraPlugin::m_pluginDescriptor = {
+ displayedName: QString("Tetra Demodulator"),
+ version: QString("---"),
+ copyright: QString("(c) maintech GmbH (written by Christian Daniel)"),
+ website: QString("http://www.maintech.de"),
+ licenseIsGPL: true,
+ sourceCodeURL: 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));
+}
+
+Q_EXPORT_PLUGIN2(tetraPlugin, TetraPlugin);
diff --git a/plugins/demod/tetra/tetraplugin.h b/plugins/demod/tetra/tetraplugin.h
new file mode 100644
index 0000000..b3b6fd1
--- /dev/null
+++ b/plugins/demod/tetra/tetraplugin.h
@@ -0,0 +1,28 @@
+#ifndef INCLUDE_TETRAPLUGIN_H
+#define INCLUDE_TETRAPLUGIN_H
+
+#include <QObject>
+#include "plugin/plugininterface.h"
+
+class TetraPlugin : public QObject, PluginInterface {
+ Q_OBJECT
+ Q_INTERFACES(PluginInterface)
+
+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 0000000..1a82fc6
--- /dev/null
+++ b/plugins/samplesource/CMakeLists.txt
@@ -0,0 +1,7 @@
+project(samplesource)
+
+find_package(LibOsmoSDR REQUIRED)
+find_package(LibRTLSDR REQUIRED)
+
+add_subdirectory(osmosdr)
+add_subdirectory(rtlsdr)
diff --git a/plugins/samplesource/osmosdr/CMakeLists.txt b/plugins/samplesource/osmosdr/CMakeLists.txt
new file mode 100644
index 0000000..d3b1b61
--- /dev/null
+++ b/plugins/samplesource/osmosdr/CMakeLists.txt
@@ -0,0 +1,47 @@
+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)
+
+qt4_wrap_cpp(osmosdr_HEADERS_MOC ${osmosdr_HEADERS})
+qt4_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}
+)
diff --git a/plugins/samplesource/osmosdr/osmosdrgui.cpp b/plugins/samplesource/osmosdr/osmosdrgui.cpp
new file mode 100644
index 0000000..ddaf4d3
--- /dev/null
+++ b/plugins/samplesource/osmosdr/osmosdrgui.cpp
@@ -0,0 +1,305 @@
+#include "osmosdrgui.h"
+#include "ui_osmosdrgui.h"
+#include "plugin/pluginapi.h"
+
+OsmoSDRGui::OsmoSDRGui(PluginAPI* pluginAPI, QWidget* parent) :
+ PluginGUI(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::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/hardware/osmosdr/osmosdrgui.h b/plugins/samplesource/osmosdr/osmosdrgui.h
index 2882a54..770b48e 100644
--- a/hardware/osmosdr/osmosdrgui.h
+++ b/plugins/samplesource/osmosdr/osmosdrgui.h
@@ -2,31 +2,48 @@
#define INCLUDE_OSMOSDRGUI_H
#include <QTimer>
-#include "../samplesourcegui.h"
+#include "plugin/plugingui.h"
#include "osmosdrinput.h"
+class PluginAPI;
+
namespace Ui {
class OsmoSDRGui;
}
-class OsmoSDRGui : public SampleSourceGUI {
+class OsmoSDRGui : public PluginGUI {
Q_OBJECT
public:
- explicit OsmoSDRGui(MessageQueue* msgQueue, QWidget* parent = NULL);
+ explicit OsmoSDRGui(PluginAPI* pluginAPI, QWidget* parent = NULL);
~OsmoSDRGui();
+ void destroy();
- QString serializeSettings() const;
- bool deserializeSettings(const QString& settings);
-
- void handleSourceMessage(DSPCmdSourceToGUI* cmd);
+ 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;
MessageQueue* m_msgQueue;
OsmoSDRInput::Settings m_settings;
QTimer m_updateTimer;
+ */
+
+ Ui::OsmoSDRGui* ui;
+
+ PluginAPI* m_pluginAPI;
+ SampleSource::GeneralSettings m_generalSettings;
+ OsmoSDRInput::Settings m_settings;
+ QTimer m_updateTimer;
+ std::vector<int> m_gains;
+ SampleSource* m_sampleSource;
void displaySettings();
void sendSettings();
diff --git a/hardware/osmosdr/osmosdrgui.ui b/plugins/samplesource/osmosdr/osmosdrgui.ui
index 1ad4a88..1ad4a88 100644
--- a/hardware/osmosdr/osmosdrgui.ui
+++ b/plugins/samplesource/osmosdr/osmosdrgui.ui
diff --git a/hardware/osmosdr/osmosdrinput.cpp b/plugins/samplesource/osmosdr/osmosdrinput.cpp
index 702f39f..8e724cf 100644
--- a/hardware/osmosdr/osmosdrinput.cpp
+++ b/plugins/samplesource/osmosdr/osmosdrinput.cpp
@@ -20,26 +20,110 @@
#include "osmosdrinput.h"
#include "osmosdrthread.h"
#include "osmosdrgui.h"
+#include "util/simpleserializer.h"
+
+MessageRegistrator OsmoSDRInput::MsgConfigureOsmoSDR::ID("MsgConfigureOsmoSDR");
OsmoSDRInput::Settings::Settings() :
- centerFrequency(100000000),
- swapIQ(false),
- decimation(3),
- lnaGain(-50),
- mixerGain(40),
- mixerEnhancement(0),
- if1gain(-30),
- if2gain(0),
- if3gain(0),
- if4gain(0),
- if5gain(30),
- if6gain(30),
- opAmpI1(0),
- opAmpI2(0),
- opAmpQ1(0),
- opAmpQ2(0),
- dcOfsI(0),
- dcOfsQ(0)
+ 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() :
{
}
@@ -138,6 +222,8 @@ bool OsmoSDRInput::Settings::deserialize(const QString& settings)
}
}
+MessageRegistrator OsmoSDRInput::MsgConfigureSourceOsmoSDR::ID("MsgConfigureSourceOsmoSDR");
+#endif
OsmoSDRInput::OsmoSDRInput(MessageQueue* msgQueueToGUI) :
SampleSource(msgQueueToGUI),
m_settings(),
@@ -201,7 +287,7 @@ bool OsmoSDRInput::startInput(int device)
m_osmoSDRThread->startWork();
mutexLocker.unlock();
- applySettings(m_settings, true);
+ applySettings(m_generalSettings, m_settings, true);
qDebug("OsmoSDRInput: start");
@@ -235,154 +321,159 @@ const QString& OsmoSDRInput::getDeviceDescription() const
int OsmoSDRInput::getSampleRate() const
{
- return 4000000 / (1 << m_settings.decimation);
+ return 4000000 / (1 << m_settings.m_decimation);
}
quint64 OsmoSDRInput::getCenterFrequency() const
{
- return m_settings.centerFrequency;
+ return m_generalSettings.m_centerFrequency;
}
-SampleSourceGUI* OsmoSDRInput::createGUI(MessageQueue* msgQueueToEngine, QWidget* parent) const
+bool OsmoSDRInput::handleMessage(Message* message)
{
- return new OsmoSDRGui(msgQueueToEngine, parent);
-}
+ if(message->id() == MsgConfigureOsmoSDR::ID()) {
+ MsgConfigureOsmoSDR* conf = (MsgConfigureOsmoSDR*)message;
+ if(!applySettings(conf->getGeneralSettings(), conf->getSettings(), false))
+ qDebug("OsmoSDR config error");
+ message->completed();
+ return true;
+ } else {
+ return false;
+ }
-void OsmoSDRInput::handleGUIMessage(DSPCmdGUIToSource* cmd)
-{
+ /*
if(cmd->sourceType() != DSPCmdConfigureSourceOsmoSDR::SourceType)
- return;
+ return false;
if(!applySettings(((DSPCmdConfigureSourceOsmoSDR*)cmd)->getSettings(), false))
qDebug("OsmoSDR config error");
+ cmd->completed();
+ return true;
+ */
+ return false;
}
-bool OsmoSDRInput::applySettings(const Settings& settings, bool force)
+bool OsmoSDRInput::applySettings(const GeneralSettings& generalSettings, const Settings& settings, bool force)
{
QMutexLocker mutexLocker(&m_mutex);
- if((m_settings.centerFrequency != settings.centerFrequency) || force) {
- m_settings.centerFrequency = settings.centerFrequency;
+ 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_settings.centerFrequency) != 0)
- qDebug("osmosdr_set_center_freq(%lld) failed", m_settings.centerFrequency);
+ 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.swapIQ != settings.swapIQ) || force) {
- m_settings.swapIQ = settings.swapIQ;
+ 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.swapIQ ? 1 : 0) == 0)
+ 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.decimation != settings.decimation) || force) {
- m_settings.decimation = settings.decimation;
+ 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.decimation))
+ if(!osmosdr_set_fpga_decimation(m_dev, m_settings.m_decimation))
qDebug("osmosdr_set_fpga_decimation() failed");
}
}
- if((m_settings.lnaGain != settings.lnaGain) || force) {
- m_settings.lnaGain = settings.lnaGain;
+ 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.lnaGain))
+ if(!osmosdr_set_tuner_lna_gain(m_dev, m_settings.m_lnaGain))
qDebug("osmosdr_set_tuner_lna_gain() failed");
}
}
- if((m_settings.mixerGain != settings.mixerGain) || force) {
- m_settings.mixerGain = settings.mixerGain;
+ 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.mixerGain))
+ if(!osmosdr_set_tuner_mixer_gain(m_dev, m_settings.m_mixerGain))
qDebug("osmosdr_set_tuner_mixer_gain() failed");
}
}
- if((m_settings.mixerEnhancement != settings.mixerEnhancement) || force) {
- m_settings.mixerEnhancement = settings.mixerEnhancement;
+ 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.mixerEnhancement))
+ if(!osmosdr_set_tuner_mixer_enh(m_dev, m_settings.m_mixerEnhancement))
qDebug("osmosdr_set_tuner_mixer_enh() failed");
}
}
- if((m_settings.if1gain != settings.if1gain) || force) {
- m_settings.if1gain = settings.if1gain;
+ 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.if1gain))
+ if(!osmosdr_set_tuner_if_gain(m_dev, 1, m_settings.m_if1gain))
qDebug("osmosdr_set_tuner_if_gain(1) failed");
}
}
- if((m_settings.if2gain != settings.if2gain) || force) {
- m_settings.if2gain = settings.if2gain;
+ 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.if2gain))
+ if(!osmosdr_set_tuner_if_gain(m_dev, 2, m_settings.m_if2gain))
qDebug("osmosdr_set_tuner_if_gain(2) failed");
}
}
- if((m_settings.if3gain != settings.if3gain) || force) {
- m_settings.if3gain = settings.if3gain;
+ 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.if3gain))
+ if(!osmosdr_set_tuner_if_gain(m_dev, 3, m_settings.m_if3gain))
qDebug("osmosdr_set_tuner_if_gain(3) failed");
}
}
- if((m_settings.if4gain != settings.if4gain) || force) {
- m_settings.if4gain = settings.if4gain;
+ 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.if4gain))
+ if(!osmosdr_set_tuner_if_gain(m_dev, 4, m_settings.m_if4gain))
qDebug("osmosdr_set_tuner_if_gain(4) failed");
}
}
- if((m_settings.if5gain != settings.if5gain) || force) {
- m_settings.if5gain = settings.if5gain;
+ 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.if5gain))
+ if(!osmosdr_set_tuner_if_gain(m_dev, 5, m_settings.m_if5gain))
qDebug("osmosdr_set_tuner_if_gain(5) failed");
}
}
- if((m_settings.if6gain != settings.if6gain) || force) {
- m_settings.if6gain = settings.if6gain;
+ 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.if6gain))
+ if(!osmosdr_set_tuner_if_gain(m_dev, 6, m_settings.m_if6gain))
qDebug("osmosdr_set_tuner_if_gain(6) failed");
}
}
- if((m_settings.opAmpI1 != settings.opAmpI1) || (m_settings.opAmpI2 != settings.opAmpI2) ||
- (m_settings.opAmpQ1 != settings.opAmpQ1) || (m_settings.opAmpQ2 != settings.opAmpQ2) ||
+ 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.opAmpI1 = settings.opAmpI1;
- m_settings.opAmpI2 = settings.opAmpI2;
- m_settings.opAmpQ1 = settings.opAmpQ1;
- m_settings.opAmpQ2 = settings.opAmpQ2;
+ 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.opAmpI1, m_settings.opAmpI2, m_settings.opAmpQ1, m_settings.opAmpQ2))
+ 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.dcOfsI != settings.dcOfsI) || (m_settings.dcOfsQ != settings.dcOfsQ) ||
+ if((m_settings.m_dcOfsI != settings.m_dcOfsI) || (m_settings.m_dcOfsQ != settings.m_dcOfsQ) ||
force) {
- m_settings.dcOfsI = settings.dcOfsI;
- m_settings.dcOfsQ = settings.dcOfsQ;
+ 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.dcOfsI, m_settings.dcOfsQ))
+ 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;
}
-
-int DSPCmdConfigureSourceOsmoSDR::sourceType() const
-{
- return SourceType;
-}
diff --git a/hardware/osmosdr/osmosdrinput.h b/plugins/samplesource/osmosdr/osmosdrinput.h
index 069e03d..9cea94d 100644
--- a/hardware/osmosdr/osmosdrinput.h
+++ b/plugins/samplesource/osmosdr/osmosdrinput.h
@@ -18,7 +18,7 @@
#ifndef INCLUDE_OSMOSDRINPUT_H
#define INCLUDE_OSMOSDRINPUT_H
-#include "../samplesource.h"
+#include "dsp/samplesource/samplesource.h"
#include <osmosdr.h>
#include <QString>
@@ -27,28 +27,51 @@ class OsmoSDRThread;
class OsmoSDRInput : public SampleSource {
public:
struct Settings {
- quint64 centerFrequency;
- bool swapIQ;
- int decimation;
- int lnaGain;
- int mixerGain;
- int mixerEnhancement;
- int if1gain;
- int if2gain;
- int if3gain;
- int if4gain;
- int if5gain;
- int if6gain;
- int opAmpI1;
- int opAmpI2;
- int opAmpQ1;
- int opAmpQ2;
- int dcOfsI;
- int dcOfsQ;
+ 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();
- QString serialize() const;
- bool deserialize(const QString& settings);
+ void resetToDefaults();
+ QByteArray serialize() const;
+ bool deserialize(const QByteArray& data);
+ };
+
+ class MsgConfigureOsmoSDR : public Message {
+ public:
+ static MessageRegistrator ID;
+
+ 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(ID()),
+ m_generalSettings(generalSettings),
+ m_settings(settings)
+ { }
};
OsmoSDRInput(MessageQueue* msgQueueToGUI);
@@ -61,9 +84,7 @@ public:
int getSampleRate() const;
quint64 getCenterFrequency() const;
- SampleSourceGUI* createGUI(MessageQueue* msgQueueToEngine, QWidget* parent = NULL) const;
-
- void handleGUIMessage(DSPCmdGUIToSource* cmd);
+ bool handleMessage(Message* message);
private:
QMutex m_mutex;
@@ -72,27 +93,7 @@ private:
OsmoSDRThread* m_osmoSDRThread;
QString m_deviceDescription;
- bool applySettings(const Settings& settings, bool force);
-};
-
-class DSPCmdConfigureSourceOsmoSDR : public DSPCmdGUIToSource {
-public:
- enum {
- SourceType = 1
- };
-
- int sourceType() const;
- const OsmoSDRInput::Settings& getSettings() const { return m_settings; }
-
- static DSPCmdConfigureSourceOsmoSDR* create(const OsmoSDRInput::Settings& settings)
- {
- return new DSPCmdConfigureSourceOsmoSDR(settings);
- }
-
-protected:
- OsmoSDRInput::Settings m_settings;
-
- DSPCmdConfigureSourceOsmoSDR(const OsmoSDRInput::Settings& settings) : m_settings(settings) { }
+ 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 0000000..2b06922
--- /dev/null
+++ b/plugins/samplesource/osmosdr/osmosdrplugin.cpp
@@ -0,0 +1,67 @@
+#include <QtPlugin>
+#include <QAction>
+#include <osmosdr.h>
+#include "plugin/pluginapi.h"
+#include "util/simpleserializer.h"
+#include "osmosdrplugin.h"
+#include "osmosdrgui.h"
+
+const PluginDescriptor OsmoSDRPlugin::m_pluginDescriptor = {
+ displayedName: QString("OsmoSDR Input"),
+ version: QString("---"),
+ copyright: QString("(c) Christian Daniel"),
+ website: QString("http://sdr.osmocom.org/trac/wiki/osmo-sdr"),
+ licenseIsGPL: true,
+ sourceCodeURL: 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));
+ 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") {
+ return new OsmoSDRGui(m_pluginAPI);
+ } else {
+ return NULL;
+ }
+}
+
+Q_EXPORT_PLUGIN2(osmosdrPlugin, OsmoSDRPlugin);
diff --git a/plugins/samplesource/osmosdr/osmosdrplugin.h b/plugins/samplesource/osmosdr/osmosdrplugin.h
new file mode 100644
index 0000000..65f541b
--- /dev/null
+++ b/plugins/samplesource/osmosdr/osmosdrplugin.h
@@ -0,0 +1,26 @@
+#ifndef INCLUDE_OSMOSDRPLUGIN_H
+#define INCLUDE_OSMOSDRPLUGIN_H
+
+#include <QObject>
+#include "plugin/plugininterface.h"
+
+class OsmoSDRPlugin : public QObject, PluginInterface {
+ Q_OBJECT
+ Q_INTERFACES(PluginInterface)
+
+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/hardware/osmosdr/osmosdrthread.cpp b/plugins/samplesource/osmosdr/osmosdrthread.cpp
index 74790a1..25fcfdb 100644
--- a/hardware/osmosdr/osmosdrthread.cpp
+++ b/plugins/samplesource/osmosdr/osmosdrthread.cpp
@@ -18,7 +18,7 @@
#include <stdio.h>
#include <errno.h>
#include "osmosdrthread.h"
-#include "../samplefifo.h"
+#include "dsp/samplefifo.h"
OsmoSDRThread::OsmoSDRThread(osmosdr_dev_t* dev, SampleFifo* sampleFifo, QObject* parent) :
QThread(parent),
diff --git a/hardware/osmosdr/osmosdrthread.h b/plugins/samplesource/osmosdr/osmosdrthread.h
index 0aa0142..0aa0142 100644
--- a/hardware/osmosdr/osmosdrthread.h
+++ b/plugins/samplesource/osmosdr/osmosdrthread.h
diff --git a/hardware/osmosdr/osmosdrupgrade.cpp b/plugins/samplesource/osmosdr/osmosdrupgrade.cpp
index bba600b..bba600b 100644
--- a/hardware/osmosdr/osmosdrupgrade.cpp
+++ b/plugins/samplesource/osmosdr/osmosdrupgrade.cpp
diff --git a/hardware/osmosdr/osmosdrupgrade.h b/plugins/samplesource/osmosdr/osmosdrupgrade.h
index efd930b..efd930b 100644
--- a/hardware/osmosdr/osmosdrupgrade.h
+++ b/plugins/samplesource/osmosdr/osmosdrupgrade.h
diff --git a/hardware/osmosdr/osmosdrupgrade.ui b/plugins/samplesource/osmosdr/osmosdrupgrade.ui
index fbb2939..fbb2939 100644
--- a/hardware/osmosdr/osmosdrupgrade.ui
+++ b/plugins/samplesource/osmosdr/osmosdrupgrade.ui
diff --git a/plugins/samplesource/rtlsdr/CMakeLists.txt b/plugins/samplesource/rtlsdr/CMakeLists.txt
new file mode 100644
index 0000000..916bded
--- /dev/null
+++ b/plugins/samplesource/rtlsdr/CMakeLists.txt
@@ -0,0 +1,47 @@
+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})
+qt4_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}
+)
diff --git a/plugins/samplesource/rtlsdr/rtlsdrgui.cpp b/plugins/samplesource/rtlsdr/rtlsdrgui.cpp
new file mode 100644
index 0000000..a3d825c
--- /dev/null
+++ b/plugins/samplesource/rtlsdr/rtlsdrgui.cpp
@@ -0,0 +1,149 @@
+#include "rtlsdrgui.h"
+#include "ui_rtlsdrgui.h"
+#include "plugin/pluginapi.h"
+
+RTLSDRGui::RTLSDRGui(PluginAPI* pluginAPI, QWidget* parent) :
+ PluginGUI(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::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(message->id() == RTLSDRInput::MsgReportRTLSDR::ID()) {
+ 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 > 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/hardware/rtlsdr/rtlsdrgui.h b/plugins/samplesource/rtlsdr/rtlsdrgui.h
index 7c26312..5a1944d 100644
--- a/hardware/rtlsdr/rtlsdrgui.h
+++ b/plugins/samplesource/rtlsdr/rtlsdrgui.h
@@ -2,32 +2,40 @@
#define INCLUDE_RTLSDRGUI_H
#include <QTimer>
-#include "../samplesourcegui.h"
+#include "plugin/plugingui.h"
#include "rtlsdrinput.h"
+class PluginAPI;
+
namespace Ui {
class RTLSDRGui;
}
-class RTLSDRGui : public SampleSourceGUI {
+class RTLSDRGui : public PluginGUI {
Q_OBJECT
public:
- explicit RTLSDRGui(MessageQueue* msgQueue, QWidget* parent = NULL);
+ explicit RTLSDRGui(PluginAPI* pluginAPI, QWidget* parent = NULL);
~RTLSDRGui();
+ void destroy();
- QString serializeSettings() const;
- bool deserializeSettings(const QString& settings);
-
- void handleSourceMessage(DSPCmdSourceToGUI* cmd);
+ 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;
- MessageQueue* m_msgQueue;
+ PluginAPI* m_pluginAPI;
+ SampleSource::GeneralSettings m_generalSettings;
RTLSDRInput::Settings m_settings;
QTimer m_updateTimer;
std::vector<int> m_gains;
+ SampleSource* m_sampleSource;
void displaySettings();
void sendSettings();
diff --git a/hardware/rtlsdr/rtlsdrgui.ui b/plugins/samplesource/rtlsdr/rtlsdrgui.ui
index 3a3d3f5..ce2ea4c 100644
--- a/hardware/rtlsdr/rtlsdrgui.ui
+++ b/plugins/samplesource/rtlsdr/rtlsdrgui.ui
@@ -6,8 +6,8 @@
<rect>
<x>0</x>
<y>0</y>
- <width>196</width>
- <height>74</height>
+ <width>132</width>
+ <height>82</height>
</rect>
</property>
<property name="sizePolicy">
@@ -23,7 +23,16 @@
<property name="spacing">
<number>3</number>
</property>
- <property name="margin">
+ <property name="leftMargin">
+ <number>2</number>
+ </property>
+ <property name="topMargin">
+ <number>2</number>
+ </property>
+ <property name="rightMargin">
+ <number>2</number>
+ </property>
+ <property name="bottomMargin">
<number>2</number>
</property>
<item>
diff --git a/hardware/rtlsdr/rtlsdrinput.cpp b/plugins/samplesource/rtlsdr/rtlsdrinput.cpp
index 6ede90a..655d8d7 100644
--- a/hardware/rtlsdr/rtlsdrinput.cpp
+++ b/plugins/samplesource/rtlsdr/rtlsdrinput.cpp
@@ -20,45 +20,46 @@
#include "rtlsdrinput.h"
#include "rtlsdrthread.h"
#include "rtlsdrgui.h"
+#include "util/simpleserializer.h"
+
+MessageRegistrator RTLSDRInput::MsgConfigureRTLSDR::ID("MsgConfigureRTLSDR");
+MessageRegistrator RTLSDRInput::MsgReportRTLSDR::ID("MsgReportRTLSDR");
RTLSDRInput::Settings::Settings() :
- centerFrequency(100000000),
- gain(0),
- decimation(0)
+ m_gain(0),
+ m_decimation(0)
{
}
-QString RTLSDRInput::Settings::serialize() const
+void RTLSDRInput::Settings::resetToDefaults()
{
- return QString("rtlsdr:a:%1:%2:%3")
- .arg(centerFrequency)
- .arg(gain)
- .arg(decimation);
+ m_gain = 0;
+ m_decimation = 0;
}
-bool RTLSDRInput::Settings::deserialize(const QString& settings)
+QByteArray RTLSDRInput::Settings::serialize() const
{
- QStringList list = settings.split(":");
- if(list.size() < 2)
- return false;
- if(list[0] != "rtlsdr")
+ 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(list[1] == "a") {
- bool ok;
- if(list.size() != 5)
- return false;
- centerFrequency = list[2].toLongLong(&ok);
- if(!ok)
- return false;
- gain = list[3].toInt(&ok);
- if(!ok)
- return false;
- decimation = list[4].toInt(&ok);
- if(!ok)
- return false;
+ if(d.getVersion() == 1) {
+ d.readS32(1, &m_gain, 0);
+ d.readS32(2, &m_decimation, 0);
return true;
} else {
+ resetToDefaults();
return false;
}
}
@@ -146,10 +147,10 @@ bool RTLSDRInput::startInput(int device)
m_rtlSDRThread->startWork();
mutexLocker.unlock();
- applySettings(m_settings, true);
+ applySettings(m_generalSettings, m_settings, true);
qDebug("RTLSDRInput: start");
- DSPCmdGUIInfoRTLSDR::create(m_gains)->submit(m_guiMessageQueue);
+ MsgReportRTLSDR::create(m_gains)->submit(m_guiMessageQueue);
return true;
@@ -181,59 +182,49 @@ const QString& RTLSDRInput::getDeviceDescription() const
int RTLSDRInput::getSampleRate() const
{
- return 2000000 / (1 << m_settings.decimation);
+ return 2000000 / (1 << m_settings.m_decimation);
}
quint64 RTLSDRInput::getCenterFrequency() const
{
- return m_settings.centerFrequency;
-}
-
-SampleSourceGUI* RTLSDRInput::createGUI(MessageQueue* msgQueueToEngine, QWidget* parent) const
-{
- return new RTLSDRGui(msgQueueToEngine, parent);
+ return m_generalSettings.m_centerFrequency;
}
-void RTLSDRInput::handleGUIMessage(DSPCmdGUIToSource* cmd)
+bool RTLSDRInput::handleMessage(Message* message)
{
- if(cmd->sourceType() != DSPCmdConfigureSourceRTLSDR::SourceType)
- return;
- if(!applySettings(((DSPCmdConfigureSourceRTLSDR*)cmd)->getSettings(), false))
- qDebug("RTLSDR config error");
+ if(message->id() == MsgConfigureRTLSDR::ID()) {
+ 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 Settings& settings, bool force)
+bool RTLSDRInput::applySettings(const GeneralSettings& generalSettings, const Settings& settings, bool force)
{
QMutexLocker mutexLocker(&m_mutex);
- if((m_settings.centerFrequency != settings.centerFrequency) || force) {
- m_settings.centerFrequency = settings.centerFrequency;
+ 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_settings.centerFrequency) != 0)
- qDebug("osmosdr_set_center_freq(%lld) failed", m_settings.centerFrequency);
+ 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.gain != settings.gain) || force) {
- m_settings.gain = settings.gain;
+ 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.gain) != 0)
+ if(rtlsdr_set_tuner_gain(m_dev, m_settings.m_gain) != 0)
qDebug("rtlsdr_set_tuner_gain() failed");
}
}
- if((m_settings.decimation != settings.decimation) || force) {
- m_settings.decimation = settings.decimation;
+ 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.decimation);
+ m_rtlSDRThread->setDecimation(m_settings.m_decimation);
}
return true;
}
-
-int DSPCmdConfigureSourceRTLSDR::sourceType() const
-{
- return SourceType;
-}
-
-int DSPCmdGUIInfoRTLSDR::sourceType() const
-{
- return SourceType;
-}
diff --git a/hardware/rtlsdr/rtlsdrinput.h b/plugins/samplesource/rtlsdr/rtlsdrinput.h
index eb2bdda..a92702e 100644
--- a/hardware/rtlsdr/rtlsdrinput.h
+++ b/plugins/samplesource/rtlsdr/rtlsdrinput.h
@@ -18,7 +18,7 @@
#ifndef INCLUDE_RTLSDRINPUT_H
#define INCLUDE_RTLSDRINPUT_H
-#include "../samplesource.h"
+#include "dsp/samplesource/samplesource.h"
#include <rtl-sdr.h>
#include <QString>
@@ -27,13 +27,56 @@ class RTLSDRThread;
class RTLSDRInput : public SampleSource {
public:
struct Settings {
- quint64 centerFrequency;
- int gain;
- int decimation;
+ qint32 m_gain;
+ qint32 m_decimation;
Settings();
- QString serialize() const;
- bool deserialize(const QString& settings);
+ void resetToDefaults();
+ QByteArray serialize() const;
+ bool deserialize(const QByteArray& data);
+ };
+
+ class MsgConfigureRTLSDR : public Message {
+ public:
+ static MessageRegistrator ID;
+
+ 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(ID()),
+ m_generalSettings(generalSettings),
+ m_settings(settings)
+ { }
+ };
+
+ class MsgReportRTLSDR : public Message {
+ public:
+ static MessageRegistrator ID;
+
+ const std::vector<int>& getGains() const { return m_gains; }
+
+ static MsgReportRTLSDR* create(const std::vector<int>& gains)
+ {
+ return new MsgReportRTLSDR(gains);
+ }
+
+ protected:
+ std::vector<int> m_gains;
+
+ MsgReportRTLSDR(const std::vector<int>& gains) :
+ Message(ID()),
+ m_gains(gains)
+ { }
};
RTLSDRInput(MessageQueue* msgQueueToGUI);
@@ -46,9 +89,7 @@ public:
int getSampleRate() const;
quint64 getCenterFrequency() const;
- SampleSourceGUI* createGUI(MessageQueue* msgQueueToEngine, QWidget* parent = NULL) const;
-
- void handleGUIMessage(DSPCmdGUIToSource* cmd);
+ bool handleMessage(Message* message);
private:
QMutex m_mutex;
@@ -58,50 +99,7 @@ private:
QString m_deviceDescription;
std::vector<int> m_gains;
- bool applySettings(const Settings& settings, bool force);
-};
-
-class DSPCmdConfigureSourceRTLSDR : public DSPCmdGUIToSource {
-public:
- enum {
- SourceType = 2
- };
-
- int sourceType() const;
- const RTLSDRInput::Settings& getSettings() const { return m_settings; }
-
- static DSPCmdConfigureSourceRTLSDR* create(const RTLSDRInput::Settings& settings)
- {
- return new DSPCmdConfigureSourceRTLSDR(settings);
- }
-
-protected:
- RTLSDRInput::Settings m_settings;
-
- DSPCmdConfigureSourceRTLSDR(const RTLSDRInput::Settings& settings) :
- m_settings(settings)
- { }
-};
-
-class DSPCmdGUIInfoRTLSDR : public DSPCmdSourceToGUI {
-public:
- enum {
- SourceType = 2
- };
- int sourceType() const;
- const std::vector<int>& getGains() const { return m_gains; }
-
- static DSPCmdGUIInfoRTLSDR* create(const std::vector<int>& gains)
- {
- return new DSPCmdGUIInfoRTLSDR(gains);
- }
-
-protected:
- std::vector<int> m_gains;
-
- DSPCmdGUIInfoRTLSDR(const std::vector<int>& gains) :
- m_gains(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 0000000..b5ad76c
--- /dev/null
+++ b/plugins/samplesource/rtlsdr/rtlsdrplugin.cpp
@@ -0,0 +1,67 @@
+#include <QtPlugin>
+#include <QAction>
+#include <rtl-sdr.h>
+#include "plugin/pluginapi.h"
+#include "util/simpleserializer.h"
+#include "rtlsdrplugin.h"
+#include "rtlsdrgui.h"
+
+const PluginDescriptor RTLSDRPlugin::m_pluginDescriptor = {
+ displayedName: QString("RTL-SDR Input"),
+ version: QString("---"),
+ copyright: QString("(c) librtlsdr Authors (see source URL)"),
+ website: QString("http://sdr.osmocom.org/trac/wiki/rtl-sdr"),
+ licenseIsGPL: true,
+ sourceCodeURL: 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") {
+ return new RTLSDRGui(m_pluginAPI);
+ } else {
+ return NULL;
+ }
+}
+
+Q_EXPORT_PLUGIN2(rtlsdrPlugin, RTLSDRPlugin);
diff --git a/plugins/samplesource/rtlsdr/rtlsdrplugin.h b/plugins/samplesource/rtlsdr/rtlsdrplugin.h
new file mode 100644
index 0000000..f559a97
--- /dev/null
+++ b/plugins/samplesource/rtlsdr/rtlsdrplugin.h
@@ -0,0 +1,26 @@
+#ifndef INCLUDE_RTLSDRPLUGIN_H
+#define INCLUDE_RTLSDRPLUGIN_H
+
+#include <QObject>
+#include "plugin/plugininterface.h"
+
+class RTLSDRPlugin : public QObject, PluginInterface {
+ Q_OBJECT
+ Q_INTERFACES(PluginInterface)
+
+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/hardware/rtlsdr/rtlsdrthread.cpp b/plugins/samplesource/rtlsdr/rtlsdrthread.cpp
index 2614b9a..8c8a17c 100644
--- a/hardware/rtlsdr/rtlsdrthread.cpp
+++ b/plugins/samplesource/rtlsdr/rtlsdrthread.cpp
@@ -18,7 +18,7 @@
#include <stdio.h>
#include <errno.h>
#include "rtlsdrthread.h"
-#include "../samplefifo.h"
+#include "dsp/samplefifo.h"
#define BLOCKSIZE 16384
@@ -77,10 +77,9 @@ void RTLSDRThread::run()
void RTLSDRThread::decimate2(SampleVector::iterator* it, const quint8* buf, qint32 len)
{
for(int pos = 0; pos < len; pos += 2) {
- qint16 i = (((qint8)buf[pos]) - 128) << 8;
- qint16 q = (((qint8)buf[pos + 1]) - 128) << 8;
- if(m_decimator2.workDecimate(&i, &q)) {
- **it = Sample(i, q);
+ Sample s((((qint8)buf[pos]) - 128) << 8, (((qint8)buf[pos + 1]) - 128) << 8);
+ if(m_decimator2.workDecimateCenter(&s)) {
+ **it = s;
++(*it);
}
}
@@ -89,11 +88,10 @@ void RTLSDRThread::decimate2(SampleVector::iterator* it, const quint8* buf, qint
void RTLSDRThread::decimate4(SampleVector::iterator* it, const quint8* buf, qint32 len)
{
for(int pos = 0; pos < len; pos += 2) {
- qint16 i = (((qint8)buf[pos]) - 128) << 8;
- qint16 q = (((qint8)buf[pos + 1]) - 128) << 8;
- if(m_decimator2.workDecimate(&i, &q)) {
- if(m_decimator4.workDecimate(&i, &q)) {
- **it = Sample(i, q);
+ 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);
}
}
@@ -103,12 +101,11 @@ void RTLSDRThread::decimate4(SampleVector::iterator* it, const quint8* buf, qint
void RTLSDRThread::decimate8(SampleVector::iterator* it, const quint8* buf, qint32 len)
{
for(int pos = 0; pos < len; pos += 2) {
- qint16 i = (((qint8)buf[pos]) - 128) << 8;
- qint16 q = (((qint8)buf[pos + 1]) - 128) << 8;
- if(m_decimator2.workDecimate(&i, &q)) {
- if(m_decimator4.workDecimate(&i, &q)) {
- if(m_decimator8.workDecimate(&i, &q)) {
- **it = Sample(i, q);
+ 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);
}
}
@@ -119,13 +116,12 @@ void RTLSDRThread::decimate8(SampleVector::iterator* it, const quint8* buf, qint
void RTLSDRThread::decimate16(SampleVector::iterator* it, const quint8* buf, qint32 len)
{
for(int pos = 0; pos < len; pos += 2) {
- qint16 i = (((qint8)buf[pos]) - 128) << 8;
- qint16 q = (((qint8)buf[pos + 1]) - 128) << 8;
- if(m_decimator2.workDecimate(&i, &q)) {
- if(m_decimator4.workDecimate(&i, &q)) {
- if(m_decimator8.workDecimate(&i, &q)) {
- if(m_decimator16.workDecimate(&i, &q)) {
- **it = Sample(i, q);
+ 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);
}
}
diff --git a/hardware/rtlsdr/rtlsdrthread.h b/plugins/samplesource/rtlsdr/rtlsdrthread.h
index afb9142..08837ef 100644
--- a/hardware/rtlsdr/rtlsdrthread.h
+++ b/plugins/samplesource/rtlsdr/rtlsdrthread.h
@@ -22,8 +22,7 @@
#include <QMutex>
#include <QWaitCondition>
#include <rtl-sdr.h>
-#include "../samplefifo.h"
-
+#include "dsp/samplefifo.h"
#include "dsp/inthalfbandfilter.h"
class RTLSDRThread : public QThread {
diff --git a/preset.cpp b/preset.cpp
deleted file mode 100644
index 6e09b76..0000000
--- a/preset.cpp
+++ /dev/null
@@ -1,25 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include "preset.h"
-
-Preset::Preset(const QString& name, const Settings& settings) :
- m_name(name),
- m_settings()
-{
- m_settings = settings;
-}
diff --git a/preset.h b/preset.h
deleted file mode 100644
index ad5a7be..0000000
--- a/preset.h
+++ /dev/null
@@ -1,35 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include <QString>
-#include <QMetaType>
-#include "settings.h"
-
-class Preset {
-public:
- Preset(const QString& name, const Settings& settings);
-
- const QString& name() const { return m_name; }
- const Settings* settings() const { return &m_settings; }
-
-private:
- QString m_name;
- Settings m_settings;
-};
-
-typedef QList<Preset*> PresetList;
-Q_DECLARE_METATYPE(Preset*)
diff --git a/hardware/soundcardinfo.cpp b/sdrbase/audio/audiodeviceinfo.cpp
index 6d5ccf2..dacefc3 100644
--- a/hardware/soundcardinfo.cpp
+++ b/sdrbase/audio/audiodeviceinfo.cpp
@@ -1,87 +1,84 @@
-///////////////////////////////////////////////////////////////////////////////////
-// 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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include <QMessageBox>
-#include "soundcardinfo.h"
-#include "portaudio.h"
-
-SoundcardInfo::SoundcardInfo()
-{
- const PaDeviceInfo *deviceInfo;
- const PaHostApiInfo *apiInfo;
- PaError err;
- int numDevices;
- int i;
- QString name;
-
- if((numDevices = Pa_GetDeviceCount()) < 0) {
- err = numDevices;
- goto failed;
- }
-
- m_devices.clear();
- qDebug("Audio initialisation: %d devices found", numDevices);
-
- for(i = 0; i < numDevices; i++) {
- deviceInfo = Pa_GetDeviceInfo(i);
- apiInfo = Pa_GetHostApiInfo(deviceInfo->hostApi);
-
- name = QString("%1 (record %2, playblack %3, API %4)").
- arg(QString::fromLatin1(deviceInfo->name)).
- arg(deviceInfo->maxInputChannels).
- arg(deviceInfo->maxOutputChannels).
- arg(QString::fromLatin1(apiInfo->name));
-
- m_devices.append(name);
-
- qDebug(" Device #%d: %s", i, qPrintable(name));
- }
- return;
-
-failed:
- if(err != paNoError)
- qCritical("Audio initialisation failed: %s (%d)", Pa_GetErrorText(err), err);
-}
-#if 0
-int SoundcardInfo::getInputDevice()
-{
- // find device
- for(i = 0; i < m_soundCardInfo->getDeviceCount(); i++) {
- if(m_soundCardInfo->getDevice(i) == dev) {
- device = i;
- break;
- }
- }
-
- // if no device is found or configured, find first DirectSound input device
- if(device < 0) {
- int numHostApis = Pa_GetHostApiCount();
- const PaHostApiInfo *apiInfo;
- int i;
- for(i = 0; i < numHostApis; i++) {
- apiInfo = Pa_GetHostApiInfo(i);
- if(strcmp(apiInfo->name, defaultDev) == 0) {
- device = apiInfo->defaultInputDevice;
- if(device >= 0)
- break;
- }
- }
- if(device < 0)
- device = Pa_GetDefaultInputDevice();
- }
-}
-#endif
+///////////////////////////////////////////////////////////////////////////////////
+// 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 <http://www.gnu.org/licenses/>. //
+///////////////////////////////////////////////////////////////////////////////////
+
+#include "audio/audiodeviceinfo.h"
+#include <portaudio.h>
+
+AudioDeviceInfo::AudioDeviceInfo()
+{
+ const PaDeviceInfo *deviceInfo;
+ const PaHostApiInfo *apiInfo;
+ PaError err;
+ int numDevices;
+ int i;
+
+ if((numDevices = Pa_GetDeviceCount()) < 0) {
+ err = numDevices;
+ goto failed;
+ }
+
+ m_devices.clear();
+
+ for(i = 0; i < numDevices; i++) {
+ deviceInfo = Pa_GetDeviceInfo(i);
+ if(deviceInfo->maxOutputChannels >= 2) {
+ apiInfo = Pa_GetHostApiInfo(deviceInfo->hostApi);
+ m_devices.append(Device(
+ QString::fromLatin1(deviceInfo->name),
+ QString::fromLatin1(apiInfo->name),
+ i));
+ }
+ }
+ qDebug("Audio initialisation: %d devices found", m_devices.count());
+ return;
+
+failed:
+ if(err != paNoError)
+ qCritical("Audio initialisation failed: %s (%d)", Pa_GetErrorText(err), err);
+}
+
+int AudioDeviceInfo::match(const QString& api, const QString device) const
+{
+ if(m_devices.count() <= 0)
+ return -1;
+
+ // default - use first device
+ if(api.isEmpty())
+ return 0;
+
+ if(device.isEmpty()) {
+ // only match API
+ for(int i = 0; i < m_devices.count(); ++i) {
+ if(m_devices[i].api == api)
+ return i;
+ }
+ } else {
+ // match API and device name
+ for(int i = 0; i < m_devices.count(); ++i) {
+ if((m_devices[i].api == api) && (m_devices[i].name == device))
+ return i;
+ }
+ // not found - only match API
+ for(int i = 0; i < m_devices.count(); ++i) {
+ if(m_devices[i].api == api)
+ return i;
+ }
+ }
+
+ // nothing found - fall back to default
+ return 0;
+}
diff --git a/hardware/audiofifo.cpp b/sdrbase/audio/audiofifo.cpp
index efe2d79..dd475ca 100644
--- a/hardware/audiofifo.cpp
+++ b/sdrbase/audio/audiofifo.cpp
@@ -17,7 +17,7 @@
#include <string.h>
#include <QTime>
-#include "audiofifo.h"
+#include "audio/audiofifo.h"
#define MIN(x, y) ((x) < (y) ? (x) : (y))
@@ -184,6 +184,17 @@ uint AudioFifo::drain(uint numSamples)
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) {
diff --git a/hardware/audiooutput.cpp b/sdrbase/audio/audiooutput.cpp
index 46091da..5599bf2 100644
--- a/hardware/audiooutput.cpp
+++ b/sdrbase/audio/audiooutput.cpp
@@ -15,54 +15,14 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
-#include <QMessageBox>
-#include "audiooutput.h"
-#include "audiofifo.h"
-
-int AudioOutput::callbackHelper(
- const void *inputBuffer,
- void *outputBuffer,
- unsigned long framesPerBuffer,
- const PaStreamCallbackTimeInfo* timeInfo,
- PaStreamCallbackFlags statusFlags,
- void *userData)
-{
- AudioOutput* audioOutput = (AudioOutput*)userData;
-
- if(outputBuffer == NULL)
- return 0;
-
- return audioOutput->callback(inputBuffer, outputBuffer, framesPerBuffer, timeInfo, statusFlags);
-}
-
-int AudioOutput::callback(
- const void* inputBuffer,
- void* outputBuffer,
- unsigned long framesPerBuffer,
- const PaStreamCallbackTimeInfo* timeInfo,
- PaStreamCallbackFlags statusFlags)
-{
- Q_UNUSED(inputBuffer);
- Q_UNUSED(timeInfo);
- Q_UNUSED(statusFlags);
-
- uint needed = framesPerBuffer;
- uint done = m_audioFifo->read((quint8*)outputBuffer, needed, 1);
-
- if(needed > done) {
- memset(((quint8*)outputBuffer) + done * 4, 0x00, (needed - done) * 4);
- qDebug("************* inserted %d samples *************", needed - done);
- //m_rateCorrection = 0.99;
- }
-
- m_streamStartTime += (PaTime)framesPerBuffer / (PaTime)m_sampleRate;
-
- return 0;
-}
+#include <string.h>
+#include "audio/audiooutput.h"
+#include "audio/audiofifo.h"
AudioOutput::AudioOutput() :
+ m_mutex(),
m_stream(NULL),
- m_audioFifo(NULL),
+ m_audioFifos(),
m_sampleRate(0)
{
}
@@ -70,19 +30,30 @@ AudioOutput::AudioOutput() :
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, AudioFifo* audioFifo)
+bool AudioOutput::start(int device, int rate)
{
- if(m_stream != NULL)
- stop();
+ QMutexLocker mutexLocker(&m_mutex);
+ if(m_stream != NULL) {
+ Pa_StopStream(m_stream);
+ Pa_CloseStream(m_stream);
+ m_stream = NULL;
+ m_sampleRate = 0;
+ }
+
+ for(AudioFifos::iterator it = m_audioFifos.begin(); it != m_audioFifos.end(); ++it)
+ (*it)->clear();
PaStreamParameters outputParameters;
const PaStreamInfo* streamInfo;
PaError err;
- m_audioFifo = audioFifo;
-
outputParameters.device = device;
outputParameters.channelCount = 2;
outputParameters.sampleFormat = paInt16;
@@ -93,7 +64,7 @@ bool AudioOutput::start(int device, int rate, AudioFifo* audioFifo)
goto failed;
qDebug("AudioOutput: start");
- m_streamStartTime = Pa_GetStreamTime(m_stream);
+// m_streamStartTime = Pa_GetStreamTime(m_stream);
if((err = Pa_StartStream(m_stream)) != paNoError)
goto failed;
@@ -113,16 +84,109 @@ failed:
void AudioOutput::stop()
{
+ m_mutex.lock();
if(m_stream != NULL) {
+ m_mutex.unlock();
Pa_StopStream(m_stream);
+ m_mutex.lock();
Pa_CloseStream(m_stream);
m_stream = NULL;
m_sampleRate = 0;
qDebug("AudioOutput: stopped");
}
+ m_mutex.unlock();
+}
+
+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);
}
+/*
int AudioOutput::bufferedSamples()
{
return (Pa_GetStreamTime(m_stream) - m_streamStartTime) * m_sampleRate;
}
+*/
+
+int AudioOutput::callbackHelper(
+ const void *inputBuffer,
+ void *outputBuffer,
+ unsigned long framesPerBuffer,
+ const PaStreamCallbackTimeInfo* timeInfo,
+ PaStreamCallbackFlags statusFlags,
+ void *userData)
+{
+ AudioOutput* audioOutput = (AudioOutput*)userData;
+
+ if(audioOutput == NULL)
+ return paAbort;
+
+ if(outputBuffer == NULL)
+ return paAbort;
+
+ return audioOutput->callback(inputBuffer, outputBuffer, framesPerBuffer, timeInfo, statusFlags);
+}
+
+int AudioOutput::callback(
+ const void* inputBuffer,
+ void* outputBuffer,
+ unsigned long framesPerBuffer,
+ const PaStreamCallbackTimeInfo* timeInfo,
+ PaStreamCallbackFlags statusFlags)
+{
+ QMutexLocker mutexLocker(&m_mutex);
+
+ Q_UNUSED(inputBuffer);
+ Q_UNUSED(timeInfo);
+ Q_UNUSED(statusFlags);
+
+ if(m_mixBuffer.size() != framesPerBuffer * 2) {
+ m_mixBuffer.resize(framesPerBuffer * 2); // allocate 2 qint32 per frame (stereo)
+ if(m_mixBuffer.size() != framesPerBuffer * 2)
+ return paAbort;
+
+ }
+ memset(m_mixBuffer.data(), 0x00, m_mixBuffer.size() * 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*)outputBuffer, framesPerBuffer, 0);
+ const qint16* src = (const qint16*)outputBuffer;
+ std::vector<qint32>::iterator dst = m_mixBuffer.begin();
+ for(int i = 0; i < samples; i++) {
+ *dst += *src;
+ ++src;
+ ++dst;
+ *dst += *src;
+ ++src;
+ ++dst;
+ }
+ }
+
+ // convert to int16
+ std::vector<qint32>::const_iterator src = m_mixBuffer.begin();
+ qint16* dst = (qint16*)outputBuffer;
+ for(int i = 0; i < framesPerBuffer; ++i) {
+ qint32 s = *src++;
+ if(s < -32768)
+ s = -32768;
+ else if(s > 32767)
+ s = 32767;
+ *dst++ = s;
+ }
+
+// m_streamStartTime += (PaTime)framesPerBuffer / (PaTime)m_sampleRate;
+
+ return paContinue;
+}
diff --git a/sdrbase/audio/portaudioholder.cpp b/sdrbase/audio/portaudioholder.cpp
new file mode 100644
index 0000000..1ba31c8
--- /dev/null
+++ b/sdrbase/audio/portaudioholder.cpp
@@ -0,0 +1,26 @@
+#include <QMessageBox>
+#include <portaudio.h>
+#include "audio/portaudioholder.h"
+
+PortAudioHolder::PortAudioHolder() :
+ m_initialized(false)
+{
+ PaError err;
+
+ if((err = Pa_Initialize()) == paNoError) {
+ m_initialized = true;
+ qDebug("PortAudio initialized");
+ } else {
+ qCritical("PortAudio: could not initialise: %s (%d)", Pa_GetErrorText(err), err);
+ QString error = QObject::tr("PortAudio could not be initialised: %1 (%2)").arg(Pa_GetErrorText(err)).arg(err);
+ QMessageBox::critical(NULL, "PortAudio failure", error);
+ }
+}
+
+PortAudioHolder::~PortAudioHolder()
+{
+ if(m_initialized) {
+ Pa_Terminate();
+ qDebug("PortAudio terminated");
+ }
+}
diff --git a/sdrbase/dsp/channelizer.cpp b/sdrbase/dsp/channelizer.cpp
new file mode 100644
index 0000000..34df1fa
--- /dev/null
+++ b/sdrbase/dsp/channelizer.cpp
@@ -0,0 +1,326 @@
+#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(cmd->id() == DSPSignalNotification::ID()) {
+ 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(cmd->id() == DSPConfigureChannelizer::ID()) {
+ 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;
+
+ //qDebug("Signal [%f, %f] (BW %f), Channel [%f, %f], Rot %f, Safety %f", sigStart, sigEnd, sigBw, chanStart, chanEnd, rot, safetyMargin);
+
+ // 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);
+ }
+
+ 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 <http://www.gnu.org/licenses/>. //
+///////////////////////////////////////////////////////////////////////////////////
+
+#include <QTime>
+#include <stdio.h>
+#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 0000000..a39ae63
--- /dev/null
+++ b/sdrbase/dsp/channelmarker.cpp
@@ -0,0 +1,40 @@
+#include "dsp/channelmarker.h"
+
+ChannelMarker::ChannelMarker(QObject* parent) :
+ QObject(parent),
+ m_centerFrequency(0),
+ m_bandwidth(0),
+ m_visible(false),
+ m_color(Qt::red)
+{
+}
+
+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 0000000..55dade9
--- /dev/null
+++ b/sdrbase/dsp/dspcommands.cpp
@@ -0,0 +1,19 @@
+#include "dsp/dspcommands.h"
+
+MessageRegistrator DSPPing::ID("DSPPing");
+MessageRegistrator DSPExit::ID("DSPExit");
+MessageRegistrator DSPAcquisitionStart::ID("DSPAcquisitionStart");
+MessageRegistrator DSPAcquisitionStop::ID("DSPAcquisitionStop");
+MessageRegistrator DSPGetDeviceDescription::ID("DSPGetDeviceDescription");
+MessageRegistrator DSPGetErrorMessage::ID("DSPGetErrorMessage");
+MessageRegistrator DSPSetSource::ID("DSPSetSource");
+MessageRegistrator DSPAddSink::ID("DSPAddSink");
+MessageRegistrator DSPAddAudioSource::ID("DSPAddAudioSource");
+MessageRegistrator DSPRemoveAudioSource::ID("DSPRemoveAudioSource");
+MessageRegistrator DSPRemoveSink::ID("DSPRemoveSink");
+MessageRegistrator DSPConfigureSpectrumVis::ID("DSPConfigureSpectrumVis");
+MessageRegistrator DSPConfigureCorrection::ID("DSPConfigureCorrection");
+MessageRegistrator DSPEngineReport::ID("DSPEngineReport");
+MessageRegistrator DSPConfigureScopeVis::ID("DSPConfigureScopeVis");
+MessageRegistrator DSPSignalNotification::ID("DSPSignalNotification");
+MessageRegistrator DSPConfigureChannelizer::ID("DSPConfigureChannelizer");
diff --git a/dsp/dspengine.cpp b/sdrbase/dsp/dspengine.cpp
index f5a6b46..e196601 100644
--- a/dsp/dspengine.cpp
+++ b/sdrbase/dsp/dspengine.cpp
@@ -16,13 +16,12 @@
///////////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
-#include "dspengine.h"
-#include "settings.h"
-#include "channelizer.h"
-#include "hardware/samplefifo.h"
-#include "hardware/samplesource.h"
-#include "samplesink.h"
-#include "dspcommands.h"
+#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),
@@ -51,63 +50,75 @@ DSPEngine::~DSPEngine()
void DSPEngine::start()
{
- DSPCmdPing cmd;
+ DSPPing cmd;
QThread::start();
cmd.execute(&m_messageQueue);
}
void DSPEngine::stop()
{
- DSPCmdExit cmd;
+ DSPExit cmd;
cmd.execute(&m_messageQueue);
}
bool DSPEngine::startAcquisition()
{
- DSPCmdAcquisitionStart cmd;
+ DSPAcquisitionStart cmd;
return cmd.execute(&m_messageQueue) == StRunning;
}
void DSPEngine::stopAcquistion()
{
- DSPCmdAcquisitionStop cmd;
+ DSPAcquisitionStop cmd;
cmd.execute(&m_messageQueue);
}
void DSPEngine::setSource(SampleSource* source)
{
- DSPCmdSetSource cmd(source);
+ DSPSetSource cmd(source);
cmd.execute(&m_messageQueue);
}
void DSPEngine::addSink(SampleSink* sink)
{
- DSPCmdAddSink cmd(sink);
+ DSPAddSink cmd(sink);
cmd.execute(&m_messageQueue);
}
void DSPEngine::removeSink(SampleSink* sink)
{
- DSPCmdRemoveSink cmd(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 = DSPCmdConfigureCorrection::create(dcOffsetCorrection, iqImbalanceCorrection);
+ Message* cmd = DSPConfigureCorrection::create(dcOffsetCorrection, iqImbalanceCorrection);
cmd->submit(&m_messageQueue);
}
QString DSPEngine::errorMessage()
{
- DSPCmdGetErrorMessage cmd;
+ DSPGetErrorMessage cmd;
cmd.execute(&m_messageQueue);
return cmd.getErrorMessage();
}
QString DSPEngine::deviceDescription()
{
- DSPCmdGetDeviceDescription cmd;
+ DSPGetDeviceDescription cmd;
cmd.execute(&m_messageQueue);
return cmd.getDeviceDescription();
}
@@ -314,6 +325,8 @@ DSPEngine::State DSPEngine::gotoIdle()
(*it)->stop();
m_sampleSource->stopInput();
m_deviceDescription.clear();
+ m_audioOutput.stop();
+ m_sampleRate = 0;
return StIdle;
}
@@ -342,11 +355,13 @@ DSPEngine::State DSPEngine::gotoRunning()
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;
}
@@ -387,8 +402,10 @@ void DSPEngine::generateReport()
if(sampleRate != m_sampleRate) {
m_sampleRate = sampleRate;
needReport = true;
- for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++)
- (*it)->setSampleRate(m_sampleRate);
+ 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;
@@ -396,11 +413,30 @@ void DSPEngine::generateReport()
}
if(needReport) {
- Message* rep = DSPRepEngineReport::create(m_sampleRate, m_centerFrequency);
+ Message* rep = DSPEngineReport::create(m_sampleRate, m_centerFrequency);
rep->submit(m_reportQueue);
}
}
+bool DSPEngine::distributeMessage(Message* message)
+{
+ if(m_sampleSource != NULL) {
+ if((message->destination() == NULL) || (message->destination() == 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->destination() == NULL) || (message->destination() == *it)) {
+ if((*it)->handleMessage(message))
+ return true;
+ }
+ }
+ return false;
+}
+
void DSPEngine::handleData()
{
if(m_state == StRunning)
@@ -409,100 +445,73 @@ void DSPEngine::handleData()
void DSPEngine::handleMessages()
{
- Message* cmd;
- while((cmd = m_messageQueue.accept()) != NULL) {
- qDebug("CMD: %s", cmd->name());
-
- switch(cmd->type()) {
- case DSPCmdPing::Type:
- cmd->completed(m_state);
- break;
-
- case DSPCmdExit::Type:
- gotoIdle();
- m_state = StNotStarted;
- exit();
- cmd->completed(m_state);
- break;
-
- case DSPCmdAcquisitionStart::Type:
- m_state = gotoIdle();
- if(m_state == StIdle)
- m_state = gotoRunning();
- cmd->completed(m_state);
- break;
-
- case DSPCmdAcquisitionStop::Type:
- m_state = gotoIdle();
- cmd->completed(m_state);
- break;
-
- case DSPCmdGetDeviceDescription::Type:
- ((DSPCmdGetDeviceDescription*)cmd)->setDeviceDescription(m_deviceDescription);
- cmd->completed();
- break;
-
- case DSPCmdGetErrorMessage::Type:
- ((DSPCmdGetErrorMessage*)cmd)->setErrorMessage(m_errorMessage);
- cmd->completed();
- break;
-
- case DSPCmdSetSource::Type:
- handleSetSource(((DSPCmdSetSource*)cmd)->getSource());
- cmd->completed();
- break;
-
- case DSPCmdAddSink::Type: {
- SampleSink* sink = ((DSPCmdAddSink*)cmd)->getSink();
- if(m_state == StRunning) {
- sink->setSampleRate(m_sampleRate);
- sink->start();
- }
- m_sampleSinks.push_back(sink);
- cmd->completed();
- break;
+ Message* message;
+ while((message = m_messageQueue.accept()) != NULL) {
+ qDebug("Message: %d: %s", message->id(), message->name());
+
+ if(message->id() == DSPPing::ID()) {
+ message->completed(m_state);
+ } else if(message->id() == DSPExit::ID()) {
+ gotoIdle();
+ m_state = StNotStarted;
+ exit();
+ message->completed(m_state);
+ } else if(message->id() == DSPAcquisitionStart::ID()) {
+ m_state = gotoIdle();
+ if(m_state == StIdle)
+ m_state = gotoRunning();
+ message->completed(m_state);
+ } else if(message->id() == DSPAcquisitionStop::ID()) {
+ m_state = gotoIdle();
+ message->completed(m_state);
+ } else if(message->id() == DSPGetDeviceDescription::ID()) {
+ ((DSPGetDeviceDescription*)message)->setDeviceDescription(m_deviceDescription);
+ message->completed();
+ } else if(message->id() == DSPGetErrorMessage::ID()) {
+ ((DSPGetErrorMessage*)message)->setErrorMessage(m_errorMessage);
+ message->completed();
+ } else if(message->id() == DSPSetSource::ID()) {
+ handleSetSource(((DSPSetSource*)message)->getSampleSource());
+ message->completed();
+ } else if(message->id() == DSPAddSink::ID()) {
+ SampleSink* sink = ((DSPAddSink*)message)->getSampleSink();
+ if(m_state == StRunning) {
+ DSPSignalNotification* signal = DSPSignalNotification::create(m_sampleRate, 0);
+ signal->submit(&m_messageQueue, sink);
+ sink->start();
}
-
- case DSPCmdRemoveSink::Type: {
- SampleSink* sink = ((DSPCmdAddSink*)cmd)->getSink();
- if(m_state == StRunning)
- sink->stop();
- m_sampleSinks.remove(sink);
- cmd->completed();
- break;
+ m_sampleSinks.push_back(sink);
+ message->completed();
+ } else if(message->id() == DSPRemoveSink::ID()) {
+ SampleSink* sink = ((DSPAddSink*)message)->getSampleSink();
+ if(m_state == StRunning)
+ sink->stop();
+ m_sampleSinks.remove(sink);
+ message->completed();
+ } else if(message->id() == DSPAddAudioSource::ID()) {
+ m_audioOutput.addFifo(((DSPAddAudioSource*)message)->getAudioFifo());
+ message->completed();
+ } else if(message->id() == DSPRemoveAudioSource::ID()) {
+ m_audioOutput.removeFifo(((DSPAddAudioSource*)message)->getAudioFifo());
+ message->completed();
+ } else if(message->id() == DSPConfigureCorrection::ID()) {
+ DSPConfigureCorrection* conf = (DSPConfigureCorrection*)message;
+ m_iqImbalanceCorrection = conf->getIQImbalanceCorrection();
+ if(m_dcOffsetCorrection != conf->getDCOffsetCorrection()) {
+ m_dcOffsetCorrection = conf->getDCOffsetCorrection();
+ m_iOffset = 0;
+ m_qOffset = 0;
}
-
- case DSPCmdConfigureCorrection::Type: {
- DSPCmdConfigureCorrection* conf = (DSPCmdConfigureCorrection*)cmd;
+ if(m_iqImbalanceCorrection != conf->getIQImbalanceCorrection()) {
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;
- }
- cmd->completed();
- break;
+ m_iRange = 1 << 16;
+ m_qRange = 1 << 16;
+ m_imbalance = 65536;
}
-
- case DSPCmdGUIToSource::Type:
- if(m_sampleSource != NULL) {
- m_sampleSource->handleGUIMessage((DSPCmdGUIToSource*)cmd);
- generateReport();
- }
- cmd->completed();
- break;
-
- default:
- for(SampleSinks::const_iterator it = m_sampleSinks.begin(); it != m_sampleSinks.end(); it++)
- (*it)->handleMessage(cmd);
- cmd->completed();
- break;
+ message->completed();
+ } else {
+ if(!distributeMessage(message))
+ message->completed();
}
}
}
diff --git a/dsp/fftengine.cpp b/sdrbase/dsp/fftengine.cpp
index 040449e..fe431b1 100644
--- a/dsp/fftengine.cpp
+++ b/sdrbase/dsp/fftengine.cpp
@@ -1,9 +1,9 @@
-#include "fftengine.h"
+#include "dsp/fftengine.h"
#ifdef USE_KISSFFT
-#include "kissengine.h"
+#include "dsp/kissengine.h"
#endif
#ifdef USE_FFTW
-#include "fftwengine.h"
+#include "dsp/fftwengine.h"
#endif // USE_FFTW
FFTEngine::~FFTEngine()
diff --git a/dsp/fftwengine.cpp b/sdrbase/dsp/fftwengine.cpp
index b5ca9e2..a19d113 100644
--- a/dsp/fftwengine.cpp
+++ b/sdrbase/dsp/fftwengine.cpp
@@ -1,4 +1,5 @@
-#include "fftwengine.h"
+#include <QTime>
+#include "dsp/fftwengine.h"
FFTWEngine::FFTWEngine() :
m_plans(),
@@ -25,7 +26,10 @@ void FFTWEngine::configure(int n, bool inverse)
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_currentPlan->plan = fftwf_plan_dft_1d(n, m_currentPlan->in, m_currentPlan->out, inverse ? FFTW_BACKWARD : FFTW_FORWARD, FFTW_PATIENT);
+ qDebug("FFT: creating FFTW plan (n=%d,%s) took %dms", n, inverse ? "inverse" : "forward", t.elapsed());
m_plans.push_back(m_currentPlan);
}
diff --git a/dsp/fftwindow.cpp b/sdrbase/dsp/fftwindow.cpp
index b07eacf..b363b21 100644
--- a/dsp/fftwindow.cpp
+++ b/sdrbase/dsp/fftwindow.cpp
@@ -15,7 +15,7 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
-#include "fftwindow.h"
+#include "dsp/fftwindow.h"
void FFTWindow::create(Function function, int n)
{
diff --git a/dsp/interpolator.cpp b/sdrbase/dsp/interpolator.cpp
index 06dad92..629240c 100644
--- a/dsp/interpolator.cpp
+++ b/sdrbase/dsp/interpolator.cpp
@@ -1,7 +1,7 @@
#define _USE_MATH_DEFINES
#include <math.h>
#include <vector>
-#include "interpolator.h"
+#include "dsp/interpolator.h"
Interpolator::Interpolator()
{
diff --git a/dsp/inthalfbandfilter.cpp b/sdrbase/dsp/inthalfbandfilter.cpp
index 8ff9b07..db41dc9 100644
--- a/dsp/inthalfbandfilter.cpp
+++ b/sdrbase/dsp/inthalfbandfilter.cpp
@@ -1,8 +1,8 @@
-#include "inthalfbandfilter.h"
+#include "dsp/inthalfbandfilter.h"
IntHalfbandFilter::IntHalfbandFilter()
{
- for(int i = 0; i < FILTERORDER + 1; i++) {
+ for(int i = 0; i < HB_FILTERORDER + 1; i++) {
m_samples[i][0] = 0;
m_samples[i][1] = 0;
}
diff --git a/dsp/kissengine.cpp b/sdrbase/dsp/kissengine.cpp
index 826fa6e..5649128 100644
--- a/dsp/kissengine.cpp
+++ b/sdrbase/dsp/kissengine.cpp
@@ -1,4 +1,4 @@
-#include "kissengine.h"
+#include "dsp/kissengine.h"
void KissEngine::configure(int n, bool inverse)
{
diff --git a/dsp/lowpass.cpp b/sdrbase/dsp/lowpass.cpp
index f85402d..1b8d9f2 100644
--- a/dsp/lowpass.cpp
+++ b/sdrbase/dsp/lowpass.cpp
@@ -3,4 +3,4 @@
#define _USE_MATH_DEFINES
#include <math.h>
#include <vector>
-#include "lowpass.h"
+#include "dsp/lowpass.h"
diff --git a/dsp/nco.cpp b/sdrbase/dsp/nco.cpp
index 36755c5..1143cf8 100644
--- a/dsp/nco.cpp
+++ b/sdrbase/dsp/nco.cpp
@@ -19,7 +19,7 @@
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
-#include "nco.h"
+#include "dsp/nco.h"
Real NCO::m_table[NCO::TableSize];
bool NCO::m_tableInitialized = false;
diff --git a/dsp/pidcontroller.cpp b/sdrbase/dsp/pidcontroller.cpp
index 8b015f6..8b015f6 100644
--- a/dsp/pidcontroller.cpp
+++ b/sdrbase/dsp/pidcontroller.cpp
diff --git a/dsp/pidcontroller.h b/sdrbase/dsp/pidcontroller.h
index 113947d..7b96793 100644
--- a/dsp/pidcontroller.h
+++ b/sdrbase/dsp/pidcontroller.h
@@ -1,7 +1,7 @@
#ifndef INCLUDE_PIDCONTROLLER_H
#define INCLUDE_PIDCONTROLLER_H
-#include "dsptypes.h"
+#include "dsp/dsptypes.h"
class PIDController {
private:
diff --git a/hardware/samplefifo.cpp b/sdrbase/dsp/samplefifo.cpp
index 321914a..caa4969 100644
--- a/hardware/samplefifo.cpp
+++ b/sdrbase/dsp/samplefifo.cpp
@@ -15,11 +15,11 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
-#include "samplefifo.h"
+#include "dsp/samplefifo.h"
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
-void SampleFifo::create(size_t s)
+void SampleFifo::create(uint s)
{
m_size = 0;
m_fill = 0;
@@ -64,15 +64,15 @@ bool SampleFifo::setSize(int size)
{
create(size);
- return m_data.size() == (size_t)size;
+ return m_data.size() == (uint)size;
}
-size_t SampleFifo::write(const quint8* data, size_t count)
+uint SampleFifo::write(const quint8* data, uint count)
{
QMutexLocker mutexLocker(&m_mutex);
- size_t total;
- size_t remaining;
- size_t len;
+ uint total;
+ uint remaining;
+ uint len;
const Sample* begin = (const Sample*)data;
count /= 4;
@@ -81,11 +81,11 @@ size_t SampleFifo::write(const quint8* data, size_t count)
if(m_suppressed < 0) {
m_suppressed = 0;
m_msgRateTimer.start();
- qCritical("SampleFifo: overflow - dropping %d samples", count - total);
+ qCritical("SampleFifo: overflow - dropping %u samples", count - total);
} else {
if(m_msgRateTimer.elapsed() > 2500) {
- qCritical("SampleFifo: %d messages dropped", m_suppressed);
- qCritical("SampleFifo: overflow - dropping %d samples", count - total);
+ qCritical("SampleFifo: %u messages dropped", m_suppressed);
+ qCritical("SampleFifo: overflow - dropping %u samples", count - total);
m_suppressed = -1;
} else {
m_suppressed++;
@@ -110,24 +110,24 @@ size_t SampleFifo::write(const quint8* data, size_t count)
return total;
}
-size_t SampleFifo::write(SampleVector::const_iterator begin, SampleVector::const_iterator end)
+uint SampleFifo::write(SampleVector::const_iterator begin, SampleVector::const_iterator end)
{
QMutexLocker mutexLocker(&m_mutex);
- size_t count = end - begin;
- size_t total;
- size_t remaining;
- size_t len;
+ 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 %d samples", count - total);
+ qCritical("SampleFifo: overflow - dropping %u samples", count - total);
} else {
if(m_msgRateTimer.elapsed() > 2500) {
- qCritical("SampleFifo: %d messages dropped", m_suppressed);
- qCritical("SampleFifo: overflow - dropping %d samples", count - total);
+ qCritical("SampleFifo: %u messages dropped", m_suppressed);
+ qCritical("SampleFifo: overflow - dropping %u samples", count - total);
m_suppressed = -1;
} else {
m_suppressed++;
@@ -152,17 +152,17 @@ size_t SampleFifo::write(SampleVector::const_iterator begin, SampleVector::const
return total;
}
-size_t SampleFifo::read(SampleVector::iterator begin, SampleVector::iterator end)
+uint SampleFifo::read(SampleVector::iterator begin, SampleVector::iterator end)
{
QMutexLocker mutexLocker(&m_mutex);
- size_t count = end - begin;
- size_t total;
- size_t remaining;
- size_t len;
+ uint count = end - begin;
+ uint total;
+ uint remaining;
+ uint len;
total = MIN(count, m_fill);
if(total < count)
- qCritical("SampleFifo: underflow - missing %d samples", count - total);
+ qCritical("SampleFifo: underflow - missing %u samples", count - total);
remaining = total;
while(remaining > 0) {
@@ -178,20 +178,19 @@ size_t SampleFifo::read(SampleVector::iterator begin, SampleVector::iterator end
return total;
}
-
-size_t SampleFifo::readBegin(size_t count,
+uint SampleFifo::readBegin(uint count,
SampleVector::iterator* part1Begin, SampleVector::iterator* part1End,
SampleVector::iterator* part2Begin, SampleVector::iterator* part2End)
{
QMutexLocker mutexLocker(&m_mutex);
- size_t total;
- size_t remaining;
- size_t len;
- size_t head = m_head;
+ uint total;
+ uint remaining;
+ uint len;
+ uint head = m_head;
total = MIN(count, m_fill);
if(total < count)
- qCritical("SampleFifo: underflow - missing %d samples", count - total);
+ qCritical("SampleFifo: underflow - missing %u samples", count - total);
remaining = total;
if(remaining > 0) {
@@ -217,7 +216,7 @@ size_t SampleFifo::readBegin(size_t count,
return total;
}
-size_t SampleFifo::readCommit(size_t count)
+uint SampleFifo::readCommit(uint count)
{
QMutexLocker mutexLocker(&m_mutex);
diff --git a/dsp/samplesink.cpp b/sdrbase/dsp/samplesink.cpp
index 796c7a8..5ff0dd1 100644
--- a/dsp/samplesink.cpp
+++ b/sdrbase/dsp/samplesink.cpp
@@ -1,4 +1,4 @@
-#include "samplesink.h"
+#include "dsp/samplesink.h"
SampleSink::SampleSink()
{
diff --git a/hardware/samplesource.cpp b/sdrbase/dsp/samplesource/samplesource.cpp
index d88375d..dda41d0 100644
--- a/hardware/samplesource.cpp
+++ b/sdrbase/dsp/samplesource/samplesource.cpp
@@ -15,34 +15,50 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
-#include "samplesource.h"
+#include "dsp/samplesource/samplesource.h"
+#include "util/simpleserializer.h"
-SampleSource::SampleSource(MessageQueue* msgQueueToGUI) :
- m_sampleFifo(),
- m_guiMessageQueue(msgQueueToGUI)
+SampleSource::GeneralSettings::GeneralSettings() :
+ m_centerFrequency(100000000)
{
}
-SampleSource::~SampleSource()
+void SampleSource::GeneralSettings::resetToDefaults()
{
+ m_centerFrequency = 100000000;
}
-int DSPCmdGUIToSource::type() const
+QByteArray SampleSource::GeneralSettings::serialize() const
{
- return Type;
+ SimpleSerializer s(1);
+ s.writeU64(1, m_centerFrequency);
+ return s.final();
}
-const char* DSPCmdGUIToSource::name() const
+bool SampleSource::GeneralSettings::deserialize(const QByteArray& data)
{
- return "GUIToSource";
+ 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;
+ }
}
-int DSPCmdSourceToGUI::type() const
+SampleSource::SampleSource(MessageQueue* guiMessageQueue) :
+ m_sampleFifo(),
+ m_guiMessageQueue(guiMessageQueue)
{
- return Type;
}
-const char* DSPCmdSourceToGUI::name() const
+SampleSource::~SampleSource()
{
- return "SourceToGUI";
}
diff --git a/dsp/scopevis.cpp b/sdrbase/dsp/scopevis.cpp
index 61ae98f..7a94130 100644
--- a/dsp/scopevis.cpp
+++ b/sdrbase/dsp/scopevis.cpp
@@ -1,7 +1,7 @@
-#include "scopevis.h"
-#include "../gui/glscope.h"
-#include "dspcommands.h"
-#include "../util/messagequeue.h"
+#include "dsp/scopevis.h"
+#include "gui/glscope.h"
+#include "dsp/dspcommands.h"
+#include "util/messagequeue.h"
ScopeVis::ScopeVis(GLScope* glScope) :
m_glScope(glScope),
@@ -17,8 +17,8 @@ ScopeVis::ScopeVis(GLScope* glScope) :
void ScopeVis::configure(MessageQueue* msgQueue, TriggerChannel triggerChannel, Real triggerLevelHigh, Real triggerLevelLow)
{
- Message* cmd = DSPCmdConfigureScopeVis::create(triggerChannel, triggerLevelHigh, triggerLevelLow);
- cmd->submit(msgQueue);
+ Message* cmd = DSPConfigureScopeVis::create(triggerChannel, triggerLevelHigh, triggerLevelLow);
+ cmd->submit(msgQueue, this);
}
void ScopeVis::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst)
@@ -120,24 +120,22 @@ void ScopeVis::stop()
{
}
-void ScopeVis::setSampleRate(int sampleRate)
+bool ScopeVis::handleMessage(Message* message)
{
- m_sampleRate = sampleRate;
-}
-
-void ScopeVis::handleMessage(Message* cmd)
-{
- switch(cmd->type()) {
- case DSPCmdConfigureScopeVis::Type: {
- DSPCmdConfigureScopeVis* conf = (DSPCmdConfigureScopeVis*)cmd;
- m_triggerState = Untriggered;
- m_triggerChannel = (TriggerChannel)conf->getTriggerChannel();
- m_triggerLevelHigh = conf->getTriggerLevelHigh() * 32767;
- m_triggerLevelLow = conf->getTriggerLevelLow() * 32767;
- break;
- }
-
- default:
- break;
+ if(message->id() == DSPSignalNotification::ID()) {
+ DSPSignalNotification* signal = (DSPSignalNotification*)message;
+ m_sampleRate = signal->getSampleRate();
+ message->completed();
+ return true;
+ } else if(message->id() == DSPConfigureScopeVis::ID()) {
+ 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/dsp/spectrumvis.cpp b/sdrbase/dsp/spectrumvis.cpp
index 880e4ce..e09cca5 100644
--- a/dsp/spectrumvis.cpp
+++ b/sdrbase/dsp/spectrumvis.cpp
@@ -1,6 +1,6 @@
-#include "spectrumvis.h"
+#include "dsp/spectrumvis.h"
#include "gui/glspectrum.h"
-#include "dspcommands.h"
+#include "dsp/dspcommands.h"
#include "util/messagequeue.h"
#define MAX_FFT_SIZE 4096
@@ -30,8 +30,8 @@ SpectrumVis::~SpectrumVis()
void SpectrumVis::configure(MessageQueue* msgQueue, int fftSize, int overlapPercent, FFTWindow::Function window)
{
- Message* cmd = DSPCmdConfigureSpectrumVis::create(fftSize, overlapPercent, window);
- cmd->submit(msgQueue);
+ Message* cmd = DSPConfigureSpectrumVis::create(fftSize, overlapPercent, window);
+ cmd->submit(msgQueue, this);
}
void SpectrumVis::feed(SampleVector::const_iterator begin, SampleVector::const_iterator end, bool firstOfBurst)
@@ -92,21 +92,15 @@ void SpectrumVis::stop()
{
}
-void SpectrumVis::setSampleRate(int sampleRate)
+bool SpectrumVis::handleMessage(Message* message)
{
-}
-
-void SpectrumVis::handleMessage(Message* cmd)
-{
- switch(cmd->type()) {
- case DSPCmdConfigureSpectrumVis::Type: {
- DSPCmdConfigureSpectrumVis* conf = (DSPCmdConfigureSpectrumVis*)cmd;
- handleConfigure(conf->getFFTSize(), conf->getOverlapPercent(), conf->getWindow());
- break;
- }
-
- default:
- break;
+ if(message->id() == DSPConfigureSpectrumVis::ID()) {
+ DSPConfigureSpectrumVis* conf = (DSPConfigureSpectrumVis*)message;
+ handleConfigure(conf->getFFTSize(), conf->getOverlapPercent(), conf->getWindow());
+ message->completed();
+ return true;
+ } else {
+ return false;
}
}
diff --git a/sdrbase/dsp/threadedsamplesink.cpp b/sdrbase/dsp/threadedsamplesink.cpp
new file mode 100644
index 0000000..f9396dd
--- /dev/null
+++ b/sdrbase/dsp/threadedsamplesink.cpp
@@ -0,0 +1,109 @@
+#include <QThread>
+#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);
+}
+
+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->name());
+ 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/addpresetdialog.cpp b/sdrbase/gui/addpresetdialog.cpp
new file mode 100644
index 0000000..c4d037b
--- /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 0000000..cbd6b5f
--- /dev/null
+++ b/sdrbase/gui/addpresetdialog.ui
@@ -0,0 +1,121 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>AddPresetDialog</class>
+ <widget class="QDialog" name="AddPresetDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>324</width>
+ <height>204</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Dialog</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QGroupBox" name="groupBox">
+ <property name="title">
+ <string>Preset Description</string>
+ </property>
+ <layout class="QFormLayout" name="formLayout">
+ <item row="0" column="0">
+ <widget class="QLabel" name="label">
+ <property name="text">
+ <string>&amp;Group</string>
+ </property>
+ <property name="buddy">
+ <cstring>group</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QComboBox" name="group">
+ <property name="editable">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_2">
+ <property name="text">
+ <string>&amp;Description</string>
+ </property>
+ <property name="buddy">
+ <cstring>description</cstring>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QLineEdit" name="description"/>
+ </item>
+ </layout>
+ </widget>
+ </item>
+ <item>
+ <spacer name="verticalSpacer">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>20</width>
+ <height>40</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <tabstops>
+ <tabstop>description</tabstop>
+ <tabstop>buttonBox</tabstop>
+ <tabstop>group</tabstop>
+ </tabstops>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>AddPresetDialog</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>257</x>
+ <y>194</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>157</x>
+ <y>203</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>AddPresetDialog</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>314</x>
+ <y>194</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>286</x>
+ <y>203</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/gui/glscope.cpp b/sdrbase/gui/glscope.cpp
index 3a03615..9f8c9a9 100644
--- a/gui/glscope.cpp
+++ b/sdrbase/gui/glscope.cpp
@@ -1,7 +1,7 @@
#include <QPainter>
#include <QMouseEvent>
-#include "glscope.h"
-#include "../dsp/dspengine.h"
+#include "gui/glscope.h"
+#include "dsp/dspengine.h"
#ifdef _WIN32
double log2f(double n)
@@ -22,7 +22,7 @@ GLScope::GLScope(QWidget* parent) :
m_dspEngine(NULL),
m_scopeVis(NULL),
m_amp(1.0),
- m_timeStep(1),
+ m_timeBase(1),
m_timeOfsProMill(0),
m_triggerChannel(ScopeVis::TriggerFreeRun)
{
@@ -54,9 +54,9 @@ void GLScope::setAmp(Real amp)
update();
}
-void GLScope::setTimeStep(int timeStep)
+void GLScope::setTimeBase(int timeBase)
{
- m_timeStep = timeStep;
+ m_timeBase = timeBase;
update();
}
@@ -191,14 +191,14 @@ void GLScope::paintGL()
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_timeStep / (float)(m_displayTrace->size() - 1), -(m_glScopeRect1.height() / 2) * m_amp1, 1);
+ 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_timeStep)) / 1000;
- int end = start + m_displayTrace->size() / m_timeStep;
+ 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;
@@ -278,14 +278,14 @@ void GLScope::paintGL()
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_timeStep / (float)(m_displayTrace->size() - 1), -(m_glScopeRect2.height() / 2) * m_amp2, 1);
+ 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_timeStep)) / 1000;
- int end = start + m_displayTrace->size() / m_timeStep;
+ 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;
@@ -322,8 +322,8 @@ void GLScope::mousePressEvent(QMouseEvent* event)
if((y < 0) || (y >= height() - 20))
return;
- if((m_sampleRate != 0) && (m_timeStep != 0) && (width() > 20))
- time = ((Real)x * (Real)m_displayTrace->size()) / ((Real)m_sampleRate * (Real)m_timeStep * (Real)(width() - 20));
+ 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) {
@@ -403,18 +403,20 @@ void GLScope::handleMode()
}
case ModeDerived12: {
- m_mathTrace.resize(m_rawTrace.size() - 3);
- std::vector<Complex>::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]));
+ if(m_rawTrace.size() > 3) {
+ m_mathTrace.resize(m_rawTrace.size() - 3);
+ std::vector<Complex>::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;
}
- m_displayTrace = &m_mathTrace;
- m_amp1 = m_amp;
- m_amp2 = m_amp;
- m_ofs1 = -1.0 / m_amp1;
- m_ofs2 = 0.0;
break;
}
}
diff --git a/gui/glspectrum.cpp b/sdrbase/gui/glspectrum.cpp
index a3b983d..1ab3eb7 100644
--- a/gui/glspectrum.cpp
+++ b/sdrbase/gui/glspectrum.cpp
@@ -16,7 +16,7 @@
///////////////////////////////////////////////////////////////////////////////////
#include <QMouseEvent>
-#include "glspectrum.h"
+#include "gui/glspectrum.h"
GLSpectrum::GLSpectrum(QWidget* parent) :
QGLWidget(parent),
@@ -41,9 +41,6 @@ GLSpectrum::GLSpectrum(QWidget* parent) :
m_histogramHoldoff(NULL),
m_histogramTextureAllocated(false),
m_displayHistogram(true),
- m_displayChannel(false),
- m_channelCenterFrequency(100000000),
- m_channelBandwidth(100000),
m_displayChanged(false)
{
setAutoFillBackground(false);
@@ -88,6 +85,7 @@ GLSpectrum::GLSpectrum(QWidget* parent) :
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());
@@ -108,7 +106,8 @@ GLSpectrum::~GLSpectrum()
m_waterfallBuffer = NULL;
}
if(m_waterfallTextureAllocated) {
- glDeleteTextures(1, &m_waterfallTexture);
+ makeCurrent();
+ deleteTexture(m_waterfallTexture);
m_waterfallTextureAllocated = false;
}
if(m_histogramBuffer != NULL) {
@@ -124,7 +123,8 @@ GLSpectrum::~GLSpectrum()
m_histogramHoldoff = NULL;
}
if(m_histogramTextureAllocated) {
- glDeleteTextures(1, &m_histogramTexture);
+ makeCurrent();
+ deleteTexture(m_histogramTexture);
m_histogramTextureAllocated = false;
}
if(m_leftMarginTextureAllocated) {
@@ -169,7 +169,7 @@ void GLSpectrum::setDisplayWaterfall(bool display)
{
m_displayWaterfall = display;
m_changesPending = true;
- stopSplitterMove();
+ stopDrag();
update();
}
@@ -177,7 +177,7 @@ void GLSpectrum::setInvertedWaterfall(bool inv)
{
m_invertedWaterfall = inv;
m_changesPending = true;
- stopSplitterMove();
+ stopDrag();
update();
}
@@ -185,7 +185,7 @@ void GLSpectrum::setDisplayLiveSpectrum(bool display)
{
m_displayLiveSpectrum = display;
m_changesPending = true;
- stopSplitterMove();
+ stopDrag();
update();
}
@@ -193,20 +193,38 @@ void GLSpectrum::setDisplayHistogram(bool display)
{
m_displayHistogram = display;
m_changesPending = true;
- stopSplitterMove();
+ stopDrag();
update();
}
-void GLSpectrum::setDisplayChannel(bool display, quint64 centerFrequency, quint64 bandwidth)
+void GLSpectrum::addChannelMarker(ChannelMarker* channelMarker)
{
- m_displayChannel = display;
- m_channelCenterFrequency = centerFrequency;
- m_channelBandwidth = bandwidth;
+ 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;
- stopSplitterMove();
+ 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<Real>& spectrum, int fftSize)
{
QMutexLocker mutexLocker(&m_mutex);
@@ -354,22 +372,25 @@ void GLSpectrum::paintGL()
glEnd();
glDisable(GL_TEXTURE_2D);
- // paint channel
- if(m_displayChannel) {
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glColor4f(1, 0, 0, 0.15f);
- glPushMatrix();
- glTranslatef(m_glChannelRect.x(), m_glChannelRect.y(), 0);
- glScalef(m_glChannelRect.width(), m_glChannelRect.height(), 1);
- glBegin(GL_QUADS);
- glVertex2f(0, 0);
- glVertex2f(1, 0);
- glVertex2f(1, 1);
- glVertex2f(0, 1);
- glEnd();
- glDisable(GL_BLEND);
- glPopMatrix();
+ // paint channels
+ 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.15f);
+ 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
@@ -429,27 +450,30 @@ void GLSpectrum::paintGL()
glDisable(GL_TEXTURE_2D);
}
- // paint channel
- if(m_displayChannel) {
- glEnable(GL_BLEND);
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
- glColor4f(1, 0, 0, 0.15f);
- glPushMatrix();
- glTranslatef(m_glChannelRect.x(), m_glChannelRect.y(), 0);
- glScalef(m_glChannelRect.width(), m_glChannelRect.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();
+ // paint channels
+ 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.15f);
+ 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
@@ -644,10 +668,10 @@ void GLSpectrum::paintGL()
m_mutex.unlock();
}
-void GLSpectrum::stopSplitterMove()
+void GLSpectrum::stopDrag()
{
if(m_cursorState != CSNormal) {
- if(m_cursorState == CSSplitterMoving)
+ if((m_cursorState == CSSplitterMoving) || (m_cursorState == CSChannelMoving))
releaseMouse();
setCursor(Qt::ArrowCursor);
m_cursorState = CSNormal;
@@ -695,9 +719,13 @@ void GLSpectrum::applyChanges()
}
m_timeScale.setSize(waterfallHeight);
- 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);
+ 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();
@@ -749,9 +777,15 @@ void GLSpectrum::applyChanges()
histogramTop = 0;
m_timeScale.setSize(waterfallHeight);
- 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);
+ 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;
@@ -784,7 +818,7 @@ void GLSpectrum::applyChanges()
(float)(leftMargin - 1) / (float)width(),
(float)1
);
- } else if(m_displayHistogram | m_displayLiveSpectrum) {
+ } else if(m_displayHistogram || m_displayLiveSpectrum) {
bottomMargin = frequencyScaleHeight;
frequencyScaleTop = height() - bottomMargin;
histogramTop = topMargin - 1;
@@ -830,12 +864,21 @@ void GLSpectrum::applyChanges()
waterfallHeight = 0;
}
- // channel overlay
- m_glChannelRect.setRect(
- m_frequencyScale.getPosFromValue(m_channelCenterFrequency - m_channelBandwidth / 2) / (float)(width() - leftMargin - rightMargin),
- 0,
- (m_channelBandwidth / (float)m_sampleRate),
- 1);
+ // 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_displayLiveSpectrum || 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)
{
@@ -983,16 +1026,18 @@ void GLSpectrum::applyChanges()
void GLSpectrum::mouseMoveEvent(QMouseEvent* event)
{
- if(m_displayWaterfall && (m_displayHistogram || m_displayLiveSpectrum)) {
+ if(m_displayWaterfall && (m_displayWaterfall || m_displayHistogram || m_displayLiveSpectrum)) {
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;
}
}
}
@@ -1010,6 +1055,29 @@ void GLSpectrum::mouseMoveEvent(QMouseEvent* event)
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_displayLiveSpectrum) {
+ 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;
}
}
@@ -1021,6 +1089,19 @@ void GLSpectrum::mousePressEvent(QMouseEvent* event)
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;
}
}
@@ -1029,6 +1110,9 @@ void GLSpectrum::mouseReleaseEvent(QMouseEvent*)
if(m_cursorState == CSSplitterMoving) {
releaseMouse();
m_cursorState = CSSplitter;
+ } else if(m_cursorState == CSChannelMoving) {
+ releaseMouse();
+ m_cursorState = CSChannel;
}
}
@@ -1039,3 +1123,14 @@ void GLSpectrum::tick()
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 0000000..6feaffd
--- /dev/null
+++ b/sdrbase/gui/glspectrumgui.cpp
@@ -0,0 +1,165 @@
+#include "gui/glspectrumgui.h"
+#include "dsp/fftwindow.h"
+#include "dsp/spectrumvis.h"
+#include "gui/glspectrum.h"
+#include "ui_glspectrumgui.h"
+#include "util/simpleserializer.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_displayWaterfall(true),
+ m_invertedWaterfall(false),
+ m_displayLiveSpectrum(false),
+ m_displayHistogram(true)
+{
+ ui->setupUi(this);
+}
+
+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_displayWaterfall = true;
+ m_invertedWaterfall = false;
+ m_displayLiveSpectrum = false;
+ m_displayHistogram = true;
+ 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_displayLiveSpectrum);
+ s.writeBool(9, m_displayHistogram);
+ 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_displayLiveSpectrum, false);
+ d.readBool(9, &m_displayHistogram, true);
+ applySettings();
+ return true;
+ } else {
+ resetToDefaults();
+ return false;
+ }
+}
+
+void GLSpectrumGUI::applySettings()
+{
+ for(int i = 0; i < 6; i++) {
+ if(m_fftSize == (1 << (i + 7))) {
+ ui->fftSize->setValue(i);
+ break;
+ }
+ }
+ ui->fftWindow->setCurrentIndex(m_fftWindow);
+ ui->waterfall->setChecked(m_displayWaterfall);
+ m_glSpectrum->setDisplayWaterfall(m_displayWaterfall);
+ m_glSpectrum->setInvertedWaterfall(m_invertedWaterfall);
+ ui->liveSpectrum->setChecked(m_displayLiveSpectrum);
+ m_glSpectrum->setDisplayLiveSpectrum(m_displayLiveSpectrum);
+ ui->histogram->setChecked(m_displayHistogram);
+ m_glSpectrum->setDisplayHistogram(m_displayHistogram);
+ ui->refLevel->setValue((int)(m_refLevel / 10.0));
+ ui->levelRange->setValue((int)(m_powerRange / 10.0));
+
+ m_spectrumVis->configure(m_messageQueue, m_fftSize, m_fftOverlap, (FFTWindow::Function)m_fftWindow);
+}
+
+void GLSpectrumGUI::on_fftSize_valueChanged(int value)
+{
+ m_fftSize = 1 << (7 + value);
+ ui->fftSizeDisplay->setText(tr("%1").arg(m_fftSize));
+ m_spectrumVis->configure(m_messageQueue, m_fftSize, m_fftOverlap, (FFTWindow::Function)m_fftWindow);
+}
+
+void GLSpectrumGUI::on_fftWindow_currentIndexChanged(int index)
+{
+ m_fftWindow = index;
+ m_spectrumVis->configure(m_messageQueue, m_fftSize, m_fftOverlap, (FFTWindow::Function)m_fftWindow);
+}
+
+void GLSpectrumGUI::on_refLevel_valueChanged(int value)
+{
+ m_refLevel = value * 10;
+ m_glSpectrum->setReferenceLevel(m_refLevel);
+ ui->refLevelDisplay->setText(tr("%1").arg(m_refLevel));
+}
+
+void GLSpectrumGUI::on_levelRange_valueChanged(int value)
+{
+ m_powerRange = value * 10;
+ m_glSpectrum->setPowerRange(m_powerRange);
+ ui->levelRangeDisplay->setText(tr("%1").arg(m_powerRange));
+}
+
+void GLSpectrumGUI::on_decay_valueChanged(int value)
+{
+}
+
+void GLSpectrumGUI::on_waterfall_toggled(bool checked)
+{
+ m_displayWaterfall = checked;
+ m_glSpectrum->setDisplayWaterfall(m_displayWaterfall);
+}
+
+void GLSpectrumGUI::on_histogram_toggled(bool checked)
+{
+ m_displayHistogram = checked;
+ m_glSpectrum->setDisplayHistogram(m_displayHistogram);
+}
+
+void GLSpectrumGUI::on_liveSpectrum_toggled(bool checked)
+{
+ m_displayLiveSpectrum = checked;
+ m_glSpectrum->setDisplayLiveSpectrum(m_displayLiveSpectrum);
+}
diff --git a/sdrbase/gui/glspectrumgui.ui b/sdrbase/gui/glspectrumgui.ui
new file mode 100644
index 0000000..5c67ba6
--- /dev/null
+++ b/sdrbase/gui/glspectrumgui.ui
@@ -0,0 +1,418 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>GLSpectrumGUI</class>
+ <widget class="QWidget" name="GLSpectrumGUI">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>203</width>
+ <height>136</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Oscilloscope</string>
+ </property>
+ <layout class="QGridLayout" name="gridLayout_2">
+ <property name="margin">
+ <number>2</number>
+ </property>
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_5">
+ <property name="text">
+ <string>Reference</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1">
+ <widget class="QSlider" name="refLevel">
+ <property name="toolTip">
+ <string>Spectrum reference level</string>
+ </property>
+ <property name="minimum">
+ <number>-9</number>
+ </property>
+ <property name="maximum">
+ <number>0</number>
+ </property>
+ <property name="singleStep">
+ <number>1</number>
+ </property>
+ <property name="pageStep">
+ <number>1</number>
+ </property>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="tickPosition">
+ <enum>QSlider::TicksAbove</enum>
+ </property>
+ <property name="tickInterval">
+ <number>1</number>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="2">
+ <widget class="QLabel" name="refLevelDisplay">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>25</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>0</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="3" rowspan="3">
+ <widget class="Line" name="line_2">
+ <property name="orientation">
+ <enum>Qt::Vertical</enum>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="4">
+ <widget class="QToolButton" name="waterfall">
+ <property name="minimumSize">
+ <size>
+ <width>24</width>
+ <height>24</height>
+ </size>
+ </property>
+ <property name="toolTip">
+ <string>Display waterfall</string>
+ </property>
+ <property name="text">
+ <string>Waterfall</string>
+ </property>
+ <property name="icon">
+ <iconset resource="../resources/res.qrc">
+ <normaloff>:/waterfall.png</normaloff>:/waterfall.png</iconset>
+ </property>
+ <property name="iconSize">
+ <size>
+ <width>16</width>
+ <height>16</height>
+ </size>
+ </property>
+ <property name="checkable">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="0">
+ <widget class="QLabel" name="label_6">
+ <property name="text">
+ <string>Range</string>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="1">
+ <widget class="QSlider" name="levelRange">
+ <property name="toolTip">
+ <string>Spectrum range</string>
+ </property>
+ <property name="minimum">
+ <number>1</number>
+ </property>
+ <property name="maximum">
+ <number>10</number>
+ </property>
+ <property name="singleStep">
+ <number>1</number>
+ </property>
+ <property name="pageStep">
+ <number>1</number>
+ </property>
+ <property name="value">
+ <number>10</number>
+ </property>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="tickPosition">
+ <enum>QSlider::TicksAbove</enum>
+ </property>
+ <property name="tickInterval">
+ <number>1</number>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="2">
+ <widget class="QLabel" name="levelRangeDisplay">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>25</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>100</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="2" column="4">
+ <widget class="QToolButton" name="histogram">
+ <property name="minimumSize">
+ <size>
+ <width>24</width>
+ <height>24</height>
+ </size>
+ </property>
+ <property name="toolTip">
+ <string>Display phosphor effect spectrum</string>
+ </property>
+ <property name="text">
+ <string>Histogram</string>
+ </property>
+ <property name="icon">
+ <iconset resource="../resources/res.qrc">
+ <normaloff>:/histogram.png</normaloff>:/histogram.png</iconset>
+ </property>
+ <property name="iconSize">
+ <size>
+ <width>16</width>
+ <height>16</height>
+ </size>
+ </property>
+ <property name="checkable">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="0">
+ <widget class="QLabel" name="label_7">
+ <property name="text">
+ <string>Decay</string>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="1">
+ <widget class="QSlider" name="decay">
+ <property name="enabled">
+ <bool>false</bool>
+ </property>
+ <property name="toolTip">
+ <string>Digital phosphor effect decay time</string>
+ </property>
+ <property name="maximum">
+ <number>100</number>
+ </property>
+ <property name="singleStep">
+ <number>10</number>
+ </property>
+ <property name="pageStep">
+ <number>10</number>
+ </property>
+ <property name="value">
+ <number>100</number>
+ </property>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="tickPosition">
+ <enum>QSlider::TicksAbove</enum>
+ </property>
+ <property name="tickInterval">
+ <number>10</number>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="2">
+ <widget class="QLabel" name="levelRangeDisplay_2">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Minimum" vsizetype="Preferred">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="minimumSize">
+ <size>
+ <width>25</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>100</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="3" column="4">
+ <widget class="QToolButton" name="liveSpectrum">
+ <property name="minimumSize">
+ <size>
+ <width>24</width>
+ <height>24</height>
+ </size>
+ </property>
+ <property name="toolTip">
+ <string>Display live spectrum</string>
+ </property>
+ <property name="text">
+ <string>Live Spectrum</string>
+ </property>
+ <property name="icon">
+ <iconset resource="../resources/res.qrc">
+ <normaloff>:/livespectrum.png</normaloff>:/livespectrum.png</iconset>
+ </property>
+ <property name="iconSize">
+ <size>
+ <width>16</width>
+ <height>16</height>
+ </size>
+ </property>
+ <property name="checkable">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="0" colspan="5">
+ <layout class="QGridLayout" name="gridLayout">
+ <property name="margin">
+ <number>2</number>
+ </property>
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <item row="0" column="0">
+ <widget class="QLabel" name="label_15">
+ <property name="text">
+ <string>FFT Size</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="0">
+ <widget class="QLabel" name="label_17">
+ <property name="text">
+ <string>Window</string>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1" colspan="2">
+ <widget class="QComboBox" name="fftWindow">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Expanding" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="toolTip">
+ <string>FFT window function</string>
+ </property>
+ <property name="sizeAdjustPolicy">
+ <enum>QComboBox::AdjustToContents</enum>
+ </property>
+ <item>
+ <property name="text">
+ <string>Bartlett</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Blackman-Harris</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Flat Top</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Hamming</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Hanning</string>
+ </property>
+ </item>
+ <item>
+ <property name="text">
+ <string>Rectangle</string>
+ </property>
+ </item>
+ </widget>
+ </item>
+ <item row="0" column="2">
+ <widget class="QLabel" name="fftSizeDisplay">
+ <property name="minimumSize">
+ <size>
+ <width>40</width>
+ <height>0</height>
+ </size>
+ </property>
+ <property name="text">
+ <string>128</string>
+ </property>
+ <property name="alignment">
+ <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
+ </property>
+ </widget>
+ </item>
+ <item row="0" column="1">
+ <widget class="QSlider" name="fftSize">
+ <property name="toolTip">
+ <string>FFT calculation block size</string>
+ </property>
+ <property name="maximum">
+ <number>5</number>
+ </property>
+ <property name="pageStep">
+ <number>1</number>
+ </property>
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="tickPosition">
+ <enum>QSlider::TicksAbove</enum>
+ </property>
+ <property name="tickInterval">
+ <number>1</number>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ </layout>
+ </widget>
+ <tabstops>
+ <tabstop>fftSize</tabstop>
+ <tabstop>fftWindow</tabstop>
+ <tabstop>refLevel</tabstop>
+ <tabstop>levelRange</tabstop>
+ <tabstop>decay</tabstop>
+ <tabstop>waterfall</tabstop>
+ <tabstop>histogram</tabstop>
+ <tabstop>liveSpectrum</tabstop>
+ </tabstops>
+ <resources>
+ <include location="../resources/res.qrc"/>
+ </resources>
+ <connections/>
+</ui>
diff --git a/gui/indicator.cpp b/sdrbase/gui/indicator.cpp
index 0dcf901..184197d 100644
--- a/gui/indicator.cpp
+++ b/sdrbase/gui/indicator.cpp
@@ -16,7 +16,7 @@
///////////////////////////////////////////////////////////////////////////////////
#include <QPainter>
-#include "indicator.h"
+#include "gui/indicator.h"
void Indicator::paintEvent(QPaintEvent*)
{
diff --git a/sdrbase/gui/pluginsdialog.cpp b/sdrbase/gui/pluginsdialog.cpp
new file mode 100644
index 0000000..551456f
--- /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 0000000..de2ad49
--- /dev/null
+++ b/sdrbase/gui/pluginsdialog.ui
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>PluginsDialog</class>
+ <widget class="QDialog" name="PluginsDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>300</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Loaded Plugins</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QTreeWidget" name="tree">
+ <column>
+ <property name="text">
+ <string>Name</string>
+ </property>
+ </column>
+ <column>
+ <property name="text">
+ <string>Version</string>
+ </property>
+ </column>
+ <column>
+ <property name="text">
+ <string>GPL</string>
+ </property>
+ </column>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>PluginsDialog</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>248</x>
+ <y>254</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>157</x>
+ <y>274</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/sdrbase/gui/preferencesdialog.cpp b/sdrbase/gui/preferencesdialog.cpp
new file mode 100644
index 0000000..077ef45
--- /dev/null
+++ b/sdrbase/gui/preferencesdialog.cpp
@@ -0,0 +1,55 @@
+#include <QTreeWidgetItem>
+#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 0000000..69f5d7d
--- /dev/null
+++ b/sdrbase/gui/preferencesdialog.ui
@@ -0,0 +1,109 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>PreferencesDialog</class>
+ <widget class="QDialog" name="PreferencesDialog">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>400</width>
+ <height>300</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>Dialog</string>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <item>
+ <widget class="QTabWidget" name="tabWidget">
+ <property name="currentIndex">
+ <number>1</number>
+ </property>
+ <widget class="QWidget" name="tab">
+ <attribute name="title">
+ <string>Receiver Hardware</string>
+ </attribute>
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <item>
+ <widget class="QTreeWidget" name="treeWidget">
+ <column>
+ <property name="text">
+ <string notr="true">1</string>
+ </property>
+ </column>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QWidget" name="tab_2">
+ <attribute name="title">
+ <string>Audio Output</string>
+ </attribute>
+ <layout class="QVBoxLayout" name="verticalLayout_3">
+ <item>
+ <widget class="QTreeWidget" name="audioTree">
+ <column>
+ <property name="text">
+ <string notr="true">Device</string>
+ </property>
+ </column>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ </item>
+ <item>
+ <widget class="QDialogButtonBox" name="buttonBox">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="standardButtons">
+ <set>QDialogButtonBox::Cancel|QDialogButtonBox::Ok</set>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <tabstops>
+ <tabstop>buttonBox</tabstop>
+ <tabstop>tabWidget</tabstop>
+ <tabstop>treeWidget</tabstop>
+ <tabstop>audioTree</tabstop>
+ </tabstops>
+ <resources/>
+ <connections>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>accepted()</signal>
+ <receiver>PreferencesDialog</receiver>
+ <slot>accept()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>248</x>
+ <y>254</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>157</x>
+ <y>274</y>
+ </hint>
+ </hints>
+ </connection>
+ <connection>
+ <sender>buttonBox</sender>
+ <signal>rejected()</signal>
+ <receiver>PreferencesDialog</receiver>
+ <slot>reject()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>316</x>
+ <y>260</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>286</x>
+ <y>274</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/gui/presetitem.cpp b/sdrbase/gui/presetitem.cpp
index 3d895f4..4f8f49f 100644
--- a/gui/presetitem.cpp
+++ b/sdrbase/gui/presetitem.cpp
@@ -15,10 +15,10 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
-#include "presetitem.h"
+#include "gui/presetitem.h"
-PresetItem::PresetItem(QTreeWidget* parent, const QStringList& strings, quint64 frequency) :
- QTreeWidgetItem(parent, strings),
+PresetItem::PresetItem(QTreeWidgetItem* parent, const QStringList& strings, quint64 frequency, int type) :
+ QTreeWidgetItem(parent, strings, type),
m_frequency(frequency)
{
}
diff --git a/gui/scale.cpp b/sdrbase/gui/scale.cpp
index 901a7b8..5e456ba 100644
--- a/gui/scale.cpp
+++ b/sdrbase/gui/scale.cpp
@@ -16,7 +16,7 @@
///////////////////////////////////////////////////////////////////////////////////
#include <QPainter>
-#include "scale.h"
+#include "gui/scale.h"
Scale::Scale(QWidget* parent) :
QWidget(parent)
diff --git a/gui/scaleengine.cpp b/sdrbase/gui/scaleengine.cpp
index b8c9e59..06bde36 100644
--- a/gui/scaleengine.cpp
+++ b/sdrbase/gui/scaleengine.cpp
@@ -1,569 +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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include <math.h>
-#include <QFontMetrics>
-#include <QDataStream>
-#include "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;
-}
+///////////////////////////////////////////////////////////////////////////////////
+// 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 <http://www.gnu.org/licenses/>. //
+///////////////////////////////////////////////////////////////////////////////////
+
+#include <math.h>
+#include <QFontMetrics>
+#include <QDataStream>
+#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/gui/scopewindow.cpp b/sdrbase/gui/scopewindow.cpp
index de70fe5..6188b64 100644
--- a/gui/scopewindow.cpp
+++ b/sdrbase/gui/scopewindow.cpp
@@ -15,14 +15,15 @@
// along with this program. If not, see <http://www.gnu.org/licenses/>. //
///////////////////////////////////////////////////////////////////////////////////
-#include "scopewindow.h"
+#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_timeStep(1)
+ m_timeBase(1)
{
ui->setupUi(this);
ui->scope->setDSPEngine(dspEngine);
@@ -39,16 +40,63 @@ void ScopeWindow::setSampleRate(int 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_timeStep;
+ 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)
@@ -60,18 +108,20 @@ void ScopeWindow::on_scope_traceSizeChanged(int)
void ScopeWindow::on_time_valueChanged(int value)
{
- m_timeStep = value;
+ m_timeBase = value;
on_scope_traceSizeChanged(0);
- ui->scope->setTimeStep(m_timeStep);
+ 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);
@@ -92,6 +142,7 @@ void ScopeWindow::on_displayMode_currentIndexChanged(int index)
void ScopeWindow::on_horizView_clicked()
{
+ m_displayOrientation = Qt::Horizontal;
if(ui->horizView->isChecked()) {
ui->vertView->setChecked(false);
ui->scope->setOrientation(Qt::Horizontal);
@@ -102,10 +153,29 @@ void ScopeWindow::on_horizView_clicked()
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/gui/scopewindow.ui b/sdrbase/gui/scopewindow.ui
index a2c7ffd..a2c7ffd 100644
--- a/gui/scopewindow.ui
+++ b/sdrbase/gui/scopewindow.ui
diff --git a/gui/valuedial.cpp b/sdrbase/gui/valuedial.cpp
index 9b1b392..f09a3a4 100644
--- a/gui/valuedial.cpp
+++ b/sdrbase/gui/valuedial.cpp
@@ -19,7 +19,7 @@
#include <QMouseEvent>
#include <QWheelEvent>
#include <QKeyEvent>
-#include "valuedial.h"
+#include "gui/valuedial.h"
ValueDial::ValueDial(QWidget* parent) :
QWidget(parent),
diff --git a/sdrbase/mainwindow.cpp b/sdrbase/mainwindow.cpp
new file mode 100644
index 0000000..dd11af9
--- /dev/null
+++ b/sdrbase/mainwindow.cpp
@@ -0,0 +1,506 @@
+///////////////////////////////////////////////////////////////////////////////////
+// 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 <http://www.gnu.org/licenses/>. //
+///////////////////////////////////////////////////////////////////////////////////
+
+#include <QInputDialog>
+#include <QMessageBox>
+#include <QDir>
+#include <QLabel>
+#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 "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);
+ addDockWidget(Qt::LeftDockWidgetArea, ui->inputDock);
+ addDockWidget(Qt::LeftDockWidgetArea, ui->processingDock);
+ addDockWidget(Qt::LeftDockWidgetArea, ui->presetDock);
+ ui->inputDock->show();
+ ui->processingDock->show();
+ ui->presetDock->show();
+
+ ui->menu_Window->addAction(ui->inputDock->toggleViewAction());
+ ui->menu_Window->addAction(ui->processingDock->toggleViewAction());
+ ui->menu_Window->addAction(ui->presetDock->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);
+
+ int sampleSourceIndex = m_pluginManager->selectSampleSource(-1); // select SampleSource from settings
+ if(sampleSourceIndex >= 0) {
+ bool sampleSourceSignalsBlocked = ui->sampleSource->blockSignals(true);
+ ui->sampleSource->setCurrentIndex(sampleSourceIndex);
+ ui->sampleSource->blockSignals(sampleSourceSignalsBlocked);
+ }
+
+ loadSettings();
+
+ 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::addDemodCreateAction(QAction* action)
+{
+ ui->menu_Demodulation->addAction(action);
+}
+
+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->clearDemods();
+ 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: %d: %s", message->id(), message->name());
+ if(message->id() == DSPEngineReport::ID()) {
+ 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<const Preset*>(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<const Preset*>(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());
+}
diff --git a/sdrbase/mainwindow.ui b/sdrbase/mainwindow.ui
new file mode 100644
index 0000000..2527bfa
--- /dev/null
+++ b/sdrbase/mainwindow.ui
@@ -0,0 +1,495 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>MainWindow</class>
+ <widget class="QMainWindow" name="MainWindow">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>1012</width>
+ <height>706</height>
+ </rect>
+ </property>
+ <property name="windowTitle">
+ <string>SDRangelove</string>
+ </property>
+ <property name="windowIcon">
+ <iconset resource="resources/res.qrc">
+ <normaloff>:/appicon.png</normaloff>:/appicon.png</iconset>
+ </property>
+ <property name="animated">
+ <bool>true</bool>
+ </property>
+ <widget class="QWidget" name="centralWidget">
+ <layout class="QVBoxLayout" name="verticalLayout_2">
+ <property name="leftMargin">
+ <number>0</number>
+ </property>
+ <property name="topMargin">
+ <number>0</number>
+ </property>
+ <property name="rightMargin">
+ <number>0</number>
+ </property>
+ <property name="bottomMargin">
+ <number>0</number>
+ </property>
+ <item>
+ <widget class="GLSpectrum" name="glSpectrum" native="true">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="MinimumExpanding" vsizetype="MinimumExpanding">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ <widget class="QMenuBar" name="menuBar">
+ <property name="geometry">
+ <rect>
+ <x>0</x>
+ <y>0</y>
+ <width>1012</width>
+ <height>24</height>
+ </rect>
+ </property>
+ <widget class="QMenu" name="menu_File">
+ <property name="title">
+ <string>&amp;File</string>
+ </property>
+ <addaction name="action_Exit"/>
+ </widget>
+ <widget class="QMenu" name="menu_Options">
+ <property name="title">
+ <string>&amp;Options</string>
+ </property>
+ <addaction name="actionOsmoSDR_Firmware_Upgrade"/>
+ <addaction name="separator"/>
+ <addaction name="action_Preferences"/>
+ </widget>
+ <widget class="QMenu" name="menu_Acquisition">
+ <property name="title">
+ <string>&amp;Acquisition</string>
+ </property>
+ <addaction name="action_Start"/>
+ <addaction name="action_Stop"/>
+ </widget>
+ <widget class="QMenu" name="menu_View">
+ <property name="title">
+ <string>&amp;View</string>
+ </property>
+ <addaction name="action_View_Fullscreen"/>
+ <addaction name="separator"/>
+ <addaction name="action_Oscilloscope"/>
+ </widget>
+ <widget class="QMenu" name="menu_Help">
+ <property name="title">
+ <string>&amp;Help</string>
+ </property>
+ <addaction name="action_Open_Website"/>
+ <addaction name="action_Check_for_Update"/>
+ <addaction name="separator"/>
+ <addaction name="action_Loaded_Plugins"/>
+ <addaction name="separator"/>
+ <addaction name="action_About"/>
+ </widget>
+ <widget class="QMenu" name="menu_Demodulation">
+ <property name="title">
+ <string>&amp;Demodulation</string>
+ </property>
+ </widget>
+ <widget class="QMenu" name="menu_Window">
+ <property name="title">
+ <string>&amp;Window</string>
+ </property>
+ </widget>
+ <addaction name="menu_File"/>
+ <addaction name="menu_View"/>
+ <addaction name="menu_Acquisition"/>
+ <addaction name="menu_Demodulation"/>
+ <addaction name="menu_Options"/>
+ <addaction name="menu_Window"/>
+ <addaction name="menu_Help"/>
+ </widget>
+ <widget class="QToolBar" name="mainToolBar">
+ <attribute name="toolBarArea">
+ <enum>TopToolBarArea</enum>
+ </attribute>
+ <attribute name="toolBarBreak">
+ <bool>false</bool>
+ </attribute>
+ </widget>
+ <widget class="QStatusBar" name="statusBar"/>
+ <widget class="QDockWidget" name="presetDock">
+ <property name="windowTitle">
+ <string>Presets</string>
+ </property>
+ <attribute name="dockWidgetArea">
+ <number>1</number>
+ </attribute>
+ <widget class="QWidget" name="dockWidgetContents">
+ <layout class="QGridLayout" name="gridLayout_6">
+ <property name="leftMargin">
+ <number>2</number>
+ </property>
+ <property name="topMargin">
+ <number>2</number>
+ </property>
+ <property name="rightMargin">
+ <number>2</number>
+ </property>
+ <property name="bottomMargin">
+ <number>2</number>
+ </property>
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <item row="5" column="1">
+ <widget class="QToolButton" name="presetSave">
+ <property name="toolTip">
+ <string>Save current settings as preset</string>
+ </property>
+ <property name="text">
+ <string>...</string>
+ </property>
+ <property name="icon">
+ <iconset resource="resources/res.qrc">
+ <normaloff>:/preset-save.png</normaloff>:/preset-save.png</iconset>
+ </property>
+ <property name="iconSize">
+ <size>
+ <width>16</width>
+ <height>16</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="5">
+ <widget class="QToolButton" name="presetLoad">
+ <property name="toolTip">
+ <string>Load selected preset</string>
+ </property>
+ <property name="text">
+ <string>...</string>
+ </property>
+ <property name="icon">
+ <iconset resource="resources/res.qrc">
+ <normaloff>:/preset-load.png</normaloff>:/preset-load.png</iconset>
+ </property>
+ <property name="iconSize">
+ <size>
+ <width>16</width>
+ <height>16</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="5" column="3" colspan="2">
+ <spacer name="horizontalSpacer_3">
+ <property name="orientation">
+ <enum>Qt::Horizontal</enum>
+ </property>
+ <property name="sizeHint" stdset="0">
+ <size>
+ <width>40</width>
+ <height>20</height>
+ </size>
+ </property>
+ </spacer>
+ </item>
+ <item row="5" column="2">
+ <widget class="QToolButton" name="presetDelete">
+ <property name="toolTip">
+ <string>Delete selected preset</string>
+ </property>
+ <property name="text">
+ <string>...</string>
+ </property>
+ <property name="icon">
+ <iconset resource="resources/res.qrc">
+ <normaloff>:/preset-delete.png</normaloff>:/preset-delete.png</iconset>
+ </property>
+ <property name="iconSize">
+ <size>
+ <width>16</width>
+ <height>16</height>
+ </size>
+ </property>
+ </widget>
+ </item>
+ <item row="1" column="1" rowspan="4" colspan="5">
+ <widget class="QTreeWidget" name="presetTree">
+ <property name="allColumnsShowFocus">
+ <bool>true</bool>
+ </property>
+ <column>
+ <property name="text">
+ <string>Frequency</string>
+ </property>
+ </column>
+ <column>
+ <property name="text">
+ <string>Description</string>
+ </property>
+ </column>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ <widget class="QDockWidget" name="processingDock">
+ <property name="windowTitle">
+ <string>Processing and Display</string>
+ </property>
+ <attribute name="dockWidgetArea">
+ <number>1</number>
+ </attribute>
+ <widget class="QWidget" name="dockWidgetContents_4">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout">
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <property name="leftMargin">
+ <number>2</number>
+ </property>
+ <property name="topMargin">
+ <number>2</number>
+ </property>
+ <property name="rightMargin">
+ <number>2</number>
+ </property>
+ <property name="bottomMargin">
+ <number>2</number>
+ </property>
+ <item>
+ <layout class="QHBoxLayout" name="horizontalLayout">
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <item>
+ <widget class="QToolButton" name="dcOffset">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="toolTip">
+ <string>Compensate DC offset</string>
+ </property>
+ <property name="text">
+ <string>DC Offset Corr</string>
+ </property>
+ <property name="checkable">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ <item>
+ <widget class="QToolButton" name="iqImbalance">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="MinimumExpanding" vsizetype="Fixed">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <property name="toolTip">
+ <string>Compensate I/Q imbalance</string>
+ </property>
+ <property name="text">
+ <string>I/Q Imbal. Corr</string>
+ </property>
+ <property name="checkable">
+ <bool>true</bool>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </item>
+ <item>
+ <widget class="GLSpectrumGUI" name="glSpectrumGUI" native="true"/>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ <widget class="QDockWidget" name="inputDock">
+ <property name="windowTitle">
+ <string>Sample Source</string>
+ </property>
+ <attribute name="dockWidgetArea">
+ <number>1</number>
+ </attribute>
+ <widget class="QWidget" name="dockWidgetContents_6">
+ <property name="sizePolicy">
+ <sizepolicy hsizetype="Preferred" vsizetype="Maximum">
+ <horstretch>0</horstretch>
+ <verstretch>0</verstretch>
+ </sizepolicy>
+ </property>
+ <layout class="QVBoxLayout" name="verticalLayout_3">
+ <property name="spacing">
+ <number>3</number>
+ </property>
+ <property name="leftMargin">
+ <number>2</number>
+ </property>
+ <property name="topMargin">
+ <number>2</number>
+ </property>
+ <property name="rightMargin">
+ <number>2</number>
+ </property>
+ <property name="bottomMargin">
+ <number>2</number>
+ </property>
+ <item>
+ <widget class="QComboBox" name="sampleSource">
+ <property name="sizeAdjustPolicy">
+ <enum>QComboBox::AdjustToMinimumContentsLength</enum>
+ </property>
+ </widget>
+ </item>
+ </layout>
+ </widget>
+ </widget>
+ <action name="action_Exit">
+ <property name="text">
+ <string>E&amp;xit</string>
+ </property>
+ <property name="shortcut">
+ <string>Ctrl+Q</string>
+ </property>
+ </action>
+ <action name="action_Start">
+ <property name="text">
+ <string>&amp;Start</string>
+ </property>
+ <property name="shortcut">
+ <string>F5</string>
+ </property>
+ </action>
+ <action name="action_Stop">
+ <property name="text">
+ <string>&amp;Stop</string>
+ </property>
+ <property name="shortcut">
+ <string>F6</string>
+ </property>
+ </action>
+ <action name="action_View_Fullscreen">
+ <property name="checkable">
+ <bool>true</bool>
+ </property>
+ <property name="text">
+ <string>&amp;Fullscreen</string>
+ </property>
+ <property name="shortcut">
+ <string>F11</string>
+ </property>
+ </action>
+ <action name="actionOsmoSDR_Firmware_Upgrade">
+ <property name="text">
+ <string>OsmoSDR &amp;Firmware Upgrade...</string>
+ </property>
+ </action>
+ <action name="action_Oscilloscope">
+ <property name="checkable">
+ <bool>true</bool>
+ </property>
+ <property name="text">
+ <string>&amp;Oscilloscope</string>
+ </property>
+ <property name="shortcut">
+ <string>F8</string>
+ </property>
+ </action>
+ <action name="action_About">
+ <property name="text">
+ <string>&amp;About SDRangelove...</string>
+ </property>
+ </action>
+ <action name="action_Open_Website">
+ <property name="text">
+ <string>&amp;Open Website</string>
+ </property>
+ </action>
+ <action name="action_Check_for_Update">
+ <property name="text">
+ <string>Check for &amp;Update...</string>
+ </property>
+ </action>
+ <action name="action_Preferences">
+ <property name="text">
+ <string>&amp;Preferences...</string>
+ </property>
+ </action>
+ <action name="action_Demod_NFM">
+ <property name="text">
+ <string>N&amp;FM</string>
+ </property>
+ </action>
+ <action name="action_Tetra">
+ <property name="text">
+ <string>&amp;Tetra</string>
+ </property>
+ </action>
+ <action name="action_Loaded_Plugins">
+ <property name="text">
+ <string>Loaded &amp;Plugins...</string>
+ </property>
+ </action>
+ <zorder>presetDock</zorder>
+ </widget>
+ <layoutdefault spacing="6" margin="11"/>
+ <customwidgets>
+ <customwidget>
+ <class>GLSpectrum</class>
+ <extends>QWidget</extends>
+ <header>gui/glspectrum.h</header>
+ <container>1</container>
+ </customwidget>
+ <customwidget>
+ <class>GLSpectrumGUI</class>
+ <extends>QWidget</extends>
+ <header>gui/glspectrumgui.h</header>
+ <container>1</container>
+ </customwidget>
+ </customwidgets>
+ <tabstops>
+ <tabstop>presetTree</tabstop>
+ <tabstop>presetSave</tabstop>
+ <tabstop>presetDelete</tabstop>
+ <tabstop>presetLoad</tabstop>
+ <tabstop>dcOffset</tabstop>
+ <tabstop>iqImbalance</tabstop>
+ </tabstops>
+ <resources>
+ <include location="resources/res.qrc"/>
+ </resources>
+ <connections>
+ <connection>
+ <sender>action_Exit</sender>
+ <signal>triggered()</signal>
+ <receiver>MainWindow</receiver>
+ <slot>close()</slot>
+ <hints>
+ <hint type="sourcelabel">
+ <x>-1</x>
+ <y>-1</y>
+ </hint>
+ <hint type="destinationlabel">
+ <x>462</x>
+ <y>332</y>
+ </hint>
+ </hints>
+ </connection>
+ </connections>
+</ui>
diff --git a/sdrbase/plugin/pluginapi.cpp b/sdrbase/plugin/pluginapi.cpp
new file mode 100644
index 0000000..d1059fe
--- /dev/null
+++ b/sdrbase/plugin/pluginapi.cpp
@@ -0,0 +1,84 @@
+#include <QDockWidget>
+#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::registerDemodulator(const QString& demodName, PluginInterface* plugin, QAction* action)
+{
+ m_pluginManager->registerDemodulator(demodName, plugin, action);
+}
+
+void PluginAPI::registerDemodulatorInstance(const QString& demodName, PluginGUI* pluginGUI)
+{
+ m_pluginManager->registerDemodulatorInstance(demodName, 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 0000000..a678da3
--- /dev/null
+++ b/sdrbase/plugin/plugingui.cpp
@@ -0,0 +1,26 @@
+#include "plugin/plugingui.h"
+
+PluginGUI::PluginGUI(QWidget* parent) :
+ QWidget(parent)
+{
+}
+
+void PluginGUI::setWidgetName(const QString& name)
+{
+ setObjectName(name);
+}
+
+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 0000000..1b564ab
--- /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 0000000..f0fc62c
--- /dev/null
+++ b/sdrbase/plugin/pluginmanager.cpp
@@ -0,0 +1,242 @@
+#include <QApplication>
+#include <QPluginLoader>
+#include <QComboBox>
+#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());
+ pluginsDir.cd("plugins");
+
+ 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::registerDemodulator(const QString& demodName, PluginInterface* plugin, QAction* action)
+{
+ m_demodRegistrations.append(DemodRegistration(demodName, plugin));
+ m_mainWindow->addDemodCreateAction(action);
+}
+
+void PluginManager::registerDemodulatorInstance(const QString& demodName, PluginGUI* pluginGUI)
+{
+ connect(pluginGUI, SIGNAL(destroyed(QObject*)), this, SLOT(demodInstanceDestroyed(QObject*)));
+ m_demodInstanceRegistrations.append(DemodInstanceRegistration(demodName, pluginGUI));
+ renameDemodInstances();
+}
+
+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 demods and clear list
+ DemodInstanceRegistrations availableDemods = m_demodInstanceRegistrations;
+ m_demodInstanceRegistrations.clear();
+
+ for(int i = 0; i < preset->getDemodCount(); i++) {
+ const Preset::DemodConfig& demodConfig = preset->getDemodConfig(i);
+ DemodInstanceRegistration reg;
+ // if we have one instance available already, use it
+ for(int i = 0; i < availableDemods.count(); i++) {
+ qDebug("compare [%s] vs [%s]", qPrintable(availableDemods[i].m_demodName), qPrintable(demodConfig.m_demod));
+ if(availableDemods[i].m_demodName == demodConfig.m_demod) {
+ qDebug("demod [%s] found", qPrintable(availableDemods[i].m_demodName));
+ reg = availableDemods.takeAt(i);
+ m_demodInstanceRegistrations.append(reg);
+ break;
+ }
+ }
+ // if we haven't one already, create one
+ if(reg.m_gui == NULL) {
+ for(int i = 0; i < m_demodRegistrations.count(); i++) {
+ if(m_demodRegistrations[i].m_demodName == demodConfig.m_demod) {
+ qDebug("creating new demod [%s]", qPrintable(demodConfig.m_demod));
+ reg = DemodInstanceRegistration(demodConfig.m_demod, m_demodRegistrations[i].m_plugin->createDemod(demodConfig.m_demod));
+ break;
+ }
+ }
+ }
+ if(reg.m_gui != NULL) {
+ reg.m_gui->deserialize(demodConfig.m_config);
+ reg.m_gui->raise();
+ }
+ }
+
+ // everything, that is still "available" is not needed anymore
+ for(int i = 0; i < availableDemods.count(); i++) {
+ qDebug("destroying spare demod [%s]", qPrintable(availableDemods[i].m_demodName));
+ availableDemods[i].m_gui->destroy();
+ }
+
+ renameDemodInstances();
+
+ 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());
+ }
+ for(int i = 0; i < m_demodInstanceRegistrations.size(); i++)
+ preset->addDemod(m_demodInstanceRegistrations[i].m_demodName, m_demodInstanceRegistrations[i].m_gui->serialize());
+}
+
+void PluginManager::freeAll()
+{
+ m_dspEngine->stopAcquistion();
+
+ while(!m_demodInstanceRegistrations.isEmpty()) {
+ DemodInstanceRegistration reg(m_demodInstanceRegistrations.takeLast());
+ reg.m_gui->disconnect(this);
+ 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->destination() == NULL) || (message->destination() == m_sampleSourceInstance)) {
+ if(m_sampleSourceInstance->handleMessage(message))
+ return true;
+ }
+ }
+
+ for(DemodInstanceRegistrations::iterator it = m_demodInstanceRegistrations.begin(); it != m_demodInstanceRegistrations.end(); ++it) {
+ if((message->destination() == NULL) || (message->destination() == 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);
+ m_mainWindow->setInputGUI(m_sampleSourceInstance);
+ return index;
+}
+
+void PluginManager::demodInstanceDestroyed(QObject* object)
+{
+ for(DemodInstanceRegistrations::iterator it = m_demodInstanceRegistrations.begin(); it != m_demodInstanceRegistrations.end(); ++it) {
+ if(it->m_gui == object) {
+ m_demodInstanceRegistrations.erase(it);
+ break;
+ }
+ }
+ renameDemodInstances();
+}
+
+void PluginManager::loadPlugins(const QDir& dir)
+{
+ QDir pluginsDir(dir);
+ foreach(QString fileName, pluginsDir.entryList(QDir::Files)) {
+ QPluginLoader loader(pluginsDir.absoluteFilePath(fileName));
+ PluginInterface* plugin = qobject_cast<PluginInterface*>(loader.instance());
+ if(loader.isLoaded())
+ qDebug("loaded plugin %s", qPrintable(fileName));
+ if(plugin != NULL)
+ m_plugins.append(Plugin(fileName, plugin));
+ else loader.unload();
+ }
+ foreach(QString dirName, pluginsDir.entryList(QDir::Dirs | QDir::NoDotAndDotDot))
+ loadPlugins(pluginsDir.absoluteFilePath(dirName));
+}
+
+void PluginManager::renameDemodInstances()
+{
+ for(int i = 0; i < m_demodInstanceRegistrations.count(); i++) {
+ m_demodInstanceRegistrations[i].m_gui->setWidgetName(QString("%1:%2").arg(m_demodInstanceRegistrations[i].m_demodName).arg(i));
+ }
+}
diff --git a/resources/appicon.ico b/sdrbase/resources/appicon.ico
index f2c7692..f2c7692 100644
--- a/resources/appicon.ico
+++ b/sdrbase/resources/appicon.ico
Binary files differ
diff --git a/resources/appicon.png b/sdrbase/resources/appicon.png
index c481cc3..c481cc3 100644
--- a/resources/appicon.png
+++ b/sdrbase/resources/appicon.png
Binary files differ
diff --git a/resources/histogram.png b/sdrbase/resources/histogram.png
index 673f2fa..673f2fa 100644
--- a/resources/histogram.png
+++ b/sdrbase/resources/histogram.png
Binary files differ
diff --git a/resources/horizontal.png b/sdrbase/resources/horizontal.png
index 187b23c..187b23c 100644
--- a/resources/horizontal.png
+++ b/sdrbase/resources/horizontal.png
Binary files differ
diff --git a/resources/livespectrum.png b/sdrbase/resources/livespectrum.png
index a64ea21..a64ea21 100644
--- a/resources/livespectrum.png
+++ b/sdrbase/resources/livespectrum.png
Binary files differ
diff --git a/resources/preset-delete.png b/sdrbase/resources/preset-delete.png
index d141552..d141552 100644
--- a/resources/preset-delete.png
+++ b/sdrbase/resources/preset-delete.png
Binary files differ
diff --git a/resources/preset-load.png b/sdrbase/resources/preset-load.png
index c706198..c706198 100644
--- a/resources/preset-load.png
+++ b/sdrbase/resources/preset-load.png
Binary files differ
diff --git a/resources/preset-save.png b/sdrbase/resources/preset-save.png
index 0ccc13e..0ccc13e 100644
--- a/resources/preset-save.png
+++ b/sdrbase/resources/preset-save.png
Binary files differ
diff --git a/resources/res.qrc b/sdrbase/resources/res.qrc
index e2a87d8..e2a87d8 100644
--- a/resources/res.qrc
+++ b/sdrbase/resources/res.qrc
diff --git a/resources/sdrangelove.rc b/sdrbase/resources/sdrangelove.rc
index b943fc3..b943fc3 100644
--- a/resources/sdrangelove.rc
+++ b/sdrbase/resources/sdrangelove.rc
diff --git a/resources/vertical.png b/sdrbase/resources/vertical.png
index ad78f34..ad78f34 100644
--- a/resources/vertical.png
+++ b/sdrbase/resources/vertical.png
Binary files differ
diff --git a/resources/waterfall.png b/sdrbase/resources/waterfall.png
index 9b2b727..9b2b727 100644
--- a/resources/waterfall.png
+++ b/sdrbase/resources/waterfall.png
Binary files differ
diff --git a/sdrbase/settings/preferences.cpp b/sdrbase/settings/preferences.cpp
new file mode 100644
index 0000000..c649cda
--- /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 0000000..189012e
--- /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_demodConfigs.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_demodConfigs.size());
+ for(int i = 0; i < m_demodConfigs.size(); i++) {
+ s.writeString(101 + i * 2, m_demodConfigs[i].m_demod);
+ s.writeBlob(102 + i * 2, m_demodConfigs[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 demodCount = 0;
+ d.readS32(100, &demodCount, 0);
+ for(int i = 0; i < demodCount; i++) {
+ QString demod;
+ QByteArray config;
+ d.readString(101 + i * 2, &demod, "unknown-demod");
+ d.readBlob(102 + i * 2, &config);
+ m_demodConfigs.append(DemodConfig(demod, config));
+ }
+ return true;
+ } else {
+ resetToDefaults();
+ return false;
+ }
+}
diff --git a/sdrbase/settings/settings.cpp b/sdrbase/settings/settings.cpp
new file mode 100644
index 0000000..b7012bc
--- /dev/null
+++ b/sdrbase/settings/settings.cpp
@@ -0,0 +1,76 @@
+#include <QSettings>
+#include <QStringList>
+#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 0000000..df45080
--- /dev/null
+++ b/sdrbase/util/message.cpp
@@ -0,0 +1,113 @@
+#include <vector>
+#include <QWaitCondition>
+#include <QMutex>
+#include "util/message.h"
+#include "util/messagequeue.h"
+#include "util/spinlock.h"
+
+class Registry {
+public:
+ static Registry* getInstance()
+ {
+ SpinlockHolder spinlockHolder(&m_registryLock);
+ if(m_instance != NULL) {
+ return m_instance;
+ } else {
+ m_instance = new Registry;
+ return m_instance;
+ }
+ }
+
+ int registerMessage(const char* name)
+ {
+ SpinlockHolder spinlockHolder(&m_registryLock);
+ m_registry.push_back(name);
+ return m_registry.size() - 1;
+ }
+
+ const char* name(int id) const
+ {
+ return m_registry[id];
+ }
+
+private:
+ static Registry* m_instance;
+ static Spinlock m_registryLock;
+ std::vector<const char*> m_registry;
+
+ Registry() :
+ m_registry()
+ { }
+};
+
+Registry* Registry::m_instance = NULL;
+Spinlock Registry::m_registryLock;
+
+MessageRegistrator::MessageRegistrator(const char* name)
+{
+ Registry* registry = Registry::getInstance();
+ m_registeredID = registry->registerMessage(name);
+ qDebug("%s registered as %d", name, m_registeredID);
+}
+
+Message::~Message()
+{
+ if(m_waitCondition != NULL)
+ delete m_waitCondition;
+ if(m_mutex != NULL)
+ delete m_mutex;
+}
+
+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))
+ 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;
+ m_waitCondition->wakeAll();
+ } else {
+ delete this;
+ }
+}
+
+const char* Message::name() const
+{
+ return Registry::getInstance()->name(m_id);
+}
+
+Message::Message(int id) :
+ m_id(id),
+ m_destination(NULL),
+ m_synchronous(false),
+ m_waitCondition(NULL),
+ m_mutex(NULL),
+ m_complete(0)
+{
+}
diff --git a/util/messagequeue.cpp b/sdrbase/util/messagequeue.cpp
index 41790bb..53bd3e3 100644
--- a/util/messagequeue.cpp
+++ b/sdrbase/util/messagequeue.cpp
@@ -1,5 +1,5 @@
-#include "messagequeue.h"
-#include "message.h"
+#include "util/messagequeue.h"
+#include "util/message.h"
MessageQueue::MessageQueue(QObject* parent) :
QObject(parent),
@@ -10,10 +10,9 @@ MessageQueue::MessageQueue(QObject* parent) :
MessageQueue::~MessageQueue()
{
- SpinlockHolder spinlockHolder(&m_lock);
-
- while(!m_queue.isEmpty())
- delete m_queue.takeFirst();
+ Message* cmd;
+ while((cmd = accept()) != NULL)
+ cmd->completed();
}
void MessageQueue::submit(Message* message)
diff --git a/util/miniz.cpp b/sdrbase/util/miniz.cpp
index e962a23..bc99568 100644
--- a/util/miniz.cpp
+++ b/sdrbase/util/miniz.cpp
@@ -1,4835 +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 <richgel99@gmail.com>, 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 <time.h> (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 <bruced@valvesoftware.com> 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 <stdlib.h>
-#include <stdint.h>
-
-#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
-#include <time.h>
-#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 <string.h>
-#include <assert.h>
-
-#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 __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<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key;
- if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
- }
- A[n-2].m_key = 0; for (next=n-3; next>=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 <stdio.h>
- #include <sys/stat.h>
-
- #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 <sys/utime.h>
- #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 <sys/utime.h>
- #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 <sys\utime.h>
- #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 <utime.h>
- #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, &central_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 <http://unlicense.org/>
-*/
+/* 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 <richgel99@gmail.com>, 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 <time.h> (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 <bruced@valvesoftware.com> 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 <stdlib.h>
+#include <stdint.h>
+
+#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS)
+#include <time.h>
+#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 <string.h>
+#include <assert.h>
+
+#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<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key;
+ if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key);
+ }
+ A[n-2].m_key = 0; for (next=n-3; next>=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 <stdio.h>
+ #include <sys/stat.h>
+
+ #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 <sys/utime.h>
+ #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 <sys/utime.h>
+ #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 <sys\utime.h>
+ #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 <utime.h>
+ #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, &central_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 <http://unlicense.org/>
+*/
diff --git a/sdrbase/util/simpleserializer.cpp b/sdrbase/util/simpleserializer.cpp
new file mode 100644
index 0000000..4574108
--- /dev/null
+++ b/sdrbase/util/simpleserializer.cpp
@@ -0,0 +1,704 @@
+#include <stdint.h>
+#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 <bool> 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(int 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(int 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(int 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(int 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(int 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 < 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 0000000..f923ba4
--- /dev/null
+++ b/sdrbase/util/spinlock.cpp
@@ -0,0 +1 @@
+#include "util/spinlock.h"
diff --git a/settings.cpp b/settings.cpp
deleted file mode 100644
index 16fd0c0..0000000
--- a/settings.cpp
+++ /dev/null
@@ -1,101 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#include <QSettings>
-#include "settings.h"
-
-Settings::Settings()
-{
- defaults();
-}
-
-Settings& Settings::operator=(const Settings& other)
-{
- m_fftSize = other.m_fftSize;
- m_fftOverlap = other.m_fftOverlap;
- m_fftWindow = other.m_fftWindow;
- m_displayWaterfall = other.m_displayWaterfall;
- m_invertedWaterfall = other.m_invertedWaterfall;
- m_displayLiveSpectrum = other.m_displayLiveSpectrum;
- m_displayHistogram = other.displayHistogram();
- m_dcOffsetCorrection = other.m_dcOffsetCorrection;
- m_iqImbalanceCorrection = other.m_iqImbalanceCorrection;
- m_displayScope = other.m_displayScope;
- m_centerFrequency = other.m_centerFrequency;
- m_sourceSettings = other.m_sourceSettings;
- return *this;
-}
-
-void Settings::defaults()
-{
- m_fftSize = 1024;
- m_fftOverlap = 10;
- m_fftWindow = 3;
- m_displayWaterfall = true;
- m_invertedWaterfall = false;
- m_displayLiveSpectrum = true;
- m_displayHistogram = true;
- m_dcOffsetCorrection = true;
- m_iqImbalanceCorrection = true;
- m_displayScope = true;
- m_centerFrequency = 0;
- m_sourceSettings.clear();
-}
-
-void Settings::load(QSettings* settings, const QString& path)
-{
- settings->beginGroup(path);
- m_fftSize = settings->value("fftsize", 512).toInt();
- m_fftOverlap = settings->value("fftoverlap", 10).toInt();
- m_fftWindow = settings->value("fftwindow", 3).toInt();
- m_displayWaterfall = settings->value("displaywaterfall", true).toBool();
- m_invertedWaterfall = settings->value("invertedwaterfall", false).toBool();
- m_displayLiveSpectrum = settings->value("displaylivespectrum", true).toBool();
- m_displayHistogram = settings->value("displayhistogram", true).toBool();
- m_dcOffsetCorrection = settings->value("dcoffsetcorrection", true).toBool();
- m_iqImbalanceCorrection = settings->value("iqimbalancecorrection", true).toBool();
- m_centerFrequency = settings->value("centerfrequency", 0).toLongLong();
- m_sourceSettings = settings->value("sourcesettings", "").toString();
-
- if(path == "") {
- m_displayScope = settings->value("displayscope", true).toBool();
- }
-
- settings->endGroup();
-}
-
-void Settings::save(QSettings* settings, const QString& path) const
-{
- settings->beginGroup(path);
- settings->setValue("fftsize", m_fftSize);
- settings->setValue("fftoverlap", m_fftOverlap);
- settings->setValue("fftwindow", m_fftWindow);
- settings->setValue("displaywaterfall", m_displayWaterfall);
- settings->setValue("invertedwaterfall", m_invertedWaterfall);
- settings->setValue("displaylivespectrum", m_displayLiveSpectrum);
- settings->setValue("displayhistogram", m_displayHistogram);
- settings->setValue("dcoffsetcorrection", m_dcOffsetCorrection);
- settings->setValue("iqimbalancecorrection", m_iqImbalanceCorrection);
- settings->setValue("centerfrequency", m_centerFrequency);
- settings->setValue("sourcesettings", m_sourceSettings);
-
- if(path == "") {
- settings->setValue("displayscope", m_displayScope);
- }
-
- settings->endGroup();
-}
diff --git a/settings.h b/settings.h
deleted file mode 100644
index fed7800..0000000
--- a/settings.h
+++ /dev/null
@@ -1,85 +0,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 <http://www.gnu.org/licenses/>. //
-///////////////////////////////////////////////////////////////////////////////////
-
-#ifndef INCLUDE_SETTINGS_H
-#define INCLUDE_SETTINGS_H
-
-#include <QtGlobal>
-#include <QSettings>
-
-class Settings {
-public:
- Settings();
- Settings(const Settings& other);
- Settings& operator=(const Settings& other);
-
- void defaults();
- void load(QSettings* settings, const QString& path);
- void save(QSettings* settings, const QString& path) const;
-
- int fftSize() const { return m_fftSize; }
- void setFFTSize(int v) { m_fftSize = v; }
-
- int fftOverlap() const { return m_fftOverlap; }
- void setFFTOverlap(int v) { m_fftOverlap = v; }
-
- int fftWindow() const { return m_fftWindow; }
- void setFFTWindow(int v) { m_fftWindow = v; }
-
- bool displayWaterfall() const { return m_displayWaterfall; }
- void setDisplayWaterfall(bool v) { m_displayWaterfall = v; }
-
- bool invertedWaterfall() const { return m_invertedWaterfall; }
- void setInvertedWaterfall(bool v) { m_invertedWaterfall = v; }
-
- bool displayLiveSpectrum() const { return m_displayLiveSpectrum; }
- void setDisplayLiveSpectrum(bool v) { m_displayLiveSpectrum = v; }
-
- bool displayHistogram() const { return m_displayHistogram; }
- void setDisplayHistogram(bool v) { m_displayHistogram = v; }
-
- bool dcOffsetCorrection() const { return m_dcOffsetCorrection; }
- void setDCOffsetCorrection(bool v) { m_dcOffsetCorrection = v; }
-
- bool iqImbalanceCorrection() const { return m_iqImbalanceCorrection; }
- void setIQImbalanceCorrection(bool v) { m_iqImbalanceCorrection = v; }
-
- bool displayScope() const { return m_displayScope; }
- void setDisplayScope(bool v) { m_displayScope = v; }
-
- quint64 centerFrequency() const { return m_centerFrequency; }
- void setCenterFrequency(quint64 v) { m_centerFrequency = v; }
-
- const QString& sourceSettings() const { return m_sourceSettings; }
- void setSourceSettings(const QString& v) { m_sourceSettings = v; }
-
-private:
- int m_fftSize;
- int m_fftOverlap;
- int m_fftWindow;
- bool m_displayWaterfall;
- bool m_invertedWaterfall;
- bool m_displayLiveSpectrum;
- bool m_displayHistogram;
- bool m_dcOffsetCorrection;
- bool m_iqImbalanceCorrection;
- bool m_displayScope;
- quint64 m_centerFrequency;
- QString m_sourceSettings;
-};
-
-#endif // INCLUDE_SETTINGS_H
diff --git a/util/message.cpp b/util/message.cpp
deleted file mode 100644
index 6e1b4c6..0000000
--- a/util/message.cpp
+++ /dev/null
@@ -1,57 +0,0 @@
-#include <QWaitCondition>
-#include <QMutex>
-#include "message.h"
-#include "messagequeue.h"
-
-Message::Message() :
- 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;
-}
-
-void Message::submit(MessageQueue* queue)
-{
- m_synchronous = false;
- queue->submit(this);
-}
-
-int Message::execute(MessageQueue* queue)
-{
- 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))
- 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;
- m_waitCondition->wakeAll();
- } else {
- delete this;
- }
-}
diff --git a/util/message.h b/util/message.h
deleted file mode 100644
index cd1f391..0000000
--- a/util/message.h
+++ /dev/null
@@ -1,32 +0,0 @@
-#ifndef INCLUDE_MESSAGE_H
-#define INCLUDE_MESSAGE_H
-
-#include <QAtomicInt>
-
-class MessageQueue;
-class QWaitCondition;
-class QMutex;
-
-class Message {
-public:
- Message();
- virtual ~Message();
-
- void submit(MessageQueue* queue);
- int execute(MessageQueue* queue);
-
- void completed(int result = 0);
-
- virtual int type() const = 0;
- virtual const char* name() const = 0;
-
-protected:
- // stuff for synchronous messages
- bool m_synchronous;
- QWaitCondition* m_waitCondition;
- QMutex* m_mutex;
- QAtomicInt m_complete;
- int m_result;
-};
-
-#endif // INCLUDE_MESSAGE_H
diff --git a/util/spinlock.cpp b/util/spinlock.cpp
deleted file mode 100644
index 63a803a..0000000
--- a/util/spinlock.cpp
+++ /dev/null
@@ -1 +0,0 @@
-#include "spinlock.h"