Repository: lordmulder/DynamicAudioNormalizer Branch: master Commit: 3d991fd3c833 Files: 157 Total size: 2.1 MB Directory structure: gitextract_sinsno6i/ ├── .gitignore ├── DynamicAudioNormalizerAPI/ │ ├── DynamicAudioNormalizerAPI_VS2013.vcxproj │ ├── DynamicAudioNormalizerAPI_VS2013.vcxproj.filters │ ├── DynamicAudioNormalizerAPI_VS2015.vcxproj │ ├── DynamicAudioNormalizerAPI_VS2015.vcxproj.filters │ ├── DynamicAudioNormalizerAPI_VS2017.vcxproj │ ├── DynamicAudioNormalizerAPI_VS2017.vcxproj.filters │ ├── include/ │ │ └── DynamicAudioNormalizer.h │ ├── makefile │ ├── res/ │ │ └── DynamicAudioNormalizerAPI.rc │ └── src/ │ ├── Binding_C.cpp │ ├── Binding_JNI.cpp │ ├── DLLMain.cpp │ ├── DynamicAudioNormalizer.cpp │ ├── FrameBuffer.cpp │ ├── FrameBuffer.h │ ├── GaussianFilter.cpp │ ├── GaussianFilter.h │ ├── Logging.cpp │ ├── Logging.h │ ├── Test_API.c │ ├── Version.cpp │ └── Version.h ├── DynamicAudioNormalizerCLI/ │ ├── DynamicAudioNormalizerCLI_VS2013.vcxproj │ ├── DynamicAudioNormalizerCLI_VS2013.vcxproj.filters │ ├── DynamicAudioNormalizerCLI_VS2015.vcxproj │ ├── DynamicAudioNormalizerCLI_VS2015.vcxproj.filters │ ├── DynamicAudioNormalizerCLI_VS2017.vcxproj │ ├── DynamicAudioNormalizerCLI_VS2017.vcxproj.filters │ ├── makefile │ ├── res/ │ │ └── DynamicAudioNormalizerCLI.rc │ └── src/ │ ├── 3rd_party/ │ │ └── memmem.h │ ├── AudioIO.cpp │ ├── AudioIO.h │ ├── AudioIO_Mpg123.cpp │ ├── AudioIO_Mpg123.h │ ├── AudioIO_OpusFile.cpp │ ├── AudioIO_OpusFile.h │ ├── AudioIO_SndFile.cpp │ ├── AudioIO_SndFile.h │ ├── Main.cpp │ ├── Parameters.cpp │ ├── Parameters.h │ ├── Platform.h │ ├── Platform_Linux.cpp │ ├── Platform_OSX.cpp │ └── Platform_Win32.cpp ├── DynamicAudioNormalizerGUI/ │ ├── DynamicAudioNormalizerGUI.qrc │ ├── DynamicAudioNormalizerGUI_VS2013.vcxproj │ ├── DynamicAudioNormalizerGUI_VS2013.vcxproj.filters │ ├── DynamicAudioNormalizerGUI_VS2015.vcxproj │ ├── DynamicAudioNormalizerGUI_VS2015.vcxproj.filters │ ├── DynamicAudioNormalizerGUI_VS2017.vcxproj │ ├── DynamicAudioNormalizerGUI_VS2017.vcxproj.filters │ ├── makefile │ ├── res/ │ │ └── DynamicAudioNormalizerGUI.rc │ └── src/ │ ├── 3rd_party/ │ │ ├── qcustomplot.cpp │ │ └── qcustomplot.h │ ├── Main.cpp │ └── WinMain.cpp ├── DynamicAudioNormalizerJNI/ │ ├── .classpath │ ├── .project │ ├── build.xml │ ├── generate_headers.bat │ ├── include/ │ │ ├── com_muldersoft_dynaudnorm_JDynamicAudioNormalizer.h │ │ ├── com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error.h │ │ ├── com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Logger.h │ │ └── com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8.h │ ├── makefile │ ├── samples/ │ │ └── com/ │ │ └── muldersoft/ │ │ └── dynaudnorm/ │ │ └── samples/ │ │ ├── AudioFileIO.java │ │ └── DynamicAudioNormalizerExample.java │ ├── src/ │ │ └── com/ │ │ └── muldersoft/ │ │ └── dynaudnorm/ │ │ └── JDynamicAudioNormalizer.java │ └── test/ │ └── com/ │ └── muldersoft/ │ └── dynaudnorm/ │ └── test/ │ └── JDynamicAudioNormalizerTest.java ├── DynamicAudioNormalizerNET/ │ ├── DynamicAudioNormalizerNET_VS2013.vcxproj │ ├── DynamicAudioNormalizerNET_VS2013.vcxproj.filters │ ├── DynamicAudioNormalizerNET_VS2015.vcxproj │ ├── DynamicAudioNormalizerNET_VS2015.vcxproj.filters │ ├── DynamicAudioNormalizerNET_VS2017.vcxproj │ ├── DynamicAudioNormalizerNET_VS2017.vcxproj.filters │ ├── res/ │ │ └── DynamicAudioNormalizerNET.rc │ ├── samples/ │ │ ├── DynamicAudioNormalizerExample.cs │ │ ├── DynamicAudioNormalizerExample.vb │ │ ├── DynamicAudioNormalizerExample_CS.csproj │ │ ├── DynamicAudioNormalizerExample_VB.vbproj │ │ ├── DynamicAudioNormalizerExamples.sln │ │ └── Properties/ │ │ ├── AssemblyInfo.cs │ │ └── AssemblyInfo.vb │ └── src/ │ ├── AssemblyInfo.cpp │ ├── DynamicAudioNormalizerNET.cpp │ ├── DynamicAudioNormalizerNET.h │ └── resource.h ├── DynamicAudioNormalizerPAS/ │ ├── DynamicAudioNormalizerPAS.cfg │ ├── DynamicAudioNormalizerPAS.dof │ ├── DynamicAudioNormalizerPAS.dpr │ ├── DynamicAudioNormalizerPAS.res │ ├── include/ │ │ └── DynamicAudioNormalizer.pas │ └── src/ │ ├── DynamicAudioNormalizerExample.dfm │ └── DynamicAudioNormalizerExample.pas ├── DynamicAudioNormalizerPYD/ │ ├── DynamicAudioNormalizerPYD_VS2013.vcxproj │ ├── DynamicAudioNormalizerPYD_VS2013.vcxproj.filters │ ├── DynamicAudioNormalizerPYD_VS2015.vcxproj │ ├── DynamicAudioNormalizerPYD_VS2015.vcxproj.filters │ ├── DynamicAudioNormalizerPYD_VS2017.vcxproj │ ├── DynamicAudioNormalizerPYD_VS2017.vcxproj.filters │ ├── include/ │ │ └── DynamicAudioNormalizer.py │ ├── makefile │ ├── res/ │ │ └── DynamicAudioNormalizerPYD.rc │ ├── samples/ │ │ ├── DynamicAudioNormalizerExample.py │ │ └── WaveFileUtils.py │ └── src/ │ └── DynamicAudioNormalizerPYD.cpp ├── DynamicAudioNormalizerShared/ │ ├── include/ │ │ ├── Common.h │ │ └── Threads.h │ └── res/ │ ├── compat.manifest │ └── version.inc ├── DynamicAudioNormalizerSoX/ │ ├── DynamicAudioNormalizerSoX.c │ ├── INFO.txt │ ├── extra/ │ │ ├── main.c │ │ ├── unicode_support.c │ │ └── unicode_support.h │ └── patch/ │ ├── SoX-v14.4.2-Patch1-UnicodeSupport+BuildFix.diff │ └── SoX-v14.4.2-Patch2-AddDynAudNormEffect.diff ├── DynamicAudioNormalizerVST/ │ ├── DynamicAudioNormalizerVST.def │ ├── DynamicAudioNormalizerVST_VS2013.vcxproj │ ├── DynamicAudioNormalizerVST_VS2013.vcxproj.filters │ ├── DynamicAudioNormalizerVST_VS2015.vcxproj │ ├── DynamicAudioNormalizerVST_VS2015.vcxproj.filters │ ├── DynamicAudioNormalizerVST_VS2017.vcxproj │ ├── DynamicAudioNormalizerVST_VS2017.vcxproj.filters │ ├── res/ │ │ └── DynamicAudioNormalizerVST.rc │ └── src/ │ ├── DynamicAudioNormalizerVST.cpp │ ├── DynamicAudioNormalizerVST.h │ ├── Spooky.cpp │ └── Spooky.h ├── DynamicAudioNormalizerWA5/ │ ├── DynamicAudioNormalizerWA5_VS2013.vcxproj │ ├── DynamicAudioNormalizerWA5_VS2013.vcxproj.filters │ ├── DynamicAudioNormalizerWA5_VS2015.vcxproj │ ├── DynamicAudioNormalizerWA5_VS2015.vcxproj.filters │ ├── DynamicAudioNormalizerWA5_VS2017.vcxproj │ ├── DynamicAudioNormalizerWA5_VS2017.vcxproj.filters │ ├── res/ │ │ └── DynamicAudioNormalizerWA5.rc │ └── src/ │ └── DynamicAudioNormalizerWA5.cpp ├── DynamicAudioNormalizer_VS2013.sln ├── DynamicAudioNormalizer_VS2015.sln ├── DynamicAudioNormalizer_VS2017.props ├── DynamicAudioNormalizer_VS2017.sln ├── LICENSE-GPL2.html ├── LICENSE-GPL3.html ├── LICENSE-LGPL.html ├── Makefile ├── README.md ├── etc/ │ ├── vst_sdk/ │ │ └── VST_SDK_INFO.txt │ └── winamp_sdk/ │ ├── LICENSE.txt │ └── include/ │ ├── winamp_dsp.h │ └── winamp_ipc.h ├── img/ │ └── dyauno/ │ └── Style.inc ├── z_build.bat └── z_test.bat ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ *.VC.db *.bin *.dcu *.ddp *.dll *.dylib *.exe *.local.* *.o *.old *.opendb *.opensdf *.sdf *.so *.suo *.user *.~* *__pycache__* *_old_* /.vs /DynamicAudioNormalizerGUI/tmp /DynamicAudioNormalizerJNI/.settings /DynamicAudioNormalizerJNI/bin /DynamicAudioNormalizerJNI/out /DynamicAudioNormalizerNET/samples/bin /DynamicAudioNormalizerNET/samples/obj /bin /doc /etc/vst_sdk/pluginterfaces /etc/vst_sdk/public.sdk /ipch /obj /out /tmp ================================================ FILE: DynamicAudioNormalizerAPI/DynamicAudioNormalizerAPI_VS2013.vcxproj ================================================  Debug Win32 Debug x64 Release_DLL Win32 Release_DLL x64 Release_Static Win32 Release_Static x64 {376386EE-8268-47E3-A335-7663716E4C60} Win32Proj DynamicAudioNormalizerAPI DynamicAudioNormalizerAPI DynamicLibrary true v120_xp Unicode DynamicLibrary true v120_xp Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode StaticLibrary false v120_xp true Unicode StaticLibrary false v120_xp true Unicode true $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ true $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ NotUsing Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Disabled false MultiThreadedDebugDLL Sync ProgramDatabase NoExtensions Windows true $(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) NotUsing Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Disabled false MultiThreadedDebugDLL Sync ProgramDatabase Windows true $(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) false StreamingSIMDExtensions2 MultiThreadedDLL AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) LinkVerboseLib %(AdditionalDependencies) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) false MultiThreadedDLL AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $$(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) LinkVerboseLib %(AdditionalDependencies) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) false StreamingSIMDExtensions2 MultiThreaded AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $(SolutionDir)\etc\vld\lib\$(Platform);%(AdditionalLibraryDirectories) true Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) false MultiThreaded AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $(SolutionDir)\etc\vld\lib\$(Platform);%(AdditionalLibraryDirectories) true ================================================ FILE: DynamicAudioNormalizerAPI/DynamicAudioNormalizerAPI_VS2013.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {eec3c662-ede0-4758-ba9f-e053d0324afa} {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Internal Header Files Internal Header Files Public Header Files Internal Header Files Internal Header Files ================================================ FILE: DynamicAudioNormalizerAPI/DynamicAudioNormalizerAPI_VS2015.vcxproj ================================================  Debug Win32 Debug x64 Release_DLL Win32 Release_DLL x64 Release_Static Win32 Release_Static x64 {376386EE-8268-47E3-A335-7663716E4C60} Win32Proj DynamicAudioNormalizerAPI DynamicAudioNormalizerAPI DynamicLibrary true v140_xp Unicode DynamicLibrary true v140_xp Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode StaticLibrary false v140_xp true Unicode StaticLibrary false v140_xp true Unicode true $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ true $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ NotUsing Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Disabled false MultiThreadedDebugDLL Sync ProgramDatabase NoExtensions Windows true $(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) NotUsing Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Disabled false MultiThreadedDebugDLL Sync ProgramDatabase Windows true $(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) false StreamingSIMDExtensions2 MultiThreadedDLL AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) LinkVerboseLib %(AdditionalDependencies) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) false MultiThreadedDLL AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $$(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) LinkVerboseLib %(AdditionalDependencies) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) false StreamingSIMDExtensions2 MultiThreaded AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $(SolutionDir)\etc\vld\lib\$(Platform);%(AdditionalLibraryDirectories) true Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) false MultiThreaded AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $(SolutionDir)\etc\vld\lib\$(Platform);%(AdditionalLibraryDirectories) true ================================================ FILE: DynamicAudioNormalizerAPI/DynamicAudioNormalizerAPI_VS2015.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {eec3c662-ede0-4758-ba9f-e053d0324afa} {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Internal Header Files Internal Header Files Public Header Files Internal Header Files Internal Header Files ================================================ FILE: DynamicAudioNormalizerAPI/DynamicAudioNormalizerAPI_VS2017.vcxproj ================================================  Debug Win32 Debug x64 Release_DLL Win32 Release_DLL x64 Release_Static Win32 Release_Static x64 true true {376386EE-8268-47E3-A335-7663716E4C60} Win32Proj DynamicAudioNormalizerAPI DynamicAudioNormalizerAPI 7.0 DynamicLibrary true v141_xp Unicode DynamicLibrary true v141_xp Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode StaticLibrary false v141_xp true Unicode StaticLibrary false v141_xp true Unicode true $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ true $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ NotUsing Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Disabled false MultiThreadedDebugDLL Sync ProgramDatabase NoExtensions Windows true $(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) NotUsing Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Disabled false MultiThreadedDebugDLL Sync ProgramDatabase Windows true $(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) false StreamingSIMDExtensions2 MultiThreadedDLL AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) LinkVerboseLib %(AdditionalDependencies) $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_EXPORTS;%(PreprocessorDefinitions) false MultiThreadedDLL AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $$(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) LinkVerboseLib %(AdditionalDependencies) $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) false StreamingSIMDExtensions2 MultiThreaded AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $(SolutionDir)\etc\vld\lib\$(Platform);%(AdditionalLibraryDirectories) true Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) false MultiThreaded AnySuitable Speed true $(ProjectDir)\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerJNI\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(JAVA_HOME)\include;$(JAVA_HOME)\include\win32;%(AdditionalIncludeDirectories) Fast true Windows false true true $(SolutionDir)\etc\vld\lib\$(Platform);%(AdditionalLibraryDirectories) true ================================================ FILE: DynamicAudioNormalizerAPI/DynamicAudioNormalizerAPI_VS2017.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {eec3c662-ede0-4758-ba9f-e053d0324afa} {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Internal Header Files Internal Header Files Public Header Files Internal Header Files Internal Header Files Resource Files ================================================ FILE: DynamicAudioNormalizerAPI/include/DynamicAudioNormalizer.h ================================================ /* ================================================================================== */ /* Dynamic Audio Normalizer - Audio Processing Library */ /* Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. */ /* */ /* This library is free software; you can redistribute it and/or */ /* modify it under the terms of the GNU Lesser General Public */ /* License as published by the Free Software Foundation; either */ /* version 2.1 of the License, or (at your option) any later version. */ /* */ /* This library 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 */ /* Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public */ /* License along with this library; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* */ /* http://www.gnu.org/licenses/lgpl-2.1.txt */ /* ================================================================================== */ #pragma once /*StdLib includes*/ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include /*DLL Export Definitions*/ #ifdef _MSC_VER # ifdef MDYNAMICAUDIONORMALIZER_EXPORTS # pragma message("MDynamicAudioNormalizer DLL: Export") # define MDYNAMICAUDIONORMALIZER_DLL __declspec(dllexport) # else # ifndef MDYNAMICAUDIONORMALIZER_STATIC # pragma message("MDynamicAudioNormalizer DLL: Import") # define MDYNAMICAUDIONORMALIZER_DLL __declspec(dllimport) # else # define MDYNAMICAUDIONORMALIZER_DLL # endif # endif #else # ifdef __GNUC__ # ifdef MDYNAMICAUDIONORMALIZER_EXPORTS # define MDYNAMICAUDIONORMALIZER_DLL __attribute__ ((visibility ("default"))) # else # define MDYNAMICAUDIONORMALIZER_DLL # endif # else # define MDYNAMICAUDIONORMALIZER_DLL # endif #endif /*Utility macros*/ #define MDYNAMICAUDIONORMALIZER_GLUE1(X,Y) X##Y #define MDYNAMICAUDIONORMALIZER_GLUE2(X,Y) MDYNAMICAUDIONORMALIZER_GLUE1(X,Y) /*Interface version*/ #define MDYNAMICAUDIONORMALIZER_CORE 8 #define MDYNAMICAUDIONORMALIZER_FUNCTION(X) MDYNAMICAUDIONORMALIZER_GLUE2(MDynamicAudioNormalizer_##X##_r, MDYNAMICAUDIONORMALIZER_CORE) #define MDynamicAudioNormalizer MDYNAMICAUDIONORMALIZER_GLUE2(MDynamicAudioNormalizer_r,MDYNAMICAUDIONORMALIZER_CORE) /*Callback for log messages*/ typedef void (MDYNAMICAUDIONORMALIZER_FUNCTION(LogFunction))(const int logLevel, const char *const message); /* ================================================================================== */ /* API for C++ application */ /* ================================================================================== */ #ifdef __cplusplus /*C++ compiler!*/ /*Standard Library include*/ #include /*Opaque Data Class*/ class MDynamicAudioNormalizer_PrivateData; /*Dynamic Normalizer Class*/ class MDYNAMICAUDIONORMALIZER_DLL MDynamicAudioNormalizer { public: /*Constructor & Destructor*/ MDynamicAudioNormalizer(const uint32_t channels, const uint32_t sampleRate, const uint32_t frameLenMsec = 500, const uint32_t filterSize = 31, const double peakValue = 0.95, const double maxAmplification = 10.0, const double targetRms = 0.0, const double compressFactor = 0.0, const bool channelsCoupled = true, const bool enableDCCorrection = false, const bool altBoundaryMode = false, FILE *const logFile = NULL); virtual ~MDynamicAudioNormalizer(void); /*Public API*/ bool initialize(void); bool process(const double *const *const samplesIn, double *const *const samplesOut, const int64_t inputSize, int64_t &outputSize); bool processInplace(double *const *const samplesInOut, const int64_t inputSize, int64_t &outputSize); bool flushBuffer(double *const *const samplesOut, const int64_t bufferSize, int64_t &outputSize); bool reset(void); bool getConfiguration(uint32_t &channels, uint32_t &sampleRate, uint32_t &frameLen, uint32_t &filterSize); bool getInternalDelay(int64_t &delayInSamples); /*Type definitions*/ typedef MDYNAMICAUDIONORMALIZER_FUNCTION(LogFunction) LogFunction; enum { LOG_LEVEL_DBG = 0, LOG_LEVEL_WRN = 1, LOG_LEVEL_ERR = 2 }; /*Static functions*/ static void getVersionInfo(uint32_t &major, uint32_t &minor, uint32_t &patch); static void getBuildInfo(const char **const date, const char **const time, const char **const compiler, const char **const arch, bool &debug); static LogFunction *setLogFunction(LogFunction *const logFunction); private: MDynamicAudioNormalizer(const MDynamicAudioNormalizer&) : p(NULL) { throw "unsupported"; } MDynamicAudioNormalizer &operator=(const MDynamicAudioNormalizer&) { throw "unsupported"; } MDynamicAudioNormalizer_PrivateData *const p; }; #endif /*__cplusplus*/ /* ================================================================================== */ /* API for C applications */ /* ================================================================================== */ #ifdef __cplusplus extern "C" { #endif /*__cplusplus*/ /*Standard Library include*/ #include /*Opaque handle*/ typedef struct MDynamicAudioNormalizer_Handle MDynamicAudioNormalizer_Handle; /*Global Functions*/ MDYNAMICAUDIONORMALIZER_DLL MDynamicAudioNormalizer_Handle* MDYNAMICAUDIONORMALIZER_FUNCTION(createInstance)(const uint32_t channels, const uint32_t sampleRate, const uint32_t frameLenMsec, const uint32_t filterSize, const double peakValue, const double maxAmplification, const double targetRms, const double compressFactor, const int channelsCoupled, const int enableDCCorrection, const int altBoundaryMode, FILE *const logFile); MDYNAMICAUDIONORMALIZER_DLL void MDYNAMICAUDIONORMALIZER_FUNCTION(destroyInstance)(MDynamicAudioNormalizer_Handle **const handle); MDYNAMICAUDIONORMALIZER_DLL int MDYNAMICAUDIONORMALIZER_FUNCTION(process)(MDynamicAudioNormalizer_Handle *const handle, const double *const *const samplesIn, double *const *const samplesOut, const int64_t inputSize, int64_t *const outputSize); MDYNAMICAUDIONORMALIZER_DLL int MDYNAMICAUDIONORMALIZER_FUNCTION(processInplace)(MDynamicAudioNormalizer_Handle *const handle, double *const *const samplesInOut, const int64_t inputSize, int64_t *const outputSize); MDYNAMICAUDIONORMALIZER_DLL int MDYNAMICAUDIONORMALIZER_FUNCTION(flushBuffer)(MDynamicAudioNormalizer_Handle *const handle, double *const *const samplesOut, const int64_t bufferSize, int64_t *const outputSize); MDYNAMICAUDIONORMALIZER_DLL int MDYNAMICAUDIONORMALIZER_FUNCTION(reset)(MDynamicAudioNormalizer_Handle *const handle); MDYNAMICAUDIONORMALIZER_DLL int MDYNAMICAUDIONORMALIZER_FUNCTION(getConfiguration)(MDynamicAudioNormalizer_Handle *const handle, uint32_t *const channels, uint32_t *const sampleRate, uint32_t *const frameLen, uint32_t *const filterSize); MDYNAMICAUDIONORMALIZER_DLL int MDYNAMICAUDIONORMALIZER_FUNCTION(getInternalDelay)(MDynamicAudioNormalizer_Handle *const handle, int64_t *const delayInSamples); MDYNAMICAUDIONORMALIZER_DLL void MDYNAMICAUDIONORMALIZER_FUNCTION(getVersionInfo)(uint32_t *const major, uint32_t *const minor, uint32_t *const patch); MDYNAMICAUDIONORMALIZER_DLL void MDYNAMICAUDIONORMALIZER_FUNCTION(getBuildInfo)(const char **const date, const char **const time, const char **const compiler, const char **const arch, int *const debug); MDYNAMICAUDIONORMALIZER_DLL MDYNAMICAUDIONORMALIZER_FUNCTION(LogFunction) *MDYNAMICAUDIONORMALIZER_FUNCTION(setLogFunction)(MDYNAMICAUDIONORMALIZER_FUNCTION(LogFunction) *const logFunction); #ifdef __cplusplus } #endif /*__cplusplus*/ ================================================ FILE: DynamicAudioNormalizerAPI/makefile ================================================ ############################################################################## # Dynamic Audio Normalizer - Audio Processing Library # Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # http://www.gnu.org/licenses/lgpl-2.1.txt ############################################################################## ECHO=echo -e SHELL=/bin/bash JAVA_HOME ?= $(shell update-java-alternatives -l 2>/dev/null | grep -oE '[^[:space:]]+$$' || echo "/usr/lib/jvm/default") ############################################################################## # Constants ############################################################################## LIBRARY_NAME := libDynamicAudioNormalizerAPI ifndef API_VERSION $(error API_VERSION variable is not set!) endif ############################################################################## # JDK Checks ############################################################################## ifneq ($(MAKECMDGOALS),clean) ifneq ($(ENABLE_JNI),false) JDK_CHECK := $(shell [ -f $(JAVA_HOME)/include/jni.h ] && echo true || echo false) ifneq ($(JDK_CHECK),true) $(error File "include/jni.h" not found in JAVA_HOME path!) endif endif endif ############################################################################## # Flags ############################################################################## DEBUG_BUILD ?= 0 MARCH ?= native ifeq ($(DEBUG_BUILD), 1) CONFIG_NAME = Debug CXXFLAGS = -g -O0 -D_DEBUG else CONFIG_NAME = Release CXXFLAGS = -O3 -Wall -ffast-math -mfpmath=sse -msse -fomit-frame-pointer -fno-tree-vectorize -DNDEBUG -march=$(MARCH) endif ifneq ($(findstring MINGW,$(shell uname -s)),MINGW) CXXFLAGS += -fPIC endif CXXFLAGS += -std=gnu++11 CXXFLAGS += -fvisibility=hidden CXXFLAGS += -DMDYNAMICAUDIONORMALIZER_EXPORTS CXXFLAGS += -I./src CXXFLAGS += -I./include CXXFLAGS += -I../DynamicAudioNormalizerShared/include CXXFLAGS += -I../DynamicAudioNormalizerJNI/include ifneq ($(ENABLE_JNI),false) CXXFLAGS += -I$(JAVA_HOME)/include ifeq ($(findstring MINGW,$(shell uname -s)),MINGW) CXXFLAGS += -I$(JAVA_HOME)/include/win32 else ifeq ($(shell uname), Darwin) CXXFLAGS += -I$(JAVA_HOME)/include/darwin else CXXFLAGS += -I$(JAVA_HOME)/include/linux endif else CXXFLAGS += -DNO_JAVA_SUPPORT endif ############################################################################## # File Names ############################################################################## ifeq ($(findstring MINGW,$(shell uname -s)),MINGW) SO_EXT = dll LDXFLAGS += -Wl,--out-implib,$@.a SHAREDFLAG = -shared else ifeq ($(shell uname), Darwin) SO_EXT = dylib SHAREDFLAG = -dynamiclib else SO_EXT = so SHAREDFLAG = -shared endif SOURCES_CPP = $(wildcard src/*.cpp) SOURCES_OBJ = $(patsubst %.cpp,%.o,$(SOURCES_CPP)) LIBRARY_OUT = lib/$(LIBRARY_NAME)-$(API_VERSION) LIBRARY_BIN = $(LIBRARY_OUT).$(SO_EXT) LIBRARY_DBG = $(LIBRARY_OUT)-DBG.$(SO_EXT) ############################################################################## # Rules ############################################################################## .PHONY: all clean all: $(LIBRARY_DBG) $(LIBRARY_BIN) #------------------------------------------------------------- # Link & Strip #------------------------------------------------------------- $(LIBRARY_BIN): $(SOURCES_OBJ) @$(ECHO) "\e[1;36m[STR] $@\e[0m" @mkdir -p $(dir $@) g++ $(SHAREDFLAG) -g0 -o $@ $+ $(LDXFLAGS) ifeq ($(shell uname), Darwin) install_name_tool -id "@loader_path/$(notdir $@)" $@ strip -u -r -x $@ else strip --strip-unneeded $@ endif $(LIBRARY_DBG): $(SOURCES_OBJ) @$(ECHO) "\e[1;36m[LNK] $@\e[0m" @mkdir -p $(dir $@) g++ $(SHAREDFLAG) -o $@ $+ $(LDXFLAGS) ifeq ($(shell uname), Darwin) install_name_tool -id "@loader_path/$(notdir $@)" $@ endif #------------------------------------------------------------- # Compile #------------------------------------------------------------- %.o: %.cpp @$(ECHO) "\e[1;36m[CXX] $<\e[0m" @mkdir -p $(dir $@) g++ $(CXXFLAGS) -c $< -o $@ #------------------------------------------------------------- # Clean #------------------------------------------------------------- clean: rm -fv $(SOURCES_OBJ) rm -rfv ./lib ================================================ FILE: DynamicAudioNormalizerAPI/res/DynamicAudioNormalizerAPI.rc ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "WinResrc.h" //"afxres.h" #define INC_DYNAUDNORM_VERSION_INTERNAL 0x22b4f8a9 #include "../DynamicAudioNormalizerShared/res/version.inc" ////////////////////////////////////////////////////////////////////////////////// // Neutral resources ////////////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) #ifdef _WIN32 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL #pragma code_page(1252) #endif //_WIN32 ////////////////////////////////////////////////////////////////////////////////// // Version ////////////////////////////////////////////////////////////////////////////////// VS_VERSION_INFO VERSIONINFO FILEVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH PRODUCTVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x3L #else FILEFLAGS 0x2L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ." VALUE "CompanyName", "LoRd_MuldeR " VALUE "FileDescription", "DynamicAudioNormalizer Core Library" VALUE "FileVersion", VER_DYNAUDNORM_STR VALUE "InternalName", "DynamicAudioNormalizerAPI" VALUE "LegalCopyright", "Copyright (c) 2014-2019 LoRd_MuldeR " VALUE "LegalTrademarks", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License " VALUE "OriginalFilename", "DynamicAudioNormalizerAPI.dll" VALUE "ProductName", "DynamicAudioNormalizer" VALUE "ProductVersion", VER_DYNAUDNORM_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // Neutral resources ================================================ FILE: DynamicAudioNormalizerAPI/src/Binding_C.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "DynamicAudioNormalizer.h" #define INT2BOOL(X) ((X) != 0) extern "C" { MDynamicAudioNormalizer_Handle* MDYNAMICAUDIONORMALIZER_FUNCTION(createInstance)(const uint32_t channels, const uint32_t sampleRate, const uint32_t frameLenMsec, const uint32_t filterSize, const double peakValue, const double maxAmplification, const double targetRms, const double compressFactor, const int channelsCoupled, const int enableDCCorrection, const int altBoundaryMode, FILE *const logFile) { try { MDynamicAudioNormalizer *const instance = new MDynamicAudioNormalizer(channels, sampleRate, frameLenMsec, filterSize, peakValue, maxAmplification, targetRms, compressFactor, INT2BOOL(channelsCoupled), INT2BOOL(enableDCCorrection), INT2BOOL(altBoundaryMode), logFile); if(instance->initialize()) { return reinterpret_cast(instance); } else { delete instance; return NULL; } } catch(...) { return NULL; } } MDYNAMICAUDIONORMALIZER_DLL void MDYNAMICAUDIONORMALIZER_FUNCTION(destroyInstance)(MDynamicAudioNormalizer_Handle **const handle) { if(MDynamicAudioNormalizer **const instance = reinterpret_cast(handle)) { try { delete (*instance); (*instance) = NULL; } catch(...) { /*ignore exception*/ } } } int MDYNAMICAUDIONORMALIZER_FUNCTION(process)(MDynamicAudioNormalizer_Handle *const handle, const double *const *const samplesIn, double *const *const samplesOut, const int64_t inputSize, int64_t *const outputSize) { if (MDynamicAudioNormalizer *const instance = reinterpret_cast(handle)) { try { return instance->process(samplesIn, samplesOut, inputSize, (*outputSize)) ? 1 : 0; } catch (...) { return 0; } } return 0; } int MDYNAMICAUDIONORMALIZER_FUNCTION(processInplace)(MDynamicAudioNormalizer_Handle *const handle, double *const *const samplesInOut, const int64_t inputSize, int64_t *const outputSize) { if(MDynamicAudioNormalizer *const instance = reinterpret_cast(handle)) { try { return instance->processInplace(samplesInOut, inputSize, (*outputSize)) ? 1 : 0; } catch(...) { return 0; } } return 0; } int MDYNAMICAUDIONORMALIZER_FUNCTION(flushBuffer)(MDynamicAudioNormalizer_Handle *const handle, double *const *const samplesOut, const int64_t bufferSize, int64_t *const outputSize) { if(MDynamicAudioNormalizer *const instance = reinterpret_cast(handle)) { try { return instance->flushBuffer(samplesOut, bufferSize, (*outputSize)) ? 1 : 0; } catch(...) { return 0; } } return 0; } int MDYNAMICAUDIONORMALIZER_FUNCTION(reset)(MDynamicAudioNormalizer_Handle *const handle) { if(MDynamicAudioNormalizer *instance = reinterpret_cast(handle)) { try { return instance->reset() ? 1 : 0; } catch(...) { return 0; } } return 0; } int MDYNAMICAUDIONORMALIZER_FUNCTION(getConfiguration)(MDynamicAudioNormalizer_Handle *const handle, uint32_t *const channels, uint32_t *const sampleRate, uint32_t *const frameLen, uint32_t *const filterSize) { if(MDynamicAudioNormalizer *const instance = reinterpret_cast(handle)) { try { return instance->getConfiguration((*channels), (*sampleRate), (*frameLen), (*filterSize)) ? 1 : 0; } catch(...) { return 0; } } return 0; } int MDYNAMICAUDIONORMALIZER_FUNCTION(getInternalDelay)(MDynamicAudioNormalizer_Handle *const handle, int64_t *const delayInSamples) { if(MDynamicAudioNormalizer *const instance = reinterpret_cast(handle)) { try { return instance->getInternalDelay(*delayInSamples) ? 1 : 0; } catch(...) { return 0; } } return 0; } MDYNAMICAUDIONORMALIZER_FUNCTION(LogFunction) *MDYNAMICAUDIONORMALIZER_FUNCTION(setLogFunction)(MDYNAMICAUDIONORMALIZER_FUNCTION(LogFunction) *const logFunction) { return MDynamicAudioNormalizer::setLogFunction(logFunction); } void MDYNAMICAUDIONORMALIZER_FUNCTION(getVersionInfo)(uint32_t *const major, uint32_t *const minor, uint32_t *const patch) { MDynamicAudioNormalizer::getVersionInfo((*major), (*minor), (*patch)); } void MDYNAMICAUDIONORMALIZER_FUNCTION(getBuildInfo)(const char **const date, const char **const time, const char **const compiler, const char **const arch, int *const debug) { bool isDebug; MDynamicAudioNormalizer::getBuildInfo(date, time, compiler, arch, isDebug); *debug = isDebug ? 1 : 0; } } ================================================ FILE: DynamicAudioNormalizerAPI/src/Binding_JNI.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "DynamicAudioNormalizer.h" //Java support? #ifndef NO_JAVA_SUPPORT //StdLib #include #include #include #include #ifdef __APPLE__ #include #else #include #endif //__APPLE__ //C++11 support #if (__cplusplus >= 201100L) || (defined(_MSC_VER) && (_MSC_VER > 1600)) #include #define MAP_TYPE std::unordered_map #else #pragma message "C++11 support *not* enabled" #include #define MAP_TYPE std::map #endif //Generate the JNI header file name #define JAVA_HDRNAME_GLUE1(X,Y) #define JAVA_HDRNAME_GLUE2(X,Y) JAVA_HDRNAME_GLUE1(X,Y) #define JAVA_HDRNAME(X) JAVA_HDRNAME_GLUE2(X, MDYNAMICAUDIONORMALIZER_CORE) //Generate JNI export names and corresponding helper functions #define JAVA_FUNCTION_GLUE1(X,Y,Z) X##Y##_##Z #define JAVA_FUNCTION_GLUE2(X,Y,Z) JAVA_FUNCTION_GLUE1(X,Y,Z) #define JAVA_FUNCTION(X) JAVA_FUNCTION_GLUE2(Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r, MDYNAMICAUDIONORMALIZER_CORE, X) #define JAVA_FUNCIMPL(X) JAVA_FUNCTION_GLUE2(Impl_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r, MDYNAMICAUDIONORMALIZER_CORE, X) //JNI Headers #include JAVA_HDRNAME(com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI) //Internal #include #include //Globals static MY_CRITSEC_INIT(g_javaLock); /////////////////////////////////////////////////////////////////////////////// // Utility Functions /////////////////////////////////////////////////////////////////////////////// #define JAVA_FIND_CLASS(VAR,NAME,RET) do \ { \ (VAR) = env->FindClass((NAME)); \ if((VAR) == NULL) \ { \ return (RET); \ } \ } \ while(0) #define JAVA_GET_METHOD(VAR,CLASS,NAME,ARGS,RET) do \ { \ (VAR) = env->GetMethodID((CLASS), (NAME), (ARGS)); \ if((VAR) == NULL) \ { \ return (RET); \ } \ } \ while(0) #define JAVA_GET_METHOD_STATIC(VAR,CLASS,NAME,ARGS,RET) do \ { \ (VAR) = env->GetStaticMethodID((CLASS), (NAME), (ARGS)); \ if((VAR) == NULL) \ { \ return (RET); \ } \ } \ while(0) #define JAVA_MAP_PUT_STRING(MAP,KEY,VAL) do \ { \ jstring _key = env->NewStringUTF((KEY)); \ jstring _val = env->NewStringUTF((VAL)); \ \ if(_key && _val) \ { \ jobject _ret = env->CallObjectMethod((MAP), putMethod, _key, _val); \ if(_ret) env->DeleteLocalRef(_ret); \ } \ \ if(_key) env->DeleteLocalRef(_key); \ if(_val) env->DeleteLocalRef(_val); \ } \ while(0) #define JAVA_MAP_PUT_INTEGER(MAP,KEY,VAL) do \ { \ jstring _key = env->NewStringUTF((KEY)); \ jobject _val = javaNewInteger(env, (VAL)); \ \ if(_key && _val) \ { \ jobject _ret = env->CallObjectMethod((MAP), putMethod, _key, _val); \ if(_ret) env->DeleteLocalRef(_ret); \ } \ \ if(_key) env->DeleteLocalRef(_key); \ if(_val) env->DeleteLocalRef(_val); \ } \ while(0) #define JAVA_THROW_EXCEPTION(TEXT, RET) do \ { \ if(jclass runtimeError = env->FindClass("java/lang/Error")) \ { \ env->ThrowNew(runtimeError, (TEXT)); \ env->DeleteLocalRef(runtimeError); \ } \ else \ { \ abort(); \ } \ return (RET); \ } \ while(0) #define JAVA_TRY_CATCH(FUNC_NAME, RET, ...) \ try \ { \ return JAVA_FUNCIMPL(FUNC_NAME)(__VA_ARGS__); \ } \ catch(std::exception e) \ { \ JAVA_THROW_EXCEPTION(e.what(), (RET)); \ } \ catch(...) \ { \ JAVA_THROW_EXCEPTION("An unknown C++ exception has occurred!", (RET)); \ } /////////////////////////////////////////////////////////////////////////////// // Create Boxed Type /////////////////////////////////////////////////////////////////////////////// static jobject javaNewInteger(JNIEnv *env, const jint &value) { jclass integerClass; jmethodID valueOfMethod; JAVA_FIND_CLASS(integerClass, "java/lang/Integer", NULL); JAVA_GET_METHOD_STATIC(valueOfMethod, integerClass, "valueOf", "(I)Ljava/lang/Integer;", NULL); jobject const integerObj = env->CallStaticObjectMethod(integerClass, valueOfMethod, value); env->DeleteLocalRef(integerClass); return integerObj; } /////////////////////////////////////////////////////////////////////////////// // Logging Function /////////////////////////////////////////////////////////////////////////////// static JavaVM *g_javaLoggingJVM = NULL; static jobject g_javaLoggingHandler = NULL; static jboolean javaLogMessage_Helper(JNIEnv *env, const int &level, const char *const message) { jclass loggerClass = NULL; jmethodID logMethod = NULL; JAVA_FIND_CLASS(loggerClass, "com/muldersoft/dynaudnorm/JDynamicAudioNormalizer$Logger", JNI_FALSE); JAVA_GET_METHOD(logMethod, loggerClass, "log", "(ILjava/lang/String;)V", JNI_FALSE); jstring text = env->NewStringUTF(message); if(text) { env->CallVoidMethod(g_javaLoggingHandler, logMethod, level, text); env->DeleteLocalRef(text); } env->DeleteLocalRef(loggerClass); return JNI_TRUE; } static void javaLogMessage(const int logLevel, const char *const message) { MY_CRITSEC_ENTER(g_javaLock); if(g_javaLoggingHandler && g_javaLoggingJVM) { JNIEnv *env = NULL; if(g_javaLoggingJVM->GetEnv((void**)&env, JNI_VERSION_1_6) == JNI_OK) { javaLogMessage_Helper(env, logLevel, message); } } MY_CRITSEC_LEAVE(g_javaLock); } static void javaSetLoggingHandler(JNIEnv *env, jobject loggerGlobalReference) { MY_CRITSEC_ENTER(g_javaLock); if(g_javaLoggingHandler) { env->DeleteGlobalRef(g_javaLoggingHandler); g_javaLoggingHandler = NULL; } if(loggerGlobalReference) { if(env->GetJavaVM(&g_javaLoggingJVM) == 0) { g_javaLoggingHandler = loggerGlobalReference; MDynamicAudioNormalizer::setLogFunction(javaLogMessage); } } MY_CRITSEC_LEAVE(g_javaLock); } /////////////////////////////////////////////////////////////////////////////// // Instance Handling /////////////////////////////////////////////////////////////////////////////// #define MY_RANDOMIZE(X) ((X) = ((((X) * 1103515245) + 12345) & INT32_MAX)) static jint g_nextHandleValue = 0x49A887DC; static MAP_TYPE g_instances; static jint javaCreateHandle(MDynamicAudioNormalizer *const instance) { MY_CRITSEC_ENTER(g_javaLock); jint handleValue = MY_RANDOMIZE(g_nextHandleValue); uint32_t retryCounter = 0; while((handleValue <= 0) || (g_instances.find(handleValue) != g_instances.end())) { if(++retryCounter >= INT32_MAX) { handleValue = -1; break; } handleValue = MY_RANDOMIZE(g_nextHandleValue); } if(handleValue >= 0) { g_instances.insert(std::pair(handleValue, instance)); } MY_CRITSEC_LEAVE(g_javaLock); return handleValue; } static MDynamicAudioNormalizer *javaHandleToInstance(const jint &handleValue, const bool remove = false) { MY_CRITSEC_ENTER(g_javaLock); MDynamicAudioNormalizer *instance = NULL; if(g_instances.find(handleValue) != g_instances.end()) { instance = g_instances[handleValue]; if(remove) { g_instances.erase(handleValue); } } MY_CRITSEC_LEAVE(g_javaLock); return instance; } /////////////////////////////////////////////////////////////////////////////// // 2D Array Support /////////////////////////////////////////////////////////////////////////////// static jboolean javaRelease2DArrayElements(JNIEnv *const env, jobjectArray const outerArray, const jsize &countOuter, double **const arrayElements) { jclass doubleArrayClass; JAVA_FIND_CLASS(doubleArrayClass, "[D", JNI_FALSE); jboolean success = JNI_TRUE; for(jsize c = 0; c < countOuter; c++) { if(arrayElements[c]) { jobject innerArray = env->GetObjectArrayElement(outerArray, jsize(c)); if(innerArray) { if(env->IsInstanceOf(innerArray, doubleArrayClass)) { env->ReleaseDoubleArrayElements(static_cast(innerArray), arrayElements[c], 0); } else { success = JNI_FALSE; /*element is not a double array*/ } env->DeleteLocalRef(innerArray); } arrayElements[c] = NULL; } } env->DeleteLocalRef(doubleArrayClass); return success; } static jboolean javaGet2DArrayElements(JNIEnv *const env, const jobjectArray outerArray, const jsize &countOuter, double **arrayElementsOut, jsize &countInnerOut) { jclass doubleArrayClass; JAVA_FIND_CLASS(doubleArrayClass, "[D", JNI_FALSE); countInnerOut = INT32_MAX; jboolean success = JNI_TRUE; for(jsize c = 0; c < countOuter; c++) { arrayElementsOut[c] = NULL; jobject innerArray = env->GetObjectArrayElement(outerArray, jsize(c)); if(innerArray) { if(env->IsInstanceOf(innerArray, doubleArrayClass)) { countInnerOut = std::min(countInnerOut, env->GetArrayLength(static_cast(innerArray))); if(!(arrayElementsOut[c] = env->GetDoubleArrayElements(static_cast(innerArray), NULL))) { success = JNI_FALSE; /*failed to get the array elements*/ } } else { success = JNI_FALSE; /*element is not a double array*/ } env->DeleteLocalRef(innerArray); } } if(!success) { javaRelease2DArrayElements(env, outerArray, countOuter, arrayElementsOut); } env->DeleteLocalRef(doubleArrayClass); return success; } /////////////////////////////////////////////////////////////////////////////// // JNI Functions /////////////////////////////////////////////////////////////////////////////// static jboolean JAVA_FUNCIMPL(getVersionInfo)(JNIEnv *const env, jintArray versionInfo) { if(versionInfo == NULL) { return JNI_FALSE; } if(env->GetArrayLength(versionInfo) == 3) { if(jint *const versionInfoElements = env->GetIntArrayElements(versionInfo, NULL)) { uint32_t major, minor, patch; MDynamicAudioNormalizer::getVersionInfo(major, minor, patch); versionInfoElements[0] = (int32_t) std::min(major, uint32_t(INT32_MAX)); versionInfoElements[1] = (int32_t) std::min(minor, uint32_t(INT32_MAX)); versionInfoElements[2] = (int32_t) std::min(patch, uint32_t(INT32_MAX)); env->ReleaseIntArrayElements(versionInfo, versionInfoElements, 0); return JNI_TRUE; } } return JNI_FALSE; } static jboolean JAVA_FUNCIMPL(getBuildInfo)(JNIEnv *const env, jobject const buildInfo) { if(buildInfo == NULL) { return JNI_FALSE; } jclass mapClass = NULL; jmethodID putMethod = NULL, clearMethod = NULL; JAVA_FIND_CLASS(mapClass, "java/util/Map", JNI_FALSE); JAVA_GET_METHOD(putMethod, mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", JNI_FALSE); JAVA_GET_METHOD(clearMethod, mapClass, "clear", "()V", JNI_FALSE); if(!env->IsInstanceOf(buildInfo, mapClass)) { return JNI_FALSE; } env->CallVoidMethod(buildInfo, clearMethod); const char *date, *time, *compiler, *arch; bool debug; MDynamicAudioNormalizer::getBuildInfo(&date, &time, &compiler, &arch, debug); JAVA_MAP_PUT_STRING(buildInfo, "BuildDate", date); JAVA_MAP_PUT_STRING(buildInfo, "BuildTime", time); JAVA_MAP_PUT_STRING(buildInfo, "Compiler", compiler); JAVA_MAP_PUT_STRING(buildInfo, "Architecture", arch); JAVA_MAP_PUT_STRING(buildInfo, "DebugBuild", debug ? "Yes" : "No"); env->DeleteLocalRef(mapClass); return JNI_TRUE; } static jboolean JAVA_FUNCIMPL(setLoggingHandler)(JNIEnv *const env, jobject const loggerObject) { if(loggerObject == NULL) { javaSetLoggingHandler(env, NULL); return JNI_TRUE; } jclass loggerClass = NULL; JAVA_FIND_CLASS(loggerClass, "com/muldersoft/dynaudnorm/JDynamicAudioNormalizer$Logger", JNI_FALSE); if(!env->IsInstanceOf(loggerObject, loggerClass)) { return JNI_FALSE; } jobject globalReference = env->NewGlobalRef(loggerObject); if(globalReference) { javaSetLoggingHandler(env, globalReference); return JNI_TRUE; } env->DeleteLocalRef(loggerClass); return JNI_FALSE; } static jint JAVA_FUNCIMPL(createInstance)(JNIEnv *const env, const jint &channels, const jint &sampleRate, const jint &frameLenMsec, const jint &filterSize, const jdouble &peakValue, const jdouble &maxAmplification, const jdouble &targetRms, const jdouble &compressFactor, const jboolean &channelsCoupled, const jboolean &enableDCCorrection, const jboolean &altBoundaryMode) { if((channels > 0) && (sampleRate > 0) && (frameLenMsec > 0) & (filterSize > 0)) { MDynamicAudioNormalizer *instance = new MDynamicAudioNormalizer(channels, sampleRate, frameLenMsec, filterSize, peakValue, maxAmplification, targetRms, compressFactor, (channelsCoupled != JNI_FALSE), (enableDCCorrection != JNI_FALSE), (altBoundaryMode != JNI_FALSE)); if(!instance->initialize()) { delete instance; return -1; } const jint handle = javaCreateHandle(instance); if(handle < 0) { delete instance; return -1; } return handle; } return -1; } static jboolean JAVA_FUNCIMPL(destroyInstance)(JNIEnv *const env, const jint &handle) { if(MDynamicAudioNormalizer *const instance = javaHandleToInstance(handle, true)) { delete instance; return JNI_TRUE; } return JNI_FALSE; } static jlong JAVA_FUNCIMPL(process)(JNIEnv *const env, const jint &handle, jobjectArray const samplesIn, jobjectArray const samplesOut, const jlong &inputSize) { if ((handle < 0) || (samplesIn == NULL) || (samplesOut == NULL) || (inputSize < 1)) { return -1; /*invalid parameters detected*/ } MDynamicAudioNormalizer *const instance = javaHandleToInstance(handle); if (instance == NULL) { return -1; /*invalid handle value*/ } uint32_t channels, sampleRate, frameLen, filterSize; if (!instance->getConfiguration(channels, sampleRate, frameLen, filterSize)) { return -1; /*unable to get configuration*/ } if ((env->GetArrayLength(samplesIn) < jint(channels)) || (env->GetArrayLength(samplesOut) < jint(channels))) { return -1; /*array diemnsion is too small*/ } double **arrayElementsIn = (double**)alloca(sizeof(double*) * channels); jsize arrayLengthIn = 0; if (!javaGet2DArrayElements(env, samplesIn, channels, arrayElementsIn, arrayLengthIn)) { return -1; /*failed to retrieve the array elements*/ } double **arrayElementsOut = (double**)alloca(sizeof(double*) * channels); jsize arrayLengthOut = 0; if (!javaGet2DArrayElements(env, samplesOut, channels, arrayElementsOut, arrayLengthOut)) { return -1; /*failed to retrieve the array elements*/ } int64_t outputSize = 0; const bool success = instance->process(arrayElementsIn, arrayElementsOut, std::min(inputSize, std::min(jlong(arrayLengthIn), jlong(arrayLengthOut))), outputSize); if (!javaRelease2DArrayElements(env, samplesIn, channels, arrayElementsIn)) { return -1; /*failed to release the array elements*/ } if (!javaRelease2DArrayElements(env, samplesOut, channels, arrayElementsOut)) { return -1; /*failed to release the array elements*/ } return success ? outputSize : (-1); } static jlong JAVA_FUNCIMPL(processInplace)(JNIEnv *const env, const jint &handle, jobjectArray const samplesInOut, const jlong &inputSize) { if((handle < 0) || (samplesInOut == NULL) || (inputSize < 1)) { return -1; /*invalid parameters detected*/ } MDynamicAudioNormalizer *const instance = javaHandleToInstance(handle); if(instance == NULL) { return -1; /*invalid handle value*/ } uint32_t channels, sampleRate, frameLen, filterSize; if(!instance->getConfiguration(channels, sampleRate, frameLen, filterSize)) { return -1; /*unable to get configuration*/ } if(env->GetArrayLength(samplesInOut) < jint(channels)) { return -1; /*array diemnsion is too small*/ } double **arrayElements = (double**) alloca(sizeof(double*) * channels); jsize arrayLength = 0; if(!javaGet2DArrayElements(env, samplesInOut, channels, arrayElements, arrayLength)) { return -1; /*failed to retrieve the array elements*/ } int64_t outputSize = 0; const bool success = instance->processInplace(arrayElements, std::min(inputSize, jlong(arrayLength)), outputSize); if(!javaRelease2DArrayElements(env, samplesInOut, channels, arrayElements)) { return -1; /*failed to release the array elements*/ } return success ? outputSize : (-1); } static jlong JAVA_FUNCIMPL(flushBuffer)(JNIEnv *const env, const jint &handle, jobjectArray const samplesOut) { if((handle < 0) || (samplesOut == NULL)) { return -1; /*invalid parameters detected*/ } MDynamicAudioNormalizer *const instance = javaHandleToInstance(handle); if(instance == NULL) { return -1; /*invalid handle value*/ } uint32_t channels, sampleRate, frameLen, filterSize; if(!instance->getConfiguration(channels, sampleRate, frameLen, filterSize)) { return -1; /*unable to get configuration*/ } if(env->GetArrayLength(samplesOut) < jint(channels)) { return -1; /*array diemnsion is too small*/ } double **arrayElements = (double**) alloca(sizeof(double*) * channels); jsize arrayLength = 0; if(!javaGet2DArrayElements(env, samplesOut, channels, arrayElements, arrayLength)) { return -1; /*failed to retrieve the array elements*/ } int64_t outputSize = 0; const bool success = instance->flushBuffer(arrayElements, arrayLength, outputSize); if(!javaRelease2DArrayElements(env, samplesOut, channels, arrayElements)) { return -1; /*failed to release the array elements*/ } return success ? outputSize : (-1); } static jboolean JAVA_FUNCIMPL(reset)(JNIEnv *const env, const jint &handle) { if(handle < 0) { return JNI_FALSE; } MDynamicAudioNormalizer *const instance = javaHandleToInstance(handle); if(instance == NULL) { return JNI_FALSE; /*invalid handle value*/ } return instance->reset() ? JNI_TRUE : JNI_FALSE; } static jboolean JAVA_FUNCIMPL(getConfiguration)(JNIEnv *const env, const jint &handle, jobject const configuration) { if((handle < 0) || (configuration == NULL)) { return JNI_FALSE; } MDynamicAudioNormalizer *const instance = javaHandleToInstance(handle); if(instance == NULL) { return JNI_FALSE; /*invalid handle value*/ } jclass mapClass = NULL; jmethodID putMethod = NULL, clearMethod = NULL; JAVA_FIND_CLASS(mapClass, "java/util/Map", JNI_FALSE); JAVA_GET_METHOD(putMethod, mapClass, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;", JNI_FALSE); JAVA_GET_METHOD(clearMethod, mapClass, "clear", "()V", JNI_FALSE); if(!env->IsInstanceOf(configuration, mapClass)) { return JNI_FALSE; } env->CallVoidMethod(configuration, clearMethod); uint32_t channels, sampleRate, frameLen, filterSize; if(!instance->getConfiguration(channels, sampleRate, frameLen, filterSize)) { return JNI_FALSE; } JAVA_MAP_PUT_INTEGER(configuration, "channelCount", static_cast(channels)); JAVA_MAP_PUT_INTEGER(configuration, "sampleRate", static_cast(sampleRate)); JAVA_MAP_PUT_INTEGER(configuration, "frameLen", static_cast(frameLen)); JAVA_MAP_PUT_INTEGER(configuration, "filterSize", static_cast(filterSize)); env->DeleteLocalRef(mapClass); return JNI_TRUE; } static jlong JAVA_FUNCIMPL(getInternalDelay)(JNIEnv *const env, const jint &handle) { if(handle < 0) { return -1; } MDynamicAudioNormalizer *const instance = javaHandleToInstance(handle); if(instance == NULL) { return -1; /*invalid handle value*/ } int64_t delayInSamples = 0; if(!instance->getInternalDelay(delayInSamples)) { delayInSamples = -1; } return delayInSamples; } /////////////////////////////////////////////////////////////////////////////// // JNI Entry Points /////////////////////////////////////////////////////////////////////////////// extern "C" { JNIEXPORT jboolean JNICALL JAVA_FUNCTION(getVersionInfo)(JNIEnv *const env, jobject, jintArray versionInfo) { JAVA_TRY_CATCH(getVersionInfo, JNI_FALSE, env, versionInfo) } JNIEXPORT jboolean JNICALL JAVA_FUNCTION(getBuildInfo)(JNIEnv *const env, jobject, jobject buildInfo) { JAVA_TRY_CATCH(getBuildInfo, JNI_FALSE, env, buildInfo) } JNIEXPORT jboolean JNICALL JAVA_FUNCTION(setLoggingHandler)(JNIEnv *const env, jobject, jobject loggerObject) { JAVA_TRY_CATCH(setLoggingHandler, JNI_FALSE, env, loggerObject) } JNIEXPORT jint JNICALL JAVA_FUNCTION(createInstance)(JNIEnv *const env, jobject, jint channels, jint sampleRate, jint frameLenMsec, jint filterSize, jdouble peakValue, jdouble maxAmplification, jdouble targetRms, jdouble compressFactor, jboolean channelsCoupled, jboolean enableDCCorrection, jboolean altBoundaryMode) { JAVA_TRY_CATCH(createInstance, -1, env, channels, sampleRate, frameLenMsec, filterSize, peakValue, maxAmplification, targetRms, compressFactor, channelsCoupled, enableDCCorrection, altBoundaryMode) } JNIEXPORT jboolean JNICALL JAVA_FUNCTION(destroyInstance)(JNIEnv *const env, jobject, jint instance) { JAVA_TRY_CATCH(destroyInstance, JNI_FALSE, env, instance) } JNIEXPORT jlong JNICALL JAVA_FUNCTION(process)(JNIEnv *const env, jobject, jint handle, jobjectArray samplesIn, jobjectArray samplesOut, jlong inputSize) { JAVA_TRY_CATCH(process, -1, env, handle, samplesIn, samplesOut, inputSize) } JNIEXPORT jlong JNICALL JAVA_FUNCTION(processInplace)(JNIEnv *const env, jobject, jint handle, jobjectArray samplesInOut, jlong inputSize) { JAVA_TRY_CATCH(processInplace, -1, env, handle, samplesInOut, inputSize) } JNIEXPORT jlong JNICALL JAVA_FUNCTION(flushBuffer)(JNIEnv *const env, jobject, jint handle, jobjectArray samplesOut) { JAVA_TRY_CATCH(flushBuffer, -1, env, handle, samplesOut) } JNIEXPORT jboolean JNICALL JAVA_FUNCTION(reset)(JNIEnv *const env, jobject, jint handle) { JAVA_TRY_CATCH(reset, JNI_FALSE, env, handle) } JNIEXPORT jboolean JNICALL JAVA_FUNCTION(getConfiguration)(JNIEnv *const env, jobject, jint handle, jobject configuration) { JAVA_TRY_CATCH(getConfiguration, JNI_FALSE, env, handle, configuration) } JNIEXPORT jlong JNICALL JAVA_FUNCTION(getInternalDelay)(JNIEnv *const env, jobject, jint handle) { JAVA_TRY_CATCH(getInternalDelay, -1, env, handle) } } #endif //NO_JAVA_SUPPORT ================================================ FILE: DynamicAudioNormalizerAPI/src/DLLMain.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #ifdef _WIN32 /*Win32 only*/ #ifndef MDYNAMICAUDIONORMALIZER_STATIC /*only if building DLL*/ //Windows #define WIN32_LEAN_AND_MEAN #include //VLD #ifndef __MINGW32__ #include #endif BOOL APIENTRY DllMain(HMODULE hModule,DWORD ul_reason_for_call, LPVOID lpReserved) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } #endif //MDYNAMICAUDIONORMALIZER_STATIC #endif //_WIN32 ================================================ FILE: DynamicAudioNormalizerAPI/src/DynamicAudioNormalizer.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif #include "DynamicAudioNormalizer.h" #include "Common.h" #include "FrameBuffer.h" #include "GaussianFilter.h" #include "Logging.h" #include "Version.h" #include #include #include #include #include #include #include #include /////////////////////////////////////////////////////////////////////////////// // Constants /////////////////////////////////////////////////////////////////////////////// static const uint32_t CHANNELS_MIN = 1U; static const uint32_t CHANNELS_MAX = 16U; static const uint32_t SAMPLERATE_MIN = 8000U; static const uint32_t SAMPLERATE_MAX = 192000U; static const uint32_t FRAMELEN_MIN = 32U; static const uint32_t FRAMELEN_MAX = 2097152U; /////////////////////////////////////////////////////////////////////////////// // Static Initializer /////////////////////////////////////////////////////////////////////////////// namespace DYNAUDNORM_NS { class StaticInitializer { public: StaticInitializer(void) { #if defined(_MSC_VER) && (_MSC_VER >= 1800) && (_MSC_VER < 1900) && defined(_M_X64) && (_M_X64 >= 100) // FMA3 support in the MSVC 2013 CRT is broken on Vista and Windows 7 RTM (fixed in SP1). // See https://connect.microsoft.com/VisualStudio/feedback/details/987093/x64-log-function-uses-vpsrlq-avx-instruction-without-regard-to-operating-system-so-it-crashes-on-vista-x64 _set_FMA3_enable(0); #endif } }; } static const DYNAUDNORM_NS::StaticInitializer g_static_init; /////////////////////////////////////////////////////////////////////////////// // Utility Functions /////////////////////////////////////////////////////////////////////////////// #undef LOG_AMPFACTORS #ifdef LOG_AMPFACTORS static void LOG_VALUE(const double &value, const double &prev, const double &curr, const double &next, const uint32_t &channel, const uint32_t &pos) { static FILE *g_myLogfile = FOPEN(TXT("ampFactors.log"), TXT("w")); if(g_myLogfile && (channel == 0) && (pos % 10 == 0)) { fprintf(g_myLogfile, "%.8f\t%.8f %.8f %.8f\n", value, prev, curr, next); } } #else #define LOG_VALUE(...) ((void)0) #endif template static inline T LIMIT(const T &min, const T &val, const T &max) { return std::min(max, std::max(min, val)); } template static inline void UPDATE_MAX(T &max, const T &val) { if (val > max) { max = val; } } static inline uint32_t FRAME_SIZE(const uint32_t &sampleRate, const uint32_t &frameLenMsec) { const uint32_t frameSize = static_cast(round(double(sampleRate) * (double(frameLenMsec) / 1000.0))); return frameSize + (frameSize % 2); } static inline double UPDATE_VALUE(const double &NEW, const double &OLD, const double &aggressiveness) { assert((aggressiveness >= 0.0) && (aggressiveness <= 1.0)); return (aggressiveness * NEW) + ((1.0 - aggressiveness) * OLD); } static inline double FADE(const double &prev, const double &next, const uint32_t &pos, const double *const fadeFactors[2]) { return (fadeFactors[0][pos] * prev) + (fadeFactors[1][pos] * next); } static inline double BOUND(const double &threshold, const double &val) { const double SQRT_PI = 0.8862269254527580136490837416705725913987747280611935; //sqrt(PI) / 2.0 return erf(SQRT_PI * (val / threshold)) * threshold; } static inline double POW2(const double &value) { return value * value; } #define BOOLIFY(X) ((X) ? "YES" : "NO") #define POW2(X) ((X)*(X)) #define CLEAR_QUEUE(X) do \ { \ while(!(X).empty()) (X).pop(); \ } \ while(0) /////////////////////////////////////////////////////////////////////////////// // MDynamicAudioNormalizer_PrivateData /////////////////////////////////////////////////////////////////////////////// class MDynamicAudioNormalizer_PrivateData { public: MDynamicAudioNormalizer_PrivateData(const uint32_t channels, const uint32_t sampleRate, const uint32_t frameLenMsec, const uint32_t filterSize, const double peakValue, const double maxAmplification, const double targetRms, const double compressThresh, const bool channelsCoupled, const bool enableDCCorrection, const bool altBoundaryMode, FILE *const logFile); ~MDynamicAudioNormalizer_PrivateData(void); bool initialize(void); bool process(const double *const *const samplesIn, double *const *const samplesOut, const int64_t inputSize, int64_t &outputSize, const bool &bFlush); bool flushBuffer(double *const *const samplesOut, const int64_t bufferSize, int64_t &outputSize); bool reset(void); bool getConfiguration(uint32_t &channels, uint32_t &sampleRate, uint32_t &frameLen, uint32_t &filterSize); bool getInternalDelay(int64_t &delayInSamples); private: const uint32_t m_channels; const uint32_t m_sampleRate; const uint32_t m_frameLen; const uint32_t m_filterSize; const uint32_t m_prefillLen; const uint32_t m_delay; const double m_peakValue; const double m_maxAmplification; const double m_targetRms; const double m_compressFactor; const bool m_channelsCoupled; const bool m_enableDCCorrection; const bool m_altBoundaryMode; FILE *const m_logFile; bool m_initialized; bool m_flushBuffer; DYNAUDNORM_NS::FrameFIFO *m_buffSrc; DYNAUDNORM_NS::FrameFIFO *m_buffOut; int64_t m_delayedSamples; uint64_t m_sampleCounterTotal; uint64_t m_sampleCounterClips; uint64_t m_sampleCounterCompr; DYNAUDNORM_NS::FrameBuffer *m_frameBuffer; std::deque *m_gainHistory_original; std::deque *m_gainHistory_minimum; std::deque *m_gainHistory_smoothed; std::queue *m_loggingData_original; std::queue *m_loggingData_minimum; std::queue *m_loggingData_smoothed; DYNAUDNORM_NS::GaussianFilter *m_gaussianFilter; double *m_prevAmplificationFactor; double *m_dcCorrectionValue; double *m_compressThreshold; double *m_fadeFactors[2]; protected: void analyzeFrame(DYNAUDNORM_NS::FrameData *const frame); void amplifyFrame(DYNAUDNORM_NS::FrameData *const frame); double getMaxLocalGain(DYNAUDNORM_NS::FrameData *const frame, const uint32_t channel = UINT32_MAX); double findPeakMagnitude(DYNAUDNORM_NS::FrameData *const frame, const uint32_t channel = UINT32_MAX); double computeFrameRMS(const DYNAUDNORM_NS::FrameData *const frame, const uint32_t channel = UINT32_MAX); double computeFrameStdDev(const DYNAUDNORM_NS::FrameData *const frame, const uint32_t channel = UINT32_MAX); void updateGainHistory(const uint32_t &channel, const double ¤tGainFactor); void perfromDCCorrection(DYNAUDNORM_NS::FrameData *const frame, const bool &isFirstFrame); void perfromCompression(DYNAUDNORM_NS::FrameData *const frame, const bool &isFirstFrame); void writeLogFile(void); void printParameters(void); static void precalculateFadeFactors(double *const fadeFactors[2], const uint32_t frameLen); static double setupCompressThresh(const double &dThreshold); }; /////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor /////////////////////////////////////////////////////////////////////////////// MDynamicAudioNormalizer::MDynamicAudioNormalizer(const uint32_t channels, const uint32_t sampleRate, const uint32_t frameLenMsec, const uint32_t filterSize, const double peakValue, const double maxAmplification, const double targetRms, const double compressThresh, const bool channelsCoupled, const bool enableDCCorrection, const bool altBoundaryMode, FILE *const logFile) : p(new MDynamicAudioNormalizer_PrivateData(channels, sampleRate, frameLenMsec, filterSize, peakValue, maxAmplification, targetRms, compressThresh, channelsCoupled, enableDCCorrection, altBoundaryMode,logFile)) { /*nothing to do here*/ } MDynamicAudioNormalizer_PrivateData::MDynamicAudioNormalizer_PrivateData(const uint32_t channels, const uint32_t sampleRate, const uint32_t frameLenMsec, const uint32_t filterSize, const double peakValue, const double maxAmplification, const double targetRms, const double compressFactor, const bool channelsCoupled, const bool enableDCCorrection, const bool altBoundaryMode, FILE *const logFile) : m_channels(channels), m_sampleRate(sampleRate), m_frameLen(FRAME_SIZE(sampleRate, frameLenMsec)), m_filterSize(LIMIT(3u, filterSize, 301u)), m_prefillLen(m_filterSize / 2u), m_delay(m_frameLen * m_filterSize), m_peakValue(LIMIT(0.01, peakValue, 1.0)), m_maxAmplification(LIMIT(1.0, maxAmplification, 100.0)), m_targetRms(LIMIT(0.0, targetRms, 1.0)), m_compressFactor(compressFactor ? LIMIT(1.0, compressFactor, 30.0) : 0.0), m_channelsCoupled(channelsCoupled), m_enableDCCorrection(enableDCCorrection), m_altBoundaryMode(altBoundaryMode), m_logFile(logFile) { // LOG2_DBG("channels: %u", channels); // LOG2_DBG("sampleRate: %u", sampleRate); // LOG2_DBG("frameLenMsec: %u", frameLenMsec); // LOG2_DBG("filterSize: %u", filterSize); // LOG2_DBG("peakValue: %.4f", peakValue); // LOG2_DBG("maxAmplification: %.4f", maxAmplification); // LOG2_DBG("targetRms: %.4f", targetRms); // LOG2_DBG("compressFactor: %.4f", compressFactor); // LOG2_DBG("channelsCoupled: %s", channelsCoupled ? "YES" : "NO"); // LOG2_DBG("enableDCCorrection: %s", enableDCCorrection ? "YES" : "NO"); // LOG2_DBG("altBoundaryMode: %s", altBoundaryMode ? "YES" : "NO"); // LOG2_DBG("logFile: %p", logFile); m_initialized = false; m_flushBuffer = false; m_buffSrc = NULL; m_buffOut = NULL; m_delayedSamples = 0; m_sampleCounterClips = m_sampleCounterTotal = 0; m_frameBuffer = NULL; m_gaussianFilter = NULL; m_gainHistory_original = NULL; m_gainHistory_minimum = NULL; m_gainHistory_smoothed = NULL; m_loggingData_original = NULL; m_loggingData_minimum = NULL; m_loggingData_smoothed = NULL; m_prevAmplificationFactor = NULL; m_dcCorrectionValue = NULL; m_compressThreshold = NULL; m_fadeFactors[0] = m_fadeFactors[1] = NULL; } MDynamicAudioNormalizer::~MDynamicAudioNormalizer(void) { delete p; } MDynamicAudioNormalizer_PrivateData::~MDynamicAudioNormalizer_PrivateData(void) { LOG2_DBG("Processed %" PRIu64 " samples total, clipped %" PRIu64 " samples (%.2f%%).", m_sampleCounterTotal, m_sampleCounterClips, m_sampleCounterTotal ? (double(m_sampleCounterClips) / double(m_sampleCounterTotal) * 100.0) : 0.0 ); MY_DELETE(m_buffSrc); MY_DELETE(m_buffOut); MY_DELETE(m_frameBuffer); MY_DELETE(m_gaussianFilter); MY_DELETE_ARRAY(m_gainHistory_original); MY_DELETE_ARRAY(m_gainHistory_minimum ); MY_DELETE_ARRAY(m_gainHistory_smoothed); MY_DELETE_ARRAY(m_loggingData_original); MY_DELETE_ARRAY(m_loggingData_minimum ); MY_DELETE_ARRAY(m_loggingData_smoothed); MY_DELETE_ARRAY(m_prevAmplificationFactor); MY_DELETE_ARRAY(m_dcCorrectionValue); MY_DELETE_ARRAY(m_compressThreshold); MY_DELETE_ARRAY(m_fadeFactors[0]); MY_DELETE_ARRAY(m_fadeFactors[1]); } /////////////////////////////////////////////////////////////////////////////// // Public API /////////////////////////////////////////////////////////////////////////////// bool MDynamicAudioNormalizer::initialize(void) { try { return p->initialize(); } catch(std::exception &e) { LOG1_ERR(e.what()); return false; } } bool MDynamicAudioNormalizer_PrivateData::initialize(void) { if(m_initialized) { LOG1_WRN("Already initialized -> ignoring!"); return true; } if((m_channels < CHANNELS_MIN) || (m_channels > CHANNELS_MAX)) { LOG2_ERR("Invalid or unsupported channel count. Should be in the %u to %u range!", CHANNELS_MIN, CHANNELS_MAX); return false; } if((m_sampleRate < SAMPLERATE_MIN) || (m_sampleRate > SAMPLERATE_MAX)) { LOG2_ERR("Invalid or unsupported sampling rate. Should be in the %u to %u range!", SAMPLERATE_MIN, SAMPLERATE_MAX); return false; } if((m_frameLen < FRAMELEN_MIN) || (m_frameLen > FRAMELEN_MAX)) { LOG2_ERR("Invalid or unsupported frame size. Should be in the %u to %u range!", FRAMELEN_MIN, FRAMELEN_MAX); return false; } if(m_logFile && (ferror(m_logFile) != 0)) { LOG1_WRN("Specified log file has the error indicator set, no logging information will be created!"); } m_buffSrc = new DYNAUDNORM_NS::FrameFIFO(m_channels, m_frameLen); m_buffOut = new DYNAUDNORM_NS::FrameFIFO(m_channels, m_frameLen); m_frameBuffer = new DYNAUDNORM_NS::FrameBuffer(m_channels, m_frameLen, m_filterSize + 1); m_gainHistory_original = new std::deque[m_channels]; m_gainHistory_minimum = new std::deque[m_channels]; m_gainHistory_smoothed = new std::deque[m_channels]; m_loggingData_original = new std::queue[m_channels]; m_loggingData_minimum = new std::queue[m_channels]; m_loggingData_smoothed = new std::queue[m_channels]; const double sigma = (((double(m_filterSize) / 2.0) - 1.0) / 3.0) + (1.0 / 3.0); m_gaussianFilter = new DYNAUDNORM_NS::GaussianFilter(m_filterSize, sigma); m_dcCorrectionValue = new double[m_channels]; m_prevAmplificationFactor = new double[m_channels]; m_compressThreshold = new double[m_channels]; m_fadeFactors[0] = new double[m_frameLen]; m_fadeFactors[1] = new double[m_frameLen]; precalculateFadeFactors(m_fadeFactors, m_frameLen); printParameters(); if(m_logFile) { fprintf(m_logFile, "DynamicAudioNormalizer Logfile v%u.%02u-%u\n", DYNAUDNORM_NS::VERSION_MAJOR, DYNAUDNORM_NS::VERSION_MINOR, DYNAUDNORM_NS::VERSION_PATCH); fprintf(m_logFile, "CHANNEL_COUNT:%u\n\n", m_channels); } m_initialized = true; reset(); return true; } bool MDynamicAudioNormalizer::reset(void) { try { return p->reset(); } catch(std::exception &e) { LOG1_ERR(e.what()); return false; } } bool MDynamicAudioNormalizer_PrivateData::reset(void) { //Check audio normalizer status if(!m_initialized) { LOG1_ERR("Not initialized yet. Must call initialize() first!"); return false; } m_delayedSamples = 0; m_flushBuffer = false; m_buffSrc->reset(); m_buffOut->reset(); m_frameBuffer->reset(); for(uint32_t c = 0; c < m_channels; c++) { m_gainHistory_original[c].clear(); m_gainHistory_minimum [c].clear(); m_gainHistory_smoothed[c].clear(); CLEAR_QUEUE(m_loggingData_original[c]); CLEAR_QUEUE(m_loggingData_minimum [c]); CLEAR_QUEUE(m_loggingData_smoothed[c]); m_dcCorrectionValue [c] = 0.0; m_prevAmplificationFactor[c] = 1.0; m_compressThreshold [c] = 0.0; } return true; } bool MDynamicAudioNormalizer::getConfiguration(uint32_t &channels, uint32_t &sampleRate, uint32_t &frameLen, uint32_t &filterSize) { try { return p->getConfiguration(channels, sampleRate, frameLen, filterSize); } catch(std::exception &e) { LOG1_ERR(e.what()); return false; } } bool MDynamicAudioNormalizer::getInternalDelay(int64_t &delayInSamples) { try { return p->getInternalDelay(delayInSamples); } catch(std::exception &e) { LOG1_ERR(e.what()); return false; } } bool MDynamicAudioNormalizer_PrivateData::getConfiguration(uint32_t &channels, uint32_t &sampleRate, uint32_t &frameLen, uint32_t &filterSize) { //Check audio normalizer status if(!m_initialized) { LOG1_ERR("Not initialized yet. Must call initialize() first!"); return false; } channels = m_channels; sampleRate = m_sampleRate; frameLen = m_frameLen; filterSize = m_filterSize; return true; } bool MDynamicAudioNormalizer_PrivateData::getInternalDelay(int64_t &delayInSamples) { //Check audio normalizer status if(!m_initialized) { LOG1_ERR("Not initialized yet. Must call initialize() first!"); return false; } delayInSamples = m_delay; //m_frameLen * m_filterSize; return true; } bool MDynamicAudioNormalizer::process(const double *const *const samplesIn, double *const *const samplesOut, const int64_t inputSize, int64_t &outputSize) { try { return p->process(samplesIn, samplesOut, inputSize, outputSize, false); } catch (std::exception &e) { LOG1_ERR(e.what()); return false; } } bool MDynamicAudioNormalizer::processInplace(double *const *const samplesInOut, const int64_t inputSize, int64_t &outputSize) { try { return p->process(samplesInOut, samplesInOut, inputSize, outputSize, false); } catch(std::exception &e) { LOG1_ERR(e.what()); return false; } } bool MDynamicAudioNormalizer_PrivateData::process(const double *const *const samplesIn, double *const *const samplesOut, const int64_t inputSize, int64_t &outputSize, const bool &bFlush) { outputSize = 0; //Check audio normalizer status if(!m_initialized) { LOG1_ERR("Not initialized yet. Must call initialize() first!"); return false; } if(m_flushBuffer && (!bFlush)) { LOG1_ERR("Must not call processInplace() after flushBuffer(). Call reset() first!"); return false; } bool bStop = false; uint32_t inputPos = 0; uint32_t inputSamplesLeft = static_cast(LIMIT(int64_t(0), inputSize, int64_t(UINT32_MAX))); uint32_t outputPos = 0; uint32_t outputBufferLeft = 0; while(!bStop) { bStop = true; //Read as many input samples as possible while((inputSamplesLeft > 0) && (m_buffSrc->samplesLeftPut() > 0)) { bStop = false; const uint32_t copyLen = std::min(inputSamplesLeft, m_buffSrc->samplesLeftPut()); m_buffSrc->putSamples(samplesIn, inputPos, copyLen); inputPos += copyLen; inputSamplesLeft -= copyLen; outputBufferLeft += copyLen; if(!bFlush) { m_delayedSamples += copyLen; } } //Analyze next input frame, if we have enough input if(m_buffSrc->samplesLeftGet() >= m_frameLen) { bStop = false; analyzeFrame(m_buffSrc->data()); if(!m_frameBuffer->putFrame(m_buffSrc)) { LOG1_ERR("Failed to append current input frame to internal buffer!"); return false; } m_buffSrc->reset(); } //Amplify next output frame, if we have enough output if((m_buffOut->samplesLeftPut() >= m_frameLen) && (m_frameBuffer->framesUsed() > 0) && (!m_gainHistory_smoothed[0].empty())) { bStop = false; if(!m_frameBuffer->getFrame(m_buffOut)) { LOG1_ERR("Failed to retrieve next output frame from internal buffer!"); return false; } amplifyFrame(m_buffOut->data()); } //Write as many output samples as possible while((outputBufferLeft > 0) && (m_buffOut->samplesLeftGet() > 0) && (bFlush || (m_delayedSamples > m_delay))) { bStop = false; const uint32_t pending = bFlush ? UINT32_MAX : uint32_t(m_delayedSamples - m_delay); const uint32_t copyLen = std::min(std::min(outputBufferLeft, m_buffOut->samplesLeftGet()), pending); m_buffOut->getSamples(samplesOut, outputPos, copyLen); outputPos += copyLen; outputBufferLeft -= copyLen; m_delayedSamples -= copyLen; if((m_buffOut->samplesLeftGet() < 1) && (m_buffOut->samplesLeftPut() < 1)) { m_buffOut->reset(); } } } outputSize = int64_t(outputPos); if(inputSamplesLeft > 0) { LOG1_WRN("No all input samples could be processed -> discarding pending input!"); return false; } return true; } bool MDynamicAudioNormalizer::flushBuffer(double *const *const samplesOut, const int64_t bufferSize, int64_t &outputSize) { try { return p->flushBuffer(samplesOut, bufferSize, outputSize); } catch(std::exception &e) { LOG1_ERR(e.what()); return false; } } bool MDynamicAudioNormalizer_PrivateData::flushBuffer(double *const *const samplesOut, const int64_t bufferSize, int64_t &outputSize) { outputSize = 0; //Check audio normalizer status if(!m_initialized) { LOG1_ERR("Not initialized yet. Must call initialize() first!"); return false; } m_flushBuffer = true; const uint32_t pendingSamples = static_cast(LIMIT(int64_t(0), std::min(m_delayedSamples, bufferSize), int64_t(UINT32_MAX))); if(pendingSamples < 1) { return true; /*no pending samples left*/ } bool success = false; do { for(uint32_t c = 0; c < m_channels; c++) { for(uint32_t i = 0; i < pendingSamples; i++) { samplesOut[c][i] = m_altBoundaryMode ? DBL_EPSILON : ((m_targetRms > DBL_EPSILON) ? std::min(m_peakValue, m_targetRms) : m_peakValue); if(m_enableDCCorrection) { samplesOut[c][i] *= ((i % 2) == 1) ? (-1) : 1; samplesOut[c][i] += m_dcCorrectionValue[c]; } } } success = process(samplesOut, samplesOut, pendingSamples, outputSize, true); } while(success && (outputSize <= 0)); return success; } /////////////////////////////////////////////////////////////////////////////// // Public Static Functions /////////////////////////////////////////////////////////////////////////////// void MDynamicAudioNormalizer::getVersionInfo(uint32_t &major, uint32_t &minor,uint32_t &patch) { major = DYNAUDNORM_NS::VERSION_MAJOR; minor = DYNAUDNORM_NS::VERSION_MINOR; patch = DYNAUDNORM_NS::VERSION_PATCH; } void MDynamicAudioNormalizer::getBuildInfo(const char **const date, const char **const time, const char **const compiler, const char **const arch, bool &debug) { *date = DYNAUDNORM_NS::BUILD_DATE; *time = DYNAUDNORM_NS::BUILD_TIME; *compiler = DYNAUDNORM_NS::BUILD_COMPILER; *arch = DYNAUDNORM_NS::BUILD_ARCH; debug = bool(DYNAUDNORM_DEBUG); } MDynamicAudioNormalizer::LogFunction *MDynamicAudioNormalizer::setLogFunction(MDynamicAudioNormalizer::LogFunction *const logFunction) { return DYNAUDNORM_NS::setLoggingHandler(logFunction); } /////////////////////////////////////////////////////////////////////////////// // Procesing Functions /////////////////////////////////////////////////////////////////////////////// void MDynamicAudioNormalizer_PrivateData::analyzeFrame(DYNAUDNORM_NS::FrameData *const frame) { //Perform DC Correction (optional) if(m_enableDCCorrection) { perfromDCCorrection(frame, m_gainHistory_original[0].empty()); } //Perform compression (optional) if(m_compressFactor > DBL_EPSILON) { perfromCompression(frame, m_gainHistory_original[0].empty()); } //Find the frame's peak sample value if(m_channelsCoupled) { const double currentGainFactor = getMaxLocalGain(frame); for(uint32_t c = 0; c < m_channels; c++) { updateGainHistory(c, currentGainFactor); } } else { for(uint32_t c = 0; c < m_channels; c++) { updateGainHistory(c, getMaxLocalGain(frame, c)); } } //Write data to the log file writeLogFile(); } void MDynamicAudioNormalizer_PrivateData::amplifyFrame(DYNAUDNORM_NS::FrameData *const frame) { for(uint32_t c = 0; c < m_channels; c++) { if(m_gainHistory_smoothed[c].empty()) { LOG1_WRN("There are no information available for the current frame!"); break; } double *const dataPtr = frame->data(c); const double currAmplificationFactor = m_gainHistory_smoothed[c].front(); m_gainHistory_smoothed[c].pop_front(); for(uint32_t i = 0; i < m_frameLen; i++) { const double amplificationFactor = FADE(m_prevAmplificationFactor[c], currAmplificationFactor, i, m_fadeFactors); dataPtr[i] *= amplificationFactor; LOG_VALUE(amplificationFactor, m_prevAmplificationFactor[c], currAmplificationFactor, nextAmplificationFactor, c, i); if(fabs(dataPtr[i]) > m_peakValue) { m_sampleCounterClips++; dataPtr[i] = copysign(m_peakValue, dataPtr[i]); /*fix rare clipping*/ } } m_prevAmplificationFactor[c] = currAmplificationFactor; m_sampleCounterTotal += m_frameLen; } } /////////////////////////////////////////////////////////////////////////////// // Helper Functions /////////////////////////////////////////////////////////////////////////////// double MDynamicAudioNormalizer_PrivateData::getMaxLocalGain(DYNAUDNORM_NS::FrameData *const frame, const uint32_t channel) { const double maximumGain = m_peakValue / findPeakMagnitude(frame, channel); const double rmsGain = (m_targetRms > DBL_EPSILON) ? (m_targetRms / computeFrameRMS(frame, channel)) : DBL_MAX; return BOUND(m_maxAmplification, std::min(maximumGain, rmsGain)); } double MDynamicAudioNormalizer_PrivateData::findPeakMagnitude(DYNAUDNORM_NS::FrameData *const frame, const uint32_t channel) { double dMax = DBL_EPSILON; if (channel == UINT32_MAX) { for (uint32_t c = 0; c < m_channels; c++) { double *const dataPtr = frame->data(c); for (uint32_t i = 0; i < m_frameLen; i++) { UPDATE_MAX(dMax, fabs(dataPtr[i])); } } } else { double *const dataPtr = frame->data(channel); for (uint32_t i = 0; i < m_frameLen; i++) { UPDATE_MAX(dMax, fabs(dataPtr[i])); } } return dMax; } double MDynamicAudioNormalizer_PrivateData::computeFrameRMS(const DYNAUDNORM_NS::FrameData *const frame, const uint32_t channel) { double rmsValue = 0.0; if(channel == UINT32_MAX) { for(uint32_t c = 0; c < m_channels; c++) { const double *dataPtr = frame->data(c); for(uint32_t i = 0; i < m_frameLen; i++) { rmsValue += POW2(dataPtr[i]); } } rmsValue /= double(m_frameLen * m_channels); } else { const double *dataPtr = frame->data(channel); for(uint32_t i = 0; i < m_frameLen; i++) { rmsValue += POW2(dataPtr[i]); } rmsValue /= double(m_frameLen); } return std::max(sqrt(rmsValue), DBL_EPSILON); } double MDynamicAudioNormalizer_PrivateData::computeFrameStdDev(const DYNAUDNORM_NS::FrameData *const frame, const uint32_t channel) { double variance = 0.0; if(channel == UINT32_MAX) { for(uint32_t c = 0; c < m_channels; c++) { const double *dataPtr = frame->data(c); for(uint32_t i = 0; i < m_frameLen; i++) { variance += POW2(dataPtr[i]); //Assume that MEAN is *zero* } } variance /= double((m_channels * m_frameLen) - 1); } else { const double *dataPtr = frame->data(channel); for(uint32_t i = 0; i < m_frameLen; i++) { variance += POW2(dataPtr[i]); //Assume that MEAN is *zero* } variance /= double(m_frameLen - 1); } return std::max(sqrt(variance), DBL_EPSILON); } void MDynamicAudioNormalizer_PrivateData::updateGainHistory(const uint32_t &channel, const double ¤tGainFactor) { //Pre-fill the gain history if(m_gainHistory_original[channel].empty() || m_gainHistory_minimum[channel].empty()) { const double initial_value = m_altBoundaryMode ? currentGainFactor : 1.0; m_prevAmplificationFactor[channel] = initial_value; while(m_gainHistory_original[channel].size() < m_prefillLen) { m_gainHistory_original[channel].push_back(initial_value); } } //Insert current gain factor m_gainHistory_original[channel].push_back(currentGainFactor); m_loggingData_original[channel].push (currentGainFactor); //Apply the minimum filter while(m_gainHistory_original[channel].size() >= m_filterSize) { assert(m_gainHistory_original[channel].size() == m_filterSize); if (m_gainHistory_minimum[channel].empty()) { double initial_value = m_altBoundaryMode ? m_gainHistory_original[channel].front() : 1.0; std::deque::const_iterator input = m_gainHistory_original[channel].begin() + m_prefillLen; while (m_gainHistory_minimum[channel].size() < m_prefillLen) { initial_value = std::min(initial_value, *(++input)); m_gainHistory_minimum[channel].push_back(initial_value); } } const double minimum = *std::min_element(m_gainHistory_original[channel].begin(), m_gainHistory_original[channel].end()); m_gainHistory_original[channel].pop_front(); m_gainHistory_minimum[channel].push_back(minimum); m_loggingData_minimum[channel].push(minimum); } //Apply the Gaussian filter while(m_gainHistory_minimum[channel].size() >= m_filterSize) { assert(m_gainHistory_minimum[channel].size() == m_filterSize); const double smoothed = m_gaussianFilter->apply(m_gainHistory_minimum[channel]); m_gainHistory_minimum[channel].pop_front(); m_gainHistory_smoothed[channel].push_back(smoothed); m_loggingData_smoothed[channel].push(smoothed); } } void MDynamicAudioNormalizer_PrivateData::perfromDCCorrection(DYNAUDNORM_NS::FrameData *const frame, const bool &isFirstFrame) { const double diff = 1.0 / double(m_frameLen); for(uint32_t c = 0; c < m_channels; c++) { double *const dataPtr = frame->data(c); double currentAverageValue = 0.0; for(uint32_t i = 0; i < m_frameLen; i++) { currentAverageValue += (dataPtr[i] * diff); } const double prevValue = isFirstFrame ? currentAverageValue : m_dcCorrectionValue[c]; m_dcCorrectionValue[c] = isFirstFrame ? currentAverageValue : UPDATE_VALUE(currentAverageValue, m_dcCorrectionValue[c], 0.1); for(uint32_t i = 0; i < m_frameLen; i++) { dataPtr[i] -= FADE(prevValue, m_dcCorrectionValue[c], i, m_fadeFactors); } } } void MDynamicAudioNormalizer_PrivateData::perfromCompression(DYNAUDNORM_NS::FrameData *const frame, const bool &isFirstFrame) { if(m_channelsCoupled) { const double standardDeviation = computeFrameStdDev(frame); const double currentThreshold = std::min(1.0, m_compressFactor * standardDeviation); const double prevValue = isFirstFrame ? currentThreshold : m_compressThreshold[0]; m_compressThreshold[0] = isFirstFrame ? currentThreshold : UPDATE_VALUE(currentThreshold, m_compressThreshold[0], (1.0/3.0)); const double prevActualThresh = setupCompressThresh(prevValue); const double currActualThresh = setupCompressThresh(m_compressThreshold[0]); for(uint32_t c = 0; c < m_channels; c++) { double *const dataPtr = frame->data(c); for(uint32_t i = 0; i < m_frameLen; i++) { const double localThresh = FADE(prevActualThresh, currActualThresh, i, m_fadeFactors); dataPtr[i] = copysign(BOUND(localThresh, fabs(dataPtr[i])), dataPtr[i]); } } } else { for(uint32_t c = 0; c < m_channels; c++) { const double standardDeviation = computeFrameStdDev(frame, c); const double currentThreshold = setupCompressThresh(std::min(1.0,m_compressFactor * standardDeviation)); const double prevValue = isFirstFrame ? currentThreshold : m_compressThreshold[c]; m_compressThreshold[c] = isFirstFrame ? currentThreshold : UPDATE_VALUE(currentThreshold, m_compressThreshold[c], (1.0/3.0)); const double prevActualThresh = setupCompressThresh(prevValue); const double currActualThresh = setupCompressThresh(m_compressThreshold[c]); double *const dataPtr = frame->data(c); for(uint32_t i = 0; i < m_frameLen; i++) { const double localThresh = FADE(prevActualThresh, currActualThresh, i, m_fadeFactors); dataPtr[i] = copysign(BOUND(localThresh, fabs(dataPtr[i])), dataPtr[i]); } } } } void MDynamicAudioNormalizer_PrivateData::writeLogFile(void) { bool bIsEmpty = false; for (uint32_t c = 0; c < m_channels; c++) { bIsEmpty = bIsEmpty || m_loggingData_original[c].empty() || m_loggingData_minimum[c].empty() || m_loggingData_smoothed[c].empty(); } while (!bIsEmpty) { for (uint32_t c = 0; c < m_channels; c++) { if (m_logFile && (ferror(m_logFile) == 0)) { if (c > 0) { fprintf(m_logFile, "\t\t"); } fprintf(m_logFile, "%.5f\t%.5f\t%.5f", m_loggingData_original[c].front(), m_loggingData_minimum[c].front(), m_loggingData_smoothed[c].front()); } m_loggingData_original[c].pop(); m_loggingData_minimum[c].pop(); m_loggingData_smoothed[c].pop(); bIsEmpty = bIsEmpty || m_loggingData_original[c].empty() || m_loggingData_minimum[c].empty() || m_loggingData_smoothed[c].empty(); } if (m_logFile && (ferror(m_logFile) == 0)) { fprintf(m_logFile, "\n"); } } if(m_logFile && (ferror(m_logFile) != 0)) { if(ferror(m_logFile) != 0) { LOG1_WRN("Error while writing to log file. No further logging output will be created."); } } } void MDynamicAudioNormalizer_PrivateData::printParameters(void) { LOG1_DBG("------- DynamicAudioNormalizer -------"); LOG2_DBG("Lib Version : %u.%02u-%u", DYNAUDNORM_NS::VERSION_MAJOR, DYNAUDNORM_NS::VERSION_MINOR , DYNAUDNORM_NS::VERSION_PATCH); LOG2_DBG("m_channels : %u", m_channels); LOG2_DBG("m_sampleRate : %u", m_sampleRate); LOG2_DBG("m_frameLen : %u", m_frameLen); LOG2_DBG("m_filterSize : %u", m_filterSize); LOG2_DBG("m_peakValue : %.4f", m_peakValue); LOG2_DBG("m_maxAmplification : %.4f", m_maxAmplification); LOG2_DBG("m_targetRms : %.4f", m_targetRms); LOG2_DBG("m_compressFactor : %.4f", m_compressFactor); LOG2_DBG("m_channelsCoupled : %s", BOOLIFY(m_channelsCoupled)); LOG2_DBG("m_enableDCCorrection : %s", BOOLIFY(m_enableDCCorrection)); LOG2_DBG("m_altBoundaryMode : %s", BOOLIFY(m_altBoundaryMode)); LOG1_DBG("------- DynamicAudioNormalizer -------"); } /////////////////////////////////////////////////////////////////////////////// // Static Utility Functions /////////////////////////////////////////////////////////////////////////////// void MDynamicAudioNormalizer_PrivateData::precalculateFadeFactors(double *const fadeFactors[2], const uint32_t frameLen) { assert((frameLen > 0) && ((frameLen % 2) == 0)); const double dStepSize = 1.0 / double(frameLen); for(uint32_t pos = 0; pos < frameLen; pos++) { fadeFactors[0][pos] = 1.0 - (dStepSize * double(pos + 1U)); fadeFactors[1][pos] = 1.0 - fadeFactors[0][pos]; } //for(uint32_t pos = 0; pos < frameLen; pos++) //{ // LOG2_DBG("%.8f %.8f %.8f", fadeFactors[0][pos], fadeFactors[1][pos], fadeFactors[0][pos] + fadeFactors[1][pos]); //} } double MDynamicAudioNormalizer_PrivateData::setupCompressThresh(const double &dThreshold) { if((dThreshold > DBL_EPSILON) && (dThreshold < (1.0 - DBL_EPSILON))) { double dCurrentThreshold = dThreshold; double dStepSize = 1.0; while(dStepSize > DBL_EPSILON) { while((dCurrentThreshold + dStepSize > dCurrentThreshold) && (BOUND(dCurrentThreshold + dStepSize, 1.0) <= dThreshold)) { dCurrentThreshold += dStepSize; } dStepSize /= 2.0; } return dCurrentThreshold; } else { return dThreshold; } } ================================================ FILE: DynamicAudioNormalizerAPI/src/FrameBuffer.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "FrameBuffer.h" /////////////////////////////////////////////////////////////////////////////// // Frame Data /////////////////////////////////////////////////////////////////////////////// DYNAUDNORM_NS::FrameData::FrameData(const uint32_t &channels, const uint32_t &frameLength) : m_channels(channels), m_frameLength(frameLength) { m_data = new double*[m_channels]; for(uint32_t c = 0; c < m_channels; c++) { m_data[c] = new double[m_frameLength]; } clear(); } DYNAUDNORM_NS::FrameData::~FrameData(void) { for(uint32_t c = 0; c < m_channels; c++) { MY_DELETE_ARRAY(m_data[c]); } MY_DELETE_ARRAY(m_data); } void DYNAUDNORM_NS::FrameData::clear(void) { for(uint32_t c = 0; c < m_channels; c++) { memset(m_data[c], 0, m_frameLength * sizeof(double)); } } /////////////////////////////////////////////////////////////////////////////// // Frame FIFO /////////////////////////////////////////////////////////////////////////////// DYNAUDNORM_NS::FrameFIFO::FrameFIFO(const uint32_t &channels, const uint32_t &frameLength) { m_data = new DYNAUDNORM_NS::FrameData(channels, frameLength); reset(false); } DYNAUDNORM_NS::FrameFIFO::~FrameFIFO(void) { MY_DELETE(m_data); } void DYNAUDNORM_NS::FrameFIFO::reset(const bool &bForceClear) { if(bForceClear) m_data->clear(); m_posPut = m_posGet = m_leftGet = 0; m_leftPut = m_data->frameLength(); } /////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor /////////////////////////////////////////////////////////////////////////////// DYNAUDNORM_NS::FrameBuffer::FrameBuffer(const uint32_t &channels, const uint32_t &frameLength, const uint32_t &frameCount) : m_channels(channels), m_frameLength(frameLength), m_frameCount(frameCount) { m_framesFree = m_frameCount; m_framesUsed = 0; m_posPut = m_posGet = 0; m_frames = new DYNAUDNORM_NS::FrameData*[m_frameCount]; for(uint32_t i = 0; i < m_frameCount; i++) { m_frames[i] = new DYNAUDNORM_NS::FrameData(m_channels, m_frameLength); } } DYNAUDNORM_NS::FrameBuffer::~FrameBuffer(void) { for(uint32_t i = 0; i < m_frameCount; i++) { MY_DELETE(m_frames[i]); } MY_DELETE_ARRAY(m_frames); } /////////////////////////////////////////////////////////////////////////////// // Reset /////////////////////////////////////////////////////////////////////////////// void DYNAUDNORM_NS::FrameBuffer::reset(void) { m_framesFree = m_frameCount; m_framesUsed = 0; m_posPut = m_posGet = 0; for(uint32_t i = 0; i < m_frameCount; i++) { m_frames[i]->clear(); } } /////////////////////////////////////////////////////////////////////////////// // Put / Get Frame /////////////////////////////////////////////////////////////////////////////// bool DYNAUDNORM_NS::FrameBuffer::putFrame(DYNAUDNORM_NS::FrameFIFO *const src) { if((m_framesFree < 1) && (src->samplesLeftGet() < m_frameLength)) { return false; } src->getSamples(m_frames[m_posPut], 0, m_frameLength); m_posPut = ((m_posPut + 1) % m_frameCount); m_framesUsed++; m_framesFree--; return true; } bool DYNAUDNORM_NS::FrameBuffer::getFrame(DYNAUDNORM_NS::FrameFIFO *const dest) { if((m_framesUsed < 1) && (dest->samplesLeftPut() < m_frameLength)) { return false; } dest->putSamples(m_frames[m_posGet], 0, m_frameLength); m_posGet = ((m_posGet + 1) % m_frameCount); m_framesUsed--; m_framesFree++; return true; } ================================================ FILE: DynamicAudioNormalizerAPI/src/FrameBuffer.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #include "Common.h" #include #include #include namespace DYNAUDNORM_NS { class FrameData { public: FrameData(const uint32_t &channels, const uint32_t &frameLength); ~FrameData(void); inline double *data(const uint32_t &channel) { assert(channel < m_channels); return m_data[channel]; } inline const double *data(const uint32_t &channel) const { assert(channel < m_channels); return m_data[channel]; } inline const uint32_t &channels(void) { return m_channels; } inline const uint32_t &frameLength(void) { return m_frameLength; } inline void write(const double *const *const src, const uint32_t &srcOffset, const uint32_t &destOffset, const uint32_t &length) { assert(length + destOffset <= m_frameLength); for (uint32_t c = 0; c < m_channels; c++) { memcpy(&m_data[c][destOffset], &src[c][srcOffset], length * sizeof(double)); } } inline void write(const FrameData *const src, const uint32_t &srcOffset, const uint32_t &destOffset, const uint32_t &length) { assert(length + destOffset <= m_frameLength); for (uint32_t c = 0; c < m_channels; c++) { memcpy(&m_data[c][destOffset], &src->data(c)[srcOffset], length * sizeof(double)); } } inline void read(double *const *const dest, const uint32_t &destOffset, const uint32_t &srcOffset, const uint32_t &length) { assert(length + srcOffset <= m_frameLength); for (uint32_t c = 0; c < m_channels; c++) { memcpy(&dest[c][destOffset], &m_data[c][srcOffset], length * sizeof(double)); } } inline void read(FrameData *const dest, const uint32_t &destOffset, const uint32_t &srcOffset, const uint32_t &length) { assert(length + srcOffset <= m_frameLength); for (uint32_t c = 0; c < m_channels; c++) { memcpy(&dest->data(c)[destOffset], &m_data[c][srcOffset], length * sizeof(double)); } } void clear(void); private: FrameData(const FrameData&) : m_channels(0), m_frameLength(0) { throw "unsupported"; } FrameData &operator=(const FrameData&) { throw "unsupported"; } const uint32_t m_channels; const uint32_t m_frameLength; double **m_data; }; class FrameFIFO { public: FrameFIFO(const uint32_t &channels, const uint32_t &frameLength); ~FrameFIFO(void); inline uint32_t samplesLeftPut(void) { return m_leftPut; } inline uint32_t samplesLeftGet(void) { return m_leftGet; } inline void putSamples(const double *const *const src, const uint32_t &srcOffset, const uint32_t &length) { assert(length <= samplesLeftPut()); m_data->write(src, srcOffset, m_posPut, length); m_posPut += length; m_leftPut -= length; m_leftGet += length; } inline void putSamples(const FrameData *const src, const uint32_t &srcOffset, const uint32_t &length) { assert(length <= samplesLeftPut()); m_data->write(src, srcOffset, m_posPut, length); m_posPut += length; m_leftPut -= length; m_leftGet += length; } inline void getSamples(double *const *const dest, const uint32_t &destOffset, const uint32_t &length) { assert(length <= samplesLeftGet()); m_data->read(dest, destOffset, m_posGet, length); m_posGet += length; m_leftGet -= length; } inline void getSamples(FrameData *const dest, const uint32_t &destOffset, const uint32_t &length) { assert(length <= samplesLeftGet()); m_data->read(dest, destOffset, m_posGet, length); m_posGet += length; m_leftGet -= length; } inline FrameData *data(void) { return m_data; } void reset(const bool &bForceClear = true); private: FrameData *m_data; uint32_t m_posPut; uint32_t m_posGet; uint32_t m_leftPut; uint32_t m_leftGet; }; class FrameBuffer { public: FrameBuffer(const uint32_t &channels, const uint32_t &frameLength, const uint32_t &frameCount); ~FrameBuffer(void); bool putFrame(FrameFIFO *const src); bool getFrame(FrameFIFO *const dest); inline const uint32_t &channels(void) { return m_channels; } inline const uint32_t &frameLength(void) { return m_frameLength; } inline const uint32_t &frameCount(void) { return m_frameCount; } inline const uint32_t &framesFree(void) { return m_framesFree; } inline const uint32_t &framesUsed(void) { return m_framesUsed; } void reset(void); private: FrameBuffer(const FrameBuffer&) : m_channels(0), m_frameLength(0), m_frameCount(0) { throw "unsupported"; } FrameBuffer &operator=(const FrameBuffer&) { throw "unsupported"; } const uint32_t m_channels; const uint32_t m_frameLength; const uint32_t m_frameCount; uint32_t m_framesFree; uint32_t m_framesUsed; uint32_t m_posPut; uint32_t m_posGet; FrameData **m_frames; }; } ================================================ FILE: DynamicAudioNormalizerAPI/src/GaussianFilter.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "GaussianFilter.h" #include "Common.h" #include #include #include static const double s_pi = 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679; /////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor /////////////////////////////////////////////////////////////////////////////// DYNAUDNORM_NS::GaussianFilter::GaussianFilter(const uint32_t &filterSize, const double &sigma) : m_filterSize(filterSize) { if((filterSize < 1) || ((filterSize % 2) != 1)) { throw std::runtime_error("Filter size must be a positive and odd value!"); } //Allocate weights m_weights = new double[filterSize]; double totalWeight = 0.0; //Pre-computer constants const uint32_t offset = m_filterSize / 2; const double c1 = 1.0 / (sigma * sqrt(2.0 * s_pi)); const double c2 = 2.0 * pow(sigma, 2.0); //Compute weights for(uint32_t i = 0; i < m_filterSize; i++) { const int32_t x = int32_t(i) - int32_t(offset); m_weights[i] = c1 * exp(-(pow(x, 2.0) / c2)); totalWeight += m_weights[i]; } //Adjust weights const double adjust = 1.0 / totalWeight; for(uint32_t i = 0; i < m_filterSize; i++) { m_weights[i] *= adjust; //LOG_WRN(TXT("Gauss Weight %02u = %.4f"), i, m_weights[i]); } } DYNAUDNORM_NS::GaussianFilter::~GaussianFilter(void) { MY_DELETE_ARRAY(m_weights); } /////////////////////////////////////////////////////////////////////////////// // Apply Filter /////////////////////////////////////////////////////////////////////////////// double DYNAUDNORM_NS::GaussianFilter::apply(const std::deque &values) { if(values.size() != m_filterSize) { throw std::runtime_error("Input data has the wrong size!"); } uint32_t w = 0; double result = 0.0; //Apply Gaussian filter for(std::deque::const_iterator iter = values.begin(); iter != values.end(); iter++) { result += (*iter) * m_weights[w++]; } return result; } ================================================ FILE: DynamicAudioNormalizerAPI/src/GaussianFilter.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #include "Common.h" #include #include #include namespace DYNAUDNORM_NS { class GaussianFilter { public: GaussianFilter(const uint32_t &filterSize, const double &sigma); virtual ~GaussianFilter(void); double apply(const std::deque &values); private: const uint32_t m_filterSize; double *m_weights; GaussianFilter &operator=(const GaussianFilter &) { throw 666; } }; } ================================================ FILE: DynamicAudioNormalizerAPI/src/Logging.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "Logging.h" #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif //Internal #include //Stdlib #include #include #include //Globals static MY_CRITSEC_INIT(g_mutex); static DYNAUDNORM_NS::LoggingCallback *g_loggingCallback = NULL; static char g_messageBuffer[1024]; /////////////////////////////////////////////////////////////////////////////// // Logging Functions /////////////////////////////////////////////////////////////////////////////// DYNAUDNORM_NS::LoggingCallback *DYNAUDNORM_NS::setLoggingHandler(LoggingCallback *const callback) { LoggingCallback *oldValue; MY_CRITSEC_ENTER(g_mutex); oldValue = g_loggingCallback; g_loggingCallback = callback; MY_CRITSEC_LEAVE(g_mutex); return oldValue; } void DYNAUDNORM_NS::postLogMessage(const int &logLevel, const char *const message, ...) { MY_CRITSEC_ENTER(g_mutex); if(g_loggingCallback) { va_list args; va_start (args, message); vsnprintf(g_messageBuffer, 1024, message, args); va_end(args); g_loggingCallback(logLevel, g_messageBuffer); } MY_CRITSEC_LEAVE(g_mutex); } ================================================ FILE: DynamicAudioNormalizerAPI/src/Logging.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #include "Common.h" namespace DYNAUDNORM_NS { typedef void (LoggingCallback)(const int logLevel, const char *const message); LoggingCallback *setLoggingHandler(LoggingCallback *const callback); void postLogMessage(const int &logLevel, const char *const message, ...); } #define LOG1_DBG(X) DYNAUDNORM_NS::postLogMessage(0, (X)) #define LOG1_WRN(X) DYNAUDNORM_NS::postLogMessage(1, (X)) #define LOG1_ERR(X) DYNAUDNORM_NS::postLogMessage(2, (X)) #define LOG2_DBG(X,...) DYNAUDNORM_NS::postLogMessage(0, (X), __VA_ARGS__) #define LOG2_WRN(X,...) DYNAUDNORM_NS::postLogMessage(1, (X), __VA_ARGS__) #define LOG2_ERR(X,...) DYNAUDNORM_NS::postLogMessage(2, (X), __VA_ARGS__) ================================================ FILE: DynamicAudioNormalizerAPI/src/Test_API.c ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "DynamicAudioNormalizer.h" void MDynamicAudioNormalizer_Test_C_API(void) { MDynamicAudioNormalizer_Handle *handle = MDYNAMICAUDIONORMALIZER_FUNCTION(createInstance)(2, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, 1, 0, 0, NULL); if (handle) { uint32_t channels, sampleRate, frameLen, filterSize; MDYNAMICAUDIONORMALIZER_FUNCTION(getConfiguration)(handle, &channels, &sampleRate, &frameLen, &filterSize); MDYNAMICAUDIONORMALIZER_FUNCTION(destroyInstance)(&handle); } } ================================================ FILE: DynamicAudioNormalizerAPI/src/Version.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "Version.h" #define INC_DYNAUDNORM_VERSION_INTERNAL 0x22b4f8a9 #include "../../DynamicAudioNormalizerShared/res/version.inc" //Version info const unsigned int DYNAUDNORM_NS::VERSION_MAJOR = VER_DYNAUDNORM_MAJOR; const unsigned int DYNAUDNORM_NS::VERSION_MINOR = VER_DYNAUDNORM_MINOR; const unsigned int DYNAUDNORM_NS::VERSION_PATCH = VER_DYNAUDNORM_PATCH; //Build date/time const char *const DYNAUDNORM_NS::BUILD_DATE = __DATE__; const char *const DYNAUDNORM_NS::BUILD_TIME = __TIME__; //Compiler detection const char *const DYNAUDNORM_NS::BUILD_COMPILER = #if defined(__INTEL_COMPILER) #if (__INTEL_COMPILER >= 1600) "ICL 16.x"; #elif (__INTEL_COMPILER >= 1500) "ICL 15.x"; #elif (__INTEL_COMPILER >= 1400) "ICL 14.x"; #elif (__INTEL_COMPILER >= 1300) "ICL 13.x"; #elif (__INTEL_COMPILER >= 1200) "ICL 12.x"; #elif (__INTEL_COMPILER >= 1100) "ICL 11.x"; #elif (__INTEL_COMPILER >= 1000) "ICL 10.x"; #else #error Compiler is not supported! #endif #elif defined(_MSC_VER) #if (_MSC_VER == 1916) #if((_MSC_FULL_VER >= 191627024) && (_MSC_FULL_VER <= 191627034)) "MSVC 2017.9"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1915) #if((_MSC_FULL_VER >= 191526726) && (_MSC_FULL_VER <= 191526732)) "MSVC 2017.8"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1914) #if((_MSC_FULL_VER >= 191426430) && (_MSC_FULL_VER <= 191426433)) "MSVC 2017.7"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1913) #if((_MSC_FULL_VER >= 191326128) && (_MSC_FULL_VER <= 191326132)) "MSVC 2017.6"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1912) #if((_MSC_FULL_VER >= 191225830) && (_MSC_FULL_VER <= 191225835)) "MSVC 2017.5"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1911) #if((_MSC_FULL_VER >= 191125542) && (_MSC_FULL_VER <= 191125547)) "MSVC 2017.4"; #elif((_MSC_FULL_VER >= 191125506) && (_MSC_FULL_VER <= 191125508)) "MSVC 2017.3"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1910) #if (_MSC_FULL_VER >= 191025017) && (_MSC_FULL_VER <= 191025019) "MSVC 2017.2"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1900) #if (_MSC_FULL_VER == 190023026) "MSVC 2015"; #elif (_MSC_FULL_VER == 190023506) "MSVC 2015.1"; #elif (_MSC_FULL_VER == 190023918) "MSVC 2015.2"; #elif (_MSC_FULL_VER >= 190024210) && (_MSC_FULL_VER <= 190024215) "MSVC 2015.3"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1800) #if (_MSC_FULL_VER == 180021005) "MSVC 2013"; #elif (_MSC_FULL_VER == 180030501) "MSVC 2013.2"; #elif (_MSC_FULL_VER == 180030723) "MSVC 2013.3"; #elif (_MSC_FULL_VER == 180031101) "MSVC 2013.4"; #elif (_MSC_FULL_VER == 180040629) "MSVC 2013.5"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1700) #if (_MSC_FULL_VER == 170050727) "MSVC 2012"; #elif (_MSC_FULL_VER == 170051106) "MSVC 2012.1"; #elif (_MSC_FULL_VER == 170060315) "MSVC 2012.2"; #elif (_MSC_FULL_VER == 170060610) "MSVC 2012.3"; #elif (_MSC_FULL_VER == 170061030) "MSVC 2012.4"; #else #error Compiler version is not supported yet! #endif #elif (_MSC_VER == 1600) #if (_MSC_FULL_VER >= 160040219) "MSVC 2010-SP1"; #else "MSVC 2010"; #endif #elif (_MSC_VER == 1500) #if (_MSC_FULL_VER >= 150030729) "MSVC 2008-SP1"; #else "MSVC 2008"; #endif #else #error Compiler is not supported! #endif // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform #if !defined(_M_X64) && defined(_M_IX86_FP) #if (_M_IX86_FP == 1) #pragma message("SSE instruction set is enabled!") #elif (_M_IX86_FP >= 2) #pragma message("SSE2 (or higher) instruction set is enabled!") #endif #endif #elif defined(__GNUC__) #define GCC_VERSION_GLUE1(X,Y,Z) "GCC " #X "." #Y "." #Z #define GCC_VERSION_GLUE2(X,Y,Z) GCC_VERSION_GLUE1(X,Y,Z) GCC_VERSION_GLUE2(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); #else #error Compiler is not supported! #endif //Architecture detection const char *const DYNAUDNORM_NS::BUILD_ARCH = #if defined(_M_X64) || defined(__x86_64__) "x64"; #elif defined(_M_IX86) || defined(__i386__) "x86"; #else #error Architecture is not supported! #endif ================================================ FILE: DynamicAudioNormalizerAPI/src/Version.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #include "Common.h" //============================================================================= // Version //============================================================================= namespace DYNAUDNORM_NS { //Version info extern const unsigned int VERSION_MAJOR; extern const unsigned int VERSION_MINOR; extern const unsigned int VERSION_PATCH; //Build date/time extern const char *const BUILD_DATE; extern const char *const BUILD_TIME; //Compiler info extern const char *const BUILD_COMPILER; extern const char *const BUILD_ARCH; } ================================================ FILE: DynamicAudioNormalizerCLI/DynamicAudioNormalizerCLI_VS2013.vcxproj ================================================  Debug Win32 Release_DLL Win32 Release_Static Win32 {376386ee-8268-47e3-a335-7663716e4c60} true true false true false {5B755CC3-EC17-490F-AE82-CBC16E2EB143} Win32Proj DynamicAudioNormalizerCLI DynamicAudioNormalizerCLI Application true v120_xp Unicode Application false v120_xp true Unicode Application false v120_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ Level3 Disabled WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include;$(SolutionDir)\..\Prerequisites\LibSndFile\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(SolutionDir)\..\Prerequisites\LibMpg123\include;%(AdditionalIncludeDirectories) NoExtensions Disabled false MultiThreadedDebugDLL Sync ProgramDatabase Console true $(SolutionDir)\..\Prerequisites\LibSndFile\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\LibMpg123\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) libsndfile-1.lib;libmpg123.$(PlatformToolset).lib;%(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include;$(SolutionDir)\..\Prerequisites\LibSndFile\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(SolutionDir)\..\Prerequisites\LibMpg123\include;%(AdditionalIncludeDirectories) StreamingSIMDExtensions2 MultiThreadedDLL AnySuitable Speed true false Fast true Console false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\LibSndFile\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\LibMpg123\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\VisualLeaksDetector\lib\$(Platform);%(AdditionalLibraryDirectories) libsndfile-1.lib;libmpg123.$(PlatformToolset).lib;%(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include;$(SolutionDir)\..\Prerequisites\LibSndFile\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(SolutionDir)\..\Prerequisites\LibMpg123\include;%(AdditionalIncludeDirectories) StreamingSIMDExtensions2 MultiThreaded AnySuitable Speed true false Fast true Console false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\Win32\static;$(SolutionDir)\..\Prerequisites\LibSndFile\lib\$(Platform)\static;$(SolutionDir)\..\Prerequisites\VisualLeaksDetector\lib\$(Platform);$(SolutionDir)\..\Prerequisites\XiphAudioLibs\lib\$(Platform)\static;$(SolutionDir)\..\Prerequisites\LibMpg123\lib\Win32\static;%(AdditionalLibraryDirectories) libsndfile_msvc.$(PlatformToolset).lib;libogg_static.$(PlatformToolset).lib;libvorbis_static.$(PlatformToolset).lib;libFLAC_static.$(PlatformToolset).lib;libmpg123.$(PlatformToolset).lib;shlwapi.lib;%(AdditionalDependencies) LinkVerboseLib ================================================ FILE: DynamicAudioNormalizerCLI/DynamicAudioNormalizerCLI_VS2013.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files Source Files Source Files Source Files Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files ================================================ FILE: DynamicAudioNormalizerCLI/DynamicAudioNormalizerCLI_VS2015.vcxproj ================================================  Debug Win32 Release_DLL Win32 Release_Static Win32 {376386ee-8268-47e3-a335-7663716e4c60} true true false true false {5B755CC3-EC17-490F-AE82-CBC16E2EB143} Win32Proj DynamicAudioNormalizerCLI DynamicAudioNormalizerCLI Application true v140_xp Unicode Application false v140_xp true Unicode Application false v140_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ Level3 Disabled WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include;$(SolutionDir)\..\Prerequisites\LibSndFile\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(SolutionDir)\..\Prerequisites\LibMpg123\include;%(AdditionalIncludeDirectories) NoExtensions Disabled false MultiThreadedDebugDLL Sync ProgramDatabase Console true $(SolutionDir)\..\Prerequisites\LibSndFile\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\LibMpg123\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) libsndfile-1.lib;libmpg123.$(PlatformToolset).lib;%(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include;$(SolutionDir)\..\Prerequisites\LibSndFile\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(SolutionDir)\..\Prerequisites\LibMpg123\include;%(AdditionalIncludeDirectories) StreamingSIMDExtensions2 MultiThreadedDLL AnySuitable Speed true false Fast true Console false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\LibSndFile\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\LibMpg123\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\VisualLeaksDetector\lib\$(Platform);%(AdditionalLibraryDirectories) libsndfile-1.lib;libmpg123.$(PlatformToolset).lib;%(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include;$(SolutionDir)\..\Prerequisites\LibSndFile\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(SolutionDir)\..\Prerequisites\LibMpg123\include;%(AdditionalIncludeDirectories) StreamingSIMDExtensions2 MultiThreaded AnySuitable Speed true false Fast true Console false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\Win32\static;$(SolutionDir)\..\Prerequisites\LibSndFile\lib\$(Platform)\static;$(SolutionDir)\..\Prerequisites\VisualLeaksDetector\lib\$(Platform);$(SolutionDir)\..\Prerequisites\XiphAudioLibs\lib\$(Platform)\static;$(SolutionDir)\..\Prerequisites\LibMpg123\lib\Win32\static;%(AdditionalLibraryDirectories) libsndfile_msvc.$(PlatformToolset).lib;libogg_static.$(PlatformToolset).lib;libvorbis_static.$(PlatformToolset).lib;libFLAC_static.$(PlatformToolset).lib;libmpg123.$(PlatformToolset).lib;shlwapi.lib;%(AdditionalDependencies) LinkVerboseLib ================================================ FILE: DynamicAudioNormalizerCLI/DynamicAudioNormalizerCLI_VS2015.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files Source Files Source Files Source Files Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files ================================================ FILE: DynamicAudioNormalizerCLI/DynamicAudioNormalizerCLI_VS2017.vcxproj ================================================  Debug Win32 Release_DLL Win32 Release_Static Win32 {376386ee-8268-47e3-a335-7663716e4c60} true true false true false {5B755CC3-EC17-490F-AE82-CBC16E2EB143} Win32Proj DynamicAudioNormalizerCLI DynamicAudioNormalizerCLI 8.1 Application true v141_xp Unicode Application false v141_xp true Unicode Application false v141_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ Level3 Disabled WIN32;_DEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include;$(SolutionDir)\..\Prerequisites\LibSndFile\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(SolutionDir)\..\Prerequisites\LibMpg123\include;$(SolutionDir)\..\Prerequisites\XiphAudioLibs\include;%(AdditionalIncludeDirectories) NoExtensions Disabled false MultiThreadedDebugDLL Sync ProgramDatabase Console true $(SolutionDir)\..\Prerequisites\LibSndFile\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\LibMpg123\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\XiphAudioLibs\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\lib\$(Platform);%(AdditionalLibraryDirectories) libsndfile-1.lib;libmpg123.$(PlatformToolset).lib;libopus.$(PlatformToolset).lib;libopusfile.$(PlatformToolset).lib;%(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include;$(SolutionDir)\..\Prerequisites\LibSndFile\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(SolutionDir)\..\Prerequisites\LibMpg123\include;$(SolutionDir)\..\Prerequisites\XiphAudioLibs\include;%(AdditionalIncludeDirectories) StreamingSIMDExtensions2 MultiThreadedDLL AnySuitable Speed true false Fast true Console false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\LibSndFile\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\LibMpg123\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\XiphAudioLibs\lib\$(Platform)\shared;$(SolutionDir)\..\Prerequisites\VisualLeaksDetector\lib\$(Platform);%(AdditionalLibraryDirectories) libsndfile-1.lib;libmpg123.$(PlatformToolset).lib;libopus.$(PlatformToolset).lib;libopusfile.$(PlatformToolset).lib;%(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include;$(SolutionDir)\..\Prerequisites\LibSndFile\include;$(SolutionDir)\..\Prerequisites\VisualLeakDetector\include;$(SolutionDir)\..\Prerequisites\LibMpg123\include;$(SolutionDir)\..\Prerequisites\XiphAudioLibs\include;%(AdditionalIncludeDirectories) StreamingSIMDExtensions2 MultiThreaded AnySuitable Speed true false Fast true Console false true true $(SolutionDir)\..\Prerequisites\EncodePointer\lib;$(SolutionDir)\..\Prerequisites\PthreadsW32\lib\Win32\static;$(SolutionDir)\..\Prerequisites\LibSndFile\lib\$(Platform)\static;$(SolutionDir)\..\Prerequisites\VisualLeaksDetector\lib\$(Platform);$(SolutionDir)\..\Prerequisites\XiphAudioLibs\lib\$(Platform)\static;$(SolutionDir)\..\Prerequisites\LibMpg123\lib\Win32\static;%(AdditionalLibraryDirectories) EncodePointer.lib;libsndfile_msvc.$(PlatformToolset).lib;libogg_static.$(PlatformToolset).lib;libvorbis_static.$(PlatformToolset).lib;libFLAC_static.$(PlatformToolset).lib;libmpg123.$(PlatformToolset).lib;libopus_static.$(PlatformToolset).lib;libopusfile_static.$(PlatformToolset).lib;shlwapi.lib;%(AdditionalDependencies) LinkVerboseLib false $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) ================================================ FILE: DynamicAudioNormalizerCLI/DynamicAudioNormalizerCLI_VS2017.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {bd2e7d56-31ce-46cc-88f9-34740968028e} Source Files Source Files Source Files Source Files Source Files Source Files Source Files Source Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files Header Files\3rd Party Sources Resource Files ================================================ FILE: DynamicAudioNormalizerCLI/makefile ================================================ ############################################################################## # Dynamic Audio Normalizer - Audio Processing Utility # Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # http://www.gnu.org/licenses/gpl-2.0.txt ############################################################################## ECHO=echo -e SHELL=/bin/bash ############################################################################## # Constants ############################################################################## PROGRAM_NAME := DynamicAudioNormalizerCLI ifndef API_VERSION $(error API_VERSION variable is not set!) endif ############################################################################## # Flags ############################################################################## DEBUG_BUILD ?= 0 MARCH ?= native ifeq ($(DEBUG_BUILD), 1) CONFIG_NAME = Debug CXXFLAGS = -g -O0 -D_DEBUG else CONFIG_NAME = Release CXXFLAGS = -O3 -Wall -ffast-math -mfpmath=sse -msse -fomit-frame-pointer -fno-tree-vectorize -DNDEBUG -march=$(MARCH) endif CXXFLAGS += -std=gnu++11 CXXFLAGS += -I./src CXXFLAGS += -I./include CXXFLAGS += -I../DynamicAudioNormalizerAPI/include CXXFLAGS += -I../DynamicAudioNormalizerShared/include ifeq ($(findstring MINGW,$(shell uname -s)),MINGW) CXXFLAGS += -I../../libsndfile/include LDXFLAGS += -L../../libsndfile/lib else LDXFLAGS += -Wl,-rpath,'$$ORIGIN' endif LDXFLAGS += -L../DynamicAudioNormalizerAPI/lib LDXFLAGS += -lDynamicAudioNormalizerAPI-$(API_VERSION) #Externel libraries LDXFLAGS += -lsndfile -lmpg123 ############################################################################## # File Names ############################################################################## ifeq ($(findstring MINGW,$(shell uname -s)),MINGW) PRG_EXT = exe else PRG_EXT = bin endif SOURCES_CPP = $(wildcard src/*.cpp) SOURCES_OBJ = $(patsubst %.cpp,%.o,$(SOURCES_CPP)) PROGRAM_OUT = bin/$(PROGRAM_NAME) PROGRAM_BIN = $(PROGRAM_OUT).$(PRG_EXT) PROGRAM_DBG = $(PROGRAM_OUT)-DBG.$(PRG_EXT) ############################################################################## # Rules ############################################################################## .PHONY: all clean all: $(PROGRAM_BIN) #------------------------------------------------------------- # Link & Strip #------------------------------------------------------------- $(PROGRAM_BIN): $(PROGRAM_DBG) @$(ECHO) "\e[1;36m[STR] $@\e[0m" @mkdir -p $(dir $@) ifeq ($(shell uname), Darwin) strip -u -r -x -o $@ $< else strip --strip-unneeded -o $@ $< endif $(PROGRAM_DBG): $(SOURCES_OBJ) @$(ECHO) "\e[1;36m[LNK] $@\e[0m" @mkdir -p $(dir $@) g++ -o $@ $+ $(LDXFLAGS) #------------------------------------------------------------- # Compile #------------------------------------------------------------- %.o: %.cpp @$(ECHO) "\e[1;36m[CXX] $<\e[0m" @mkdir -p $(dir $@) g++ $(CXXFLAGS) -c $< -o $@ #------------------------------------------------------------- # Clean #------------------------------------------------------------- clean: rm -fv $(SOURCES_OBJ) rm -rfv ./bin ================================================ FILE: DynamicAudioNormalizerCLI/res/DynamicAudioNormalizerCLI.rc ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "WinResrc.h" //"afxres.h" #define INC_DYNAUDNORM_VERSION_INTERNAL 0x22b4f8a9 #include "../DynamicAudioNormalizerShared/res/version.inc" ////////////////////////////////////////////////////////////////////////////////// // Neutral resources ////////////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) #ifdef _WIN32 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL #pragma code_page(1252) #endif //_WIN32 ////////////////////////////////////////////////////////////////////////////////// // Version ////////////////////////////////////////////////////////////////////////////////// VS_VERSION_INFO VERSIONINFO FILEVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH PRODUCTVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x3L #else FILEFLAGS 0x2L #endif FILEOS 0x40004L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ." VALUE "CompanyName", "LoRd_MuldeR " VALUE "FileDescription", "DynamicAudioNormalizer Command-Line Interface" VALUE "FileVersion", VER_DYNAUDNORM_STR VALUE "InternalName", "DynamicAudioNormalizerCLI" VALUE "LegalCopyright", "Copyright (c) 2014-2019 LoRd_MuldeR " VALUE "LegalTrademarks", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License " VALUE "OriginalFilename", "DynamicAudioNormalizerCLI.exe" VALUE "ProductName", "DynamicAudioNormalizer" VALUE "ProductVersion", VER_DYNAUDNORM_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // Neutral resources ================================================ FILE: DynamicAudioNormalizerCLI/src/3rd_party/memmem.h ================================================ /* * Copyright (C) 2008 The Android Open Source Project * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * This uses the "Not So Naive" algorithm, a very simple but * usually effective algorithm, see: * http://www-igm.univ-mlv.fr/~lecroq/string/ */ #include #ifdef __GNUC__ #define _EXPECT(X,Y) __builtin_expect((X),(Y)) #else #define _EXPECT(X,Y) (X) #endif static const void *memmem(const void *haystack, size_t n, const void *needle, size_t m) { if ((m > n) || (!m) || (!n)) { return NULL; } if (_EXPECT((m > 1), 1)) { const unsigned char* y = (const unsigned char*)haystack; const unsigned char* x = (const unsigned char*)needle; size_t j = 0; size_t k = 1, l = 2; if (x[0] == x[1]) { k = 2; l = 1; } while (j <= (n - m)) { if (x[1] != y[j + 1]) { j += k; } else { if (!memcmp(x + 2, y + j + 2, m - 2) && (x[0] == y[j])) { return (void*)&y[j]; } j += l; } } } else { /* degenerate case */ return memchr(haystack, ((unsigned char*)needle)[0], n); } return NULL; } ================================================ FILE: DynamicAudioNormalizerCLI/src/AudioIO.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #include "AudioIO.h" #include "AudioIO_SndFile.h" #include "AudioIO_Mpg123.h" #include "AudioIO_OpusFile.h" #include #include #ifdef __unix #include #else #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif /////////////////////////////////////////////////////////////////////////////// // Helper Functions /////////////////////////////////////////////////////////////////////////////// //AudioIO libraries static const uint8_t AUDIO_LIB_NULL = 0x00u; static const uint8_t AUDIO_LIB_LIBSNDFILE = 0x01u; static const uint8_t AUDIO_LIB_LIBOPUSFILE = 0x02u; static const uint8_t AUDIO_LIB_LIBMPG123 = 0x03u; //Function prototypes typedef const CHR * (libraryVersion_t) (void); typedef const CHR *const *(supportedFormats_t)(const CHR **const list, const uint32_t maxLen); typedef bool (checkFileType_t) (FILE *const); typedef AudioIO* (createInstance_t) (void); //AudioIO library mappings static const struct { const CHR name[16]; const uint8_t id; libraryVersion_t *const libraryVersion; supportedFormats_t *const supportedFormats; checkFileType_t *const checkFileType; createInstance_t *const createInstance; } g_audioIO_mapping[] = { { TXT("libsndfile"), AUDIO_LIB_LIBSNDFILE, AudioIO_SndFile ::libraryVersion, AudioIO_SndFile ::supportedFormats, AudioIO_SndFile ::checkFileType, AudioIO_SndFile ::createInstance }, { TXT("libopusfile"), AUDIO_LIB_LIBOPUSFILE, AudioIO_OpusFile::libraryVersion, AudioIO_OpusFile::supportedFormats, AudioIO_OpusFile::checkFileType, AudioIO_OpusFile::createInstance }, { TXT("libmpg123"), AUDIO_LIB_LIBMPG123, AudioIO_Mpg123 ::libraryVersion, AudioIO_Mpg123 ::supportedFormats, AudioIO_Mpg123 ::checkFileType, AudioIO_Mpg123 ::createInstance }, { TXT(""), AUDIO_LIB_NULL, NULL, NULL, NULL, NULL } }; //Get id from AudioIO library name static uint8_t parseName(const CHR *const name) { if (name && name[0]) { for (size_t i = 0; g_audioIO_mapping[i].id; ++i) { if (STRCASECMP(name, g_audioIO_mapping[i].name) == 0) { return g_audioIO_mapping[i].id; } } return AUDIO_LIB_NULL; } else { return AUDIO_LIB_LIBSNDFILE; /*default*/ } } //Get id from AudioIO library name static const CHR* getLibName(const uint8_t id) { for (size_t i = 0; g_audioIO_mapping[i].id; ++i) { if (g_audioIO_mapping[i].id == id) { return g_audioIO_mapping[i].name; } } return NULL; } //Check file type static bool checkFileType(bool(*const check)(FILE *const), FILE *const file) { const bool check_result = check(file); rewind(file); return check_result; } /////////////////////////////////////////////////////////////////////////////// // AudioIO Factory /////////////////////////////////////////////////////////////////////////////// const CHR *const *AudioIO::getSupportedLibraries(const CHR **const list, const uint32_t maxLen) { if (list && (maxLen > 0)) { uint32_t nextPos = 0; for (size_t i = 0; g_audioIO_mapping[i].id; ++i) { if (g_audioIO_mapping[i].name[0] && (nextPos < maxLen)) { list[nextPos++] = &g_audioIO_mapping[i].name[0]; } } list[(nextPos < maxLen) ? nextPos : (maxLen - 1)] = NULL; } return list; } AudioIO *AudioIO::createInstance(const CHR *const name) { const uint8_t id = parseName(name); for (size_t i = 0; g_audioIO_mapping[i].id; ++i) { if (g_audioIO_mapping[i].id == id) { return g_audioIO_mapping[i].createInstance(); } } throw "Unsupported audio I/O library!"; } const CHR *const *AudioIO::getSupportedFormats(const CHR **const list, const uint32_t maxLen, const CHR *const name) { const uint8_t id = parseName(name); for (size_t i = 0; g_audioIO_mapping[i].id; ++i) { if (g_audioIO_mapping[i].id == id) { return g_audioIO_mapping[i].supportedFormats(list, maxLen); } } throw "Unsupported audio I/O library!"; } const CHR *AudioIO::getLibraryVersion(const CHR *const name) { const uint8_t id = parseName(name); for (size_t i = 0; g_audioIO_mapping[i].id; ++i) { if (g_audioIO_mapping[i].id == id) { return g_audioIO_mapping[i].libraryVersion(); } } throw "Unsupported audio I/O library!"; } const CHR *AudioIO::detectSourceType(const CHR *const fileName, const bool verbose) { if (verbose) { PRINT_NFO(TXT("------- Audio I/O -------")); } uint8_t type = AUDIO_LIB_NULL; const bool bStdIn = (STRCASECMP(fileName, TXT("-")) == 0); if (bStdIn || PATH_ISREG(fileName)) { if (FILE *const file = bStdIn ? stdin : FOPEN(fileName, TXT("rb"))) { if (FD_ISREG(FILENO(file))) { for (size_t i = 0; g_audioIO_mapping[i].id; ++i) { if (verbose) { PRINT2_NFO(TXT("Trying input module ") FMT_CHR TXT("..."), g_audioIO_mapping[i].name); } if (checkFileType(g_audioIO_mapping[i].checkFileType, file)) { type = g_audioIO_mapping[i].id; if (verbose) { PRINT_NFO(TXT("succeeded.")); } break; } } } if (!bStdIn) { fclose(file); } } } if (verbose) { if(type == AUDIO_LIB_NULL) { PRINT_NFO(TXT("No suitable input module found -> falling back to default!")); } PRINT_NFO(TXT("------- Audio I/O -------\n")); } return getLibName(type); } ================================================ FILE: DynamicAudioNormalizerCLI/src/AudioIO.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #include #include "Platform.h" /////////////////////////////////////////////////////////////////////////////// // AudioIO Interface /////////////////////////////////////////////////////////////////////////////// class AudioIO { public: AudioIO(void) {}; virtual ~AudioIO(void) {} //Functions implemented in derived classes virtual bool openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth) = 0; virtual bool openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format = NULL) = 0; virtual int64_t read(double **buffer, const int64_t count) = 0; virtual int64_t write(double *const *buffer, const int64_t count) = 0; virtual bool close(void) = 0; virtual bool queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth) = 0; virtual void getFormatInfo(CHR *buffer, const uint32_t buffSize) = 0; //Static "factory" functions static const CHR *const *getSupportedLibraries(const CHR **const list, const uint32_t maxLen); static AudioIO *createInstance(const CHR *const name = NULL); static const CHR *const *getSupportedFormats(const CHR **const list, const uint32_t maxLen, const CHR *const name = NULL); static const CHR *getLibraryVersion(const CHR *const name = NULL); //File type auto-detection static const CHR *detectSourceType(const CHR *const fileName = NULL, const bool verbose = false); private: AudioIO(const AudioIO &) { throw 666; } AudioIO &operator=(const AudioIO &) { throw 666; } }; ================================================ FILE: DynamicAudioNormalizerCLI/src/AudioIO_Mpg123.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #define __STDC_LIMIT_MACROS #include "AudioIO_Mpg123.h" #include #include #ifdef _WIN32 #include #define MPG123OPEN(X,Y) mpg123_topen((X),(Y)) #define MPG123CLOSE(X) mpg123_tclose((X)) #else #include #define MPG123OPEN(X,Y) mpg123_open((X),(Y)) #define MPG123CLOSE(X) mpg123_close((X)) #endif #include #include #ifdef __unix #include #else #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif #define MPG123_DELETE(X) do \ { \ if((X)) \ { \ mpg123_delete((X)); \ (X) = NULL; \ } \ } \ while(0) #define MY_THROW(X) throw std::runtime_error((X)) /////////////////////////////////////////////////////////////////////////////// // Const /////////////////////////////////////////////////////////////////////////////// static const size_t MPG123_HDR_SIZE = 4U; static const uint32_t MPG123_SRATE[2][4] = { { 22050, 24000, 16000, 0 }, /*V2*/ { 44100, 48000, 32000, 0 } /*V1*/ }; static const uint32_t MPG123_BITRT[2][4][16] = { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /*V2*/ { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0 }, /*L3*/ { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0 }, /*L2*/ { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0 }, /*L1*/ }, { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, /*V1*/ { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0 }, /*L3*/ { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0 }, /*L2*/ { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0 }, /*L1*/ } }; static const uint32_t MPG123_FSIZE[2][4] = { { 0, 72, 144, 48 }, /*V2*/ { 0, 144, 144, 48 } /*V1*/ }; /////////////////////////////////////////////////////////////////////////////// // FMT123.H COMPAT /////////////////////////////////////////////////////////////////////////////// #ifndef MPG123_ENC_H #define MPG123_SAMPLESIZE(enc) ((enc) & MPG123_ENC_8 ? 1 : ((enc) & \ MPG123_ENC_16 ? 2 : ((enc) & MPG123_ENC_24 ? 3 : (((enc) & MPG123_ENC_32 || \ (enc) == MPG123_ENC_FLOAT_32) ? 4 : ((enc) == MPG123_ENC_FLOAT_64 ? 8 : 0))))) struct mpg123_fmt { long rate; int channels; int encoding; }; #endif //MPG123_ENC_H /////////////////////////////////////////////////////////////////////////////// // Private Data /////////////////////////////////////////////////////////////////////////////// class AudioIO_Mpg123_Private { public: AudioIO_Mpg123_Private(void); ~AudioIO_Mpg123_Private(void); //Open and Close bool openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth); bool openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format); bool close(void); //Read and Write int64_t read(double **buffer, const int64_t count); int64_t write(double *const *buffer, const int64_t count); //Query info bool queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth); void getFormatInfo(CHR *buffer, const uint32_t buffSize); //Library info static const CHR *libraryVersion(void); static const CHR *const *supportedFormats(const CHR **const list, const uint32_t maxLen); static bool checkFileType(FILE *const); private: //libmpg123 mpg123_handle *handle; //audio format info struct mpg123_fmt format; //(De)Interleaving buffer uint8_t *tempBuff; size_t frameSize, buffSize; //Library info static MY_CRITSEC_DECL(mutex_lock); static CHR versionBuffer[256]; static uint32_t instanceCounter; //Helper functions static uint32_t checkMpg123Sequence(const uint8_t *const buffer, const size_t &count, uint32_t &max_sequence); static bool checkMpg123SyncWord(const uint8_t *const buffer, const size_t &fpos); template static void deinterleave(double **destination, const int64_t offset, const T *const source, const int &channels, const int64_t &len); static void libraryInit(void); static void libraryExit(void); }; /////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor /////////////////////////////////////////////////////////////////////////////// AudioIO_Mpg123::AudioIO_Mpg123(void) : p(new AudioIO_Mpg123_Private()) { } AudioIO_Mpg123::~AudioIO_Mpg123(void) { delete p; } AudioIO_Mpg123_Private::AudioIO_Mpg123_Private(void) { libraryInit(); tempBuff = NULL; handle = NULL; frameSize = 0; buffSize = 0; memset(&format, 0, sizeof(struct mpg123_fmt)); } AudioIO_Mpg123_Private::~AudioIO_Mpg123_Private(void) { close(); libraryExit(); } /////////////////////////////////////////////////////////////////////////////// // Public API /////////////////////////////////////////////////////////////////////////////// bool AudioIO_Mpg123::openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth) { return p->openRd(fileName, channels, sampleRate, bitDepth); } bool AudioIO_Mpg123::openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format) { return p->openWr(fileName, channels, sampleRate, bitDepth, format); } bool AudioIO_Mpg123::close(void) { return p->close(); } int64_t AudioIO_Mpg123::read(double **buffer, const int64_t count) { return p->read(buffer, count); } int64_t AudioIO_Mpg123::write(double *const *buffer, const int64_t count) { return p->write(buffer, count); } bool AudioIO_Mpg123::queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth) { return p->queryInfo(channels, sampleRate, length, bitDepth); } void AudioIO_Mpg123::getFormatInfo(CHR *buffer, const uint32_t buffSize) { p->getFormatInfo(buffer, buffSize); } const CHR *AudioIO_Mpg123::libraryVersion(void) { return AudioIO_Mpg123_Private::libraryVersion(); } const CHR *const *AudioIO_Mpg123::supportedFormats(const CHR **const list, const uint32_t maxLen) { return AudioIO_Mpg123_Private::supportedFormats(list, maxLen); } bool AudioIO_Mpg123::checkFileType(FILE *const file) { return AudioIO_Mpg123_Private::checkFileType(file); } /////////////////////////////////////////////////////////////////////////////// // Internal Functions /////////////////////////////////////////////////////////////////////////////// bool AudioIO_Mpg123_Private::openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth) { if (handle) { PRINT_ERR(TXT("Sound file is already open!\n")); return false; } //Create libmpg123 handle int error = 0; if (!(handle = mpg123_new(NULL, &error))) { PRINT2_ERR(TXT("Failed to create libmpg123 handle:\n") FMT_chr TXT("\n"), mpg123_plain_strerror(error)); return false; } //Initialize the libmpg123 flags long flags; double fflags; if (mpg123_getparam(handle, MPG123_FLAGS, &flags, &fflags) == MPG123_OK) { flags |= MPG123_FORCE_FLOAT; flags |= MPG123_QUIET; if (mpg123_param(handle, MPG123_FLAGS, flags, fflags) != MPG123_OK) { PRINT2_ERR(TXT("Failed to set up libmpg123 flags: \"") FMT_chr TXT("\"\n"), mpg123_strerror(handle)); MPG123_DELETE(handle); return false; } } else { PRINT2_ERR(TXT("Failed to query libmpg123 flags: \"") FMT_chr TXT("\"\n"), mpg123_strerror(handle)); MPG123_DELETE(handle); return false; } //Use pipe? const bool bStdIn = (STRCASECMP(fileName, TXT("-")) == 0); //Open file in libmpg123 if ((bStdIn ? mpg123_open_fd(handle, STDIN_FILENO) : MPG123OPEN(handle, fileName)) != MPG123_OK) { PRINT2_ERR(TXT("Failed to open file for reading: \"") FMT_chr TXT("\"\n"), mpg123_strerror(handle)); MPG123_DELETE(handle); return false; } //Detect format info if (mpg123_getformat(handle, &format.rate, &format.channels, &format.encoding) != MPG123_OK) { PRINT2_ERR(TXT("Failed to get format info from audio file:\n") FMT_chr TXT("\n"), mpg123_strerror(handle)); close(); return false; } //Ensure that this output format will not change if ((mpg123_format_none(handle) != MPG123_OK) || (mpg123_format(handle, format.rate, format.channels, format.encoding) != MPG123_OK)) { PRINT2_ERR(TXT("Failed to set up output format:\n") FMT_chr TXT("\n"), mpg123_strerror(handle)); close(); return false; } //Query output buffer size if ((buffSize = mpg123_outblock(handle)) < 1) { PRINT2_ERR(TXT("Failed to get output buffer size from libmpg123:\n") FMT_chr TXT("\n"), mpg123_strerror(handle)); close(); return false; } //Compute frame size frameSize = MPG123_SAMPLESIZE(format.encoding) * format.channels; //Allocate temp buffer tempBuff = new uint8_t[buffSize]; return true; } bool AudioIO_Mpg123_Private::openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format) { return false; /*unsupported*/ } bool AudioIO_Mpg123_Private::close(void) { bool result = false; //Close audio file if (handle) { result = (MPG123CLOSE(handle) == MPG123_OK); } //Free handle MPG123_DELETE(handle); //Clear format info memset(&format, 0, sizeof(struct mpg123_fmt)); //Free temp buffer buffSize = frameSize = 0; MY_DELETE_ARRAY(tempBuff); return result; } int64_t AudioIO_Mpg123_Private::read(double **buffer, const int64_t count) { if (!handle) { MY_THROW("Audio file not currently open!"); } int64_t offset = 0, remaining = count; const int64_t maxRdSize = static_cast(buffSize / frameSize); while (remaining > 0) { //Read data const size_t rdBytes = static_cast(std::min(remaining, maxRdSize) * frameSize); size_t outBytes = 0; if (mpg123_read(handle, tempBuff, rdBytes, &outBytes) != MPG123_OK) { break; } //Deinterleaving const int64_t rdFrames = (int64_t)(outBytes / frameSize); switch (format.encoding) { case MPG123_ENC_FLOAT_32: deinterleave(buffer, offset, reinterpret_cast (tempBuff), format.channels, rdFrames); break; case MPG123_ENC_FLOAT_64: deinterleave(buffer, offset, reinterpret_cast(tempBuff), format.channels, rdFrames); break; default: PRINT2_ERR(TXT("Sample encoding 0x%X is NOT supported!"), format.encoding); return 0; } offset += rdFrames, remaining -= rdFrames; if (outBytes < rdBytes) { break; /*end of file, or read error*/ } } //Zero remaining data if (remaining > 0) { for (int c = 0; c < format.channels; c++) { memset(&buffer[c][offset], 0, sizeof(double) * size_t(remaining)); } } return count - remaining; } int64_t AudioIO_Mpg123_Private::write(double *const *buffer, const int64_t count) { return -1; /*unsupported*/ } bool AudioIO_Mpg123_Private::queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth) { if (!handle) { MY_THROW("Audio file not currently open!"); } if (format.channels && format.rate && format.encoding) { channels = format.channels; sampleRate = format.rate; if ((length = mpg123_length(handle)) == MPG123_ERR) { length = INT64_MAX; } bitDepth = MPG123_SAMPLESIZE(format.encoding) * 8U; return true; } return false; } void AudioIO_Mpg123_Private::getFormatInfo(CHR *buffer, const uint32_t buffSize) { SNPRINTF(buffer, buffSize, TXT("MPG123 Audio")); } /////////////////////////////////////////////////////////////////////////////// // Static Functions /////////////////////////////////////////////////////////////////////////////// CHR AudioIO_Mpg123_Private::versionBuffer[256] = { '\0' }; MY_CRITSEC_DECL(AudioIO_Mpg123_Private::mutex_lock); uint32_t AudioIO_Mpg123_Private::instanceCounter = 0U; const CHR *AudioIO_Mpg123_Private::libraryVersion(void) { MY_CRITSEC_ENTER(mutex_lock); if(!versionBuffer[0]) { SNPRINTF(versionBuffer, 256, TXT("libmpg123 API-v%u, written and copyright by Michael Hipp and others."), MPG123_API_VERSION); } MY_CRITSEC_LEAVE(mutex_lock); return versionBuffer; } const CHR *const *AudioIO_Mpg123_Private::supportedFormats(const CHR **const list, const uint32_t maxLen) { static const CHR *const MP3_FORMAT = TXT("mp3"); if (list && (maxLen > 0)) { uint32_t nextPos = 0; list[nextPos++] = &MP3_FORMAT[0]; list[(nextPos < maxLen) ? nextPos : (maxLen - 1)] = NULL; } return list; } bool AudioIO_Mpg123_Private::checkFileType(FILE *const file) { static const uint32_t THRESHOLD = 13U; static const size_t BUFF_SIZE = 128U * 1024U; uint32_t max_sequence = 0; uint8_t *buffer = new uint8_t[BUFF_SIZE]; size_t count = BUFF_SIZE; for (int chunk = 0; (chunk < 64) && (count >= BUFF_SIZE); ++chunk) { if ((count = fread(buffer, sizeof(uint8_t), BUFF_SIZE, file)) >= MPG123_HDR_SIZE) { if (checkMpg123Sequence(buffer, count, max_sequence) >= THRESHOLD) { break; /*early termination*/ } } } MY_DELETE_ARRAY(buffer); return (max_sequence >= THRESHOLD); } uint32_t AudioIO_Mpg123_Private::checkMpg123Sequence(const uint8_t *const buffer, const size_t &count, uint32_t &max_sequence) { const size_t limit = count - MPG123_HDR_SIZE; uint32_t sequence_len = 0; uint8_t prev_idx[3] = { 0, 0, 0 }; size_t fpos = 0; while (fpos < limit) { if (checkMpg123SyncWord(buffer, fpos)) { const uint8_t versn_idx = ((buffer[fpos + 1U] & ((uint8_t)0x08)) >> 3U); const uint8_t layer_idx = ((buffer[fpos + 1U] & ((uint8_t)0x06)) >> 1U); const uint8_t bitrt_idx = ((buffer[fpos + 2U] & ((uint8_t)0xF0)) >> 4U); const uint8_t srate_idx = ((buffer[fpos + 2U] & ((uint8_t)0x0C)) >> 2U); const uint8_t padd_byte = ((buffer[fpos + 2U] & ((uint8_t)0x02)) >> 1U); if ((layer_idx > 0x00) && (layer_idx <= 0x03) && (bitrt_idx > 0x00) && (bitrt_idx < 0x0F) && (srate_idx < 0x03)) { const uint32_t bitrt = MPG123_BITRT[versn_idx][layer_idx][bitrt_idx]; const uint32_t srate = MPG123_SRATE[versn_idx][srate_idx]; const uint32_t fsize = (MPG123_FSIZE[versn_idx][layer_idx] * bitrt * 1000U / srate) + padd_byte; if ((sequence_len < 1U) || ((prev_idx[0] == versn_idx) && (prev_idx[1] == layer_idx) && (prev_idx[2] == srate_idx))) { prev_idx[0] = versn_idx; prev_idx[1] = layer_idx; prev_idx[2] = srate_idx; max_sequence = std::max(max_sequence, ++sequence_len); if ((fsize > 0) && ((fpos + fsize) < limit) && checkMpg123SyncWord(buffer, fpos + fsize)) { fpos += fsize; continue; } } } } sequence_len = 0; prev_idx[0] = prev_idx[1] = prev_idx[2] = 0; fpos++; } return max_sequence; } bool AudioIO_Mpg123_Private::checkMpg123SyncWord(const uint8_t *const buffer, const size_t &fpos) { return (buffer[fpos] == ((uint8_t)0xFF)) && ((buffer[fpos + 1] & ((uint8_t)0xF0)) == ((uint8_t)0xF0)); } template void AudioIO_Mpg123_Private::deinterleave(double **destination, const int64_t offset, const T *const source, const int &channels, const int64_t &len) { for (int64_t i = 0; i < len; i++) { for (int c = 0; c < channels; c++) { destination[c][i + offset] = source[(i * channels) + c]; } } } void AudioIO_Mpg123_Private::libraryInit(void) { MY_CRITSEC_ENTER(mutex_lock); if (!(instanceCounter++)) { if (mpg123_init() != MPG123_OK) { abort(); } } MY_CRITSEC_LEAVE(mutex_lock); } void AudioIO_Mpg123_Private::libraryExit(void) { MY_CRITSEC_ENTER(mutex_lock); if (!(--instanceCounter)) { mpg123_exit(); } MY_CRITSEC_LEAVE(mutex_lock); } ================================================ FILE: DynamicAudioNormalizerCLI/src/AudioIO_Mpg123.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #include "AudioIO.h" class AudioIO_Mpg123_Private; class AudioIO_Mpg123 : public AudioIO { public: AudioIO_Mpg123(void); virtual ~AudioIO_Mpg123(void); //Open and Close virtual bool openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth); virtual bool openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format = NULL); virtual bool close(void); //Read and Write virtual int64_t read(double **buffer, const int64_t count); virtual int64_t write(double *const *buffer, const int64_t count); //Query info virtual bool queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth); virtual void getFormatInfo(CHR *buffer, const uint32_t buffSize); //Static functions static const CHR *libraryVersion(void); static const CHR *const *supportedFormats(const CHR **const list, const uint32_t maxLen); static bool checkFileType(FILE *const file); static AudioIO *createInstance() { return new AudioIO_Mpg123(); } private: AudioIO_Mpg123 &operator=(const AudioIO_Mpg123 &) { throw 666; } AudioIO_Mpg123_Private *const p; }; ================================================ FILE: DynamicAudioNormalizerCLI/src/AudioIO_OpusFile.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #define __STDC_LIMIT_MACROS #include "AudioIO_OpusFile.h" #include #include #include #include //#include #include #ifdef __unix #include #else #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif #define OPUS_SRATE 48000U #define MY_THROW(X) throw std::runtime_error((X)) /////////////////////////////////////////////////////////////////////////////// // Private Data /////////////////////////////////////////////////////////////////////////////// class AudioIO_OpusFile_Private { public: AudioIO_OpusFile_Private(void); ~AudioIO_OpusFile_Private(void); //Open and Close bool openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth); bool openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format); bool close(void); //Read and Write int64_t read(double **buffer, const int64_t count); int64_t write(double *const *buffer, const int64_t count); //Query info bool queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth); void getFormatInfo(CHR *buffer, const uint32_t buffSize); //Library info static const CHR *libraryVersion(void); static const CHR *const *supportedFormats(const CHR **const list, const uint32_t maxLen); static bool checkFileType(FILE *const); private: //opusfile OggOpusFile *handle; OpusFileCallbacks callbacks; void *stream; //properties int chanCount; bool downmix; //(De)Interleaving buffer float *tempBuff; size_t buffSize; //Library info static MY_CRITSEC_DECL(mutex_lock); static CHR versionBuffer[256]; //Helper functions template static void deinterleave(double **destination, const int64_t offset, const T *const source, const int &channels, const int64_t &len); }; /////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor /////////////////////////////////////////////////////////////////////////////// AudioIO_OpusFile::AudioIO_OpusFile(void) : p(new AudioIO_OpusFile_Private()) { } AudioIO_OpusFile::~AudioIO_OpusFile(void) { delete p; } AudioIO_OpusFile_Private::AudioIO_OpusFile_Private(void) { tempBuff = NULL; handle = NULL; stream = NULL; buffSize = 0; chanCount = 0; downmix = false; memset(&callbacks, 0, sizeof(OpusFileCallbacks)); } AudioIO_OpusFile_Private::~AudioIO_OpusFile_Private(void) { close(); } /////////////////////////////////////////////////////////////////////////////// // Public API /////////////////////////////////////////////////////////////////////////////// bool AudioIO_OpusFile::openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth) { return p->openRd(fileName, channels, sampleRate, bitDepth); } bool AudioIO_OpusFile::openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format) { return p->openWr(fileName, channels, sampleRate, bitDepth, format); } bool AudioIO_OpusFile::close(void) { return p->close(); } int64_t AudioIO_OpusFile::read(double **buffer, const int64_t count) { return p->read(buffer, count); } int64_t AudioIO_OpusFile::write(double *const *buffer, const int64_t count) { return p->write(buffer, count); } bool AudioIO_OpusFile::queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth) { return p->queryInfo(channels, sampleRate, length, bitDepth); } void AudioIO_OpusFile::getFormatInfo(CHR *buffer, const uint32_t buffSize) { p->getFormatInfo(buffer, buffSize); } const CHR *AudioIO_OpusFile::libraryVersion(void) { return AudioIO_OpusFile_Private::libraryVersion(); } const CHR *const *AudioIO_OpusFile::supportedFormats(const CHR **const list, const uint32_t maxLen) { return AudioIO_OpusFile_Private::supportedFormats(list, maxLen); } bool AudioIO_OpusFile::checkFileType(FILE *const file) { return AudioIO_OpusFile_Private::checkFileType(file); } /////////////////////////////////////////////////////////////////////////////// // Internal Functions /////////////////////////////////////////////////////////////////////////////// bool AudioIO_OpusFile_Private::openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth) { if (handle) { PRINT_ERR(TXT("OggOpus file is already open!\n")); return false; } //Open file descriptor const int fd = OPEN(fileName, O_RDONLY); if (fd < 0) { PRINT2_ERR(TXT("Failed to open input file for reading! [error: %d]\n"), errno); return false; } //Create callbacks if (!(stream = op_fdopen(&callbacks, fd, "rb"))) { PRINT_ERR(TXT("Failed to initialize OpusFile callbacks!\n")); CLOSE(fd); return false; } //Create opusfile handle int error; if (!(handle = op_open_callbacks(stream, &callbacks, NULL, 0U, &error))) { PRINT2_ERR(TXT("Failed to open OggOpus file for reading [error: %d]\n"), error); callbacks.close(stream); stream = NULL; memset(&callbacks, 0, sizeof(OpusFileCallbacks)); return false; } //Is seekable? if (op_seekable(handle)) { //Get the number of links const int linkCount = op_link_count(handle); if (linkCount < 1) { MY_THROW("Insanity: Link count is zero or negative!"); } //Get channel count chanCount = op_channel_count(handle, 0); if (chanCount < 1) { MY_THROW("Insanity: Channel count is zero or negative!"); } //Too many channels for us? downmix = false; if (chanCount > 8) { downmix = true, chanCount = 2; /*enforce stereo*/ } //Check consistency of channel count for *all* links if ((!downmix) && (linkCount > 1)) { for (int link = 1; link < linkCount; ++link) { const int chanCountNext = op_channel_count(handle, link); if (chanCountNext < 1) { MY_THROW("Insanity: Channel count is zero or negative!"); } if (chanCountNext != chanCount) { downmix = true, chanCount = 2; /*enforce stereo*/ break; } } } } else { //For non-seekable stream, we can't do anything but enforce stereo! downmix = true, chanCount = 2; } //Print warning if downmixing is enabled if (downmix) { PRINT_WRN(TXT("Opus source has inconsistent channel count -> downminxing to stereo! (\n")); } //Allocate I/O buffer tempBuff = new float[buffSize = (OPUS_SRATE * chanCount)]; /*1 sec per channel*/ return true; } bool AudioIO_OpusFile_Private::openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format) { return false; /*unsupported*/ } bool AudioIO_OpusFile_Private::close(void) { bool result = false; //Close audio file if (handle) { op_free(handle); result = true; } //Clear callbacks memset(&callbacks, 0, sizeof(OpusFileCallbacks)); //Free temp buffer MY_DELETE_ARRAY(tempBuff); buffSize = chanCount = 0, downmix = false, handle = NULL, stream = NULL; return result; } int64_t AudioIO_OpusFile_Private::read(double **buffer, const int64_t count) { if (!handle) { MY_THROW("Audio file not currently open!"); } int64_t offset = 0, remaining = count; //Read next chunk of data while (remaining > 0) { int result, link = -1; const int rdSize = static_cast(std::min(remaining * chanCount, static_cast(buffSize))); //Read next chunk of data for(int retry = 0; retry < 9999; ++retry) { result = downmix ? op_read_float_stereo(handle, tempBuff, rdSize) : op_read_float(handle, tempBuff, rdSize, &link); if (result != OP_HOLE) { break; /*no more holes*/ } } //Check result for errors if (result <= 0) { break; /*end of file, or read error*/ } //Check number of channels if ((!downmix) && (op_channel_count(handle, link) != chanCount)) { MY_THROW("Number of channels inconsistent!"); } //Deinterleaving deinterleave(buffer, offset, tempBuff, chanCount, result); offset += result, remaining -= result; } //Zero remaining data if (remaining > 0) { for (int c = 0; c < chanCount; c++) { memset(&buffer[c][offset], 0, sizeof(double) * size_t(remaining)); } } return count - remaining; } int64_t AudioIO_OpusFile_Private::write(double *const *buffer, const int64_t count) { return -1; /*unsupported*/ } bool AudioIO_OpusFile_Private::queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth) { if (!handle) { MY_THROW("Audio file not currently open!"); } //Try to compute number of samples const ogg_int64_t samplesTotal = op_pcm_total(handle, -1); //Set up audio properties channels = (uint32_t)chanCount; sampleRate = OPUS_SRATE; length = (samplesTotal > 0) ? samplesTotal : INT64_MAX; bitDepth = 32U; return true; } void AudioIO_OpusFile_Private::getFormatInfo(CHR *buffer, const uint32_t buffSize) { SNPRINTF(buffer, buffSize, TXT("MPG123 Audio")); } /////////////////////////////////////////////////////////////////////////////// // Static Functions /////////////////////////////////////////////////////////////////////////////// CHR AudioIO_OpusFile_Private::versionBuffer[256] = { '\0' }; MY_CRITSEC_DECL(AudioIO_OpusFile_Private::mutex_lock); const CHR *AudioIO_OpusFile_Private::libraryVersion(void) { MY_CRITSEC_ENTER(mutex_lock); if(!versionBuffer[0]) { SNPRINTF(versionBuffer, 256, FMT_chr TXT(", created by the Xiph.Org Foundation and contributors."), opus_get_version_string()); } MY_CRITSEC_LEAVE(mutex_lock); return versionBuffer; } const CHR *const *AudioIO_OpusFile_Private::supportedFormats(const CHR **const list, const uint32_t maxLen) { static const CHR *const OPUS_FORMAT = TXT("opus"); if (list && (maxLen > 0)) { uint32_t nextPos = 0; list[nextPos++] = &OPUS_FORMAT[0]; list[(nextPos < maxLen) ? nextPos : (maxLen - 1)] = NULL; } return list; } bool AudioIO_OpusFile_Private::checkFileType(FILE *const file) { static const size_t BUFF_SIZE = 4096U; uint8_t *buffer = new uint8_t[BUFF_SIZE]; bool result = false; const size_t count = fread(buffer, sizeof(uint8_t), BUFF_SIZE, file); if (count >= 57U) { OpusHead head; result = (op_test(&head, buffer, count) == 0); } MY_DELETE_ARRAY(buffer); return result; } template void AudioIO_OpusFile_Private::deinterleave(double **destination, const int64_t offset, const T *const source, const int &channels, const int64_t &len) { for (int64_t i = 0; i < len; i++) { for (int c = 0; c < channels; c++) { destination[c][i + offset] = source[(i * channels) + c]; } } } ================================================ FILE: DynamicAudioNormalizerCLI/src/AudioIO_OpusFile.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #include "AudioIO.h" class AudioIO_OpusFile_Private; class AudioIO_OpusFile : public AudioIO { public: AudioIO_OpusFile(void); virtual ~AudioIO_OpusFile(void); //Open and Close virtual bool openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth); virtual bool openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format = NULL); virtual bool close(void); //Read and Write virtual int64_t read(double **buffer, const int64_t count); virtual int64_t write(double *const *buffer, const int64_t count); //Query info virtual bool queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth); virtual void getFormatInfo(CHR *buffer, const uint32_t buffSize); //Static functions static const CHR *libraryVersion(void); static const CHR *const *supportedFormats(const CHR **const list, const uint32_t maxLen); static bool checkFileType(FILE *const file); static AudioIO *createInstance() { return new AudioIO_OpusFile(); } private: AudioIO_OpusFile &operator=(const AudioIO_OpusFile &) { throw 666; } AudioIO_OpusFile_Private *const p; }; ================================================ FILE: DynamicAudioNormalizerCLI/src/AudioIO_SndFile.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #define __STDC_LIMIT_MACROS #ifdef _WIN32 #define ENABLE_SNDFILE_WINDOWS_PROTOTYPES 1 #define SF_OPEN_FILE(X,Y,Z) sf_wchar_open((X),(Y),(Z)) #else #define SF_OPEN_FILE(X,Y,Z) sf_open((X),(Y),(Z)) #endif #include "AudioIO_SndFile.h" #include #include #include #include #include #include "3rd_party/memmem.h" #ifdef __unix #include #else #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 #endif #define MY_THROW(X) throw std::runtime_error((X)) /////////////////////////////////////////////////////////////////////////////// // Const /////////////////////////////////////////////////////////////////////////////// static const struct { const CHR *const extension[3]; const int format; const int sub_format; const bool flag[2]; } g_audio_formats[] = { { { TXT("wav"), NULL }, SF_FORMAT_WAV, 0, 0, 1 }, { { TXT("w64"), NULL }, SF_FORMAT_W64, 0, 0, 1 }, { { TXT("rf64"), NULL }, SF_FORMAT_RF64, 0, 0, 1 }, { { TXT("au"), NULL }, SF_FORMAT_AU, 0, 1, 1 }, { { TXT("aiff"), NULL }, SF_FORMAT_AIFF, 0, 1, 1 }, { { TXT("ogg"), TXT("oga"), NULL }, SF_FORMAT_OGG, SF_FORMAT_VORBIS, 0, 0 }, { { TXT("flac"), TXT("fla"), NULL }, SF_FORMAT_FLAC, 0, 1, 0 }, { { TXT("raw") , TXT("pcm"), NULL }, SF_FORMAT_RAW, 0, 1, 1 }, { { NULL }, 0, 0, 0, 0 } }; static const uint32_t CHANNELS_MIN = 1U; static const uint32_t CHANNELS_MAX = 16U; static const uint32_t SAMPLERATE_MIN = 8000U; static const uint32_t SAMPLERATE_MAX = 192000U; /////////////////////////////////////////////////////////////////////////////// // Private Data /////////////////////////////////////////////////////////////////////////////// class AudioIO_SndFile_Private { public: AudioIO_SndFile_Private(void); ~AudioIO_SndFile_Private(void); //Open and Close bool openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth); bool openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format); bool close(void); //Read and Write int64_t read(double **buffer, const int64_t count); int64_t write(double *const *buffer, const int64_t count); //Query info bool queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth); void getFormatInfo(CHR *buffer, const uint32_t buffSize); //Library info static const CHR *libraryVersion(void); static const CHR *const *supportedFormats(const CHR **const list, const uint32_t maxLen); static bool checkFileType(FILE *const file); private: //libsndfile SF_INFO info; SNDFILE *handle; int access; bool is_pipe; //(De)Interleaving buffer double *tempBuff; static const size_t BUFF_SIZE = 2048; //Library info static MY_CRITSEC_DECL(mutex_lock); static CHR versionBuffer[256]; //Helper functions static int formatToBitDepth(const int &format); static int formatFromExtension(const CHR *const fileName, const int &bitDepth); static int getSubFormat(const int &bitDepth, const bool &eightBitIsSigned, const bool &hightBitdepthSupported); static bool checkRawParameters(const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth); }; /////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor /////////////////////////////////////////////////////////////////////////////// AudioIO_SndFile::AudioIO_SndFile(void) : p(new AudioIO_SndFile_Private()) { } AudioIO_SndFile::~AudioIO_SndFile(void) { delete p; } AudioIO_SndFile_Private::AudioIO_SndFile_Private(void) { access = 0; is_pipe = false; handle = NULL; tempBuff = NULL; } AudioIO_SndFile_Private::~AudioIO_SndFile_Private(void) { close(); } /////////////////////////////////////////////////////////////////////////////// // Public API /////////////////////////////////////////////////////////////////////////////// bool AudioIO_SndFile::openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth) { return p->openRd(fileName, channels, sampleRate, bitDepth); } bool AudioIO_SndFile::openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format) { return p->openWr(fileName, channels, sampleRate, bitDepth, format); } bool AudioIO_SndFile::close(void) { return p->close(); } int64_t AudioIO_SndFile::read(double **buffer, const int64_t count) { return p->read(buffer, count); } int64_t AudioIO_SndFile::write(double *const *buffer, const int64_t count) { return p->write(buffer, count); } bool AudioIO_SndFile::queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth) { return p->queryInfo(channels, sampleRate, length, bitDepth); } void AudioIO_SndFile::getFormatInfo(CHR *buffer, const uint32_t buffSize) { p->getFormatInfo(buffer, buffSize); } const CHR *AudioIO_SndFile::libraryVersion(void) { return AudioIO_SndFile_Private::libraryVersion(); } const CHR *const *AudioIO_SndFile::supportedFormats(const CHR **const list, const uint32_t maxLen) { return AudioIO_SndFile_Private::supportedFormats(list, maxLen); } bool AudioIO_SndFile::checkFileType(FILE *const file) { return AudioIO_SndFile_Private::checkFileType(file); } /////////////////////////////////////////////////////////////////////////////// // Internal Functions /////////////////////////////////////////////////////////////////////////////// bool AudioIO_SndFile_Private::openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth) { if(handle) { PRINT_ERR(TXT("Sound file is already open!\n")); return false; } //Initialize memset(&info, 0, sizeof(SF_INFO)); //Use pipe? const bool bStdIn = (STRCASECMP(fileName, TXT("-")) == 0); const bool bPipe = bStdIn && (!FD_ISREG(STDIN_FILENO)); //Setup info for "raw" input if(bPipe) { if(!checkRawParameters(channels, sampleRate, bitDepth)) { return false; } info.format = formatFromExtension(TXT("raw"), bitDepth); info.channels = channels; info.samplerate = sampleRate; } //Open file in libsndfile handle = bStdIn ? sf_open_fd(STDIN_FILENO, SFM_READ, &info, SF_FALSE) : SF_OPEN_FILE(fileName, SFM_READ, &info); if(!handle) { PRINT2_ERR(TXT("Failed to open file for reading: \"") FMT_chr TXT("\"\n"), sf_strerror(NULL)); return false; } //Allocate temp buffer tempBuff = new double[BUFF_SIZE * info.channels]; is_pipe = bPipe; access = SFM_READ; return true; } bool AudioIO_SndFile_Private::openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format) { if(handle) { PRINT_ERR(TXT("Sound file is already open!\n")); return false; } //Initialize memset(&info, 0, sizeof(SF_INFO)); //Use pipe? const bool bStdOut = (STRCASECMP(fileName, TXT("-")) == 0); const bool bPipe = bStdOut && (!FD_ISREG(STDOUT_FILENO)); //Setup output format info.format = format ? formatFromExtension(format, bitDepth) : formatFromExtension(bPipe ? TXT("raw") : fileName, bitDepth); info.channels = channels; info.samplerate = sampleRate; //Open file in libsndfile handle = bStdOut ? sf_open_fd(STDOUT_FILENO, SFM_WRITE, &info, SF_FALSE) : SF_OPEN_FILE(fileName, SFM_WRITE, &info); if(!handle) { PRINT2_ERR(TXT("Failed to open file for writing: \"") FMT_chr TXT("\"\n"), sf_strerror(NULL)); return false; } //Allocate temp buffer tempBuff = new double[BUFF_SIZE * info.channels]; //Set Vorbis quality if((info.format & SF_FORMAT_SUBMASK) == SF_FORMAT_VORBIS) { double vorbisQualityLevel = 0.6; sf_command(handle, SFC_SET_VBR_ENCODING_QUALITY, &vorbisQualityLevel, sizeof(double)); } is_pipe = bPipe; access = SFM_WRITE; return true; } bool AudioIO_SndFile_Private::close(void) { bool result = false; //Close sndfile if(handle) { sf_close(handle); handle = NULL; result = true; } //Free temp buffer MY_DELETE_ARRAY(tempBuff); //Clear sndfile status access = 0; memset(&info, 0, sizeof(SF_INFO)); return result; } int64_t AudioIO_SndFile_Private::read(double **buffer, const int64_t count) { if(!handle) { MY_THROW("Audio file not currently open!"); } if(access != SFM_READ) { MY_THROW("Audio file not open in READ mode!"); } sf_count_t offset = 0; sf_count_t remaining = count; while(remaining > 0) { //Read data const sf_count_t rdSize = std::min(remaining, int64_t(BUFF_SIZE)); const sf_count_t result = sf_readf_double(handle, tempBuff, rdSize); //Deinterleaving for(sf_count_t i = 0; i < result; i++) { for(int c = 0; c < info.channels; c++) { buffer[c][i + offset] = tempBuff[(i * info.channels) + c]; } } offset += result; remaining -= result; if(result < rdSize) { break; /*end of file, or read error*/ } } //Zero remaining data if(remaining > 0) { for(int c = 0; c < info.channels; c++) { memset(&buffer[c][offset], 0, sizeof(double) * size_t(remaining)); } } return count - remaining; } int64_t AudioIO_SndFile_Private::write(double *const *buffer, const int64_t count) { if(!handle) { MY_THROW("Audio file not currently open!"); } if(access != SFM_WRITE) { MY_THROW("Audio file not open in WRITE mode!"); } sf_count_t offset = 0; sf_count_t remaining = count; while(remaining > 0) { const sf_count_t wrSize = std::min(remaining, int64_t(BUFF_SIZE)); //Interleave data for(sf_count_t i = 0; i < wrSize; i++) { for(int c = 0; c < info.channels; c++) { tempBuff[(i * info.channels) + c] = buffer[c][i + offset]; } } //Write data const sf_count_t result = sf_writef_double(handle, tempBuff, wrSize); offset += result; remaining -= result; if(result < wrSize) { PRINT_WRN(TXT("File write error. Wrote fewer frames that what was requested!")); break; } } return count - remaining; } bool AudioIO_SndFile_Private::queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth) { if(!handle) { MY_THROW("Audio file not currently open!"); } channels = info.channels; sampleRate = info.samplerate; length = (is_pipe) ? INT64_MAX : info.frames; bitDepth = formatToBitDepth(info.format); return true; } void AudioIO_SndFile_Private::getFormatInfo(CHR *buffer, const uint32_t buffSize) { const CHR *format = TXT("Unknown Format"); const CHR *subfmt = TXT("Unknown SubFmt"); switch(info.format & SF_FORMAT_TYPEMASK) { case SF_FORMAT_WAV: format = TXT("RIFF WAVE"); break; case SF_FORMAT_AIFF: format = TXT("AIFF"); break; case SF_FORMAT_AU: format = TXT("AU/SND"); break; case SF_FORMAT_RAW: format = TXT("Raw Data"); break; case SF_FORMAT_W64: format = TXT("Wave64"); break; case SF_FORMAT_WAVEX: format = TXT("WAVE EX"); break; case SF_FORMAT_FLAC: format = TXT("FLAC"); break; case SF_FORMAT_OGG: format = TXT("Ogg"); break; case SF_FORMAT_RF64: format = TXT("RF64"); break; } switch(info.format & SF_FORMAT_SUBMASK) { case SF_FORMAT_PCM_S8: subfmt = TXT("8-Bit Signed"); break; case SF_FORMAT_PCM_U8: subfmt = TXT("8-Bit Unsigned"); break; case SF_FORMAT_PCM_16: subfmt = TXT("16-Bit Integer"); break; case SF_FORMAT_PCM_24: subfmt = TXT("24-Bit Integer"); break; case SF_FORMAT_PCM_32: subfmt = TXT("32-Bit Integer"); break; case SF_FORMAT_FLOAT: subfmt = TXT("32-Bit Floating-Point"); break; case SF_FORMAT_DOUBLE: subfmt = TXT("64-Bit Floating-Point"); break; case SF_FORMAT_VORBIS: subfmt = TXT("Xiph Vorbis"); break; } SNPRINTF(buffer, buffSize, FMT_CHR TXT(", ") FMT_CHR, format, subfmt); } /////////////////////////////////////////////////////////////////////////////// // Static Functions /////////////////////////////////////////////////////////////////////////////// CHR AudioIO_SndFile_Private::versionBuffer[256] = { TXT('\0') }; MY_CRITSEC_INIT(AudioIO_SndFile_Private::mutex_lock); const CHR *AudioIO_SndFile_Private::libraryVersion(void) { MY_CRITSEC_ENTER(mutex_lock); if(!versionBuffer[0]) { char temp[128] = { '\0' }; sf_command(NULL, SFC_GET_LIB_VERSION, temp, sizeof(temp)); SNPRINTF(versionBuffer, 256, FMT_chr TXT(", by Erik de Castro Lopo ."), temp); } MY_CRITSEC_LEAVE(mutex_lock); return versionBuffer; } const CHR *const *AudioIO_SndFile_Private::supportedFormats(const CHR **const list, const uint32_t maxLen) { if (list && (maxLen > 0)) { uint32_t nextPos = 0; for (size_t i = 0; g_audio_formats[i].format; ++i) { if (g_audio_formats[i].extension[0] && (nextPos < maxLen)) { list[nextPos++] = g_audio_formats[i].extension[0]; } } list[(nextPos < maxLen) ? nextPos : (maxLen - 1)] = NULL; } return list; } bool AudioIO_SndFile_Private::checkFileType(FILE *const file) { static const size_t BUFF_SIZE = 256; uint8_t buffer[BUFF_SIZE]; const size_t count = fread(buffer, sizeof(uint8_t), BUFF_SIZE, file); if (count >= BUFF_SIZE) { if (((memcmp(&buffer[0], "RIFF", 4) == 0) || (memcmp(&buffer[0], "RF64", 4) == 0)) && (memcmp(&buffer[8], "WAVE", 4) == 0)) { return true; } if ((memcmp(&buffer[0], "riff\x2E\x91\xCF\x11\xA5\xD6\x28\xDB\x04\xC1\x00\x00", 16) == 0) && (memcmp(&buffer[24], "wave\xF3\xAC\xD3\x11\x8C\xD1\x00\xC0\x4F\x8E\xDB\x8A", 16) == 0)) { return true; } if ((memcmp(&buffer[0], "FORM", 4U) == 0) && (memcmp(&buffer[8], "AIFF", 4U) == 0)) { return true; } if ((memcmp(&buffer[0], "fLaC\0", 5U) == 0) || (memcmp(&buffer[0], ".snd\0", 5U) == 0)) { return true; } if (const uint8_t *pos_oggs = (const uint8_t*)memmem(&buffer[0], count, "OggS\0", 5)) { if (memmem(pos_oggs + 5, count - ((pos_oggs + 5) - &buffer[0]), "vorbis", 6) != NULL) { return true; } } } return false; } int AudioIO_SndFile_Private::formatToBitDepth(const int &format) { switch(format & SF_FORMAT_SUBMASK) { case SF_FORMAT_PCM_S8: case SF_FORMAT_PCM_U8: return 8; case SF_FORMAT_PCM_16: return 16; case SF_FORMAT_PCM_24: return 24; case SF_FORMAT_PCM_32: case SF_FORMAT_FLOAT: return 32; case SF_FORMAT_DOUBLE: return 64; default: return 16; } } int AudioIO_SndFile_Private::formatFromExtension(const CHR *const fileName, const int &bitDepth) { const CHR *ext = fileName; if(const CHR *tmp = STRRCHR(ext, TXT('/' ))) ext = ++tmp; if(const CHR *tmp = STRRCHR(ext, TXT('\\'))) ext = ++tmp; if(const CHR *tmp = STRRCHR(ext, TXT('.' ))) ext = ++tmp; for (size_t i = 0; g_audio_formats[i].format; ++i) { for (size_t j = 0; g_audio_formats[i].extension[j]; ++j) { if (STRCASECMP(ext, g_audio_formats[i].extension[j]) == 0) { return g_audio_formats[i].format | (g_audio_formats[i].sub_format ? g_audio_formats[i].sub_format : getSubFormat(bitDepth, g_audio_formats[i].flag[0], g_audio_formats[i].flag[1])); } } } return SF_FORMAT_WAV | getSubFormat(bitDepth, 0, 1); } int AudioIO_SndFile_Private::getSubFormat(const int &bitDepth, const bool &eightBitIsSigned, const bool &hightBitdepthSupported) { int format = 0; switch(bitDepth) { case 8: format = eightBitIsSigned ? SF_FORMAT_PCM_S8 : SF_FORMAT_PCM_U8; break; case 16: format = SF_FORMAT_PCM_16; break; case 24: format = SF_FORMAT_PCM_24; break; case 32: format = hightBitdepthSupported ? SF_FORMAT_FLOAT : SF_FORMAT_PCM_24; break; case 64: format = hightBitdepthSupported ? SF_FORMAT_DOUBLE : SF_FORMAT_PCM_24; break; default: format = SF_FORMAT_PCM_16; break; } return format; } bool AudioIO_SndFile_Private::checkRawParameters(const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth) { if((channels < CHANNELS_MIN) || (channels > CHANNELS_MAX)) { PRINT2_ERR(TXT("Invalid number of channels (%u). Must be in the %u to %u range!\n"), channels, CHANNELS_MIN, CHANNELS_MAX); return false; } if((sampleRate < SAMPLERATE_MIN) || (sampleRate > SAMPLERATE_MAX)) { PRINT2_ERR(TXT("Invalid sampele rate (%u). Must be in the %u to %u range!\n"), sampleRate, SAMPLERATE_MIN, SAMPLERATE_MAX); return false; } if((bitDepth != 8U) && (bitDepth != 16U) && (bitDepth != 24U) && (bitDepth != 32U) && (bitDepth != 64U)) { PRINT2_ERR(TXT("Invalid bit depth (%u). Only 8, 16, 24, 32 and 64 bits/sample are supported!\n"), bitDepth); return false; } return true; } ================================================ FILE: DynamicAudioNormalizerCLI/src/AudioIO_SndFile.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #include "AudioIO.h" class AudioIO_SndFile_Private; class AudioIO_SndFile : public AudioIO { public: AudioIO_SndFile(void); virtual ~AudioIO_SndFile(void); //Open and Close virtual bool openRd(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth); virtual bool openWr(const CHR *const fileName, const uint32_t channels, const uint32_t sampleRate, const uint32_t bitDepth, const CHR *const format = NULL); virtual bool close(void); //Read and Write virtual int64_t read(double **buffer, const int64_t count); virtual int64_t write(double *const *buffer, const int64_t count); //Query info virtual bool queryInfo(uint32_t &channels, uint32_t &sampleRate, int64_t &length, uint32_t &bitDepth); virtual void getFormatInfo(CHR *buffer, const uint32_t buffSize); //Static functions static const CHR *libraryVersion(void); static const CHR *const *supportedFormats(const CHR **const list, const uint32_t maxLen); static bool checkFileType(FILE *const file); static AudioIO *createInstance() { return new AudioIO_SndFile(); } private: AudioIO_SndFile &operator=(const AudioIO_SndFile &) { throw 666; } AudioIO_SndFile_Private *const p; }; ================================================ FILE: DynamicAudioNormalizerCLI/src/Main.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif //Internal #include "Common.h" #include "Platform.h" #include "Parameters.h" #include "AudioIO.h" //MDynamicAudioNormalizer API #include "DynamicAudioNormalizer.h" //VLD #ifdef _MSC_VER #include #endif //C++ #include #include #include #include //Linkage #ifdef MDYNAMICAUDIONORMALIZER_STATIC static const CHR *LINKAGE = TXT("Static"); #else static const CHR *LINKAGE = TXT("Shared"); #endif //Utility macros #define BOOLIFY(X) ((X) ? TXT("on") : TXT("off")) #define FILENAME_SRC(X) (STRCASECMP((X), TXT("-")) ? (X) : TXT("")) #define FILENAME_OUT(X) (STRCASECMP((X), TXT("-")) ? (X) : TXT("")) //Const static const size_t FRAME_SIZE = 4096; static const CHR *appName(const CHR* argv0) { const CHR *appName = argv0; while(const CHR *temp = STRCHR(appName, TXT('/' ))) appName = &temp[1]; while(const CHR *temp = STRCHR(appName, TXT('\\'))) appName = &temp[1]; return appName; } static const CHR *timeToString(CHR *timeBuffer, const size_t buffSize, const int64_t &length, const uint32_t &sampleRate) { if(length != INT64_MAX) { double durationInt; double durationFrc = modf(double(length) / double(sampleRate), &durationInt); const uint32_t msc = uint32_t(durationFrc * 1000.0); const uint32_t sec = uint32_t(durationInt) % 60; const uint32_t min = (uint32_t(durationInt) / 60) % 60; const uint32_t hrs = uint32_t(durationInt) / 3600; SNPRINTF(timeBuffer, buffSize, TXT("%u:%02u:%02u.%03u"), hrs, min, sec, msc); } else { SNPRINTF(timeBuffer, buffSize, TXT("Unknown")); } return timeBuffer; } static void loggingCallback_default(const int logLevel, const char *const message) { switch(logLevel) { case MDynamicAudioNormalizer::LOG_LEVEL_WRN: PRINT2_WRN(FMT_chr, message); break; case MDynamicAudioNormalizer::LOG_LEVEL_ERR: PRINT2_ERR(FMT_chr, message); break; } } static void loggingCallback_verbose(const int logLevel, const char *const message) { switch(logLevel) { case MDynamicAudioNormalizer::LOG_LEVEL_DBG: PRINT2_NFO(FMT_chr, message); break; case MDynamicAudioNormalizer::LOG_LEVEL_WRN: PRINT2_WRN(FMT_chr, message); break; case MDynamicAudioNormalizer::LOG_LEVEL_ERR: PRINT2_ERR(FMT_chr, message); break; } } static bool openFiles(const Parameters ¶meters, AudioIO **sourceFile, AudioIO **outputFile) { uint32_t channels = 0, sampleRate = 0, bitDepth = 0; int64_t length = 0; MY_DELETE(*sourceFile); MY_DELETE(*outputFile); //Auto-detect source file type const CHR *sourceLibrary = parameters.sourceLibrary(); if (!(sourceLibrary && sourceLibrary[0])) { sourceLibrary = AudioIO::detectSourceType(parameters.sourceFile(), parameters.verboseMode()); } //Print Audio I/O information PRINT(TXT("Using ") FMT_CHR TXT("\n\n"), AudioIO::getLibraryVersion(sourceLibrary)); PRINT(TXT("SourceFile: ") FMT_CHR TXT("\n"), FILENAME_SRC(parameters.sourceFile())); PRINT(TXT("OutputFile: ") FMT_CHR TXT("\n\n"), FILENAME_OUT(parameters.outputFile())); //Open *source* file *sourceFile = AudioIO::createInstance(sourceLibrary); if(!(*sourceFile)->openRd(parameters.sourceFile(), parameters.inputChannels(), parameters.inputSampleRate(), parameters.inputBitDepth())) { PRINT2_WRN(TXT("Failed to open input file \"") FMT_CHR TXT("\" for reading!\n"), FILENAME_SRC(parameters.sourceFile())); MY_DELETE(*sourceFile); return false; } //Query file properties if((*sourceFile)->queryInfo(channels, sampleRate, length, bitDepth)) { CHR timeBuffer[32]; PRINT(TXT("Properties: %u channels, %u Hz, %u bit/sample (Duration: ") FMT_CHR TXT(")\n\n"), channels, sampleRate, bitDepth, timeToString(timeBuffer, 32, length, sampleRate)); } else { PRINT_WRN(TXT("Failed to determine source file properties!\n")); MY_DELETE(*sourceFile); return false; } //Open *output* file *outputFile = AudioIO::createInstance(); if(!(*outputFile)->openWr(parameters.outputFile(), channels, sampleRate, parameters.outputBitDepth() ? parameters.outputBitDepth() : bitDepth, parameters.outputFormat())) { PRINT2_WRN(TXT("Failed to open output file \"") FMT_CHR TXT("\" for writing!\n"), FILENAME_OUT(parameters.outputFile())); MY_DELETE(*sourceFile); MY_DELETE(*outputFile); return false; } if(parameters.verboseMode()) { CHR info[128]; (*sourceFile)->getFormatInfo(info, 128); PRINT(TXT("SourceInfo: ") FMT_CHR TXT("\n"), info); (*outputFile)->getFormatInfo(info, 128); PRINT(TXT("OutputInfo: ") FMT_CHR TXT("\n\n"), info); } return true; } static void printProgress(const int64_t &length, const int64_t &remaining, short &spinnerPos, bool done = false) { static const CHR spinner[4] = { TXT('-'), TXT('\\'), TXT('|'), TXT('/') }; if(length != INT64_MAX) { const double progress = 99.99 * (double(length - remaining) / double(length)); PRINT(TXT("\rNormalization in progress: %5.1f%% [%c]"), done ? std::max(progress, 100.0) : progress, done ? TXT('*') : spinner[spinnerPos++]); } else { PRINT(TXT("\rNormalization in progress... [%c]"), done ? TXT('*') : spinner[spinnerPos++]); } spinnerPos %= 4; FLUSH(); } static int processingLoop(MDynamicAudioNormalizer *normalizer, AudioIO *const sourceFile, AudioIO *const outputFile, double **buffer, const uint32_t channels, const int64_t length) { //Init status variables int64_t remaining = length; short indicator = 0, spinnerPos = 1; bool error = false; //Print progress printProgress(length, remaining, spinnerPos); //Main audio processing loop for(;;) { if((++indicator >= 256)) { printProgress(length, remaining, spinnerPos); indicator = 0; } const int64_t samplesRead = sourceFile->read(buffer, int64_t(FRAME_SIZE)); if(samplesRead > 0) { if(length != INT64_MAX) { remaining -= samplesRead; } int64_t outputSize; if (!normalizer->processInplace(buffer, samplesRead, outputSize)) { error = true; break; /*internal error*/ } if(outputSize > 0) { if(outputFile->write(buffer, outputSize) != outputSize) { error = true; break; /*write error must have ocurred*/ } } } if(samplesRead < int64_t(FRAME_SIZE)) { break; /*end of file*/ } } //Flush all the delayed samples while (!error) { int64_t outputSize; if (!normalizer->flushBuffer(buffer, int64_t(FRAME_SIZE), outputSize)) { error = true; break; /*internal error*/ } if (outputSize > 0) { if (outputFile->write(buffer, outputSize) != outputSize) { error = true; break; /*write error must have ocurred*/ } } else { break; /*no more pending samples*/ } } //Completed printProgress(length, remaining, spinnerPos, (!error)); PRINT(TXT("\n") FMT_CHR TXT(".\n\n"), error ? TXT("Aborted") : TXT("Finished")); //Check remaining samples if (!error) { const int64_t samples_delta = (length != INT64_MAX) ? abs(remaining) : (-1); if (samples_delta > 0) { const double delta_fract = double(samples_delta) / double(length); if (!(error = (delta_fract >= 0.25))) { PRINT2_WRN(TXT("Audio reader got %g (~%.1f%%) ") FMT_CHR TXT(" samples than projected!\n"), double(samples_delta), 100.0 * delta_fract, (remaining > 0) ? TXT("less") : TXT("more")); } } } //Error checking if(error) { PRINT_ERR(TXT("I/O error encountered -> stopping!\n")); } return error ? EXIT_FAILURE : EXIT_SUCCESS; } static int processFiles(const Parameters ¶meters, AudioIO *const sourceFile, AudioIO *const outputFile, FILE *const logFile) { int exitCode = EXIT_SUCCESS; //Get source info uint32_t channels, sampleRate, bitDepth; int64_t length; if(!sourceFile->queryInfo(channels, sampleRate, length, bitDepth)) { PRINT_WRN(TXT("Failed to determine source file properties!\n")); return EXIT_FAILURE; } //Create the normalizer instance MDynamicAudioNormalizer *normalizer = new MDynamicAudioNormalizer ( channels, sampleRate, parameters.frameLenMsec(), parameters.filterSize(), parameters.peakValue(), parameters.maxAmplification(), parameters.targetRms(), parameters.compressFactor(), parameters.channelsCoupled(), parameters.enableDCCorrection(), parameters.altBoundaryMode(), logFile ); //Initialze normalizer if(!normalizer->initialize()) { PRINT_ERR(TXT("Failed to initialize the normalizer instance!\n")); MY_DELETE(normalizer); return EXIT_FAILURE; } //Allocate buffers double **buffer = new double*[channels]; for(uint32_t channel = 0; channel < channels; channel++) { buffer[channel] = new double[FRAME_SIZE]; } //Some extra spacing in VERBOSE mode if(parameters.verboseMode()) { PRINT(TXT("\n")); } //Run normalizer now! exitCode = processingLoop(normalizer, sourceFile, outputFile, buffer, channels, length); //Destroy the normalizer MY_DELETE(normalizer); //Memory clean-up for(uint32_t channel = 0; channel < channels; channel++) { MY_DELETE_ARRAY(buffer[channel]); } MY_DELETE_ARRAY(buffer); //Some extra spacing in VERBOSE mode if(parameters.verboseMode()) { PRINT(TXT("\n")); } //Return result return exitCode; } static void printHelpScreen(int argc, CHR* argv[]) { Parameters defaults; PUTS (TXT("Basic Usage:\n")); PRINT(TXT(" ") FMT_CHR TXT(" [options] -i -o \n"), appName(argv[0])); PUTS (TXT("\n")); PUTS (TXT("Input/Output:\n")); PUTS (TXT(" -i --input Input audio file [required]\n")); PUTS (TXT(" -d --input-lib Input decoder library [default: auto-detect]\n")); PUTS (TXT(" -o --output Output audio file [required]\n")); PUTS (TXT(" -t --output-fmt Output format [default: auto-detect]\n")); PUTS (TXT(" -u --output-bps Output bits per sample [default: like input]\n")); PUTS (TXT("\n")); PUTS (TXT("Algorithm Tweaks:\n")); PRINT(TXT(" -f --frame-len Frame length, in milliseconds [default: %u]\n"), defaults.frameLenMsec()); PRINT(TXT(" -g --gauss-size Gauss filter size, in frames [default: %u]\n"), defaults.filterSize()); PRINT(TXT(" -p --peak Target peak magnitude, 0.1-1 [default: %.2f]\n"), defaults.peakValue()); PRINT(TXT(" -m --max-gain Maximum gain factor [default: %.2f]\n"), defaults.maxAmplification()); PRINT(TXT(" -r --target-rms Target RMS value [default: %.2f]\n"), defaults.targetRms()); PRINT(TXT(" -n --no-coupling Disable channel coupling [default: ") FMT_CHR TXT("]\n"), BOOLIFY(defaults.channelsCoupled())); PRINT(TXT(" -c --correct-dc Enable the DC bias correction [default: ") FMT_CHR TXT("]\n"), BOOLIFY(defaults.enableDCCorrection())); PRINT(TXT(" -b --alt-boundary Use alternative boundary mode [default: ") FMT_CHR TXT("]\n"), BOOLIFY(defaults.altBoundaryMode())); PRINT(TXT(" -s --compress Compress the input data [default: %.2f]\n"), defaults.compressFactor()); PUTS (TXT("\n")); PUTS (TXT("Diagnostics:\n")); PUTS (TXT(" -v --verbose Output additional diagnostic info\n")); PUTS (TXT(" -l --log-file Create a log file\n")); PUTS (TXT(" -h --help Print *this* help screen\n")); PUTS (TXT("\n")); PUTS (TXT("Raw Data Options:\n")); PUTS (TXT(" --input-bits Bits per sample, e.g. '16' or '32'\n")); PUTS (TXT(" --input-chan Number of channels, e.g. '2' for Stereo\n")); PUTS (TXT(" --input-rate Sample rate in Hertz, e.g. '44100'\n")); PUTS (TXT("\n")); } static void printLogo(void) { uint32_t versionMajor, versionMinor, versionPatch; MDynamicAudioNormalizer::getVersionInfo(versionMajor, versionMinor, versionPatch); const char *buildDate, *buildTime, *buildCompiler, *buildArch; bool buildDebug; MDynamicAudioNormalizer::getBuildInfo(&buildDate, &buildTime, &buildCompiler, &buildArch, buildDebug); PRINT(TXT("---------------------------------------------------------------------------\n")); PRINT(TXT("Dynamic Audio Normalizer, Version %u.%02u-%u, ") FMT_CHR TXT("\n"), versionMajor, versionMinor, versionPatch, LINKAGE); PRINT(TXT("Copyright (c) 2014-") FMT_chr TXT(" LoRd_MuldeR . Some rights reserved.\n"), &buildDate[7]); PRINT(TXT("Built on ") FMT_chr TXT(" at ") FMT_chr TXT(" with ") FMT_chr TXT(" for ") OS_TYPE TXT("-") FMT_chr TXT(".\n\n"), buildDate, buildTime, buildCompiler, buildArch); PRINT(TXT("This program is free software: you can redistribute it and/or modify\n")); PRINT(TXT("it under the terms of the GNU General Public License .\n")); PRINT(TXT("Note that this program is distributed with ABSOLUTELY NO WARRANTY.\n")); if(DYNAUDNORM_DEBUG) { PRINT(TXT("\n!!! DEBUG BUILD !!! DEBUG BUILD !!! DEBUG BUILD !!! DEBUG BUILD !!!\n")); } PRINT(TXT("---------------------------------------------------------------------------\n\n")); if((DYNAUDNORM_DEBUG) != buildDebug) { PRINT_ERR(TXT("Trying to use DEBUG library with RELEASE binary or vice versa!\n")); exit(EXIT_FAILURE); } } int dynamicNormalizerMain(int argc, CHR* argv[]) { printLogo(); Parameters parameters; if(!parameters.parseArgs(argc, argv)) { PRINT2_ERR(TXT("Invalid or incomplete command-line arguments have been detected.\n\nPlease type \"") FMT_CHR TXT(" --help\" for details!\n"), appName(argv[0])); return EXIT_FAILURE; } if(parameters.showHelp()) { printHelpScreen(argc, argv); return EXIT_SUCCESS; } MDynamicAudioNormalizer::setLogFunction(parameters.verboseMode() ? loggingCallback_verbose : loggingCallback_default); AudioIO *sourceFile = NULL, *outputFile = NULL; if(!openFiles(parameters, &sourceFile, &outputFile)) { PRINT_ERR(TXT("Failed to open input and/or output file -> aborting!\n")); return EXIT_FAILURE; } FILE *logFile = NULL; if(parameters.dbgLogFile()) { if(!(logFile = FOPEN(parameters.dbgLogFile(), TXT("w")))) { PRINT_WRN(TXT("Failed to open log file -> No log file will be created!\n")); } } const clock_t clockStart = clock(); const int result = processFiles(parameters, sourceFile, outputFile, logFile); const double elapsed = double(clock() - clockStart) / double(CLOCKS_PER_SEC); sourceFile->close(); outputFile->close(); MY_DELETE(sourceFile); MY_DELETE(outputFile); if(logFile) { fclose(logFile); logFile = NULL; } PRINT(TXT("--------------\n\n")); PRINT(FMT_CHR TXT("\n\nOperation took %.1f seconds.\n\n"), ((result != EXIT_SUCCESS) ? TXT("Sorry, something went wrong :-(") : TXT("Everything completed successfully :-)")), elapsed); return result; } int mainEx(int argc, CHR* argv[]) { int exitCode = EXIT_SUCCESS; try { exitCode = dynamicNormalizerMain(argc, argv); } catch(std::exception &e) { PRINT(TXT("\n\nGURU MEDITATION: Unhandeled C++ exception error: ") FMT_chr TXT("\n\n"), e.what()); exitCode = EXIT_FAILURE; } catch(...) { PRINT(TXT("\n\nGURU MEDITATION: Unhandeled unknown C++ exception error!\n\n")); exitCode = EXIT_FAILURE; } return exitCode; } int MAIN(int argc, CHR* argv[]) { int exitCode = EXIT_SUCCESS; if(DYNAUDNORM_DEBUG) { SYSTEM_INIT(true); exitCode = dynamicNormalizerMain(argc, argv); } else { TRY_SEH { SYSTEM_INIT(false); exitCode = mainEx(argc, argv); } CATCH_SEH { PRINT(TXT("\n\nGURU MEDITATION: Unhandeled structured exception error!\n\n")); exitCode = EXIT_FAILURE; } } return exitCode; } ================================================ FILE: DynamicAudioNormalizerCLI/src/Parameters.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #include "Parameters.h" #include "AudioIO.h" #include /////////////////////////////////////////////////////////////////////////////// // Helper functions /////////////////////////////////////////////////////////////////////////////// #define IS_ARG_LONG(ARG_LONG) (STRCASECMP(argv[pos], TXT("--") TXT(ARG_LONG)) == 0) #define IS_ARG_SHRT(ARG_SHRT, ARG_LONG) ((STRCASECMP(argv[pos], TXT("-") TXT(ARG_SHRT)) == 0) || (STRCASECMP(argv[pos], TXT("--") TXT(ARG_LONG)) == 0)) #define ENSURE_NEXT_ARG() do \ { \ if(++pos >= argc) \ { \ PRINT2_WRN(TXT("Missing argument for option \"") FMT_CHR TXT("\".\n"), argv[pos-1]); \ return false; \ } \ } \ while(0) #define ENSURE_NEXT_ARGS(N) do \ { \ if(((pos++) + (N)) >= argc) \ { \ PRINT2_WRN(TXT("Missing argument(s) for option \"") FMT_CHR TXT("\".\n"), argv[pos-1]); \ return false; \ } \ } \ while(0) static bool STR_TO_FLT(double &output, const CHR *str) { double temp; if(SSCANF(str, TXT("%lf"), &temp) == 1) { output = temp; return true; } return false; } static bool STR_TO_UINT(uint32_t &output, const CHR *str) { uint32_t temp; if(SSCANF(str, TXT("%u"), &temp) == 1) { output = temp; return true; } return false; } #define PARSE_VALUE_FLT(OUT) do \ { \ if(!STR_TO_FLT((OUT), argv[pos])) \ { \ PRINT2_WRN(TXT("Failed to parse floating point value \"") FMT_CHR TXT("\"\n"), argv[pos]); \ return false; \ } \ } \ while(0) #define PARSE_VALUE_UINT(OUT) do \ { \ if(!STR_TO_UINT((OUT), argv[pos])) \ { \ PRINT2_WRN(TXT("Failed to parse unsigned integral value \"") FMT_CHR TXT("\"\n"), argv[pos]); \ return false; \ } \ } \ while(0) static bool CHECK_ENUM(const CHR *const str, const CHR *const *const values) { for (size_t i = 0; values[i]; ++i) { if (STRCASECMP(str, values[i]) == 0) { return true; } } return false; } static const CHR *JOIN_STR(CHR *const buffer, uint32_t buffSize, const CHR *const *const values, const CHR *const separator) { if (buffer && (buffSize > 0)) { buffer[0] = TXT('\0'); for (size_t i = 0; values[i]; ++i) { if (i > 0) { STRNCAT(buffer, separator, buffSize); } STRNCAT(buffer, values[i], buffSize); } } return buffer; } /////////////////////////////////////////////////////////////////////////////// // Parameters Class /////////////////////////////////////////////////////////////////////////////// Parameters::Parameters(void) { setDefaults(); } Parameters::~Parameters(void) { } void Parameters::setDefaults(void) { m_sourceFile = NULL; m_sourceLibrary = NULL; m_outputFile = NULL; m_outputFormat = NULL; m_dbgLogFile = NULL; m_frameLenMsec = 500; m_filterSize = 31; m_inputChannels = 0U; m_inputSampleRate = 0U; m_inputBitDepth = 0U; m_outputBitDepth = 0U; m_channelsCoupled = true; m_enableDCCorrection = false; m_altBoundaryMode = false; m_verboseMode = false; m_showHelp = false; m_peakValue = 0.95; m_maxAmplification = 10.00; m_targetRms = 0.00; m_compressFactor = 0.00; } bool Parameters::parseArgs(const int argc, CHR* argv[]) { int pos = 0; while(++pos < argc) { /*help screen*/ if(IS_ARG_SHRT("h", "help")) { m_showHelp = true; break; } /*input and output*/ if(IS_ARG_SHRT("i", "input")) { ENSURE_NEXT_ARG(); m_sourceFile = argv[pos]; continue; } if (IS_ARG_SHRT("d", "input-lib")) { ENSURE_NEXT_ARG(); m_sourceLibrary = argv[pos]; continue; } if(IS_ARG_SHRT("o", "output")) { ENSURE_NEXT_ARG(); m_outputFile = argv[pos]; continue; } if (IS_ARG_SHRT("t", "output-fmt")) { ENSURE_NEXT_ARG(); m_outputFormat = argv[pos]; continue; } if (IS_ARG_SHRT("u", "output-bps")) { ENSURE_NEXT_ARG(); PARSE_VALUE_UINT(m_outputBitDepth); continue; } /*algorithm twekas*/ if(IS_ARG_SHRT("f", "frame-len")) { ENSURE_NEXT_ARG(); PARSE_VALUE_UINT(m_frameLenMsec); continue; } if(IS_ARG_SHRT("g", "gauss-size")) { ENSURE_NEXT_ARG(); PARSE_VALUE_UINT(m_filterSize); continue; } if(IS_ARG_SHRT("p", "peak")) { ENSURE_NEXT_ARG(); PARSE_VALUE_FLT(m_peakValue); continue; } if(IS_ARG_SHRT("m", "max-gain")) { ENSURE_NEXT_ARG(); PARSE_VALUE_FLT(m_maxAmplification); continue; } if(IS_ARG_SHRT("r", "target-rms")) { ENSURE_NEXT_ARG(); PARSE_VALUE_FLT(m_targetRms); continue; } if(IS_ARG_SHRT("s", "compress")) { ENSURE_NEXT_ARG(); PARSE_VALUE_FLT(m_compressFactor); continue; } if(IS_ARG_SHRT("n", "no-coupling")) { m_channelsCoupled = false; continue; } if(IS_ARG_SHRT("c", "correct-dc")) { m_enableDCCorrection = true; continue; } if(IS_ARG_SHRT("b", "alt-boundary")) { m_altBoundaryMode = true; continue; } /*diagnostics*/ if(IS_ARG_SHRT("l", "log-file")) { ENSURE_NEXT_ARG(); m_dbgLogFile = argv[pos]; continue; } if(IS_ARG_SHRT("v", "verbose")) { m_verboseMode = true; continue; } /*raw input options*/ if(IS_ARG_LONG("input-chan")) { ENSURE_NEXT_ARG(); PARSE_VALUE_UINT(m_inputChannels); continue; } if(IS_ARG_LONG("input-rate")) { ENSURE_NEXT_ARG(); PARSE_VALUE_UINT(m_inputSampleRate); continue; } if(IS_ARG_LONG("input-bits")) { ENSURE_NEXT_ARG(); PARSE_VALUE_UINT(m_inputBitDepth); continue; } PRINT2_WRN(TXT("Unknown command-line argument \"") FMT_CHR TXT("\"\n"), argv[pos]); return false; } if((!m_showHelp) && (pos < argc)) { PRINT2_WRN(TXT("Excess command-line argument \"") FMT_CHR TXT("\"\n"), argv[pos]); return false; } return m_showHelp || validateParameters(); } bool Parameters::validateParameters(void) { if(!m_sourceFile) { PRINT_WRN(TXT("Input file not specified!\n")); return false; } if(!m_outputFile) { PRINT_WRN(TXT("Output file not specified!\n")); return false; } /*validate input library*/ if (m_sourceLibrary) { const CHR *supportedLibraries[8]; if (!CHECK_ENUM(m_sourceLibrary, AudioIO::getSupportedLibraries(supportedLibraries, 8))) { CHR allLibraries[128]; PRINT2_WRN(TXT("Unknown input library \"") FMT_CHR TXT("\" specified!\nSupported libraries include: ") FMT_CHR TXT("\n"), m_sourceLibrary, JOIN_STR(allLibraries, 128, supportedLibraries, TXT(", "))); return false; } } /*validate output format*/ if(m_outputFormat) { const CHR *supportedFormats[32]; if (!CHECK_ENUM(m_outputFormat, AudioIO::getSupportedFormats(supportedFormats, 32))) { CHR allFormats[256]; PRINT2_WRN(TXT("Unknown output format \"") FMT_CHR TXT("\" specified!\nSupported formats include: ") FMT_CHR TXT("\n"), m_outputFormat, JOIN_STR(allFormats, 256, supportedFormats, TXT(", "))); return false; } } /*validate output bit-depth*/ if (m_outputBitDepth) { if((m_outputBitDepth != 8U) && (m_outputBitDepth != 16U) && (m_outputBitDepth != 24U) && (m_outputBitDepth != 32U)) { PRINT2_WRN(TXT("Invalid output bit-depth %u specified!\nSupported bit-depth include: 8, 16, 24 and 32 bits/sample\n"), m_outputBitDepth); return false; } } /*check input file*/ if(STRCASECMP(m_sourceFile, TXT("-")) != 0) { if(ACCESS(m_sourceFile, R_OK) != 0) { if(errno != ENOENT) { PRINT_WRN(TXT("Selected input file can not be read!\n")); } else { PRINT_WRN(TXT("Selected input file does not exist!\n")); } return false; } } /*check output file*/ if(STRCASECMP(m_outputFile, TXT("-")) != 0) { if(ACCESS(m_outputFile, W_OK) != 0) { if(errno != ENOENT) { PRINT_WRN(TXT("Selected output file is read-only!\n")); return false; } } } /*check input properties for raw data*/ if((STRCASECMP(m_sourceFile, TXT("-")) == 0) && (!FD_ISREG(FILENO(stdin)))) { if((m_inputChannels == 0) || (m_inputSampleRate == 0) || (m_inputBitDepth == 0)) { PRINT2_WRN(TXT("Channel-count, sample-rate and bit-depth *must* be specified for pipe'd input!\n"), m_filterSize); return false; } } else { if((m_inputChannels != 0) || (m_inputSampleRate != 0) || (m_inputBitDepth != 0)) { PRINT2_WRN(TXT("Channel-count, sample-rate and bit-depth will be *ignored* for file source!\n"), m_filterSize); } } /*parameter range checking*/ if((m_filterSize < 3) || (m_filterSize > 301)) { PRINT2_WRN(TXT("Filter size %u is out of range. Must be in the 3 to 301 range!\n"), m_filterSize); return false; } if((m_filterSize % 2) != 1) { PRINT2_WRN(TXT("Filter size %u is invalid. Must be an odd value! (i.e. 'filter_size mod 2 == 1')\n"), m_filterSize); return false; } if((m_peakValue < 0.01) || (m_peakValue > 1.0)) { PRINT2_WRN(TXT("Peak value value %.2f is out of range. Must be in the 0.01 to 1.00 range!\n"), m_peakValue); return false; } if((m_targetRms < 0.0) || (m_targetRms > 1.0)) { PRINT2_WRN(TXT("Target RMS value %.2f is out of range. Must be in the 0.00 to 1.00 range!\n"), m_targetRms); return false; } if((m_compressFactor && (m_compressFactor < 1.0)) || (m_compressFactor > 30.0)) { PRINT2_WRN(TXT("Compression threshold value %.2f is out of range. Must be in the 1.00 to 30.00 range!\n"), m_compressFactor); return false; } if((m_maxAmplification < 1.0) || (m_maxAmplification > 100.0)) { PRINT2_WRN(TXT("Maximum amplification %.2f is out of range. Must be in the 1.00 to 100.00 range!\n"), m_maxAmplification); return false; } if((m_frameLenMsec < 10) || (m_frameLenMsec > 8000)) { PRINT2_WRN(TXT("Frame length %u is out of range. Must be in the 10 to 8000 range!\n"), m_frameLenMsec); return false; } return true; } ================================================ FILE: DynamicAudioNormalizerCLI/src/Parameters.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #include "Common.h" #include "Platform.h" class Parameters { public: Parameters(void); ~Parameters(void); bool parseArgs(const int argc, CHR* argv[]); inline const CHR* sourceFile(void) const { return m_sourceFile; } inline const CHR* sourceLibrary(void) const { return m_sourceLibrary; } inline const CHR* outputFile(void) const { return m_outputFile; } inline const CHR* outputFormat(void) const { return m_outputFormat; } inline const CHR* dbgLogFile(void) const { return m_dbgLogFile; } inline const uint32_t &frameLenMsec(void) const { return m_frameLenMsec; } inline const uint32_t &filterSize(void) const { return m_filterSize; } inline const uint32_t &inputChannels(void) const { return m_inputChannels; } inline const uint32_t &inputSampleRate(void) const { return m_inputSampleRate; } inline const uint32_t &inputBitDepth(void) const { return m_inputBitDepth; } inline const uint32_t &outputBitDepth(void) const { return m_outputBitDepth; } inline const double &peakValue(void) const { return m_peakValue; } inline const double &maxAmplification(void) const { return m_maxAmplification; } inline const double &targetRms(void) const { return m_targetRms; } inline const double &compressFactor(void) const { return m_compressFactor; } inline const bool &channelsCoupled(void) const { return m_channelsCoupled; } inline const bool &enableDCCorrection(void) const { return m_enableDCCorrection; } inline const bool &altBoundaryMode(void) const { return m_altBoundaryMode; } inline const bool &showHelp(void) const { return m_showHelp; } inline const bool &verboseMode(void) const { return m_verboseMode; } protected: void setDefaults(void); bool validateParameters(void); private: const CHR* m_sourceFile; const CHR* m_sourceLibrary; const CHR* m_outputFile; const CHR* m_outputFormat; const CHR* m_dbgLogFile; uint32_t m_frameLenMsec; uint32_t m_filterSize; uint32_t m_inputChannels; uint32_t m_inputSampleRate; uint32_t m_inputBitDepth; uint32_t m_outputBitDepth; bool m_channelsCoupled; bool m_enableDCCorrection; bool m_altBoundaryMode; bool m_verboseMode; bool m_showHelp; double m_peakValue; double m_maxAmplification; double m_targetRms; double m_compressFactor; }; ================================================ FILE: DynamicAudioNormalizerCLI/src/Platform.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #ifdef _DYNAUDNORM_PLATFORM_SUPPORT #undef _DYNAUDNORM_PLATFORM_SUPPORT #endif #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS #endif #include #include #include #include #include #include #include //============================================================================ // WINDOWS | MSVC //============================================================================ #if defined(_WIN32) && defined(_MSC_VER) /*Windows MSVC only*/ #ifndef _DYNAUDNORM_PLATFORM_SUPPORT #define _DYNAUDNORM_PLATFORM_SUPPORT 1 #else #error Whoops, more than one platform has been detected! #endif #include #include #define _TXT(X) L##X #define TXT(X) _TXT(X) #define OS_TYPE TXT("Win") #define FMT_CHR TXT("%s") #define FMT_chr TXT("%S") #define MAIN wmain #define TRY_SEH __try #define CATCH_SEH __except(1) #define F_OK 0 #define X_OK 1 #define W_OK 2 #define R_OK 4 typedef wchar_t CHR; typedef struct _stat64 STAT64_T; inline static int PRINT(const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vfwprintf_s(stderr, format, ap); va_end(ap); return result; } inline static int PUTS(const CHR *const format) { return fputws(format, stderr); } inline static void FLUSH(void) { fflush(stderr); } inline static FILE *FOPEN(const CHR *const fileName, const CHR *const mode) { FILE *temp; if(_wfopen_s(&temp, fileName, mode) == 0) { return temp; } return NULL; } inline static int OPEN(const CHR *const fileName, const int flags) { int temp; if (_wsopen_s(&temp, fileName, _O_BINARY | flags, _SH_DENYWR, 0) == 0) { return temp; } return -1; } inline static int CLOSE(const int fd) { return _close(fd); } inline static int FILENO(FILE *const file) { return _fileno(file); } inline static int FSTAT64(const int fd, STAT64_T *stat) { return _fstat64(fd, stat); } inline static int FSEEK64(FILE *const file, int64_t offset, const int origin) { return _fseeki64(file, offset, origin); } inline static int64_t FTELL64(FILE *const file) { return _ftelli64(file); } inline static int ACCESS(const CHR *const fileName, const int mode) { return _waccess(fileName, mode); } inline static int STAT64(const CHR *const fileName, STAT64_T *stat) { return _wstat64(fileName, stat); } inline static int STRCASECMP(const CHR *const s1, const CHR *const s2) { return _wcsicmp(s1, s2); } inline static const CHR *STRCHR(const CHR *const str, const CHR c) { return wcschr(str, c); } inline static const CHR *STRRCHR(const CHR *const str, const CHR c) { return wcsrchr(str, c); } inline static int SNPRINTF(CHR *const buffer, size_t buffSize, const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = _vsnwprintf_s(buffer, buffSize, _TRUNCATE, format, ap); va_end(ap); return result; } inline static int SSCANF(const CHR *const str, const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vswscanf(str, format, ap); va_end(ap); return result; } inline static const CHR *STRNCAT(CHR *const buff, const CHR *const str, const uint32_t len) { wcsncat_s(buff, len, str, _TRUNCATE); return buff; } #endif //_WIN32 //============================================================================ // WINDOWS | MINGW //============================================================================ #if defined(_WIN32) && defined(__MINGW32__) /*Windows MinGW only*/ #ifndef _DYNAUDNORM_PLATFORM_SUPPORT #define _DYNAUDNORM_PLATFORM_SUPPORT 1 #else #error Whoops, more than one platform has been detected! #endif #include #define _TXT(X) L##X #define TXT(X) _TXT(X) #define OS_TYPE TXT("Win") #define FMT_CHR TXT("%ls") #define FMT_chr TXT("%s") #define MAIN wmain #define TRY_SEH if(1) #define CATCH_SEH else #define F_OK 0 #define X_OK 1 #define W_OK 2 #define R_OK 4 typedef wchar_t CHR; typedef struct _stati64 STAT64_T; inline static int PRINT(const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vfwprintf(stderr, format, ap); va_end(ap); return result; } inline static void FLUSH(void) { fflush(stderr); } inline static FILE *FOPEN(const CHR *const fileName, const CHR *const mode) { return _wfopen(fileName, mode); } inline static int FILENO(FILE *const file) { return _fileno(file); } inline static int FSTAT64(const int fd, STAT64_T *stat) { return _fstati64(fd, stat); } inline static int FSEEK64(FILE *const file, int64_t offset, const int origin) { return fseeko64(file, offset, origin); //__mingw_fseeko64(file, offset, origin) } inline static int64_t FTELL64(FILE *const file) { return ftello64(file); } inline static int ACCESS(const CHR *const fileName, const int mode) { return _waccess(fileName, mode); } inline static int STAT64(const CHR *const fileName, STAT64_T *stat) { return _wstati64(fileName, stat); } inline static int STRCASECMP(const CHR *const s1, const CHR *const s2) { return _wcsicmp(s1, s2); } inline static const CHR *STRCHR(const CHR *const str, const CHR c) { return wcschr(str, c); } inline static const CHR *STRRCHR(const CHR *const str, const CHR c) { return wcsrchr(str, c); } inline static int SNPRINTF(CHR *const buffer, size_t buffSize, const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = _vsnwprintf(buffer, buffSize, format, ap); buffer[buffSize-1] = 0x00; va_end(ap); return result; } inline static int SSCANF(const CHR *const str, const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vswscanf(str, format, ap); va_end(ap); return result; } inline static const CHR *STRNCAT(CHR *const buff, const CHR *const str, const uint32_t len) { const size_t offset = wcslen(buffer); if (len >= 1) { return wcsncat(buff, str, len - offset - 1); } return buff; } #endif //_WIN32 //============================================================================ // LINUX //============================================================================ #ifdef __linux /*Linux only*/ #ifndef _DYNAUDNORM_PLATFORM_SUPPORT #define _DYNAUDNORM_PLATFORM_SUPPORT 1 #else #error Whoops, more than one platform has been detected! #endif #include #define _TXT(X) X #define TXT(X) _TXT(X) #define OS_TYPE TXT("Linux") #define FMT_CHR TXT("%s") #define FMT_chr TXT("%s") #define MAIN main #define TRY_SEH if(1) #define CATCH_SEH else typedef char CHR; typedef struct stat64 STAT64_T; inline static int PRINT(const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vfprintf(stderr, format, ap); va_end(ap); return result; } inline static void FLUSH(void) { fflush(stderr); } inline static FILE *FOPEN(const CHR *const fileName, const CHR *const mode) { return fopen(fileName, mode); } inline static int FILENO(FILE *const file) { return fileno(file); } inline static int FSTAT64(const int fd, STAT64_T *stat) { return fstat64(fd, stat); } inline static int FSEEK64(FILE *const file, int64_t offset, const int origin) { return fseeko64(file, offset, origin); } inline static int64_t FTELL64(FILE *const file) { return ftello64(file); } inline static int ACCESS(const CHR *const fileName, const int mode) { return access(fileName, mode); } inline static int STAT64(const CHR *const fileName, STAT64_T *stat) { return stat64(fileName, stat); } inline static int STRCASECMP(const CHR *const s1, const CHR *const s2) { return strcasecmp(s1, s2); } inline static const CHR *STRCHR(const CHR *const str, const CHR c) { return strchr(str, c); } inline static const CHR *STRRCHR(const CHR *const str, const CHR c) { return strrchr(str, c); } inline static int SNPRINTF(CHR *const buffer, size_t buffSize, const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vsnprintf(buffer, buffSize, format, ap); va_end(ap); return result; } inline static int SSCANF(const CHR *const str, const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vsscanf(str, format, ap); va_end(ap); return result; } inline static const CHR *STRNCAT(CHR *const buff, const CHR *const str, const uint32_t len) { const size_t offset = strlen(buff); if (len >= 1) { return strncat(buff, str, len - offset - 1); } return buff; } #endif //__linux //============================================================================ // OS X //============================================================================ #ifdef __APPLE__ // OS X #ifndef _DYNAUDNORM_PLATFORM_SUPPORT #define _DYNAUDNORM_PLATFORM_SUPPORT 1 #else #error Whoops, more than one platform has been detected! #endif #include #define _TXT(X) X #define TXT(X) _TXT(X) #define OS_TYPE TXT("OS X") #define FMT_CHR TXT("%s") #define FMT_chr TXT("%s") #define MAIN main #define TRY_SEH if(1) #define CATCH_SEH else typedef char CHR; typedef struct stat STAT64_T; inline static int PRINT(const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vfprintf(stderr, format, ap); va_end(ap); return result; } inline static void FLUSH(void) { fflush(stderr); } inline static FILE *FOPEN(const CHR *const fileName, const CHR *const mode) { return fopen(fileName, mode); } inline static int FILENO(FILE *const file) { return fileno(file); } inline static int FSTAT64(const int fd, STAT64_T *_stat) { return fstat(fd, _stat); } inline static int FSEEK64(FILE *const file, int64_t offset, const int origin) { return fseeko(file, offset, origin); } inline static int64_t FTELL64(FILE *const file) { return ftello(file); } inline static int ACCESS(const CHR *const fileName, const int mode) { return access(fileName, mode); } inline static int STAT64(const CHR *const fileName, STAT64_T *stat) { return stat64(fileName, stat); } inline static int STRCASECMP(const CHR *const s1, const CHR *const s2) { return strcasecmp(s1, s2); } inline static const CHR *STRCHR(const CHR *const str, const CHR c) { return strchr(str, c); } inline static const CHR *STRRCHR(const CHR *const str, const CHR c) { return strrchr(str, c); } inline static int SNPRINTF(CHR *const buffer, size_t buffSize, const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vsnprintf(buffer, buffSize, format, ap); va_end(ap); return result; } inline static int SSCANF(const CHR *const str, const CHR *const format, ...) { va_list ap; va_start(ap, format); const int result = vsscanf(str, format, ap); va_end(ap); return result; } inline static const CHR *STRNCAT(CHR *const buff, const CHR *const str, const uint32_t len) { const size_t offset = strlen(buff); if (len >= 1) { return strncat(buff, str, len - offset - 1); } return buff; } #endif // __APPLE__ //============================================================================ // COMMON //============================================================================ void SYSTEM_INIT(const bool &debugMode); #define PRINT_NFO(X) do { PUTS(TXT("INFO: ") X TXT("\n")); } while(0) #define PRINT_WRN(X) do { PUTS(TXT("WARNING: ") X TXT("\n")); } while(0) #define PRINT_ERR(X) do { PUTS(TXT("ERROR: ") X TXT("\n")); } while(0) #define PRINT2_NFO(X, ...) do { PRINT(TXT("INFO: ") X TXT("\n"), __VA_ARGS__); } while(0) #define PRINT2_WRN(X, ...) do { PRINT(TXT("WARNING: ") X TXT("\n"), __VA_ARGS__); } while(0) #define PRINT2_ERR(X, ...) do { PRINT(TXT("ERROR: ") X TXT("\n"), __VA_ARGS__); } while(0) inline static bool FD_ISREG(const int fd) { STAT64_T _stat; if (FSTAT64(fd, &_stat) == 0) { return ((_stat.st_mode & S_IFMT) == S_IFREG); } return false; } inline static bool PATH_ISREG(const CHR *const fileName) { STAT64_T _stat; if (STAT64(fileName, &_stat) == 0) { return ((_stat.st_mode & S_IFMT) == S_IFREG); } return false; } //============================================================================ // VALIDATION //============================================================================ /*make sure one platform has been initialized!*/ #if !(defined(_DYNAUDNORM_PLATFORM_SUPPORT) && _DYNAUDNORM_PLATFORM_SUPPORT) #error This platform is *not* currently supported! #endif ================================================ FILE: DynamicAudioNormalizerCLI/src/Platform_Linux.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #include "Platform.h" #ifdef __linux #pragma GCC diagnostic ignored "-Wunused-result" #include #include static void my_crash_handler(const char *const message) { try { write(STDERR_FILENO, message, strlen(message)); fsync(STDERR_FILENO); } catch(...) { /*ignore any exception*/ } for(;;) { _exit(666); } } static void my_signal_handler(int signal_num) { if(signal_num != SIGINT) { my_crash_handler("\n\nGURU MEDITATION: Signal handler has been invoked, application will exit!\n\n"); } else { my_crash_handler("\n\nGURU MEDITATION: Operation has been interrupted, application will exit!\n\n"); } } void SYSTEM_INIT(const bool &debugMode) { static const int signal_num[6] = { SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM }; if(!debugMode) { for(size_t i = 0; i < 6; i++) { struct sigaction sa; sa.sa_handler = my_signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sigaction(signal_num[i], &sa, NULL); } } } #endif //__linux ================================================ FILE: DynamicAudioNormalizerCLI/src/Platform_OSX.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #include "Platform.h" #ifdef __APPLE__ #pragma GCC diagnostic ignored "-Wunused-result" #include #include static void my_crash_handler(const char *const message) { try { write(STDERR_FILENO, message, strlen(message)); fsync(STDERR_FILENO); } catch(...) { /*ignore any exception*/ } for(;;) { _exit(666); } } static void my_signal_handler(int signal_num) { if(signal_num != SIGINT) { my_crash_handler("\n\nGURU MEDITATION: Signal handler has been invoked, application will exit!\n\n"); } else { my_crash_handler("\n\nGURU MEDITATION: Operation has been interrupted, application will exit!\n\n"); } } void SYSTEM_INIT(const bool &debugMode) { static const int signal_num[6] = { SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM }; if(!debugMode) { for(size_t i = 0; i < 6; i++) { struct sigaction sa; sa.sa_handler = my_signal_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; sigaction(signal_num[i], &sa, NULL); } } } #endif // __APPLE__ ================================================ FILE: DynamicAudioNormalizerCLI/src/Platform_Win32.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // http://www.gnu.org/licenses/gpl-2.0.txt ////////////////////////////////////////////////////////////////////////////////// #include "Platform.h" #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include #include #include #include #ifdef __MINGW32__ extern "C" { typedef struct { int newmode; } _startupinfo; int __cdecl __declspec(dllimport) __wgetmainargs (int *_Argc, wchar_t ***_Argv, wchar_t ***_Env, int _DoWildCard, _startupinfo * _StartInfo); int wmain(int argc, CHR* argv[]); } #endif //__MINGW32__ static void my_crash_handler(const char *const message) { TRY_SEH { DWORD bytesWritten; if(HANDLE hStdErr = GetStdHandle(STD_ERROR_HANDLE)) { WriteFile(hStdErr, message, lstrlenA(message), &bytesWritten, NULL); FlushFileBuffers(hStdErr); } } CATCH_SEH { /*ignore any exception that might occur in crash handler*/ } for(;;) { TerminateProcess(GetCurrentProcess(), 666); } } static void my_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t) { my_crash_handler("\n\nGURU MEDITATION: Invalid parameter handler invoked, application will exit!\n\n"); } static void my_signal_handler(int signal_num) { signal(signal_num, my_signal_handler); if(signal_num != SIGINT) { my_crash_handler("\n\nGURU MEDITATION: Signal handler has been invoked, application will exit!\n\n"); } else { my_crash_handler("\n\nGURU MEDITATION: Operation has been interrupted, application will exit!\n\n"); } } static LONG WINAPI my_exception_handler(struct _EXCEPTION_POINTERS*) { my_crash_handler("\n\nGURU MEDITATION: Unhandeled exception handler invoked, application will exit!\n"); return EXCEPTION_EXECUTE_HANDLER; } void SYSTEM_INIT(const bool &debugMode) { static const int signal_num[6] = { SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM }; if(!debugMode) { SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); SetUnhandledExceptionFilter(my_exception_handler); _set_invalid_parameter_handler(my_invalid_param_handler); for(size_t i = 0; i < 6; i++) { signal(signal_num[i], my_signal_handler); } } SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); _setmode(_fileno(stdin ), _O_BINARY); _setmode(_fileno(stdout), _O_BINARY); } //MinGW does *not* provide a proper wmain() entry point, so we have to emulate it here! #ifdef __MINGW32__ int main() { int argc; wchar_t **argv_wide, **envp_wide; _startupinfo startup = { 0 }; if(__wgetmainargs(&argc, &argv_wide, &envp_wide, 0, &startup) != 0) { abort(); } return wmain(argc, argv_wide); } #endif //__MINGW32__ #endif //_WIN32 ================================================ FILE: DynamicAudioNormalizerGUI/DynamicAudioNormalizerGUI.qrc ================================================ res/chart_curve.png ================================================ FILE: DynamicAudioNormalizerGUI/DynamicAudioNormalizerGUI_VS2013.vcxproj ================================================  Debug Win32 Release_DLL Win32 Release_Static Win32 "$(QTDIR)\bin\moc.exe" -o "$(ProjectDir)tmp\MOC_%(Filename).cpp" "%(FullPath)" MOC "$(ProjectDir)tmp\MOC_%(Filename).cpp" "$(QTDIR)\bin\moc.exe" -o "$(ProjectDir)tmp\MOC_%(Filename).cpp" "%(FullPath)" "$(QTDIR)\bin\moc.exe" -o "$(ProjectDir)tmp\MOC_%(Filename).cpp" "%(FullPath)" MOC "$(ProjectDir)tmp\MOC_%(Filename).cpp" MOC "$(ProjectDir)tmp\MOC_%(Filename).cpp" $(ProjectDir)tmp\MOC_%(Filename).cpp;%(Outputs) $(ProjectDir)tmp\MOC_%(Filename).cpp;%(Outputs) $(ProjectDir)tmp\MOC_%(Filename).cpp;%(Outputs) RES Document "$(QTDIR)\bin\rcc.exe" -o "$(ProjectDir)tmp\QRC_%(Filename).cpp" -name "%(Filename)" "%(FullPath)" RCC "$(ProjectDir)tmp\QRC_%(Filename).cpp" $(ProjectDir)tmp\QRC_%(Filename).cpp;%(Outputs) "$(QTDIR)\bin\rcc.exe" -o "$(ProjectDir)tmp\QRC_%(Filename).cpp" -name "%(Filename)" "%(FullPath)" RCC "$(ProjectDir)tmp\QRC_%(Filename).cpp" $(ProjectDir)tmp\QRC_%(Filename).cpp;%(Outputs) "$(QTDIR)\bin\rcc.exe" -o "$(ProjectDir)tmp\QRC_%(Filename).cpp" -name "%(Filename)" "%(FullPath)" RCC "$(ProjectDir)tmp\QRC_%(Filename).cpp" $(ProjectDir)tmp\QRC_%(Filename).cpp;%(Outputs) {376386ee-8268-47e3-a335-7663716e4c60} true true false true false {131C921A-7144-4C1D-9C97-57C43FA83DFE} Win32Proj DynamicAudioNormalizerGUI DynamicAudioNormalizerGUI Application true v120_xp Unicode Application false v120_xp true Unicode Application false v120_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ Level3 Disabled WIN32;_DEBUG;_CONSOLE;_LIB;QT_GUI_LIB;QT_CORE_LIB;QT_THREAD_SUPPORT;QT_DLL;QT_DEBUG;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(QTDIR)\include;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGUI NoExtensions MultiThreadedDebugDLL Windows true $(SolutionDir)\..\Prerequisites\Qt4\$(PlatformToolset)\Debug\lib QtCored4.lib;QtGuid4.lib;%(AdditionalDependencies) win32EntryPoint LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;QT_GUI_LIB;QT_CORE_LIB;QT_THREAD_SUPPORT;QT_DLL;QT_NO_DEBUG;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(QTDIR)\include;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGUI AnySuitable Speed true false StreamingSIMDExtensions2 MultiThreadedDLL Fast Windows false true true $(SolutionDir)\..\Prerequisites\Qt4\$(PlatformToolset)\Shared\lib QtCore4.lib;QtGui4.lib;%(AdditionalDependencies) win32EntryPoint win32EntryPoint win32EntryPoint win32EntryPoint win32EntryPoint win32EntryPoint LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;QT_GUI_LIB;QT_CORE_LIB;QT_THREAD_SUPPORT;QT_NODLL;QT_NO_DEBUG;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(QTDIR)\include;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGUI MultiThreaded AnySuitable Speed true false StreamingSIMDExtensions2 true Fast Windows false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\Win32\static;$(SolutionDir)\..\Prerequisites\Qt4\$(PlatformToolset)\Static\lib QtCore.lib;QtGui.lib;Imm32.lib;Winmm.lib;Ws2_32.lib;%(AdditionalDependencies) win32EntryPoint LinkVerboseLib ================================================ FILE: DynamicAudioNormalizerGUI/DynamicAudioNormalizerGUI_VS2013.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {2f1efda3-3e92-4158-960c-40e4ceaf03ba} {7867be34-0625-4766-8937-eb65d6ae1533} Source Files Source Files\3rd Party Sources Source Files\Generated Files Source Files Source Files\Generated Files Header Files Resource Files ================================================ FILE: DynamicAudioNormalizerGUI/DynamicAudioNormalizerGUI_VS2015.vcxproj ================================================  Debug Win32 Release_DLL Win32 Release_Static Win32 "$(QTDIR)\bin\moc.exe" -o "$(ProjectDir)tmp\MOC_%(Filename).cpp" "%(FullPath)" MOC "$(ProjectDir)tmp\MOC_%(Filename).cpp" "$(QTDIR)\bin\moc.exe" -o "$(ProjectDir)tmp\MOC_%(Filename).cpp" "%(FullPath)" "$(QTDIR)\bin\moc.exe" -o "$(ProjectDir)tmp\MOC_%(Filename).cpp" "%(FullPath)" MOC "$(ProjectDir)tmp\MOC_%(Filename).cpp" MOC "$(ProjectDir)tmp\MOC_%(Filename).cpp" $(ProjectDir)tmp\MOC_%(Filename).cpp;%(Outputs) $(ProjectDir)tmp\MOC_%(Filename).cpp;%(Outputs) $(ProjectDir)tmp\MOC_%(Filename).cpp;%(Outputs) RES Document "$(QTDIR)\bin\rcc.exe" -o "$(ProjectDir)tmp\QRC_%(Filename).cpp" -name "%(Filename)" "%(FullPath)" RCC "$(ProjectDir)tmp\QRC_%(Filename).cpp" $(ProjectDir)tmp\QRC_%(Filename).cpp;%(Outputs) "$(QTDIR)\bin\rcc.exe" -o "$(ProjectDir)tmp\QRC_%(Filename).cpp" -name "%(Filename)" "%(FullPath)" RCC "$(ProjectDir)tmp\QRC_%(Filename).cpp" $(ProjectDir)tmp\QRC_%(Filename).cpp;%(Outputs) "$(QTDIR)\bin\rcc.exe" -o "$(ProjectDir)tmp\QRC_%(Filename).cpp" -name "%(Filename)" "%(FullPath)" RCC "$(ProjectDir)tmp\QRC_%(Filename).cpp" $(ProjectDir)tmp\QRC_%(Filename).cpp;%(Outputs) {376386ee-8268-47e3-a335-7663716e4c60} true true false true false {131C921A-7144-4C1D-9C97-57C43FA83DFE} Win32Proj DynamicAudioNormalizerGUI DynamicAudioNormalizerGUI Application true v140_xp Unicode Application false v140_xp true Unicode Application false v140_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ Level3 Disabled WIN32;_DEBUG;_CONSOLE;_LIB;QT_GUI_LIB;QT_CORE_LIB;QT_THREAD_SUPPORT;QT_DLL;QT_DEBUG;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(QTDIR)\include;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGUI NoExtensions MultiThreadedDebugDLL Windows true $(SolutionDir)\..\Prerequisites\Qt4\$(PlatformToolset)\Debug\lib QtCored4.lib;QtGuid4.lib;%(AdditionalDependencies) win32EntryPoint LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;QT_GUI_LIB;QT_CORE_LIB;QT_THREAD_SUPPORT;QT_DLL;QT_NO_DEBUG;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(QTDIR)\include;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGUI AnySuitable Speed true false StreamingSIMDExtensions2 MultiThreadedDLL Fast Windows false true true $(SolutionDir)\..\Prerequisites\Qt4\$(PlatformToolset)\Shared\lib QtCore4.lib;QtGui4.lib;%(AdditionalDependencies) win32EntryPoint win32EntryPoint win32EntryPoint win32EntryPoint win32EntryPoint win32EntryPoint LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_CONSOLE;_LIB;QT_GUI_LIB;QT_CORE_LIB;QT_THREAD_SUPPORT;QT_NODLL;QT_NO_DEBUG;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(QTDIR)\include;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGUI MultiThreaded AnySuitable Speed true false StreamingSIMDExtensions2 true Fast Windows false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\Win32\static;$(SolutionDir)\..\Prerequisites\Qt4\$(PlatformToolset)\Static\lib QtCore.lib;QtGui.lib;Imm32.lib;Winmm.lib;Ws2_32.lib;%(AdditionalDependencies) win32EntryPoint LinkVerboseLib ================================================ FILE: DynamicAudioNormalizerGUI/DynamicAudioNormalizerGUI_VS2015.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {2f1efda3-3e92-4158-960c-40e4ceaf03ba} {7867be34-0625-4766-8937-eb65d6ae1533} Source Files Source Files\3rd Party Sources Source Files\Generated Files Source Files Source Files\Generated Files Header Files Resource Files ================================================ FILE: DynamicAudioNormalizerGUI/DynamicAudioNormalizerGUI_VS2017.vcxproj ================================================  Debug Win32 Release_DLL Win32 Release_Static Win32 "$(QTDIR)\bin\moc.exe" -o "$(ProjectDir)tmp\MOC_%(Filename).cpp" "%(FullPath)" MOC "$(ProjectDir)tmp\MOC_%(Filename).cpp" "$(QTDIR)\bin\moc.exe" -o "$(ProjectDir)tmp\MOC_%(Filename).cpp" "%(FullPath)" "$(QTDIR)\bin\moc.exe" -o "$(ProjectDir)tmp\MOC_%(Filename).cpp" "%(FullPath)" MOC "$(ProjectDir)tmp\MOC_%(Filename).cpp" MOC "$(ProjectDir)tmp\MOC_%(Filename).cpp" $(ProjectDir)tmp\MOC_%(Filename).cpp;%(Outputs) $(ProjectDir)tmp\MOC_%(Filename).cpp;%(Outputs) $(ProjectDir)tmp\MOC_%(Filename).cpp;%(Outputs) Document "$(QTDIR)\bin\rcc.exe" -o "$(ProjectDir)tmp\QRC_%(Filename).cpp" -name "%(Filename)" "%(FullPath)" RCC "$(ProjectDir)tmp\QRC_%(Filename).cpp" $(ProjectDir)tmp\QRC_%(Filename).cpp;%(Outputs) "$(QTDIR)\bin\rcc.exe" -o "$(ProjectDir)tmp\QRC_%(Filename).cpp" -name "%(Filename)" "%(FullPath)" RCC "$(ProjectDir)tmp\QRC_%(Filename).cpp" $(ProjectDir)tmp\QRC_%(Filename).cpp;%(Outputs) "$(QTDIR)\bin\rcc.exe" -o "$(ProjectDir)tmp\QRC_%(Filename).cpp" -name "%(Filename)" "%(FullPath)" RCC "$(ProjectDir)tmp\QRC_%(Filename).cpp" $(ProjectDir)tmp\QRC_%(Filename).cpp;%(Outputs) {376386ee-8268-47e3-a335-7663716e4c60} true true false true false {131C921A-7144-4C1D-9C97-57C43FA83DFE} Win32Proj DynamicAudioNormalizerGUI DynamicAudioNormalizerGUI 8.1 Application true v141_xp Unicode Application false v141_xp true Unicode Application false v141_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ Level3 Disabled WIN32;_DEBUG;_CONSOLE;_LIB;QT_GUI_LIB;QT_CORE_LIB;QT_THREAD_SUPPORT;QT_DLL;QT_DEBUG;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(QTDIR)\include;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGUI NoExtensions MultiThreadedDebugDLL Windows true $(SolutionDir)\..\Prerequisites\Qt4\$(PlatformToolset)\Debug\lib QtCored4.lib;QtGuid4.lib;%(AdditionalDependencies) win32EntryPoint LinkVerboseLib Level3 MinSpace true true WIN32;NDEBUG;_CONSOLE;_LIB;QT_GUI_LIB;QT_CORE_LIB;QT_THREAD_SUPPORT;QT_DLL;QT_NO_DEBUG;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(QTDIR)\include;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGUI Default Size true false StreamingSIMDExtensions2 MultiThreadedDLL Fast false Windows false true true $(SolutionDir)\..\Prerequisites\Qt4\$(PlatformToolset)\Shared\lib QtCore4.lib;QtGui4.lib;%(AdditionalDependencies) win32EntryPoint win32EntryPoint win32EntryPoint win32EntryPoint win32EntryPoint win32EntryPoint LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 MinSpace true true WIN32;NDEBUG;_CONSOLE;_LIB;QT_GUI_LIB;QT_CORE_LIB;QT_THREAD_SUPPORT;QT_NODLL;QT_NO_DEBUG;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(QTDIR)\include;$(QTDIR)\include\QtCore;$(QTDIR)\include\QtGUI MultiThreaded Default Size true false StreamingSIMDExtensions2 Fast false Windows false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\Win32\static;$(SolutionDir)\..\Prerequisites\Qt4\$(PlatformToolset)\Static\lib QtCore.lib;QtGui.lib;Imm32.lib;Winmm.lib;Ws2_32.lib;%(AdditionalDependencies) win32EntryPoint LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) ================================================ FILE: DynamicAudioNormalizerGUI/DynamicAudioNormalizerGUI_VS2017.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {2f1efda3-3e92-4158-960c-40e4ceaf03ba} {7867be34-0625-4766-8937-eb65d6ae1533} Source Files Source Files\3rd Party Sources Source Files\Generated Files Source Files Source Files\Generated Files Header Files Resource Files ================================================ FILE: DynamicAudioNormalizerGUI/makefile ================================================ ############################################################################## # Dynamic Audio Normalizer - Audio Processing Utility # Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License 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/gpl-3.0.txt ############################################################################## ECHO=echo -e SHELL=/bin/bash MOC ?= moc QTDIR ?= /usr/include/qt4 ############################################################################## # Constants ############################################################################## PROGRAM_NAME := DynamicAudioNormalizerGUI ifndef API_VERSION $(error API_VERSION variable is not set!) endif ############################################################################## # Qt Checks ############################################################################## ifneq ($(MAKECMDGOALS),clean) MOC_CHECK := $(findstring Qt Meta Object Compiler,$(shell $(MOC) -v 2>&1)) ifneq ($(MOC_CHECK),Qt Meta Object Compiler) $(error Qt Meta Object Compiler not found. Please set MOC environment variable properly!) endif ifneq ($(notdir $(realpath $(QTDIR)/QtGui/QApplication)),QApplication) $(error File "QtGui/QApplication" not found in Qt include path. Please set QTDIR environment variable properly!) endif endif ############################################################################## # Flags ############################################################################## DEBUG_BUILD ?= 0 MARCH ?= native ifeq ($(DEBUG_BUILD), 1) CONFIG_NAME = Debug CXXFLAGS = -g -O0 -D_DEBUG else CONFIG_NAME = Release CXXFLAGS = -O3 -Wall -ffast-math -mfpmath=sse -msse -fomit-frame-pointer -fno-tree-vectorize -DNDEBUG -march=$(MARCH) -Wno-strict-overflow endif CXXFLAGS += -I./src CXXFLAGS += -I../DynamicAudioNormalizerAPI/include LDXFLAGS += -Wl,-rpath,'$$ORIGIN' LDXFLAGS += -L../DynamicAudioNormalizerAPI/lib LDXFLAGS += -lDynamicAudioNormalizerAPI-$(API_VERSION) #Externel libraries CXXFLAGS += -I$(QTDIR) CXXFLAGS += -I$(QTDIR)/QtGui CXXFLAGS += -I$(QTDIR)/QtCore LDXFLAGS += -lQtCore -lQtGui ############################################################################## # File Names ############################################################################## ifeq ($(findstring MINGW,$(shell uname -s)),MINGW) PRG_EXT = exe else PRG_EXT = bin endif SOURCES_HDR = $(wildcard src/*.h) $(wildcard src/3rd_party/*.h) SOURCES_MOC = $(patsubst %.h,%_MOC.cpp,$(SOURCES_HDR)) SOURCES_CPP = $(wildcard src/*.cpp) $(wildcard src/3rd_party/*.cpp) $(SOURCES_MOC) SOURCES_OBJ = $(patsubst %.cpp,%.o,$(SOURCES_CPP)) PROGRAM_OUT = bin/$(PROGRAM_NAME) PROGRAM_BIN = $(PROGRAM_OUT).$(PRG_EXT) PROGRAM_DBG = $(PROGRAM_OUT)-DBG.$(PRG_EXT) ############################################################################## # Rules ############################################################################## .PHONY: all clean all: $(PROGRAM_BIN) #------------------------------------------------------------- # Link & Strip #------------------------------------------------------------- $(PROGRAM_BIN): $(PROGRAM_DBG) @$(ECHO) "\e[1;36m[STR] $@\e[0m" @mkdir -p $(dir $@) strip --strip-unneeded -o $@ $< $(PROGRAM_DBG): $(SOURCES_OBJ) @$(ECHO) "\e[1;36m[LNK] $@\e[0m" @mkdir -p $(dir $@) g++ -o $@ $+ $(LDXFLAGS) #------------------------------------------------------------- # Compile #------------------------------------------------------------- %_MOC.cpp: %.h @$(ECHO) "\e[1;36m[MOC] $<\e[0m" @mkdir -p $(dir $@) $(MOC) -o $@ $< %.o: %.cpp @$(ECHO) "\e[1;36m[CXX] $<\e[0m" @mkdir -p $(dir $@) g++ $(CXXFLAGS) -c $< -o $@ #------------------------------------------------------------- # Clean #------------------------------------------------------------- clean: rm -fv $(SOURCES_OBJ) rm -fv $(SOURCES_MOC) rm -rfv ./bin ================================================ FILE: DynamicAudioNormalizerGUI/res/DynamicAudioNormalizerGUI.rc ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "WinResrc.h" //"afxres.h" #define INC_DYNAUDNORM_VERSION_INTERNAL 0x22b4f8a9 #include "../DynamicAudioNormalizerShared/res/version.inc" ////////////////////////////////////////////////////////////////////////////////// // Neutral resources ////////////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) #ifdef _WIN32 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL #pragma code_page(1252) #endif //_WIN32 ////////////////////////////////////////////////////////////////////////////////// // Icon ////////////////////////////////////////////////////////////////////////////////// 101 ICON "DynamicAudioNormalizerGUI.ico" ////////////////////////////////////////////////////////////////////////////////// // Version ////////////////////////////////////////////////////////////////////////////////// VS_VERSION_INFO VERSIONINFO FILEVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH PRODUCTVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x3L #else FILEFLAGS 0x2L #endif FILEOS 0x40004L FILETYPE 0x1L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ." VALUE "CompanyName", "LoRd_MuldeR " VALUE "FileDescription", "DynamicAudioNormalizer Log Viewer" VALUE "FileVersion", VER_DYNAUDNORM_STR VALUE "InternalName", "DynamicAudioNormalizerGUI" VALUE "LegalCopyright", "Copyright (c) 2014-2019 LoRd_MuldeR " VALUE "LegalTrademarks", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License " VALUE "OriginalFilename", "DynamicAudioNormalizerGUI.exe" VALUE "ProductName", "DynamicAudioNormalizer" VALUE "ProductVersion", VER_DYNAUDNORM_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // Neutral resources ================================================ FILE: DynamicAudioNormalizerGUI/src/3rd_party/qcustomplot.cpp ================================================ /*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011, 2012, 2013, 2014 Emanuel Eichhammer ** ** ** ** This program is free software: you can redistribute it and/or modify ** ** it under the terms of the GNU General Public License as published by ** ** the Free Software Foundation, either version 3 of the License, or ** ** (at your option) any later version. ** ** ** ** This program is distributed in the hope that it will be useful, ** ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** ** GNU General Public License 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/. ** ** ** **************************************************************************** ** Author: Emanuel Eichhammer ** ** Website/Contact: http://www.qcustomplot.com/ ** ** Date: 07.04.14 ** ** Version: 1.2.1 ** ****************************************************************************/ #include "qcustomplot.h" //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPainter //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPainter \brief QPainter subclass used internally This QPainter subclass is used to provide some extended functionality e.g. for tweaking position consistency between antialiased and non-antialiased painting. Further it provides workarounds for QPainter quirks. \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and restore. So while it is possible to pass a QCPPainter instance to a function that expects a QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because it will call the base class implementations of the functions actually hidden by QCPPainter). */ /*! Creates a new QCPPainter instance and sets default values */ QCPPainter::QCPPainter() : QPainter(), mModes(pmDefault), mIsAntialiasing(false) { // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and // a call to begin() will follow } /*! Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just like the analogous QPainter constructor, begins painting on \a device immediately. Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. */ QCPPainter::QCPPainter(QPaintDevice *device) : QPainter(device), mModes(pmDefault), mIsAntialiasing(false) { #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. if (isActive()) setRenderHint(QPainter::NonCosmeticDefaultPen); #endif } QCPPainter::~QCPPainter() { } /*! Sets the pen of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QPen &pen) { QPainter::setPen(pen); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(const QColor &color) { QPainter::setPen(color); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of this QCPPainter. \note this function hides the non-virtual base class implementation. */ void QCPPainter::setPen(Qt::PenStyle penStyle) { QPainter::setPen(penStyle); if (mModes.testFlag(pmNonCosmetic)) makeNonCosmetic(); } /*! \overload Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to integer coordinates and then passes it to the original drawLine. \note this function hides the non-virtual base class implementation. */ void QCPPainter::drawLine(const QLineF &line) { if (mIsAntialiasing || mModes.testFlag(pmVectorized)) QPainter::drawLine(line); else QPainter::drawLine(line.toLine()); } /*! Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for AA/Non-AA painting). */ void QCPPainter::setAntialiasing(bool enabled) { setRenderHint(QPainter::Antialiasing, enabled); if (mIsAntialiasing != enabled) { mIsAntialiasing = enabled; if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs { if (mIsAntialiasing) translate(0.5, 0.5); else translate(-0.5, -0.5); } } } /*! Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setModes(QCPPainter::PainterModes modes) { mModes = modes; } /*! Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that behaviour. The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets the render hint as appropriate. \note this function hides the non-virtual base class implementation. */ bool QCPPainter::begin(QPaintDevice *device) { bool result = QPainter::begin(device); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. if (result) setRenderHint(QPainter::NonCosmeticDefaultPen); #endif return result; } /*! \overload Sets the mode of the painter. This controls whether the painter shall adjust its fixes/workarounds optimized for certain output devices. */ void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) { if (!enabled && mModes.testFlag(mode)) mModes &= ~mode; else if (enabled && !mModes.testFlag(mode)) mModes |= mode; } /*! Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. \note this function hides the non-virtual base class implementation. \see restore */ void QCPPainter::save() { mAntialiasingStack.push(mIsAntialiasing); QPainter::save(); } /*! Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to QPainter, the save/restore functions are reimplemented to also save/restore those members. \note this function hides the non-virtual base class implementation. \see save */ void QCPPainter::restore() { if (!mAntialiasingStack.isEmpty()) mIsAntialiasing = mAntialiasingStack.pop(); else qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; QPainter::restore(); } /*! Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen overrides when the \ref pmNonCosmetic mode is set. */ void QCPPainter::makeNonCosmetic() { if (qFuzzyIsNull(pen().widthF())) { QPen p = pen(); p.setWidth(1); QPainter::setPen(p); } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPScatterStyle //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPScatterStyle \brief Represents the visual appearance of scatter points This class holds information about shape, color and size of scatter points. In plottables like QCPGraph it is used to store how scatter points shall be drawn. For example, \ref QCPGraph::setScatterStyle takes a QCPScatterStyle instance. A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can be controlled with \ref setSize. \section QCPScatterStyle-defining Specifying a scatter style You can set all these configurations either by calling the respective functions on an instance: \code QCPScatterStyle myScatter; myScatter.setShape(QCPScatterStyle::ssCircle); myScatter.setPen(Qt::blue); myScatter.setBrush(Qt::white); myScatter.setSize(5); customPlot->graph(0)->setScatterStyle(myScatter); \endcode Or you can use one of the various constructors that take different parameter combinations, making it easy to specify a scatter style in a single call, like so: \code customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::white, 5)); \endcode \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref isPenDefined will return false. It leads to scatter points that inherit the pen from the plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes it very convenient to set up typical scatter settings: \code customPlot->graph(0)->setScatterStyle(QCPScatterStyle::ssPlus); \endcode Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size) constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref ScatterShape, where actually a QCPScatterStyle is expected. \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points. For custom shapes, you can provide a QPainterPath with the desired shape to the \ref setCustomPath function or call the constructor that takes a painter path. The scatter shape will automatically be set to \ref ssCustom. For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap. Note that \ref setSize does not influence the appearance of the pixmap. */ /* start documentation of inline functions */ /*! \fn bool QCPScatterStyle::isNone() const Returns whether the scatter shape is \ref ssNone. \see setShape */ /*! \fn bool QCPScatterStyle::isPenDefined() const Returns whether a pen has been defined for this scatter style. The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is left undefined, the scatter color will be inherited from the plottable that uses this scatter style. \see setPen */ /* end documentation of inline functions */ /*! Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited from the plottable that uses this scatter style. */ QCPScatterStyle::QCPScatterStyle() : mSize(6), mShape(ssNone), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or brush is defined. Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited from the plottable that uses this scatter style. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : mSize(size), mShape(shape), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, and size to \a size. No brush is defined, i.e. the scatter point will not be filled. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(Qt::NoBrush), mPenDefined(true) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, the brush color to \a fill (with a solid pattern), and size to \a size. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) : mSize(size), mShape(shape), mPen(QPen(color)), mBrush(QBrush(fill)), mPenDefined(true) { } /*! Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the brush to \a brush, and size to \a size. \warning In some cases it might be tempting to directly use a pen style like Qt::NoPen as \a pen and a color like Qt::blue as \a brush. Notice however, that the corresponding call\n QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)\n doesn't necessarily lead C++ to use this constructor in some cases, but might mistake Qt::NoPen for a QColor and use the \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) constructor instead (which will lead to an unexpected look of the scatter points). To prevent this, be more explicit with the parameter types. For example, use QBrush(Qt::blue) instead of just Qt::blue, to clearly point out to the compiler that this constructor is wanted. */ QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) : mSize(size), mShape(shape), mPen(pen), mBrush(brush), mPenDefined(pen.style() != Qt::NoPen) { } /*! Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape is set to \ref ssPixmap. */ QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : mSize(5), mShape(ssPixmap), mPen(Qt::NoPen), mBrush(Qt::NoBrush), mPixmap(pixmap), mPenDefined(false) { } /*! Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The scatter shape is set to \ref ssCustom. The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly different meaning than for built-in scatter points: The custom path will be drawn scaled by a factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its natural size by default. To double the size of the path for example, set \a size to 12. */ QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) : mSize(size), mShape(ssCustom), mPen(pen), mBrush(brush), mCustomPath(customPath), mPenDefined(false) { } /*! Sets the size (pixel diameter) of the drawn scatter points to \a size. \see setShape */ void QCPScatterStyle::setSize(double size) { mSize = size; } /*! Sets the shape to \a shape. Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref ssPixmap and \ref ssCustom, respectively. \see setSize */ void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape) { mShape = shape; } /*! Sets the pen that will be used to draw scatter points to \a pen. If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after a call to this function, even if \a pen is Qt::NoPen. \see setBrush */ void QCPScatterStyle::setPen(const QPen &pen) { mPenDefined = true; mPen = pen; } /*! Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does. \see setPen */ void QCPScatterStyle::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the pixmap that will be drawn as scatter point to \a pixmap. Note that \ref setSize does not influence the appearance of the pixmap. The scatter shape is automatically set to \ref ssPixmap. */ void QCPScatterStyle::setPixmap(const QPixmap &pixmap) { setShape(ssPixmap); mPixmap = pixmap; } /*! Sets the custom shape that will be drawn as scatter point to \a customPath. The scatter shape is automatically set to \ref ssCustom. */ void QCPScatterStyle::setCustomPath(const QPainterPath &customPath) { setShape(ssCustom); mCustomPath = customPath; } /*! Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead. This function is used by plottables (or any class that wants to draw scatters) just before a number of scatters with this style shall be drawn with the \a painter. \see drawShape */ void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const { painter->setPen(mPenDefined ? mPen : defaultPen); painter->setBrush(mBrush); } /*! Draws the scatter shape with \a painter at position \a pos. This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be called before scatter points are drawn with \ref drawShape. \see applyTo */ void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const { drawShape(painter, pos.x(), pos.y()); } /*! \overload Draws the scatter shape with \a painter at position \a x and \a y. */ void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const { double w = mSize/2.0; switch (mShape) { case ssNone: break; case ssDot: { painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y)); break; } case ssCross: { painter->drawLine(QLineF(x-w, y-w, x+w, y+w)); painter->drawLine(QLineF(x-w, y+w, x+w, y-w)); break; } case ssPlus: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); break; } case ssCircle: { painter->drawEllipse(QPointF(x , y), w, w); break; } case ssDisc: { QBrush b = painter->brush(); painter->setBrush(painter->pen().color()); painter->drawEllipse(QPointF(x , y), w, w); painter->setBrush(b); break; } case ssSquare: { painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssDiamond: { painter->drawLine(QLineF(x-w, y, x, y-w)); painter->drawLine(QLineF( x, y-w, x+w, y)); painter->drawLine(QLineF(x+w, y, x, y+w)); painter->drawLine(QLineF( x, y+w, x-w, y)); break; } case ssStar: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707)); painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707)); break; } case ssTriangle: { painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w)); painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w)); painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w)); break; } case ssTriangleInverted: { painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w)); painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w)); painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w)); break; } case ssCrossSquare: { painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95)); painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w)); painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssPlusSquare: { painter->drawLine(QLineF(x-w, y, x+w*0.95, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); break; } case ssCrossCircle: { painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670)); painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707)); painter->drawEllipse(QPointF(x, y), w, w); break; } case ssPlusCircle: { painter->drawLine(QLineF(x-w, y, x+w, y)); painter->drawLine(QLineF( x, y+w, x, y-w)); painter->drawEllipse(QPointF(x, y), w, w); break; } case ssPeace: { painter->drawLine(QLineF(x, y-w, x, y+w)); painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707)); painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707)); painter->drawEllipse(QPointF(x, y), w, w); break; } case ssPixmap: { painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap); break; } case ssCustom: { QTransform oldTransform = painter->transform(); painter->translate(x, y); painter->scale(mSize/6.0, mSize/6.0); painter->drawPath(mCustomPath); painter->setTransform(oldTransform); break; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayer \brief A layer that may contain objects, to control the rendering order The Layering system of QCustomPlot is the mechanism to control the rendering order of the elements inside the plot. It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer, QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers bottom to top and successively draws the layerables of the layers. A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base class from which almost all visible objects derive, like axes, grids, graphs, items, etc. Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in that order). The top two layers "axes" and "legend" contain the default axes and legend, so they will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the "background" layer. Of course, the layer affiliation of the individual objects can be changed as required (\ref QCPLayerable::setLayer). Controlling the ordering of objects is easy: Create a new layer in the position you want it to be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will be placed on the new layer automatically, due to the current layer setting. Alternatively you could have also ignored the current layer setting and just moved the objects with QCPLayerable::setLayer to the desired layer after creating them. It is also possible to move whole layers. For example, If you want the grid to be shown in front of all plottables/items on the "main" layer, just move it above "main" with QCustomPlot::moveLayer. The rendering order within one layer is simply by order of creation or insertion. The item created last (or added last to the layer), is drawn on top of all other objects on that layer. When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below the deleted layer, see QCustomPlot::removeLayer. */ /* start documentation of inline functions */ /*! \fn QList QCPLayer::children() const Returns a list of all layerables on this layer. The order corresponds to the rendering order: layerables with higher indices are drawn above layerables with lower indices. */ /*! \fn int QCPLayer::index() const Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be accessed via \ref QCustomPlot::layer. Layers with higher indices will be drawn above layers with lower indices. */ /* end documentation of inline functions */ /*! Creates a new QCPLayer instance. Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. This check is only performed by \ref QCustomPlot::addLayer. */ QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : QObject(parentPlot), mParentPlot(parentPlot), mName(layerName), mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function mVisible(true) { // Note: no need to make sure layerName is unique, because layer // management is done with QCustomPlot functions. } QCPLayer::~QCPLayer() { // If child layerables are still on this layer, detach them, so they don't try to reach back to this // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) while (!mChildren.isEmpty()) mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() if (mParentPlot->currentLayer() == this) qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; } /*! Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this layer will be invisible. This function doesn't change the visibility property of the layerables (\ref QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the visibility of the parent layer into account. */ void QCPLayer::setVisible(bool visible) { mVisible = visible; } /*! \internal Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will be prepended to the list, i.e. be drawn beneath the other layerables already in the list. This function does not change the \a mLayer member of \a layerable to this layer. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) \see removeChild */ void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) { if (!mChildren.contains(layerable)) { if (prepend) mChildren.prepend(layerable); else mChildren.append(layerable); } else qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); } /*! \internal Removes the \a layerable from the list of this layer. This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer to change the layer of an object, not this function.) \see addChild */ void QCPLayer::removeChild(QCPLayerable *layerable) { if (!mChildren.removeOne(layerable)) qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayerable //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayerable \brief Base class for all drawable objects This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid etc. Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking the layers accordingly. For details about the layering mechanism, see the QCPLayer documentation. */ /* start documentation of inline functions */ /*! \fn QCPLayerable *QCPLayerable::parentLayerable() const Returns the parent layerable of this layerable. The parent layerable is used to provide visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables only get drawn if their parent layerables are visible, too. Note that a parent layerable is not necessarily also the QObject parent for memory management. Further, a layerable doesn't always have a parent layerable, so this function may return 0. A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be set manually by the user. */ /* end documentation of inline functions */ /* start documentation of pure virtual functions */ /*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 \internal This function applies the default antialiasing setting to the specified \a painter, using the function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing setting may be specified individually, this function should set the antialiasing state of the most prominent entity. In this case however, the \ref draw function usually calls the specialized versions of this function before drawing each entity, effectively overriding the setting of the default antialiasing hint. First example: QCPGraph has multiple entities that have an antialiasing setting: The graph line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased, QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw calls the respective specialized applyAntialiasingHint function. Second example: QCPItemLine consists only of a line so there is only one antialiasing setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the respective layerable subclass.) Consequently it only has the normal QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to care about setting any antialiasing states, because the default antialiasing hint is already set on the painter when the \ref draw function is called, and that's the state it wants to draw the line with. */ /*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 \internal This function draws the layerable with the specified \a painter. It is only called by QCustomPlot, if the layerable is visible (\ref setVisible). Before this function is called, the painter's antialiasing state is set via \ref applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was set to \ref clipRect. */ /* end documentation of pure virtual functions */ /* start documentation of signals */ /*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to a different layer. \see setLayer */ /* end documentation of signals */ /*! Creates a new QCPLayerable instance. Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the derived classes. If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a targetLayer is an empty string, it places itself on the current layer of the plot (see \ref QCustomPlot::setCurrentLayer). It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later time with \ref initializeParentPlot. The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents are mainly used to control visibility in a hierarchy of layerables. This means a layerable is only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable, \a plot does. */ QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : QObject(plot), mVisible(true), mParentPlot(plot), mParentLayerable(parentLayerable), mLayer(0), mAntialiased(true) { if (mParentPlot) { if (targetLayer.isEmpty()) setLayer(mParentPlot->currentLayer()); else if (!setLayer(targetLayer)) qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; } } QCPLayerable::~QCPLayerable() { if (mLayer) { mLayer->removeChild(this); mLayer = 0; } } /*! Sets the visibility of this layerable object. If an object is not visible, it will not be drawn on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not possible. */ void QCPLayerable::setVisible(bool on) { mVisible = on; } /*! Sets the \a layer of this layerable object. The object will be placed on top of the other objects already on \a layer. Returns true on success, i.e. if \a layer is a valid layer. */ bool QCPLayerable::setLayer(QCPLayer *layer) { return moveToLayer(layer, false); } /*! \overload Sets the layer of this layerable object by name Returns true on success, i.e. if \a layerName is a valid layer name. */ bool QCPLayerable::setLayer(const QString &layerName) { if (!mParentPlot) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } if (QCPLayer *layer = mParentPlot->layer(layerName)) { return setLayer(layer); } else { qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; return false; } } /*! Sets whether this object will be drawn antialiased or not. Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and QCustomPlot::setNotAntialiasedElements. */ void QCPLayerable::setAntialiased(bool enabled) { mAntialiased = enabled; } /*! Returns whether this layerable is visible, taking the visibility of the layerable parent and the visibility of the layer this layerable is on into account. This is the method that is consulted to decide whether a layerable shall be drawn or not. If this layerable has a direct layerable parent (usually set via hierarchies implemented in subclasses, like in the case of QCPLayoutElement), this function returns true only if this layerable has its visibility set to true and the parent layerable's \ref realVisibility returns true. If this layerable doesn't have a direct layerable parent, returns the state of this layerable's visibility. */ bool QCPLayerable::realVisibility() const { return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); } /*! This function is used to decide whether a click hits a layerable object or not. \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the shortest pixel distance of this point to the object. If the object is either invisible or the distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the object is not selectable, -1.0 is returned, too. If the item is represented not by single lines but by an area like QCPItemRect or QCPItemText, a click inside the area returns a constant value greater zero (typically the selectionTolerance of the parent QCustomPlot multiplied by 0.99). If the click lies outside the area, this function returns -1.0. Providing a constant value for area objects allows selecting line objects even when they are obscured by such area objects, by clicking close to the lines (i.e. closer than 0.99*selectionTolerance). The actual setting of the selection state is not done by this function. This is handled by the parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified via the selectEvent/deselectEvent methods. \a details is an optional output parameter. Every layerable subclass may place any information in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot decides on the basis of this selectTest call, that the object was successfully selected. The subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be placed in \a details. So in the subsequent \ref selectEvent, the decision which part was selected doesn't have to be done a second time for a single selection operation. You may pass 0 as \a details to indicate that you are not interested in those selection details. \see selectEvent, deselectEvent, QCustomPlot::setInteractions */ double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(pos) Q_UNUSED(onlySelectable) Q_UNUSED(details) return -1.0; } /*! \internal Sets the parent plot of this layerable. Use this function once to set the parent plot if you have passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to another one. Note that, unlike when passing a non-null parent plot in the constructor, this function does not make \a parentPlot the QObject-parent of this layerable. If you want this, call QObject::setParent(\a parentPlot) in addition to this function. Further, you will probably want to set a layer (\ref setLayer) after calling this function, to make the layerable appear on the QCustomPlot. The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized so they can react accordingly (e.g. also initialize the parent plot of child layerables, like QCPLayout does). */ void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) { if (mParentPlot) { qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; return; } if (!parentPlot) qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; mParentPlot = parentPlot; parentPlotInitialized(mParentPlot); } /*! \internal Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not become the QObject-parent (for memory management) of this layerable. The parent layerable has influence on the return value of the \ref realVisibility method. Only layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be drawn. \see realVisibility */ void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) { mParentLayerable = parentLayerable; } /*! \internal Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is false, the object will be appended. Returns true on success, i.e. if \a layer is a valid layer. */ bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) { if (layer && !mParentPlot) { qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; return false; } if (layer && layer->parentPlot() != mParentPlot) { qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; return false; } QCPLayer *oldLayer = mLayer; if (mLayer) mLayer->removeChild(this); mLayer = layer; if (mLayer) mLayer->addChild(this, prepend); if (mLayer != oldLayer) emit layerChanged(mLayer); return true; } /*! \internal Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is controlled via \a overrideElement. */ void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const { if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) painter->setAntialiasing(false); else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) painter->setAntialiasing(true); else painter->setAntialiasing(localAntialiased); } /*! \internal This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the parent plot is set at a later time. For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To propagate the parent plot to all the children of the hierarchy, the top level element then uses this function to pass the parent plot on to its child elements. The default implementation does nothing. \see initializeParentPlot */ void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) { Q_UNUSED(parentPlot) } /*! \internal Returns the selection category this layerable shall belong to. The selection category is used in conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and which aren't. Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref QCP::iSelectOther. This is what the default implementation returns. \see QCustomPlot::setInteractions */ QCP::Interaction QCPLayerable::selectionCategory() const { return QCP::iSelectOther; } /*! \internal Returns the clipping rectangle of this layerable object. By default, this is the viewport of the parent QCustomPlot. Specific subclasses may reimplement this function to provide different clipping rects. The returned clipping rect is set on the painter before the draw function of the respective object is called. */ QRect QCPLayerable::clipRect() const { if (mParentPlot) return mParentPlot->viewport(); else return QRect(); } /*! \internal This event is called when the layerable shall be selected, as a consequence of a click by the user. Subclasses should react to it by setting their selection state appropriately. The default implementation does nothing. \a event is the mouse event that caused the selection. \a additive indicates, whether the user was holding the multi-select-modifier while performing the selection (see \ref QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled (i.e. become selected when unselected and unselected when selected). Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). The \a details data you output from \ref selectTest is fed back via \a details here. You may use it to transport any kind of information from the selectTest to the possibly subsequent selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need to do the calculation again to find out which part was actually clicked. \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must set the value either to true or false, depending on whether the selection state of this layerable was actually changed. For layerables that only are selectable as a whole and not in parts, this is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the layerable was previously unselected and now is switched to the selected state. \see selectTest, deselectEvent */ void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(additive) Q_UNUSED(details) Q_UNUSED(selectionStateChanged) } /*! \internal This event is called when the layerable shall be deselected, either as consequence of a user interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by unsetting their selection appropriately. just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must return true or false when the selection state of this layerable has changed or not changed, respectively. \see selectTest, selectEvent */ void QCPLayerable::deselectEvent(bool *selectionStateChanged) { Q_UNUSED(selectionStateChanged) } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPRange //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPRange \brief Represents the range an axis is encompassing. contains a \a lower and \a upper double value and provides convenience input, output and modification functions. \see QCPAxis::setRange */ /*! Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller intervals would cause errors due to the 11-bit exponent of double precision numbers, corresponding to a minimum magnitude of roughly 1e-308. \see validRange, maxRange */ const double QCPRange::minRange = 1e-280; /*! Maximum values (negative and positive) the range will accept in range-changing functions. Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers, corresponding to a maximum magnitude of roughly 1e308. Since the number of planck-volumes in the entire visible universe is only ~1e183, this should be enough. \see validRange, minRange */ const double QCPRange::maxRange = 1e250; /*! Constructs a range with \a lower and \a upper set to zero. */ QCPRange::QCPRange() : lower(0), upper(0) { } /*! \overload Constructs a range with the specified \a lower and \a upper values. */ QCPRange::QCPRange(double lower, double upper) : lower(lower), upper(upper) { normalize(); } /*! Returns the size of the range, i.e. \a upper-\a lower */ double QCPRange::size() const { return upper-lower; } /*! Returns the center of the range, i.e. (\a upper+\a lower)*0.5 */ double QCPRange::center() const { return (upper+lower)*0.5; } /*! Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values are swapped. */ void QCPRange::normalize() { if (lower > upper) qSwap(lower, upper); } /*! Expands this range such that \a otherRange is contained in the new range. It is assumed that both this range and \a otherRange are normalized (see \ref normalize). If \a otherRange is already inside the current range, this function does nothing. \see expanded */ void QCPRange::expand(const QCPRange &otherRange) { if (lower > otherRange.lower) lower = otherRange.lower; if (upper < otherRange.upper) upper = otherRange.upper; } /*! Returns an expanded range that contains this and \a otherRange. It is assumed that both this range and \a otherRange are normalized (see \ref normalize). \see expand */ QCPRange QCPRange::expanded(const QCPRange &otherRange) const { QCPRange result = *this; result.expand(otherRange); return result; } /*! Returns a sanitized version of the range. Sanitized means for logarithmic scales, that the range won't span the positive and negative sign domain, i.e. contain zero. Further \a lower will always be numerically smaller (or equal) to \a upper. If the original range does span positive and negative sign domains or contains zero, the returned range will try to approximate the original range as good as possible. If the positive interval of the original range is wider than the negative interval, the returned range will only contain the positive interval, with lower bound set to \a rangeFac or \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval is wider than the positive interval, this time by changing the \a upper bound. */ QCPRange QCPRange::sanitizedForLogScale() const { double rangeFac = 1e-3; QCPRange sanitizedRange(lower, upper); sanitizedRange.normalize(); // can't have range spanning negative and positive values in log plot, so change range to fix it //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) { // case lower is 0 if (rangeFac < sanitizedRange.upper*rangeFac) sanitizedRange.lower = rangeFac; else sanitizedRange.lower = sanitizedRange.upper*rangeFac; } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) { // case upper is 0 if (-rangeFac > sanitizedRange.lower*rangeFac) sanitizedRange.upper = -rangeFac; else sanitizedRange.upper = sanitizedRange.lower*rangeFac; } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) { // find out whether negative or positive interval is wider to decide which sign domain will be chosen if (-sanitizedRange.lower > sanitizedRange.upper) { // negative is wider, do same as in case upper is 0 if (-rangeFac > sanitizedRange.lower*rangeFac) sanitizedRange.upper = -rangeFac; else sanitizedRange.upper = sanitizedRange.lower*rangeFac; } else { // positive is wider, do same as in case lower is 0 if (rangeFac < sanitizedRange.upper*rangeFac) sanitizedRange.lower = rangeFac; else sanitizedRange.lower = sanitizedRange.upper*rangeFac; } } // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper= lower && value <= upper; } /*! Checks, whether the specified range is within valid bounds, which are defined as QCPRange::maxRange and QCPRange::minRange. A valid range means: \li range bounds within -maxRange and maxRange \li range size above minRange \li range size below maxRange */ bool QCPRange::validRange(double lower, double upper) { /* return (lower > -maxRange && upper < maxRange && qAbs(lower-upper) > minRange && (lower < -minRange || lower > minRange) && (upper < -minRange || upper > minRange)); */ return (lower > -maxRange && upper < maxRange && qAbs(lower-upper) > minRange && qAbs(lower-upper) < maxRange); } /*! \overload Checks, whether the specified range is within valid bounds, which are defined as QCPRange::maxRange and QCPRange::minRange. A valid range means: \li range bounds within -maxRange and maxRange \li range size above minRange \li range size below maxRange */ bool QCPRange::validRange(const QCPRange &range) { /* return (range.lower > -maxRange && range.upper < maxRange && qAbs(range.lower-range.upper) > minRange && qAbs(range.lower-range.upper) < maxRange && (range.lower < -minRange || range.lower > minRange) && (range.upper < -minRange || range.upper > minRange)); */ return (range.lower > -maxRange && range.upper < maxRange && qAbs(range.lower-range.upper) > minRange && qAbs(range.lower-range.upper) < maxRange); } /*! \page thelayoutsystem The Layout System The layout system is responsible for positioning and scaling layout elements such as axis rects, legends and plot titles in a QCustomPlot. \section layoutsystem-classesandmechanisms Classes and mechanisms The layout system is based on the abstract base class \ref QCPLayoutElement. All objects that take part in the layout system derive from this class, either directly or indirectly. Since QCPLayoutElement itself derives from \ref QCPLayerable, a layout element may draw its own content. However, it is perfectly possible for a layout element to only serve as a structuring and/or positioning element, not drawing anything on its own. \subsection layoutsystem-rects Rects of a layout element A layout element is a rectangular object described by two rects: the inner rect (\ref QCPLayoutElement::rect) and the outer rect (\ref QCPLayoutElement::setOuterRect). The inner rect is calculated automatically by applying the margin (\ref QCPLayoutElement::setMargins) inward from the outer rect. The inner rect is meant for main content while the margin area may either be left blank or serve for displaying peripheral graphics. For example, \ref QCPAxisRect positions the four main axes at the sides of the inner rect, so graphs end up inside it and the axis labels and tick labels are in the margin area. \subsection layoutsystem-margins Margins Each layout element may provide a mechanism to automatically determine its margins. Internally, this is realized with the \ref QCPLayoutElement::calculateAutoMargin function which takes a \ref QCP::MarginSide and returns an integer value which represents the ideal margin for the specified side. The automatic margin will be used on the sides specified in \ref QCPLayoutElement::setAutoMargins. By default, it is set to \ref QCP::msAll meaning automatic margin calculation is enabled for all four sides. In this case, a minimum margin may be set with \ref QCPLayoutElement::setMinimumMargins, to prevent the automatic margin mechanism from setting margins smaller than desired for a specific situation. If automatic margin calculation is unset for a specific side, the margin of that side can be controlled directy via \ref QCPLayoutElement::setMargins. If multiple layout ements are arranged next to or beneath each other, it may be desirable to align their inner rects on certain sides. Since they all might have different automatic margins, this usually isn't the case. The class \ref QCPMarginGroup and \ref QCPLayoutElement::setMarginGroup fix this by allowing to synchronize multiple margins. See the documentation there for details. \subsection layoutsystem-layout Layouts As mentioned, a QCPLayoutElement may have an arbitrary number of child layout elements and in princple can have the only purpose to manage/arrange those child elements. This is what the subclass \ref QCPLayout specializes on. It is a QCPLayoutElement itself but has no visual representation. It defines an interface to add, remove and manage child layout elements. QCPLayout isn't a usable layout though, it's an abstract base class that concrete layouts derive from, like \ref QCPLayoutGrid which arranges its child elements in a grid and \ref QCPLayoutInset which allows placing child elements freely inside its rect. Since a QCPLayout is a layout element itself, it may be placed inside other layouts. This way, complex hierarchies may be created, offering very flexible arrangements. \image html LayoutsystemSketch.png Above is a sketch of the default \ref QCPLayoutGrid accessible via \ref QCustomPlot::plotLayout. It shows how two child layout elements are placed inside the grid layout next to each other in cells (0, 0) and (0, 1). \subsection layoutsystem-plotlayout The top level plot layout Every QCustomPlot has one top level layout of type \ref QCPLayoutGrid. It is accessible via \ref QCustomPlot::plotLayout and contains (directly or indirectly via other sub-layouts) all layout elements in the QCustomPlot. By default, this top level grid layout contains a single cell which holds the main axis rect. \subsection layoutsystem-examples Examples Adding a plot title is a typical and simple case to demonstrate basic workings of the layout system. \code // first we create and prepare a plot title layout element: QCPPlotTitle *title = new QCPPlotTitle(customPlot); title->setText("Plot Title Example"); title->setFont(QFont("sans", 12, QFont::Bold)); // then we add it to the main plot layout: customPlot->plotLayout()->insertRow(0); // insert an empty row above the axis rect customPlot->plotLayout()->addElement(0, 0, title); // place the title in the empty cell we've just created \endcode \image html layoutsystem-addingplottitle.png Arranging multiple axis rects actually is the central purpose of the layout system. \code customPlot->plotLayout()->clear(); // let's start from scratch and remove the default axis rect // add the first axis rect in second row (row index 1): QCPAxisRect *topAxisRect = new QCPAxisRect(customPlot); customPlot->plotLayout()->addElement(1, 0, topAxisRect); // create a sub layout that we'll place in first row: QCPLayoutGrid *subLayout = new QCPLayoutGrid; customPlot->plotLayout()->addElement(0, 0, subLayout); // add two axis rects in the sub layout next to each other: QCPAxisRect *leftAxisRect = new QCPAxisRect(customPlot); QCPAxisRect *rightAxisRect = new QCPAxisRect(customPlot); subLayout->addElement(0, 0, leftAxisRect); subLayout->addElement(0, 1, rightAxisRect); subLayout->setColumnStretchFactor(0, 3); // left axis rect shall have 60% of width subLayout->setColumnStretchFactor(1, 2); // right one only 40% (3:2 = 60:40) // since we've created the axis rects and axes from scratch, we need to place them on // according layers, if we don't want the grid to be drawn above the axes etc. // place the axis on "axes" layer and grids on the "grid" layer, which is below "axes": QList allAxes; allAxes << topAxisRect->axes() << leftAxisRect->axes() << rightAxisRect->axes(); foreach (QCPAxis *axis, allAxes) { axis->setLayer("axes"); axis->grid()->setLayer("grid"); } \endcode \image html layoutsystem-multipleaxisrects.png */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPMarginGroup //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPMarginGroup \brief A margin group allows synchronization of margin sides if working with multiple layout elements. QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that they will all have the same size, based on the largest required margin in the group. \n \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" \n In certain situations it is desirable that margins at specific sides are synchronized across layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will provide a cleaner look to the user if the left and right margins of the two axis rects are of the same size. The left axis of the top axis rect will then be at the same horizontal position as the left axis of the lower axis rect, making them appear aligned. The same applies for the right axes. This is what QCPMarginGroup makes possible. To add/remove a specific side of a layout element to/from a margin group, use the \ref QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call \ref clear, or just delete the margin group. \section QCPMarginGroup-example Example First create a margin group: \code QCPMarginGroup *group = new QCPMarginGroup(customPlot); \endcode Then set this group on the layout element sides: \code customPlot->axisRect(0)->setMarginGroup(QCP::msLeft|QCP::msRight, group); customPlot->axisRect(1)->setMarginGroup(QCP::msLeft|QCP::msRight, group); \endcode Here, we've used the first two axis rects of the plot and synchronized their left margins with each other and their right margins with each other. */ /* start documentation of inline functions */ /*! \fn QList QCPMarginGroup::elements(QCP::MarginSide side) const Returns a list of all layout elements that have their margin \a side associated with this margin group. */ /* end documentation of inline functions */ /*! Creates a new QCPMarginGroup instance in \a parentPlot. */ QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : QObject(parentPlot), mParentPlot(parentPlot) { mChildren.insert(QCP::msLeft, QList()); mChildren.insert(QCP::msRight, QList()); mChildren.insert(QCP::msTop, QList()); mChildren.insert(QCP::msBottom, QList()); } QCPMarginGroup::~QCPMarginGroup() { clear(); } /*! Returns whether this margin group is empty. If this function returns true, no layout elements use this margin group to synchronize margin sides. */ bool QCPMarginGroup::isEmpty() const { QHashIterator > it(mChildren); while (it.hasNext()) { it.next(); if (!it.value().isEmpty()) return false; } return true; } /*! Clears this margin group. The synchronization of the margin sides that use this margin group is lifted and they will use their individual margin sizes again. */ void QCPMarginGroup::clear() { // make all children remove themselves from this margin group: QHashIterator > it(mChildren); while (it.hasNext()) { it.next(); const QList elements = it.value(); for (int i=elements.size()-1; i>=0; --i) elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild } } /*! \internal Returns the synchronized common margin for \a side. This is the margin value that will be used by the layout element on the respective side, if it is part of this margin group. The common margin is calculated by requesting the automatic margin (\ref QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into account, too.) */ int QCPMarginGroup::commonMargin(QCP::MarginSide side) const { // query all automatic margins of the layout elements in this margin group side and find maximum: int result = 0; const QList elements = mChildren.value(side); for (int i=0; iautoMargins().testFlag(side)) continue; int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); if (m > result) result = m; } return result; } /*! \internal Adds \a element to the internal list of child elements, for the margin \a side. This function does not modify the margin group property of \a element. */ void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) { if (!mChildren[side].contains(element)) mChildren[side].append(element); else qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); } /*! \internal Removes \a element from the internal list of child elements, for the margin \a side. This function does not modify the margin group property of \a element. */ void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) { if (!mChildren[side].removeOne(element)) qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutElement //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutElement \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. A Layout element is a rectangular object which can be placed in layouts. It has an outer rect (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference between outer and inner rect is called its margin. The margin can either be set to automatic or manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, the layout element subclass will control the value itself (via \ref calculateAutoMargin). Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. Thus in QCustomPlot one can divide layout elements into two categories: The ones that are invisible by themselves, because they don't draw anything. Their only purpose is to manage the position and size of other layout elements. This category of layout elements usually use QCPLayout as base class. Then there is the category of layout elements which actually draw something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does not necessarily mean that the latter category can't have child layout elements. QCPLegend for instance, actually derives from QCPLayoutGrid and the individual legend items are child layout elements in the grid layout. */ /* start documentation of inline functions */ /*! \fn QCPLayout *QCPLayoutElement::layout() const Returns the parent layout of this layout element. */ /*! \fn QRect QCPLayoutElement::rect() const Returns the inner rect of this layout element. The inner rect is the outer rect (\ref setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). In some cases, the area between outer and inner rect is left blank. In other cases the margin area is used to display peripheral graphics while the main content is in the inner rect. This is where automatic margin calculation becomes interesting because it allows the layout element to adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if \ref setAutoMargins is enabled) according to the space required by the labels of the axes. */ /*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event) This event is called, if the mouse was pressed while being inside the outer rect of this layout element. */ /*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event) This event is called, if the mouse is moved inside the outer rect of this layout element. */ /*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event) This event is called, if the mouse was previously pressed inside the outer rect of this layout element and is now released. */ /*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event) This event is called, if the mouse is double-clicked inside the outer rect of this layout element. */ /*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event) This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this layout element. */ /* end documentation of inline functions */ /*! Creates an instance of QCPLayoutElement and sets default values. */ QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) mParentLayout(0), mMinimumSize(), mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), mRect(0, 0, 0, 0), mOuterRect(0, 0, 0, 0), mMargins(0, 0, 0, 0), mMinimumMargins(0, 0, 0, 0), mAutoMargins(QCP::msAll) { } QCPLayoutElement::~QCPLayoutElement() { setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any // unregister at layout: if (qobject_cast(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor mParentLayout->take(this); } /*! Sets the outer rect of this layout element. If the layout element is inside a layout, the layout sets the position and size of this layout element using this function. Calling this function externally has no effect, since the layout will overwrite any changes to the outer rect upon the next replot. The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. \see rect */ void QCPLayoutElement::setOuterRect(const QRect &rect) { if (mOuterRect != rect) { mOuterRect = rect; mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); } } /*! Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all sides, this function is used to manually set the margin on those sides. Sides that are still set to be handled automatically are ignored and may have any value in \a margins. The margin is the distance between the outer rect (controlled by the parent layout via \ref setOuterRect) and the inner \ref rect (which usually contains the main content of this layout element). \see setAutoMargins */ void QCPLayoutElement::setMargins(const QMargins &margins) { if (mMargins != margins) { mMargins = margins; mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); } } /*! If \ref setAutoMargins is enabled on some or all margins, this function is used to provide minimum values for those margins. The minimum values are not enforced on margin sides that were set to be under manual control via \ref setAutoMargins. \see setAutoMargins */ void QCPLayoutElement::setMinimumMargins(const QMargins &margins) { if (mMinimumMargins != margins) { mMinimumMargins = margins; } } /*! Sets on which sides the margin shall be calculated automatically. If a side is calculated automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is set to be controlled manually, the value may be specified with \ref setMargins. Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref setMarginGroup), to synchronize (align) it with other layout elements in the plot. \see setMinimumMargins, setMargins */ void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) { mAutoMargins = sides; } /*! Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. If the parent layout size is not sufficient to satisfy all minimum size constraints of its child layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot propagates the layout's size constraints to the outside by setting its own minimum QWidget size accordingly, so violations of \a size should be exceptions. */ void QCPLayoutElement::setMinimumSize(const QSize &size) { if (mMinimumSize != size) { mMinimumSize = size; if (mParentLayout) mParentLayout->sizeConstraintsChanged(); } } /*! \overload Sets the minimum size for the inner \ref rect of this layout element. */ void QCPLayoutElement::setMinimumSize(int width, int height) { setMinimumSize(QSize(width, height)); } /*! Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to respect the \a size here by changing row/column sizes in the layout accordingly. */ void QCPLayoutElement::setMaximumSize(const QSize &size) { if (mMaximumSize != size) { mMaximumSize = size; if (mParentLayout) mParentLayout->sizeConstraintsChanged(); } } /*! \overload Sets the maximum size for the inner \ref rect of this layout element. */ void QCPLayoutElement::setMaximumSize(int width, int height) { setMaximumSize(QSize(width, height)); } /*! Sets the margin \a group of the specified margin \a sides. Margin groups allow synchronizing specified margins across layout elements, see the documentation of \ref QCPMarginGroup. To unset the margin group of \a sides, set \a group to 0. Note that margin groups only work for margin sides that are set to automatic (\ref setAutoMargins). */ void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group) { QVector sideVector; if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); for (int i=0; iremoveChild(side, this); if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there { mMarginGroups.remove(side); } else // setting to a new group { mMarginGroups[side] = group; group->addChild(side, this); } } } } /*! Updates the layout element and sub-elements. This function is automatically called before every replot by the parent layout element. It is called multiple times, once for every \ref UpdatePhase. The phases are run through in the order of the enum values. For details about what happens at the different phases, see the documentation of \ref UpdatePhase. Layout elements that have child elements should call the \ref update method of their child elements, and pass the current \a phase unchanged. The default implementation executes the automatic margin mechanism in the \ref upMargins phase. Subclasses should make sure to call the base class implementation. */ void QCPLayoutElement::update(UpdatePhase phase) { if (phase == upMargins) { if (mAutoMargins != QCP::msNone) { // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: QMargins newMargins = mMargins; foreach (QCP::MarginSide side, QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom) { if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically { if (mMarginGroups.contains(side)) QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group else QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly // apply minimum margin restrictions: if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); } } setMargins(newMargins); } } } /*! Returns the minimum size this layout element (the inner \ref rect) may be compressed to. if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this function to determine the minimum allowed size of this layout element. (A manual minimum size is considered set if it is non-zero.) */ QSize QCPLayoutElement::minimumSizeHint() const { return mMinimumSize; } /*! Returns the maximum size this layout element (the inner \ref rect) may be expanded to. if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this function to determine the maximum allowed size of this layout element. (A manual maximum size is considered set if it is smaller than Qt's QWIDGETSIZE_MAX.) */ QSize QCPLayoutElement::maximumSizeHint() const { return mMaximumSize; } /*! Returns a list of all child elements in this layout element. If \a recursive is true, all sub-child elements are included in the list, too. \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have empty cells which yield 0 at the respective index.) */ QList QCPLayoutElement::elements(bool recursive) const { Q_UNUSED(recursive) return QList(); } /*! Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer rect, this method returns a value corresponding to 0.99 times the parent plot's selection tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is true, -1.0 is returned. See \ref QCPLayerable::selectTest for a general explanation of this virtual method. QCPLayoutElement subclasses may reimplement this method to provide more specific selection test behaviour. */ double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable) return -1; if (QRectF(mOuterRect).contains(pos)) { if (mParentPlot) return mParentPlot->selectionTolerance()*0.99; else { qDebug() << Q_FUNC_INFO << "parent plot not defined"; return -1; } } else return -1; } /*! \internal propagates the parent plot initialization to all child elements, by calling \ref QCPLayerable::initializeParentPlot on them. */ void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) { foreach (QCPLayoutElement* el, elements(false)) { if (!el->parentPlot()) el->initializeParentPlot(parentPlot); } } /*! \internal Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the returned value will not be smaller than the specified minimum margin. The default implementation just returns the respective manual margin (\ref setMargins) or the minimum margin, whichever is larger. */ int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) { return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayout //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayout \brief The abstract base class for layouts This is an abstract base class for layout elements whose main purpose is to define the position and size of other child layout elements. In most cases, layouts don't draw anything themselves (but there are exceptions to this, e.g. QCPLegend). QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. QCPLayout introduces a common interface for accessing and manipulating the child elements. Those functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions to this interface which are more specialized to the form of the layout. For example, \ref QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid more conveniently. Since this is an abstract base class, you can't instantiate it directly. Rather use one of its subclasses like QCPLayoutGrid or QCPLayoutInset. For a general introduction to the layout system, see the dedicated documentation page \ref thelayoutsystem "The Layout System". */ /* start documentation of pure virtual functions */ /*! \fn virtual int QCPLayout::elementCount() const = 0 Returns the number of elements/cells in the layout. \see elements, elementAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 Returns the element in the cell with the given \a index. If \a index is invalid, returns 0. Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check whether a cell is empty or not. \see elements, elementCount, takeAt */ /*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 Removes the element with the given \a index from the layout and returns it. If the \a index is invalid or the cell with that index is empty, returns 0. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see elementAt, take */ /*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 Removes the specified \a element from the layout and returns true on success. If the \a element isn't in this layout, returns false. Note that some layouts don't remove the respective cell right away but leave an empty cell after successful removal of the layout element. To collapse empty cells, use \ref simplify. \see takeAt */ /* end documentation of pure virtual functions */ /*! Creates an instance of QCPLayout and sets default values. Note that since QCPLayout is an abstract base class, it can't be instantiated directly. */ QCPLayout::QCPLayout() { } /*! First calls the QCPLayoutElement::update base class implementation to update the margins on this layout. Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells. Finally, \ref update is called on all child elements. */ void QCPLayout::update(UpdatePhase phase) { QCPLayoutElement::update(phase); // set child element rects according to layout: if (phase == upLayout) updateLayout(); // propagate update call to child elements: const int elCount = elementCount(); for (int i=0; iupdate(phase); } } /* inherits documentation from base class */ QList QCPLayout::elements(bool recursive) const { const int c = elementCount(); QList result; #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) result.reserve(c); #endif for (int i=0; ielements(recursive); } } return result; } /*! Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the default implementation does nothing. Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit simplification while QCPLayoutGrid does. */ void QCPLayout::simplify() { } /*! Removes and deletes the element at the provided \a index. Returns true on success. If \a index is invalid or points to an empty cell, returns false. This function internally uses \ref takeAt to remove the element from the layout and then deletes the returned element. \see remove, takeAt */ bool QCPLayout::removeAt(int index) { if (QCPLayoutElement *el = takeAt(index)) { delete el; return true; } else return false; } /*! Removes and deletes the provided \a element. Returns true on success. If \a element is not in the layout, returns false. This function internally uses \ref takeAt to remove the element from the layout and then deletes the element. \see removeAt, take */ bool QCPLayout::remove(QCPLayoutElement *element) { if (take(element)) { delete element; return true; } else return false; } /*! Removes and deletes all layout elements in this layout. \see remove, removeAt */ void QCPLayout::clear() { for (int i=elementCount()-1; i>=0; --i) { if (elementAt(i)) removeAt(i); } simplify(); } /*! Subclasses call this method to report changed (minimum/maximum) size constraints. If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, it may update itself and resize cells accordingly. */ void QCPLayout::sizeConstraintsChanged() const { if (QWidget *w = qobject_cast(parent())) w->updateGeometry(); else if (QCPLayout *l = qobject_cast(parent())) l->sizeConstraintsChanged(); } /*! \internal Subclasses reimplement this method to update the position and sizes of the child elements/cells via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay within that rect. \ref getSectionSizes may help with the reimplementation of this function. \see update */ void QCPLayout::updateLayout() { } /*! \internal Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the \ref QCPLayerable::parentLayerable and the QObject parent to this layout. Further, if \a el didn't previously have a parent plot, calls \ref QCPLayerable::initializeParentPlot on \a el to set the paret plot. This method is used by subclass specific methods that add elements to the layout. Note that this method only changes properties in \a el. The removal from the old layout and the insertion into the new layout must be done additionally. */ void QCPLayout::adoptElement(QCPLayoutElement *el) { if (el) { el->mParentLayout = this; el->setParentLayerable(this); el->setParent(this); if (!el->parentPlot()) el->initializeParentPlot(mParentPlot); } else qDebug() << Q_FUNC_INFO << "Null element passed"; } /*! \internal Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent QCustomPlot. This method is used by subclass specific methods that remove elements from the layout (e.g. \ref take or \ref takeAt). Note that this method only changes properties in \a el. The removal from the old layout must be done additionally. */ void QCPLayout::releaseElement(QCPLayoutElement *el) { if (el) { el->mParentLayout = 0; el->setParentLayerable(0); el->setParent(mParentPlot); // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot } else qDebug() << Q_FUNC_INFO << "Null element passed"; } /*! \internal This is a helper function for the implementation of \ref updateLayout in subclasses. It calculates the sizes of one-dimensional sections with provided constraints on maximum section sizes, minimum section sizes, relative stretch factors and the final total size of all sections. The QVector entries refer to the sections. Thus all QVectors must have the same size. \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size imposed, set all vector values to Qt's QWIDGETSIZE_MAX. \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, not exceeding the allowed total size is taken to be more important than not going below minimum section sizes.) \a stretchFactors give the relative proportions of the sections to each other. If all sections shall be scaled equally, set all values equal. If the first section shall be double the size of each individual other section, set the first number of \a stretchFactors to double the value of the other individual values (e.g. {2, 1, 1, 1}). \a totalSize is the value that the final section sizes will add up to. Due to rounding, the actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, you could distribute the remaining difference on the sections. The return value is a QVector containing the section sizes. */ QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const { if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) { qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; return QVector(); } if (stretchFactors.isEmpty()) return QVector(); int sectionCount = stretchFactors.size(); QVector sectionSizes(sectionCount); // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): int minSizeSum = 0; for (int i=0; i minimumLockedSections; QList unfinishedSections; for (int i=0; i result(sectionCount); for (int i=0; i= 0 && row < mElements.size()) { if (column >= 0 && column < mElements.first().size()) { if (QCPLayoutElement *result = mElements.at(row).at(column)) return result; else qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; } else qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; } else qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; return 0; } /*! Returns the number of rows in the layout. \see columnCount */ int QCPLayoutGrid::rowCount() const { return mElements.size(); } /*! Returns the number of columns in the layout. \see rowCount */ int QCPLayoutGrid::columnCount() const { if (mElements.size() > 0) return mElements.first().size(); else return 0; } /*! Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it is first removed from there. If \a row or \a column don't exist yet, the layout is expanded accordingly. Returns true if the element was added successfully, i.e. if the cell at \a row and \a column didn't already have an element. \see element, hasElement, take, remove */ bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) { if (element) { if (!hasElement(row, column)) { if (element->layout()) // remove from old layout first element->layout()->take(element); expandTo(row+1, column+1); mElements[row][column] = element; adoptElement(element); return true; } else qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; } else qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column; return false; } /*! Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't empty. \see element */ bool QCPLayoutGrid::hasElement(int row, int column) { if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) return mElements.at(row).at(column); else return false; } /*! Sets the stretch \a factor of \a column. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setColumnStretchFactors, setRowStretchFactor */ void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) { if (column >= 0 && column < columnCount()) { if (factor > 0) mColumnStretchFactors[column] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; } else qDebug() << Q_FUNC_INFO << "Invalid column:" << column; } /*! Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setColumnStretchFactor, setRowStretchFactors */ void QCPLayoutGrid::setColumnStretchFactors(const QList &factors) { if (factors.size() == mColumnStretchFactors.size()) { mColumnStretchFactors = factors; for (int i=0; i= 0 && row < rowCount()) { if (factor > 0) mRowStretchFactors[row] = factor; else qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; } else qDebug() << Q_FUNC_INFO << "Invalid row:" << row; } /*! Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize), regardless of the stretch factor. The default stretch factor of newly created rows/columns is 1. \see setRowStretchFactor, setColumnStretchFactors */ void QCPLayoutGrid::setRowStretchFactors(const QList &factors) { if (factors.size() == mRowStretchFactors.size()) { mRowStretchFactors = factors; for (int i=0; i()); mRowStretchFactors.append(1); } // go through rows and expand columns as necessary: int newColCount = qMax(columnCount(), newColumnCount); for (int i=0; i rowCount()) newIndex = rowCount(); mRowStretchFactors.insert(newIndex, 1); QList newRow; for (int col=0; col columnCount()) newIndex = columnCount(); mColumnStretchFactors.insert(newIndex, 1); for (int row=0; row minColWidths, minRowHeights, maxColWidths, maxRowHeights; getMinimumRowColSizes(&minColWidths, &minRowHeights); getMaximumRowColSizes(&maxColWidths, &maxRowHeights); int totalRowSpacing = (rowCount()-1) * mRowSpacing; int totalColSpacing = (columnCount()-1) * mColumnSpacing; QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); // go through cells and set rects accordingly: int yOffset = mRect.top(); for (int row=0; row 0) yOffset += rowHeights.at(row-1)+mRowSpacing; int xOffset = mRect.left(); for (int col=0; col 0) xOffset += colWidths.at(col-1)+mColumnSpacing; if (mElements.at(row).at(col)) mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); } } } /* inherits documentation from base class */ int QCPLayoutGrid::elementCount() const { return rowCount()*columnCount(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const { if (index >= 0 && index < elementCount()) return mElements.at(index / columnCount()).at(index % columnCount()); else return 0; } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutGrid::takeAt(int index) { if (QCPLayoutElement *el = elementAt(index)) { releaseElement(el); mElements[index / columnCount()][index % columnCount()] = 0; return el; } else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return 0; } } /* inherits documentation from base class */ bool QCPLayoutGrid::take(QCPLayoutElement *element) { if (element) { for (int i=0; i QCPLayoutGrid::elements(bool recursive) const { QList result; int colC = columnCount(); int rowC = rowCount(); #if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) result.reserve(colC*rowC); #endif for (int row=0; rowelements(recursive); } } return result; } /*! Simplifies the layout by collapsing rows and columns which only contain empty cells. */ void QCPLayoutGrid::simplify() { // remove rows with only empty cells: for (int row=rowCount()-1; row>=0; --row) { bool hasElements = false; for (int col=0; col=0; --col) { bool hasElements = false; for (int row=0; row minColWidths, minRowHeights; getMinimumRowColSizes(&minColWidths, &minRowHeights); QSize result(0, 0); for (int i=0; i maxColWidths, maxRowHeights; getMaximumRowColSizes(&maxColWidths, &maxRowHeights); QSize result(0, 0); for (int i=0; i *minColWidths, QVector *minRowHeights) const { *minColWidths = QVector(columnCount(), 0); *minRowHeights = QVector(rowCount(), 0); for (int row=0; rowminimumSizeHint(); QSize min = mElements.at(row).at(col)->minimumSize(); QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height()); if (minColWidths->at(col) < final.width()) (*minColWidths)[col] = final.width(); if (minRowHeights->at(row) < final.height()) (*minRowHeights)[row] = final.height(); } } } } /*! \internal Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights respectively. The maximum height of a row is the smallest maximum height of any element in that row. The maximum width of a column is the smallest maximum width of any element in that column. This is a helper function for \ref updateLayout. \see getMinimumRowColSizes */ void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const { *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); for (int row=0; rowmaximumSizeHint(); QSize max = mElements.at(row).at(col)->maximumSize(); QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height()); if (maxColWidths->at(col) > final.width()) (*maxColWidths)[col] = final.width(); if (maxRowHeights->at(row) > final.height()) (*maxRowHeights)[row] = final.height(); } } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLayoutInset //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLayoutInset \brief A layout that places child elements aligned to the border or arbitrarily positioned Elements are placed either aligned to the border or at arbitrary position in the area of the layout. Which placement applies is controlled with the \ref InsetPlacement (\ref setInsetPlacement). Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset placement will default to \ref ipBorderAligned and the element will be aligned according to the \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at arbitrary position and size, defined by \a rect. The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively. This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout. */ /* start documentation of inline functions */ /*! \fn virtual void QCPLayoutInset::simplify() The QCPInsetLayout does not need simplification since it can never have empty cells due to its linear index structure. This method does nothing. */ /* end documentation of inline functions */ /*! Creates an instance of QCPLayoutInset and sets default values. */ QCPLayoutInset::QCPLayoutInset() { } QCPLayoutInset::~QCPLayoutInset() { // clear all child layout elements. This is important because only the specific layouts know how // to handle removing elements (clear calls virtual removeAt method to do that). clear(); } /*! Returns the placement type of the element with the specified \a index. */ QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const { if (elementAt(index)) return mInsetPlacement.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return ipFree; } } /*! Returns the alignment of the element with the specified \a index. The alignment only has a meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned. */ Qt::Alignment QCPLayoutInset::insetAlignment(int index) const { if (elementAt(index)) return mInsetAlignment.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return 0; } } /*! Returns the rect of the element with the specified \a index. The rect only has a meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree. */ QRectF QCPLayoutInset::insetRect(int index) const { if (elementAt(index)) return mInsetRect.at(index); else { qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; return QRectF(); } } /*! Sets the inset placement type of the element with the specified \a index to \a placement. \see InsetPlacement */ void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement) { if (elementAt(index)) mInsetPlacement[index] = placement; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /*! If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function is used to set the alignment of the element with the specified \a index to \a alignment. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. */ void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment) { if (elementAt(index)) mInsetAlignment[index] = alignment; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /*! If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the position and size of the element with the specified \a index to \a rect. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. Note that the minimum and maximum sizes of the embedded element (\ref QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced. */ void QCPLayoutInset::setInsetRect(int index, const QRectF &rect) { if (elementAt(index)) mInsetRect[index] = rect; else qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; } /* inherits documentation from base class */ void QCPLayoutInset::updateLayout() { for (int i=0; iminimumSizeHint(); QSize maxSizeHint = mElements.at(i)->maximumSizeHint(); finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width()); finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height()); finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width()); finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height()); if (mInsetPlacement.at(i) == ipFree) { insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(), rect().y()+rect().height()*mInsetRect.at(i).y(), rect().width()*mInsetRect.at(i).width(), rect().height()*mInsetRect.at(i).height()); if (insetRect.size().width() < finalMinSize.width()) insetRect.setWidth(finalMinSize.width()); if (insetRect.size().height() < finalMinSize.height()) insetRect.setHeight(finalMinSize.height()); if (insetRect.size().width() > finalMaxSize.width()) insetRect.setWidth(finalMaxSize.width()); if (insetRect.size().height() > finalMaxSize.height()) insetRect.setHeight(finalMaxSize.height()); } else if (mInsetPlacement.at(i) == ipBorderAligned) { insetRect.setSize(finalMinSize); Qt::Alignment al = mInsetAlignment.at(i); if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter } mElements.at(i)->setOuterRect(insetRect); } } /* inherits documentation from base class */ int QCPLayoutInset::elementCount() const { return mElements.size(); } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::elementAt(int index) const { if (index >= 0 && index < mElements.size()) return mElements.at(index); else return 0; } /* inherits documentation from base class */ QCPLayoutElement *QCPLayoutInset::takeAt(int index) { if (QCPLayoutElement *el = elementAt(index)) { releaseElement(el); mElements.removeAt(index); mInsetPlacement.removeAt(index); mInsetAlignment.removeAt(index); mInsetRect.removeAt(index); return el; } else { qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; return 0; } } /* inherits documentation from base class */ bool QCPLayoutInset::take(QCPLayoutElement *element) { if (element) { for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) return mParentPlot->selectionTolerance()*0.99; } return -1; } /*! Adds the specified \a element to the layout as an inset aligned at the border (\ref setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a alignment. \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other alignment flags will be ignored. \see addElement(QCPLayoutElement *element, const QRectF &rect) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) { if (element) { if (element->layout()) // remove from old layout first element->layout()->take(element); mElements.append(element); mInsetPlacement.append(ipBorderAligned); mInsetAlignment.append(alignment); mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); adoptElement(element); } else qDebug() << Q_FUNC_INFO << "Can't add null element"; } /*! Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a rect. \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right corner of the layout, with 35% width and height of the parent layout. \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) */ void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) { if (element) { if (element->layout()) // remove from old layout first element->layout()->take(element); mElements.append(element); mInsetPlacement.append(ipFree); mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); mInsetRect.append(rect); adoptElement(element); } else qDebug() << Q_FUNC_INFO << "Can't add null element"; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLineEnding //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLineEnding \brief Handles the different ending decorations for line-like items \image html QCPLineEnding.png "The various ending styles currently supported" For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite directions, e.g. "outward". This can be changed by \ref setInverted, which would make the respective arrow point inward. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \code myItemLine->setHead(QCPLineEnding::esSpikeArrow) \endcode */ /*! Creates a QCPLineEnding instance with default values (style \ref esNone). */ QCPLineEnding::QCPLineEnding() : mStyle(esNone), mWidth(8), mLength(10), mInverted(false) { } /*! Creates a QCPLineEnding instance with the specified values. */ QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : mStyle(style), mWidth(width), mLength(length), mInverted(inverted) { } /*! Sets the style of the ending decoration. */ void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) { mStyle = style; } /*! Sets the width of the ending decoration, if the style supports it. On arrows, for example, the width defines the size perpendicular to the arrow's pointing direction. \see setLength */ void QCPLineEnding::setWidth(double width) { mWidth = width; } /*! Sets the length of the ending decoration, if the style supports it. On arrows, for example, the length defines the size in pointing direction. \see setWidth */ void QCPLineEnding::setLength(double length) { mLength = length; } /*! Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point inward when \a inverted is set to true. Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are affected by it, which can be used to control to which side the half bar points to. */ void QCPLineEnding::setInverted(bool inverted) { mInverted = inverted; } /*! \internal Returns the maximum pixel radius the ending decoration might cover, starting from the position the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). This is relevant for clipping. Only omit painting of the decoration when the position where the decoration is supposed to be drawn is farther away from the clipping rect than the returned distance. */ double QCPLineEnding::boundingDistance() const { switch (mStyle) { case esNone: return 0; case esFlatArrow: case esSpikeArrow: case esLineArrow: case esSkewedBar: return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length case esDisc: case esSquare: case esDiamond: case esBar: case esHalfBar: return mWidth*1.42; // items that only have a width -> width*sqrt(2) } return 0; } /*! Starting from the origin of this line ending (which is style specific), returns the length covered by the line ending symbol, in backward direction. For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if both have the same \ref setLength value, because the spike arrow has an inward curved back, which reduces the length along its center axis (the drawing origin for arrows is at the tip). This function is used for precise, style specific placement of line endings, for example in QCPAxes. */ double QCPLineEnding::realLength() const { switch (mStyle) { case esNone: case esLineArrow: case esSkewedBar: case esBar: case esHalfBar: return 0; case esFlatArrow: return mLength; case esDisc: case esSquare: case esDiamond: return mWidth*0.5; case esSpikeArrow: return mLength*0.8; } return 0; } /*! \internal Draws the line ending with the specified \a painter at the position \a pos. The direction of the line ending is controlled with \a dir. */ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const { if (mStyle == esNone) return; QVector2D lengthVec(dir.normalized()); if (lengthVec.isNull()) lengthVec = QVector2D(1, 0); QVector2D widthVec(-lengthVec.y(), lengthVec.x()); lengthVec *= (float)(mLength*(mInverted ? -1 : 1)); widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1)); QPen penBackup = painter->pen(); QBrush brushBackup = painter->brush(); QPen miterPen = penBackup; miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey QBrush brush(painter->pen().color(), Qt::SolidPattern); switch (mStyle) { case esNone: break; case esFlatArrow: { QPointF points[3] = {pos.toPointF(), (pos-lengthVec+widthVec).toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 3); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esSpikeArrow: { QPointF points[4] = {pos.toPointF(), (pos-lengthVec+widthVec).toPointF(), (pos-lengthVec*0.8f).toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esLineArrow: { QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), pos.toPointF(), (pos-lengthVec-widthVec).toPointF() }; painter->setPen(miterPen); painter->drawPolyline(points, 3); painter->setPen(penBackup); break; } case esDisc: { painter->setBrush(brush); painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); painter->setBrush(brushBackup); break; } case esSquare: { QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), (pos-widthVecPerp-widthVec).toPointF(), (pos+widthVecPerp-widthVec).toPointF(), (pos+widthVecPerp+widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esDiamond: { QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); QPointF points[4] = {(pos-widthVecPerp).toPointF(), (pos-widthVec).toPointF(), (pos+widthVecPerp).toPointF(), (pos+widthVec).toPointF() }; painter->setPen(miterPen); painter->setBrush(brush); painter->drawConvexPolygon(points, 4); painter->setBrush(brushBackup); painter->setPen(penBackup); break; } case esBar: { painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); break; } case esHalfBar: { painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); break; } case esSkewedBar: { if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic)) { // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(), (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF()); } else { // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(), (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF()); } break; } } } /*! \internal \overload Draws the line ending. The direction is controlled with the \a angle parameter in radians. */ void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const { draw(painter, pos, QVector2D(qCos(angle), qSin(angle))); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGrid //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPGrid \brief Responsible for drawing the grid of a QCPAxis. This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. The axis and grid drawing was split into two classes to allow them to be placed on different layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid in the background and the axes in the foreground, and any plottables/items in between. This described situation is the default setup, see the QCPLayer documentation. */ /*! Creates a QCPGrid instance and sets default values. You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. */ QCPGrid::QCPGrid(QCPAxis *parentAxis) : QCPLayerable(parentAxis->parentPlot(), "", parentAxis), mParentAxis(parentAxis) { // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called setParent(parentAxis); setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); setSubGridVisible(false); setAntialiased(false); setAntialiasedSubGrid(false); setAntialiasedZeroLine(false); } /*! Sets whether grid lines at sub tick marks are drawn. \see setSubGridPen */ void QCPGrid::setSubGridVisible(bool visible) { mSubGridVisible = visible; } /*! Sets whether sub grid lines are drawn antialiased. */ void QCPGrid::setAntialiasedSubGrid(bool enabled) { mAntialiasedSubGrid = enabled; } /*! Sets whether zero lines are drawn antialiased. */ void QCPGrid::setAntialiasedZeroLine(bool enabled) { mAntialiasedZeroLine = enabled; } /*! Sets the pen with which (major) grid lines are drawn. */ void QCPGrid::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen with which sub grid lines are drawn. */ void QCPGrid::setSubGridPen(const QPen &pen) { mSubGridPen = pen; } /*! Sets the pen with which zero lines are drawn. Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. */ void QCPGrid::setZeroLinePen(const QPen &pen) { mZeroLinePen = pen; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing the major grid lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); } /*! \internal Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). */ void QCPGrid::draw(QCPPainter *painter) { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } if (mSubGridVisible) drawSubGridLines(painter); drawGridLines(painter); } /*! \internal Draws the main grid lines and possibly a zero line with the specified painter. This is a helper function called by \ref draw. */ void QCPGrid::drawGridLines(QCPPainter *painter) const { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } int lowTick = mParentAxis->mLowestVisibleTick; int highTick = mParentAxis->mHighestVisibleTick; double t; // helper variable, result of coordinate-to-pixel transforms if (mParentAxis->orientation() == Qt::Horizontal) { // draw zeroline: int zeroLineIndex = -1; if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); painter->setPen(mZeroLinePen); double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero for (int i=lowTick; i <= highTick; ++i) { if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { zeroLineIndex = i; t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); break; } } } // draw grid lines: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); for (int i=lowTick; i <= highTick; ++i) { if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); } } else { // draw zeroline: int zeroLineIndex = -1; if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) { applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); painter->setPen(mZeroLinePen); double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero for (int i=lowTick; i <= highTick; ++i) { if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) { zeroLineIndex = i; t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); break; } } } // draw grid lines: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); for (int i=lowTick; i <= highTick; ++i) { if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } } } /*! \internal Draws the sub grid lines with the specified painter. This is a helper function called by \ref draw. */ void QCPGrid::drawSubGridLines(QCPPainter *painter) const { if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); double t; // helper variable, result of coordinate-to-pixel transforms painter->setPen(mSubGridPen); if (mParentAxis->orientation() == Qt::Horizontal) { for (int i=0; imSubTickVector.size(); ++i) { t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); } } else { for (int i=0; imSubTickVector.size(); ++i) { t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxis //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxis \brief Manages a single axis inside a QCustomPlot. Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and QCustomPlot::yAxis2 (right). Axes are always part of an axis rect, see QCPAxisRect. \image html AxisNamesOverview.png
Naming convention of axis parts
\n \image html AxisRectSpacingOverview.png
Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line on the left represents the QCustomPlot widget border.
*/ /* start of documentation of inline functions */ /*! \fn Qt::Orientation QCPAxis::orientation() const Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced from the axis type (left, top, right or bottom). \see orientation(AxisType type) */ /*! \fn QCPGrid *QCPAxis::grid() const Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the grid is displayed. */ /*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type) Returns the orientation of the specified axis type \see orientation() */ /* end of documentation of inline functions */ /* start of documentation of signals */ /*! \fn void QCPAxis::ticksRequest() This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick labels for a replot. Modifying the tick positions can be done with \ref setTickVector. If you also want to control the tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref setTickVectorLabels. If you only want static ticks you probably don't need this signal, since you can just set the tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this signal and set the vector/vectors there. */ /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange) This signal is emitted when the range of this axis has changed. You can connect it to the \ref setRange slot of another axis to communicate the new range to the other axis, in order for it to be synchronized. */ /*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) \overload Additionally to the new range, this signal also provides the previous range held by the axis as \a oldRange. */ /*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the scale type changes, by calls to \ref setScaleType */ /*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) This signal is emitted when the selection state of this axis has changed, either by user interaction or by a direct call to \ref setSelectedParts. */ /*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); This signal is emitted when the selectability changes, by calls to \ref setSelectableParts */ /* end of documentation of signals */ /*! Constructs an Axis instance of Type \a type for the axis rect \a parent. You shouldn't instantiate axes directly, rather use \ref QCPAxisRect::addAxis. */ QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : QCPLayerable(parent->parentPlot(), "", parent), // axis base: mAxisType(type), mAxisRect(parent), mPadding(5), mOrientation(orientation(type)), mSelectableParts(spAxis | spTickLabels | spAxisLabel), mSelectedParts(spNone), mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedBasePen(QPen(Qt::blue, 2)), // axis label: mLabel(""), mLabelFont(mParentPlot->font()), mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), mLabelColor(Qt::black), mSelectedLabelColor(Qt::blue), // tick labels: mTickLabels(true), mAutoTickLabels(true), mTickLabelType(ltNumber), mTickLabelFont(mParentPlot->font()), mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), mTickLabelColor(Qt::black), mSelectedTickLabelColor(Qt::blue), mDateTimeFormat("hh:mm:ss\ndd.MM.yy"), mDateTimeSpec(Qt::LocalTime), mNumberPrecision(6), mNumberFormatChar('g'), mNumberBeautifulPowers(true), // ticks and subticks: mTicks(true), mTickStep(1), mSubTickCount(4), mAutoTickCount(6), mAutoTicks(true), mAutoTickStep(true), mAutoSubTicks(true), mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedTickPen(QPen(Qt::blue, 2)), mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), mSelectedSubTickPen(QPen(Qt::blue, 2)), // scale and range: mRange(0, 5), mRangeReversed(false), mScaleType(stLinear), mScaleLogBase(10), mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)), // internal members: mGrid(new QCPGrid(this)), mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), mLowestVisibleTick(0), mHighestVisibleTick(-1), mCachedMarginValid(false), mCachedMargin(0) { mGrid->setVisible(false); setAntialiased(false); setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again if (type == atTop) { setTickLabelPadding(3); setLabelPadding(6); } else if (type == atRight) { setTickLabelPadding(7); setLabelPadding(12); } else if (type == atBottom) { setTickLabelPadding(3); setLabelPadding(3); } else if (type == atLeft) { setTickLabelPadding(5); setLabelPadding(10); } } QCPAxis::~QCPAxis() { delete mAxisPainter; } /* No documentation as it is a property getter */ int QCPAxis::tickLabelPadding() const { return mAxisPainter->tickLabelPadding; } /* No documentation as it is a property getter */ double QCPAxis::tickLabelRotation() const { return mAxisPainter->tickLabelRotation; } /* No documentation as it is a property getter */ QString QCPAxis::numberFormat() const { QString result; result.append(mNumberFormatChar); if (mNumberBeautifulPowers) { result.append("b"); if (mAxisPainter->numberMultiplyCross) result.append("c"); } return result; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthIn() const { return mAxisPainter->tickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::tickLengthOut() const { return mAxisPainter->tickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthIn() const { return mAxisPainter->subTickLengthIn; } /* No documentation as it is a property getter */ int QCPAxis::subTickLengthOut() const { return mAxisPainter->subTickLengthOut; } /* No documentation as it is a property getter */ int QCPAxis::labelPadding() const { return mAxisPainter->labelPadding; } /* No documentation as it is a property getter */ int QCPAxis::offset() const { return mAxisPainter->offset; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::lowerEnding() const { return mAxisPainter->lowerEnding; } /* No documentation as it is a property getter */ QCPLineEnding QCPAxis::upperEnding() const { return mAxisPainter->upperEnding; } /*! Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major ticks, consider choosing a logarithm base of 100, 1000 or even higher. If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" part). To only display the decimal power, set the number precision to zero with \ref setNumberPrecision. */ void QCPAxis::setScaleType(QCPAxis::ScaleType type) { if (mScaleType != type) { mScaleType = type; if (mScaleType == stLogarithmic) setRange(mRange.sanitizedForLogScale()); mCachedMarginValid = false; emit scaleTypeChanged(mScaleType); } } /*! If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base. Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major ticks, consider choosing \a base 100, 1000 or even higher. */ void QCPAxis::setScaleLogBase(double base) { if (base > 1) { mScaleLogBase = base; mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation mCachedMarginValid = false; } else qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base; } /*! Sets the range of the axis. This slot may be connected with the \ref rangeChanged signal of another axis so this axis is always synchronized with the other axis range, when it changes. To invert the direction of an axis, use \ref setRangeReversed. */ void QCPAxis::setRange(const QCPRange &range) { if (range.lower == mRange.lower && range.upper == mRange.upper) return; if (!QCPRange::validRange(range)) return; QCPRange oldRange = mRange; if (mScaleType == stLogarithmic) { mRange = range.sanitizedForLogScale(); } else { mRange = range.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectAxes.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPAxis::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font. The entire selection mechanism for axes is handled automatically when \ref QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part, independent of the \ref setSelectableParts setting. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor */ void QCPAxis::setSelectedParts(const SelectableParts &selected) { if (mSelectedParts != selected) { mSelectedParts = selected; emit selectionChanged(mSelectedParts); } } /*! \overload Sets the lower and upper bound of the axis range. To invert the direction of an axis, use \ref setRangeReversed. There is also a slot to set a range, see \ref setRange(const QCPRange &range). */ void QCPAxis::setRange(double lower, double upper) { if (lower == mRange.lower && upper == mRange.upper) return; if (!QCPRange::validRange(lower, upper)) return; QCPRange oldRange = mRange; mRange.lower = lower; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! \overload Sets the range of the axis. The \a position coordinate indicates together with the \a alignment parameter, where the new range will be positioned. \a size defines the size of the new axis range. \a alignment may be Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, or center of the range to be aligned with \a position. Any other values of \a alignment will default to Qt::AlignCenter. */ void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) { if (alignment == Qt::AlignLeft) setRange(position, position+size); else if (alignment == Qt::AlignRight) setRange(position-size, position); else // alignment == Qt::AlignCenter setRange(position-size/2.0, position+size/2.0); } /*! Sets the lower bound of the axis range. The upper bound is not changed. \see setRange */ void QCPAxis::setRangeLower(double lower) { if (mRange.lower == lower) return; QCPRange oldRange = mRange; mRange.lower = lower; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets the upper bound of the axis range. The lower bound is not changed. \see setRange */ void QCPAxis::setRangeUpper(double upper) { if (mRange.upper == upper) return; QCPRange oldRange = mRange; mRange.upper = upper; if (mScaleType == stLogarithmic) { mRange = mRange.sanitizedForLogScale(); } else { mRange = mRange.sanitizedForLinScale(); } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the direction of increasing values is inverted. Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part of the \ref setRange interface will still reference the mathematically smaller number than the \a upper part. */ void QCPAxis::setRangeReversed(bool reversed) { if (mRangeReversed != reversed) { mRangeReversed = reversed; mCachedMarginValid = false; } } /*! Sets whether the tick positions should be calculated automatically (either from an automatically generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep). If \a on is set to false, you must provide the tick positions manually via \ref setTickVector. For these manual ticks you may let QCPAxis generate the appropriate labels automatically by leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels manually, set \ref setAutoTickLabels to false and provide the label strings with \ref setTickVectorLabels. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the vectors in a slot connected to the \ref ticksRequest signal. \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep */ void QCPAxis::setAutoTicks(bool on) { if (mAutoTicks != on) { mAutoTicks = on; mCachedMarginValid = false; } } /*! When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be generated in the visible range, approximately. It's not guaranteed that this number of ticks is met exactly, but approximately within a tolerance of about two. Only values greater than zero are accepted as \a approximateCount. \see setAutoTickStep, setAutoTicks, setAutoSubTicks */ void QCPAxis::setAutoTickCount(int approximateCount) { if (mAutoTickCount != approximateCount) { if (approximateCount > 0) { mAutoTickCount = approximateCount; mCachedMarginValid = false; } else qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount; } } /*! Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat. If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This is usually used in a combination with \ref setAutoTicks set to false for complete control over tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi" etc. as tick labels. If you need dynamically calculated tick vectors (and possibly tick label vectors), set the vectors in a slot connected to the \ref ticksRequest signal. \see setAutoTicks */ void QCPAxis::setAutoTickLabels(bool on) { if (mAutoTickLabels != on) { mAutoTickLabels = on; mCachedMarginValid = false; } } /*! Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human readable plots. The number of ticks the algorithm aims for within the visible range can be specified with \ref setAutoTickCount. If \a on is set to false, you may set the tick step manually with \ref setTickStep. \see setAutoTicks, setAutoSubTicks, setAutoTickCount */ void QCPAxis::setAutoTickStep(bool on) { if (mAutoTickStep != on) { mAutoTickStep = on; mCachedMarginValid = false; } } /*! Sets whether the number of sub ticks in one tick interval is determined automatically. This works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is always the case. When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually. \see setAutoTickCount, setAutoTicks, setAutoTickStep */ void QCPAxis::setAutoSubTicks(bool on) { if (mAutoSubTicks != on) { mAutoSubTicks = on; mCachedMarginValid = false; } } /*! Sets whether tick marks are displayed. Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve that, see \ref setTickLabels. */ void QCPAxis::setTicks(bool show) { if (mTicks != show) { mTicks = show; mCachedMarginValid = false; } } /*! Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. */ void QCPAxis::setTickLabels(bool show) { if (mTickLabels != show) { mTickLabels = show; mCachedMarginValid = false; } } /*! Sets the distance between the axis base line (including any outward ticks) and the tick labels. \see setLabelPadding, setPadding */ void QCPAxis::setTickLabelPadding(int padding) { if (mAxisPainter->tickLabelPadding != padding) { mAxisPainter->tickLabelPadding = padding; mCachedMarginValid = false; } } /*! Sets whether the tick labels display numbers or dates/times. If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply. If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply. In QCustomPlot, date/time coordinates are double numbers representing the seconds since 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in milliseconds. Divide its return value by 1000.0 to get a value with the format needed for date/time plotting, with a resolution of one millisecond. Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C. (represented by a negative number), unlike the toTime_t function, which works with unsigned integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes. \see setTickLabels */ void QCPAxis::setTickLabelType(LabelType type) { if (mTickLabelType != type) { mTickLabelType = type; mCachedMarginValid = false; } } /*! Sets the font of the tick labels. \see setTickLabels, setTickLabelColor */ void QCPAxis::setTickLabelFont(const QFont &font) { if (font != mTickLabelFont) { mTickLabelFont = font; mCachedMarginValid = false; } } /*! Sets the color of the tick labels. \see setTickLabels, setTickLabelFont */ void QCPAxis::setTickLabelColor(const QColor &color) { if (color != mTickLabelColor) { mTickLabelColor = color; mCachedMarginValid = false; } } /*! Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values from -90 to 90 degrees. If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For other angles, the label is drawn with an offset such that it seems to point toward or away from the tick mark. */ void QCPAxis::setTickLabelRotation(double degrees) { if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) { mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); mCachedMarginValid = false; } } /*! Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime. for details about the \a format string, see the documentation of QDateTime::toString(). Newlines can be inserted with "\n". \see setDateTimeSpec */ void QCPAxis::setDateTimeFormat(const QString &format) { if (mDateTimeFormat != format) { mDateTimeFormat = format; mCachedMarginValid = false; } } /*! Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref ltDateTime. The default value of QDateTime objects (and also QCustomPlot) is Qt::LocalTime. However, if the date time values passed to QCustomPlot are given in the UTC spec, set \a timeSpec to Qt::UTC to get the correct axis labels. \see setDateTimeFormat */ void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) { mDateTimeSpec = timeSpec; } /*! Sets the number format for the numbers drawn as tick labels (if tick label type is \ref ltNumber). This \a formatCode is an extended version of the format code used e.g. by QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats" section in the detailed description of the QString class. \a formatCode is a string of one, two or three characters. The first character is identical to the normal format code used by Qt. In short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed, whichever is shorter. The second and third characters are optional and specific to QCustomPlot:\n If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5 [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot. If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the cross and 183 (0xB7) for the dot. If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b' option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" part). To only display the decimal power, set the number precision to zero with \ref setNumberPrecision. Examples for \a formatCode: \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large, normal scientific format is used \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with beautifully typeset decimal powers and a dot as multiplication sign \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as multiplication sign \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal powers. Format code will be reduced to 'f'. \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format code will not be changed. */ void QCPAxis::setNumberFormat(const QString &formatCode) { if (formatCode.isEmpty()) { qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; return; } mCachedMarginValid = false; // interpret first char as number format char: QString allowedFormatChars = "eEfgG"; if (allowedFormatChars.contains(formatCode.at(0))) { mNumberFormatChar = formatCode.at(0).toLatin1(); } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; return; } if (formatCode.length() < 2) { mNumberBeautifulPowers = false; mAxisPainter->numberMultiplyCross = false; return; } // interpret second char as indicator for beautiful decimal powers: if (formatCode.at(1) == 'b' && (mNumberFormatChar == 'e' || mNumberFormatChar == 'g')) { mNumberBeautifulPowers = true; } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; return; } if (formatCode.length() < 3) { mAxisPainter->numberMultiplyCross = false; return; } // interpret third char as indicator for dot or cross multiplication symbol: if (formatCode.at(2) == 'c') { mAxisPainter->numberMultiplyCross = true; } else if (formatCode.at(2) == 'd') { mAxisPainter->numberMultiplyCross = false; } else { qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; return; } } /*! Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec) for details. The effect of precisions are most notably for number Formats starting with 'e', see \ref setNumberFormat If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10 [superscript] n", set \a precision to zero. */ void QCPAxis::setNumberPrecision(int precision) { if (mNumberPrecision != precision) { mNumberPrecision = precision; mCachedMarginValid = false; } } /*! If \ref setAutoTickStep is set to false, use this function to set the tick step manually. The tick step is the interval between (major) ticks, in plot coordinates. \see setSubTickCount */ void QCPAxis::setTickStep(double step) { if (mTickStep != step) { mTickStep = step; mCachedMarginValid = false; } } /*! If you want full control over what ticks (and possibly labels) the axes show, this function is used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else the provided tick vector will be overwritten with automatically generated tick coordinates upon replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels. \a vec is a vector containing the positions of the ticks, in plot coordinates. \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this. \see setTickVectorLabels */ void QCPAxis::setTickVector(const QVector &vec) { // don't check whether mTickVector != vec here, because it takes longer than we would save mTickVector = vec; mCachedMarginValid = false; } /*! If you want full control over what ticks and labels the axes show, this function is used to set a number of QStrings that will be displayed at the tick positions which you need to provide with \ref setTickVector. These two vectors should have the same size. (Note that you need to disable \ref setAutoTicks and \ref setAutoTickLabels first.) \a vec is a vector containing the labels of the ticks. The entries correspond to the respective indices in the tick vector, passed via \ref setTickVector. \see setTickVector */ void QCPAxis::setTickVectorLabels(const QVector &vec) { // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save mTickVectorLabels = vec; mCachedMarginValid = false; } /*! Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLength, setTickLengthIn, setTickLengthOut */ void QCPAxis::setTickLength(int inside, int outside) { setTickLengthIn(inside); setTickLengthOut(outside); } /*! Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach inside the plot. \see setTickLengthOut, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthIn(int inside) { if (mAxisPainter->tickLengthIn != inside) { mAxisPainter->tickLengthIn = inside; } } /*! Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLengthIn, setTickLength, setSubTickLength */ void QCPAxis::setTickLengthOut(int outside) { if (mAxisPainter->tickLengthOut != outside) { mAxisPainter->tickLengthOut = outside; mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example, divides the tick intervals in four sub intervals. By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is always the case. If you want to disable automatic sub tick count and use this function to set the count manually, see \ref setAutoSubTicks. */ void QCPAxis::setSubTickCount(int count) { mSubTickCount = count; } /*! Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside the plot and \a outside is the length they will reach outside the plot. If \a outside is greater than zero, the tick labels and axis label will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setTickLength, setSubTickLengthIn, setSubTickLengthOut */ void QCPAxis::setSubTickLength(int inside, int outside) { setSubTickLengthIn(inside); setSubTickLengthOut(outside); } /*! Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside the plot. \see setSubTickLengthOut, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthIn(int inside) { if (mAxisPainter->subTickLengthIn != inside) { mAxisPainter->subTickLengthIn = inside; } } /*! Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach outside the plot. If \a outside is greater than zero, the tick labels will increase their distance to the axis accordingly, so they won't collide with the ticks. \see setSubTickLengthIn, setSubTickLength, setTickLength */ void QCPAxis::setSubTickLengthOut(int outside) { if (mAxisPainter->subTickLengthOut != outside) { mAxisPainter->subTickLengthOut = outside; mCachedMarginValid = false; // only outside tick length can change margin } } /*! Sets the pen, the axis base line is drawn with. \see setTickPen, setSubTickPen */ void QCPAxis::setBasePen(const QPen &pen) { mBasePen = pen; } /*! Sets the pen, tick marks will be drawn with. \see setTickLength, setBasePen */ void QCPAxis::setTickPen(const QPen &pen) { mTickPen = pen; } /*! Sets the pen, subtick marks will be drawn with. \see setSubTickCount, setSubTickLength, setBasePen */ void QCPAxis::setSubTickPen(const QPen &pen) { mSubTickPen = pen; } /*! Sets the font of the axis label. \see setLabelColor */ void QCPAxis::setLabelFont(const QFont &font) { if (mLabelFont != font) { mLabelFont = font; mCachedMarginValid = false; } } /*! Sets the color of the axis label. \see setLabelFont */ void QCPAxis::setLabelColor(const QColor &color) { mLabelColor = color; } /*! Sets the text of the axis label that will be shown below/above or next to the axis, depending on its orientation. To disable axis labels, pass an empty string as \a str. */ void QCPAxis::setLabel(const QString &str) { if (mLabel != str) { mLabel = str; mCachedMarginValid = false; } } /*! Sets the distance between the tick labels and the axis label. \see setTickLabelPadding, setPadding */ void QCPAxis::setLabelPadding(int padding) { if (mAxisPainter->labelPadding != padding) { mAxisPainter->labelPadding = padding; mCachedMarginValid = false; } } /*! Sets the padding of the axis. When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, that is left blank. The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. \see setLabelPadding, setTickLabelPadding */ void QCPAxis::setPadding(int padding) { if (mPadding != padding) { mPadding = padding; mCachedMarginValid = false; } } /*! Sets the offset the axis has to its axis rect side. If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, only the offset of the inner most axis has meaning (even if it is set to be invisible). The offset of the other, outer axes is controlled automatically, to place them at appropriate positions. */ void QCPAxis::setOffset(int offset) { mAxisPainter->offset = offset; } /*! Sets the font that is used for tick labels when they are selected. \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelFont(const QFont &font) { if (font != mSelectedTickLabelFont) { mSelectedTickLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } } /*! Sets the font that is used for the axis label when it is selected. \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelFont(const QFont &font) { mSelectedLabelFont = font; // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts } /*! Sets the color that is used for tick labels when they are selected. \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickLabelColor(const QColor &color) { if (color != mSelectedTickLabelColor) { mSelectedTickLabelColor = color; } } /*! Sets the color that is used for the axis label when it is selected. \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedLabelColor(const QColor &color) { mSelectedLabelColor = color; } /*! Sets the pen that is used to draw the axis base line when selected. \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedBasePen(const QPen &pen) { mSelectedBasePen = pen; } /*! Sets the pen that is used to draw the (major) ticks when selected. \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedTickPen(const QPen &pen) { mSelectedTickPen = pen; } /*! Sets the pen that is used to draw the subticks when selected. \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions */ void QCPAxis::setSelectedSubTickPen(const QPen &pen) { mSelectedSubTickPen = pen; } /*! Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available styles. For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. \see setUpperEnding */ void QCPAxis::setLowerEnding(const QCPLineEnding &ending) { mAxisPainter->lowerEnding = ending; } /*! Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available styles. For horizontal axes, this method refers to the right ending, for vertical axes the top ending. Note that this meaning does not change when the axis range is reversed with \ref setRangeReversed. \see setLowerEnding */ void QCPAxis::setUpperEnding(const QCPLineEnding &ending) { mAxisPainter->upperEnding = ending; } /*! If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper bounds of the range. The range is simply moved by \a diff. If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). */ void QCPAxis::moveRange(double diff) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { mRange.lower += diff; mRange.upper += diff; } else // mScaleType == stLogarithmic { mRange.lower *= diff; mRange.upper *= diff; } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates around 1.0 will have moved symmetrically closer to 1.0). */ void QCPAxis::scaleRange(double factor, double center) { QCPRange oldRange = mRange; if (mScaleType == stLinear) { QCPRange newRange; newRange.lower = (mRange.lower-center)*factor + center; newRange.upper = (mRange.upper-center)*factor + center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLinScale(); } else // mScaleType == stLogarithmic { if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range { QCPRange newRange; newRange.lower = pow(mRange.lower/center, factor)*center; newRange.upper = pow(mRange.upper/center, factor)*center; if (QCPRange::validRange(newRange)) mRange = newRange.sanitizedForLogScale(); } else qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; } mCachedMarginValid = false; emit rangeChanged(mRange); emit rangeChanged(mRange, oldRange); } /*! Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will be done around the center of the current axis range. For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the axis rect has. This is an operation that changes the range of this axis once, it doesn't fix the scale ratio indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent will follow. */ void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) { int otherPixelSize, ownPixelSize; if (otherAxis->orientation() == Qt::Horizontal) otherPixelSize = otherAxis->axisRect()->width(); else otherPixelSize = otherAxis->axisRect()->height(); if (orientation() == Qt::Horizontal) ownPixelSize = axisRect()->width(); else ownPixelSize = axisRect()->height(); double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize; setRange(range().center(), newRangeSize, Qt::AlignCenter); } /*! Changes the axis range such that all plottables associated with this axis are fully visible in that dimension. \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPAxis::rescale(bool onlyVisiblePlottables) { QList p = plottables(); QCPRange newRange; bool haveRange = false; for (int i=0; irealVisibility() && onlyVisiblePlottables) continue; QCPRange plottableRange; bool currentFoundRange; QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth; if (mScaleType == stLogarithmic) signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive); if (p.at(i)->keyAxis() == this) plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); else plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); if (currentFoundRange) { if (!haveRange) newRange = plottableRange; else newRange.expand(plottableRange); haveRange = true; } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (mScaleType == stLinear) { newRange.lower = center-mRange.size()/2.0; newRange.upper = center+mRange.size()/2.0; } else // mScaleType == stLogarithmic { newRange.lower = center/qSqrt(mRange.upper/mRange.lower); newRange.upper = center*qSqrt(mRange.upper/mRange.lower); } } setRange(newRange); } } /*! Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. */ double QCPAxis::pixelToCoord(double value) const { if (orientation() == Qt::Horizontal) { if (mScaleType == stLinear) { if (!mRangeReversed) return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower; else return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper; } else // mScaleType == stLogarithmic { if (!mRangeReversed) return pow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower; else return pow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper; } } else // orientation() == Qt::Vertical { if (mScaleType == stLinear) { if (!mRangeReversed) return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower; else return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper; } else // mScaleType == stLogarithmic { if (!mRangeReversed) return pow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower; else return pow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper; } } } /*! Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. */ double QCPAxis::coordToPixel(double value) const { if (orientation() == Qt::Horizontal) { if (mScaleType == stLinear) { if (!mRangeReversed) return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); else return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); } else // mScaleType == stLogarithmic { if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; else { if (!mRangeReversed) return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); else return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); } } } else // orientation() == Qt::Vertical { if (mScaleType == stLinear) { if (!mRangeReversed) return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); else return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); } else // mScaleType == stLogarithmic { if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; else { if (!mRangeReversed) return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); else return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); } } } } /*! Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this function does not change the current selection state of the axis. If the axis is not visible (\ref setVisible), this function always returns \ref spNone. \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions */ QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const { if (!mVisible) return spNone; if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) return spAxis; else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) return spTickLabels; else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) return spAxisLabel; else return spNone; } /* inherits documentation from base class */ double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mParentPlot) return -1; SelectablePart part = getPartAt(pos); if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) return -1; if (details) details->setValue(part); return mParentPlot->selectionTolerance()*0.99; } /*! Returns a list of all the plottables that have this axis as key or value axis. If you are only interested in plottables of type QCPGraph, see \ref graphs. \see graphs, items */ QList QCPAxis::plottables() const { QList result; if (!mParentPlot) return result; for (int i=0; imPlottables.size(); ++i) { if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this) result.append(mParentPlot->mPlottables.at(i)); } return result; } /*! Returns a list of all the graphs that have this axis as key or value axis. \see plottables, items */ QList QCPAxis::graphs() const { QList result; if (!mParentPlot) return result; for (int i=0; imGraphs.size(); ++i) { if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) result.append(mParentPlot->mGraphs.at(i)); } return result; } /*! Returns a list of all the items that are associated with this axis. An item is considered associated with an axis if at least one of its positions uses the axis as key or value axis. \see plottables, graphs */ QList QCPAxis::items() const { QList result; if (!mParentPlot) return result; for (int itemId=0; itemIdmItems.size(); ++itemId) { QList positions = mParentPlot->mItems.at(itemId)->positions(); for (int posId=0; posIdkeyAxis() == this || positions.at(posId)->valueAxis() == this) { result.append(mParentPlot->mItems.at(itemId)); break; } } } return result; } /*! Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.) */ QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) { switch (side) { case QCP::msLeft: return atLeft; case QCP::msRight: return atRight; case QCP::msTop: return atTop; case QCP::msBottom: return atBottom; default: break; } qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; return atLeft; } /*! Returns the axis type that describes the opposite axis of an axis with the specified \a type. */ QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) { switch (type) { case atLeft: return atRight; break; case atRight: return atLeft; break; case atBottom: return atTop; break; case atTop: return atBottom; break; default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break; } } /*! \internal This function is called to prepare the tick vector, sub tick vector and tick label vector. If \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to provide external tick positions. Then the sub tick vectors and tick label vectors are created. */ void QCPAxis::setupTickVectors() { if (!mParentPlot) return; if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself if (mAutoTicks) { generateAutoTicks(); } else { emit ticksRequest(); } visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick); if (mTickVector.isEmpty()) { mSubTickVector.clear(); return; } // generate subticks between ticks: mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount); if (mSubTickCount > 0) { double subTickStep = 0; double subTickPosition = 0; int subTickIndex = 0; bool done = false; int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick; int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick; for (int i=lowTick+1; i<=highTick; ++i) { subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1); for (int k=1; k<=mSubTickCount; ++k) { subTickPosition = mTickVector.at(i-1) + k*subTickStep; if (subTickPosition < mRange.lower) continue; if (subTickPosition > mRange.upper) { done = true; break; } mSubTickVector[subTickIndex] = subTickPosition; subTickIndex++; } if (done) break; } mSubTickVector.resize(subTickIndex); } // generate tick labels according to tick positions: if (mAutoTickLabels) { int vecsize = mTickVector.size(); mTickVectorLabels.resize(vecsize); if (mTickLabelType == ltNumber) { for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar, mNumberPrecision); } else if (mTickLabelType == ltDateTime) { for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) { #if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz") mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat); #else mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat); #endif } } } else // mAutoTickLabels == false { if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels { emit ticksRequest(); } // make sure provided tick label vector has correct (minimal) length: if (mTickVectorLabels.size() < mTickVector.size()) mTickVectorLabels.resize(mTickVector.size()); } } /*! \internal If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to generate reasonable tick positions (and subtick count). The algorithm tries to create approximately mAutoTickCount ticks (set via \ref setAutoTickCount). If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every power of the current logarithm base, set via \ref setScaleLogBase. */ void QCPAxis::generateAutoTicks() { if (mScaleType == stLinear) { if (mAutoTickStep) { // Generate tick positions according to linear scaling: mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. double tickStepMantissa = mTickStep/magnitudeFactor; if (tickStepMantissa < 5) { // round digit after decimal point to 0.5 mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor; } else { // round to first digit in multiples of 2 mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor; } } if (mAutoSubTicks) mSubTickCount = calculateAutoSubTickCount(mTickStep); // Generate tick positions according to mTickStep: qint64 firstStep = floor(mRange.lower/mTickStep); qint64 lastStep = ceil(mRange.upper/mTickStep); int tickcount = lastStep-firstStep+1; if (tickcount < 0) tickcount = 0; mTickVector.resize(tickcount); for (int i=0; i 0 && mRange.upper > 0) // positive range { double lowerMag = basePow((int)floor(baseLog(mRange.lower))); double currentMag = lowerMag; mTickVector.clear(); mTickVector.append(currentMag); while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case { currentMag *= mScaleLogBase; mTickVector.append(currentMag); } } else if (mRange.lower < 0 && mRange.upper < 0) // negative range { double lowerMag = -basePow((int)ceil(baseLog(-mRange.lower))); double currentMag = lowerMag; mTickVector.clear(); mTickVector.append(currentMag); while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case { currentMag /= mScaleLogBase; mTickVector.append(currentMag); } } else // invalid range for logarithmic scale, because lower and upper have different sign { mTickVector.clear(); qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper; } } } /*! \internal Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks, because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note that a subtick count of 4 means dividing the major tick step into 5 sections. This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is returned. */ int QCPAxis::calculateAutoSubTickCount(double tickStep) const { int result = mSubTickCount; // default to current setting, if no proper value can be found // get mantissa of tickstep: double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. double tickStepMantissa = tickStep/magnitudeFactor; // separate integer and fractional part of mantissa: double epsilon = 0.01; double intPartf; int intPart; double fracPart = modf(tickStepMantissa, &intPartf); intPart = intPartf; // handle cases with (almost) integer mantissa: if (fracPart < epsilon || 1.0-fracPart < epsilon) { if (1.0-fracPart < epsilon) ++intPart; switch (intPart) { case 1: result = 4; break; // 1.0 -> 0.2 substep case 2: result = 3; break; // 2.0 -> 0.5 substep case 3: result = 2; break; // 3.0 -> 1.0 substep case 4: result = 3; break; // 4.0 -> 1.0 substep case 5: result = 4; break; // 5.0 -> 1.0 substep case 6: result = 2; break; // 6.0 -> 2.0 substep case 7: result = 6; break; // 7.0 -> 1.0 substep case 8: result = 3; break; // 8.0 -> 2.0 substep case 9: result = 2; break; // 9.0 -> 3.0 substep } } else { // handle cases with significantly fractional mantissa: if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa { switch (intPart) { case 1: result = 2; break; // 1.5 -> 0.5 substep case 2: result = 4; break; // 2.5 -> 0.5 substep case 3: result = 4; break; // 3.5 -> 0.7 substep case 4: result = 2; break; // 4.5 -> 1.5 substep case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on) case 6: result = 4; break; // 6.5 -> 1.3 substep case 7: result = 2; break; // 7.5 -> 2.5 substep case 8: result = 4; break; // 8.5 -> 1.7 substep case 9: result = 4; break; // 9.5 -> 1.9 substep } } // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default } return result; } /* inherits documentation from base class */ void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) SelectablePart part = details.value(); if (mSelectableParts.testFlag(part)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(additive ? mSelectedParts^part : part); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ void QCPAxis::deselectEvent(bool *selectionStateChanged) { SelectableParts selBefore = mSelectedParts; setSelectedParts(mSelectedParts & ~mSelectableParts); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing axis lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); } /*! \internal Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. */ void QCPAxis::draw(QCPPainter *painter) { const int lowTick = mLowestVisibleTick; const int highTick = mHighestVisibleTick; QVector subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickLabels; // the final vector passed to QCPAxisPainter tickPositions.reserve(highTick-lowTick+1); tickLabels.reserve(highTick-lowTick+1); subTickPositions.reserve(mSubTickVector.size()); if (mTicks) { for (int i=lowTick; i<=highTick; ++i) { tickPositions.append(coordToPixel(mTickVector.at(i))); if (mTickLabels) tickLabels.append(mTickVectorLabels.at(i)); } if (mSubTickCount > 0) { const int subTickCount = mSubTickVector.size(); for (int i=0; itype = mAxisType; mAxisPainter->basePen = getBasePen(); mAxisPainter->labelFont = getLabelFont(); mAxisPainter->labelColor = getLabelColor(); mAxisPainter->label = mLabel; mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; mAxisPainter->tickPen = getTickPen(); mAxisPainter->subTickPen = getSubTickPen(); mAxisPainter->tickLabelFont = getTickLabelFont(); mAxisPainter->tickLabelColor = getTickLabelColor(); mAxisPainter->alignmentRect = mAxisRect->rect(); mAxisPainter->viewportRect = mParentPlot->viewport(); mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; mAxisPainter->reversedEndings = mRangeReversed; mAxisPainter->tickPositions = tickPositions; mAxisPainter->tickLabels = tickLabels; mAxisPainter->subTickPositions = subTickPositions; mAxisPainter->draw(painter); } /*! \internal Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in the current range. The return values are indices of the tick vector, not the positions of the ticks themselves. The actual use of this function is when an external tick vector is provided, since it might exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of subticks. If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be smaller than lowIndex. There is one case, where this function returns indices that are not really visible in the current axis range: When the tick spacing is larger than the axis range size and one tick is below the axis range and the next tick is already above the axis range. Because in such cases it is usually desirable to know the tick pair, to draw proper subticks. */ void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const { bool lowFound = false; bool highFound = false; lowIndex = 0; highIndex = -1; for (int i=0; i < mTickVector.size(); ++i) { if (mTickVector.at(i) >= mRange.lower) { lowFound = true; lowIndex = i; break; } } for (int i=mTickVector.size()-1; i >= 0; --i) { if (mTickVector.at(i) <= mRange.upper) { highFound = true; highIndex = i; break; } } if (!lowFound && highFound) lowIndex = highIndex+1; else if (lowFound && !highFound) highIndex = lowIndex-1; } /*! \internal A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation. This is set to 1.0/qLn(mScaleLogBase) in \ref setScaleLogBase. \see basePow, setScaleLogBase, setScaleType */ double QCPAxis::baseLog(double value) const { return qLn(value)*mScaleLogBaseLogInv; } /*! \internal A power function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic scales with arbitrary log base. \see baseLog, setScaleLogBase, setScaleType */ double QCPAxis::basePow(double value) const { return qPow(mScaleLogBase, value); } /*! \internal Returns the pen that is used to draw the axis base line. Depending on the selection state, this is either mSelectedBasePen or mBasePen. */ QPen QCPAxis::getBasePen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; } /*! \internal Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this is either mSelectedTickPen or mTickPen. */ QPen QCPAxis::getTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; } /*! \internal Returns the pen that is used to draw the subticks. Depending on the selection state, this is either mSelectedSubTickPen or mSubTickPen. */ QPen QCPAxis::getSubTickPen() const { return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; } /*! \internal Returns the font that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelFont or mTickLabelFont. */ QFont QCPAxis::getTickLabelFont() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; } /*! \internal Returns the font that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelFont or mLabelFont. */ QFont QCPAxis::getLabelFont() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; } /*! \internal Returns the color that is used to draw the tick labels. Depending on the selection state, this is either mSelectedTickLabelColor or mTickLabelColor. */ QColor QCPAxis::getTickLabelColor() const { return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; } /*! \internal Returns the color that is used to draw the axis label. Depending on the selection state, this is either mSelectedLabelColor or mLabelColor. */ QColor QCPAxis::getLabelColor() const { return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; } /*! \internal Returns the appropriate outward margin for this axis. It is needed if \ref QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom margin and so forth. For the calculation, this function goes through similar steps as \ref draw, so changing one function likely requires the modification of the other one as well. The margin consists of the outward tick length, tick label padding, tick label size, label padding, label size, and padding. The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. unchanged are very fast. */ int QCPAxis::calculateMargin() { if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis return 0; if (mCachedMarginValid) return mCachedMargin; // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels int margin = 0; int lowTick, highTick; visibleTickBounds(lowTick, highTick); QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter QVector tickLabels; // the final vector passed to QCPAxisPainter tickPositions.reserve(highTick-lowTick+1); tickLabels.reserve(highTick-lowTick+1); if (mTicks) { for (int i=lowTick; i<=highTick; ++i) { tickPositions.append(coordToPixel(mTickVector.at(i))); if (mTickLabels) tickLabels.append(mTickVectorLabels.at(i)); } } // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters mAxisPainter->type = mAxisType; mAxisPainter->labelFont = getLabelFont(); mAxisPainter->label = mLabel; mAxisPainter->tickLabelFont = mTickLabelFont; mAxisPainter->alignmentRect = mAxisRect->rect(); mAxisPainter->viewportRect = mParentPlot->viewport(); mAxisPainter->tickPositions = tickPositions; mAxisPainter->tickLabels = tickLabels; margin += mAxisPainter->size(); margin += mPadding; mCachedMargin = margin; mCachedMarginValid = true; return margin; } /* inherits documentation from base class */ QCP::Interaction QCPAxis::selectionCategory() const { return QCP::iSelectAxes; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisPainterPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisPainterPrivate \internal \brief (Private) This is a private class and not part of the public QCustomPlot interface. It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and axis label. It also buffers the labels to reduce replot times. The parameters are configured by directly accessing the public member variables. */ /*! Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every redraw, to utilize the caching mechanisms. */ QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : type(QCPAxis::atLeft), basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), lowerEnding(QCPLineEnding::esNone), upperEnding(QCPLineEnding::esNone), labelPadding(0), tickLabelPadding(0), tickLabelRotation(0), substituteExponent(true), numberMultiplyCross(false), tickLengthIn(5), tickLengthOut(0), subTickLengthIn(2), subTickLengthOut(0), tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), offset(0), abbreviateDecimalPowers(false), reversedEndings(false), mParentPlot(parentPlot), mLabelCache(16) // cache at most 16 (tick) labels { } QCPAxisPainterPrivate::~QCPAxisPainterPrivate() { } /*! \internal Draws the axis with the specified \a painter. The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set here, too. */ void QCPAxisPainterPrivate::draw(QCPPainter *painter) { QByteArray newHash = generateLabelParameterHash(); if (newHash != mLabelParameterHash) { mLabelCache.clear(); mLabelParameterHash = newHash; } QPoint origin; switch (type) { case QCPAxis::atLeft: origin = alignmentRect.bottomLeft() +QPoint(-offset, 0); break; case QCPAxis::atRight: origin = alignmentRect.bottomRight()+QPoint(+offset, 0); break; case QCPAxis::atTop: origin = alignmentRect.topLeft() +QPoint(0, -offset); break; case QCPAxis::atBottom: origin = alignmentRect.bottomLeft() +QPoint(0, +offset); break; } double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) switch (type) { case QCPAxis::atTop: yCor = -1; break; case QCPAxis::atRight: xCor = 1; break; default: break; } int margin = 0; // draw baseline: QLineF baseLine; painter->setPen(basePen); if (QCPAxis::orientation(type) == Qt::Horizontal) baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(alignmentRect.width()+xCor, yCor)); else baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -alignmentRect.height()+yCor)); if (reversedEndings) baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later painter->drawLine(baseLine); // draw ticks: if (!tickPositions.isEmpty()) { painter->setPen(tickPen); int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) if (QCPAxis::orientation(type) == Qt::Horizontal) { for (int i=0; idrawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor)); } else { for (int i=0; idrawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor)); } } // draw subticks: if (!subTickPositions.isEmpty()) { painter->setPen(subTickPen); // direction of ticks ("inward" is right for left axis and left for right axis) int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; if (QCPAxis::orientation(type) == Qt::Horizontal) { for (int i=0; idrawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); } else { for (int i=0; idrawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor)); } } margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); // draw axis base endings: bool antialiasingBackup = painter->antialiasing(); painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't painter->setBrush(QBrush(basePen.color())); QVector2D baseLineVector(baseLine.dx(), baseLine.dy()); if (lowerEnding.style() != QCPLineEnding::esNone) lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector); if (upperEnding.style() != QCPLineEnding::esNone) upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector); painter->setAntialiasing(antialiasingBackup); // tick labels: QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label if (!tickLabels.isEmpty()) { margin += tickLabelPadding; painter->setFont(tickLabelFont); painter->setPen(QPen(tickLabelColor)); const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); for (int i=0; isetFont(labelFont); painter->setPen(QPen(labelColor)); labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); if (type == QCPAxis::atLeft) { QTransform oldTransform = painter->transform(); painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); painter->rotate(-90); painter->drawText(0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); painter->setTransform(oldTransform); } else if (type == QCPAxis::atRight) { QTransform oldTransform = painter->transform(); painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-alignmentRect.height()); painter->rotate(90); painter->drawText(0, 0, alignmentRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); painter->setTransform(oldTransform); } else if (type == QCPAxis::atTop) painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); else if (type == QCPAxis::atBottom) painter->drawText(origin.x(), origin.y()+margin, alignmentRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); } // set selection boxes: int selectionTolerance = 0; if (mParentPlot) selectionTolerance = mParentPlot->selectionTolerance(); else qDebug() << Q_FUNC_INFO << "mParentPlot is null"; int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); int selAxisInSize = selectionTolerance; int selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); int selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; int selLabelSize = labelBounds.height(); int selLabelOffset = selTickLabelOffset+selTickLabelSize+labelPadding; if (type == QCPAxis::atLeft) { mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, alignmentRect.top(), origin.x()+selAxisInSize, alignmentRect.bottom()); mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, alignmentRect.top(), origin.x()-selTickLabelOffset, alignmentRect.bottom()); mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, alignmentRect.top(), origin.x()-selLabelOffset, alignmentRect.bottom()); } else if (type == QCPAxis::atRight) { mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, alignmentRect.top(), origin.x()+selAxisOutSize, alignmentRect.bottom()); mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, alignmentRect.top(), origin.x()+selTickLabelOffset, alignmentRect.bottom()); mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, alignmentRect.top(), origin.x()+selLabelOffset, alignmentRect.bottom()); } else if (type == QCPAxis::atTop) { mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisOutSize, alignmentRect.right(), origin.y()+selAxisInSize); mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, alignmentRect.right(), origin.y()-selTickLabelOffset); mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()-selLabelOffset-selLabelSize, alignmentRect.right(), origin.y()-selLabelOffset); } else if (type == QCPAxis::atBottom) { mAxisSelectionBox.setCoords(alignmentRect.left(), origin.y()-selAxisInSize, alignmentRect.right(), origin.y()+selAxisOutSize); mTickLabelsSelectionBox.setCoords(alignmentRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, alignmentRect.right(), origin.y()+selTickLabelOffset); mLabelSelectionBox.setCoords(alignmentRect.left(), origin.y()+selLabelOffset+selLabelSize, alignmentRect.right(), origin.y()+selLabelOffset); } // draw hitboxes for debug purposes: //painter->setBrush(Qt::NoBrush); //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); } /*! \internal Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone direction) needed to fit the axis. */ int QCPAxisPainterPrivate::size() const { int result = 0; // get length of tick marks pointing outwards: if (!tickPositions.isEmpty()) result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); // calculate size of tick labels: QSize tickLabelsSize(0, 0); if (!tickLabels.isEmpty()) { for (int i=0; iplottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled { if (!mLabelCache.contains(text)) // no cached label exists, create it { CachedLabel *newCachedLabel = new CachedLabel; TickLabelData labelData = getTickLabelData(painter->font(), text); QPointF drawOffset = getTickLabelDrawOffset(labelData); newCachedLabel->offset = drawOffset+labelData.rotatedTotalBounds.topLeft(); newCachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); newCachedLabel->pixmap.fill(Qt::transparent); QCPPainter cachePainter(&newCachedLabel->pixmap); cachePainter.setPen(painter->pen()); drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); mLabelCache.insert(text, newCachedLabel, 1); } // draw cached label: const CachedLabel *cachedLabel = mLabelCache.object(text); // if label would be partly clipped by widget border on sides, don't draw it: if (QCPAxis::orientation(type) == Qt::Horizontal) { if (labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() || labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left()) return; } else { if (labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() >viewportRect.bottom() || labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top()) return; } painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); finalSize = cachedLabel->pixmap.size(); } else // label caching disabled, draw text directly on surface: { TickLabelData labelData = getTickLabelData(painter->font(), text); QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); // if label would be partly clipped by widget border on sides, don't draw it: if (QCPAxis::orientation(type) == Qt::Horizontal) { if (finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left()) return; } else { if (finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top()) return; } drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); finalSize = labelData.rotatedTotalBounds.size(); } // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); } /*! \internal This is a \ref placeTickLabel helper function. Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when QCP::phCacheLabels plotting hint is not set. */ void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const { // backup painter settings that we're about to change: QTransform oldTransform = painter->transform(); QFont oldFont = painter->font(); // transform painter to position/rotation: painter->translate(x, y); if (!qFuzzyIsNull(tickLabelRotation)) painter->rotate(tickLabelRotation); // draw text: if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used { painter->setFont(labelData.baseFont); painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); painter->setFont(labelData.expFont); painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); } else { painter->setFont(labelData.baseFont); painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); } // reset painter settings to what it was before: painter->setTransform(oldTransform); painter->setFont(oldFont); } /*! \internal This is a \ref placeTickLabel helper function. Transforms the passed \a text and \a font to a tickLabelData structure that can then be further processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. */ QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const { TickLabelData result; // determine whether beautiful decimal powers should be used bool useBeautifulPowers = false; int ePos = -1; if (substituteExponent) { ePos = text.indexOf('e'); if (ePos > -1) useBeautifulPowers = true; } // calculate text bounding rects and do string preparation for beautiful decimal powers: result.baseFont = font; if (result.baseFont.pointSizeF() > 0) // On some rare systems, this sometimes is initialized with -1 (Qt bug?), so we check here before possibly setting a negative value in the next line result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding if (useBeautifulPowers) { // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent: result.basePart = text.left(ePos); // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base: if (abbreviateDecimalPowers && result.basePart == "1") result.basePart = "10"; else result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + "10"; result.expPart = text.mid(ePos+1); // clip "+" and leading zeros off expPart: while (result.expPart.length() > 2 && result.expPart.at(1) == '0') // length > 2 so we leave one zero when numberFormatChar is 'e' result.expPart.remove(1, 1); if (!result.expPart.isEmpty() && result.expPart.at(0) == '+') result.expPart.remove(0, 1); // prepare smaller font for exponent: result.expFont = font; result.expFont.setPointSize(result.expFont.pointSize()*0.75); // calculate bounding rects of base part, exponent part and total one: result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA } else // useBeautifulPowers == false { result.basePart = text; result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); } result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler // calculate possibly different bounding rect after rotation: result.rotatedTotalBounds = result.totalBounds; if (!qFuzzyIsNull(tickLabelRotation)) { QTransform transform; transform.rotate(tickLabelRotation); result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); } return result; } /*! \internal This is a \ref placeTickLabel helper function. Calculates the offset at which the top left corner of the specified tick label shall be drawn. The offset is relative to a point right next to the tick the label belongs to. This function is thus responsible for e.g. centering tick labels under ticks and positioning them appropriately when they are rotated. */ QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const { /* calculate label offset from base point at tick (non-trivial, for best visual appearance): short explanation for bottom axis: The anchor, i.e. the point in the label that is placed horizontally under the corresponding tick is always on the label side that is closer to the axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text will be centered under the tick (i.e. displaced horizontally by half its height). At the same time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick labels. */ bool doRotation = !qFuzzyIsNull(tickLabelRotation); bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. double radians = tickLabelRotation/180.0*M_PI; int x=0, y=0; if (type == QCPAxis::atLeft) { if (doRotation) { if (tickLabelRotation > 0) { x = -qCos(radians)*labelData.totalBounds.width(); y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; } else { x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; } } else { x = -labelData.totalBounds.width(); y = -labelData.totalBounds.height()/2.0; } } else if (type == QCPAxis::atRight) { if (doRotation) { if (tickLabelRotation > 0) { x = +qSin(radians)*labelData.totalBounds.height(); y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; } else { x = 0; y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; } } else { x = 0; y = -labelData.totalBounds.height()/2.0; } } else if (type == QCPAxis::atTop) { if (doRotation) { if (tickLabelRotation > 0) { x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); } else { x = -qSin(-radians)*labelData.totalBounds.height()/2.0; y = -qCos(-radians)*labelData.totalBounds.height(); } } else { x = -labelData.totalBounds.width()/2.0; y = -labelData.totalBounds.height(); } } else if (type == QCPAxis::atBottom) { if (doRotation) { if (tickLabelRotation > 0) { x = +qSin(radians)*labelData.totalBounds.height()/2.0; y = 0; } else { x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; y = +qSin(-radians)*labelData.totalBounds.width(); } } else { x = -labelData.totalBounds.width()/2.0; y = 0; } } return QPointF(x, y); } /*! \internal Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label to be drawn, depending on number format etc. Since only the largest tick label is wanted for the margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a smaller width/height. */ void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const { // note: this function must return the same tick label sizes as the placeTickLabel function. QSize finalSize; if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label { const CachedLabel *cachedLabel = mLabelCache.object(text); finalSize = cachedLabel->pixmap.size(); } else // label caching disabled or no label with this text cached: { TickLabelData labelData = getTickLabelData(font, text); finalSize = labelData.rotatedTotalBounds.size(); } // expand passed tickLabelsSize if current tick label is larger: if (finalSize.width() > tickLabelsSize->width()) tickLabelsSize->setWidth(finalSize.width()); if (finalSize.height() > tickLabelsSize->height()) tickLabelsSize->setHeight(finalSize.height()); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractPlottable //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractPlottable \brief The abstract base class for all data representing objects in a plot. It defines a very basic interface like name, pen, brush, visibility etc. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new ways of displaying data (see "Creating own plottables" below). All further specifics are in the subclasses, for example: \li A normal graph with possibly a line, scatter points and error bars is displayed by \ref QCPGraph (typically created with \ref QCustomPlot::addGraph). \li A parametric curve can be displayed with \ref QCPCurve. \li A stackable bar chart can be achieved with \ref QCPBars. \li A box of a statistical box plot is created with \ref QCPStatisticalBox. \section plottables-subclassing Creating own plottables To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure virtual functions, you must implement: \li \ref clearData \li \ref selectTest \li \ref draw \li \ref drawLegendIcon \li \ref getKeyRange \li \ref getValueRange See the documentation of those functions for what they need to do. For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot coordinates to pixel coordinates. This function is quite convenient, because it takes the orientation of the key and value axes into account for you (x and y are swapped when the key axis is vertical and the value axis horizontal). If you are worried about performance (i.e. you need to translate many points in a loop like QCPGraph), you can directly use \ref QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis yourself. Here are some important members you inherit from QCPAbstractPlottable:
QCustomPlot *\b mParentPlot A pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.
QString \b mName The name of the plottable.
QPen \b mPen The generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)
QPen \b mSelectedPen The generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).
QBrush \b mBrush The generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)
QBrush \b mSelectedBrush The generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).
QPointer\b mKeyAxis, \b mValueAxis The key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension. Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.
bool \b mSelected indicates whether the plottable is selected or not.
*/ /* start of documentation of pure virtual functions */ /*! \fn void QCPAbstractPlottable::clearData() = 0 Clears all data in the plottable. */ /*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 \internal called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation of this plottable inside \a rect, next to the plottable name. */ /*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0 \internal called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref sdNegative and all positive points will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output parameter that indicates whether a range could be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data). Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by this function may have size zero, which wouldn't count as a valid range. \see rescaleAxes, getValueRange */ /*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0 \internal called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain to \ref sdNegative and all positive points will be ignored for range calculation. For no restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output parameter that indicates whether a range could be found or not. If this is false, you shouldn't use the returned range (e.g. no points in data). Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by this function may have size zero, which wouldn't count as a valid range. \see rescaleAxes, getKeyRange */ /* end of documentation of pure virtual functions */ /* start of documentation of signals */ /*! \fn void QCPAbstractPlottable::selectionChanged(bool selected) This signal is emitted when the selection state of this plottable has changed, either by user interaction or by a direct call to \ref setSelected. */ /*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable); This signal is emitted when the selectability of this plottable has changed. \see setSelectable */ /* end of documentation of signals */ /*! Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and have perpendicular orientations. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, it can't be directly instantiated. You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. */ QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPLayerable(keyAxis->parentPlot(), "", keyAxis->axisRect()), mName(""), mAntialiasedFill(true), mAntialiasedScatters(true), mAntialiasedErrorBars(false), mPen(Qt::black), mSelectedPen(Qt::black), mBrush(Qt::NoBrush), mSelectedBrush(Qt::NoBrush), mKeyAxis(keyAxis), mValueAxis(valueAxis), mSelectable(true), mSelected(false) { if (keyAxis->parentPlot() != valueAxis->parentPlot()) qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; if (keyAxis->orientation() == valueAxis->orientation()) qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other."; } /*! The name is the textual representation of this plottable as it is displayed in the legend (\ref QCPLegend). It may contain any UTF-8 characters, including newlines. */ void QCPAbstractPlottable::setName(const QString &name) { mName = name; } /*! Sets whether fills of this plottable is drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedFill(bool enabled) { mAntialiasedFill = enabled; } /*! Sets whether the scatter symbols of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedScatters(bool enabled) { mAntialiasedScatters = enabled; } /*! Sets whether the error bars of this plottable are drawn antialiased or not. Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. */ void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled) { mAntialiasedErrorBars = enabled; } /*! The pen is used to draw basic lines that make up the plottable representation in the plot. For example, the \ref QCPGraph subclass draws its graph lines and scatter points with this pen. \see setBrush */ void QCPAbstractPlottable::setPen(const QPen &pen) { mPen = pen; } /*! When the plottable is selected, this pen is used to draw basic lines instead of the normal pen set via \ref setPen. \see setSelected, setSelectable, setSelectedBrush, selectTest */ void QCPAbstractPlottable::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! The brush is used to draw basic fills of the plottable representation in the plot. The Fill can be a color, gradient or texture, see the usage of QBrush. For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when it's not set to Qt::NoBrush. \see setPen */ void QCPAbstractPlottable::setBrush(const QBrush &brush) { mBrush = brush; } /*! When the plottable is selected, this brush is used to draw fills instead of the normal brush set via \ref setBrush. \see setSelected, setSelectable, setSelectedPen, selectTest */ void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's value axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setValueAxis */ void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) { mKeyAxis = axis; } /*! The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal to the plottable's key axis. This function performs no checks to make sure this is the case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the y-axis (QCustomPlot::yAxis) as value axis. Normally, the key and value axes are set in the constructor of the plottable (or \ref QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). \see setKeyAxis */ void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) { mValueAxis = axis; } /*! Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains iSelectPlottables.) However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected directly. \see setSelected */ void QCPAbstractPlottable::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this plottable is selected or not. When selected, it uses a different pen and brush to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush. The entire selection mechanism for plottables is handled automatically when \ref QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when you wish to change the selection state manually. This function can change the selection state even when \ref setSelectable was set to false. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see setSelectable, selectTest */ void QCPAbstractPlottable::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /*! Rescales the key and value axes associated with this plottable to contain all displayed data, so the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. Instead it will stay in the current sign domain and ignore all parts of the plottable that lie outside of that domain. \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has \a onlyEnlarge set to false (the default), and all subsequent set to true. \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale */ void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const { rescaleKeyAxis(onlyEnlarge); rescaleValueAxis(onlyEnlarge); } /*! Rescales the key axis of the plottable so the whole plottable is visible. See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const { QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } SignDomain signDomain = sdBoth; if (keyAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getKeyRange(foundRange, signDomain); if (foundRange) { if (onlyEnlarge) newRange.expand(keyAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (keyAxis->scaleType() == QCPAxis::stLinear) { newRange.lower = center-keyAxis->range().size()/2.0; newRange.upper = center+keyAxis->range().size()/2.0; } else // scaleType() == stLogarithmic { newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); } } keyAxis->setRange(newRange); } } /*! Rescales the value axis of the plottable so the whole plottable is visible. Returns true if the axis was actually scaled. This might not be the case if this plottable has an invalid range, e.g. because it has no data points. See \ref rescaleAxes for detailed behaviour. */ void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const { QCPAxis *valueAxis = mValueAxis.data(); if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } SignDomain signDomain = sdBoth; if (valueAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getValueRange(foundRange, signDomain); if (foundRange) { if (onlyEnlarge) newRange.expand(valueAxis->range()); if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (valueAxis->scaleType() == QCPAxis::stLinear) { newRange.lower = center-valueAxis->range().size()/2.0; newRange.upper = center+valueAxis->range().size()/2.0; } else // scaleType() == stLogarithmic { newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); } } valueAxis->setRange(newRange); } } /*! Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend). Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable needs a more specialized representation in the legend, this function will take this into account and instead create the specialized subclass of QCPAbstractLegendItem. Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in the legend. \see removeFromLegend, QCPLegend::addItem */ bool QCPAbstractPlottable::addToLegend() { if (!mParentPlot || !mParentPlot->legend) return false; if (!mParentPlot->legend->hasItemWithPlottable(this)) { mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); return true; } else return false; } /*! Removes the plottable from the legend of the parent QCustomPlot. This means the QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable is removed. Returns true on success, i.e. if the legend exists and a legend item associated with this plottable was found and removed. \see addToLegend, QCPLegend::removeItem */ bool QCPAbstractPlottable::removeFromLegend() const { if (!mParentPlot->legend) return false; if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this)) return mParentPlot->legend->removeItem(lip); else return false; } /* inherits documentation from base class */ QRect QCPAbstractPlottable::clipRect() const { if (mKeyAxis && mValueAxis) return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); else return QRect(); } /* inherits documentation from base class */ QCP::Interaction QCPAbstractPlottable::selectionCategory() const { return QCP::iSelectPlottables; } /*! \internal Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface, taking the orientations of the axes associated with this plottable into account (e.g. whether key represents x or y). \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y. \see pixelsToCoords, QCPAxis::coordToPixel */ void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { x = keyAxis->coordToPixel(key); y = valueAxis->coordToPixel(value); } else { y = keyAxis->coordToPixel(key); x = valueAxis->coordToPixel(value); } } /*! \internal \overload Returns the input as pixel coordinates in a QPointF. */ const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } if (keyAxis->orientation() == Qt::Horizontal) return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value)); else return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key)); } /*! \internal Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates, taking the orientations of the axes associated with this plottable into account (e.g. whether key represents x or y). \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value. \see coordsToPixels, QCPAxis::coordToPixel */ void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (keyAxis->orientation() == Qt::Horizontal) { key = keyAxis->pixelToCoord(x); value = valueAxis->pixelToCoord(y); } else { key = keyAxis->pixelToCoord(y); value = valueAxis->pixelToCoord(x); } } /*! \internal \overload Returns the pixel input \a pixelPos as plot coordinates \a key and \a value. */ void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const { pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); } /*! \internal Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the graph is not selected and mSelectedPen when it is. */ QPen QCPAbstractPlottable::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the graph is not selected and mSelectedBrush when it is. */ QBrush QCPAbstractPlottable::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable fills. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable scatter points. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint */ void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing plottable error bars. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint */ void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars); } /*! \internal Finds the shortest squared distance of \a point to the line segment defined by \a start and \a end. This function may be used to help with the implementation of the \ref selectTest function for specific plottables. \note This function is identical to QCPAbstractItem::distSqrToLine */ double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const { QVector2D a(start); QVector2D b(end); QVector2D p(point); QVector2D v(b-a); double vLengthSqr = v.lengthSquared(); if (!qFuzzyIsNull(vLengthSqr)) { double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; if (mu < 0) return (a-p).lengthSquared(); else if (mu > 1) return (b-p).lengthSquared(); else return ((a + mu*v)-p).lengthSquared(); } else return (a-p).lengthSquared(); } /* inherits documentation from base class */ void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemAnchor //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemAnchor \brief An anchor of an item to which positions can be attached to. An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't control anything on its item, but provides a way to tie other items via their positions to the anchor. For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight. Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the QCPItemRect. This way the start of the line will now always follow the respective anchor location on the rect item. Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an anchor to other positions. To learn how to provide anchors in your own item subclasses, see the subclassing section of the QCPAbstractItem documentation. */ /* start documentation of inline functions */ /*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with gcc compiler). */ /* end documentation of inline functions */ /*! Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) : mName(name), mParentPlot(parentPlot), mParentItem(parentItem), mAnchorId(anchorId) { } QCPItemAnchor::~QCPItemAnchor() { // unregister as parent at children: QList currentChildren(mChildren.toList()); for (int i=0; isetParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren } /*! Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the parent item, QCPItemAnchor is just an intermediary. */ QPointF QCPItemAnchor::pixelPoint() const { if (mParentItem) { if (mAnchorId > -1) { return mParentItem->anchorPixelPoint(mAnchorId); } else { qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; return QPointF(); } } else { qDebug() << Q_FUNC_INFO << "no parent item set"; return QPointF(); } } /*! \internal Adds \a pos to the child list of this anchor. This is necessary to notify the children prior to destruction of the anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::addChild(QCPItemPosition *pos) { if (!mChildren.contains(pos)) mChildren.insert(pos); else qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); } /*! \internal Removes \a pos from the child list of this anchor. Note that this function does not change the parent setting in \a pos. */ void QCPItemAnchor::removeChild(QCPItemPosition *pos) { if (!mChildren.remove(pos)) qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPosition //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemPosition \brief Manages the position of an item. Every item has at least one public QCPItemPosition member pointer which provides ways to position the item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: \a topLeft and \a bottomRight. QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel coordinates, as plot coordinates of certain axes, etc. Further, QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. (Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent anchor for other positions.) This way you can tie multiple items together. If the QCPItemPosition has a parent, the coordinates set with \ref setCoords are considered to be absolute values in the reference frame of the parent anchor, where (0, 0) means directly ontop of the parent anchor. For example, You could attach the \a start position of a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line always be centered under the text label, no matter where the text is moved to, or is itself tied to. To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified pixel values. */ /*! Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as explained in the subclassing section of the QCPAbstractItem documentation. */ QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) : QCPItemAnchor(parentPlot, parentItem, name), mPositionType(ptAbsolute), mKey(0), mValue(0), mParentAnchor(0) { } QCPItemPosition::~QCPItemPosition() { // unregister as parent at children: // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint QList currentChildren(mChildren.toList()); for (int i=0; isetParentAnchor(0); // this acts back on this anchor and child removes itself from mChildren // unregister as child in parent: if (mParentAnchor) mParentAnchor->removeChild(this); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPItemPosition::axisRect() const { return mAxisRect.data(); } /*! Sets the type of the position. The type defines how the coordinates passed to \ref setCoords should be handled and how the QCPItemPosition should behave in the plot. The possible values for \a type can be separated in two main categories: \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. By default, the QCustomPlot's x- and yAxis are used. \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref ptAxisRectRatio. They differ only in the way the absolute position is described, see the documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify the axis rect with \ref setAxisRect. By default this is set to the main axis rect. Note that the position type \ref ptPlotCoords is only available (and sensible) when the position has no parent anchor (\ref setParentAnchor). If the type is changed, the apparent pixel position on the plot is preserved. This means the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. */ void QCPItemPosition::setType(QCPItemPosition::PositionType type) { if (mPositionType != type) { // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. bool recoverPixelPosition = true; if ((mPositionType == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) recoverPixelPosition = false; if ((mPositionType == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) recoverPixelPosition = false; QPointF pixelP; if (recoverPixelPosition) pixelP = pixelPoint(); mPositionType = type; if (recoverPixelPosition) setPixelPoint(pixelP); } } /*! Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now follow any position changes of the anchor. The local coordinate system of positions with a parent anchor always is absolute with (0, 0) being exactly on top of the parent anchor. (Hence the type shouldn't be \ref ptPlotCoords for positions with parent anchors.) if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position will be exactly on top of the parent anchor. To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0. If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is set to \ref ptAbsolute, to keep the position in a valid state. */ bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) { // make sure self is not assigned as parent: if (parentAnchor == this) { qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); return false; } // make sure no recursive parent-child-relationships are created: QCPItemAnchor *currentParent = parentAnchor; while (currentParent) { if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) { // is a QCPItemPosition, might have further parent, so keep iterating if (currentParentPos == this) { qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); return false; } currentParent = currentParentPos->mParentAnchor; } else { // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the // same, to prevent a position being child of an anchor which itself depends on the position, // because they're both on the same item: if (currentParent->mParentItem == mParentItem) { qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); return false; } break; } } // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: if (!mParentAnchor && mPositionType == ptPlotCoords) setType(ptAbsolute); // save pixel position: QPointF pixelP; if (keepPixelPosition) pixelP = pixelPoint(); // unregister at current parent anchor: if (mParentAnchor) mParentAnchor->removeChild(this); // register at new parent anchor: if (parentAnchor) parentAnchor->addChild(this); mParentAnchor = parentAnchor; // restore pixel position under new parent: if (keepPixelPosition) setPixelPoint(pixelP); else setCoords(0, 0); return true; } /*! Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type (\ref setType). For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the plot coordinate system defined by the axes set by \ref setAxes. By default those are the QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available coordinate types and their meaning. \see setPixelPoint */ void QCPItemPosition::setCoords(double key, double value) { mKey = key; mValue = value; } /*! \overload Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the meaning of \a value of the \ref setCoords(double key, double value) method. */ void QCPItemPosition::setCoords(const QPointF &pos) { setCoords(pos.x(), pos.y()); } /*! Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor). \see setPixelPoint */ QPointF QCPItemPosition::pixelPoint() const { switch (mPositionType) { case ptAbsolute: { if (mParentAnchor) return QPointF(mKey, mValue) + mParentAnchor->pixelPoint(); else return QPointF(mKey, mValue); } case ptViewportRatio: { if (mParentAnchor) { return QPointF(mKey*mParentPlot->viewport().width(), mValue*mParentPlot->viewport().height()) + mParentAnchor->pixelPoint(); } else { return QPointF(mKey*mParentPlot->viewport().width(), mValue*mParentPlot->viewport().height()) + mParentPlot->viewport().topLeft(); } } case ptAxisRectRatio: { if (mAxisRect) { if (mParentAnchor) { return QPointF(mKey*mAxisRect.data()->width(), mValue*mAxisRect.data()->height()) + mParentAnchor->pixelPoint(); } else { return QPointF(mKey*mAxisRect.data()->width(), mValue*mAxisRect.data()->height()) + mAxisRect.data()->topLeft(); } } else { qDebug() << Q_FUNC_INFO << "No axis rect defined"; return QPointF(mKey, mValue); } } case ptPlotCoords: { double x, y; if (mKeyAxis && mValueAxis) { // both key and value axis are given, translate key/value to x/y coordinates: if (mKeyAxis.data()->orientation() == Qt::Horizontal) { x = mKeyAxis.data()->coordToPixel(mKey); y = mValueAxis.data()->coordToPixel(mValue); } else { y = mKeyAxis.data()->coordToPixel(mKey); x = mValueAxis.data()->coordToPixel(mValue); } } else if (mKeyAxis) { // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel: if (mKeyAxis.data()->orientation() == Qt::Horizontal) { x = mKeyAxis.data()->coordToPixel(mKey); y = mValue; } else { y = mKeyAxis.data()->coordToPixel(mKey); x = mValue; } } else if (mValueAxis) { // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel: if (mValueAxis.data()->orientation() == Qt::Horizontal) { x = mValueAxis.data()->coordToPixel(mValue); y = mKey; } else { y = mValueAxis.data()->coordToPixel(mValue); x = mKey; } } else { // no axis given, basically the same as if mPositionType were ptAbsolute qDebug() << Q_FUNC_INFO << "No axes defined"; x = mKey; y = mValue; } return QPointF(x, y); } } return QPointF(); } /*! When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and yAxis of the QCustomPlot. */ void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) { mKeyAxis = keyAxis; mValueAxis = valueAxis; } /*! When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of the QCustomPlot. */ void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) { mAxisRect = axisRect; } /*! Sets the apparent pixel position. This works no matter what type (\ref setType) this QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed appropriately, to make the position finally appear at the specified pixel values. Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is identical to that of \ref setCoords. \see pixelPoint, setCoords */ void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) { switch (mPositionType) { case ptAbsolute: { if (mParentAnchor) setCoords(pixelPoint-mParentAnchor->pixelPoint()); else setCoords(pixelPoint); break; } case ptViewportRatio: { if (mParentAnchor) { QPointF p(pixelPoint-mParentAnchor->pixelPoint()); p.rx() /= (double)mParentPlot->viewport().width(); p.ry() /= (double)mParentPlot->viewport().height(); setCoords(p); } else { QPointF p(pixelPoint-mParentPlot->viewport().topLeft()); p.rx() /= (double)mParentPlot->viewport().width(); p.ry() /= (double)mParentPlot->viewport().height(); setCoords(p); } break; } case ptAxisRectRatio: { if (mAxisRect) { if (mParentAnchor) { QPointF p(pixelPoint-mParentAnchor->pixelPoint()); p.rx() /= (double)mAxisRect.data()->width(); p.ry() /= (double)mAxisRect.data()->height(); setCoords(p); } else { QPointF p(pixelPoint-mAxisRect.data()->topLeft()); p.rx() /= (double)mAxisRect.data()->width(); p.ry() /= (double)mAxisRect.data()->height(); setCoords(p); } } else { qDebug() << Q_FUNC_INFO << "No axis rect defined"; setCoords(pixelPoint); } break; } case ptPlotCoords: { double newKey, newValue; if (mKeyAxis && mValueAxis) { // both key and value axis are given, translate point to key/value coordinates: if (mKeyAxis.data()->orientation() == Qt::Horizontal) { newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x()); newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y()); } else { newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y()); newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x()); } } else if (mKeyAxis) { // only key axis is given, depending on orientation only transform x or y to key coordinate, other stays pixel: if (mKeyAxis.data()->orientation() == Qt::Horizontal) { newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.x()); newValue = pixelPoint.y(); } else { newKey = mKeyAxis.data()->pixelToCoord(pixelPoint.y()); newValue = pixelPoint.x(); } } else if (mValueAxis) { // only value axis is given, depending on orientation only transform x or y to value coordinate, other stays pixel: if (mValueAxis.data()->orientation() == Qt::Horizontal) { newKey = pixelPoint.y(); newValue = mValueAxis.data()->pixelToCoord(pixelPoint.x()); } else { newKey = pixelPoint.x(); newValue = mValueAxis.data()->pixelToCoord(pixelPoint.y()); } } else { // no axis given, basically the same as if mPositionType were ptAbsolute qDebug() << Q_FUNC_INFO << "No axes defined"; newKey = pixelPoint.x(); newValue = pixelPoint.y(); } setCoords(newKey, newValue); break; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractItem \brief The abstract base class for all items in a plot. In QCustomPlot, items are supplemental graphical elements that are neither plottables (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each specific item has at least one QCPItemPosition member which controls the positioning. Some items are defined by more than one coordinate and thus have two or more QCPItemPosition members (For example, QCPItemRect has \a topLeft and \a bottomRight). This abstract base class defines a very basic interface like visibility and clipping. Since this class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to create new items. The built-in items are:
QCPItemLineA line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).
QCPItemStraightLineA straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.
QCPItemCurveA curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).
QCPItemRectA rectangle
QCPItemEllipseAn ellipse
QCPItemPixmapAn arbitrary pixmap
QCPItemTextA text label
QCPItemBracketA bracket which may be used to reference/highlight certain parts in the plot.
QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.
Items are by default clipped to the main axis rect. To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect. \section items-using Using items First you instantiate the item you want to use and add it to the plot: \code QCPItemLine *line = new QCPItemLine(customPlot); customPlot->addItem(line); \endcode by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just set the plot coordinates where the line should start/end: \code line->start->setCoords(-0.1, 0.8); line->end->setCoords(1.1, 0.2); \endcode If we don't want the line to be positioned in plot coordinates but a different coordinate system, e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this: \code line->start->setType(QCPItemPosition::ptAbsolute); line->end->setType(QCPItemPosition::ptAbsolute); \endcode Then we can set the coordinates, this time in pixels: \code line->start->setCoords(100, 200); line->end->setCoords(450, 320); \endcode \section items-subclassing Creating own items To create an own item, you implement a subclass of QCPAbstractItem. These are the pure virtual functions, you must implement: \li \ref selectTest \li \ref draw See the documentation of those functions for what they need to do. \subsection items-positioning Allowing the item to be positioned As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add a public member of type QCPItemPosition like so: \code QCPItemPosition * const myPosition;\endcode the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition instance it points to, can be modified, of course). The initialization of this pointer is made easy with the \ref createPosition function. Just assign the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition takes a string which is the name of the position, typically this is identical to the variable name. For example, the constructor of QCPItemExample could look like this: \code QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), myPosition(createPosition("myPosition")) { // other constructor code } \endcode \subsection items-drawing The draw function To give your item a visual representation, reimplement the \ref draw function and use the passed QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the position member(s) via \ref QCPItemPosition::pixelPoint. To optimize performance you should calculate a bounding rect first (don't forget to take the pen width into account), check whether it intersects the \ref clipRect, and only draw the item at all if this is the case. \subsection items-selection The selectTest function Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and \ref rectSelectTest. With these, the implementation of the selection test becomes significantly simpler for most items. See the documentation of \ref selectTest for what the function parameters mean and what the function should return. \subsection anchors Providing anchors Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public member, e.g. \code QCPItemAnchor * const bottom;\endcode and create it in the constructor with the \ref createAnchor function, assigning it a name and an anchor id (an integer enumerating all anchors on the item, you may create an own enum for this). Since anchors can be placed anywhere, relative to the item's position(s), your item needs to provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int anchorId) function. In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel position when anything attached to the anchor needs to know the coordinates. */ /* start of documentation of inline functions */ /*! \fn QList QCPAbstractItem::positions() const Returns all positions of the item in a list. \see anchors, position */ /*! \fn QList QCPAbstractItem::anchors() const Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always also an anchor, the list will also contain the positions of this item. \see positions, anchor */ /* end of documentation of inline functions */ /* start documentation of pure virtual functions */ /*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 \internal Draws this item with the provided \a painter. The cliprect of the provided painter is set to the rect returned by \ref clipRect before this function is called. The clipRect depends on the clipping settings defined by \ref setClipToAxisRect and \ref setClipAxisRect. */ /* end documentation of pure virtual functions */ /* start documentation of signals */ /*! \fn void QCPAbstractItem::selectionChanged(bool selected) This signal is emitted when the selection state of this item has changed, either by user interaction or by a direct call to \ref setSelected. */ /* end documentation of signals */ /*! Base class constructor which initializes base class members. */ QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : QCPLayerable(parentPlot), mClipToAxisRect(false), mSelectable(true), mSelected(false) { QList rects = parentPlot->axisRects(); if (rects.size() > 0) { setClipToAxisRect(true); setClipAxisRect(rects.first()); } } QCPAbstractItem::~QCPAbstractItem() { // don't delete mPositions because every position is also an anchor and thus in mAnchors qDeleteAll(mAnchors); } /* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ QCPAxisRect *QCPAbstractItem::clipAxisRect() const { return mClipAxisRect.data(); } /*! Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. \see setClipAxisRect */ void QCPAbstractItem::setClipToAxisRect(bool clip) { mClipToAxisRect = clip; if (mClipToAxisRect) setParentLayerable(mClipAxisRect.data()); } /*! Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref setClipToAxisRect is set to true. \see setClipToAxisRect */ void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) { mClipAxisRect = rect; if (mClipToAxisRect) setParentLayerable(mClipAxisRect.data()); } /*! Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) However, even when \a selectable was set to false, it is possible to set the selection manually, by calling \ref setSelected. \see QCustomPlot::setInteractions, setSelected */ void QCPAbstractItem::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this item is selected or not. When selected, it might use a different visual appearance (e.g. pen and brush), this depends on the specific item though. The entire selection mechanism for items is handled automatically when \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this function when you wish to change the selection state manually. This function can change the selection state even when \ref setSelectable was set to false. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. \see setSelectable, selectTest */ void QCPAbstractItem::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /*! Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by that name, returns 0. This function provides an alternative way to access item positions. Normally, you access positions direcly by their member pointers (which typically have the same variable name as \a name). \see positions, anchor */ QCPItemPosition *QCPAbstractItem::position(const QString &name) const { for (int i=0; iname() == name) return mPositions.at(i); } qDebug() << Q_FUNC_INFO << "position with name not found:" << name; return 0; } /*! Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by that name, returns 0. This function provides an alternative way to access item anchors. Normally, you access anchors direcly by their member pointers (which typically have the same variable name as \a name). \see anchors, position */ QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const { for (int i=0; iname() == name) return mAnchors.at(i); } qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; return 0; } /*! Returns whether this item has an anchor with the specified \a name. Note that you can check for positions with this function, too. This is because every position is also an anchor (QCPItemPosition inherits from QCPItemAnchor). \see anchor, position */ bool QCPAbstractItem::hasAnchor(const QString &name) const { for (int i=0; iname() == name) return true; } return false; } /*! \internal Returns the rect the visual representation of this item is clipped to. This depends on the current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect. If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned. \see draw */ QRect QCPAbstractItem::clipRect() const { if (mClipToAxisRect && mClipAxisRect) return mClipAxisRect.data()->rect(); else return mParentPlot->viewport(); } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing item lines. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); } /*! \internal Finds the shortest squared distance of \a point to the line segment defined by \a start and \a end. This function may be used to help with the implementation of the \ref selectTest function for specific items. \note This function is identical to QCPAbstractPlottable::distSqrToLine \see rectSelectTest */ double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const { QVector2D a(start); QVector2D b(end); QVector2D p(point); QVector2D v(b-a); double vLengthSqr = v.lengthSquared(); if (!qFuzzyIsNull(vLengthSqr)) { double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; if (mu < 0) return (a-p).lengthSquared(); else if (mu > 1) return (b-p).lengthSquared(); else return ((a + mu*v)-p).lengthSquared(); } else return (a-p).lengthSquared(); } /*! \internal A convenience function which returns the selectTest value for a specified \a rect and a specified click position \a pos. \a filledRect defines whether a click inside the rect should also be considered a hit or whether only the rect border is sensitive to hits. This function may be used to help with the implementation of the \ref selectTest function for specific items. For example, if your item consists of four rects, call this function four times, once for each rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned values which were greater or equal to zero. (Because this function may return -1.0 when \a pos doesn't hit \a rect at all). If all calls returned -1.0, return -1.0, too, because your item wasn't hit. \see distSqrToLine */ double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const { double result = -1; // distance to border: QList lines; lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); double minDistSqr = std::numeric_limits::max(); for (int i=0; i mParentPlot->selectionTolerance()*0.99) { if (rect.contains(pos)) result = mParentPlot->selectionTolerance()*0.99; } return result; } /*! \internal Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in item subclasses if they want to provide anchors (QCPItemAnchor). For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor ids and returns the respective pixel points of the specified anchor. \see createAnchor */ QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const { qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; return QPointF(); } /*! \internal Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the position member (This is needed to provide the name-based \ref position access to positions). Don't delete positions created by this function manually, as the item will take care of it. Use this function in the constructor (initialization list) of the specific item subclass to create each position member. Don't create QCPItemPositions with \b new yourself, because they won't be registered with the item properly. \see createAnchor */ QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) { if (hasAnchor(name)) qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); mPositions.append(newPosition); mAnchors.append(newPosition); // every position is also an anchor newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); newPosition->setType(QCPItemPosition::ptPlotCoords); if (mParentPlot->axisRect()) newPosition->setAxisRect(mParentPlot->axisRect()); newPosition->setCoords(0, 0); return newPosition; } /*! \internal Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified \a name must be a unique string that is usually identical to the variable name of the anchor member (This is needed to provide the name based \ref anchor access to anchors). The \a anchorId must be a number identifying the created anchor. It is recommended to create an enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns the correct pixel coordinates for the passed anchor id. Don't delete anchors created by this function manually, as the item will take care of it. Use this function in the constructor (initialization list) of the specific item subclass to create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they won't be registered with the item properly. \see createPosition */ QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) { if (hasAnchor(name)) qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); mAnchors.append(newAnchor); return newAnchor; } /* inherits documentation from base class */ void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ QCP::Interaction QCPAbstractItem::selectionCategory() const { return QCP::iSelectItems; } /*! \file */ /*! \mainpage %QCustomPlot 1.2.1 Documentation \image html qcp-doc-logo.png Below is a brief overview of and guide to the classes and their relations. If you are new to QCustomPlot and just want to start using it, it's recommended to look at the tutorials and examples at http://www.qcustomplot.com/ This documentation is especially helpful as a reference, when you're familiar with the basic concept of how to use %QCustomPlot and you wish to learn more about specific functionality. See the \ref classoverview "class overview" for diagrams explaining the relationships between the most important classes of the QCustomPlot library. The central widget which displays the plottables and axes on its surface is QCustomPlot. Every QCustomPlot contains four axes by default. They can be accessed via the members \ref QCustomPlot::xAxis "xAxis", \ref QCustomPlot::yAxis "yAxis", \ref QCustomPlot::xAxis2 "xAxis2" and \ref QCustomPlot::yAxis2 "yAxis2", and are of type QCPAxis. QCustomPlot supports an arbitrary number of axes and axis rects, see the documentation of QCPAxisRect for details. \section mainpage-plottables Plottables \a Plottables are classes that display any kind of data inside the QCustomPlot. They all derive from QCPAbstractPlottable. For example, the QCPGraph class is a plottable that displays a graph inside the plot with different line styles, scatter styles, filling etc. Since plotting graphs is such a dominant use case, QCustomPlot has a special interface for working with QCPGraph plottables, that makes it very easy to handle them:\n You create a new graph with QCustomPlot::addGraph and access them with QCustomPlot::graph. For all other plottables, you need to use the normal plottable interface:\n First, you create an instance of the plottable you want, e.g. \code QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode add it to the customPlot: \code customPlot->addPlottable(newCurve);\endcode and then modify the properties of the newly created plottable via the newCurve pointer. Plottables (including graphs) can be retrieved via QCustomPlot::plottable. Since the return type of that function is the abstract base class of all plottables, QCPAbstractPlottable, you will probably want to qobject_cast the returned pointer to the respective plottable subclass. (As usual, if the cast returns zero, the plottable wasn't of that specific subclass.) All further interfacing with plottables (e.g how to set data) is specific to the plottable type. See the documentations of the subclasses: QCPGraph, QCPCurve, QCPBars, QCPStatisticalBox, QCPColorMap. \section mainpage-axes Controlling the Axes As mentioned, QCustomPlot has four axes by default: \a xAxis (bottom), \a yAxis (left), \a xAxis2 (top), \a yAxis2 (right). Their range is handled by the simple QCPRange class. You can set the range with the QCPAxis::setRange function. By default, the axes represent a linear scale. To set a logarithmic scale, set \ref QCPAxis::setScaleType to \ref QCPAxis::stLogarithmic. The logarithm base can be set freely with \ref QCPAxis::setScaleLogBase. By default, an axis automatically creates and labels ticks in a sensible manner. See the following functions for tick manipulation:\n QCPAxis::setTicks, QCPAxis::setAutoTicks, QCPAxis::setAutoTickCount, QCPAxis::setAutoTickStep, QCPAxis::setTickLabels, QCPAxis::setTickLabelType, QCPAxis::setTickLabelRotation, QCPAxis::setTickStep, QCPAxis::setTickLength,... Each axis can be given an axis label (e.g. "Voltage (mV)") with QCPAxis::setLabel. The distance of an axis backbone to the respective viewport border is called its margin. Normally, the margins are calculated automatically. To change this, set \ref QCPAxisRect::setAutoMargins to exclude the respective margin sides, set the margins manually with \ref QCPAxisRect::setMargins. The main axis rect can be reached with \ref QCustomPlot::axisRect(). \section mainpage-legend Plot Legend Every QCustomPlot has one QCPLegend (as \ref QCustomPlot::legend) by default. A legend is a small layout element inside the plot which lists the plottables with an icon of the plottable line/symbol and a name (QCPAbstractPlottable::setName). Plottables can be added and removed from the main legend via \ref QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. By default, adding a plottable to QCustomPlot automatically adds it to the legend, too. This behaviour can be modified with the QCustomPlot::setAutoAddPlottableToLegend property. The QCPLegend provides an interface to access, add and remove legend items directly, too. See QCPLegend::item, QCPLegend::itemWithPlottable, QCPLegend::addItem, QCPLegend::removeItem for example. Multiple legends are supported via the \link thelayoutsystem layout system\endlink (as a QCPLegend simply is a normal layout element). \section mainpage-userinteraction User Interactions QCustomPlot supports dragging axis ranges with the mouse (\ref QCPAxisRect::setRangeDrag), zooming axis ranges with the mouse wheel (\ref QCPAxisRect::setRangeZoom) and a complete selection mechanism. The availability of these interactions is controlled with \ref QCustomPlot::setInteractions. For details about the interaction system, see the documentation there. Further, QCustomPlot always emits corresponding signals, when objects are clicked or doubleClicked. See \ref QCustomPlot::plottableClick, \ref QCustomPlot::plottableDoubleClick and \ref QCustomPlot::axisClick for example. \section mainpage-items Items Apart from plottables there is another category of plot objects that are important: Items. The base class of all items is QCPAbstractItem. An item sets itself apart from plottables in that it's not necessarily bound to any axes. This means it may also be positioned in absolute pixel coordinates or placed at a relative position on an axis rect. Further, it usually doesn't represent data directly, but acts as decoration, emphasis, description etc. Multiple items can be arranged in a parent-child-hierarchy allowing for dynamical behaviour. For example, you could place the head of an arrow at a fixed plot coordinate, so it always points to some important area in the plot. The tail of the arrow can be anchored to a text item which always resides in the top center of the axis rect, independent of where the user drags the axis ranges. This way the arrow stretches and turns so it always points from the label to the specified plot coordinate, without any further code necessary. For a more detailed introduction, see the QCPAbstractItem documentation, and from there the documentations of the individual built-in items, to find out how to use them. \section mainpage-layoutelements Layout elements and layouts QCustomPlot uses an internal layout system to provide dynamic sizing and positioning of objects like the axis rect(s), legends and the plot title. They are all based on \ref QCPLayoutElement and are arranged by placing them inside a \ref QCPLayout. Details on this topic are given on the dedicated page about \link thelayoutsystem the layout system\endlink. \section mainpage-performancetweaks Performance Tweaks Although QCustomPlot is quite fast, some features like translucent fills, antialiasing and thick lines can cause a significant slow down. If you notice this in your application, here are some thoughts on how to increase performance. By far the most time is spent in the drawing functions, specifically the drawing of graphs. For maximum performance, consider the following (most recommended/effective measures first): \li use Qt 4.8.0 and up. Performance has doubled or tripled with respect to Qt 4.7.4. However QPainter was broken and drawing pixel precise things, e.g. scatters, isn't possible with Qt >= 4.8.0. So it's a performance vs. plot quality tradeoff when switching to Qt 4.8. \li To increase responsiveness during dragging, consider setting \ref QCustomPlot::setNoAntialiasingOnDrag to true. \li On X11 (GNU/Linux), avoid the slow native drawing system, use raster by supplying "-graphicssystem raster" as command line argument or calling QApplication::setGraphicsSystem("raster") before creating the QApplication object. (Only available for Qt versions before 5.0) \li On all operating systems, use OpenGL hardware acceleration by supplying "-graphicssystem opengl" as command line argument or calling QApplication::setGraphicsSystem("opengl") (Only available for Qt versions before 5.0). If OpenGL is available, this will slightly decrease the quality of antialiasing, but extremely increase performance especially with alpha (semi-transparent) fills, much antialiasing and a large QCustomPlot drawing surface. Note however, that the maximum frame rate might be constrained by the vertical sync frequency of your monitor (VSync can be disabled in the graphics card driver configuration). So for simple plots (where the potential framerate is far above 60 frames per second), OpenGL acceleration might achieve numerically lower frame rates than the other graphics systems, because they are not capped at the VSync frequency. \li Avoid any kind of alpha (transparency), especially in fills \li Avoid lines with a pen width greater than one \li Avoid any kind of antialiasing, especially in graph lines (see \ref QCustomPlot::setNotAntialiasedElements) \li Avoid repeatedly setting the complete data set with \ref QCPGraph::setData. Use \ref QCPGraph::addData instead, if most data points stay unchanged, e.g. in a running measurement. \li Set the \a copy parameter of the setData functions to false, so only pointers get transferred. (Relevant only if preparing data maps with a large number of points, i.e. over 10000) \section mainpage-flags Preprocessor Define Flags QCustomPlot understands some preprocessor defines that are useful for debugging and compilation:
\c QCUSTOMPLOT_COMPILE_LIBRARY
Define this flag when you compile QCustomPlot as a shared library (.so/.dll)
\c QCUSTOMPLOT_USE_LIBRARY
Define this flag before including the header, when using QCustomPlot as a shared library
\c QCUSTOMPLOT_CHECK_DATA
If this flag is defined, the QCustomPlot plottables will perform data validity checks on every redraw. This means they will give qDebug output when you plot \e inf or \e nan values, they will not fix your data.
*/ /*! \page classoverview Class Overview The following diagrams may help to gain a deeper understanding of the relationships between classes that make up the QCustomPlot library. The diagrams are not exhaustive, so only the classes deemed most relevant are shown. \section classoverview-relations Class Relationship Diagram \image html RelationOverview.png "Overview of most important classes and their relations" \section classoverview-inheritance Class Inheritance Tree \image html InheritanceOverview.png "Inheritance tree of most important classes" */ //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCustomPlot //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCustomPlot \brief The central class of the library. This is the QWidget which displays the plot and interacts with the user. For tutorials on how to use QCustomPlot, see the website\n http://www.qcustomplot.com/ */ /* start of documentation of inline functions */ /*! \fn QRect QCustomPlot::viewport() const Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left (0, 0) and size of the QCustomPlot widget. Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger and contains also the axes themselves, their tick numbers, their labels, the plot title etc. Only when saving to a file (see \ref savePng, savePdf etc.) the viewport is temporarily modified to allow saving plots with sizes independent of the current widget size. */ /*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just one cell with the main QCPAxisRect inside. */ /* end of documentation of inline functions */ /* start of documentation of signals */ /*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse double click event. */ /*! \fn void QCustomPlot::mousePress(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse press event. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. */ /*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse move event. It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref QCPAxisRect::setRangeDragAxes. \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, because the dragging starting point was saved the moment the mouse was pressed. Thus it only has a meaning for the range drag axes that were set at that moment. If you want to change the drag axes, consider doing this in the \ref mousePress signal instead. */ /*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse release event. It is emitted before QCustomPlot handles any other mechanisms like object selection. So a slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or \ref QCPAbstractPlottable::setSelectable. */ /*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) This signal is emitted when the QCustomPlot receives a mouse wheel event. It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. */ /*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event) This signal is emitted when a plottable is clicked. \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. \see plottableDoubleClick */ /*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event) This signal is emitted when a plottable is double clicked. \a event is the mouse event that caused the click and \a plottable is the plottable that received the click. \see plottableClick */ /*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) This signal is emitted when an item is clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. \see itemDoubleClick */ /*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) This signal is emitted when an item is double clicked. \a event is the mouse event that caused the click and \a item is the item that received the click. \see itemClick */ /*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is clicked. \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. \see axisDoubleClick */ /*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) This signal is emitted when an axis is double clicked. \a event is the mouse event that caused the click, \a axis is the axis that received the click and \a part indicates the part of the axis that was clicked. \see axisClick */ /*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is clicked. \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. \see legendDoubleClick */ /*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) This signal is emitted when a legend (item) is double clicked. \a event is the mouse event that caused the click, \a legend is the legend that received the click and \a item is the legend item that received the click. If only the legend and no item is clicked, \a item is 0. This happens for a click inside the legend padding or the space between two items. \see legendClick */ /*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title) This signal is emitted when a plot title is clicked. \a event is the mouse event that caused the click and \a title is the plot title that received the click. \see titleDoubleClick */ /*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title) This signal is emitted when a plot title is double clicked. \a event is the mouse event that caused the click and \a title is the plot title that received the click. \see titleClick */ /*! \fn void QCustomPlot::selectionChangedByUser() This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by clicking. It is not emitted when the selection state of an object has changed programmatically by a direct call to setSelected() on an object or by calling \ref deselectAll. In addition to this signal, selectable objects also provide individual signals, for example QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are emitted even if the selection state is changed programmatically. See the documentation of \ref setInteractions for details about the selection mechanism. \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends */ /*! \fn void QCustomPlot::beforeReplot() This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref replot). It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. \see replot, afterReplot */ /*! \fn void QCustomPlot::afterReplot() This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref replot). It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. \see replot, beforeReplot */ /* end of documentation of signals */ /* start of documentation of public members */ /*! \var QCPAxis *QCustomPlot::xAxis A pointer to the primary x Axis (bottom) of the main axis rect of the plot. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPAxis *QCustomPlot::yAxis A pointer to the primary y Axis (left) of the main axis rect of the plot. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPAxis *QCustomPlot::xAxis2 A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPAxis *QCustomPlot::yAxis2 A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are invisible by default. Use QCPAxis::setVisible to change this (or use \ref QCPAxisRect::setupFullAxesBox). QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointers become 0. */ /*! \var QCPLegend *QCustomPlot::legend A pointer to the default legend of the main axis rect. The legend is invisible by default. Use QCPLegend::setVisible to change this. QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref yAxis2) and the \ref legend. They make it very easy working with plots that only have a single axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the layout system\endlink to add multiple legends to the plot, use the layout system interface to access the new legend. For example, legends can be placed inside an axis rect's \ref QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If the default legend is removed due to manipulation of the layout system (e.g. by removing the main axis rect), the corresponding pointer becomes 0. */ /* end of documentation of public members */ /*! Constructs a QCustomPlot and sets reasonable default values. */ QCustomPlot::QCustomPlot(QWidget *parent) : QWidget(parent), xAxis(0), yAxis(0), xAxis2(0), yAxis2(0), legend(0), mPlotLayout(0), mAutoAddPlottableToLegend(true), mAntialiasedElements(QCP::aeNone), mNotAntialiasedElements(QCP::aeNone), mInteractions(0), mSelectionTolerance(8), mNoAntialiasingOnDrag(false), mBackgroundBrush(Qt::white, Qt::SolidPattern), mBackgroundScaled(true), mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), mCurrentLayer(0), mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint), mMultiSelectModifier(Qt::ControlModifier), mPaintBuffer(size()), mMouseEventElement(0), mReplotting(false) { setAttribute(Qt::WA_NoMousePropagation); setAttribute(Qt::WA_OpaquePaintEvent); setMouseTracking(true); QLocale currentLocale = locale(); currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); setLocale(currentLocale); // create initial layers: mLayers.append(new QCPLayer(this, "background")); mLayers.append(new QCPLayer(this, "grid")); mLayers.append(new QCPLayer(this, "main")); mLayers.append(new QCPLayer(this, "axes")); mLayers.append(new QCPLayer(this, "legend")); updateLayerIndices(); setCurrentLayer("main"); // create initial layout, axis rect and legend: mPlotLayout = new QCPLayoutGrid; mPlotLayout->initializeParentPlot(this); mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry mPlotLayout->setLayer("main"); QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); mPlotLayout->addElement(0, 0, defaultAxisRect); xAxis = defaultAxisRect->axis(QCPAxis::atBottom); yAxis = defaultAxisRect->axis(QCPAxis::atLeft); xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); legend = new QCPLegend; legend->setVisible(false); defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); defaultAxisRect->setLayer("background"); xAxis->setLayer("axes"); yAxis->setLayer("axes"); xAxis2->setLayer("axes"); yAxis2->setLayer("axes"); xAxis->grid()->setLayer("grid"); yAxis->grid()->setLayer("grid"); xAxis2->grid()->setLayer("grid"); yAxis2->grid()->setLayer("grid"); legend->setLayer("legend"); setViewport(rect()); // needs to be called after mPlotLayout has been created replot(); } QCustomPlot::~QCustomPlot() { clearPlottables(); clearItems(); if (mPlotLayout) { delete mPlotLayout; mPlotLayout = 0; } mCurrentLayer = 0; qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed mLayers.clear(); } /*! Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is removed from there. \see setNotAntialiasedElements */ void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) { mAntialiasedElements = antialiasedElements; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mNotAntialiasedElements |= ~mAntialiasedElements; } /*! Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. See \ref setAntialiasedElements for details. \see setNotAntialiasedElement */ void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) { if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) mAntialiasedElements &= ~antialiasedElement; else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) mAntialiasedElements |= antialiasedElement; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mNotAntialiasedElements |= ~mAntialiasedElements; } /*! Sets which elements are forcibly drawn not antialiased as an \a or combination of QCP::AntialiasedElement. This overrides the antialiasing settings for whole element groups, normally controlled with the \a setAntialiasing function on the individual elements. If an element is neither specified in \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on each individual element instance is used. For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set to. if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is removed from there. \see setAntialiasedElements */ void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements) { mNotAntialiasedElements = notAntialiasedElements; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mAntialiasedElements |= ~mNotAntialiasedElements; } /*! Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. See \ref setNotAntialiasedElements for details. \see setAntialiasedElement */ void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) { if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) mNotAntialiasedElements &= ~notAntialiasedElement; else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) mNotAntialiasedElements |= notAntialiasedElement; // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: if ((mNotAntialiasedElements & mAntialiasedElements) != 0) mAntialiasedElements |= ~mNotAntialiasedElements; } /*! If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the plottable to the legend (QCustomPlot::legend). \see addPlottable, addGraph, QCPLegend::addItem */ void QCustomPlot::setAutoAddPlottableToLegend(bool on) { mAutoAddPlottableToLegend = on; } /*! Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction enums. There are the following types of interactions: Axis range manipulation is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. For details how to control which axes the user may drag/zoom and in what orientations, see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes, \ref QCPAxisRect::setRangeZoomAxes. Plottable selection is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific plottable. To find out whether a specific plottable is selected, call QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience function \ref selectedGraphs. Item selection is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of all currently selected items, call \ref selectedItems. Axis selection is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for each axis. To retrieve a list of all axes that currently contain selected parts, call \ref selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). Legend selection is controlled with \ref QCP::iSelectLegend. If this is set, the user may select the legend itself or individual items by clicking on them. What parts exactly are selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To find out which child items are selected, call \ref QCPLegend::selectedItems. All other selectable elements The selection of all other selectable objects (e.g. QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the user may select those objects by clicking on them. To find out which are currently selected, you need to check their selected state explicitly. If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is emitted. Each selectable object additionally emits an individual selectionChanged signal whenever their selection state has changed, i.e. not only by user interaction. To allow multiple objects to be selected by holding the selection modifier (\ref setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. \note In addition to the selection mechanism presented here, QCustomPlot always emits corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and \ref plottableDoubleClick for example. \see setInteraction, setSelectionTolerance */ void QCustomPlot::setInteractions(const QCP::Interactions &interactions) { mInteractions = interactions; } /*! Sets the single \a interaction of this QCustomPlot to \a enabled. For details about the interaction system, see \ref setInteractions. \see setInteractions */ void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) { if (!enabled && mInteractions.testFlag(interaction)) mInteractions &= ~interaction; else if (enabled && !mInteractions.testFlag(interaction)) mInteractions |= interaction; } /*! Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or not. If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a potential selection when the minimum distance between the click position and the graph line is smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks directly inside the area and ignore this selection tolerance. In other words, it only has meaning for parts of objects that are too thin to exactly hit with a click and thus need such a tolerance. \see setInteractions, QCPLayerable::selectTest */ void QCustomPlot::setSelectionTolerance(int pixels) { mSelectionTolerance = pixels; } /*! Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves performance during dragging. Thus it creates a more responsive user experience. As soon as the user stops dragging, the last replot is done with normal antialiasing, to restore high image quality. \see setAntialiasedElements, setNotAntialiasedElements */ void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) { mNoAntialiasingOnDrag = enabled; } /*! Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. \see setPlottingHint */ void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) { mPlottingHints = hints; } /*! Sets the specified plotting \a hint to \a enabled. \see setPlottingHints */ void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) { QCP::PlottingHints newHints = mPlottingHints; if (!enabled) newHints &= ~hint; else newHints |= hint; if (newHints != mPlottingHints) setPlottingHints(newHints); } /*! Sets the keyboard modifier that will be recognized as multi-select-modifier. If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects by clicking on them one after the other while holding down \a modifier. By default the multi-select-modifier is set to Qt::ControlModifier. \see setInteractions */ void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) { mMultiSelectModifier = modifier; } /*! Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect. This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref savePdf, etc. by temporarily changing the viewport size. */ void QCustomPlot::setViewport(const QRect &rect) { mViewport = rect; if (mPlotLayout) mPlotLayout->setOuterRect(mViewport); } /*! Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn below all other objects in the plot. For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will first be filled with that brush, before drawing the background pixmap. This can be useful for background pixmaps with translucent areas. \see setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QPixmap &pm) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); } /*! Sets the background brush of the viewport (see \ref setViewport). Before drawing everything else, the background is filled with \a brush. If a background pixmap was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport before the background pixmap is drawn. This can be useful for background pixmaps with translucent areas. Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be useful for exporting to image formats which support transparency, e.g. \ref savePng. \see setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QBrush &brush) { mBackgroundBrush = brush; } /*! \overload Allows setting the background pixmap of the viewport, whether it shall be scaled and how it shall be scaled in one call. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); mBackgroundScaled = scaled; mBackgroundScaledMode = mode; } /*! Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is set to true, control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the viewport dimensions are changed continuously.) \see setBackground, setBackgroundScaledMode */ void QCustomPlot::setBackgroundScaled(bool scaled) { mBackgroundScaled = scaled; } /*! If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap is preserved. \see setBackground, setBackgroundScaled */ void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) { mBackgroundScaledMode = mode; } /*! Returns the plottable with \a index. If the index is invalid, returns 0. There is an overloaded version of this function with no parameter which returns the last added plottable, see QCustomPlot::plottable() \see plottableCount, addPlottable */ QCPAbstractPlottable *QCustomPlot::plottable(int index) { if (index >= 0 && index < mPlottables.size()) { return mPlottables.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! \overload Returns the last plottable that was added with \ref addPlottable. If there are no plottables in the plot, returns 0. \see plottableCount, addPlottable */ QCPAbstractPlottable *QCustomPlot::plottable() { if (!mPlottables.isEmpty()) { return mPlottables.last(); } else return 0; } /*! Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable. Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the plottable's constructor). \see plottable, plottableCount, removePlottable, clearPlottables */ bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable) { if (mPlottables.contains(plottable)) { qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast(plottable); return false; } if (plottable->parentPlot() != this) { qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast(plottable); return false; } mPlottables.append(plottable); // possibly add plottable to legend: if (mAutoAddPlottableToLegend) plottable->addToLegend(); // special handling for QCPGraphs to maintain the simple graph interface: if (QCPGraph *graph = qobject_cast(plottable)) mGraphs.append(graph); if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) plottable->setLayer(currentLayer()); return true; } /*! Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend). Returns true on success. \see addPlottable, clearPlottables */ bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) { if (!mPlottables.contains(plottable)) { qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); return false; } // remove plottable from legend: plottable->removeFromLegend(); // special handling for QCPGraphs to maintain the simple graph interface: if (QCPGraph *graph = qobject_cast(plottable)) mGraphs.removeOne(graph); // remove plottable: delete plottable; mPlottables.removeOne(plottable); return true; } /*! \overload Removes the plottable by its \a index. */ bool QCustomPlot::removePlottable(int index) { if (index >= 0 && index < mPlottables.size()) return removePlottable(mPlottables[index]); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return false; } } /*! Removes all plottables from the plot (and the QCustomPlot::legend, if necessary). Returns the number of plottables removed. \see removePlottable */ int QCustomPlot::clearPlottables() { int c = mPlottables.size(); for (int i=c-1; i >= 0; --i) removePlottable(mPlottables[i]); return c; } /*! Returns the number of currently existing plottables in the plot \see plottable, addPlottable */ int QCustomPlot::plottableCount() const { return mPlottables.size(); } /*! Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected */ QList QCustomPlot::selectedPlottables() const { QList result; foreach (QCPAbstractPlottable *plottable, mPlottables) { if (plottable->selected()) result.append(plottable); } return result; } /*! Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple plottables come into consideration, the one closest to \a pos is returned. If \a onlySelectable is true, only plottables that are selectable (QCPAbstractPlottable::setSelectable) are considered. If there is no plottable at \a pos, the return value is 0. \see itemAt, layoutElementAt */ QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const { QCPAbstractPlottable *resultPlottable = 0; double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value foreach (QCPAbstractPlottable *plottable, mPlottables) { if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable continue; if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes { double currentDistance = plottable->selectTest(pos, false); if (currentDistance >= 0 && currentDistance < resultDistance) { resultPlottable = plottable; resultDistance = currentDistance; } } } return resultPlottable; } /*! Returns whether this QCustomPlot instance contains the \a plottable. \see addPlottable */ bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const { return mPlottables.contains(plottable); } /*! Returns the graph with \a index. If the index is invalid, returns 0. There is an overloaded version of this function with no parameter which returns the last created graph, see QCustomPlot::graph() \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph(int index) const { if (index >= 0 && index < mGraphs.size()) { return mGraphs.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! \overload Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, returns 0. \see graphCount, addGraph */ QCPGraph *QCustomPlot::graph() const { if (!mGraphs.isEmpty()) { return mGraphs.last(); } else return 0; } /*! Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a keyAxis and \a valueAxis must reside in this QCustomPlot. \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically "y") for the graph. Returns a pointer to the newly created graph, or 0 if adding the graph failed. \see graph, graphCount, removeGraph, clearGraphs */ QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) { if (!keyAxis) keyAxis = xAxis; if (!valueAxis) valueAxis = yAxis; if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; return 0; } if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) { qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; return 0; } QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); if (addPlottable(newGraph)) { newGraph->setName("Graph "+QString::number(mGraphs.size())); return newGraph; } else { delete newGraph; return 0; } } /*! Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If any other graphs in the plot have a channel fill set towards the removed graph, the channel fill property of those graphs is reset to zero (no channel fill). Returns true on success. \see clearGraphs */ bool QCustomPlot::removeGraph(QCPGraph *graph) { return removePlottable(graph); } /*! \overload Removes the graph by its \a index. */ bool QCustomPlot::removeGraph(int index) { if (index >= 0 && index < mGraphs.size()) return removeGraph(mGraphs[index]); else return false; } /*! Removes all graphs from the plot (and the QCustomPlot::legend, if necessary). Returns the number of graphs removed. \see removeGraph */ int QCustomPlot::clearGraphs() { int c = mGraphs.size(); for (int i=c-1; i >= 0; --i) removeGraph(mGraphs[i]); return c; } /*! Returns the number of currently existing graphs in the plot \see graph, addGraph */ int QCustomPlot::graphCount() const { return mGraphs.size(); } /*! Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars, etc., use \ref selectedPlottables. \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected */ QList QCustomPlot::selectedGraphs() const { QList result; foreach (QCPGraph *graph, mGraphs) { if (graph->selected()) result.append(graph); } return result; } /*! Returns the item with \a index. If the index is invalid, returns 0. There is an overloaded version of this function with no parameter which returns the last added item, see QCustomPlot::item() \see itemCount, addItem */ QCPAbstractItem *QCustomPlot::item(int index) const { if (index >= 0 && index < mItems.size()) { return mItems.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! \overload Returns the last item, that was added with \ref addItem. If there are no items in the plot, returns 0. \see itemCount, addItem */ QCPAbstractItem *QCustomPlot::item() const { if (!mItems.isEmpty()) { return mItems.last(); } else return 0; } /*! Adds the specified item to the plot. QCustomPlot takes ownership of the item. Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a item is this QCustomPlot. \see item, itemCount, removeItem, clearItems */ bool QCustomPlot::addItem(QCPAbstractItem *item) { if (!mItems.contains(item) && item->parentPlot() == this) { mItems.append(item); return true; } else { qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast(item); return false; } } /*! Removes the specified item from the plot. Returns true on success. \see addItem, clearItems */ bool QCustomPlot::removeItem(QCPAbstractItem *item) { if (mItems.contains(item)) { delete item; mItems.removeOne(item); return true; } else { qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); return false; } } /*! \overload Removes the item by its \a index. */ bool QCustomPlot::removeItem(int index) { if (index >= 0 && index < mItems.size()) return removeItem(mItems[index]); else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return false; } } /*! Removes all items from the plot. Returns the number of items removed. \see removeItem */ int QCustomPlot::clearItems() { int c = mItems.size(); for (int i=c-1; i >= 0; --i) removeItem(mItems[i]); return c; } /*! Returns the number of currently existing items in the plot \see item, addItem */ int QCustomPlot::itemCount() const { return mItems.size(); } /*! Returns a list of the selected items. If no items are currently selected, the list is empty. \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected */ QList QCustomPlot::selectedItems() const { QList result; foreach (QCPAbstractItem *item, mItems) { if (item->selected()) result.append(item); } return result; } /*! Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is returned. If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are considered. If there is no item at \a pos, the return value is 0. \see plottableAt, layoutElementAt */ QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const { QCPAbstractItem *resultItem = 0; double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value foreach (QCPAbstractItem *item, mItems) { if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable continue; if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it { double currentDistance = item->selectTest(pos, false); if (currentDistance >= 0 && currentDistance < resultDistance) { resultItem = item; resultDistance = currentDistance; } } } return resultItem; } /*! Returns whether this QCustomPlot contains the \a item. \see addItem */ bool QCustomPlot::hasItem(QCPAbstractItem *item) const { return mItems.contains(item); } /*! Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is returned. Layer names are case-sensitive. \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(const QString &name) const { foreach (QCPLayer *layer, mLayers) { if (layer->name() == name) return layer; } return 0; } /*! \overload Returns the layer by \a index. If the index is invalid, 0 is returned. \see addLayer, moveLayer, removeLayer */ QCPLayer *QCustomPlot::layer(int index) const { if (index >= 0 && index < mLayers.size()) { return mLayers.at(index); } else { qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; return 0; } } /*! Returns the layer that is set as current layer (see \ref setCurrentLayer). */ QCPLayer *QCustomPlot::currentLayer() const { return mCurrentLayer; } /*! Sets the layer with the specified \a name to be the current layer. All layerables (\ref QCPLayerable), e.g. plottables and items, are created on the current layer. Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. Layer names are case-sensitive. \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer */ bool QCustomPlot::setCurrentLayer(const QString &name) { if (QCPLayer *newCurrentLayer = layer(name)) { return setCurrentLayer(newCurrentLayer); } else { qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; return false; } } /*! \overload Sets the provided \a layer to be the current layer. Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. \see addLayer, moveLayer, removeLayer */ bool QCustomPlot::setCurrentLayer(QCPLayer *layer) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); return false; } mCurrentLayer = layer; return true; } /*! Returns the number of currently existing layers in the plot \see layer, addLayer */ int QCustomPlot::layerCount() const { return mLayers.size(); } /*! Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a valid layer inside this QCustomPlot. If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. \see layer, moveLayer, removeLayer */ bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { if (!otherLayer) otherLayer = mLayers.last(); if (!mLayers.contains(otherLayer)) { qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); return false; } if (layer(name)) { qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; return false; } QCPLayer *newLayer = new QCPLayer(this, name); mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer); updateLayerIndices(); return true; } /*! Removes the specified \a layer and returns true on success. All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both cases, the total rendering order of all layerables in the QCustomPlot is preserved. If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom layer) becomes the new current layer. It is not possible to remove the last layer of the plot. \see layer, addLayer, moveLayer */ bool QCustomPlot::removeLayer(QCPLayer *layer) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); return false; } if (mLayers.size() < 2) { qDebug() << Q_FUNC_INFO << "can't remove last layer"; return false; } // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) int removedIndex = layer->index(); bool isFirstLayer = removedIndex==0; QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); QList children = layer->children(); if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same) { for (int i=children.size()-1; i>=0; --i) children.at(i)->moveToLayer(targetLayer, true); } else // append normally { for (int i=0; imoveToLayer(targetLayer, false); } // if removed layer is current layer, change current layer to layer below/above: if (layer == mCurrentLayer) setCurrentLayer(targetLayer); // remove layer: delete layer; mLayers.removeOne(layer); updateLayerIndices(); return true; } /*! Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or below is controlled with \a insertMode. Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the QCustomPlot. \see layer, addLayer, moveLayer */ bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) { if (!mLayers.contains(layer)) { qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); return false; } if (!mLayers.contains(otherLayer)) { qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); return false; } mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0)); updateLayerIndices(); return true; } /*! Returns the number of axis rects in the plot. All axis rects can be accessed via QCustomPlot::axisRect(). Initially, only one axis rect exists in the plot. \see axisRect, axisRects */ int QCustomPlot::axisRectCount() const { return axisRects().size(); } /*! Returns the axis rect with \a index. Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were added, all of them may be accessed with this function in a linear fashion (even when they are nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). \see axisRectCount, axisRects */ QCPAxisRect *QCustomPlot::axisRect(int index) const { const QList rectList = axisRects(); if (index >= 0 && index < rectList.size()) { return rectList.at(index); } else { qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; return 0; } } /*! Returns all axis rects in the plot. \see axisRectCount, axisRect */ QList QCustomPlot::axisRects() const { QList result; QStack elementStack; if (mPlotLayout) elementStack.push(mPlotLayout); while (!elementStack.isEmpty()) { foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) { if (element) { elementStack.push(element); if (QCPAxisRect *ar = qobject_cast(element)) result.append(ar); } } } return result; } /*! Returns the layout element at pixel position \a pos. If there is no element at that position, returns 0. Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on any of its parent elements is set to false, it will not be considered. \see itemAt, plottableAt */ QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const { QCPLayoutElement *currentElement = mPlotLayout; bool searchSubElements = true; while (searchSubElements && currentElement) { searchSubElements = false; foreach (QCPLayoutElement *subElement, currentElement->elements(false)) { if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0) { currentElement = subElement; searchSubElements = true; break; } } } return currentElement; } /*! Returns the axes that currently have selected parts, i.e. whose selection state is not \ref QCPAxis::spNone. \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, QCPAxis::setSelectableParts */ QList QCustomPlot::selectedAxes() const { QList result, allAxes; foreach (QCPAxisRect *rect, axisRects()) allAxes << rect->axes(); foreach (QCPAxis *axis, allAxes) { if (axis->selectedParts() != QCPAxis::spNone) result.append(axis); } return result; } /*! Returns the legends that currently have selected parts, i.e. whose selection state is not \ref QCPLegend::spNone. \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, QCPLegend::setSelectableParts, QCPLegend::selectedItems */ QList QCustomPlot::selectedLegends() const { QList result; QStack elementStack; if (mPlotLayout) elementStack.push(mPlotLayout); while (!elementStack.isEmpty()) { foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) { if (subElement) { elementStack.push(subElement); if (QCPLegend *leg = qobject_cast(subElement)) { if (leg->selectedParts() != QCPLegend::spNone) result.append(leg); } } } } return result; } /*! Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. Since calling this function is not a user interaction, this does not emit the \ref selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the objects were previously selected. \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends */ void QCustomPlot::deselectAll() { foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *layerable, layer->children()) layerable->deselectEvent(0); } } /*! Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the buffer on the QCustomPlot widget surface. This is the method that must be called to make changes, for example on the axis ranges or data points of graphs, visible. Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the QCustomPlot widget and user interactions (object selection and range dragging/zooming). Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite recursion. */ void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) { if (mReplotting) // incase signals loop back to replot slot return; mReplotting = true; emit beforeReplot(); mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); QCPPainter painter; painter.begin(&mPaintBuffer); if (painter.isActive()) { painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) painter.fillRect(mViewport, mBackgroundBrush); draw(&painter); painter.end(); if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate) repaint(); else update(); } else // might happen if QCustomPlot has width or height zero qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer"; emit afterReplot(); mReplotting = false; } /*! Rescales the axes such that all plottables (like graphs) in the plot are fully visible. if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true (QCPLayerable::setVisible), will be used to rescale the axes. \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale */ void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) { QList allAxes; foreach (QCPAxisRect *rect, axisRects()) allAxes << rect->axes(); foreach (QCPAxis *axis, allAxes) axis->rescale(onlyVisiblePlottables); } /*! Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale of texts and lines will be derived from the specified \a width and \a height. This means, the output will look like the normal on-screen output of a QCustomPlot widget with the corresponding pixel width and height. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter and QPen documentation. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. Returns true on success. \warning \li If you plan on editing the exported PDF file with a vector graphics editor like Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks). \li If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting PDF file. \note On Android systems, this method does nothing and issues an according qDebug warning message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set. \see savePng, saveBmp, saveJpg, saveRastered */ bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle) { bool success = false; #ifdef QT_NO_PRINTER Q_UNUSED(fileName) Q_UNUSED(noCosmeticPen) Q_UNUSED(width) Q_UNUSED(height) qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; #else int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } QPrinter printer(QPrinter::ScreenResolution); printer.setOutputFileName(fileName); printer.setOutputFormat(QPrinter::PdfFormat); printer.setFullPage(true); printer.setColorMode(QPrinter::Color); printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); QCPPainter printpainter; if (printpainter.begin(&printer)) { printpainter.setMode(QCPPainter::pmVectorized); printpainter.setMode(QCPPainter::pmNoCaching); printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen); printpainter.setWindow(mViewport); if (mBackgroundBrush.style() != Qt::NoBrush && mBackgroundBrush.color() != Qt::white && mBackgroundBrush.color() != Qt::transparent && mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent printpainter.fillRect(viewport(), mBackgroundBrush); draw(&printpainter); printpainter.end(); success = true; } setViewport(oldViewport); #endif // QT_NO_PRINTER return success; } /*! Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. If you want the PNG to have a transparent background, call \ref setBackground(const QBrush &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving. PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or -1 to use the default setting. Returns true on success. If this function fails, most likely the PNG format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see savePdf, saveBmp, saveJpg, saveRastered */ bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality) { return saveRastered(fileName, width, height, scale, "PNG", quality); } /*! Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or -1 to use the default setting. Returns true on success. If this function fails, most likely the JPG format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see savePdf, savePng, saveBmp, saveRastered */ bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality) { return saveRastered(fileName, width, height, scale, "JPG", quality); } /*! Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width and \a height in pixels. If either \a width or \a height is zero, the exported image will have the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full 200*200 pixel resolution. If you use a high scaling factor, it is recommended to enable antialiasing for all elements via temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows QCustomPlot to place objects with sub-pixel accuracy. \warning If calling this function inside the constructor of the parent of the QCustomPlot widget (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this function uses the current width and height of the QCustomPlot widget. However, in Qt, these aren't defined yet inside the constructor, so you would get an image that has strange widths/heights. The objects of the plot will appear in the current selection state. If you don't want any selected objects to be painted in their selected look, deselect everything with \ref deselectAll before calling this function. Returns true on success. If this function fails, most likely the BMP format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see savePdf, savePng, saveJpg, saveRastered */ bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale) { return saveRastered(fileName, width, height, scale, "BMP"); } /*! \internal Returns a minimum size hint that corresponds to the minimum size of the top level layout (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. This is especially important, when placed in a QLayout where other components try to take in as much space as possible (e.g. QMdiArea). */ QSize QCustomPlot::minimumSizeHint() const { return mPlotLayout->minimumSizeHint(); } /*! \internal Returns a size hint that is the same as \ref minimumSizeHint. */ QSize QCustomPlot::sizeHint() const { return mPlotLayout->minimumSizeHint(); } /*! \internal Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but draws the internal buffer on the widget surface. */ void QCustomPlot::paintEvent(QPaintEvent *event) { Q_UNUSED(event); QPainter painter(this); painter.drawPixmap(0, 0, mPaintBuffer); } /*! \internal Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized appropriately. Finally a \ref replot is performed. */ void QCustomPlot::resizeEvent(QResizeEvent *event) { // resize and repaint the buffer: mPaintBuffer = QPixmap(event->size()); setViewport(rect()); replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts } /*! \internal Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to it. \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event) { emit mouseDoubleClick(event); QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // emit specialized object double click signals: if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) emit plottableDoubleClick(ap, event); else if (QCPAxis *ax = qobject_cast(clickedLayerable)) emit axisDoubleClick(ax, details.value(), event); else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) emit itemDoubleClick(ai, event); else if (QCPLegend *lg = qobject_cast(clickedLayerable)) emit legendDoubleClick(lg, 0, event); else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) emit legendDoubleClick(li->parentLegend(), li, event); else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) emit titleDoubleClick(event, pt); // call double click event of affected layout element: if (QCPLayoutElement *el = layoutElementAt(event->pos())) el->mouseDoubleClickEvent(event); // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case): if (mMouseEventElement) { mMouseEventElement->mouseReleaseEvent(event); mMouseEventElement = 0; } //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want. } /*! \internal Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines the affected layout element and forwards the event to it. \see mouseMoveEvent, mouseReleaseEvent */ void QCustomPlot::mousePressEvent(QMouseEvent *event) { emit mousePress(event); mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release) // call event of affected layout element: mMouseEventElement = layoutElementAt(event->pos()); if (mMouseEventElement) mMouseEventElement->mousePressEvent(event); QWidget::mousePressEvent(event); } /*! \internal Event handler for when the cursor is moved. Emits the \ref mouseMove signal. If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout element before), the mouseMoveEvent is forwarded to that element. \see mousePressEvent, mouseReleaseEvent */ void QCustomPlot::mouseMoveEvent(QMouseEvent *event) { emit mouseMove(event); // call event of affected layout element: if (mMouseEventElement) mMouseEventElement->mouseMoveEvent(event); QWidget::mouseMoveEvent(event); } /*! \internal Event handler for when a mouse button is released. Emits the \ref mouseRelease signal. If the mouse was moved less than a certain threshold in any direction since the \ref mousePressEvent, it is considered a click which causes the selection mechanism (if activated via \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.) If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout element before), the \ref mouseReleaseEvent is forwarded to that element. \see mousePressEvent, mouseMoveEvent */ void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) { emit mouseRelease(event); bool doReplot = false; if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation { if (event->button() == Qt::LeftButton) { // handle selection mechanism: QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details); bool selectionStateChanged = false; bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier); // deselect all other layerables if not additive selection: if (!additive) { foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *layerable, layer->children()) { if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory())) { bool selChanged = false; layerable->deselectEvent(&selChanged); selectionStateChanged |= selChanged; } } } } if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory())) { // a layerable was actually clicked, call its selectEvent: bool selChanged = false; clickedLayerable->selectEvent(event, additive, details, &selChanged); selectionStateChanged |= selChanged; } doReplot = true; if (selectionStateChanged) emit selectionChangedByUser(); } // emit specialized object click signals: QVariant details; QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) emit plottableClick(ap, event); else if (QCPAxis *ax = qobject_cast(clickedLayerable)) emit axisClick(ax, details.value(), event); else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) emit itemClick(ai, event); else if (QCPLegend *lg = qobject_cast(clickedLayerable)) emit legendClick(lg, 0, event); else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) emit legendClick(li->parentLegend(), li, event); else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) emit titleClick(event, pt); } // call event of affected layout element: if (mMouseEventElement) { mMouseEventElement->mouseReleaseEvent(event); mMouseEventElement = 0; } if (doReplot || noAntialiasingOnDrag()) replot(); QWidget::mouseReleaseEvent(event); } /*! \internal Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then determines the affected layout element and forwards the event to it. */ void QCustomPlot::wheelEvent(QWheelEvent *event) { emit mouseWheel(event); // call event of affected layout element: if (QCPLayoutElement *el = layoutElementAt(event->pos())) el->wheelEvent(event); QWidget::wheelEvent(event); } /*! \internal This is the main draw function. It draws the entire plot, including background pixmap, with the specified \a painter. Note that it does not fill the background with the background brush (as the user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter). */ void QCustomPlot::draw(QCPPainter *painter) { // run through layout phases: mPlotLayout->update(QCPLayoutElement::upPreparation); mPlotLayout->update(QCPLayoutElement::upMargins); mPlotLayout->update(QCPLayoutElement::upLayout); // draw viewport background pixmap: drawBackground(painter); // draw all layered objects (grid, axes, plottables, items, legend,...): foreach (QCPLayer *layer, mLayers) { foreach (QCPLayerable *child, layer->children()) { if (child->realVisibility()) { painter->save(); painter->setClipRect(child->clipRect().translated(0, -1)); child->applyDefaultAntialiasingHint(painter); child->draw(painter); painter->restore(); } } } /* Debug code to draw all layout element rects foreach (QCPLayoutElement* el, findChildren()) { painter->setBrush(Qt::NoBrush); painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->rect()); painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); painter->drawRect(el->outerRect()); } */ } /*! \internal Draws the viewport background pixmap of the plot. If a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the viewport with the provided \a painter. The scaled version is buffered in mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was set. Note that this function does not draw a fill with the background brush (\ref setBackground(const QBrush &brush)) beneath the pixmap. \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCustomPlot::drawBackground(QCPPainter *painter) { // Note: background color is handled in individual replot/save functions // draw background pixmap (on top of fill, if brush specified): if (!mBackgroundPixmap.isNull()) { if (mBackgroundScaled) { // check whether mScaledBackground needs to be updated: QSize scaledSize(mBackgroundPixmap.size()); scaledSize.scale(mViewport.size(), mBackgroundScaledMode); if (mScaledBackgroundPixmap.size() != scaledSize) mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); } else { painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); } } } /*! \internal This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. */ void QCustomPlot::axisRemoved(QCPAxis *axis) { if (xAxis == axis) xAxis = 0; if (xAxis2 == axis) xAxis2 = 0; if (yAxis == axis) yAxis = 0; if (yAxis2 == axis) yAxis2 = 0; // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers } /*! \internal This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so it may clear its QCustomPlot::legend member accordingly. */ void QCustomPlot::legendRemoved(QCPLegend *legend) { if (this->legend == legend) this->legend = 0; } /*! \internal Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called after every operation that changes the layer indices, like layer removal, layer creation, layer moving. */ void QCustomPlot::updateLayerIndices() const { for (int i=0; imIndex = i; } /*! \internal Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those layerables that are selectable will be considered. (Layerable subclasses communicate their selectability via the QCPLayerable::selectTest method, by returning -1.) \a selectionDetails is an output parameter that contains selection specifics of the affected layerable. This is useful if the respective layerable shall be given a subsequent QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains information about which part of the layerable was hit, in multi-part layerables (e.g. QCPAxis::SelectablePart). */ QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const { for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex) { const QList layerables = mLayers.at(layerIndex)->children(); double minimumDistance = selectionTolerance()*1.1; QCPLayerable *minimumDistanceLayerable = 0; for (int i=layerables.size()-1; i>=0; --i) { if (!layerables.at(i)->realVisibility()) continue; QVariant details; double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details); if (dist >= 0 && dist < minimumDistance) { minimumDistance = dist; minimumDistanceLayerable = layerables.at(i); if (selectionDetails) *selectionDetails = details; } } if (minimumDistance < selectionTolerance()) return minimumDistanceLayerable; } return 0; } /*! Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead to a full resolution file with width 200.) If the \a format supports compression, \a quality may be between 0 and 100 to control it. Returns true on success. If this function fails, most likely the given \a format isn't supported by the system, see Qt docs about QImageWriter::supportedImageFormats(). \see saveBmp, saveJpg, savePng, savePdf */ bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality) { QPixmap buffer = toPixmap(width, height, scale); if (!buffer.isNull()) return buffer.save(fileName, format, quality); else return false; } /*! Renders the plot to a pixmap and returns it. The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead to a full resolution pixmap with width 200.) \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf */ QPixmap QCustomPlot::toPixmap(int width, int height, double scale) { // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } int scaledWidth = qRound(scale*newWidth); int scaledHeight = qRound(scale*newHeight); QPixmap result(scaledWidth, scaledHeight); result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later QCPPainter painter; painter.begin(&result); if (painter.isActive()) { QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); painter.setMode(QCPPainter::pmNoCaching); if (!qFuzzyCompare(scale, 1.0)) { if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales painter.setMode(QCPPainter::pmNonCosmetic); painter.scale(scale, scale); } if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) painter.fillRect(mViewport, mBackgroundBrush); draw(&painter); setViewport(oldViewport); painter.end(); } else // might happen if pixmap has width or height zero { qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; return QPixmap(); } return result; } /*! Renders the plot using the passed \a painter. The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will appear scaled accordingly. \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. \see toPixmap */ void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) { // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. int newWidth, newHeight; if (width == 0 || height == 0) { newWidth = this->width(); newHeight = this->height(); } else { newWidth = width; newHeight = height; } if (painter->isActive()) { QRect oldViewport = viewport(); setViewport(QRect(0, 0, newWidth, newHeight)); painter->setMode(QCPPainter::pmNoCaching); // warning: the following is different in toPixmap, because a solid background color is applied there via QPixmap::fill // here, we need to do this via QPainter::fillRect. if (mBackgroundBrush.style() != Qt::NoBrush) painter->fillRect(mViewport, mBackgroundBrush); draw(painter); setViewport(oldViewport); } else qDebug() << Q_FUNC_INFO << "Passed painter is not active"; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorGradient //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorGradient \brief Defines a color gradient for use with e.g. \ref QCPColorMap This class describes a color gradient which can be used to encode data with color. For example, QCPColorMap and QCPColorScale have a \ref QCPColorMap::setGradient "setGradient" method which takes an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) with a \a position from 0 to 1. In between these defined color positions, the color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation. Alternatively, load one of the preset color gradients shown in the image below, with \ref loadPreset, or by directly specifying the preset in the constructor. \image html QCPColorGradient.png The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref GradientPreset to all the \a setGradient methods, e.g.: \code colorMap->setGradient(QCPColorGradient::gpHot); \endcode The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the color gradient shall be applied periodically (wrapping around) to data values that lie outside the data range specified on the plottable instance can be controlled with \ref setPeriodic. */ /*! Constructs a new QCPColorGradient initialized with the colors and color interpolation according to \a preset. The color level count is initialized to 350. */ QCPColorGradient::QCPColorGradient(GradientPreset preset) : mLevelCount(350), mColorInterpolation(ciRGB), mPeriodic(false), mColorBufferInvalidated(true) { mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); loadPreset(preset); } /* undocumented operator */ bool QCPColorGradient::operator==(const QCPColorGradient &other) const { return ((other.mLevelCount == this->mLevelCount) && (other.mColorInterpolation == this->mColorInterpolation) && (other.mPeriodic == this->mPeriodic) && (other.mColorStops == this->mColorStops)); } /*! Sets the number of discretization levels of the color gradient to \a n. The default is 350 which is typically enough to create a smooth appearance. \image html QCPColorGradient-levelcount.png */ void QCPColorGradient::setLevelCount(int n) { if (n < 2) { qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; n = 2; } if (n != mLevelCount) { mLevelCount = n; mColorBufferInvalidated = true; } } /*! Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the colors are the values of the passed QMap \a colorStops. In between these color stops, the color is interpolated according to \ref setColorInterpolation. A more convenient way to create a custom gradient may be to clear all color stops with \ref clearColorStops and then adding them one by one with \ref setColorStopAt. \see clearColorStops */ void QCPColorGradient::setColorStops(const QMap &colorStops) { mColorStops = colorStops; mColorBufferInvalidated = true; } /*! Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between these color stops, the color is interpolated according to \ref setColorInterpolation. \see setColorStops, clearColorStops */ void QCPColorGradient::setColorStopAt(double position, const QColor &color) { mColorStops.insert(position, color); mColorBufferInvalidated = true; } /*! Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be interpolated linearly in RGB or in HSV color space. For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, whereas in HSV space the intermediate color is yellow. */ void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) { if (interpolation != mColorInterpolation) { mColorInterpolation = interpolation; mColorBufferInvalidated = true; } } /*! Sets whether data points that are outside the configured data range (e.g. \ref QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether they all have the same color, corresponding to the respective gradient boundary color. \image html QCPColorGradient-periodic.png As shown in the image above, gradients that have the same start and end color are especially suitable for a periodic gradient mapping, since they produce smooth color transitions throughout the color map. A preset that has this property is \ref gpHues. In practice, using periodic color gradients makes sense when the data corresponds to a periodic dimension, such as an angle or a phase. If this is not the case, the color encoding might become ambiguous, because multiple different data values are shown as the same color. */ void QCPColorGradient::setPeriodic(bool enabled) { mPeriodic = enabled; } /*! This method is used to quickly convert a \a data array to colors. The colors will be output in the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this function. The data range that shall be used for mapping the data value to the gradient is passed in \a range. \a logarithmic indicates whether the data values shall be mapped to colors logarithmically. if \a data actually contains 2D-data linearized via [row*columnCount + column], you can set \a dataIndexFactor to columnCount to convert a column instead of a row of the data array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data is addressed data[i*dataIndexFactor]. */ void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic) { // If you change something here, make sure to also adapt ::color() if (!data) { qDebug() << Q_FUNC_INFO << "null pointer given as data"; return; } if (!scanLine) { qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; return; } if (mColorBufferInvalidated) updateColorBuffer(); if (!logarithmic) { const double posToIndexFactor = mLevelCount/range.size(); if (mPeriodic) { for (int i=0; i= mLevelCount) index = mLevelCount-1; scanLine[i] = mColorBuffer.at(index); } } } else // logarithmic == true { if (mPeriodic) { for (int i=0; i= mLevelCount) index = mLevelCount-1; scanLine[i] = mColorBuffer.at(index); } } } } /*! \internal This method is used to colorize a single data value given in \a position, to colors. The data range that shall be used for mapping the data value to the gradient is passed in \a range. \a logarithmic indicates whether the data value shall be mapped to a color logarithmically. If an entire array of data values shall be converted, rather use \ref colorize, for better performance. */ QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic) { // If you change something here, make sure to also adapt ::colorize() if (mColorBufferInvalidated) updateColorBuffer(); int index = 0; if (!logarithmic) index = (position-range.lower)*mLevelCount/range.size(); else index = qLn(position/range.lower)/qLn(range.upper/range.lower)*mLevelCount; if (mPeriodic) { index = index % mLevelCount; if (index < 0) index += mLevelCount; } else { if (index < 0) index = 0; else if (index >= mLevelCount) index = mLevelCount-1; } return mColorBuffer.at(index); } /*! Clears the current color stops and loads the specified \a preset. A preset consists of predefined color stops and the corresponding color interpolation method. The available presets are: \image html QCPColorGradient.png */ void QCPColorGradient::loadPreset(GradientPreset preset) { clearColorStops(); switch (preset) { case gpGrayscale: setColorInterpolation(ciRGB); setColorStopAt(0, Qt::black); setColorStopAt(1, Qt::white); break; case gpHot: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(50, 0, 0)); setColorStopAt(0.2, QColor(180, 10, 0)); setColorStopAt(0.4, QColor(245, 50, 0)); setColorStopAt(0.6, QColor(255, 150, 10)); setColorStopAt(0.8, QColor(255, 255, 50)); setColorStopAt(1, QColor(255, 255, 255)); break; case gpCold: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(0, 0, 50)); setColorStopAt(0.2, QColor(0, 10, 180)); setColorStopAt(0.4, QColor(0, 50, 245)); setColorStopAt(0.6, QColor(10, 150, 255)); setColorStopAt(0.8, QColor(50, 255, 255)); setColorStopAt(1, QColor(255, 255, 255)); break; case gpNight: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(10, 20, 30)); setColorStopAt(1, QColor(250, 255, 250)); break; case gpCandy: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(0, 0, 255)); setColorStopAt(1, QColor(255, 250, 250)); break; case gpGeography: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(70, 170, 210)); setColorStopAt(0.20, QColor(90, 160, 180)); setColorStopAt(0.25, QColor(45, 130, 175)); setColorStopAt(0.30, QColor(100, 140, 125)); setColorStopAt(0.5, QColor(100, 140, 100)); setColorStopAt(0.6, QColor(130, 145, 120)); setColorStopAt(0.7, QColor(140, 130, 120)); setColorStopAt(0.9, QColor(180, 190, 190)); setColorStopAt(1, QColor(210, 210, 230)); break; case gpIon: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(50, 10, 10)); setColorStopAt(0.45, QColor(0, 0, 255)); setColorStopAt(0.8, QColor(0, 255, 255)); setColorStopAt(1, QColor(0, 255, 0)); break; case gpThermal: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(0, 0, 50)); setColorStopAt(0.15, QColor(20, 0, 120)); setColorStopAt(0.33, QColor(200, 30, 140)); setColorStopAt(0.6, QColor(255, 100, 0)); setColorStopAt(0.85, QColor(255, 255, 40)); setColorStopAt(1, QColor(255, 255, 255)); break; case gpPolar: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(50, 255, 255)); setColorStopAt(0.18, QColor(10, 70, 255)); setColorStopAt(0.28, QColor(10, 10, 190)); setColorStopAt(0.5, QColor(0, 0, 0)); setColorStopAt(0.72, QColor(190, 10, 10)); setColorStopAt(0.82, QColor(255, 70, 10)); setColorStopAt(1, QColor(255, 255, 50)); break; case gpSpectrum: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(50, 0, 50)); setColorStopAt(0.15, QColor(0, 0, 255)); setColorStopAt(0.35, QColor(0, 255, 255)); setColorStopAt(0.6, QColor(255, 255, 0)); setColorStopAt(0.75, QColor(255, 30, 0)); setColorStopAt(1, QColor(50, 0, 0)); break; case gpJet: setColorInterpolation(ciRGB); setColorStopAt(0, QColor(0, 0, 100)); setColorStopAt(0.15, QColor(0, 50, 255)); setColorStopAt(0.35, QColor(0, 255, 255)); setColorStopAt(0.65, QColor(255, 255, 0)); setColorStopAt(0.85, QColor(255, 30, 0)); setColorStopAt(1, QColor(100, 0, 0)); break; case gpHues: setColorInterpolation(ciHSV); setColorStopAt(0, QColor(255, 0, 0)); setColorStopAt(1.0/3.0, QColor(0, 0, 255)); setColorStopAt(2.0/3.0, QColor(0, 255, 0)); setColorStopAt(1, QColor(255, 0, 0)); break; } } /*! Clears all color stops. \see setColorStops, setColorStopAt */ void QCPColorGradient::clearColorStops() { mColorStops.clear(); mColorBufferInvalidated = true; } /*! Returns an inverted gradient. The inverted gradient has all properties as this \ref QCPColorGradient, but the order of the color stops is inverted. \see setColorStops, setColorStopAt */ QCPColorGradient QCPColorGradient::inverted() const { QCPColorGradient result(*this); result.clearColorStops(); for (QMap::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) result.setColorStopAt(1.0-it.key(), it.value()); return result; } /*! \internal Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly convert positions to colors. This is where the interpolation between color stops is calculated. */ void QCPColorGradient::updateColorBuffer() { if (mColorBuffer.size() != mLevelCount) mColorBuffer.resize(mLevelCount); if (mColorStops.size() > 1) { double indexToPosFactor = 1.0/(double)(mLevelCount-1); for (int i=0; i::const_iterator it = mColorStops.lowerBound(position); if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop { mColorBuffer[i] = (it-1).value().rgb(); } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop { mColorBuffer[i] = it.value().rgb(); } else // position is in between stops (or on an intermediate stop), interpolate color { QMap::const_iterator high = it; QMap::const_iterator low = it-1; double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 switch (mColorInterpolation) { case ciRGB: { mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(), (1-t)*low.value().green() + t*high.value().green(), (1-t)*low.value().blue() + t*high.value().blue()); break; } case ciHSV: { QColor lowHsv = low.value().toHsv(); QColor highHsv = high.value().toHsv(); double hue = 0; double hueDiff = highHsv.hueF()-lowHsv.hueF(); if (hueDiff > 0.5) hue = lowHsv.hueF() - t*(1.0-hueDiff); else if (hueDiff < -0.5) hue = lowHsv.hueF() + t*(1.0+hueDiff); else hue = lowHsv.hueF() + t*hueDiff; if (hue < 0) hue += 1.0; else if (hue >= 1.0) hue -= 1.0; mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); break; } } } } } else if (mColorStops.size() == 1) { mColorBuffer.fill(mColorStops.constBegin().value().rgb()); } else // mColorStops is empty, fill color buffer with black { mColorBuffer.fill(qRgb(0, 0, 0)); } mColorBufferInvalidated = false; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAxisRect //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAxisRect \brief Holds multiple axes and arranges them in a rectangular shape. This class represents an axis rect, a rectangular area that is bounded on all sides with an arbitrary number of axes. Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the layout system allows to have multiple axis rects, e.g. arranged in a grid layout (QCustomPlot::plotLayout). By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref addAxes. To remove an axis, use \ref removeAxis. The axis rect layerable itself only draws a background pixmap or color, if specified (\ref setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be placed on other layers, independently of the axis rect. Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref insetLayout and can be used to have other layout elements (or even other layouts with multiple elements) hovering inside the axis rect. If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. \image html AxisRectSpacingOverview.png
Overview of the spacings and paddings that define the geometry of an axis. The dashed line on the far left indicates the viewport/widget border.
*/ /* start documentation of inline functions */ /*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const Returns the inset layout of this axis rect. It can be used to place other layout elements (or even layouts with multiple other elements) inside/on top of an axis rect. \see QCPLayoutInset */ /*! \fn int QCPAxisRect::left() const Returns the pixel position of the left border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::right() const Returns the pixel position of the right border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::top() const Returns the pixel position of the top border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::bottom() const Returns the pixel position of the bottom border of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::width() const Returns the pixel width of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn int QCPAxisRect::height() const Returns the pixel height of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QSize QCPAxisRect::size() const Returns the pixel size of this axis rect. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topLeft() const Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::topRight() const Returns the top right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomLeft() const Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::bottomRight() const Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /*! \fn QPoint QCPAxisRect::center() const Returns the center of this axis rect in pixels. Margins are not taken into account here, so the returned value is with respect to the inner \ref rect. */ /* end documentation of inline functions */ /*! Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four sides, the top and right axes are set invisible initially. */ QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : QCPLayoutElement(parentPlot), mBackgroundBrush(Qt::NoBrush), mBackgroundScaled(true), mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), mInsetLayout(new QCPLayoutInset), mRangeDrag(Qt::Horizontal|Qt::Vertical), mRangeZoom(Qt::Horizontal|Qt::Vertical), mRangeZoomFactorHorz(0.85), mRangeZoomFactorVert(0.85), mDragging(false) { mInsetLayout->initializeParentPlot(mParentPlot); mInsetLayout->setParentLayerable(this); mInsetLayout->setParent(this); setMinimumSize(50, 50); setMinimumMargins(QMargins(15, 15, 15, 15)); mAxes.insert(QCPAxis::atLeft, QList()); mAxes.insert(QCPAxis::atRight, QList()); mAxes.insert(QCPAxis::atTop, QList()); mAxes.insert(QCPAxis::atBottom, QList()); if (setupDefaultAxes) { QCPAxis *xAxis = addAxis(QCPAxis::atBottom); QCPAxis *yAxis = addAxis(QCPAxis::atLeft); QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); setRangeDragAxes(xAxis, yAxis); setRangeZoomAxes(xAxis, yAxis); xAxis2->setVisible(false); yAxis2->setVisible(false); xAxis->grid()->setVisible(true); yAxis->grid()->setVisible(true); xAxis2->grid()->setVisible(false); yAxis2->grid()->setVisible(false); xAxis2->grid()->setZeroLinePen(Qt::NoPen); yAxis2->grid()->setZeroLinePen(Qt::NoPen); xAxis2->grid()->setVisible(false); yAxis2->grid()->setVisible(false); } } QCPAxisRect::~QCPAxisRect() { delete mInsetLayout; mInsetLayout = 0; QList axesList = axes(); for (int i=0; i ax(mAxes.value(type)); if (index >= 0 && index < ax.size()) { return ax.at(index); } else { qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; return 0; } } /*! Returns all axes on the axis rect sides specified with \a types. \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of multiple sides. \see axis */ QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const { QList result; if (types.testFlag(QCPAxis::atLeft)) result << mAxes.value(QCPAxis::atLeft); if (types.testFlag(QCPAxis::atRight)) result << mAxes.value(QCPAxis::atRight); if (types.testFlag(QCPAxis::atTop)) result << mAxes.value(QCPAxis::atTop); if (types.testFlag(QCPAxis::atBottom)) result << mAxes.value(QCPAxis::atBottom); return result; } /*! \overload Returns all axes of this axis rect. */ QList QCPAxisRect::axes() const { QList result; QHashIterator > it(mAxes); while (it.hasNext()) { it.next(); result << it.value(); } return result; } /*! Adds a new axis to the axis rect side specified with \a type, and returns it. If an axis rect side already contains one or more axes, the lower and upper endings of the new axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are initialized to \ref QCPLineEnding::esHalfBar. \see addAxes, setupFullAxesBox */ QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type) { QCPAxis *newAxis = new QCPAxis(this, type); if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset { bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); } mAxes[type].append(newAxis); return newAxis; } /*! Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an or-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. Returns a list of the added axes. \see addAxis, setupFullAxesBox */ QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) { QList result; if (types.testFlag(QCPAxis::atLeft)) result << addAxis(QCPAxis::atLeft); if (types.testFlag(QCPAxis::atRight)) result << addAxis(QCPAxis::atRight); if (types.testFlag(QCPAxis::atTop)) result << addAxis(QCPAxis::atTop); if (types.testFlag(QCPAxis::atBottom)) result << addAxis(QCPAxis::atBottom); return result; } /*! Removes the specified \a axis from the axis rect and deletes it. Returns true on success, i.e. if \a axis was a valid axis in this axis rect. \see addAxis */ bool QCPAxisRect::removeAxis(QCPAxis *axis) { // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: QHashIterator > it(mAxes); while (it.hasNext()) { it.next(); if (it.value().contains(axis)) { mAxes[it.key()].removeOne(axis); if (qobject_cast(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) parentPlot()->axisRemoved(axis); delete axis; return true; } } qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); return false; } /*! Convenience function to create an axis on each side that doesn't have any axes yet and set their visibility to true. Further, the top/right axes are assigned the following properties of the bottom/left axes: \li range (\ref QCPAxis::setRange) \li range reversed (\ref QCPAxis::setRangeReversed) \li scale type (\ref QCPAxis::setScaleType) \li scale log base (\ref QCPAxis::setScaleLogBase) \li ticks (\ref QCPAxis::setTicks) \li auto (major) tick count (\ref QCPAxis::setAutoTickCount) \li sub tick count (\ref QCPAxis::setSubTickCount) \li auto sub ticks (\ref QCPAxis::setAutoSubTicks) \li tick step (\ref QCPAxis::setTickStep) \li auto tick step (\ref QCPAxis::setAutoTickStep) \li number format (\ref QCPAxis::setNumberFormat) \li number precision (\ref QCPAxis::setNumberPrecision) \li tick label type (\ref QCPAxis::setTickLabelType) \li date time format (\ref QCPAxis::setDateTimeFormat) \li date time spec (\ref QCPAxis::setDateTimeSpec) Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false. If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes. */ void QCPAxisRect::setupFullAxesBox(bool connectRanges) { QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; if (axisCount(QCPAxis::atBottom) == 0) xAxis = addAxis(QCPAxis::atBottom); else xAxis = axis(QCPAxis::atBottom); if (axisCount(QCPAxis::atLeft) == 0) yAxis = addAxis(QCPAxis::atLeft); else yAxis = axis(QCPAxis::atLeft); if (axisCount(QCPAxis::atTop) == 0) xAxis2 = addAxis(QCPAxis::atTop); else xAxis2 = axis(QCPAxis::atTop); if (axisCount(QCPAxis::atRight) == 0) yAxis2 = addAxis(QCPAxis::atRight); else yAxis2 = axis(QCPAxis::atRight); xAxis->setVisible(true); yAxis->setVisible(true); xAxis2->setVisible(true); yAxis2->setVisible(true); xAxis2->setTickLabels(false); yAxis2->setTickLabels(false); xAxis2->setRange(xAxis->range()); xAxis2->setRangeReversed(xAxis->rangeReversed()); xAxis2->setScaleType(xAxis->scaleType()); xAxis2->setScaleLogBase(xAxis->scaleLogBase()); xAxis2->setTicks(xAxis->ticks()); xAxis2->setAutoTickCount(xAxis->autoTickCount()); xAxis2->setSubTickCount(xAxis->subTickCount()); xAxis2->setAutoSubTicks(xAxis->autoSubTicks()); xAxis2->setTickStep(xAxis->tickStep()); xAxis2->setAutoTickStep(xAxis->autoTickStep()); xAxis2->setNumberFormat(xAxis->numberFormat()); xAxis2->setNumberPrecision(xAxis->numberPrecision()); xAxis2->setTickLabelType(xAxis->tickLabelType()); xAxis2->setDateTimeFormat(xAxis->dateTimeFormat()); xAxis2->setDateTimeSpec(xAxis->dateTimeSpec()); yAxis2->setRange(yAxis->range()); yAxis2->setRangeReversed(yAxis->rangeReversed()); yAxis2->setScaleType(yAxis->scaleType()); yAxis2->setScaleLogBase(yAxis->scaleLogBase()); yAxis2->setTicks(yAxis->ticks()); yAxis2->setAutoTickCount(yAxis->autoTickCount()); yAxis2->setSubTickCount(yAxis->subTickCount()); yAxis2->setAutoSubTicks(yAxis->autoSubTicks()); yAxis2->setTickStep(yAxis->tickStep()); yAxis2->setAutoTickStep(yAxis->autoTickStep()); yAxis2->setNumberFormat(yAxis->numberFormat()); yAxis2->setNumberPrecision(yAxis->numberPrecision()); yAxis2->setTickLabelType(yAxis->tickLabelType()); yAxis2->setDateTimeFormat(yAxis->dateTimeFormat()); yAxis2->setDateTimeSpec(yAxis->dateTimeSpec()); if (connectRanges) { connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); } } /*! Returns a list of all the plottables that are associated with this axis rect. A plottable is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. \see graphs, items */ QList QCPAxisRect::plottables() const { // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries QList result; for (int i=0; imPlottables.size(); ++i) { if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) result.append(mParentPlot->mPlottables.at(i)); } return result; } /*! Returns a list of all the graphs that are associated with this axis rect. A graph is considered associated with an axis rect if its key or value axis (or both) is in this axis rect. \see plottables, items */ QList QCPAxisRect::graphs() const { // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries QList result; for (int i=0; imGraphs.size(); ++i) { if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) result.append(mParentPlot->mGraphs.at(i)); } return result; } /*! Returns a list of all the items that are associated with this axis rect. An item is considered associated with an axis rect if any of its positions has key or value axis set to an axis that is in this axis rect, or if any of its positions has \ref QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref QCPAbstractItem::setClipAxisRect) is set to this axis rect. \see plottables, graphs */ QList QCPAxisRect::items() const { // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries // and miss those items that have this axis rect as clipAxisRect. QList result; for (int itemId=0; itemIdmItems.size(); ++itemId) { if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) { result.append(mParentPlot->mItems.at(itemId)); continue; } QList positions = mParentPlot->mItems.at(itemId)->positions(); for (int posId=0; posIdaxisRect() == this || positions.at(posId)->keyAxis()->axisRect() == this || positions.at(posId)->valueAxis()->axisRect() == this) { result.append(mParentPlot->mItems.at(itemId)); break; } } } return result; } /*! This method is called automatically upon replot and doesn't need to be called by users of QCPAxisRect. Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update), and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its QCPInsetLayout::update function. */ void QCPAxisRect::update(UpdatePhase phase) { QCPLayoutElement::update(phase); switch (phase) { case upPreparation: { QList allAxes = axes(); for (int i=0; isetupTickVectors(); break; } case upLayout: { mInsetLayout->setOuterRect(rect()); break; } default: break; } // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): mInsetLayout->update(phase); } /* inherits documentation from base class */ QList QCPAxisRect::elements(bool recursive) const { QList result; if (mInsetLayout) { result << mInsetLayout; if (recursive) result << mInsetLayout->elements(recursive); } return result; } /* inherits documentation from base class */ void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const { painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPAxisRect::draw(QCPPainter *painter) { drawBackground(painter); } /*! Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, consider using the overloaded version of this function. Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref setBackground(const QBrush &brush). \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) */ void QCPAxisRect::setBackground(const QPixmap &pm) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); } /*! \overload Sets \a brush as the background brush. The axis rect background will be filled with this brush. Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds are usually drawn below everything else. The brush will be drawn before (under) any background pixmap, which may be specified with \ref setBackground(const QPixmap &pm). To disable drawing of a background brush, set \a brush to Qt::NoBrush. \see setBackground(const QPixmap &pm) */ void QCPAxisRect::setBackground(const QBrush &brush) { mBackgroundBrush = brush; } /*! \overload Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it shall be scaled in one call. \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) { mBackgroundPixmap = pm; mScaledBackgroundPixmap = QPixmap(); mBackgroundScaled = scaled; mBackgroundScaledMode = mode; } /*! Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled is set to true, you may control whether and how the aspect ratio of the original pixmap is preserved with \ref setBackgroundScaledMode. Note that the scaled version of the original pixmap is buffered, so there is no performance penalty on replots. (Except when the axis rect dimensions are changed continuously.) \see setBackground, setBackgroundScaledMode */ void QCPAxisRect::setBackgroundScaled(bool scaled) { mBackgroundScaled = scaled; } /*! If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved. \see setBackground, setBackgroundScaled */ void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) { mBackgroundScaledMode = mode; } /*! Returns the range drag axis of the \a orientation provided. \see setRangeDragAxes */ QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data()); } /*! Returns the range zoom axis of the \a orientation provided. \see setRangeZoomAxes */ QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data()); } /*! Returns the range zoom factor of the \a orientation provided. \see setRangeZoomFactor */ double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) { return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); } /*! Sets which axis orientation may be range dragged by the user with mouse interaction. What orientation corresponds to which specific axis can be set with \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref QCustomPlot::setInteractions. To enable range dragging for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag to enable the range dragging interaction. \see setRangeZoom, setRangeDragAxes, setNoAntialiasingOnDrag */ void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) { mRangeDrag = orientations; } /*! Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical axis is the left axis (yAxis). To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref QCustomPlot::setInteractions. To enable range zooming for both directions, pass Qt::Horizontal | Qt::Vertical as \a orientations. In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions contains \ref QCP::iRangeZoom to enable the range zooming interaction. \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag */ void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) { mRangeZoom = orientations; } /*! Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging on the QCustomPlot widget. \see setRangeZoomAxes */ void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) { mRangeDragHorzAxis = horizontal; mRangeDragVertAxis = vertical; } /*! Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor). \see setRangeDragAxes */ void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) { mRangeZoomHorzAxis = horizontal; mRangeZoomVertAxis = vertical; } /*! Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal and which is vertical, can be set with \ref setRangeZoomAxes. When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user) will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the same scrolling direction will zoom out. */ void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) { mRangeZoomFactorHorz = horizontalFactor; mRangeZoomFactorVert = verticalFactor; } /*! \overload Sets both the horizontal and vertical zoom \a factor. */ void QCPAxisRect::setRangeZoomFactor(double factor) { mRangeZoomFactorHorz = factor; mRangeZoomFactorVert = factor; } /*! \internal Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a pixmap. If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an according filling inside the axis rect with the provided \a painter. Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside the axis rect with the provided \a painter. The scaled version is buffered in mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when the axis rect has changed in a way that requires a rescale of the background pixmap (this is dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was set. \see setBackground, setBackgroundScaled, setBackgroundScaledMode */ void QCPAxisRect::drawBackground(QCPPainter *painter) { // draw background fill: if (mBackgroundBrush != Qt::NoBrush) painter->fillRect(mRect, mBackgroundBrush); // draw background pixmap (on top of fill, if brush specified): if (!mBackgroundPixmap.isNull()) { if (mBackgroundScaled) { // check whether mScaledBackground needs to be updated: QSize scaledSize(mBackgroundPixmap.size()); scaledSize.scale(mRect.size(), mBackgroundScaledMode); if (mScaledBackgroundPixmap.size() != scaledSize) mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); painter->drawPixmap(mRect.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); } else { painter->drawPixmap(mRect.topLeft(), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); } } } /*! \internal This function makes sure multiple axes on the side specified with \a type don't collide, but are distributed according to their respective space requirement (QCPAxis::calculateMargin). It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the one with index zero. This function is called by \ref calculateAutoMargin. */ void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) { const QList axesList = mAxes.value(type); if (axesList.isEmpty()) return; bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false for (int i=1; ioffset() + axesList.at(i-1)->calculateMargin(); if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) { if (!isFirstVisible) offset += axesList.at(i)->tickLengthIn(); isFirstVisible = false; } axesList.at(i)->setOffset(offset); } } /* inherits documentation from base class */ int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) { if (!mAutoMargins.testFlag(side)) qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; updateAxesOffset(QCPAxis::marginSideToAxisType(side)); // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); if (axesList.size() > 0) return axesList.last()->offset() + axesList.last()->calculateMargin(); else return 0; } /*! \internal Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is pressed, the range dragging interaction is initialized (the actual range manipulation happens in the \ref mouseMoveEvent). The mDragging flag is set to true and some anchor points are set that are needed to determine the distance the mouse was dragged in the mouse move/release events later. \see mouseMoveEvent, mouseReleaseEvent */ void QCPAxisRect::mousePressEvent(QMouseEvent *event) { mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release) if (event->buttons() & Qt::LeftButton) { mDragging = true; // initialize antialiasing backup in case we start dragging: if (mParentPlot->noAntialiasingOnDrag()) { mAADragBackup = mParentPlot->antialiasedElements(); mNotAADragBackup = mParentPlot->notAntialiasedElements(); } // Mouse range dragging interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { if (mRangeDragHorzAxis) mDragStartHorzRange = mRangeDragHorzAxis.data()->range(); if (mRangeDragVertAxis) mDragStartVertRange = mRangeDragVertAxis.data()->range(); } } } /*! \internal Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a preceding \ref mousePressEvent, the range is moved accordingly. \see mousePressEvent, mouseReleaseEvent */ void QCPAxisRect::mouseMoveEvent(QMouseEvent *event) { // Mouse range dragging interaction: if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) { if (mRangeDrag.testFlag(Qt::Horizontal)) { if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data()) { if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear) { double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x()); rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff); } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic) { double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x()); rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff); } } } if (mRangeDrag.testFlag(Qt::Vertical)) { if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data()) { if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear) { double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y()); rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff); } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic) { double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y()); rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff); } } } if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot { if (mParentPlot->noAntialiasingOnDrag()) mParentPlot->setNotAntialiasedElements(QCP::aeAll); mParentPlot->replot(); } } } /* inherits documentation from base class */ void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event) { Q_UNUSED(event) mDragging = false; if (mParentPlot->noAntialiasingOnDrag()) { mParentPlot->setAntialiasedElements(mAADragBackup); mParentPlot->setNotAntialiasedElements(mNotAADragBackup); } } /*! \internal Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of the scaling operation is the current cursor position inside the axis rect. The scaling factor is dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor. Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as exponent of the range zoom factor. This takes care of the wheel direction automatically, by inverting the factor, when the wheel step is negative (f^-1 = 1/f). */ void QCPAxisRect::wheelEvent(QWheelEvent *event) { // Mouse range zooming interaction: if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) { if (mRangeZoom != 0) { double factor; double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually if (mRangeZoom.testFlag(Qt::Horizontal)) { factor = pow(mRangeZoomFactorHorz, wheelSteps); if (mRangeZoomHorzAxis.data()) mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x())); } if (mRangeZoom.testFlag(Qt::Vertical)) { factor = pow(mRangeZoomFactorVert, wheelSteps); if (mRangeZoomVertAxis.data()) mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y())); } mParentPlot->replot(); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPAbstractLegendItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPAbstractLegendItem \brief The abstract base class for all entries in a QCPLegend. It defines a very basic interface for entries in a QCPLegend. For representing plottables in the legend, the subclass \ref QCPPlottableLegendItem is more suitable. Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry that's not even associated with a plottable). You must implement the following pure virtual functions: \li \ref draw (from QCPLayerable) You inherit the following members you may use:
QCPLegend *\b mParentLegend A pointer to the parent QCPLegend.
QFont \b mFont The generic font of the item. You should use this font for all or at least the most prominent text of the item.
*/ /* start of documentation of signals */ /*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) This signal is emitted when the selection state of this legend item has changed, either by user interaction or by a direct call to \ref setSelected. */ /* end of documentation of signals */ /*! Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. */ QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : QCPLayoutElement(parent->parentPlot()), mParentLegend(parent), mFont(parent->font()), mTextColor(parent->textColor()), mSelectedFont(parent->selectedFont()), mSelectedTextColor(parent->selectedTextColor()), mSelectable(true), mSelected(false) { setLayer("legend"); setMargins(QMargins(8, 2, 8, 2)); } /*! Sets the default font of this specific legend item to \a font. \see setTextColor, QCPLegend::setFont */ void QCPAbstractLegendItem::setFont(const QFont &font) { mFont = font; } /*! Sets the default text color of this specific legend item to \a color. \see setFont, QCPLegend::setTextColor */ void QCPAbstractLegendItem::setTextColor(const QColor &color) { mTextColor = color; } /*! When this legend item is selected, \a font is used to draw generic text, instead of the normal font set with \ref setFont. \see setFont, QCPLegend::setSelectedFont */ void QCPAbstractLegendItem::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! When this legend item is selected, \a color is used to draw generic text, instead of the normal color set with \ref setTextColor. \see setTextColor, QCPLegend::setSelectedTextColor */ void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; } /*! Sets whether this specific legend item is selectable. \see setSelectedParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets whether this specific legend item is selected. It is possible to set the selection state of this item by calling this function directly, even if setSelectable is set to false. \see setSelectableParts, QCustomPlot::setInteractions */ void QCPAbstractLegendItem::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /* inherits documentation from base class */ double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (!mParentPlot) return -1; if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) return -1; if (mRect.contains(pos.toPoint())) return mParentPlot->selectionTolerance()*0.99; else return -1; } /* inherits documentation from base class */ void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); } /* inherits documentation from base class */ QRect QCPAbstractLegendItem::clipRect() const { return mOuterRect; } /* inherits documentation from base class */ void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) { if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPlottableLegendItem //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPlottableLegendItem \brief A legend item representing a plottable with an icon and the plottable name. This is the standard legend item for plottables. It displays an icon of the plottable next to the plottable name. The icon is drawn by the respective plottable itself (\ref QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the middle. Legend items of this type are always associated with one plottable (retrievable via the plottable() function and settable with the constructor). You may change the font of the plottable name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding. The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend creates/removes legend items of this type in the default implementation. However, these functions may be reimplemented such that a different kind of legend item (e.g a direct subclass of QCPAbstractLegendItem) is used for that plottable. Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout interface, QCPLegend has specialized functions for handling legend items conveniently, see the documentation of \ref QCPLegend. */ /*! Creates a new legend item associated with \a plottable. Once it's created, it can be added to the legend via \ref QCPLegend::addItem. A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. */ QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : QCPAbstractLegendItem(parent), mPlottable(plottable) { } /*! \internal Returns the pen that shall be used to draw the icon border, taking into account the selection state of this item. */ QPen QCPPlottableLegendItem::getIconBorderPen() const { return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); } /*! \internal Returns the text color that shall be used to draw text, taking into account the selection state of this item. */ QColor QCPPlottableLegendItem::getTextColor() const { return mSelected ? mSelectedTextColor : mTextColor; } /*! \internal Returns the font that shall be used to draw text, taking into account the selection state of this item. */ QFont QCPPlottableLegendItem::getFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Draws the item with \a painter. The size and position of the drawn legend item is defined by the parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint of this legend item. */ void QCPPlottableLegendItem::draw(QCPPainter *painter) { if (!mPlottable) return; painter->setFont(getFont()); painter->setPen(QPen(getTextColor())); QSizeF iconSize = mParentLegend->iconSize(); QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); QRectF iconRect(mRect.topLeft(), iconSize); int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); // draw icon: painter->save(); painter->setClipRect(iconRect, Qt::IntersectClip); mPlottable->drawLegendIcon(painter, iconRect); painter->restore(); // draw icon border: if (getIconBorderPen().style() != Qt::NoPen) { painter->setPen(getIconBorderPen()); painter->setBrush(Qt::NoBrush); painter->drawRect(iconRect); } } /*! \internal Calculates and returns the size of this item. This includes the icon, the text and the padding in between. */ QSize QCPPlottableLegendItem::minimumSizeHint() const { if (!mPlottable) return QSize(); QSize result(0, 0); QRect textRect; QFontMetrics fontMetrics(getFont()); QSize iconSize = mParentLegend->iconSize(); textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right()); result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom()); return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPLegend //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPLegend \brief Manages a legend inside a QCustomPlot. A legend is a small box somewhere in the plot which lists plottables with their name and icon. Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However, QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc. The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are placed in the grid layout of the legend. QCPLegend only adds an interface specialized for handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface. However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will only return the number of items with QCPAbstractLegendItems type). By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface. */ /* start of documentation of signals */ /*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); This signal is emitted when the selection state of this legend has changed. \see setSelectedParts, setSelectableParts */ /* end of documentation of signals */ /*! Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values. Note that by default, QCustomPlot already contains a legend ready to be used as QCustomPlot::legend */ QCPLegend::QCPLegend() { setRowSpacing(0); setColumnSpacing(10); setMargins(QMargins(2, 3, 2, 2)); setAntialiased(false); setIconSize(32, 18); setIconTextPadding(7); setSelectableParts(spLegendBox | spItems); setSelectedParts(spNone); setBorderPen(QPen(Qt::black)); setSelectedBorderPen(QPen(Qt::blue, 2)); setIconBorderPen(Qt::NoPen); setSelectedIconBorderPen(QPen(Qt::blue, 2)); setBrush(Qt::white); setSelectedBrush(Qt::white); setTextColor(Qt::black); setSelectedTextColor(Qt::blue); } QCPLegend::~QCPLegend() { clearItems(); if (mParentPlot) mParentPlot->legendRemoved(this); } /* no doc for getter, see setSelectedParts */ QCPLegend::SelectableParts QCPLegend::selectedParts() const { // check whether any legend elements selected, if yes, add spItems to return value bool hasSelectedItems = false; for (int i=0; iselected()) { hasSelectedItems = true; break; } } if (hasSelectedItems) return mSelectedParts | spItems; else return mSelectedParts & ~spItems; } /*! Sets the pen, the border of the entire legend is drawn with. */ void QCPLegend::setBorderPen(const QPen &pen) { mBorderPen = pen; } /*! Sets the brush of the legend background. */ void QCPLegend::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will use this font by default. However, a different font can be specified on a per-item-basis by accessing the specific legend item. This function will also set \a font on all already existing legend items. \see QCPAbstractLegendItem::setFont */ void QCPLegend::setFont(const QFont &font) { mFont = font; for (int i=0; isetFont(mFont); } } /*! Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) will use this color by default. However, a different colors can be specified on a per-item-basis by accessing the specific legend item. This function will also set \a color on all already existing legend items. \see QCPAbstractLegendItem::setTextColor */ void QCPLegend::setTextColor(const QColor &color) { mTextColor = color; for (int i=0; isetTextColor(color); } } /*! Sets the size of legend icons. Legend items that draw an icon (e.g. a visual representation of the graph) will use this size by default. */ void QCPLegend::setIconSize(const QSize &size) { mIconSize = size; } /*! \overload */ void QCPLegend::setIconSize(int width, int height) { mIconSize.setWidth(width); mIconSize.setHeight(height); } /*! Sets the horizontal space in pixels between the legend icon and the text next to it. Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the name of the graph) will use this space by default. */ void QCPLegend::setIconTextPadding(int padding) { mIconTextPadding = padding; } /*! Sets the pen used to draw a border around each legend icon. Legend items that draw an icon (e.g. a visual representation of the graph) will use this pen by default. If no border is wanted, set this to \a Qt::NoPen. */ void QCPLegend::setIconBorderPen(const QPen &pen) { mIconBorderPen = pen; } /*! Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) However, even when \a selectable is set to a value not allowing the selection of a specific part, it is still possible to set the selection of this part manually, by calling \ref setSelectedParts directly. \see SelectablePart, setSelectedParts */ void QCPLegend::setSelectableParts(const SelectableParts &selectable) { if (mSelectableParts != selectable) { mSelectableParts = selectable; emit selectableChanged(mSelectableParts); } } /*! Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected doesn't contain \ref spItems, those items become deselected. The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions contains iSelectLegend. You only need to call this function when you wish to change the selection state manually. This function can change the selection state of a part even when \ref setSelectableParts was set to a value that actually excludes the part. emits the \ref selectionChanged signal when \a selected is different from the previous selection state. Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set before, because there's no way to specify which exact items to newly select. Do this by calling \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, setSelectedFont */ void QCPLegend::setSelectedParts(const SelectableParts &selected) { SelectableParts newSelected = selected; mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed if (mSelectedParts != newSelected) { if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) { qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; newSelected &= ~spItems; } if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection { for (int i=0; isetSelected(false); } } mSelectedParts = newSelected; emit selectionChanged(mSelectedParts); } } /*! When the legend box is selected, this pen is used to draw the border instead of the normal pen set via \ref setBorderPen. \see setSelectedParts, setSelectableParts, setSelectedBrush */ void QCPLegend::setSelectedBorderPen(const QPen &pen) { mSelectedBorderPen = pen; } /*! Sets the pen legend items will use to draw their icon borders, when they are selected. \see setSelectedParts, setSelectableParts, setSelectedFont */ void QCPLegend::setSelectedIconBorderPen(const QPen &pen) { mSelectedIconBorderPen = pen; } /*! When the legend box is selected, this brush is used to draw the legend background instead of the normal brush set via \ref setBrush. \see setSelectedParts, setSelectableParts, setSelectedBorderPen */ void QCPLegend::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the default font that is used by legend items when they are selected. This function will also set \a font on all already existing legend items. \see setFont, QCPAbstractLegendItem::setSelectedFont */ void QCPLegend::setSelectedFont(const QFont &font) { mSelectedFont = font; for (int i=0; isetSelectedFont(font); } } /*! Sets the default text color that is used by legend items when they are selected. This function will also set \a color on all already existing legend items. \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor */ void QCPLegend::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; for (int i=0; isetSelectedTextColor(color); } } /*! Returns the item with index \a i. \see itemCount */ QCPAbstractLegendItem *QCPLegend::item(int index) const { return qobject_cast(elementAt(index)); } /*! Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns 0. \see hasItemWithPlottable */ QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const { for (int i=0; i(item(i))) { if (pli->plottable() == plottable) return pli; } } return 0; } /*! Returns the number of items currently in the legend. \see item */ int QCPLegend::itemCount() const { return elementCount(); } /*! Returns whether the legend contains \a itm. */ bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const { for (int i=0; iitem(i)) return true; } return false; } /*! Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). If such an item isn't in the legend, returns false. \see itemWithPlottable */ bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const { return itemWithPlottable(plottable); } /*! Adds \a item to the legend, if it's not present already. Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added. The legend takes ownership of the item. */ bool QCPLegend::addItem(QCPAbstractLegendItem *item) { if (!hasItem(item)) { return addElement(rowCount(), 0, item); } else return false; } /*! Removes the item with index \a index from the legend. Returns true, if successful. \see itemCount, clearItems */ bool QCPLegend::removeItem(int index) { if (QCPAbstractLegendItem *ali = item(index)) { bool success = remove(ali); simplify(); return success; } else return false; } /*! \overload Removes \a item from the legend. Returns true, if successful. \see clearItems */ bool QCPLegend::removeItem(QCPAbstractLegendItem *item) { bool success = remove(item); simplify(); return success; } /*! Removes all items from the legend. */ void QCPLegend::clearItems() { for (int i=itemCount()-1; i>=0; --i) removeItem(i); } /*! Returns the legend items that are currently selected. If no items are selected, the list is empty. \see QCPAbstractLegendItem::setSelected, setSelectable */ QList QCPLegend::selectedItems() const { QList result; for (int i=0; iselected()) result.append(ali); } } return result; } /*! \internal A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter before drawing main legend elements. This is the antialiasing state the painter passed to the \ref draw method is in by default. This function takes into account the local setting of the antialiasing flag as well as the overrides set with \ref QCustomPlot::setAntialiasedElements and \ref QCustomPlot::setNotAntialiasedElements. \see setAntialiased */ void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); } /*! \internal Returns the pen used to paint the border of the legend, taking into account the selection state of the legend box. */ QPen QCPLegend::getBorderPen() const { return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; } /*! \internal Returns the brush used to paint the background of the legend, taking into account the selection state of the legend box. */ QBrush QCPLegend::getBrush() const { return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; } /*! \internal Draws the legend box with the provided \a painter. The individual legend items are layerables themselves, thus are drawn independently. */ void QCPLegend::draw(QCPPainter *painter) { // draw background rect: painter->setBrush(getBrush()); painter->setPen(getBorderPen()); painter->drawRect(mOuterRect); } /* inherits documentation from base class */ double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { if (!mParentPlot) return -1; if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) return -1; if (mOuterRect.contains(pos.toPoint())) { if (details) details->setValue(spLegendBox); return mParentPlot->selectionTolerance()*0.99; } return -1; } /* inherits documentation from base class */ void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) mSelectedParts = selectedParts(); // in case item selection has changed if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ void QCPLegend::deselectEvent(bool *selectionStateChanged) { mSelectedParts = selectedParts(); // in case item selection has changed if (mSelectableParts.testFlag(spLegendBox)) { SelectableParts selBefore = mSelectedParts; setSelectedParts(selectedParts() & ~spLegendBox); if (selectionStateChanged) *selectionStateChanged = mSelectedParts != selBefore; } } /* inherits documentation from base class */ QCP::Interaction QCPLegend::selectionCategory() const { return QCP::iSelectLegend; } /* inherits documentation from base class */ QCP::Interaction QCPAbstractLegendItem::selectionCategory() const { return QCP::iSelectLegend; } /* inherits documentation from base class */ void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) { Q_UNUSED(parentPlot) } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPPlotTitle //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPPlotTitle \brief A layout element displaying a plot title text The text may be specified with \ref setText, theformatting can be controlled with \ref setFont and \ref setTextColor. A plot title can be added as follows: \code customPlot->plotLayout()->insertRow(0); // inserts an empty row above the default axis rect customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Your Plot Title")); \endcode Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref QCustomPlot::titleDoubleClick signal. */ /* start documentation of signals */ /*! \fn void QCPPlotTitle::selectionChanged(bool selected) This signal is emitted when the selection state has changed to \a selected, either by user interaction or by a direct call to \ref setSelected. \see setSelected, setSelectable */ /* end documentation of signals */ /*! Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText). To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text). */ QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) : QCPLayoutElement(parentPlot), mFont(QFont("sans serif", 13*1.5, QFont::Bold)), mTextColor(Qt::black), mSelectedFont(QFont("sans serif", 13*1.6, QFont::Bold)), mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { if (parentPlot) { setLayer(parentPlot->currentLayer()); mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold); mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold); } setMargins(QMargins(5, 5, 5, 0)); } /*! \overload Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text. */ QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) : QCPLayoutElement(parentPlot), mText(text), mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)), mTextColor(Qt::black), mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)), mSelectedTextColor(Qt::blue), mSelectable(false), mSelected(false) { setLayer("axes"); setMargins(QMargins(5, 5, 5, 0)); } /*! Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n". \see setFont, setTextColor */ void QCPPlotTitle::setText(const QString &text) { mText = text; } /*! Sets the \a font of the title text. \see setTextColor, setSelectedFont */ void QCPPlotTitle::setFont(const QFont &font) { mFont = font; } /*! Sets the \a color of the title text. \see setFont, setSelectedTextColor */ void QCPPlotTitle::setTextColor(const QColor &color) { mTextColor = color; } /*! Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected). \see setFont */ void QCPPlotTitle::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected). \see setTextColor */ void QCPPlotTitle::setSelectedTextColor(const QColor &color) { mSelectedTextColor = color; } /*! Sets whether the user may select this plot title to \a selectable. Note that even when \a selectable is set to false, the selection state may be changed programmatically via \ref setSelected. */ void QCPPlotTitle::setSelectable(bool selectable) { if (mSelectable != selectable) { mSelectable = selectable; emit selectableChanged(mSelectable); } } /*! Sets the selection state of this plot title to \a selected. If the selection has changed, \ref selectionChanged is emitted. Note that this function can change the selection state independently of the current \ref setSelectable state. */ void QCPPlotTitle::setSelected(bool selected) { if (mSelected != selected) { mSelected = selected; emit selectionChanged(mSelected); } } /* inherits documentation from base class */ void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const { applyAntialiasingHint(painter, mAntialiased, QCP::aeNone); } /* inherits documentation from base class */ void QCPPlotTitle::draw(QCPPainter *painter) { painter->setFont(mainFont()); painter->setPen(QPen(mainTextColor())); painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); } /* inherits documentation from base class */ QSize QCPPlotTitle::minimumSizeHint() const { QFontMetrics metrics(mFont); QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); result.rwidth() += mMargins.left() + mMargins.right(); result.rheight() += mMargins.top() + mMargins.bottom(); return result; } /* inherits documentation from base class */ QSize QCPPlotTitle::maximumSizeHint() const { QFontMetrics metrics(mFont); QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); result.rheight() += mMargins.top() + mMargins.bottom(); result.setWidth(QWIDGETSIZE_MAX); return result; } /* inherits documentation from base class */ void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) { Q_UNUSED(event) Q_UNUSED(details) if (mSelectable) { bool selBefore = mSelected; setSelected(additive ? !mSelected : true); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ void QCPPlotTitle::deselectEvent(bool *selectionStateChanged) { if (mSelectable) { bool selBefore = mSelected; setSelected(false); if (selectionStateChanged) *selectionStateChanged = mSelected != selBefore; } } /* inherits documentation from base class */ double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (mTextBoundingRect.contains(pos.toPoint())) return mParentPlot->selectionTolerance()*0.99; else return -1; } /*! \internal Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to true, else mFont is returned. */ QFont QCPPlotTitle::mainFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to true, else mTextColor is returned. */ QColor QCPPlotTitle::mainTextColor() const { return mSelected ? mSelectedTextColor : mTextColor; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorScale //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorScale \brief A color scale for use with color coding data such as QCPColorMap This layout element can be placed on the plot to correlate a color gradient with data values. It is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". \image html QCPColorScale.png The color scale can be either horizontal or vertical, as shown in the image above. The orientation and the side where the numbers appear is controlled with \ref setType. Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are connected, they share their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color scale, to make them all synchronize these properties. To have finer control over the number display and axis behaviour, you can directly access the \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if you want to change the number of automatically generated ticks, call \code colorScale->axis()->setAutoTickCount(3); \endcode Placing a color scale next to the main axis rect works like with any other layout element: \code QCPColorScale *colorScale = new QCPColorScale(customPlot); customPlot->plotLayout()->addElement(0, 1, colorScale); colorScale->setLabel("Some Label Text"); \endcode In this case we have placed it to the right of the default axis rect, so it wasn't necessary to call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color scale can be set with \ref setLabel. For optimum appearance (like in the image above), it may be desirable to line up the axis rect and the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: \code QCPMarginGroup *group = new QCPMarginGroup(customPlot); colorScale->setMarginGroup(QCP::msTop|QCP::msBottom, group); customPlot->axisRect()->setMarginGroup(QCP::msTop|QCP::msBottom, group); \endcode Color scales are initialized with a non-zero minimum top and bottom margin (\ref setMinimumMargins), because vertical color scales are most common and the minimum top/bottom margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you might want to also change the minimum margins accordingly, e.g. \ref setMinimumMargins(QMargins(6, 0, 6, 0)). */ /* start documentation of inline functions */ /*! \fn QCPAxis *QCPColorScale::axis() const Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on the QCPColorScale or on its QCPAxis. If the type of the color scale is changed with \ref setType, the axis returned by this method will change, too, to either the left, right, bottom or top axis, depending on which type was set. */ /* end documentation of signals */ /* start documentation of signals */ /*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange); This signal is emitted when the data range changes. \see setDataRange */ /*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the data scale type changes. \see setDataScaleType */ /*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient); This signal is emitted when the gradient changes. \see setGradient */ /* end documentation of signals */ /*! Constructs a new QCPColorScale. */ QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : QCPLayoutElement(parentPlot), mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight mDataScaleType(QCPAxis::stLinear), mBarWidth(20), mAxisRect(new QCPColorScaleAxisRectPrivate(this)) { setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) setType(QCPAxis::atRight); setDataRange(QCPRange(0, 6)); } QCPColorScale::~QCPColorScale() { delete mAxisRect; } /* undocumented getter */ QString QCPColorScale::label() const { if (!mColorAxis) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return QString(); } return mColorAxis.data()->label(); } /* undocumented getter */ bool QCPColorScale::rangeDrag() const { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return false; } return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /* undocumented getter */ bool QCPColorScale::rangeZoom() const { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return false; } return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); } /*! Sets at which side of the color scale the axis is placed, and thus also its orientation. Note that after setting \a type to a different value, the axis returned by \ref axis() will be a different one. The new axis will adopt the following properties from the previous axis: The range, scale type, log base and label. */ void QCPColorScale::setType(QCPAxis::AxisType type) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (mType != type) { mType = type; QCPRange rangeTransfer(0, 6); double logBaseTransfer = 10; QString labelTransfer; // revert some settings on old axis: if (mColorAxis) { rangeTransfer = mColorAxis.data()->range(); labelTransfer = mColorAxis.data()->label(); logBaseTransfer = mColorAxis.data()->scaleLogBase(); mColorAxis.data()->setLabel(""); disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } foreach (QCPAxis::AxisType atype, QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop) { mAxisRect.data()->axis(atype)->setTicks(atype == mType); mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); } // set new mColorAxis pointer: mColorAxis = mAxisRect.data()->axis(mType); // transfer settings to new axis: mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa) mColorAxis.data()->setLabel(labelTransfer); mColorAxis.data()->setScaleLogBase(logBaseTransfer); // scaleType is synchronized among axes in realtime via signals (connected in QCPColorScale ctor), so we only need to take care of log base here connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0, QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0); } } /*! Sets the range spanned by the color gradient and that is shown by the axis in the color scale. It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its range with \ref QCPAxis::setRange. \see setDataScaleType, setGradient, rescaleDataRange */ void QCPColorScale::setDataRange(const QCPRange &dataRange) { if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { mDataRange = dataRange; if (mColorAxis) mColorAxis.data()->setRange(mDataRange); emit dataRangeChanged(mDataRange); } } /*! Sets the scale type of the color scale, i.e. whether values are linearly associated with colors or logarithmically. It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is also equivalent to directly accessing the \ref axis and setting its scale type with \ref QCPAxis::setScaleType. \see setDataRange, setGradient */ void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) { if (mDataScaleType != scaleType) { mDataScaleType = scaleType; if (mColorAxis) mColorAxis.data()->setScaleType(mDataScaleType); if (mDataScaleType == QCPAxis::stLogarithmic) setDataRange(mDataRange.sanitizedForLogScale()); emit dataScaleTypeChanged(mDataScaleType); } } /*! Sets the color gradient that will be used to represent data values. It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. \see setDataRange, setDataScaleType */ void QCPColorScale::setGradient(const QCPColorGradient &gradient) { if (mGradient != gradient) { mGradient = gradient; if (mAxisRect) mAxisRect.data()->mGradientImageInvalidated = true; emit gradientChanged(mGradient); } } /*! Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on the internal \ref axis. */ void QCPColorScale::setLabel(const QString &str) { if (!mColorAxis) { qDebug() << Q_FUNC_INFO << "internal color axis undefined"; return; } mColorAxis.data()->setLabel(str); } /*! Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed will have. */ void QCPColorScale::setBarWidth(int width) { mBarWidth = width; } /*! Sets whether the user can drag the data range (\ref setDataRange). Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeDrag(bool enabled) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (enabled) mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); else mAxisRect.data()->setRangeDrag(0); } /*! Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref QCustomPlot::setInteractions) to allow range dragging. */ void QCPColorScale::setRangeZoom(bool enabled) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } if (enabled) mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); else mAxisRect.data()->setRangeZoom(0); } /*! Returns a list of all the color maps associated with this color scale. */ QList QCPColorScale::colorMaps() const { QList result; for (int i=0; iplottableCount(); ++i) { if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) if (cm->colorScale() == this) result.append(cm); } return result; } /*! Changes the data range such that all color maps associated with this color scale are fully mapped to the gradient in the data dimension. \see setDataRange */ void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) { QList maps = colorMaps(); QCPRange newRange; bool haveRange = false; int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace) if (mDataScaleType == QCPAxis::stLogarithmic) sign = (mDataRange.upper < 0 ? -1 : 1); for (int i=0; irealVisibility() && onlyVisibleMaps) continue; QCPRange mapRange; if (maps.at(i)->colorScale() == this) { bool currentFoundRange = true; mapRange = maps.at(i)->data()->dataBounds(); if (sign == 1) { if (mapRange.lower <= 0 && mapRange.upper > 0) mapRange.lower = mapRange.upper*1e-3; else if (mapRange.lower <= 0 && mapRange.upper <= 0) currentFoundRange = false; } else if (sign == -1) { if (mapRange.upper >= 0 && mapRange.lower < 0) mapRange.upper = mapRange.lower*1e-3; else if (mapRange.upper >= 0 && mapRange.lower >= 0) currentFoundRange = false; } if (currentFoundRange) { if (!haveRange) newRange = mapRange; else newRange.expand(mapRange); haveRange = true; } } } if (haveRange) { if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data { double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason if (mDataScaleType == QCPAxis::stLinear) { newRange.lower = center-mDataRange.size()/2.0; newRange.upper = center+mDataRange.size()/2.0; } else // mScaleType == stLogarithmic { newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); } } setDataRange(newRange); } } /* inherits documentation from base class */ void QCPColorScale::update(UpdatePhase phase) { QCPLayoutElement::update(phase); if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->update(phase); switch (phase) { case upMargins: { if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) { setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); } else { setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX); setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0); } break; } case upLayout: { mAxisRect.data()->setOuterRect(rect()); break; } default: break; } } /* inherits documentation from base class */ void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const { painter->setAntialiasing(false); } /* inherits documentation from base class */ void QCPColorScale::mousePressEvent(QMouseEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mousePressEvent(event); } /* inherits documentation from base class */ void QCPColorScale::mouseMoveEvent(QMouseEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mouseMoveEvent(event); } /* inherits documentation from base class */ void QCPColorScale::mouseReleaseEvent(QMouseEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->mouseReleaseEvent(event); } /* inherits documentation from base class */ void QCPColorScale::wheelEvent(QWheelEvent *event) { if (!mAxisRect) { qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; return; } mAxisRect.data()->wheelEvent(event); } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorScaleAxisRectPrivate //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorScaleAxisRectPrivate \internal \brief An axis rect subclass for use in a QCPColorScale This is a private class and not part of the public QCustomPlot interface. It provides the axis rect functionality for the QCPColorScale class. */ /*! Creates a new instance, as a child of \a parentColorScale. */ QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : QCPAxisRect(parentColorScale->parentPlot(), true), mParentColorScale(parentColorScale), mGradientImageInvalidated(true) { setParentLayerable(parentColorScale); setMinimumMargins(QMargins(0, 0, 0, 0)); foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) { axis(type)->setVisible(true); axis(type)->grid()->setVisible(false); axis(type)->setPadding(0); connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); } connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); // make layer transfers of color scale transfer to axis rect and axes // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); } /*! \internal Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation. */ void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) { if (mGradientImageInvalidated) updateGradientImage(); bool mirrorHorz = false; bool mirrorVert = false; if (mParentColorScale->mColorAxis) { mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); } painter->drawImage(rect(), mGradientImage.mirrored(mirrorHorz, mirrorVert)); QCPAxisRect::draw(painter); } /*! \internal Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to generate a gradient image. This gradient image will be used in the \ref draw method. */ void QCPColorScaleAxisRectPrivate::updateGradientImage() { if (rect().isEmpty()) return; int n = mParentColorScale->mGradient.levelCount(); int w, h; QVector data(n); for (int i=0; imType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) { w = n; h = rect().height(); mGradientImage = QImage(w, h, QImage::Format_RGB32); QVector pixels; for (int y=0; y(mGradientImage.scanLine(y))); mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); for (int y=1; y(mGradientImage.scanLine(y)); const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); for (int x=0; x() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) { if (QCPAxis *senderAxis = qobject_cast(sender())) if (senderAxis->axisType() == type) continue; if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { if (selectedParts.testFlag(QCPAxis::spAxis)) axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); else axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); } } } /*! \internal This slot is connected to the selectableChanged signals of the four axes in the constructor. It synchronizes the selectability of the axes. */ void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) { // synchronize axis base selectability: foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) { if (QCPAxis *senderAxis = qobject_cast(sender())) if (senderAxis->axisType() == type) continue; if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) { if (selectableParts.testFlag(QCPAxis::spAxis)) axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); else axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); } } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPData \brief Holds the data of one single data point for QCPGraph. The container for storing multiple data points is \ref QCPDataMap. The stored data is: \li \a key: coordinate on the key axis of this data point \li \a value: coordinate on the value axis of this data point \li \a keyErrorMinus: negative error in the key dimension (for error bars) \li \a keyErrorPlus: positive error in the key dimension (for error bars) \li \a valueErrorMinus: negative error in the value dimension (for error bars) \li \a valueErrorPlus: positive error in the value dimension (for error bars) \see QCPDataMap */ /*! Constructs a data point with key, value and all errors set to zero. */ QCPData::QCPData() : key(0), value(0), keyErrorPlus(0), keyErrorMinus(0), valueErrorPlus(0), valueErrorMinus(0) { } /*! Constructs a data point with the specified \a key and \a value. All errors are set to zero. */ QCPData::QCPData(double key, double value) : key(key), value(value), keyErrorPlus(0), keyErrorMinus(0), valueErrorPlus(0), valueErrorMinus(0) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPGraph //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPGraph \brief A plottable representing a graph in a plot. \image html QCPGraph.png Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting instance is accessed via QCustomPlot::graph. To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. Graphs are used to display single-valued data. Single-valued means that there should only be one data point per unique key coordinate. In other words, the graph can't have \a loops. If you do want to plot non-single-valued curves, rather use the QCPCurve plottable. \section appearance Changing the appearance The appearance of the graph is mainly determined by the line style, scatter style, brush and pen of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen). \subsection filling Filling under or between graphs QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill between this graph and another one, call \ref setChannelFillGraph with the other graph as parameter. \see QCustomPlot::addGraph, QCustomPlot::graph, QCPLegend::addGraph */ /* start of documentation of inline functions */ /*! \fn QCPDataMap *QCPGraph::data() const Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to directly manipulate the data, which may be more convenient and faster than using the regular \ref setData or \ref addData methods, in certain situations. */ /* end of documentation of inline functions */ /*! Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the graph. To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function. */ QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis) { mData = new QCPDataMap; setPen(QPen(Qt::blue, 0)); setErrorPen(QPen(Qt::black)); setBrush(Qt::NoBrush); setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); setSelectedBrush(Qt::NoBrush); setLineStyle(lsLine); setErrorType(etNone); setErrorBarSize(6); setErrorBarSkipSymbol(true); setChannelFillGraph(0); setAdaptiveSampling(true); } QCPGraph::~QCPGraph() { delete mData; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the graph takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. */ void QCPGraph::setData(QCPDataMap *data, bool copy) { if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setData(const QVector &key, const QVector &value) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); QCPData newData; for (int i=0; iinsertMulti(newData.key, newData); } } /*! Replaces the current data with the provided points in \a key and \a value pairs. Additionally the symmetrical value error of the data points are set to the values in \a valueError. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. For asymmetrical errors (plus different from minus), see the overloaded version of this function. */ void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueError) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueError.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. Additionally the negative value error of the data points are set to the values in \a valueErrorMinus, the positive value error to \a valueErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueErrorMinus.size()); n = qMin(n, valueErrorPlus.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! Replaces the current data with the provided points in \a key and \a value pairs. Additionally the symmetrical key error of the data points are set to the values in \a keyError. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. For asymmetrical errors (plus different from minus), see the overloaded version of this function. */ void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, keyError.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. Additionally the negative key error of the data points are set to the values in \a keyErrorMinus, the positive key error to \a keyErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, keyErrorMinus.size()); n = qMin(n, keyErrorPlus.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! Replaces the current data with the provided points in \a key and \a value pairs. Additionally the symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. For asymmetrical errors (plus different from minus), see the overloaded version of this function. */ void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueError.size()); n = qMin(n, keyError.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! \overload Replaces the current data with the provided points in \a key and \a value pairs. Additionally the negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus. For error bars to show appropriately, see \ref setErrorType. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); n = qMin(n, valueErrorMinus.size()); n = qMin(n, valueErrorPlus.size()); n = qMin(n, keyErrorMinus.size()); n = qMin(n, keyErrorPlus.size()); QCPData newData; for (int i=0; iinsertMulti(key[i], newData); } } /*! Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to \ref lsNone and \ref setScatterStyle to the desired scatter style. \see setScatterStyle */ void QCPGraph::setLineStyle(LineStyle ls) { mLineStyle = ls; } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only-plots with appropriate line style). \see QCPScatterStyle, setLineStyle */ void QCPGraph::setScatterStyle(const QCPScatterStyle &style) { mScatterStyle = style; } /*! Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data point. If you set \a errorType to something other than \ref etNone, make sure to actually pass error data via the specific setData functions along with the data points (e.g. \ref setDataValueError, \ref setDataKeyError, \ref setDataBothError). \see ErrorType */ void QCPGraph::setErrorType(ErrorType errorType) { mErrorType = errorType; } /*! Sets the pen with which the error bars will be drawn. \see setErrorBarSize, setErrorType */ void QCPGraph::setErrorPen(const QPen &pen) { mErrorPen = pen; } /*! Sets the width of the handles at both ends of an error bar in pixels. */ void QCPGraph::setErrorBarSize(double size) { mErrorBarSize = size; } /*! If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but leave some free space around the symbol. This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size of the area to leave blank. So when drawing Pixmaps as scatter points (\ref QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the size of the Pixmap, if the error bars should leave gaps to its boundaries. \ref setErrorType, setErrorBarSize, setScatterStyle */ void QCPGraph::setErrorBarSkipSymbol(bool enabled) { mErrorBarSkipSymbol = enabled; } /*! Sets the target graph for filling the area between this graph and \a targetGraph with the current brush (\ref setBrush). When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To disable any filling, set the brush to Qt::NoBrush. \see setBrush */ void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) { // prevent setting channel target to this graph itself: if (targetGraph == this) { qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; mChannelFillGraph = 0; return; } // prevent setting channel target to a graph not in the plot: if (targetGraph && targetGraph->mParentPlot != mParentPlot) { qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; mChannelFillGraph = 0; return; } mChannelFillGraph = targetGraph; } /*! Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive sampling technique can drastically improve the replot performance for graphs with a larger number of points (e.g. above 10,000), without notably changing the appearance of the graph. By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no disadvantage in almost all cases. \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are reproduced reliably, as well as the overall shape of the data set. The replot time reduces dramatically though. This allows QCustomPlot to display large amounts of data in realtime. \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" Care must be taken when using high-density scatter plots in combination with adaptive sampling. The adaptive sampling algorithm treats scatter plots more carefully than line plots which still gives a significant reduction of replot times, but not quite as much as for line plots. This is because scatter plots inherently need more data points to be preserved in order to still resemble the original, non-adaptive-sampling plot. As shown above, the results still aren't quite identical, as banding occurs for the outer data points. This is in fact intentional, such that the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, depends on the point density, i.e. the number of points in the plot. For some situations with scatter plots it might thus be desirable to manually turn adaptive sampling off. For example, when saving the plot to disk. This can be achieved by setting \a enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled back to true afterwards. */ void QCPGraph::setAdaptiveSampling(bool enabled) { mAdaptiveSampling = enabled; } /*! Adds the provided data points in \a dataMap to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(const QCPDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(const QCPData &data) { mData->insertMulti(data.key, data); } /*! \overload Adds the provided single data point as \a key and \a value pair to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(double key, double value) { QCPData newData; newData.key = key; newData.value = value; mData->insertMulti(newData.key, newData); } /*! \overload Adds the provided data points as \a key and \a value pairs to the current data. Alternatively, you can also access and modify the graph's data via the \ref data method, which returns a pointer to the internal \ref QCPDataMap. \see removeData */ void QCPGraph::addData(const QVector &keys, const QVector &values) { int n = qMin(keys.size(), values.size()); QCPData newData; for (int i=0; iinsertMulti(newData.key, newData); } } /*! Removes all data points with keys smaller than \a key. \see addData, clearData */ void QCPGraph::removeDataBefore(double key) { QCPDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < key) it = mData->erase(it); } /*! Removes all data points with keys greater than \a key. \see addData, clearData */ void QCPGraph::removeDataAfter(double key) { if (mData->isEmpty()) return; QCPDataMap::iterator it = mData->upperBound(key); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with keys between \a fromKey and \a toKey. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove a single data point with known key, use \ref removeData(double key). \see addData, clearData */ void QCPGraph::removeData(double fromKey, double toKey) { if (fromKey >= toKey || mData->isEmpty()) return; QCPDataMap::iterator it = mData->upperBound(fromKey); QCPDataMap::iterator itEnd = mData->upperBound(toKey); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at \a key. If the position is not known with absolute precision, consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around the suspected position, depeding on the precision with which the key is known. \see addData, clearData */ void QCPGraph::removeData(double key) { mData->remove(key); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPGraph::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && !mSelectable) || mData->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) return pointDistance(pos); else return -1; } /*! \overload Allows to define whether error bars are taken into consideration when determining the new axis range. \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes */ void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const { rescaleKeyAxis(onlyEnlarge, includeErrorBars); rescaleValueAxis(onlyEnlarge, includeErrorBars); } /*! \overload Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration when determining the new axis range. \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis */ void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const { // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change // that getKeyRange is passed the includeErrorBars value. if (mData->isEmpty()) return; QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } SignDomain signDomain = sdBoth; if (keyAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars); if (foundRange) { if (onlyEnlarge) { if (keyAxis->range().lower < newRange.lower) newRange.lower = keyAxis->range().lower; if (keyAxis->range().upper > newRange.upper) newRange.upper = keyAxis->range().upper; } keyAxis->setRange(newRange); } } /*! \overload Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration when determining the new axis range. \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis */ void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const { // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change // is that getValueRange is passed the includeErrorBars value. if (mData->isEmpty()) return; QCPAxis *valueAxis = mValueAxis.data(); if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } SignDomain signDomain = sdBoth; if (valueAxis->scaleType() == QCPAxis::stLogarithmic) signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); bool foundRange; QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars); if (foundRange) { if (onlyEnlarge) { if (valueAxis->range().lower < newRange.lower) newRange.lower = valueAxis->range().lower; if (valueAxis->range().upper > newRange.upper) newRange.upper = valueAxis->range().upper; } valueAxis->setRange(newRange); } } /* inherits documentation from base class */ void QCPGraph::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return; if (mLineStyle == lsNone && mScatterStyle.isNone()) return; // allocate line and (if necessary) point vectors: QVector *lineData = new QVector; QVector *scatterData = 0; if (!mScatterStyle.isNone()) scatterData = new QVector; // fill vectors with data appropriate to plot style: getPlotData(lineData, scatterData); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPDataMap::const_iterator it; for (it = mData->constBegin(); it != mData->constEnd(); ++it) { if (QCP::isInvalidData(it.value().key, it.value().value) || QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) || QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus)) qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); } #endif // draw fill of graph: drawFill(painter, lineData); // draw line: if (mLineStyle == lsImpulse) drawImpulsePlot(painter, lineData); else if (mLineStyle != lsNone) drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot // draw scatters: if (scatterData) drawScatterPlot(painter, scatterData); // free allocated line and point vectors: delete lineData; if (scatterData) delete scatterData; } /* inherits documentation from base class */ void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw fill: if (mBrush.style() != Qt::NoBrush) { applyFillAntialiasingHint(painter); painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); } // draw line vertically centered: if (mLineStyle != lsNone) { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens } // draw scatter symbol: if (!mScatterStyle.isNone()) { applyScattersAntialiasingHint(painter); // scale scatter pixmap if it's too large to fit in legend icon rect: if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { QCPScatterStyle scaledStyle(mScatterStyle); scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); scaledStyle.applyTo(painter, mPen); scaledStyle.drawShape(painter, QRectF(rect).center()); } else { mScatterStyle.applyTo(painter, mPen); mScatterStyle.drawShape(painter, QRectF(rect).center()); } } } /*! \internal This function branches out to the line style specific "get(...)PlotData" functions, according to the line style of the graph. \a lineData will be filled with raw points that will be drawn with the according draw functions, e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data points, since for step plots for example, additional points are needed for drawing lines that make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left untouched. \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped. \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData, getStepCenterPlotData, getImpulsePlotData */ void QCPGraph::getPlotData(QVector *lineData, QVector *scatterData) const { switch(mLineStyle) { case lsNone: getScatterPlotData(scatterData); break; case lsLine: getLinePlotData(lineData, scatterData); break; case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break; case lsStepRight: getStepRightPlotData(lineData, scatterData); break; case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break; case lsImpulse: getImpulsePlotData(lineData, scatterData); break; } } /*! \internal If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone, this function serves at providing the visible data points in \a scatterData, so the \ref drawScatterPlot function can draw the scatter points accordingly. If line style is not \ref lsNone, this function is not called and the data for the scatter points are (if needed) calculated inside the corresponding other "get(...)PlotData" functions. \see drawScatterPlot */ void QCPGraph::getScatterPlotData(QVector *scatterData) const { getPreparedData(0, scatterData); } /*! \internal Places the raw data points needed for a normal linearly connected graph in \a linePixelData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getLinePlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()); // transform lineData points to pixels: if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; icoordToPixel(lineData.at(i).value)); (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); } } else // key axis is horizontal { for (int i=0; icoordToPixel(lineData.at(i).key)); (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); } } } /*! \internal Places the raw data points needed for a step plot with left oriented steps in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()*2); // calculate steps from lineData and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; for (int i=0; icoordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(lastValue); (*linePixelData)[i*2+0].setY(key); lastValue = valueAxis->coordToPixel(lineData.at(i).value); (*linePixelData)[i*2+1].setX(lastValue); (*linePixelData)[i*2+1].setY(key); } } else // key axis is horizontal { double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; for (int i=0; icoordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(key); (*linePixelData)[i*2+0].setY(lastValue); lastValue = valueAxis->coordToPixel(lineData.at(i).value); (*linePixelData)[i*2+1].setX(key); (*linePixelData)[i*2+1].setY(lastValue); } } } /*! \internal Places the raw data points needed for a step plot with right oriented steps in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()*2); // calculate steps from lineData and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastKey = keyAxis->coordToPixel(lineData.first().key); double value; for (int i=0; icoordToPixel(lineData.at(i).value); (*linePixelData)[i*2+0].setX(value); (*linePixelData)[i*2+0].setY(lastKey); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+1].setX(value); (*linePixelData)[i*2+1].setY(lastKey); } } else // key axis is horizontal { double lastKey = keyAxis->coordToPixel(lineData.first().key); double value; for (int i=0; icoordToPixel(lineData.at(i).value); (*linePixelData)[i*2+0].setX(lastKey); (*linePixelData)[i*2+0].setY(value); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+1].setX(lastKey); (*linePixelData)[i*2+1].setY(value); } } } /*! \internal Places the raw data points needed for a step plot with centered steps in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawLinePlot */ void QCPGraph::getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill linePixelData->resize(lineData.size()*2); // calculate steps from lineData and transform to pixel coordinates: if (keyAxis->orientation() == Qt::Vertical) { double lastKey = keyAxis->coordToPixel(lineData.first().key); double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; (*linePixelData)[0].setX(lastValue); (*linePixelData)[0].setY(lastKey); for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; (*linePixelData)[i*2-1].setX(lastValue); (*linePixelData)[i*2-1].setY(key); lastValue = valueAxis->coordToPixel(lineData.at(i).value); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(lastValue); (*linePixelData)[i*2+0].setY(key); } (*linePixelData)[lineData.size()*2-1].setX(lastValue); (*linePixelData)[lineData.size()*2-1].setY(lastKey); } else // key axis is horizontal { double lastKey = keyAxis->coordToPixel(lineData.first().key); double lastValue = valueAxis->coordToPixel(lineData.first().value); double key; (*linePixelData)[0].setX(lastKey); (*linePixelData)[0].setY(lastValue); for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; (*linePixelData)[i*2-1].setX(key); (*linePixelData)[i*2-1].setY(lastValue); lastValue = valueAxis->coordToPixel(lineData.at(i).value); lastKey = keyAxis->coordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(key); (*linePixelData)[i*2+0].setY(lastValue); } (*linePixelData)[lineData.size()*2-1].setX(lastKey); (*linePixelData)[lineData.size()*2-1].setY(lastValue); } } /*! \internal Places the raw data points needed for an impulse plot in \a lineData. As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) points that are visible for drawing scatter points, if necessary. If drawing scatter points is disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a scatterData, and the function will skip filling the vector. \see drawImpulsePlot */ void QCPGraph::getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } QVector lineData; getPreparedData(&lineData, scatterData); linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill // transform lineData points to pixels: if (keyAxis->orientation() == Qt::Vertical) { double zeroPointX = valueAxis->coordToPixel(0); double key; for (int i=0; icoordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(zeroPointX); (*linePixelData)[i*2+0].setY(key); (*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value)); (*linePixelData)[i*2+1].setY(key); } } else // key axis is horizontal { double zeroPointY = valueAxis->coordToPixel(0); double key; for (int i=0; icoordToPixel(lineData.at(i).key); (*linePixelData)[i*2+0].setX(key); (*linePixelData)[i*2+0].setY(zeroPointY); (*linePixelData)[i*2+1].setX(key); (*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value)); } } } /*! \internal Draws the fill of the graph with the specified brush. If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by \ref removeFillBasePoints after the fill drawing is done). If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the more complex polygon is calculated with the \ref getChannelFillPolygon function. \see drawLinePlot */ void QCPGraph::drawFill(QCPPainter *painter, QVector *lineData) const { if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return; applyFillAntialiasingHint(painter); if (!mChannelFillGraph) { // draw base fill under graph, fill goes all the way to the zero-value-line: addFillBasePoints(lineData); painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(QPolygonF(*lineData)); removeFillBasePoints(lineData); } else { // draw channel fill between this graph and mChannelFillGraph: painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(getChannelFillPolygon(lineData)); } } /*! \internal Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent of the line style and are always drawn if the scatter style's shape is not \ref QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData" functions, together with the (line style dependent) line data. \see drawLinePlot, drawImpulsePlot */ void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // draw error bars: if (mErrorType != etNone) { applyErrorBarsAntialiasingHint(painter); painter->setPen(mErrorPen); if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; isize(); ++i) drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i)); } else { for (int i=0; isize(); ++i) drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i)); } } // draw scatter point symbols: applyScattersAntialiasingHint(painter); mScatterStyle.applyTo(painter, mPen); if (keyAxis->orientation() == Qt::Vertical) { for (int i=0; isize(); ++i) mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key)); } else { for (int i=0; isize(); ++i) mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value)); } } /*! \internal Draws line graphs from the provided data. It connects all points in \a lineData, which was created by one of the "get(...)PlotData" functions for line styles that require simple line connections between the point vector they create. These are for example \ref getLinePlotData, \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData. \see drawScatterPlot, drawImpulsePlot */ void QCPGraph::drawLinePlot(QCPPainter *painter, QVector *lineData) const { // draw line of graph: if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(Qt::NoBrush); /* Draws polyline in batches, currently not used: int p = 0; while (p < lineData->size()) { int batch = qMin(25, lineData->size()-p); if (p != 0) { ++batch; --p; // to draw the connection lines between two batches } painter->drawPolyline(lineData->constData()+p, batch); p += batch; } */ // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && painter->pen().style() == Qt::SolidLine && !painter->modes().testFlag(QCPPainter::pmVectorized)&& !painter->modes().testFlag(QCPPainter::pmNoCaching)) { for (int i=1; isize(); ++i) painter->drawLine(lineData->at(i-1), lineData->at(i)); } else { painter->drawPolyline(QPolygonF(*lineData)); } } } /*! \internal Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was created by \ref getImpulsePlotData. \see drawScatterPlot, drawLinePlot */ void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector *lineData) const { // draw impulses: if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); QPen pen = mainPen(); pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line painter->setPen(pen); painter->setBrush(Qt::NoBrush); painter->drawLines(*lineData); } } /*! \internal Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point densities. 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a scatterData should be 0 to prevent unnecessary calculations. This method is used by the various "get(...)PlotData" methods to get the basic working set of data. */ void QCPGraph::getPreparedData(QVector *lineData, QVector *scatterData) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // get visible data range: QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point getVisibleDataBounds(lower, upper); if (lower == mData->constEnd() || upper == mData->constEnd()) return; // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling: int maxCount = std::numeric_limits::max(); if (mAdaptiveSampling) { int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key())); maxCount = 2*keyPixelSpan+2; } int dataCount = countDataInBounds(lower, upper, maxCount); if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average { if (lineData) { QCPDataMap::const_iterator it = lower; QCPDataMap::const_iterator upperEnd = upper+1; double minValue = it.value().value; double maxValue = it.value().value; QCPDataMap::const_iterator currentIntervalFirstPoint = it; int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); double lastIntervalEndKey = currentIntervalStartKey; double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) int intervalDataCount = 1; ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect while (it != upperEnd) { if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary { if (it.value().value < minValue) minValue = it.value().value; else if (it.value().value > maxValue) maxValue = it.value().value; ++intervalDataCount; } else // new pixel interval started { if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster { if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); if (it.key() > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value)); } else lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); lastIntervalEndKey = (it-1).value().key; minValue = it.value().value; maxValue = it.value().value; currentIntervalFirstPoint = it; currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); if (keyEpsilonVariable) keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); intervalDataCount = 1; } ++it; } // handle last interval: if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster { if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); } else lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); } if (scatterData) { double valueMaxRange = valueAxis->range().upper; double valueMinRange = valueAxis->range().lower; QCPDataMap::const_iterator it = lower; QCPDataMap::const_iterator upperEnd = upper+1; double minValue = it.value().value; double maxValue = it.value().value; QCPDataMap::const_iterator minValueIt = it; QCPDataMap::const_iterator maxValueIt = it; QCPDataMap::const_iterator currentIntervalStart = it; int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) int intervalDataCount = 1; ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect while (it != upperEnd) { if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary { if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) { minValue = it.value().value; minValueIt = it; } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) { maxValue = it.value().value; maxValueIt = it; } ++intervalDataCount; } else // new pixel started { if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them { // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average QCPDataMap::const_iterator intervalIt = currentIntervalStart; int c = 0; while (intervalIt != it) { if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) scatterData->append(intervalIt.value()); ++c; ++intervalIt; } } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) scatterData->append(currentIntervalStart.value()); minValue = it.value().value; maxValue = it.value().value; currentIntervalStart = it; currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); if (keyEpsilonVariable) keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); intervalDataCount = 1; } ++it; } // handle last interval: if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them { // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average QCPDataMap::const_iterator intervalIt = currentIntervalStart; int c = 0; while (intervalIt != it) { if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) scatterData->append(intervalIt.value()); ++c; ++intervalIt; } } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) scatterData->append(currentIntervalStart.value()); } } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters { QVector *dataVector = 0; if (lineData) dataVector = lineData; else if (scatterData) dataVector = scatterData; if (dataVector) { QCPDataMap::const_iterator it = lower; QCPDataMap::const_iterator upperEnd = upper+1; dataVector->reserve(dataCount+2); // +2 for possible fill end points while (it != upperEnd) { dataVector->append(it.value()); ++it; } } if (lineData && scatterData) *scatterData = *dataVector; } } /*! \internal called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data point. \a x and \a y pixel positions of the data point are passed since they are already known in pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a data is therefore only used for the errors, not key and value. */ void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } double a, b; // positions of error bar bounds in pixels double barWidthHalf = mErrorBarSize*0.5; double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true if (keyAxis->orientation() == Qt::Vertical) { // draw key error vertically and value error horizontally if (mErrorType == etKey || mErrorType == etBoth) { a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); if (keyAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); if (y-b > skipSymbolMargin) painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); } else painter->drawLine(QLineF(x, a, x, b)); // draw handles: painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); } if (mErrorType == etValue || mErrorType == etBoth) { a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); if (valueAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); if (b-x > skipSymbolMargin) painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); } else painter->drawLine(QLineF(a, y, b, y)); // draw handles: painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); } } else // mKeyAxis->orientation() is Qt::Horizontal { // draw value error vertically and key error horizontally if (mErrorType == etKey || mErrorType == etBoth) { a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); if (keyAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); if (b-x > skipSymbolMargin) painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); } else painter->drawLine(QLineF(a, y, b, y)); // draw handles: painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); } if (mErrorType == etValue || mErrorType == etBoth) { a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); if (valueAxis->rangeReversed()) qSwap(a,b); // draw spine: if (mErrorBarSkipSymbol) { if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); if (y-b > skipSymbolMargin) painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); } else painter->drawLine(QLineF(x, a, x, b)); // draw handles: painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); } } } /*! \internal called by \ref getPreparedData to determine which data (key) range is visible at the current key axis range setting, so only that needs to be processed. \a lower returns an iterator to the lowest data point that needs to be taken into account when plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a lower may still be just outside the visible range. \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie just outside of the visible range. if the graph contains no data, both \a lower and \a upper point to constEnd. */ void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } if (mData->isEmpty()) { lower = mData->constEnd(); upper = mData->constEnd(); return; } // get visible data range as QMap iterators QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn } /*! \internal Counts the number of data points between \a lower and \a upper (including them), up to a maximum of \a maxCount. This function is used by \ref getPreparedData to determine whether adaptive sampling shall be used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points only needs to be done until \a maxCount is reached, which should be set to the number of data points at which adaptive sampling sets in. */ int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const { if (upper == mData->constEnd() && lower == mData->constEnd()) return 0; QCPDataMap::const_iterator it = lower; int count = 1; while (it != upper && count < maxCount) { ++it; ++count; } return count; } /*! \internal The line data vector generated by e.g. getLinePlotData contains only the line that connects the data points. If the graph needs to be filled, two additional points need to be added at the value-zero-line in the lower and upper key positions of the graph. This function calculates these points and adds them to the end of \a lineData. Since the fill is typically drawn before the line stroke, these added points need to be removed again after the fill is done, with the removeFillBasePoints function. The expanding of \a lineData by two points will not cause unnecessary memory reallocations, because the data vector generation functions (getLinePlotData etc.) reserve two extra points when they allocate memory for \a lineData. \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint */ void QCPGraph::addFillBasePoints(QVector *lineData) const { if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } // append points that close the polygon fill at the key axis: if (mKeyAxis.data()->orientation() == Qt::Vertical) { *lineData << upperFillBasePoint(lineData->last().y()); *lineData << lowerFillBasePoint(lineData->first().y()); } else { *lineData << upperFillBasePoint(lineData->last().x()); *lineData << lowerFillBasePoint(lineData->first().x()); } } /*! \internal removes the two points from \a lineData that were added by \ref addFillBasePoints. \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint */ void QCPGraph::removeFillBasePoints(QVector *lineData) const { lineData->remove(lineData->size()-2, 2); } /*! \internal called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill polygon on the axis which lies in the direction towards the zero value. \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned point, respectively. \see upperFillBasePoint, addFillBasePoints */ QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } QPointF point; if (valueAxis->scaleType() == QCPAxis::stLinear) { if (keyAxis->axisType() == QCPAxis::atLeft) { point.setX(valueAxis->coordToPixel(0)); point.setY(lowerKey); } else if (keyAxis->axisType() == QCPAxis::atRight) { point.setX(valueAxis->coordToPixel(0)); point.setY(lowerKey); } else if (keyAxis->axisType() == QCPAxis::atTop) { point.setX(lowerKey); point.setY(valueAxis->coordToPixel(0)); } else if (keyAxis->axisType() == QCPAxis::atBottom) { point.setX(lowerKey); point.setY(valueAxis->coordToPixel(0)); } } else // valueAxis->mScaleType == QCPAxis::stLogarithmic { // In logarithmic scaling we can't just draw to value zero so we just fill all the way // to the axis which is in the direction towards zero if (keyAxis->orientation() == Qt::Vertical) { if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setX(keyAxis->axisRect()->right()); else point.setX(keyAxis->axisRect()->left()); point.setY(lowerKey); } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { point.setX(lowerKey); if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setY(keyAxis->axisRect()->top()); else point.setY(keyAxis->axisRect()->bottom()); } } return point; } /*! \internal called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative infinity. So this case is handled separately by just closing the fill polygon on the axis which lies in the direction towards the zero value. \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned point, respectively. \see lowerFillBasePoint, addFillBasePoints */ QPointF QCPGraph::upperFillBasePoint(double upperKey) const { QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } QPointF point; if (valueAxis->scaleType() == QCPAxis::stLinear) { if (keyAxis->axisType() == QCPAxis::atLeft) { point.setX(valueAxis->coordToPixel(0)); point.setY(upperKey); } else if (keyAxis->axisType() == QCPAxis::atRight) { point.setX(valueAxis->coordToPixel(0)); point.setY(upperKey); } else if (keyAxis->axisType() == QCPAxis::atTop) { point.setX(upperKey); point.setY(valueAxis->coordToPixel(0)); } else if (keyAxis->axisType() == QCPAxis::atBottom) { point.setX(upperKey); point.setY(valueAxis->coordToPixel(0)); } } else // valueAxis->mScaleType == QCPAxis::stLogarithmic { // In logarithmic scaling we can't just draw to value 0 so we just fill all the way // to the axis which is in the direction towards 0 if (keyAxis->orientation() == Qt::Vertical) { if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setX(keyAxis->axisRect()->right()); else point.setX(keyAxis->axisRect()->left()); point.setY(upperKey); } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) { point.setX(upperKey); if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis point.setY(keyAxis->axisRect()->top()); else point.setY(keyAxis->axisRect()->bottom()); } } return point; } /*! \internal Generates the polygon needed for drawing channel fills between this graph (data passed via \a lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref getPlotData function). May return an empty polygon if the key ranges have no overlap or fill target graph and this graph don't have same orientation (i.e. both key axes horizontal or both key axes vertical). For increased performance (due to implicit sharing), keep the returned QPolygonF const. */ const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *lineData) const { if (!mChannelFillGraph) return QPolygonF(); QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation()) return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis) if (lineData->isEmpty()) return QPolygonF(); QVector otherData; mChannelFillGraph.data()->getPlotData(&otherData, 0); if (otherData.isEmpty()) return QPolygonF(); QVector thisData; thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function for (int i=0; isize(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve() thisData << lineData->at(i); // pointers to be able to swap them, depending which data range needs cropping: QVector *staticData = &thisData; QVector *croppedData = &otherData; // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): if (keyAxis->orientation() == Qt::Horizontal) { // x is key // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: if (staticData->first().x() > staticData->last().x()) { int size = staticData->size(); for (int i=0; ifirst().x() > croppedData->last().x()) { int size = croppedData->size(); for (int i=0; ifirst().x() < croppedData->first().x()) // other one must be cropped qSwap(staticData, croppedData); int lowBound = findIndexBelowX(croppedData, staticData->first().x()); if (lowBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(0, lowBound); // set lowest point of cropped data to fit exactly key position of first static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation double slope; if (croppedData->at(1).x()-croppedData->at(0).x() != 0) slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); else slope = 0; (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); (*croppedData)[0].setX(staticData->first().x()); // crop upper bound: if (staticData->last().x() > croppedData->last().x()) // other one must be cropped qSwap(staticData, croppedData); int highBound = findIndexAboveX(croppedData, staticData->last().x()); if (highBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); // set highest point of cropped data to fit exactly key position of last static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation int li = croppedData->size()-1; // last index if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0) slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); else slope = 0; (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); (*croppedData)[li].setX(staticData->last().x()); } else // mKeyAxis->orientation() == Qt::Vertical { // y is key // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x, // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate. // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: if (staticData->first().y() < staticData->last().y()) { int size = staticData->size(); for (int i=0; ifirst().y() < croppedData->last().y()) { int size = croppedData->size(); for (int i=0; ifirst().y() > croppedData->first().y()) // other one must be cropped qSwap(staticData, croppedData); int lowBound = findIndexAboveY(croppedData, staticData->first().y()); if (lowBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(0, lowBound); // set lowest point of cropped data to fit exactly key position of first static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation double slope; if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); else slope = 0; (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); (*croppedData)[0].setY(staticData->first().y()); // crop upper bound: if (staticData->last().y() < croppedData->last().y()) // other one must be cropped qSwap(staticData, croppedData); int highBound = findIndexBelowY(croppedData, staticData->last().y()); if (highBound == -1) return QPolygonF(); // key ranges have no overlap croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); // set highest point of cropped data to fit exactly key position of last static data // point via linear interpolation: if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation int li = croppedData->size()-1; // last index if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); else slope = 0; (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); (*croppedData)[li].setY(staticData->last().y()); } // return joined: for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted thisData << otherData.at(i); return QPolygonF(thisData); } /*! \internal Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in \a data points are ordered ascending, as is the case when plotting with horizontal key axis. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveX(const QVector *data, double x) const { for (int i=data->size()-1; i>=0; --i) { if (data->at(i).x() < x) { if (isize()-1) return i+1; else return data->size()-1; } } return -1; } /*! \internal Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in \a data points are ordered ascending, as is the case when plotting with horizontal key axis. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowX(const QVector *data, double x) const { for (int i=0; isize(); ++i) { if (data->at(i).x() > x) { if (i>0) return i-1; else return 0; } } return -1; } /*! \internal Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in \a data points are ordered descending, as is the case when plotting with vertical key axis. Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexAboveY(const QVector *data, double y) const { for (int i=0; isize(); ++i) { if (data->at(i).y() < y) { if (i>0) return i-1; else return 0; } } return -1; } /*! \internal Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in \ref selectTest. If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns 500. */ double QCPGraph::pointDistance(const QPointF &pixelPoint) const { if (mData->isEmpty()) { qDebug() << Q_FUNC_INFO << "requested point distance on graph" << mName << "without data"; return 500; } if (mData->size() == 1) { QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); return QVector2D(dataPoint-pixelPoint).length(); } if (mLineStyle == lsNone && mScatterStyle.isNone()) return 500; // calculate minimum distances to graph representation: if (mLineStyle == lsNone) { // no line displayed, only calculate distance to scatter points: QVector *scatterData = new QVector; getScatterPlotData(scatterData); double minDistSqr = std::numeric_limits::max(); QPointF ptA; QPointF ptB = coordsToPixels(scatterData->at(0).key, scatterData->at(0).value); // getScatterPlotData returns in plot coordinates, so transform to pixels for (int i=1; isize(); ++i) { ptA = ptB; ptB = coordsToPixels(scatterData->at(i).key, scatterData->at(i).value); double currentDistSqr = distSqrToLine(ptA, ptB, pixelPoint); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } delete scatterData; return sqrt(minDistSqr); } else { // line displayed calculate distance to line segments: QVector *lineData = new QVector; getPlotData(lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here double minDistSqr = std::numeric_limits::max(); if (mLineStyle == lsImpulse) { // impulse plot differs from other line styles in that the lineData points are only pairwise connected: for (int i=0; isize()-1; i+=2) // iterate pairs { double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } else { // all other line plots (line and step) connect points directly: for (int i=0; isize()-1; ++i) { double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } } delete lineData; return sqrt(minDistSqr); } } /*! \internal Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in \a data points are ordered descending, as is the case when plotting with vertical key axis (since keys are ordered ascending). Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. */ int QCPGraph::findIndexBelowY(const QVector *data, double y) const { for (int i=data->size()-1; i>=0; --i) { if (data->at(i).y() > y) { if (isize()-1) return i+1; else return data->size()-1; } } return -1; } /* inherits documentation from base class */ QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { // just call the specialized version which takes an additional argument whether error bars // should also be taken into consideration for range calculation. We set this to true here. return getKeyRange(foundRange, inSignDomain, true); } /* inherits documentation from base class */ QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const { // just call the specialized version which takes an additional argument whether error bars // should also be taken into consideration for range calculation. We set this to true here. return getValueRange(foundRange, inSignDomain, true); } /*! \overload Allows to specify whether the error bars should be included in the range calculation. \see getKeyRange(bool &foundRange, SignDomain inSignDomain) */ QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current, currentErrorMinus, currentErrorPlus; if (inSignDomain == sdBoth) // range may be anywhere { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); if (current-currentErrorMinus < range.lower || !haveLower) { range.lower = current-currentErrorMinus; haveLower = true; } if (current+currentErrorPlus > range.upper || !haveUpper) { range.upper = current+currentErrorPlus; haveUpper = true; } ++it; } } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. { if ((current < range.lower || !haveLower) && current < 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current < 0) { range.upper = current; haveUpper = true; } } ++it; } } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. { if ((current < range.lower || !haveLower) && current > 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current > 0) { range.upper = current; haveUpper = true; } } ++it; } } foundRange = haveLower && haveUpper; return range; } /*! \overload Allows to specify whether the error bars should be included in the range calculation. \see getValueRange(bool &foundRange, SignDomain inSignDomain) */ QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current, currentErrorMinus, currentErrorPlus; if (inSignDomain == sdBoth) // range may be anywhere { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); if (current-currentErrorMinus < range.lower || !haveLower) { range.lower = current-currentErrorMinus; haveLower = true; } if (current+currentErrorPlus > range.upper || !haveUpper) { range.upper = current+currentErrorPlus; haveUpper = true; } ++it; } } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. { if ((current < range.lower || !haveLower) && current < 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current < 0) { range.upper = current; haveUpper = true; } } ++it; } } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain { QCPDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) { range.lower = current-currentErrorMinus; haveLower = true; } if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) { range.upper = current+currentErrorPlus; haveUpper = true; } if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. { if ((current < range.lower || !haveLower) && current > 0) { range.lower = current; haveLower = true; } if ((current > range.upper || !haveUpper) && current > 0) { range.upper = current; haveUpper = true; } } ++it; } } foundRange = haveLower && haveUpper; return range; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPCurveData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPCurveData \brief Holds the data of one single data point for QCPCurve. The container for storing multiple data points is \ref QCPCurveDataMap. The stored data is: \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector (x(t), y(t))) \li \a key: coordinate on the key axis of this curve point \li \a value: coordinate on the value axis of this curve point \see QCPCurveDataMap */ /*! Constructs a curve data point with t, key and value set to zero. */ QCPCurveData::QCPCurveData() : t(0), key(0), value(0) { } /*! Constructs a curve data point with the specified \a t, \a key and \a value. */ QCPCurveData::QCPCurveData(double t, double key, double value) : t(t), key(key), value(value) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPCurve //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPCurve \brief A plottable representing a parametric curve in a plot. \image html QCPCurve.png Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, so their visual representation can have \a loops. This is realized by introducing a third coordinate \a t, which defines the order of the points described by the other two coordinates \a x and \a y. To plot data, assign it with the \ref setData or \ref addData functions. \section appearance Changing the appearance The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). \section usage Usage Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \code QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode add it to the customPlot with QCustomPlot::addPlottable: \code customPlot->addPlottable(newCurve);\endcode and then modify the properties of the newly created plottable, e.g.: \code newCurve->setName("Fermat's Spiral"); newCurve->setData(tData, xData, yData);\endcode */ /*! Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the graph. */ QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis) { mData = new QCPCurveDataMap; mPen.setColor(Qt::blue); mPen.setStyle(Qt::SolidLine); mBrush.setColor(Qt::blue); mBrush.setStyle(Qt::NoBrush); mSelectedPen = mPen; mSelectedPen.setWidthF(2.5); mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen mSelectedBrush = mBrush; setScatterStyle(QCPScatterStyle()); setLineStyle(lsLine); } QCPCurve::~QCPCurve() { delete mData; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. */ void QCPCurve::setData(QCPCurveDataMap *data, bool copy) { if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided points in \a t, \a key and \a value tuples. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPCurve::setData(const QVector &t, const QVector &key, const QVector &value) { mData->clear(); int n = t.size(); n = qMin(n, key.size()); n = qMin(n, value.size()); QCPCurveData newData; for (int i=0; iinsertMulti(newData.t, newData); } } /*! \overload Replaces the current data with the provided \a key and \a value pairs. The t parameter of each data point will be set to the integer index of the respective key/value pair. */ void QCPCurve::setData(const QVector &key, const QVector &value) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); QCPCurveData newData; for (int i=0; iinsertMulti(newData.t, newData); } } /*! Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate line style). \see QCPScatterStyle, setLineStyle */ void QCPCurve::setScatterStyle(const QCPScatterStyle &style) { mScatterStyle = style; } /*! Sets how the single data points are connected in the plot or how they are represented visually apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref setScatterStyle to the desired scatter style. \see setScatterStyle */ void QCPCurve::setLineStyle(QCPCurve::LineStyle style) { mLineStyle = style; } /*! Adds the provided data points in \a dataMap to the current data. \see removeData */ void QCPCurve::addData(const QCPCurveDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. \see removeData */ void QCPCurve::addData(const QCPCurveData &data) { mData->insertMulti(data.t, data); } /*! \overload Adds the provided single data point as \a t, \a key and \a value tuple to the current data \see removeData */ void QCPCurve::addData(double t, double key, double value) { QCPCurveData newData; newData.t = t; newData.key = key; newData.value = value; mData->insertMulti(newData.t, newData); } /*! \overload Adds the provided single data point as \a key and \a value pair to the current data The t parameter of the data point is set to the t of the last data point plus 1. If there is no last data point, t will be set to 0. \see removeData */ void QCPCurve::addData(double key, double value) { QCPCurveData newData; if (!mData->isEmpty()) newData.t = (mData->constEnd()-1).key()+1; else newData.t = 0; newData.key = key; newData.value = value; mData->insertMulti(newData.t, newData); } /*! \overload Adds the provided data points as \a t, \a key and \a value tuples to the current data. \see removeData */ void QCPCurve::addData(const QVector &ts, const QVector &keys, const QVector &values) { int n = ts.size(); n = qMin(n, keys.size()); n = qMin(n, values.size()); QCPCurveData newData; for (int i=0; iinsertMulti(newData.t, newData); } } /*! Removes all data points with curve parameter t smaller than \a t. \see addData, clearData */ void QCPCurve::removeDataBefore(double t) { QCPCurveDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < t) it = mData->erase(it); } /*! Removes all data points with curve parameter t greater than \a t. \see addData, clearData */ void QCPCurve::removeDataAfter(double t) { if (mData->isEmpty()) return; QCPCurveDataMap::iterator it = mData->upperBound(t); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is greater or equal to \a tot, the function does nothing. To remove a single data point with known t, use \ref removeData(double t). \see addData, clearData */ void QCPCurve::removeData(double fromt, double tot) { if (fromt >= tot || mData->isEmpty()) return; QCPCurveDataMap::iterator it = mData->upperBound(fromt); QCPCurveDataMap::iterator itEnd = mData->upperBound(tot); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at curve parameter \a t. If the position is not known with absolute precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness interval around the suspected position, depeding on the precision with which the curve parameter is known. \see addData, clearData */ void QCPCurve::removeData(double t) { mData->remove(t); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPCurve::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if ((onlySelectable && !mSelectable) || mData->isEmpty()) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) return pointDistance(pos); else return -1; } /* inherits documentation from base class */ void QCPCurve::draw(QCPPainter *painter) { if (mData->isEmpty()) return; // allocate line vector: QVector *lineData = new QVector; // fill with curve data: getCurveData(lineData); // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA QCPCurveDataMap::const_iterator it; for (it = mData->constBegin(); it != mData->constEnd(); ++it) { if (QCP::isInvalidData(it.value().t) || QCP::isInvalidData(it.value().key, it.value().value)) qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); } #endif // draw curve fill: if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) { applyFillAntialiasingHint(painter); painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(QPolygonF(*lineData)); } // draw curve line: if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(Qt::NoBrush); // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && painter->pen().style() == Qt::SolidLine && !painter->modes().testFlag(QCPPainter::pmVectorized) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) { for (int i=1; isize(); ++i) painter->drawLine(lineData->at(i-1), lineData->at(i)); } else { painter->drawPolyline(QPolygonF(*lineData)); } } // draw scatters: if (!mScatterStyle.isNone()) drawScatterPlot(painter, lineData); // free allocated line data: delete lineData; } /* inherits documentation from base class */ void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw fill: if (mBrush.style() != Qt::NoBrush) { applyFillAntialiasingHint(painter); painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); } // draw line vertically centered: if (mLineStyle != lsNone) { applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens } // draw scatter symbol: if (!mScatterStyle.isNone()) { applyScattersAntialiasingHint(painter); // scale scatter pixmap if it's too large to fit in legend icon rect: if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) { QCPScatterStyle scaledStyle(mScatterStyle); scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); scaledStyle.applyTo(painter, mPen); scaledStyle.drawShape(painter, QRectF(rect).center()); } else { mScatterStyle.applyTo(painter, mPen); mScatterStyle.drawShape(painter, QRectF(rect).center()); } } } /*! \internal Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone. */ void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector *pointData) const { // draw scatter point symbols: applyScattersAntialiasingHint(painter); mScatterStyle.applyTo(painter, mPen); for (int i=0; isize(); ++i) mScatterStyle.drawShape(painter, pointData->at(i)); } /*! \internal called by QCPCurve::draw to generate a point vector (pixels) which represents the line of the curve. Line segments that aren't visible in the current axis rect are handled in an optimized way. */ void QCPCurve::getCurveData(QVector *lineData) const { /* Extended sides of axis rect R divide space into 9 regions: 1__|_4_|__7 2__|_R_|__8 3 | 6 | 9 General idea: If the two points of a line segment are in the same region (that is not R), the line segment corner is removed. Curves outside R become straight lines closely outside of R which greatly reduces drawing time, yet keeps the look of lines and fills inside R consistent. The region R has index 5. */ QCPAxis *keyAxis = mKeyAxis.data(); QCPAxis *valueAxis = mValueAxis.data(); if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } QRect axisRect = mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); lineData->reserve(mData->size()); QCPCurveDataMap::const_iterator it; int lastRegion = 5; int currentRegion = 5; double RLeft = keyAxis->range().lower; double RRight = keyAxis->range().upper; double RBottom = valueAxis->range().lower; double RTop = valueAxis->range().upper; double x, y; // current key/value bool addedLastAlready = true; bool firstPoint = true; // first point must always be drawn, to make sure fill works correctly for (it = mData->constBegin(); it != mData->constEnd(); ++it) { x = it.value().key; y = it.value().value; // determine current region: if (x < RLeft) // region 123 { if (y > RTop) currentRegion = 1; else if (y < RBottom) currentRegion = 3; else currentRegion = 2; } else if (x > RRight) // region 789 { if (y > RTop) currentRegion = 7; else if (y < RBottom) currentRegion = 9; else currentRegion = 8; } else // region 456 { if (y > RTop) currentRegion = 4; else if (y < RBottom) currentRegion = 6; else currentRegion = 5; } /* Watch out, the next part is very tricky. It modifies the curve such that it seems like the whole thing is still drawn, but actually the points outside the axisRect are simplified ("optimized") greatly. There are some subtle special cases when line segments are large and thereby each subsequent point may be in a different region or even skip some. */ // determine whether to keep current point: if (currentRegion == 5 || (firstPoint && mBrush.style() != Qt::NoBrush)) // current is in R, add current and last if it wasn't added already { if (!addedLastAlready) // in case curve just entered R, make sure the last point outside R is also drawn correctly lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value)); // add last point to vector else if (lastRegion != 5) // added last already. If that's the case, we probably added it at optimized position. So go back and make sure it's at original position (else the angle changes under which this segment enters R) { if (!firstPoint) // because on firstPoint, currentRegion is 5 and addedLastAlready is true, although there is no last point lineData->replace(lineData->size()-1, coordsToPixels((it-1).value().key, (it-1).value().value)); } lineData->append(coordsToPixels(it.value().key, it.value().value)); // add current point to vector addedLastAlready = true; // so in next iteration, we don't add this point twice } else if (currentRegion != lastRegion) // changed region, add current and last if not added already { // using outsideCoordsToPixels instead of coorsToPixels for optimized point placement (places points just outside axisRect instead of potentially far away) // if we're coming from R or we skip diagonally over the corner regions (so line might still be visible in R), we can't place points optimized if (lastRegion == 5 || // coming from R ((lastRegion==2 && currentRegion==4) || (lastRegion==4 && currentRegion==2)) || // skip top left diagonal ((lastRegion==4 && currentRegion==8) || (lastRegion==8 && currentRegion==4)) || // skip top right diagonal ((lastRegion==8 && currentRegion==6) || (lastRegion==6 && currentRegion==8)) || // skip bottom right diagonal ((lastRegion==6 && currentRegion==2) || (lastRegion==2 && currentRegion==6)) // skip bottom left diagonal ) { // always add last point if not added already, original: if (!addedLastAlready) lineData->append(coordsToPixels((it-1).value().key, (it-1).value().value)); // add current point, original: lineData->append(coordsToPixels(it.value().key, it.value().value)); } else // no special case that forbids optimized point placement, so do it: { // always add last point if not added already, optimized: if (!addedLastAlready) lineData->append(outsideCoordsToPixels((it-1).value().key, (it-1).value().value, currentRegion, axisRect)); // add current point, optimized: lineData->append(outsideCoordsToPixels(it.value().key, it.value().value, currentRegion, axisRect)); } addedLastAlready = true; // so that if next point enters 5, or crosses another region boundary, we don't add this point twice } else // neither in R, nor crossed a region boundary, skip current point { addedLastAlready = false; } lastRegion = currentRegion; firstPoint = false; } // If curve ends outside R, we want to add very last point so the fill looks like it should when the curve started inside R: if (lastRegion != 5 && mBrush.style() != Qt::NoBrush && !mData->isEmpty()) lineData->append(coordsToPixels((mData->constEnd()-1).value().key, (mData->constEnd()-1).value().value)); } /*! \internal Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in \ref selectTest. */ double QCPCurve::pointDistance(const QPointF &pixelPoint) const { if (mData->isEmpty()) { qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data"; return 500; } if (mData->size() == 1) { QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); return QVector2D(dataPoint-pixelPoint).length(); } // calculate minimum distance to line segments: QVector *lineData = new QVector; getCurveData(lineData); double minDistSqr = std::numeric_limits::max(); for (int i=0; isize()-1; ++i) { double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); if (currentDistSqr < minDistSqr) minDistSqr = currentDistSqr; } delete lineData; return sqrt(minDistSqr); } /*! \internal This is a specialized \ref coordsToPixels function for points that are outside the visible axisRect and just crossing a boundary (since \ref getCurveData reduces non-visible curve segments to those line segments that cross region boundaries, see documentation there). It only uses the coordinate parallel to the region boundary of the axisRect. The other coordinate is picked just outside the axisRect (how far is determined by the scatter size and the line width). Together with the optimization in \ref getCurveData this improves performance for large curves (or zoomed in ones) significantly while keeping the illusion the whole curve and its filling is still being drawn for the viewer. */ QPointF QCPCurve::outsideCoordsToPixels(double key, double value, int region, QRect axisRect) const { int margin = qCeil(qMax(mScatterStyle.size(), (double)mPen.widthF())) + 2; QPointF result = coordsToPixels(key, value); switch (region) { case 2: result.setX(axisRect.left()-margin); break; // left case 8: result.setX(axisRect.right()+margin); break; // right case 4: result.setY(axisRect.top()-margin); break; // top case 6: result.setY(axisRect.bottom()+margin); break; // bottom case 1: result.setX(axisRect.left()-margin); result.setY(axisRect.top()-margin); break; // top left case 7: result.setX(axisRect.right()+margin); result.setY(axisRect.top()-margin); break; // top right case 9: result.setX(axisRect.right()+margin); result.setY(axisRect.bottom()+margin); break; // bottom right case 3: result.setX(axisRect.left()-margin); result.setY(axisRect.bottom()+margin); break; // bottom left } return result; } /* inherits documentation from base class */ QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPCurveDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; QCPCurveDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value; if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } foundRange = haveLower && haveUpper; return range; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBarData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBarData \brief Holds the data of one single data point (one bar) for QCPBars. The container for storing multiple data points is \ref QCPBarDataMap. The stored data is: \li \a key: coordinate on the key axis of this bar \li \a value: height coordinate on the value axis of this bar \see QCPBarDataaMap */ /*! Constructs a bar data point with key and value set to zero. */ QCPBarData::QCPBarData() : key(0), value(0) { } /*! Constructs a bar data point with the specified \a key and \a value. */ QCPBarData::QCPBarData(double key, double value) : key(key), value(value) { } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPBars //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPBars \brief A plottable representing a bar chart in a plot. \image html QCPBars.png To plot data, assign it with the \ref setData or \ref addData functions. \section appearance Changing the appearance The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush). Bar charts are stackable. This means, Two QCPBars plottables can be placed on top of each other (see \ref QCPBars::moveAbove). Then, when two bars are at the same key position, they will appear stacked. \section usage Usage Like all data representing objects in QCustomPlot, the QCPBars is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \code QCPBars *newBars = new QCPBars(customPlot->xAxis, customPlot->yAxis);\endcode add it to the customPlot with QCustomPlot::addPlottable: \code customPlot->addPlottable(newBars);\endcode and then modify the properties of the newly created plottable, e.g.: \code newBars->setName("Country population"); newBars->setData(xData, yData);\endcode */ /*! \fn QCPBars *QCPBars::barBelow() const Returns the bars plottable that is directly below this bars plottable. If there is no such plottable, returns 0. \see barAbove, moveBelow, moveAbove */ /*! \fn QCPBars *QCPBars::barAbove() const Returns the bars plottable that is directly above this bars plottable. If there is no such plottable, returns 0. \see barBelow, moveBelow, moveAbove */ /*! Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the bar chart. */ QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis) { mData = new QCPBarDataMap; mPen.setColor(Qt::blue); mPen.setStyle(Qt::SolidLine); mBrush.setColor(QColor(40, 50, 255, 30)); mBrush.setStyle(Qt::SolidPattern); mSelectedPen = mPen; mSelectedPen.setWidthF(2.5); mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen mSelectedBrush = mBrush; mWidth = 0.75; } QCPBars::~QCPBars() { if (mBarBelow || mBarAbove) connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking delete mData; } /*! Sets the width of the bars in plot (key) coordinates. */ void QCPBars::setWidth(double width) { mWidth = width; } /*! Replaces the current data with the provided \a data. If \a copy is set to true, data points in \a data will only be copied. if false, the plottable takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. */ void QCPBars::setData(QCPBarDataMap *data, bool copy) { if (copy) { *mData = *data; } else { delete mData; mData = data; } } /*! \overload Replaces the current data with the provided points in \a key and \a value tuples. The provided vectors should have equal length. Else, the number of added points will be the size of the smallest vector. */ void QCPBars::setData(const QVector &key, const QVector &value) { mData->clear(); int n = key.size(); n = qMin(n, value.size()); QCPBarData newData; for (int i=0; iinsertMulti(newData.key, newData); } } /*! Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear below the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already has a bars object below itself, this bars object is inserted between the two. If this bars object is already between two other bars, the two other bars will be stacked on top of each other after the operation. To remove this bars plottable from any stacking, set \a bars to 0. \see moveBelow, barAbove, barBelow */ void QCPBars::moveBelow(QCPBars *bars) { if (bars == this) return; if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; return; } // remove from stacking: connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 // if new bar given, insert this bar below it: if (bars) { if (bars->mBarBelow) connectBars(bars->mBarBelow.data(), this); connectBars(this, bars); } } /*! Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear above the bars of \a bars. The move target \a bars must use the same key and value axis as this plottable. Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already has a bars object below itself, this bars object is inserted between the two. If this bars object is already between two other bars, the two other bars will be stacked on top of each other after the operation. To remove this bars plottable from any stacking, set \a bars to 0. \see moveBelow, barBelow, barAbove */ void QCPBars::moveAbove(QCPBars *bars) { if (bars == this) return; if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) { qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; return; } // remove from stacking: connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 // if new bar given, insert this bar above it: if (bars) { if (bars->mBarAbove) connectBars(this, bars->mBarAbove.data()); connectBars(bars, this); } } /*! Adds the provided data points in \a dataMap to the current data. \see removeData */ void QCPBars::addData(const QCPBarDataMap &dataMap) { mData->unite(dataMap); } /*! \overload Adds the provided single data point in \a data to the current data. \see removeData */ void QCPBars::addData(const QCPBarData &data) { mData->insertMulti(data.key, data); } /*! \overload Adds the provided single data point as \a key and \a value tuple to the current data \see removeData */ void QCPBars::addData(double key, double value) { QCPBarData newData; newData.key = key; newData.value = value; mData->insertMulti(newData.key, newData); } /*! \overload Adds the provided data points as \a key and \a value tuples to the current data. \see removeData */ void QCPBars::addData(const QVector &keys, const QVector &values) { int n = keys.size(); n = qMin(n, values.size()); QCPBarData newData; for (int i=0; iinsertMulti(newData.key, newData); } } /*! Removes all data points with key smaller than \a key. \see addData, clearData */ void QCPBars::removeDataBefore(double key) { QCPBarDataMap::iterator it = mData->begin(); while (it != mData->end() && it.key() < key) it = mData->erase(it); } /*! Removes all data points with key greater than \a key. \see addData, clearData */ void QCPBars::removeDataAfter(double key) { if (mData->isEmpty()) return; QCPBarDataMap::iterator it = mData->upperBound(key); while (it != mData->end()) it = mData->erase(it); } /*! Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove a single data point with known key, use \ref removeData(double key). \see addData, clearData */ void QCPBars::removeData(double fromKey, double toKey) { if (fromKey >= toKey || mData->isEmpty()) return; QCPBarDataMap::iterator it = mData->upperBound(fromKey); QCPBarDataMap::iterator itEnd = mData->upperBound(toKey); while (it != itEnd) it = mData->erase(it); } /*! \overload Removes a single data point at \a key. If the position is not known with absolute precision, consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around the suspected position, depeding on the precision with which the key is known. \see addData, clearData */ void QCPBars::removeData(double key) { mData->remove(key); } /*! Removes all data points. \see removeData, removeDataAfter, removeDataBefore */ void QCPBars::clearData() { mData->clear(); } /* inherits documentation from base class */ double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { QCPBarDataMap::ConstIterator it; double posKey, posValue; pixelsToCoords(pos, posKey, posValue); for (it = mData->constBegin(); it != mData->constEnd(); ++it) { double baseValue = getBaseValue(it.key(), it.value().value >=0); QCPRange keyRange(it.key()-mWidth*0.5, it.key()+mWidth*0.5); QCPRange valueRange(baseValue, baseValue+it.value().value); if (keyRange.contains(posKey) && valueRange.contains(posValue)) return mParentPlot->selectionTolerance()*0.99; } } return -1; } /* inherits documentation from base class */ void QCPBars::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } if (mData->isEmpty()) return; QCPBarDataMap::const_iterator it; for (it = mData->constBegin(); it != mData->constEnd(); ++it) { // skip bar if not visible in key axis range: if (it.key()+mWidth*0.5 < mKeyAxis.data()->range().lower || it.key()-mWidth*0.5 > mKeyAxis.data()->range().upper) continue; // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA if (QCP::isInvalidData(it.value().key, it.value().value)) qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name(); #endif QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value); // draw bar fill: if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) { applyFillAntialiasingHint(painter); painter->setPen(Qt::NoPen); painter->setBrush(mainBrush()); painter->drawPolygon(barPolygon); } // draw bar line: if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) { applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(Qt::NoBrush); painter->drawPolyline(barPolygon); } } } /* inherits documentation from base class */ void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw filled rect: applyDefaultAntialiasingHint(painter); painter->setBrush(mBrush); painter->setPen(mPen); QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); r.moveCenter(rect.center()); painter->drawRect(r); } /*! \internal Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom and shifted according to the bar stacking (see \ref moveAbove). */ QPolygonF QCPBars::getBarPolygon(double key, double value) const { QPolygonF result; double baseValue = getBaseValue(key, value >= 0); result << coordsToPixels(key-mWidth*0.5, baseValue); result << coordsToPixels(key-mWidth*0.5, baseValue+value); result << coordsToPixels(key+mWidth*0.5, baseValue+value); result << coordsToPixels(key+mWidth*0.5, baseValue); return result; } /*! \internal This function is called to find at which value to start drawing the base of a bar at \a key, when it is stacked on top of another QCPBars (e.g. with \ref moveAbove). positive and negative bars are separated per stack (positive are stacked above 0-value upwards, negative are stacked below 0-value downwards). This can be indicated with \a positive. So if the bar for which we need the base value is negative, set \a positive to false. */ double QCPBars::getBaseValue(double key, bool positive) const { if (mBarBelow) { double max = 0; // find bars of mBarBelow that are approximately at key and find largest one: QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-mWidth*0.1); QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+mWidth*0.1); while (it != itEnd) { if ((positive && it.value().value > max) || (!positive && it.value().value < max)) max = it.value().value; ++it; } // recurse down the bar-stack to find the total height: return max + mBarBelow.data()->getBaseValue(key, positive); } else return 0; } /*! \internal Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) currently below lower and upper will become disconnected to lower/upper. If lower is zero, upper will be disconnected at the bottom. If upper is zero, lower will be disconnected at the top. */ void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) { if (!lower && !upper) return; if (!lower) // disconnect upper at bottom { // disconnect old bar below upper: if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) upper->mBarBelow.data()->mBarAbove = 0; upper->mBarBelow = 0; } else if (!upper) // disconnect lower at top { // disconnect old bar above lower: if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) lower->mBarAbove.data()->mBarBelow = 0; lower->mBarAbove = 0; } else // connect lower and upper { // disconnect old bar above lower: if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) lower->mBarAbove.data()->mBarBelow = 0; // disconnect old bar below upper: if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) upper->mBarBelow.data()->mBarAbove = 0; lower->mBarAbove = upper; upper->mBarBelow = lower; } } /* inherits documentation from base class */ QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = false; bool haveUpper = false; double current; double barWidthHalf = mWidth*0.5; QCPBarDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().key; if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current+barWidthHalf < 0) || (inSignDomain == sdPositive && current-barWidthHalf > 0)) { if (current-barWidthHalf < range.lower || !haveLower) { range.lower = current-barWidthHalf; haveLower = true; } if (current+barWidthHalf > range.upper || !haveUpper) { range.upper = current+barWidthHalf; haveUpper = true; } } ++it; } foundRange = haveLower && haveUpper; return range; } /* inherits documentation from base class */ QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const { QCPRange range; bool haveLower = true; // set to true, because 0 should always be visible in bar charts bool haveUpper = true; // set to true, because 0 should always be visible in bar charts double current; QCPBarDataMap::const_iterator it = mData->constBegin(); while (it != mData->constEnd()) { current = it.value().value + getBaseValue(it.value().key, it.value().value >= 0); if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) { if (current < range.lower || !haveLower) { range.lower = current; haveLower = true; } if (current > range.upper || !haveUpper) { range.upper = current; haveUpper = true; } } ++it; } foundRange = true; // return true because bar charts always have the 0-line visible return range; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPStatisticalBox //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPStatisticalBox \brief A plottable representing a single statistical box in a plot. \image html QCPStatisticalBox.png To plot data, assign it with the individual parameter functions or use \ref setData to set all parameters at once. The individual functions are: \li \ref setMinimum \li \ref setLowerQuartile \li \ref setMedian \li \ref setUpperQuartile \li \ref setMaximum Additionally you can define a list of outliers, drawn as scatter datapoints: \li \ref setOutliers \section appearance Changing the appearance The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change the width of the box with \ref setWidth in plot coordinates (not pixels). Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top (maximum) and bottom (minimum). The median indicator line has its own pen, \ref setMedianPen. If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the backbone line might exceed the whisker bars by a few pixels due to the pen cap being not perfectly flat. The Outlier data points are drawn as normal scatter points. Their look can be controlled with \ref setOutlierStyle \section usage Usage Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) Usually, you first create an instance: \code QCPStatisticalBox *newBox = new QCPStatisticalBox(customPlot->xAxis, customPlot->yAxis);\endcode add it to the customPlot with QCustomPlot::addPlottable: \code customPlot->addPlottable(newBox);\endcode and then modify the properties of the newly created plottable, e.g.: \code newBox->setName("Measurement Series 1"); newBox->setData(1, 3, 4, 5, 7); newBox->setOutliers(QVector() << 0.5 << 0.64 << 7.2 << 7.42);\endcode */ /*! Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have the same orientation. If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though. The constructed statistical box can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the statistical box. */ QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mKey(0), mMinimum(0), mLowerQuartile(0), mMedian(0), mUpperQuartile(0), mMaximum(0) { setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)); setWhiskerWidth(0.2); setWidth(0.5); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2.5)); setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap)); setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap)); setWhiskerBarPen(QPen(Qt::black)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } /*! Sets the key coordinate of the statistical box. */ void QCPStatisticalBox::setKey(double key) { mKey = key; } /*! Sets the parameter "minimum" of the statistical box plot. This is the position of the lower whisker, typically the minimum measurement of the sample that's not considered an outlier. \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth */ void QCPStatisticalBox::setMinimum(double value) { mMinimum = value; } /*! Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the box. The lower and the upper quartiles are the two statistical quartiles around the median of the sample, they contain 50% of the sample data. \see setUpperQuartile, setPen, setBrush, setWidth */ void QCPStatisticalBox::setLowerQuartile(double value) { mLowerQuartile = value; } /*! Sets the parameter "median" of the statistical box plot. This is the value of the median mark inside the quartile box. The median separates the sample data in half (50% of the sample data is below/above the median). \see setMedianPen */ void QCPStatisticalBox::setMedian(double value) { mMedian = value; } /*! Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the box. The lower and the upper quartiles are the two statistical quartiles around the median of the sample, they contain 50% of the sample data. \see setLowerQuartile, setPen, setBrush, setWidth */ void QCPStatisticalBox::setUpperQuartile(double value) { mUpperQuartile = value; } /*! Sets the parameter "maximum" of the statistical box plot. This is the position of the upper whisker, typically the maximum measurement of the sample that's not considered an outlier. \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth */ void QCPStatisticalBox::setMaximum(double value) { mMaximum = value; } /*! Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers and displayed as such. \see setOutlierStyle */ void QCPStatisticalBox::setOutliers(const QVector &values) { mOutliers = values; } /*! Sets all parameters of the statistical box plot at once. \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum */ void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) { setKey(key); setMinimum(minimum); setLowerQuartile(lowerQuartile); setMedian(median); setUpperQuartile(upperQuartile); setMaximum(maximum); } /*! Sets the width of the box in key coordinates. \see setWhiskerWidth */ void QCPStatisticalBox::setWidth(double width) { mWidth = width; } /*! Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates. \see setWidth */ void QCPStatisticalBox::setWhiskerWidth(double width) { mWhiskerWidth = width; } /*! Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis). Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching a few pixels past the whisker bars, when using a non-zero pen width. \see setWhiskerBarPen */ void QCPStatisticalBox::setWhiskerPen(const QPen &pen) { mWhiskerPen = pen; } /*! Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at each end of the whisker backbone). \see setWhiskerPen */ void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) { mWhiskerBarPen = pen; } /*! Sets the pen used for drawing the median indicator line inside the statistical box. */ void QCPStatisticalBox::setMedianPen(const QPen &pen) { mMedianPen = pen; } /*! Sets the appearance of the outlier data points. \see setOutliers */ void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) { mOutlierStyle = style; } /* inherits documentation from base class */ void QCPStatisticalBox::clearData() { setOutliers(QVector()); setKey(0); setMinimum(0); setLowerQuartile(0); setMedian(0); setUpperQuartile(0); setMaximum(0); } /* inherits documentation from base class */ double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { double posKey, posValue; pixelsToCoords(pos, posKey, posValue); // quartile box: QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5); QCPRange valueRange(mLowerQuartile, mUpperQuartile); if (keyRange.contains(posKey) && valueRange.contains(posValue)) return mParentPlot->selectionTolerance()*0.99; // min/max whiskers: if (QCPRange(mMinimum, mMaximum).contains(posValue)) return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey)); } return -1; } /* inherits documentation from base class */ void QCPStatisticalBox::draw(QCPPainter *painter) { if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } // check data validity if flag set: #ifdef QCUSTOMPLOT_CHECK_DATA if (QCP::isInvalidData(mKey, mMedian) || QCP::isInvalidData(mLowerQuartile, mUpperQuartile) || QCP::isInvalidData(mMinimum, mMaximum)) qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name(); for (int i=0; isave(); painter->setClipRect(quartileBox, Qt::IntersectClip); drawMedian(painter); painter->restore(); drawWhiskers(painter); drawOutliers(painter); } /* inherits documentation from base class */ void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { // draw filled rect: applyDefaultAntialiasingHint(painter); painter->setPen(mPen); painter->setBrush(mBrush); QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); r.moveCenter(rect.center()); painter->drawRect(r); } /*! \internal Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so the median doesn't draw outside the quartile box). */ void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const { QRectF box; box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile)); box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile)); applyDefaultAntialiasingHint(painter); painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(box); if (quartileBox) *quartileBox = box; } /*! \internal Draws the median line inside the quartile box. */ void QCPStatisticalBox::drawMedian(QCPPainter *painter) const { QLineF medianLine; medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian)); medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian)); applyDefaultAntialiasingHint(painter); painter->setPen(mMedianPen); painter->drawLine(medianLine); } /*! \internal Draws both whisker backbones and bars. */ void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const { QLineF backboneMin, backboneMax, barMin, barMax; backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum)); backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum)); barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum)); barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum)); applyErrorBarsAntialiasingHint(painter); painter->setPen(mWhiskerPen); painter->drawLine(backboneMin); painter->drawLine(backboneMax); painter->setPen(mWhiskerBarPen); painter->drawLine(barMin); painter->drawLine(barMax); } /*! \internal Draws the outlier scatter points. */ void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const { applyScattersAntialiasingHint(painter); mOutlierStyle.applyTo(painter, mPen); for (int i=0; i 0) return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); else if (mKey > 0) return QCPRange(mKey, mKey+mWidth*0.5); else { foundRange = false; return QCPRange(); } } foundRange = false; return QCPRange(); } /* inherits documentation from base class */ QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const { QVector values; // values that must be considered (i.e. all outliers and the five box-parameters) values.reserve(mOutliers.size() + 5); values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum; values << mOutliers; // go through values and find the ones in legal range: bool haveUpper = false; bool haveLower = false; double upper = 0; double lower = 0; for (int i=0; i 0) || (inSignDomain == sdBoth)) { if (values.at(i) > upper || !haveUpper) { upper = values.at(i); haveUpper = true; } if (values.at(i) < lower || !haveLower) { lower = values.at(i); haveLower = true; } } } // return the bounds if we found some sensible values: if (haveLower && haveUpper) { foundRange = true; return QCPRange(lower, upper); } else // might happen if all values are in other sign domain { foundRange = false; return QCPRange(); } } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPColorMapData //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPColorMapData \brief Holds the two-dimensional data of a QCPColorMap plottable. This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a color, depending on the value. The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref setKeyRange, \ref setValueRange). The data cells can be accessed in two ways: They can be directly addressed by an integer index with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are provided by the functions \ref coordToCell and \ref cellToCoord. This class also buffers the minimum and maximum values that are in the data set, to provide QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value that is greater than the current maximum increases this maximum to the new value. However, setting the cell that currently holds the maximum value to a smaller value doesn't decrease the maximum again, because finding the true new maximum would require going through the entire data array, which might be time consuming. The same holds for the data minimum. This functionality is given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience parameter \a recalculateDataBounds which may be set to true to automatically call \ref recalculateDataBounds internally. */ /* start of documentation of inline functions */ /*! \fn bool QCPColorMapData::isEmpty() const Returns whether this instance carries no data. This is equivalent to having a size where at least one of the dimensions is 0 (see \ref setSize). */ /* end of documentation of inline functions */ /*! Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap at the coordinates \a keyRange and \a valueRange. \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange */ QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : mKeySize(0), mValueSize(0), mKeyRange(keyRange), mValueRange(valueRange), mIsEmpty(true), mData(0), mDataModified(true) { setSize(keySize, valueSize); fill(0); } QCPColorMapData::~QCPColorMapData() { if (mData) delete[] mData; } /*! Constructs a new QCPColorMapData instance copying the data and range of \a other. */ QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : mKeySize(0), mValueSize(0), mIsEmpty(true), mData(0), mDataModified(true) { *this = other; } /*! Overwrites this color map data instance with the data stored in \a other. */ QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) { if (&other != this) { const int keySize = other.keySize(); const int valueSize = other.valueSize(); setSize(keySize, valueSize); setRange(other.keyRange(), other.valueRange()); if (!mIsEmpty) memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize); mDataBounds = other.mDataBounds; mDataModified = true; } return *this; } /* undocumented getter */ double QCPColorMapData::data(double key, double value) { int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; int valueCell = (1.0-(value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower))*(mValueSize-1)+0.5; if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) return mData[valueCell*mKeySize + keyCell]; else return 0; } /* undocumented getter */ double QCPColorMapData::cell(int keyIndex, int valueIndex) { if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) return mData[valueIndex*mKeySize + keyIndex]; else return 0; } /*! Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in the value dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setRange, setKeySize, setValueSize */ void QCPColorMapData::setSize(int keySize, int valueSize) { if (keySize != mKeySize || valueSize != mValueSize) { mKeySize = keySize; mValueSize = valueSize; if (mData) delete[] mData; mIsEmpty = mKeySize == 0 || mValueSize == 0; if (!mIsEmpty) { #ifdef __EXCEPTIONS try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message #endif mData = new double[mKeySize*mValueSize]; #ifdef __EXCEPTIONS } catch (...) { mData = 0; } #endif if (mData) fill(0); else qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; } else mData = 0; mDataModified = true; } } /*! Resizes the data array to have \a keySize cells in the key dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. \see setKeyRange, setSize, setValueSize */ void QCPColorMapData::setKeySize(int keySize) { setSize(keySize, mValueSize); } /*! Resizes the data array to have \a valueSize cells in the value dimension. The current data is discarded and the map cells are set to 0, unless the map had already the requested size. Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. \see setValueRange, setSize, setKeySize */ void QCPColorMapData::setValueSize(int valueSize) { setSize(mKeySize, valueSize); } /*! Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. \see setSize */ void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) { setKeyRange(keyRange); setValueRange(valueRange); } /*! Sets the coordinate range the data shall be distributed over in the key dimension. Together with the value range, This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will be cells centered on the key coordinates 2, 2.5 and 3. \see setRange, setValueRange, setSize */ void QCPColorMapData::setKeyRange(const QCPRange &keyRange) { mKeyRange = keyRange; } /*! Sets the coordinate range the data shall be distributed over in the value dimension. Together with the key range, This defines the rectangular area covered by the color map in plot coordinates. The outer cells will be centered on the range boundaries given to this function. For example, if the value size (\ref setValueSize) is 3 and \a valueRange is set to QCPRange(2, 3) there will be cells centered on the value coordinates 2, 2.5 and 3. \see setRange, setKeyRange, setSize */ void QCPColorMapData::setValueRange(const QCPRange &valueRange) { mValueRange = valueRange; } /*! Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a z. \see setCell, setRange */ void QCPColorMapData::setData(double key, double value, double z) { int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) { mData[valueCell*mKeySize + keyCell] = z; if (z < mDataBounds.lower) mDataBounds.lower = z; if (z > mDataBounds.upper) mDataBounds.upper = z; mDataModified = true; } } /*! Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see \ref setSize). In the standard plot configuration (horizontal key axis and vertical value axis, both not range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with indices (keySize-1, valueSize-1) is in the top right corner of the color map. \see setData, setSize */ void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) { if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) { mData[valueIndex*mKeySize + keyIndex] = z; if (z < mDataBounds.lower) mDataBounds.lower = z; if (z > mDataBounds.upper) mDataBounds.upper = z; mDataModified = true; } } /*! Goes through the data and updates the buffered minimum and maximum data values. Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten with a smaller or larger value respectively, since the buffered maximum/minimum values have been updated the last time. Why this is the case is explained in the class description (\ref QCPColorMapData). Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a recalculateDataBounds for convenience. Setting this to true will call this method for you, before doing the rescale. */ void QCPColorMapData::recalculateDataBounds() { if (mKeySize > 0 && mValueSize > 0) { double minHeight = mData[0]; double maxHeight = mData[0]; const int dataCount = mValueSize*mKeySize; for (int i=0; i maxHeight) maxHeight = mData[i]; if (mData[i] < minHeight) minHeight = mData[i]; } mDataBounds.lower = minHeight; mDataBounds.upper = maxHeight; } } /*! Frees the internal data memory. This is equivalent to calling \ref setSize "setSize(0, 0)". */ void QCPColorMapData::clear() { setSize(0, 0); } /*! Sets all cells to the value \a z. */ void QCPColorMapData::fill(double z) { const int dataCount = mValueSize*mKeySize; for (int i=0; ixAxis, customPlot->yAxis);\endcode add it to the customPlot with QCustomPlot::addPlottable: \code customPlot->addPlottable(colorMap);\endcode and then modify the properties of the newly created color map, e.g.: \code colorMap->data()->setSize(50, 50); colorMap->data()->setRange(QCPRange(0, 2), QCPRange(0, 2)); for (int x=0; x<50; ++x) for (int y=0; y<50; ++y) colorMap->data()->setCell(x, y, qCos(x/10.0)+qSin(y/10.0)); colorMap->setGradient(QCPColorGradient::gpPolar); colorMap->rescaleDataRange(true); customPlot->rescaleAxes(); customPlot->replot(); \endcode \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to determine the cell index. Rather directly access the cell index with \ref QCPColorMapData::setCell. */ /* start documentation of inline functions */ /*! \fn QCPColorMapData *QCPColorMap::data() const Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to modify data points (cells) and the color map key/value range. \see setData */ /* end documentation of inline functions */ /* start documentation of signals */ /*! \fn void QCPColorMap::dataRangeChanged(QCPRange newRange); This signal is emitted when the data range changes. \see setDataRange */ /*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); This signal is emitted when the data scale type changes. \see setDataScaleType */ /*! \fn void QCPColorMap::gradientChanged(QCPColorGradient newGradient); This signal is emitted when the gradient changes. \see setGradient */ /* end documentation of signals */ /*! Constructs a color map with the specified \a keyAxis and \a valueAxis. The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot then takes ownership of the color map. */ QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) : QCPAbstractPlottable(keyAxis, valueAxis), mDataScaleType(QCPAxis::stLinear), mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))), mInterpolate(true), mTightBoundary(false), mMapImageInvalidated(true) { } QCPColorMap::~QCPColorMap() { delete mMapData; } /*! Replaces the current \ref data with the provided \a data. If \a copy is set to true, the \a data object will only be copied. if false, the color map takes ownership of the passed data and replaces the internal data pointer with it. This is significantly faster than copying for large datasets. */ void QCPColorMap::setData(QCPColorMapData *data, bool copy) { if (copy) { *mMapData = *data; } else { delete mMapData; mMapData = data; } mMapImageInvalidated = true; } /*! Sets the data range of this color map to \a dataRange. The data range defines which data values are mapped to the color gradient. To make the data range span the full range of the data set, use \ref rescaleDataRange. \see QCPColorScale::setDataRange */ void QCPColorMap::setDataRange(const QCPRange &dataRange) { if (!QCPRange::validRange(dataRange)) return; if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) { if (mDataScaleType == QCPAxis::stLogarithmic) mDataRange = dataRange.sanitizedForLogScale(); else mDataRange = dataRange.sanitizedForLinScale(); mMapImageInvalidated = true; emit dataRangeChanged(mDataRange); } } /*! Sets whether the data is correlated with the color gradient linearly or logarithmically. \see QCPColorScale::setDataScaleType */ void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) { if (mDataScaleType != scaleType) { mDataScaleType = scaleType; mMapImageInvalidated = true; emit dataScaleTypeChanged(mDataScaleType); if (mDataScaleType == QCPAxis::stLogarithmic) setDataRange(mDataRange.sanitizedForLogScale()); } } /*! Sets the color gradient that is used to represent the data. For more details on how to create an own gradient or use one of the preset gradients, see \ref QCPColorGradient. The colors defined by the gradient will be used to represent data values in the currently set data range, see \ref setDataRange. Data points that are outside this data range will either be colored uniformly with the respective gradient boundary color, or the gradient will repeat, depending on \ref QCPColorGradient::setPeriodic. \see QCPColorScale::setGradient */ void QCPColorMap::setGradient(const QCPColorGradient &gradient) { if (mGradient != gradient) { mGradient = gradient; mMapImageInvalidated = true; emit gradientChanged(mGradient); } } /*! Sets whether the color map image shall use bicubic interpolation when displaying the color map shrinked or expanded, and not at a 1:1 pixel-to-data scale. \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" */ void QCPColorMap::setInterpolate(bool enabled) { mInterpolate = enabled; } /*! Sets whether the outer most data rows and columns are clipped to the specified key and value range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). if \a enabled is set to false, the data points at the border of the color map are drawn with the same width and height as all other data points. Since the data points are represented by rectangles of one color centered on the data coordinate, this means that the shown color map extends by half a data point over the specified key/value range in each direction. \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" */ void QCPColorMap::setTightBoundary(bool enabled) { mTightBoundary = enabled; } /*! Associates the color scale \a colorScale with this color map. This means that both the color scale and the color map synchronize their gradient, data range and data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps can be associated with one single color scale. This causes the color maps to also synchronize those properties, via the mutual color scale. This function causes the color map to adopt the current color gradient, data range and data scale type of \a colorScale. After this call, you may change these properties at either the color map or the color scale, and the setting will be applied to both. Pass 0 as \a colorScale to disconnect the color scale from this color map again. */ void QCPColorMap::setColorScale(QCPColorScale *colorScale) { if (mColorScale) // unconnect signals from old color scale { disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } mColorScale = colorScale; if (mColorScale) // connect signals to new color scale { setGradient(mColorScale.data()->gradient()); setDataRange(mColorScale.data()->dataRange()); setDataScaleType(mColorScale.data()->dataScaleType()); connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); } } /*! Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, only for the third data dimension of the color map. The minimum and maximum values of the data set are buffered in the internal QCPColorMapData instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For performance reasons, however, they are only updated in an expanding fashion. So the buffered maximum can only increase and the buffered minimum can only decrease. In consequence, changes to the data that actually lower the maximum of the data set (by overwriting the cell holding the current maximum with a smaller value), aren't recognized and the buffered maximum overestimates the true maximum of the data set. The same happens for the buffered minimum. To recalculate the true minimum and maximum by explicitly looking at each cell, the method QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a recalculateDataBounds calls this method before setting the data range to the buffered minimum and maximum. \see setDataRange */ void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) { if (recalculateDataBounds) mMapData->recalculateDataBounds(); setDataRange(mMapData->dataBounds()); } /*! Takes the current appearance of the color map and updates the legend icon, which is used to represent this color map in the legend (see \ref QCPLegend). The \a transformMode specifies whether the rescaling is done by a faster, low quality image scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm (Qt::SmoothTransformation). The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured legend icon size, the thumb will be rescaled during drawing of the legend item. \see setDataRange */ void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) { if (mMapImage.isNull() && !data()->isEmpty()) updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again { bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); } } /*! Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also resizes the map to 0x0 cells. */ void QCPColorMap::clearData() { mMapData->clear(); } /* inherits documentation from base class */ double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) { double posKey, posValue; pixelsToCoords(pos, posKey, posValue); if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue)) return mParentPlot->selectionTolerance()*0.99; } return -1; } /*! \internal Updates the internal map image buffer by going through the internal \ref QCPColorMapData and turning the data values into color pixels with \ref QCPColorGradient::colorize. This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image has been invalidated for a different reason (e.g. a change of the data range with \ref setDataRange). */ void QCPColorMap::updateMapImage() { QCPAxis *keyAxis = mKeyAxis.data(); if (!keyAxis) return; // resize mMapImage to correct dimensions, according to key/value axes orientation: if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.size().width() != mMapData->keySize() || mMapImage.size().height() != mMapData->valueSize())) mMapImage = QImage(QSize(mMapData->keySize(), mMapData->valueSize()), QImage::Format_RGB32); else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.size().width() != mMapData->valueSize() || mMapImage.size().height() != mMapData->keySize())) mMapImage = QImage(QSize(mMapData->valueSize(), mMapData->keySize()), QImage::Format_RGB32); const int keySize = mMapData->keySize(); const int valueSize = mMapData->valueSize(); const double *rawData = mMapData->mData; if (keyAxis->orientation() == Qt::Horizontal) { const int lineCount = valueSize; const int rowCount = keySize; for (int line=0; line(mMapImage.scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); } } else // keyAxis->orientation() == Qt::Vertical { const int lineCount = keySize; const int rowCount = valueSize; for (int line=0; line(mMapImage.scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); } } mMapData->mDataModified = false; mMapImageInvalidated = false; } /* inherits documentation from base class */ void QCPColorMap::draw(QCPPainter *painter) { if (mMapData->isEmpty()) return; if (!mKeyAxis || !mValueAxis) return; applyDefaultAntialiasingHint(painter); if (mMapData->mDataModified || mMapImageInvalidated) updateMapImage(); double halfSampleKey = 0; double halfSampleValue = 0; if (mMapData->keySize() > 1) halfSampleKey = 0.5*mMapData->keyRange().size()/(double)(mMapData->keySize()-1); if (mMapData->valueSize() > 1) halfSampleValue = 0.5*mMapData->valueRange().size()/(double)(mMapData->valueSize()-1); QRectF imageRect(coordsToPixels(mMapData->keyRange().lower-halfSampleKey, mMapData->valueRange().lower-halfSampleValue), coordsToPixels(mMapData->keyRange().upper+halfSampleKey, mMapData->valueRange().upper+halfSampleValue)); imageRect = imageRect.normalized(); bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); bool smoothBackup = painter->renderHints().testFlag(QPainter::SmoothPixmapTransform); painter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); QRegion clipBackup; if (mTightBoundary) { clipBackup = painter->clipRegion(); painter->setClipRect(QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(), Qt::IntersectClip); } painter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); if (mTightBoundary) painter->setClipRegion(clipBackup); painter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); } /* inherits documentation from base class */ void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const { applyDefaultAntialiasingHint(painter); // draw map thumbnail: if (!mLegendIcon.isNull()) { QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); iconRect.moveCenter(rect.center()); painter->drawPixmap(iconRect.topLeft(), scaledIcon); } /* // draw frame: painter->setBrush(Qt::NoBrush); painter->setPen(Qt::black); painter->drawRect(rect.adjusted(1, 1, 0, 0)); */ } /* inherits documentation from base class */ QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const { foundRange = true; QCPRange result = mMapData->keyRange(); result.normalize(); if (inSignDomain == QCPAbstractPlottable::sdPositive) { if (result.lower <= 0 && result.upper > 0) result.lower = result.upper*1e-3; else if (result.lower <= 0 && result.upper <= 0) foundRange = false; } else if (inSignDomain == QCPAbstractPlottable::sdNegative) { if (result.upper >= 0 && result.lower < 0) result.upper = result.lower*1e-3; else if (result.upper >= 0 && result.lower >= 0) foundRange = false; } return result; } /* inherits documentation from base class */ QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const { foundRange = true; QCPRange result = mMapData->valueRange(); result.normalize(); if (inSignDomain == QCPAbstractPlottable::sdPositive) { if (result.lower <= 0 && result.upper > 0) result.lower = result.upper*1e-3; else if (result.lower <= 0 && result.upper <= 0) foundRange = false; } else if (inSignDomain == QCPAbstractPlottable::sdNegative) { if (result.upper >= 0 && result.lower < 0) result.upper = result.lower*1e-3; else if (result.upper >= 0 && result.lower >= 0) foundRange = false; } return result; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemStraightLine //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemStraightLine \brief A straight line that spans infinitely in both directions \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a point1 and \a point2, which define the straight line. */ /*! Creates a straight line item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), point1(createPosition("point1")), point2(createPosition("point2")) { point1->setCoords(0, 0); point2->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemStraightLine::~QCPItemStraightLine() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemStraightLine::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemStraightLine::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos)); } /* inherits documentation from base class */ void QCPItemStraightLine::draw(QCPPainter *painter) { QVector2D start(point1->pixelPoint()); QVector2D end(point2->pixelPoint()); // get visible segment of straight line inside clipRect: double clipPad = mainPen().widthF(); QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); // paint visible segment, if existent: if (!line.isNull()) { painter->setPen(mainPen()); painter->drawLine(line); } } /*! \internal finds the shortest distance of \a point to the straight line defined by the base point \a base and the direction vector \a vec. This is a helper function for \ref selectTest. */ double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const { return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length(); } /*! \internal Returns the section of the straight line defined by \a base and direction vector \a vec, that is visible in the specified \a rect. This is a helper function for \ref draw. */ QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const { double bx, by; double gamma; QLineF result; if (vec.x() == 0 && vec.y() == 0) return result; if (qFuzzyIsNull(vec.x())) // line is vertical { // check top of rect: bx = rect.left(); by = rect.top(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical } else if (qFuzzyIsNull(vec.y())) // line is horizontal { // check left of rect: bx = rect.left(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal } else // line is skewed { QList pointVectors; // check top of rect: bx = rect.left(); by = rect.top(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); // check bottom of rect: bx = rect.left(); by = rect.bottom(); gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); // check left of rect: bx = rect.left(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); // check right of rect: bx = rect.right(); by = rect.top(); gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); // evaluate points: if (pointVectors.size() == 2) { result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); } else if (pointVectors.size() > 2) { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; QVector2D pv1, pv2; for (int i=0; i distSqrMax) { pv1 = pointVectors.at(i); pv2 = pointVectors.at(k); distSqrMax = distSqr; } } } result.setPoints(pv1.toPointF(), pv2.toPointF()); } } return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemStraightLine::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemLine //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemLine \brief A line from one point to another \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a start and \a end, which define the end points of the line. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. */ /*! Creates a line item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), start(createPosition("start")), end(createPosition("end")) { start->setCoords(0, 0); end->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemLine::~QCPItemLine() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemLine::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemLine::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode \see setTail */ void QCPItemLine::setHead(const QCPLineEnding &head) { mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode \see setHead */ void QCPItemLine::setTail(const QCPLineEnding &tail) { mTail = tail; } /* inherits documentation from base class */ double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos)); } /* inherits documentation from base class */ void QCPItemLine::draw(QCPPainter *painter) { QVector2D startVec(start->pixelPoint()); QVector2D endVec(end->pixelPoint()); if (startVec.toPoint() == endVec.toPoint()) return; // get visible segment of straight line inside clipRect: double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance()); clipPad = qMax(clipPad, (double)mainPen().widthF()); QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); // paint visible segment, if existent: if (!line.isNull()) { painter->setPen(mainPen()); painter->drawLine(line); painter->setBrush(Qt::SolidPattern); if (mTail.style() != QCPLineEnding::esNone) mTail.draw(painter, startVec, startVec-endVec); if (mHead.style() != QCPLineEnding::esNone) mHead.draw(painter, endVec, endVec-startVec); } } /*! \internal Returns the section of the line defined by \a start and \a end, that is visible in the specified \a rect. This is a helper function for \ref draw. */ QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const { bool containsStart = rect.contains(start.x(), start.y()); bool containsEnd = rect.contains(end.x(), end.y()); if (containsStart && containsEnd) return QLineF(start.toPointF(), end.toPointF()); QVector2D base = start; QVector2D vec = end-start; double bx, by; double gamma, mu; QLineF result; QList pointVectors; if (!qFuzzyIsNull(vec.y())) // line is not horizontal { // check top of rect: bx = rect.left(); by = rect.top(); mu = (by-base.y())/vec.y(); if (mu >= 0 && mu <= 1) { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); } // check bottom of rect: bx = rect.left(); by = rect.bottom(); mu = (by-base.y())/vec.y(); if (mu >= 0 && mu <= 1) { gamma = base.x()-bx + mu*vec.x(); if (gamma >= 0 && gamma <= rect.width()) pointVectors.append(QVector2D(bx+gamma, by)); } } if (!qFuzzyIsNull(vec.x())) // line is not vertical { // check left of rect: bx = rect.left(); by = rect.top(); mu = (bx-base.x())/vec.x(); if (mu >= 0 && mu <= 1) { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); } // check right of rect: bx = rect.right(); by = rect.top(); mu = (bx-base.x())/vec.x(); if (mu >= 0 && mu <= 1) { gamma = base.y()-by + mu*vec.y(); if (gamma >= 0 && gamma <= rect.height()) pointVectors.append(QVector2D(bx, by+gamma)); } } if (containsStart) pointVectors.append(start); if (containsEnd) pointVectors.append(end); // evaluate points: if (pointVectors.size() == 2) { result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); } else if (pointVectors.size() > 2) { // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: double distSqrMax = 0; QVector2D pv1, pv2; for (int i=0; i distSqrMax) { pv1 = pointVectors.at(i); pv2 = pointVectors.at(k); distSqrMax = distSqr; } } } result.setPoints(pv1.toPointF(), pv2.toPointF()); } return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemLine::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemCurve //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemCurve \brief A curved line from one point to another \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions." It has four positions, \a start and \a end, which define the end points of the line, and two control points which define the direction the line exits from the start and the direction from which it approaches the end: \a startDir and \a endDir. With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. Often it is desirable for the control points to stay at fixed relative positions to the start/end point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. */ /*! Creates a curve item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), start(createPosition("start")), startDir(createPosition("startDir")), endDir(createPosition("endDir")), end(createPosition("end")) { start->setCoords(0, 0); startDir->setCoords(0.5, 0); endDir->setCoords(0, 0.5); end->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); } QCPItemCurve::~QCPItemCurve() { } /*! Sets the pen that will be used to draw the line \see setSelectedPen */ void QCPItemCurve::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line when selected \see setPen, setSelected */ void QCPItemCurve::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the line ending style of the head. The head corresponds to the \a end position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode \see setTail */ void QCPItemCurve::setHead(const QCPLineEnding &head) { mHead = head; } /*! Sets the line ending style of the tail. The tail corresponds to the \a start position. Note that due to the overloaded QCPLineEnding constructor, you may directly specify a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode \see setHead */ void QCPItemCurve::setTail(const QCPLineEnding &tail) { mTail = tail; } /* inherits documentation from base class */ double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QPointF startVec(start->pixelPoint()); QPointF startDirVec(startDir->pixelPoint()); QPointF endDirVec(endDir->pixelPoint()); QPointF endVec(end->pixelPoint()); QPainterPath cubicPath(startVec); cubicPath.cubicTo(startDirVec, endDirVec, endVec); QPolygonF polygon = cubicPath.toSubpathPolygons().first(); double minDistSqr = std::numeric_limits::max(); for (int i=1; ipixelPoint()); QPointF startDirVec(startDir->pixelPoint()); QPointF endDirVec(endDir->pixelPoint()); QPointF endVec(end->pixelPoint()); if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash return; QPainterPath cubicPath(startVec); cubicPath.cubicTo(startDirVec, endDirVec, endVec); // paint visible segment, if existent: QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); QRect cubicRect = cubicPath.controlPointRect().toRect(); if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position cubicRect.adjust(0, 0, 1, 1); if (clip.intersects(cubicRect)) { painter->setPen(mainPen()); painter->drawPath(cubicPath); painter->setBrush(Qt::SolidPattern); if (mTail.style() != QCPLineEnding::esNone) mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); if (mHead.style() != QCPLineEnding::esNone) mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI); } } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemCurve::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemRect //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemRect \brief A rectangle \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rectangle. */ /*! Creates a rectangle item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition("topLeft")), bottomRight(createPosition("bottomRight")), top(createAnchor("top", aiTop)), topRight(createAnchor("topRight", aiTopRight)), right(createAnchor("right", aiRight)), bottom(createAnchor("bottom", aiBottom)), bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), left(createAnchor("left", aiLeft)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue,2)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } QCPItemRect::~QCPItemRect() { } /*! Sets the pen that will be used to draw the line of the rectangle \see setSelectedPen, setBrush */ void QCPItemRect::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the rectangle when selected \see setPen, setSelected */ void QCPItemRect::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen */ void QCPItemRect::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemRect::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; return rectSelectTest(rect, pos, filledRect); } /* inherits documentation from base class */ void QCPItemRect::draw(QCPPainter *painter) { QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); if (p1.toPoint() == p2.toPoint()) return; QRectF rect = QRectF(p1, p2).normalized(); double clipPad = mainPen().widthF(); QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect { painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(rect); } } /* inherits documentation from base class */ QPointF QCPItemRect::anchorPixelPoint(int anchorId) const { QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); switch (anchorId) { case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRight: return rect.topRight(); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeft: return rect.bottomLeft(); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemRect::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemRect::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemText //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemText \brief A text label \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions." Its position is defined by the member \a position and the setting of \ref setPositionAlignment. The latter controls which part of the text rect shall be aligned with \a position. The text alignment itself (i.e. left, center, right) can be controlled with \ref setTextAlignment. The text may be rotated around the \a position point with \ref setRotation. */ /*! Creates a text item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemText::QCPItemText(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), position(createPosition("position")), topLeft(createAnchor("topLeft", aiTopLeft)), top(createAnchor("top", aiTop)), topRight(createAnchor("topRight", aiTopRight)), right(createAnchor("right", aiRight)), bottomRight(createAnchor("bottomRight", aiBottomRight)), bottom(createAnchor("bottom", aiBottom)), bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), left(createAnchor("left", aiLeft)) { position->setCoords(0, 0); setRotation(0); setTextAlignment(Qt::AlignTop|Qt::AlignHCenter); setPositionAlignment(Qt::AlignCenter); setText("text"); setPen(Qt::NoPen); setSelectedPen(Qt::NoPen); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); setColor(Qt::black); setSelectedColor(Qt::blue); } QCPItemText::~QCPItemText() { } /*! Sets the color of the text. */ void QCPItemText::setColor(const QColor &color) { mColor = color; } /*! Sets the color of the text that will be used when the item is selected. */ void QCPItemText::setSelectedColor(const QColor &color) { mSelectedColor = color; } /*! Sets the pen that will be used do draw a rectangular border around the text. To disable the border, set \a pen to Qt::NoPen. \see setSelectedPen, setBrush, setPadding */ void QCPItemText::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used do draw a rectangular border around the text, when the item is selected. To disable the border, set \a pen to Qt::NoPen. \see setPen */ void QCPItemText::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used do fill the background of the text. To disable the background, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen, setPadding */ void QCPItemText::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the background, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemText::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the font of the text. \see setSelectedFont, setColor */ void QCPItemText::setFont(const QFont &font) { mFont = font; } /*! Sets the font of the text that will be used when the item is selected. \see setFont */ void QCPItemText::setSelectedFont(const QFont &font) { mSelectedFont = font; } /*! Sets the text that will be displayed. Multi-line texts are supported by inserting a line break character, e.g. '\n'. \see setFont, setColor, setTextAlignment */ void QCPItemText::setText(const QString &text) { mText = text; } /*! Sets which point of the text rect shall be aligned with \a position. Examples: \li If \a alignment is Qt::AlignHCenter | Qt::AlignTop, the text will be positioned such that the top of the text rect will be horizontally centered on \a position. \li If \a alignment is Qt::AlignLeft | Qt::AlignBottom, \a position will indicate the bottom left corner of the text rect. If you want to control the alignment of (multi-lined) text within the text rect, use \ref setTextAlignment. */ void QCPItemText::setPositionAlignment(Qt::Alignment alignment) { mPositionAlignment = alignment; } /*! Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight). */ void QCPItemText::setTextAlignment(Qt::Alignment alignment) { mTextAlignment = alignment; } /*! Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated around \a position. */ void QCPItemText::setRotation(double degrees) { mRotation = degrees; } /*! Sets the distance between the border of the text rectangle and the text. The appearance (and visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush. */ void QCPItemText::setPadding(const QMargins &padding) { mPadding = padding; } /* inherits documentation from base class */ double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; // The rect may be rotated, so we transform the actual clicked pos to the rotated // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects: QPointF positionPixels(position->pixelPoint()); QTransform inputTransform; inputTransform.translate(positionPixels.x(), positionPixels.y()); inputTransform.rotate(-mRotation); inputTransform.translate(-positionPixels.x(), -positionPixels.y()); QPointF rotatedPos = inputTransform.map(pos); QFontMetrics fontMetrics(mFont); QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); textBoxRect.moveTopLeft(textPos.toPoint()); return rectSelectTest(textBoxRect, rotatedPos, true); } /* inherits documentation from base class */ void QCPItemText::draw(QCPPainter *painter) { QPointF pos(position->pixelPoint()); QTransform transform = painter->transform(); transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) transform.rotate(mRotation); painter->setFont(mainFont()); QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); textBoxRect.moveTopLeft(textPos.toPoint()); double clipPad = mainPen().widthF(); QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) { painter->setTransform(transform); if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) { painter->setPen(mainPen()); painter->setBrush(mainBrush()); painter->drawRect(textBoxRect); } painter->setBrush(Qt::NoBrush); painter->setPen(QPen(mainColor())); painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); } } /* inherits documentation from base class */ QPointF QCPItemText::anchorPixelPoint(int anchorId) const { // get actual rect points (pretty much copied from draw function): QPointF pos(position->pixelPoint()); QTransform transform; transform.translate(pos.x(), pos.y()); if (!qFuzzyIsNull(mRotation)) transform.rotate(mRotation); QFontMetrics fontMetrics(mainFont()); QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation textBoxRect.moveTopLeft(textPos.toPoint()); QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); switch (anchorId) { case aiTopLeft: return rectPoly.at(0); case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; case aiTopRight: return rectPoly.at(1); case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; case aiBottomRight: return rectPoly.at(2); case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; case aiBottomLeft: return rectPoly.at(3); case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the point that must be given to the QPainter::drawText function (which expects the top left point of the text rect), according to the position \a pos, the text bounding box \a rect and the requested \a positionAlignment. For example, if \a positionAlignment is Qt::AlignLeft | Qt::AlignBottom the returned point will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally drawn at that point, the lower left corner of the resulting text rect is at \a pos. */ QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const { if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) return pos; QPointF result = pos; // start at top left if (positionAlignment.testFlag(Qt::AlignHCenter)) result.rx() -= rect.width()/2.0; else if (positionAlignment.testFlag(Qt::AlignRight)) result.rx() -= rect.width(); if (positionAlignment.testFlag(Qt::AlignVCenter)) result.ry() -= rect.height()/2.0; else if (positionAlignment.testFlag(Qt::AlignBottom)) result.ry() -= rect.height(); return result; } /*! \internal Returns the font that should be used for drawing text. Returns mFont when the item is not selected and mSelectedFont when it is. */ QFont QCPItemText::mainFont() const { return mSelected ? mSelectedFont : mFont; } /*! \internal Returns the color that should be used for drawing text. Returns mColor when the item is not selected and mSelectedColor when it is. */ QColor QCPItemText::mainColor() const { return mSelected ? mSelectedColor : mColor; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemText::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemText::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemEllipse //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemEllipse \brief An ellipse \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in. */ /*! Creates an ellipse item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition("topLeft")), bottomRight(createPosition("bottomRight")), topLeftRim(createAnchor("topLeftRim", aiTopLeftRim)), top(createAnchor("top", aiTop)), topRightRim(createAnchor("topRightRim", aiTopRightRim)), right(createAnchor("right", aiRight)), bottomRightRim(createAnchor("bottomRightRim", aiBottomRightRim)), bottom(createAnchor("bottom", aiBottom)), bottomLeftRim(createAnchor("bottomLeftRim", aiBottomLeftRim)), left(createAnchor("left", aiLeft)), center(createAnchor("center", aiCenter)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); } QCPItemEllipse::~QCPItemEllipse() { } /*! Sets the pen that will be used to draw the line of the ellipse \see setSelectedPen, setBrush */ void QCPItemEllipse::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the ellipse when selected \see setPen, setSelected */ void QCPItemEllipse::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to Qt::NoBrush. \see setSelectedBrush, setPen */ void QCPItemEllipse::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a brush to Qt::NoBrush. \see setBrush */ void QCPItemEllipse::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /* inherits documentation from base class */ double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; double result = -1; QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); QPointF center((p1+p2)/2.0); double a = qAbs(p1.x()-p2.x())/2.0; double b = qAbs(p1.y()-p2.y())/2.0; double x = pos.x()-center.x(); double y = pos.y()-center.y(); // distance to border: double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); result = qAbs(c-1)*qSqrt(x*x+y*y); // filled ellipse, allow click inside to count as hit: if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { if (x*x/(a*a) + y*y/(b*b) <= 1) result = mParentPlot->selectionTolerance()*0.99; } return result; } /* inherits documentation from base class */ void QCPItemEllipse::draw(QCPPainter *painter) { QPointF p1 = topLeft->pixelPoint(); QPointF p2 = bottomRight->pixelPoint(); if (p1.toPoint() == p2.toPoint()) return; QRectF ellipseRect = QRectF(p1, p2).normalized(); QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect { painter->setPen(mainPen()); painter->setBrush(mainBrush()); #ifdef __EXCEPTIONS try // drawEllipse sometimes throws exceptions if ellipse is too big { #endif painter->drawEllipse(ellipseRect); #ifdef __EXCEPTIONS } catch (...) { qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; setVisible(false); } #endif } } /* inherits documentation from base class */ QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const { QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); switch (anchorId) { case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemEllipse::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemEllipse::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemPixmap //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemPixmap \brief An arbitrary pixmap \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to fit the rectangle or be drawn aligned to the topLeft position. If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown on the right side of the example image), the pixmap will be flipped in the respective orientations. */ /*! Creates a rectangle item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), topLeft(createPosition("topLeft")), bottomRight(createPosition("bottomRight")), top(createAnchor("top", aiTop)), topRight(createAnchor("topRight", aiTopRight)), right(createAnchor("right", aiRight)), bottom(createAnchor("bottom", aiBottom)), bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), left(createAnchor("left", aiLeft)) { topLeft->setCoords(0, 1); bottomRight->setCoords(1, 0); setPen(Qt::NoPen); setSelectedPen(QPen(Qt::blue)); setScaled(false, Qt::KeepAspectRatio); } QCPItemPixmap::~QCPItemPixmap() { } /*! Sets the pixmap that will be displayed. */ void QCPItemPixmap::setPixmap(const QPixmap &pixmap) { mPixmap = pixmap; if (mPixmap.isNull()) qDebug() << Q_FUNC_INFO << "pixmap is null"; } /*! Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a bottomRight positions. */ void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode) { mScaled = scaled; mAspectRatioMode = aspectRatioMode; updateScaledPixmap(); } /*! Sets the pen that will be used to draw a border around the pixmap. \see setSelectedPen, setBrush */ void QCPItemPixmap::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw a border around the pixmap when selected \see setPen, setSelected */ void QCPItemPixmap::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /* inherits documentation from base class */ double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; return rectSelectTest(getFinalRect(), pos, true); } /* inherits documentation from base class */ void QCPItemPixmap::draw(QCPPainter *painter) { bool flipHorz = false; bool flipVert = false; QRect rect = getFinalRect(&flipHorz, &flipVert); double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); if (boundingRect.intersects(clipRect())) { updateScaledPixmap(rect, flipHorz, flipVert); painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); QPen pen = mainPen(); if (pen.style() != Qt::NoPen) { painter->setPen(pen); painter->setBrush(Qt::NoBrush); painter->drawRect(rect); } } } /* inherits documentation from base class */ QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const { bool flipHorz; bool flipVert; QRect rect = getFinalRect(&flipHorz, &flipVert); // we actually want denormal rects (negative width/height) here, so restore // the flipped state: if (flipHorz) rect.adjust(rect.width(), 0, -rect.width(), 0); if (flipVert) rect.adjust(0, rect.height(), 0, -rect.height()); switch (anchorId) { case aiTop: return (rect.topLeft()+rect.topRight())*0.5; case aiTopRight: return rect.topRight(); case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; case aiBottomLeft: return rect.bottomLeft(); case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;; } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a bottomRight.) This function only creates the scaled pixmap when the buffered pixmap has a different size than the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does not cause expensive rescaling every time. If scaling is disabled, sets mScaledPixmap to a null QPixmap. */ void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) { if (mPixmap.isNull()) return; if (mScaled) { if (finalRect.isNull()) finalRect = getFinalRect(&flipHorz, &flipVert); if (finalRect.size() != mScaledPixmap.size()) { mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation); if (flipHorz || flipVert) mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); } } else if (!mScaledPixmap.isNull()) mScaledPixmap = QPixmap(); } /*! \internal Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions and scaling settings. The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn flipped horizontally or vertically in the returned rect. (The returned rect itself is always normalized, i.e. the top left corner of the rect is actually further to the top/left than the bottom right corner). This is the case when the item position \a topLeft is further to the bottom/right than \a bottomRight. If scaling is disabled, returns a rect with size of the original pixmap and the top left corner aligned with the item position \a topLeft. The position \a bottomRight is ignored. */ QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const { QRect result; bool flipHorz = false; bool flipVert = false; QPoint p1 = topLeft->pixelPoint().toPoint(); QPoint p2 = bottomRight->pixelPoint().toPoint(); if (p1 == p2) return QRect(p1, QSize(0, 0)); if (mScaled) { QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); QPoint topLeft = p1; if (newSize.width() < 0) { flipHorz = true; newSize.rwidth() *= -1; topLeft.setX(p2.x()); } if (newSize.height() < 0) { flipVert = true; newSize.rheight() *= -1; topLeft.setY(p2.y()); } QSize scaledSize = mPixmap.size(); scaledSize.scale(newSize, mAspectRatioMode); result = QRect(topLeft, scaledSize); } else { result = QRect(p1, mPixmap.size()); } if (flippedHorz) *flippedHorz = flipHorz; if (flippedVert) *flippedVert = flipVert; return result; } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemPixmap::mainPen() const { return mSelected ? mSelectedPen : mPen; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemTracer //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemTracer \brief Item that sticks to QCPGraph data points \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions." The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt the coordinate axes of the graph and update its \a position to be on the graph's data. This means the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a position will have no effect because they will be overriden in the next redraw (this is when the coordinate update happens). If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will stay at the corresponding end of the graph. With \ref setInterpolating you may specify whether the tracer may only stay exactly on data points or whether it interpolates data points linearly, if given a key that lies between two data points of the graph. The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer have no own visual appearance (set the style to \ref tsNone), and just connect other item positions to the tracer \a position (used as an anchor) via \ref QCPItemPosition::setParentAnchor. \note The tracer position is only automatically updated upon redraws. So when the data of the graph changes and immediately afterwards (without a redraw) the a position coordinates of the tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref updatePosition must be called manually, prior to reading the tracer coordinates. */ /*! Creates a tracer item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), position(createPosition("position")), mGraph(0) { position->setCoords(0, 0); setBrush(Qt::NoBrush); setSelectedBrush(Qt::NoBrush); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setStyle(tsCrosshair); setSize(6); setInterpolating(false); setGraphKey(0); } QCPItemTracer::~QCPItemTracer() { } /*! Sets the pen that will be used to draw the line of the tracer \see setSelectedPen, setBrush */ void QCPItemTracer::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the line of the tracer when selected \see setPen, setSelected */ void QCPItemTracer::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the brush that will be used to draw any fills of the tracer \see setSelectedBrush, setPen */ void QCPItemTracer::setBrush(const QBrush &brush) { mBrush = brush; } /*! Sets the brush that will be used to draw any fills of the tracer, when selected. \see setBrush, setSelected */ void QCPItemTracer::setSelectedBrush(const QBrush &brush) { mSelectedBrush = brush; } /*! Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare does, \ref tsCrosshair does not). */ void QCPItemTracer::setSize(double size) { mSize = size; } /*! Sets the style/visual appearance of the tracer. If you only want to use the tracer \a position as an anchor for other items, set \a style to \ref tsNone. */ void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) { mStyle = style; } /*! Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed freely like any other item position. This is the state the tracer will assume when its graph gets deleted while still attached to it. \see setGraphKey */ void QCPItemTracer::setGraph(QCPGraph *graph) { if (graph) { if (graph->parentPlot() == mParentPlot) { position->setType(QCPItemPosition::ptPlotCoords); position->setAxes(graph->keyAxis(), graph->valueAxis()); mGraph = graph; updatePosition(); } else qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; } else { mGraph = 0; } } /*! Sets the key of the graph's data point the tracer will be positioned at. This is the only free coordinate of a tracer when attached to a graph. Depending on \ref setInterpolating, the tracer will be either positioned on the data point closest to \a key, or will stay exactly at \a key and interpolate the value linearly. \see setGraph, setInterpolating */ void QCPItemTracer::setGraphKey(double key) { mGraphKey = key; } /*! Sets whether the value of the graph's data points shall be interpolated, when positioning the tracer. If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on the data point of the graph which is closest to the key, but which is not necessarily exactly there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and the appropriate value will be interpolated from the graph's data points linearly. \see setGraph, setGraphKey */ void QCPItemTracer::setInterpolating(bool enabled) { mInterpolating = enabled; } /* inherits documentation from base class */ double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QPointF center(position->pixelPoint()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) { case tsNone: return -1; case tsPlus: { if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos), distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos))); break; } case tsCrosshair: { return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos), distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos))); } case tsCircle: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { // distance to border: double centerDist = QVector2D(center-pos).length(); double circleLine = w; double result = qAbs(centerDist-circleLine); // filled ellipse, allow click inside to count as hit: if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) { if (centerDist <= circleLine) result = mParentPlot->selectionTolerance()*0.99; } return result; } break; } case tsSquare: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; return rectSelectTest(rect, pos, filledRect); } break; } } return -1; } /* inherits documentation from base class */ void QCPItemTracer::draw(QCPPainter *painter) { updatePosition(); if (mStyle == tsNone) return; painter->setPen(mainPen()); painter->setBrush(mainBrush()); QPointF center(position->pixelPoint()); double w = mSize/2.0; QRect clip = clipRect(); switch (mStyle) { case tsNone: return; case tsPlus: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) { painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); } break; } case tsCrosshair: { if (center.y() > clip.top() && center.y() < clip.bottom()) painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); if (center.x() > clip.left() && center.x() < clip.right()) painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); break; } case tsCircle: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) painter->drawEllipse(center, w, w); break; } case tsSquare: { if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); break; } } } /*! If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a position to reside on the graph data, depending on the configured key (\ref setGraphKey). It is called automatically on every redraw and normally doesn't need to be called manually. One exception is when you want to read the tracer coordinates via \a position and are not sure that the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. In that situation, call this function before accessing \a position, to make sure you don't get out-of-date coordinates. If there is no graph set on this tracer, this function does nothing. */ void QCPItemTracer::updatePosition() { if (mGraph) { if (mParentPlot->hasPlottable(mGraph)) { if (mGraph->data()->size() > 1) { QCPDataMap::const_iterator first = mGraph->data()->constBegin(); QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1; if (mGraphKey < first.key()) position->setCoords(first.key(), first.value().value); else if (mGraphKey > last.key()) position->setCoords(last.key(), last.value().value); else { QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey); if (it != first) // mGraphKey is somewhere between iterators { QCPDataMap::const_iterator prevIt = it-1; if (mInterpolating) { // interpolate between iterators around mGraphKey: double slope = 0; if (!qFuzzyCompare((double)it.key(), (double)prevIt.key())) slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key()); position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value); } else { // find iterator with key closest to mGraphKey: if (mGraphKey < (prevIt.key()+it.key())*0.5) it = prevIt; position->setCoords(it.key(), it.value().value); } } else // mGraphKey is exactly on first iterator position->setCoords(it.key(), it.value().value); } } else if (mGraph->data()->size() == 1) { QCPDataMap::const_iterator it = mGraph->data()->constBegin(); position->setCoords(it.key(), it.value().value); } else qDebug() << Q_FUNC_INFO << "graph has no data"; } else qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; } } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemTracer::mainPen() const { return mSelected ? mSelectedPen : mPen; } /*! \internal Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item is not selected and mSelectedBrush when it is. */ QBrush QCPItemTracer::mainBrush() const { return mSelected ? mSelectedBrush : mBrush; } //////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////// QCPItemBracket //////////////////////////////////////////////////////////////////////////////////////////////////// /*! \class QCPItemBracket \brief A bracket for referencing/highlighting certain parts in the plot. \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions." It has two positions, \a left and \a right, which define the span of the bracket. If \a left is actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the example image. The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket stretches away from the embraced span, can be controlled with \ref setLength. \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine or QCPItemCurve) or a text label (QCPItemText), to the bracket. */ /*! Creates a bracket item and sets default values. The constructed item can be added to the plot with QCustomPlot::addItem. */ QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) : QCPAbstractItem(parentPlot), left(createPosition("left")), right(createPosition("right")), center(createAnchor("center", aiCenter)) { left->setCoords(0, 0); right->setCoords(1, 1); setPen(QPen(Qt::black)); setSelectedPen(QPen(Qt::blue, 2)); setLength(8); setStyle(bsCalligraphic); } QCPItemBracket::~QCPItemBracket() { } /*! Sets the pen that will be used to draw the bracket. Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use \ref setLength, which has a similar effect. \see setSelectedPen */ void QCPItemBracket::setPen(const QPen &pen) { mPen = pen; } /*! Sets the pen that will be used to draw the bracket when selected \see setPen, setSelected */ void QCPItemBracket::setSelectedPen(const QPen &pen) { mSelectedPen = pen; } /*! Sets the \a length in pixels how far the bracket extends in the direction towards the embraced span of the bracket (i.e. perpendicular to the left-right-direction) \image html QCPItemBracket-length.png
Demonstrating the effect of different values for \ref setLength, for styles \ref bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
*/ void QCPItemBracket::setLength(double length) { mLength = length; } /*! Sets the style of the bracket, i.e. the shape/visual appearance. \see setPen */ void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) { mStyle = style; } /* inherits documentation from base class */ double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const { Q_UNUSED(details) if (onlySelectable && !mSelectable) return -1; QVector2D leftVec(left->pixelPoint()); QVector2D rightVec(right->pixelPoint()); if (leftVec.toPoint() == rightVec.toPoint()) return -1; QVector2D widthVec = (rightVec-leftVec)*0.5f; QVector2D lengthVec(-widthVec.y(), widthVec.x()); lengthVec = lengthVec.normalized()*mLength; QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; return qSqrt(distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos)); } /* inherits documentation from base class */ void QCPItemBracket::draw(QCPPainter *painter) { QVector2D leftVec(left->pixelPoint()); QVector2D rightVec(right->pixelPoint()); if (leftVec.toPoint() == rightVec.toPoint()) return; QVector2D widthVec = (rightVec-leftVec)*0.5f; QVector2D lengthVec(-widthVec.y(), widthVec.x()); lengthVec = lengthVec.normalized()*mLength; QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; QPolygon boundingPoly; boundingPoly << leftVec.toPoint() << rightVec.toPoint() << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); if (clip.intersects(boundingPoly.boundingRect())) { painter->setPen(mainPen()); switch (mStyle) { case bsSquare: { painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); break; } case bsRound: { painter->setBrush(Qt::NoBrush); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } case bsCurly: { painter->setBrush(Qt::NoBrush); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } case bsCalligraphic: { painter->setPen(Qt::NoPen); painter->setBrush(QBrush(mainPen().color())); QPainterPath path; path.moveTo((centerVec+widthVec+lengthVec).toPointF()); path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF()); path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF()); path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); painter->drawPath(path); break; } } } } /* inherits documentation from base class */ QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const { QVector2D leftVec(left->pixelPoint()); QVector2D rightVec(right->pixelPoint()); if (leftVec.toPoint() == rightVec.toPoint()) return leftVec.toPointF(); QVector2D widthVec = (rightVec-leftVec)*0.5f; QVector2D lengthVec(-widthVec.y(), widthVec.x()); lengthVec = lengthVec.normalized()*mLength; QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; switch (anchorId) { case aiCenter: return centerVec.toPointF(); } qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; return QPointF(); } /*! \internal Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected and mSelectedPen when it is. */ QPen QCPItemBracket::mainPen() const { return mSelected ? mSelectedPen : mPen; } ================================================ FILE: DynamicAudioNormalizerGUI/src/3rd_party/qcustomplot.h ================================================ /*************************************************************************** ** ** ** QCustomPlot, an easy to use, modern plotting widget for Qt ** ** Copyright (C) 2011, 2012, 2013, 2014 Emanuel Eichhammer ** ** ** ** This program is free software: you can redistribute it and/or modify ** ** it under the terms of the GNU General Public License as published by ** ** the Free Software Foundation, either version 3 of the License, or ** ** (at your option) any later version. ** ** ** ** This program is distributed in the hope that it will be useful, ** ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** ** GNU General Public License 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/. ** ** ** **************************************************************************** ** Author: Emanuel Eichhammer ** ** Website/Contact: http://www.qcustomplot.com/ ** ** Date: 07.04.14 ** ** Version: 1.2.1 ** ****************************************************************************/ #ifndef QCUSTOMPLOT_H #define QCUSTOMPLOT_H #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) # include # include # include #else # include # include #endif class QCPPainter; class QCustomPlot; class QCPLayerable; class QCPLayoutElement; class QCPLayout; class QCPAxis; class QCPAxisRect; class QCPAxisPainterPrivate; class QCPAbstractPlottable; class QCPGraph; class QCPAbstractItem; class QCPItemPosition; class QCPLayer; class QCPPlotTitle; class QCPLegend; class QCPAbstractLegendItem; class QCPColorMap; class QCPColorScale; /*! \file */ // decl definitions for shared library compilation/usage: #if defined(QCUSTOMPLOT_COMPILE_LIBRARY) # define QCP_LIB_DECL Q_DECL_EXPORT #elif defined(QCUSTOMPLOT_USE_LIBRARY) # define QCP_LIB_DECL Q_DECL_IMPORT #else # define QCP_LIB_DECL #endif /*! The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library */ namespace QCP { /*! Defines the sides of a rectangular entity to which margins can be applied. \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins */ enum MarginSide { msLeft = 0x01 ///< 0x01 left margin ,msRight = 0x02 ///< 0x02 right margin ,msTop = 0x04 ///< 0x04 top margin ,msBottom = 0x08 ///< 0x08 bottom margin ,msAll = 0xFF ///< 0xFF all margins ,msNone = 0x00 ///< 0x00 no margin }; Q_DECLARE_FLAGS(MarginSides, MarginSide) /*! Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective element how it is drawn. Typically it provides a \a setAntialiased function for this. \c AntialiasedElements is a flag of or-combined elements of this enum type. \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements */ enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks ,aeGrid = 0x0002 ///< 0x0002 Grid lines ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines ,aeLegend = 0x0008 ///< 0x0008 Legend box ,aeLegendItems = 0x0010 ///< 0x0010 Legend items ,aePlottables = 0x0020 ///< 0x0020 Main lines of plottables (excluding error bars, see element \ref aeErrorBars) ,aeItems = 0x0040 ///< 0x0040 Main lines of items ,aeScatters = 0x0080 ///< 0x0080 Scatter symbols of plottables (excluding scatter symbols of type ssPixmap) ,aeErrorBars = 0x0100 ///< 0x0100 Error bars ,aeFills = 0x0200 ///< 0x0200 Borders of fills (e.g. under or between graphs) ,aeZeroLine = 0x0400 ///< 0x0400 Zero-lines, see \ref QCPGrid::setZeroLinePen ,aeAll = 0xFFFF ///< 0xFFFF All elements ,aeNone = 0x0000 ///< 0x0000 No elements }; Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) /*! Defines plotting hints that control various aspects of the quality and speed of plotting. \see QCustomPlot::setPlottingHints */ enum PlottingHint { phNone = 0x000 ///< 0x000 No hints are set ,phFastPolylines = 0x001 ///< 0x001 Graph/Curve lines are drawn with a faster method. This reduces the quality ///< especially of the line segment joins. (Only relevant for solid line pens.) ,phForceRepaint = 0x002 ///< 0x002 causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpHint. ///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse). ,phCacheLabels = 0x004 ///< 0x004 axis (tick) labels will be cached as pixmaps, increasing replot performance. }; Q_DECLARE_FLAGS(PlottingHints, PlottingHint) /*! Defines the mouse interactions possible with QCustomPlot. \c Interactions is a flag of or-combined elements of this enum type. \see QCustomPlot::setInteractions */ enum Interaction { iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) ,iSelectAxes = 0x010 ///< 0x010 Axes are selectable (or parts of them, see QCPAxis::setSelectableParts) ,iSelectLegend = 0x020 ///< 0x020 Legends are selectable (or their child items, see QCPLegend::setSelectableParts) ,iSelectItems = 0x040 ///< 0x040 Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem) ,iSelectOther = 0x080 ///< 0x080 All other objects are selectable (e.g. your own derived layerables, the plot title,...) }; Q_DECLARE_FLAGS(Interactions, Interaction) /*! \internal Returns whether the specified \a value is considered an invalid data value for plottables (i.e. is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. */ inline bool isInvalidData(double value) { return qIsNaN(value) || qIsInf(value); } /*! \internal \overload Checks two arguments instead of one. */ inline bool isInvalidData(double value1, double value2) { return isInvalidData(value1) || isInvalidData(value2); } /*! \internal Sets the specified \a side of \a margins to \a value \see getMarginValue */ inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) { switch (side) { case QCP::msLeft: margins.setLeft(value); break; case QCP::msRight: margins.setRight(value); break; case QCP::msTop: margins.setTop(value); break; case QCP::msBottom: margins.setBottom(value); break; case QCP::msAll: margins = QMargins(value, value, value, value); break; default: break; } } /*! \internal Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or \ref QCP::msAll, returns 0. \see setMarginValue */ inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) { switch (side) { case QCP::msLeft: return margins.left(); case QCP::msRight: return margins.right(); case QCP::msTop: return margins.top(); case QCP::msBottom: return margins.bottom(); default: break; } return 0; } } // end of namespace QCP Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides) Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) class QCP_LIB_DECL QCPScatterStyle { Q_GADGET public: /*! Defines the shape used for scatter points. On plottables/items that draw scatters, the sizes of these visualizations (with exception of \ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are drawn with the pen and brush specified with \ref setPen and \ref setBrush. */ Q_ENUMS(ScatterShape) enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines) ,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius) ,ssCross ///< \enumimage{ssCross.png} a cross ,ssPlus ///< \enumimage{ssPlus.png} a plus ,ssCircle ///< \enumimage{ssCircle.png} a circle ,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle) ,ssSquare ///< \enumimage{ssSquare.png} a square ,ssDiamond ///< \enumimage{ssDiamond.png} a diamond ,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus ,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline ,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner ,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside ,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside ,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside ,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside ,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines ,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates ,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath) }; QCPScatterStyle(); QCPScatterStyle(ScatterShape shape, double size=6); QCPScatterStyle(ScatterShape shape, const QColor &color, double size); QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size); QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size); QCPScatterStyle(const QPixmap &pixmap); QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6); // getters: double size() const { return mSize; } ScatterShape shape() const { return mShape; } QPen pen() const { return mPen; } QBrush brush() const { return mBrush; } QPixmap pixmap() const { return mPixmap; } QPainterPath customPath() const { return mCustomPath; } // setters: void setSize(double size); void setShape(ScatterShape shape); void setPen(const QPen &pen); void setBrush(const QBrush &brush); void setPixmap(const QPixmap &pixmap); void setCustomPath(const QPainterPath &customPath); // non-property methods: bool isNone() const { return mShape == ssNone; } bool isPenDefined() const { return mPenDefined; } void applyTo(QCPPainter *painter, const QPen &defaultPen) const; void drawShape(QCPPainter *painter, QPointF pos) const; void drawShape(QCPPainter *painter, double x, double y) const; protected: // property members: double mSize; ScatterShape mShape; QPen mPen; QBrush mBrush; QPixmap mPixmap; QPainterPath mCustomPath; // non-property members: bool mPenDefined; }; Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); class QCP_LIB_DECL QCPPainter : public QPainter { Q_GADGET public: /*! Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, depending on whether they are wanted on the respective output device. */ enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. ,pmNoCaching = 0x02 ///< 0x02 Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels ,pmNonCosmetic = 0x04 ///< 0x04 Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.) }; Q_FLAGS(PainterMode PainterModes) Q_DECLARE_FLAGS(PainterModes, PainterMode) QCPPainter(); QCPPainter(QPaintDevice *device); ~QCPPainter(); // getters: bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } PainterModes modes() const { return mModes; } // setters: void setAntialiasing(bool enabled); void setMode(PainterMode mode, bool enabled=true); void setModes(PainterModes modes); // methods hiding non-virtual base class functions (QPainter bug workarounds): bool begin(QPaintDevice *device); void setPen(const QPen &pen); void setPen(const QColor &color); void setPen(Qt::PenStyle penStyle); void drawLine(const QLineF &line); void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} void save(); void restore(); // non-virtual methods: void makeNonCosmetic(); protected: // property members: PainterModes mModes; bool mIsAntialiasing; // non-property members: QStack mAntialiasingStack; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) class QCP_LIB_DECL QCPLayer : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) Q_PROPERTY(QString name READ name) Q_PROPERTY(int index READ index) Q_PROPERTY(QList children READ children) Q_PROPERTY(bool visible READ visible WRITE setVisible) /// \endcond public: QCPLayer(QCustomPlot* parentPlot, const QString &layerName); ~QCPLayer(); // getters: QCustomPlot *parentPlot() const { return mParentPlot; } QString name() const { return mName; } int index() const { return mIndex; } QList children() const { return mChildren; } bool visible() const { return mVisible; } // setters: void setVisible(bool visible); protected: // property members: QCustomPlot *mParentPlot; QString mName; int mIndex; QList mChildren; bool mVisible; // non-virtual methods: void addChild(QCPLayerable *layerable, bool prepend); void removeChild(QCPLayerable *layerable); private: Q_DISABLE_COPY(QCPLayer) friend class QCustomPlot; friend class QCPLayerable; }; class QCP_LIB_DECL QCPLayerable : public QObject { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool visible READ visible WRITE setVisible) Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) /// \endcond public: QCPLayerable(QCustomPlot *plot, QString targetLayer="", QCPLayerable *parentLayerable=0); ~QCPLayerable(); // getters: bool visible() const { return mVisible; } QCustomPlot *parentPlot() const { return mParentPlot; } QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } QCPLayer *layer() const { return mLayer; } bool antialiased() const { return mAntialiased; } // setters: void setVisible(bool on); Q_SLOT bool setLayer(QCPLayer *layer); bool setLayer(const QString &layerName); void setAntialiased(bool enabled); // introduced virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-property methods: bool realVisibility() const; signals: void layerChanged(QCPLayer *newLayer); protected: // property members: bool mVisible; QCustomPlot *mParentPlot; QPointer mParentLayerable; QCPLayer *mLayer; bool mAntialiased; // introduced virtual methods: virtual void parentPlotInitialized(QCustomPlot *parentPlot); virtual QCP::Interaction selectionCategory() const; virtual QRect clipRect() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; virtual void draw(QCPPainter *painter) = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-property methods: void initializeParentPlot(QCustomPlot *parentPlot); void setParentLayerable(QCPLayerable* parentLayerable); bool moveToLayer(QCPLayer *layer, bool prepend); void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; private: Q_DISABLE_COPY(QCPLayerable) friend class QCustomPlot; friend class QCPAxisRect; }; class QCP_LIB_DECL QCPRange { public: double lower, upper; QCPRange(); QCPRange(double lower, double upper); bool operator==(const QCPRange& other) { return lower == other.lower && upper == other.upper; } bool operator!=(const QCPRange& other) { return !(*this == other); } QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } friend inline const QCPRange operator+(const QCPRange&, double); friend inline const QCPRange operator+(double, const QCPRange&); friend inline const QCPRange operator-(const QCPRange& range, double value); friend inline const QCPRange operator*(const QCPRange& range, double value); friend inline const QCPRange operator*(double value, const QCPRange& range); friend inline const QCPRange operator/(const QCPRange& range, double value); double size() const; double center() const; void normalize(); void expand(const QCPRange &otherRange); QCPRange expanded(const QCPRange &otherRange) const; QCPRange sanitizedForLogScale() const; QCPRange sanitizedForLinScale() const; bool contains(double value) const; static bool validRange(double lower, double upper); static bool validRange(const QCPRange &range); static const double minRange; //1e-280; static const double maxRange; //1e280; }; Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); /* documentation of inline functions */ /*! \fn QCPRange &QCPRange::operator+=(const double& value) Adds \a value to both boundaries of the range. */ /*! \fn QCPRange &QCPRange::operator-=(const double& value) Subtracts \a value from both boundaries of the range. */ /*! \fn QCPRange &QCPRange::operator*=(const double& value) Multiplies both boundaries of the range by \a value. */ /*! \fn QCPRange &QCPRange::operator/=(const double& value) Divides both boundaries of the range by \a value. */ /* end documentation of inline functions */ /*! Adds \a value to both boundaries of the range. */ inline const QCPRange operator+(const QCPRange& range, double value) { QCPRange result(range); result += value; return result; } /*! Adds \a value to both boundaries of the range. */ inline const QCPRange operator+(double value, const QCPRange& range) { QCPRange result(range); result += value; return result; } /*! Subtracts \a value from both boundaries of the range. */ inline const QCPRange operator-(const QCPRange& range, double value) { QCPRange result(range); result -= value; return result; } /*! Multiplies both boundaries of the range by \a value. */ inline const QCPRange operator*(const QCPRange& range, double value) { QCPRange result(range); result *= value; return result; } /*! Multiplies both boundaries of the range by \a value. */ inline const QCPRange operator*(double value, const QCPRange& range) { QCPRange result(range); result *= value; return result; } /*! Divides both boundaries of the range by \a value. */ inline const QCPRange operator/(const QCPRange& range, double value) { QCPRange result(range); result /= value; return result; } class QCP_LIB_DECL QCPMarginGroup : public QObject { Q_OBJECT public: QCPMarginGroup(QCustomPlot *parentPlot); ~QCPMarginGroup(); // non-virtual methods: QList elements(QCP::MarginSide side) const { return mChildren.value(side); } bool isEmpty() const; void clear(); protected: // non-property members: QCustomPlot *mParentPlot; QHash > mChildren; // non-virtual methods: int commonMargin(QCP::MarginSide side) const; void addChild(QCP::MarginSide side, QCPLayoutElement *element); void removeChild(QCP::MarginSide side, QCPLayoutElement *element); private: Q_DISABLE_COPY(QCPMarginGroup) friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLayout* layout READ layout) Q_PROPERTY(QRect rect READ rect) Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) Q_PROPERTY(QMargins margins READ margins WRITE setMargins) Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) /// \endcond public: /*! Defines the phases of the update process, that happens just before a replot. At each phase, \ref update is called with the according UpdatePhase value. */ enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout ,upMargins ///< Phase in which the margins are calculated and set ,upLayout ///< Final phase in which the layout system places the rects of the elements }; Q_ENUMS(UpdatePhase) explicit QCPLayoutElement(QCustomPlot *parentPlot=0); virtual ~QCPLayoutElement(); // getters: QCPLayout *layout() const { return mParentLayout; } QRect rect() const { return mRect; } QRect outerRect() const { return mOuterRect; } QMargins margins() const { return mMargins; } QMargins minimumMargins() const { return mMinimumMargins; } QCP::MarginSides autoMargins() const { return mAutoMargins; } QSize minimumSize() const { return mMinimumSize; } QSize maximumSize() const { return mMaximumSize; } QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, (QCPMarginGroup*)0); } QHash marginGroups() const { return mMarginGroups; } // setters: void setOuterRect(const QRect &rect); void setMargins(const QMargins &margins); void setMinimumMargins(const QMargins &margins); void setAutoMargins(QCP::MarginSides sides); void setMinimumSize(const QSize &size); void setMinimumSize(int width, int height); void setMaximumSize(const QSize &size); void setMaximumSize(int width, int height); void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); // introduced virtual methods: virtual void update(UpdatePhase phase); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; virtual QList elements(bool recursive) const; // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QCPLayout *mParentLayout; QSize mMinimumSize, mMaximumSize; QRect mRect, mOuterRect; QMargins mMargins, mMinimumMargins; QCP::MarginSides mAutoMargins; QHash mMarginGroups; // introduced virtual methods: virtual int calculateAutoMargin(QCP::MarginSide side); // events: virtual void mousePressEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void mouseMoveEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void mouseReleaseEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void mouseDoubleClickEvent(QMouseEvent *event) {Q_UNUSED(event)} virtual void wheelEvent(QWheelEvent *event) {Q_UNUSED(event)} // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const { Q_UNUSED(painter) } virtual void draw(QCPPainter *painter) { Q_UNUSED(painter) } virtual void parentPlotInitialized(QCustomPlot *parentPlot); private: Q_DISABLE_COPY(QCPLayoutElement) friend class QCustomPlot; friend class QCPLayout; friend class QCPMarginGroup; }; class QCP_LIB_DECL QCPLayout : public QCPLayoutElement { Q_OBJECT public: explicit QCPLayout(); // reimplemented virtual methods: virtual void update(UpdatePhase phase); virtual QList elements(bool recursive) const; // introduced virtual methods: virtual int elementCount() const = 0; virtual QCPLayoutElement* elementAt(int index) const = 0; virtual QCPLayoutElement* takeAt(int index) = 0; virtual bool take(QCPLayoutElement* element) = 0; virtual void simplify(); // non-virtual methods: bool removeAt(int index); bool remove(QCPLayoutElement* element); void clear(); protected: // introduced virtual methods: virtual void updateLayout(); // non-virtual methods: void sizeConstraintsChanged() const; void adoptElement(QCPLayoutElement *el); void releaseElement(QCPLayoutElement *el); QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; private: Q_DISABLE_COPY(QCPLayout) friend class QCPLayoutElement; }; class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(int rowCount READ rowCount) Q_PROPERTY(int columnCount READ columnCount) Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) Q_PROPERTY(QList rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) /// \endcond public: explicit QCPLayoutGrid(); virtual ~QCPLayoutGrid(); // getters: int rowCount() const; int columnCount() const; QList columnStretchFactors() const { return mColumnStretchFactors; } QList rowStretchFactors() const { return mRowStretchFactors; } int columnSpacing() const { return mColumnSpacing; } int rowSpacing() const { return mRowSpacing; } // setters: void setColumnStretchFactor(int column, double factor); void setColumnStretchFactors(const QList &factors); void setRowStretchFactor(int row, double factor); void setRowStretchFactors(const QList &factors); void setColumnSpacing(int pixels); void setRowSpacing(int pixels); // reimplemented virtual methods: virtual void updateLayout(); virtual int elementCount() const; virtual QCPLayoutElement* elementAt(int index) const; virtual QCPLayoutElement* takeAt(int index); virtual bool take(QCPLayoutElement* element); virtual QList elements(bool recursive) const; virtual void simplify(); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; // non-virtual methods: QCPLayoutElement *element(int row, int column) const; bool addElement(int row, int column, QCPLayoutElement *element); bool hasElement(int row, int column); void expandTo(int newRowCount, int newColumnCount); void insertRow(int newIndex); void insertColumn(int newIndex); protected: // property members: QList > mElements; QList mColumnStretchFactors; QList mRowStretchFactors; int mColumnSpacing, mRowSpacing; // non-virtual methods: void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; private: Q_DISABLE_COPY(QCPLayoutGrid) }; class QCP_LIB_DECL QCPLayoutInset : public QCPLayout { Q_OBJECT public: /*! Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. */ enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect ,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment }; explicit QCPLayoutInset(); virtual ~QCPLayoutInset(); // getters: InsetPlacement insetPlacement(int index) const; Qt::Alignment insetAlignment(int index) const; QRectF insetRect(int index) const; // setters: void setInsetPlacement(int index, InsetPlacement placement); void setInsetAlignment(int index, Qt::Alignment alignment); void setInsetRect(int index, const QRectF &rect); // reimplemented virtual methods: virtual void updateLayout(); virtual int elementCount() const; virtual QCPLayoutElement* elementAt(int index) const; virtual QCPLayoutElement* takeAt(int index); virtual bool take(QCPLayoutElement* element); virtual void simplify() {} virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-virtual methods: void addElement(QCPLayoutElement *element, Qt::Alignment alignment); void addElement(QCPLayoutElement *element, const QRectF &rect); protected: // property members: QList mElements; QList mInsetPlacement; QList mInsetAlignment; QList mInsetRect; private: Q_DISABLE_COPY(QCPLayoutInset) }; class QCP_LIB_DECL QCPLineEnding { Q_GADGET public: /*! Defines the type of ending decoration for line-like items, e.g. an arrow. \image html QCPLineEnding.png The width and length of these decorations can be controlled with the functions \ref setWidth and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only support a width, the length property is ignored. \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding */ Q_ENUMS(EndingStyle) enum EndingStyle { esNone ///< No ending decoration ,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle) ,esSpikeArrow ///< A filled arrow head with an indented back ,esLineArrow ///< A non-filled arrow head with open back ,esDisc ///< A filled circle ,esSquare ///< A filled square ,esDiamond ///< A filled diamond (45° rotated square) ,esBar ///< A bar perpendicular to the line ,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted) ,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength) }; QCPLineEnding(); QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false); // getters: EndingStyle style() const { return mStyle; } double width() const { return mWidth; } double length() const { return mLength; } bool inverted() const { return mInverted; } // setters: void setStyle(EndingStyle style); void setWidth(double width); void setLength(double length); void setInverted(bool inverted); // non-property methods: double boundingDistance() const; double realLength() const; void draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const; void draw(QCPPainter *painter, const QVector2D &pos, double angle) const; protected: // property members: EndingStyle mStyle; double mWidth, mLength; bool mInverted; }; Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); class QCP_LIB_DECL QCPGrid :public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) /// \endcond public: QCPGrid(QCPAxis *parentAxis); // getters: bool subGridVisible() const { return mSubGridVisible; } bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } QPen pen() const { return mPen; } QPen subGridPen() const { return mSubGridPen; } QPen zeroLinePen() const { return mZeroLinePen; } // setters: void setSubGridVisible(bool visible); void setAntialiasedSubGrid(bool enabled); void setAntialiasedZeroLine(bool enabled); void setPen(const QPen &pen); void setSubGridPen(const QPen &pen); void setZeroLinePen(const QPen &pen); protected: // property members: bool mSubGridVisible; bool mAntialiasedSubGrid, mAntialiasedZeroLine; QPen mPen, mSubGridPen, mZeroLinePen; // non-property members: QCPAxis *mParentAxis; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); // non-virtual methods: void drawGridLines(QCPPainter *painter) const; void drawSubGridLines(QCPPainter *painter) const; friend class QCPAxis; }; class QCP_LIB_DECL QCPAxis : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(AxisType axisType READ axisType) Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) Q_PROPERTY(double scaleLogBase READ scaleLogBase WRITE setScaleLogBase) Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) Q_PROPERTY(bool autoTicks READ autoTicks WRITE setAutoTicks) Q_PROPERTY(int autoTickCount READ autoTickCount WRITE setAutoTickCount) Q_PROPERTY(bool autoTickLabels READ autoTickLabels WRITE setAutoTickLabels) Q_PROPERTY(bool autoTickStep READ autoTickStep WRITE setAutoTickStep) Q_PROPERTY(bool autoSubTicks READ autoSubTicks WRITE setAutoSubTicks) Q_PROPERTY(bool ticks READ ticks WRITE setTicks) Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels) Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding) Q_PROPERTY(LabelType tickLabelType READ tickLabelType WRITE setTickLabelType) Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont) Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor) Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation) Q_PROPERTY(QString dateTimeFormat READ dateTimeFormat WRITE setDateTimeFormat) Q_PROPERTY(Qt::TimeSpec dateTimeSpec READ dateTimeSpec WRITE setDateTimeSpec) Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat) Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) Q_PROPERTY(double tickStep READ tickStep WRITE setTickStep) Q_PROPERTY(QVector tickVector READ tickVector WRITE setTickVector) Q_PROPERTY(QVector tickVectorLabels READ tickVectorLabels WRITE setTickVectorLabels) Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount) Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) Q_PROPERTY(QString label READ label WRITE setLabel) Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) Q_PROPERTY(int padding READ padding WRITE setPadding) Q_PROPERTY(int offset READ offset WRITE setOffset) Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) Q_PROPERTY(QCPGrid* grid READ grid) /// \endcond public: /*! Defines at which side of the axis rect the axis will appear. This also affects how the tick marks are drawn, on which side the labels are placed etc. */ enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect ,atTop = 0x04 ///< 0x04 Axis is horizontal and on the top side of the axis rect ,atBottom = 0x08 ///< 0x08 Axis is horizontal and on the bottom side of the axis rect }; Q_FLAGS(AxisType AxisTypes) Q_DECLARE_FLAGS(AxisTypes, AxisType) /*! When automatic tick label generation is enabled (\ref setAutoTickLabels), defines how the coordinate of the tick is interpreted, i.e. translated into a string. \see setTickLabelType */ enum LabelType { ltNumber ///< Tick coordinate is regarded as normal number and will be displayed as such. (see \ref setNumberFormat) ,ltDateTime ///< Tick coordinate is regarded as a date/time (seconds since 1970-01-01T00:00:00 UTC) and will be displayed and formatted as such. (for details, see \ref setDateTimeFormat) }; Q_ENUMS(LabelType) /*! Defines the scale of an axis. \see setScaleType */ enum ScaleType { stLinear ///< Linear scaling ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed plots and (major) tick marks at every base power (see \ref setScaleLogBase). }; Q_ENUMS(ScaleType) /*! Defines the selectable parts of an axis. \see setSelectableParts, setSelectedParts */ enum SelectablePart { spNone = 0 ///< None of the selectable parts ,spAxis = 0x001 ///< The axis backbone and tick marks ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) ,spAxisLabel = 0x004 ///< The axis label }; Q_FLAGS(SelectablePart SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPAxis(QCPAxisRect *parent, AxisType type); virtual ~QCPAxis(); // getters: AxisType axisType() const { return mAxisType; } QCPAxisRect *axisRect() const { return mAxisRect; } ScaleType scaleType() const { return mScaleType; } double scaleLogBase() const { return mScaleLogBase; } const QCPRange range() const { return mRange; } bool rangeReversed() const { return mRangeReversed; } bool autoTicks() const { return mAutoTicks; } int autoTickCount() const { return mAutoTickCount; } bool autoTickLabels() const { return mAutoTickLabels; } bool autoTickStep() const { return mAutoTickStep; } bool autoSubTicks() const { return mAutoSubTicks; } bool ticks() const { return mTicks; } bool tickLabels() const { return mTickLabels; } int tickLabelPadding() const; LabelType tickLabelType() const { return mTickLabelType; } QFont tickLabelFont() const { return mTickLabelFont; } QColor tickLabelColor() const { return mTickLabelColor; } double tickLabelRotation() const; QString dateTimeFormat() const { return mDateTimeFormat; } Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } QString numberFormat() const; int numberPrecision() const { return mNumberPrecision; } double tickStep() const { return mTickStep; } QVector tickVector() const { return mTickVector; } QVector tickVectorLabels() const { return mTickVectorLabels; } int tickLengthIn() const; int tickLengthOut() const; int subTickCount() const { return mSubTickCount; } int subTickLengthIn() const; int subTickLengthOut() const; QPen basePen() const { return mBasePen; } QPen tickPen() const { return mTickPen; } QPen subTickPen() const { return mSubTickPen; } QFont labelFont() const { return mLabelFont; } QColor labelColor() const { return mLabelColor; } QString label() const { return mLabel; } int labelPadding() const; int padding() const { return mPadding; } int offset() const; SelectableParts selectedParts() const { return mSelectedParts; } SelectableParts selectableParts() const { return mSelectableParts; } QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } QFont selectedLabelFont() const { return mSelectedLabelFont; } QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } QColor selectedLabelColor() const { return mSelectedLabelColor; } QPen selectedBasePen() const { return mSelectedBasePen; } QPen selectedTickPen() const { return mSelectedTickPen; } QPen selectedSubTickPen() const { return mSelectedSubTickPen; } QCPLineEnding lowerEnding() const; QCPLineEnding upperEnding() const; QCPGrid *grid() const { return mGrid; } // setters: Q_SLOT void setScaleType(QCPAxis::ScaleType type); void setScaleLogBase(double base); Q_SLOT void setRange(const QCPRange &range); void setRange(double lower, double upper); void setRange(double position, double size, Qt::AlignmentFlag alignment); void setRangeLower(double lower); void setRangeUpper(double upper); void setRangeReversed(bool reversed); void setAutoTicks(bool on); void setAutoTickCount(int approximateCount); void setAutoTickLabels(bool on); void setAutoTickStep(bool on); void setAutoSubTicks(bool on); void setTicks(bool show); void setTickLabels(bool show); void setTickLabelPadding(int padding); void setTickLabelType(LabelType type); void setTickLabelFont(const QFont &font); void setTickLabelColor(const QColor &color); void setTickLabelRotation(double degrees); void setDateTimeFormat(const QString &format); void setDateTimeSpec(const Qt::TimeSpec &timeSpec); void setNumberFormat(const QString &formatCode); void setNumberPrecision(int precision); void setTickStep(double step); void setTickVector(const QVector &vec); void setTickVectorLabels(const QVector &vec); void setTickLength(int inside, int outside=0); void setTickLengthIn(int inside); void setTickLengthOut(int outside); void setSubTickCount(int count); void setSubTickLength(int inside, int outside=0); void setSubTickLengthIn(int inside); void setSubTickLengthOut(int outside); void setBasePen(const QPen &pen); void setTickPen(const QPen &pen); void setSubTickPen(const QPen &pen); void setLabelFont(const QFont &font); void setLabelColor(const QColor &color); void setLabel(const QString &str); void setLabelPadding(int padding); void setPadding(int padding); void setOffset(int offset); void setSelectedTickLabelFont(const QFont &font); void setSelectedLabelFont(const QFont &font); void setSelectedTickLabelColor(const QColor &color); void setSelectedLabelColor(const QColor &color); void setSelectedBasePen(const QPen &pen); void setSelectedTickPen(const QPen &pen); void setSelectedSubTickPen(const QPen &pen); Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); void setLowerEnding(const QCPLineEnding &ending); void setUpperEnding(const QCPLineEnding &ending); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-property methods: Qt::Orientation orientation() const { return mOrientation; } void moveRange(double diff); void scaleRange(double factor, double center); void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0); void rescale(bool onlyVisiblePlottables=false); double pixelToCoord(double value) const; double coordToPixel(double value) const; SelectablePart getPartAt(const QPointF &pos) const; QList plottables() const; QList graphs() const; QList items() const; static AxisType marginSideToAxisType(QCP::MarginSide side); static Qt::Orientation orientation(AxisType type) { return type==atBottom||type==atTop ? Qt::Horizontal : Qt::Vertical; } static AxisType opposite(AxisType type); signals: void ticksRequest(); void rangeChanged(const QCPRange &newRange); void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); void scaleTypeChanged(QCPAxis::ScaleType scaleType); void selectionChanged(const QCPAxis::SelectableParts &parts); void selectableChanged(const QCPAxis::SelectableParts &parts); protected: // property members: // axis base: AxisType mAxisType; QCPAxisRect *mAxisRect; //int mOffset; // in QCPAxisPainter int mPadding; Qt::Orientation mOrientation; SelectableParts mSelectableParts, mSelectedParts; QPen mBasePen, mSelectedBasePen; //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter // axis label: //int mLabelPadding; // in QCPAxisPainter QString mLabel; QFont mLabelFont, mSelectedLabelFont; QColor mLabelColor, mSelectedLabelColor; // tick labels: //int mTickLabelPadding; // in QCPAxisPainter bool mTickLabels, mAutoTickLabels; //double mTickLabelRotation; // in QCPAxisPainter LabelType mTickLabelType; QFont mTickLabelFont, mSelectedTickLabelFont; QColor mTickLabelColor, mSelectedTickLabelColor; QString mDateTimeFormat; Qt::TimeSpec mDateTimeSpec; int mNumberPrecision; char mNumberFormatChar; bool mNumberBeautifulPowers; //bool mNumberMultiplyCross; // QCPAxisPainter // ticks and subticks: bool mTicks; double mTickStep; int mSubTickCount, mAutoTickCount; bool mAutoTicks, mAutoTickStep, mAutoSubTicks; //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter QPen mTickPen, mSelectedTickPen; QPen mSubTickPen, mSelectedSubTickPen; // scale and range: QCPRange mRange; bool mRangeReversed; ScaleType mScaleType; double mScaleLogBase, mScaleLogBaseLogInv; // non-property members: QCPGrid *mGrid; QCPAxisPainterPrivate *mAxisPainter; int mLowestVisibleTick, mHighestVisibleTick; QVector mTickVector; QVector mTickVectorLabels; QVector mSubTickVector; bool mCachedMarginValid; int mCachedMargin; // introduced virtual methods: virtual void setupTickVectors(); virtual void generateAutoTicks(); virtual int calculateAutoSubTickCount(double tickStep) const; virtual int calculateMargin(); // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); virtual QCP::Interaction selectionCategory() const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-virtual methods: void visibleTickBounds(int &lowIndex, int &highIndex) const; double baseLog(double value) const; double basePow(double value) const; QPen getBasePen() const; QPen getTickPen() const; QPen getSubTickPen() const; QFont getTickLabelFont() const; QFont getLabelFont() const; QColor getTickLabelColor() const; QColor getLabelColor() const; private: Q_DISABLE_COPY(QCPAxis) friend class QCustomPlot; friend class QCPGrid; friend class QCPAxisRect; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) Q_DECLARE_METATYPE(QCPAxis::SelectablePart) class QCPAxisPainterPrivate { public: explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); virtual ~QCPAxisPainterPrivate(); virtual void draw(QCPPainter *painter); virtual int size() const; void clearCache(); QRect axisSelectionBox() const { return mAxisSelectionBox; } QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } QRect labelSelectionBox() const { return mLabelSelectionBox; } // public property members: QCPAxis::AxisType type; QPen basePen; QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters int labelPadding; // directly accessed by QCPAxis setters/getters QFont labelFont; QColor labelColor; QString label; int tickLabelPadding; // directly accessed by QCPAxis setters/getters double tickLabelRotation; // directly accessed by QCPAxis setters/getters bool substituteExponent; bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters QPen tickPen, subTickPen; QFont tickLabelFont; QColor tickLabelColor; QRect alignmentRect, viewportRect; double offset; // directly accessed by QCPAxis setters/getters bool abbreviateDecimalPowers; bool reversedEndings; QVector subTickPositions; QVector tickPositions; QVector tickLabels; protected: struct CachedLabel { QPointF offset; QPixmap pixmap; }; struct TickLabelData { QString basePart, expPart; QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; QFont baseFont, expFont; }; QCustomPlot *mParentPlot; QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters QCache mLabelCache; QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; virtual QByteArray generateLabelParameterHash() const; virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; }; class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill) Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters) Q_PROPERTY(bool antialiasedErrorBars READ antialiasedErrorBars WRITE setAntialiasedErrorBars) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); // getters: QString name() const { return mName; } bool antialiasedFill() const { return mAntialiasedFill; } bool antialiasedScatters() const { return mAntialiasedScatters; } bool antialiasedErrorBars() const { return mAntialiasedErrorBars; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setName(const QString &name); void setAntialiasedFill(bool enabled); void setAntialiasedScatters(bool enabled); void setAntialiasedErrorBars(bool enabled); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setKeyAxis(QCPAxis *axis); void setValueAxis(QCPAxis *axis); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // introduced virtual methods: virtual void clearData() = 0; virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; virtual bool addToLegend(); virtual bool removeFromLegend() const; // non-property methods: void rescaleAxes(bool onlyEnlarge=false) const; void rescaleKeyAxis(bool onlyEnlarge=false) const; void rescaleValueAxis(bool onlyEnlarge=false) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: /*! Represents negative and positive sign domain for passing to \ref getKeyRange and \ref getValueRange. */ enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero ,sdBoth ///< Both sign domains, including zero, i.e. all (rational) numbers ,sdPositive ///< The positive sign domain, i.e. numbers greater than zero }; // property members: QString mName; bool mAntialiasedFill, mAntialiasedScatters, mAntialiasedErrorBars; QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; QPointer mKeyAxis, mValueAxis; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QRect clipRect() const; virtual void draw(QCPPainter *painter) = 0; virtual QCP::Interaction selectionCategory() const; void applyDefaultAntialiasingHint(QCPPainter *painter) const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // introduced virtual methods: virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; // non-virtual methods: void coordsToPixels(double key, double value, double &x, double &y) const; const QPointF coordsToPixels(double key, double value) const; void pixelsToCoords(double x, double y, double &key, double &value) const; void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const; QPen mainPen() const; QBrush mainBrush() const; void applyFillAntialiasingHint(QCPPainter *painter) const; void applyScattersAntialiasingHint(QCPPainter *painter) const; void applyErrorBarsAntialiasingHint(QCPPainter *painter) const; double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; private: Q_DISABLE_COPY(QCPAbstractPlottable) friend class QCustomPlot; friend class QCPAxis; friend class QCPPlottableLegendItem; }; class QCP_LIB_DECL QCPItemAnchor { public: QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId=-1); virtual ~QCPItemAnchor(); // getters: QString name() const { return mName; } virtual QPointF pixelPoint() const; protected: // property members: QString mName; // non-property members: QCustomPlot *mParentPlot; QCPAbstractItem *mParentItem; int mAnchorId; QSet mChildren; // introduced virtual methods: virtual QCPItemPosition *toQCPItemPosition() { return 0; } // non-virtual methods: void addChild(QCPItemPosition* pos); // called from pos when this anchor is set as parent void removeChild(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted private: Q_DISABLE_COPY(QCPItemAnchor) friend class QCPItemPosition; }; class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor { public: /*! Defines the ways an item position can be specified. Thus it defines what the numbers passed to \ref setCoords actually mean. \see setType */ enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and ///< vertically at the top of the viewport/widget, etc. ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and ///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1. ,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes). }; QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name); virtual ~QCPItemPosition(); // getters: PositionType type() const { return mPositionType; } QCPItemAnchor *parentAnchor() const { return mParentAnchor; } double key() const { return mKey; } double value() const { return mValue; } QPointF coords() const { return QPointF(mKey, mValue); } QCPAxis *keyAxis() const { return mKeyAxis.data(); } QCPAxis *valueAxis() const { return mValueAxis.data(); } QCPAxisRect *axisRect() const; virtual QPointF pixelPoint() const; // setters: void setType(PositionType type); bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); void setCoords(double key, double value); void setCoords(const QPointF &coords); void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); void setAxisRect(QCPAxisRect *axisRect); void setPixelPoint(const QPointF &pixelPoint); protected: // property members: PositionType mPositionType; QPointer mKeyAxis, mValueAxis; QPointer mAxisRect; double mKey, mValue; QCPItemAnchor *mParentAnchor; // reimplemented virtual methods: virtual QCPItemPosition *toQCPItemPosition() { return this; } private: Q_DISABLE_COPY(QCPItemPosition) }; class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: QCPAbstractItem(QCustomPlot *parentPlot); virtual ~QCPAbstractItem(); // getters: bool clipToAxisRect() const { return mClipToAxisRect; } QCPAxisRect *clipAxisRect() const; bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setClipToAxisRect(bool clip); void setClipAxisRect(QCPAxisRect *rect); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; // non-virtual methods: QList positions() const { return mPositions; } QList anchors() const { return mAnchors; } QCPItemPosition *position(const QString &name) const; QCPItemAnchor *anchor(const QString &name) const; bool hasAnchor(const QString &name) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: bool mClipToAxisRect; QPointer mClipAxisRect; QList mPositions; QList mAnchors; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QCP::Interaction selectionCategory() const; virtual QRect clipRect() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter) = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // introduced virtual methods: virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; double rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const; QCPItemPosition *createPosition(const QString &name); QCPItemAnchor *createAnchor(const QString &name, int anchorId); private: Q_DISABLE_COPY(QCPAbstractItem) friend class QCustomPlot; friend class QCPItemAnchor; }; class QCP_LIB_DECL QCustomPlot : public QWidget { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) Q_PROPERTY(QPixmap background READ background WRITE setBackground) Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance) Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag) Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier) /// \endcond public: /*! Defines how a layer should be inserted relative to an other layer. \see addLayer, moveLayer */ enum LayerInsertMode { limBelow ///< Layer is inserted below other layer ,limAbove ///< Layer is inserted above other layer }; Q_ENUMS(LayerInsertMode) /*! Defines with what timing the QCustomPlot surface is refreshed after a replot. \see replot */ enum RefreshPriority { rpImmediate ///< The QCustomPlot surface is immediately refreshed, by calling QWidget::repaint() after the replot ,rpQueued ///< Queues the refresh such that it is performed at a slightly delayed point in time after the replot, by calling QWidget::update() after the replot ,rpHint ///< Whether to use immediate repaint or queued update depends on whether the plotting hint \ref QCP::phForceRepaint is set, see \ref setPlottingHints. }; explicit QCustomPlot(QWidget *parent = 0); virtual ~QCustomPlot(); // getters: QRect viewport() const { return mViewport; } QPixmap background() const { return mBackgroundPixmap; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } QCPLayoutGrid *plotLayout() const { return mPlotLayout; } QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } const QCP::Interactions interactions() const { return mInteractions; } int selectionTolerance() const { return mSelectionTolerance; } bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; } QCP::PlottingHints plottingHints() const { return mPlottingHints; } Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; } // setters: void setViewport(const QRect &rect); void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); void setBackgroundScaled(bool scaled); void setBackgroundScaledMode(Qt::AspectRatioMode mode); void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); void setAutoAddPlottableToLegend(bool on); void setInteractions(const QCP::Interactions &interactions); void setInteraction(const QCP::Interaction &interaction, bool enabled=true); void setSelectionTolerance(int pixels); void setNoAntialiasingOnDrag(bool enabled); void setPlottingHints(const QCP::PlottingHints &hints); void setPlottingHint(QCP::PlottingHint hint, bool enabled=true); void setMultiSelectModifier(Qt::KeyboardModifier modifier); // non-property methods: // plottable interface: QCPAbstractPlottable *plottable(int index); QCPAbstractPlottable *plottable(); bool addPlottable(QCPAbstractPlottable *plottable); bool removePlottable(QCPAbstractPlottable *plottable); bool removePlottable(int index); int clearPlottables(); int plottableCount() const; QList selectedPlottables() const; QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false) const; bool hasPlottable(QCPAbstractPlottable *plottable) const; // specialized interface for QCPGraph: QCPGraph *graph(int index) const; QCPGraph *graph() const; QCPGraph *addGraph(QCPAxis *keyAxis=0, QCPAxis *valueAxis=0); bool removeGraph(QCPGraph *graph); bool removeGraph(int index); int clearGraphs(); int graphCount() const; QList selectedGraphs() const; // item interface: QCPAbstractItem *item(int index) const; QCPAbstractItem *item() const; bool addItem(QCPAbstractItem* item); bool removeItem(QCPAbstractItem *item); bool removeItem(int index); int clearItems(); int itemCount() const; QList selectedItems() const; QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; bool hasItem(QCPAbstractItem *item) const; // layer interface: QCPLayer *layer(const QString &name) const; QCPLayer *layer(int index) const; QCPLayer *currentLayer() const; bool setCurrentLayer(const QString &name); bool setCurrentLayer(QCPLayer *layer); int layerCount() const; bool addLayer(const QString &name, QCPLayer *otherLayer=0, LayerInsertMode insertMode=limAbove); bool removeLayer(QCPLayer *layer); bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); // axis rect/layout interface: int axisRectCount() const; QCPAxisRect* axisRect(int index=0) const; QList axisRects() const; QCPLayoutElement* layoutElementAt(const QPointF &pos) const; Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false); QList selectedAxes() const; QList selectedLegends() const; Q_SLOT void deselectAll(); bool savePdf(const QString &fileName, bool noCosmeticPen=false, int width=0, int height=0, const QString &pdfCreator="", const QString &pdfTitle=""); bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0); bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1); QPixmap toPixmap(int width=0, int height=0, double scale=1.0); void toPainter(QCPPainter *painter, int width=0, int height=0); Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpHint); QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; QCPLegend *legend; signals: void mouseDoubleClick(QMouseEvent *event); void mousePress(QMouseEvent *event); void mouseMove(QMouseEvent *event); void mouseRelease(QMouseEvent *event); void mouseWheel(QWheelEvent *event); void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event); void plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event); void itemClick(QCPAbstractItem *item, QMouseEvent *event); void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event); void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); void titleClick(QMouseEvent *event, QCPPlotTitle *title); void titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title); void selectionChangedByUser(); void beforeReplot(); void afterReplot(); protected: // property members: QRect mViewport; QCPLayoutGrid *mPlotLayout; bool mAutoAddPlottableToLegend; QList mPlottables; QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph QList mItems; QList mLayers; QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; QCP::Interactions mInteractions; int mSelectionTolerance; bool mNoAntialiasingOnDrag; QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; QCPLayer *mCurrentLayer; QCP::PlottingHints mPlottingHints; Qt::KeyboardModifier mMultiSelectModifier; // non-property members: QPixmap mPaintBuffer; QPoint mMousePressPos; QPointer mMouseEventElement; bool mReplotting; // reimplemented virtual methods: virtual QSize minimumSizeHint() const; virtual QSize sizeHint() const; virtual void paintEvent(QPaintEvent *event); virtual void resizeEvent(QResizeEvent *event); virtual void mouseDoubleClickEvent(QMouseEvent *event); virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void wheelEvent(QWheelEvent *event); // introduced virtual methods: virtual void draw(QCPPainter *painter); virtual void axisRemoved(QCPAxis *axis); virtual void legendRemoved(QCPLegend *legend); // non-virtual methods: void updateLayerIndices() const; QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=0) const; void drawBackground(QCPPainter *painter); friend class QCPLegend; friend class QCPAxis; friend class QCPLayer; friend class QCPAxisRect; }; class QCP_LIB_DECL QCPColorGradient { Q_GADGET public: /*! Defines the color spaces in which color interpolation between gradient stops can be performed. \see setColorInterpolation */ enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) }; Q_ENUMS(ColorInterpolation) /*! Defines the available presets that can be loaded with \ref loadPreset. See the documentation there for an image of the presets. */ enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) ,gpCandy ///< Blue over pink to white ,gpGeography ///< Colors suitable to represent different elevations on geographical maps ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) }; Q_ENUMS(GradientPreset) QCPColorGradient(GradientPreset preset=gpCold); bool operator==(const QCPColorGradient &other) const; bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } // getters: int levelCount() const { return mLevelCount; } QMap colorStops() const { return mColorStops; } ColorInterpolation colorInterpolation() const { return mColorInterpolation; } bool periodic() const { return mPeriodic; } // setters: void setLevelCount(int n); void setColorStops(const QMap &colorStops); void setColorStopAt(double position, const QColor &color); void setColorInterpolation(ColorInterpolation interpolation); void setPeriodic(bool enabled); // non-property methods: void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); QRgb color(double position, const QCPRange &range, bool logarithmic=false); void loadPreset(GradientPreset preset); void clearColorStops(); QCPColorGradient inverted() const; protected: void updateColorBuffer(); // property members: int mLevelCount; QMap mColorStops; ColorInterpolation mColorInterpolation; bool mPeriodic; // non-property members: QVector mColorBuffer; bool mColorBufferInvalidated; }; class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap background READ background WRITE setBackground) Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) /// \endcond public: explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); virtual ~QCPAxisRect(); // getters: QPixmap background() const { return mBackgroundPixmap; } bool backgroundScaled() const { return mBackgroundScaled; } Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } Qt::Orientations rangeDrag() const { return mRangeDrag; } Qt::Orientations rangeZoom() const { return mRangeZoom; } QCPAxis *rangeDragAxis(Qt::Orientation orientation); QCPAxis *rangeZoomAxis(Qt::Orientation orientation); double rangeZoomFactor(Qt::Orientation orientation); // setters: void setBackground(const QPixmap &pm); void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); void setBackground(const QBrush &brush); void setBackgroundScaled(bool scaled); void setBackgroundScaledMode(Qt::AspectRatioMode mode); void setRangeDrag(Qt::Orientations orientations); void setRangeZoom(Qt::Orientations orientations); void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); void setRangeZoomFactor(double horizontalFactor, double verticalFactor); void setRangeZoomFactor(double factor); // non-property methods: int axisCount(QCPAxis::AxisType type) const; QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; QList axes(QCPAxis::AxisTypes types) const; QList axes() const; QCPAxis *addAxis(QCPAxis::AxisType type); QList addAxes(QCPAxis::AxisTypes types); bool removeAxis(QCPAxis *axis); QCPLayoutInset *insetLayout() const { return mInsetLayout; } void setupFullAxesBox(bool connectRanges=false); QList plottables() const; QList graphs() const; QList items() const; // read-only interface imitating a QRect: int left() const { return mRect.left(); } int right() const { return mRect.right(); } int top() const { return mRect.top(); } int bottom() const { return mRect.bottom(); } int width() const { return mRect.width(); } int height() const { return mRect.height(); } QSize size() const { return mRect.size(); } QPoint topLeft() const { return mRect.topLeft(); } QPoint topRight() const { return mRect.topRight(); } QPoint bottomLeft() const { return mRect.bottomLeft(); } QPoint bottomRight() const { return mRect.bottomRight(); } QPoint center() const { return mRect.center(); } // reimplemented virtual methods: virtual void update(UpdatePhase phase); virtual QList elements(bool recursive) const; protected: // property members: QBrush mBackgroundBrush; QPixmap mBackgroundPixmap; QPixmap mScaledBackgroundPixmap; bool mBackgroundScaled; Qt::AspectRatioMode mBackgroundScaledMode; QCPLayoutInset *mInsetLayout; Qt::Orientations mRangeDrag, mRangeZoom; QPointer mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; double mRangeZoomFactorHorz, mRangeZoomFactorVert; // non-property members: QCPRange mDragStartHorzRange, mDragStartVertRange; QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; QPoint mDragStart; bool mDragging; QHash > mAxes; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); virtual int calculateAutoMargin(QCP::MarginSide side); // events: virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void wheelEvent(QWheelEvent *event); // non-property methods: void drawBackground(QCPPainter *painter); void updateAxesOffset(QCPAxis::AxisType type); private: Q_DISABLE_COPY(QCPAxisRect) friend class QCustomPlot; }; class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) /// \endcond public: explicit QCPAbstractLegendItem(QCPLegend *parent); // getters: QCPLegend *parentLegend() const { return mParentLegend; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setFont(const QFont &font); void setTextColor(const QColor &color); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: QCPLegend *mParentLegend; QFont mFont; QColor mTextColor; QFont mSelectedFont; QColor mSelectedTextColor; bool mSelectable, mSelected; // reimplemented virtual methods: virtual QCP::Interaction selectionCategory() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual QRect clipRect() const; virtual void draw(QCPPainter *painter) = 0; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); private: Q_DISABLE_COPY(QCPAbstractLegendItem) friend class QCPLegend; }; class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem { Q_OBJECT public: QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); // getters: QCPAbstractPlottable *plottable() { return mPlottable; } protected: // property members: QCPAbstractPlottable *mPlottable; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QSize minimumSizeHint() const; // non-virtual methods: QPen getIconBorderPen() const; QColor getTextColor() const; QFont getFont() const; }; class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) /// \endcond public: /*! Defines the selectable parts of a legend \see setSelectedParts, setSelectableParts */ enum SelectablePart { spNone = 0x000 ///< 0x000 None ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) }; Q_FLAGS(SelectablePart SelectableParts) Q_DECLARE_FLAGS(SelectableParts, SelectablePart) explicit QCPLegend(); virtual ~QCPLegend(); // getters: QPen borderPen() const { return mBorderPen; } QBrush brush() const { return mBrush; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QSize iconSize() const { return mIconSize; } int iconTextPadding() const { return mIconTextPadding; } QPen iconBorderPen() const { return mIconBorderPen; } SelectableParts selectableParts() const { return mSelectableParts; } SelectableParts selectedParts() const; QPen selectedBorderPen() const { return mSelectedBorderPen; } QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } QBrush selectedBrush() const { return mSelectedBrush; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } // setters: void setBorderPen(const QPen &pen); void setBrush(const QBrush &brush); void setFont(const QFont &font); void setTextColor(const QColor &color); void setIconSize(const QSize &size); void setIconSize(int width, int height); void setIconTextPadding(int padding); void setIconBorderPen(const QPen &pen); Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); void setSelectedBorderPen(const QPen &pen); void setSelectedIconBorderPen(const QPen &pen); void setSelectedBrush(const QBrush &brush); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-virtual methods: QCPAbstractLegendItem *item(int index) const; QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; int itemCount() const; bool hasItem(QCPAbstractLegendItem *item) const; bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; bool addItem(QCPAbstractLegendItem *item); bool removeItem(int index); bool removeItem(QCPAbstractLegendItem *item); void clearItems(); QList selectedItems() const; signals: void selectionChanged(QCPLegend::SelectableParts parts); void selectableChanged(QCPLegend::SelectableParts parts); protected: // property members: QPen mBorderPen, mIconBorderPen; QBrush mBrush; QFont mFont; QColor mTextColor; QSize mIconSize; int mIconTextPadding; SelectableParts mSelectedParts, mSelectableParts; QPen mSelectedBorderPen, mSelectedIconBorderPen; QBrush mSelectedBrush; QFont mSelectedFont; QColor mSelectedTextColor; // reimplemented virtual methods: virtual void parentPlotInitialized(QCustomPlot *parentPlot); virtual QCP::Interaction selectionCategory() const; virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-virtual methods: QPen getBorderPen() const; QBrush getBrush() const; private: Q_DISABLE_COPY(QCPLegend) friend class QCustomPlot; friend class QCPAbstractLegendItem; }; Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) Q_DECLARE_METATYPE(QCPLegend::SelectablePart) class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) /// \endcond public: explicit QCPPlotTitle(QCustomPlot *parentPlot); explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text); // getters: QString text() const { return mText; } QFont font() const { return mFont; } QColor textColor() const { return mTextColor; } QFont selectedFont() const { return mSelectedFont; } QColor selectedTextColor() const { return mSelectedTextColor; } bool selectable() const { return mSelectable; } bool selected() const { return mSelected; } // setters: void setText(const QString &text); void setFont(const QFont &font); void setTextColor(const QColor &color); void setSelectedFont(const QFont &font); void setSelectedTextColor(const QColor &color); Q_SLOT void setSelectable(bool selectable); Q_SLOT void setSelected(bool selected); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; signals: void selectionChanged(bool selected); void selectableChanged(bool selectable); protected: // property members: QString mText; QFont mFont; QColor mTextColor; QFont mSelectedFont; QColor mSelectedTextColor; QRect mTextBoundingRect; bool mSelectable, mSelected; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; virtual void draw(QCPPainter *painter); virtual QSize minimumSizeHint() const; virtual QSize maximumSizeHint() const; // events: virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); virtual void deselectEvent(bool *selectionStateChanged); // non-virtual methods: QFont mainFont() const; QColor mainTextColor() const; private: Q_DISABLE_COPY(QCPPlotTitle) }; class QCPColorScaleAxisRectPrivate : public QCPAxisRect { Q_OBJECT public: explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); protected: QCPColorScale *mParentColorScale; QImage mGradientImage; bool mGradientImageInvalidated; // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale using QCPAxisRect::calculateAutoMargin; using QCPAxisRect::mousePressEvent; using QCPAxisRect::mouseMoveEvent; using QCPAxisRect::mouseReleaseEvent; using QCPAxisRect::wheelEvent; using QCPAxisRect::update; virtual void draw(QCPPainter *painter); void updateGradientImage(); Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); friend class QCPColorScale; }; class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) Q_PROPERTY(QString label READ label WRITE setLabel) Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) /// \endcond public: explicit QCPColorScale(QCustomPlot *parentPlot); virtual ~QCPColorScale(); // getters: QCPAxis *axis() const { return mColorAxis.data(); } QCPAxis::AxisType type() const { return mType; } QCPRange dataRange() const { return mDataRange; } QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } QCPColorGradient gradient() const { return mGradient; } QString label() const; int barWidth () const { return mBarWidth; } bool rangeDrag() const; bool rangeZoom() const; // setters: void setType(QCPAxis::AxisType type); Q_SLOT void setDataRange(const QCPRange &dataRange); Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); Q_SLOT void setGradient(const QCPColorGradient &gradient); void setLabel(const QString &str); void setBarWidth(int width); void setRangeDrag(bool enabled); void setRangeZoom(bool enabled); // non-property methods: QList colorMaps() const; void rescaleDataRange(bool onlyVisibleMaps); // reimplemented virtual methods: virtual void update(UpdatePhase phase); signals: void dataRangeChanged(QCPRange newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); void gradientChanged(QCPColorGradient newGradient); protected: // property members: QCPAxis::AxisType mType; QCPRange mDataRange; QCPAxis::ScaleType mDataScaleType; QCPColorGradient mGradient; int mBarWidth; // non-property members: QPointer mAxisRect; QPointer mColorAxis; // reimplemented virtual methods: virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; // events: virtual void mousePressEvent(QMouseEvent *event); virtual void mouseMoveEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); virtual void wheelEvent(QWheelEvent *event); private: Q_DISABLE_COPY(QCPColorScale) friend class QCPColorScaleAxisRectPrivate; }; /*! \file */ class QCP_LIB_DECL QCPData { public: QCPData(); QCPData(double key, double value); double key, value; double keyErrorPlus, keyErrorMinus; double valueErrorPlus, valueErrorMinus; }; Q_DECLARE_TYPEINFO(QCPData, Q_MOVABLE_TYPE); /*! \typedef QCPDataMap Container for storing QCPData items in a sorted fashion. The key of the map is the key member of the QCPData instance. This is the container in which QCPGraph holds its data. \see QCPData, QCPGraph::setData */ typedef QMap QCPDataMap; typedef QMapIterator QCPDataMapIterator; typedef QMutableMapIterator QCPDataMutableMapIterator; class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType) Q_PROPERTY(QPen errorPen READ errorPen WRITE setErrorPen) Q_PROPERTY(double errorBarSize READ errorBarSize WRITE setErrorBarSize) Q_PROPERTY(bool errorBarSkipSymbol READ errorBarSkipSymbol WRITE setErrorBarSkipSymbol) Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) /// \endcond public: /*! Defines how the graph's line is represented visually in the plot. The line is drawn with the current pen of the graph (\ref setPen). \see setLineStyle */ enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented ///< with symbols according to the scatter style, see \ref setScatterStyle) ,lsLine ///< data points are connected by a straight line ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point ,lsStepCenter ///< line is drawn as steps where the step is in between two data points ,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line }; Q_ENUMS(LineStyle) /*! Defines what kind of error bars are drawn for each data point */ enum ErrorType { etNone ///< No error bars are shown ,etKey ///< Error bars for the key dimension of the data point are shown ,etValue ///< Error bars for the value dimension of the data point are shown ,etBoth ///< Error bars for both key and value dimensions of the data point are shown }; Q_ENUMS(ErrorType) explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPGraph(); // getters: QCPDataMap *data() const { return mData; } LineStyle lineStyle() const { return mLineStyle; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } ErrorType errorType() const { return mErrorType; } QPen errorPen() const { return mErrorPen; } double errorBarSize() const { return mErrorBarSize; } bool errorBarSkipSymbol() const { return mErrorBarSkipSymbol; } QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } bool adaptiveSampling() const { return mAdaptiveSampling; } // setters: void setData(QCPDataMap *data, bool copy=false); void setData(const QVector &key, const QVector &value); void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError); void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus); void setDataValueError(const QVector &key, const QVector &value, const QVector &valueError); void setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus); void setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError); void setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus); void setLineStyle(LineStyle ls); void setScatterStyle(const QCPScatterStyle &style); void setErrorType(ErrorType errorType); void setErrorPen(const QPen &pen); void setErrorBarSize(double size); void setErrorBarSkipSymbol(bool enabled); void setChannelFillGraph(QCPGraph *targetGraph); void setAdaptiveSampling(bool enabled); // non-property methods: void addData(const QCPDataMap &dataMap); void addData(const QCPData &data); void addData(double key, double value); void addData(const QVector &keys, const QVector &values); void removeDataBefore(double key); void removeDataAfter(double key); void removeData(double fromKey, double toKey); void removeData(double key); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; using QCPAbstractPlottable::rescaleAxes; using QCPAbstractPlottable::rescaleKeyAxis; using QCPAbstractPlottable::rescaleValueAxis; void rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface void rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface void rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface protected: // property members: QCPDataMap *mData; QPen mErrorPen; LineStyle mLineStyle; QCPScatterStyle mScatterStyle; ErrorType mErrorType; double mErrorBarSize; bool mErrorBarSkipSymbol; QPointer mChannelFillGraph; bool mAdaptiveSampling; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface // introduced virtual methods: virtual void drawFill(QCPPainter *painter, QVector *lineData) const; virtual void drawScatterPlot(QCPPainter *painter, QVector *scatterData) const; virtual void drawLinePlot(QCPPainter *painter, QVector *lineData) const; virtual void drawImpulsePlot(QCPPainter *painter, QVector *lineData) const; // non-virtual methods: void getPreparedData(QVector *lineData, QVector *scatterData) const; void getPlotData(QVector *lineData, QVector *scatterData) const; void getScatterPlotData(QVector *scatterData) const; void getLinePlotData(QVector *linePixelData, QVector *scatterData) const; void getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const; void getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const; void getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const; void getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const; void drawError(QCPPainter *painter, double x, double y, const QCPData &data) const; void getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const; int countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const; void addFillBasePoints(QVector *lineData) const; void removeFillBasePoints(QVector *lineData) const; QPointF lowerFillBasePoint(double lowerKey) const; QPointF upperFillBasePoint(double upperKey) const; const QPolygonF getChannelFillPolygon(const QVector *lineData) const; int findIndexBelowX(const QVector *data, double x) const; int findIndexAboveX(const QVector *data, double x) const; int findIndexBelowY(const QVector *data, double y) const; int findIndexAboveY(const QVector *data, double y) const; double pointDistance(const QPointF &pixelPoint) const; friend class QCustomPlot; friend class QCPLegend; }; /*! \file */ class QCP_LIB_DECL QCPCurveData { public: QCPCurveData(); QCPCurveData(double t, double key, double value); double t, key, value; }; Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_TYPE); /*! \typedef QCPCurveDataMap Container for storing QCPCurveData items in a sorted fashion. The key of the map is the t member of the QCPCurveData instance. This is the container in which QCPCurve holds its data. \see QCPCurveData, QCPCurve::setData */ typedef QMap QCPCurveDataMap; typedef QMapIterator QCPCurveDataMapIterator; typedef QMutableMapIterator QCPCurveDataMutableMapIterator; class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) /// \endcond public: /*! Defines how the curve's line is represented visually in the plot. The line is drawn with the current pen of the curve (\ref setPen). \see setLineStyle */ enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) ,lsLine ///< Data points are connected with a straight line }; explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPCurve(); // getters: QCPCurveDataMap *data() const { return mData; } QCPScatterStyle scatterStyle() const { return mScatterStyle; } LineStyle lineStyle() const { return mLineStyle; } // setters: void setData(QCPCurveDataMap *data, bool copy=false); void setData(const QVector &t, const QVector &key, const QVector &value); void setData(const QVector &key, const QVector &value); void setScatterStyle(const QCPScatterStyle &style); void setLineStyle(LineStyle style); // non-property methods: void addData(const QCPCurveDataMap &dataMap); void addData(const QCPCurveData &data); void addData(double t, double key, double value); void addData(double key, double value); void addData(const QVector &ts, const QVector &keys, const QVector &values); void removeDataBefore(double t); void removeDataAfter(double t); void removeData(double fromt, double tot); void removeData(double t); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QCPCurveDataMap *mData; QCPScatterStyle mScatterStyle; LineStyle mLineStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // introduced virtual methods: virtual void drawScatterPlot(QCPPainter *painter, const QVector *pointData) const; // non-virtual methods: void getCurveData(QVector *lineData) const; double pointDistance(const QPointF &pixelPoint) const; QPointF outsideCoordsToPixels(double key, double value, int region, QRect axisRect) const; friend class QCustomPlot; friend class QCPLegend; }; /*! \file */ class QCP_LIB_DECL QCPBarData { public: QCPBarData(); QCPBarData(double key, double value); double key, value; }; Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_TYPE); /*! \typedef QCPBarDataMap Container for storing QCPBarData items in a sorted fashion. The key of the map is the key member of the QCPBarData instance. This is the container in which QCPBars holds its data. \see QCPBarData, QCPBars::setData */ typedef QMap QCPBarDataMap; typedef QMapIterator QCPBarDataMapIterator; typedef QMutableMapIterator QCPBarDataMutableMapIterator; class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(QCPBars* barBelow READ barBelow) Q_PROPERTY(QCPBars* barAbove READ barAbove) /// \endcond public: explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPBars(); // getters: double width() const { return mWidth; } QCPBars *barBelow() const { return mBarBelow.data(); } QCPBars *barAbove() const { return mBarAbove.data(); } QCPBarDataMap *data() const { return mData; } // setters: void setWidth(double width); void setData(QCPBarDataMap *data, bool copy=false); void setData(const QVector &key, const QVector &value); // non-property methods: void moveBelow(QCPBars *bars); void moveAbove(QCPBars *bars); void addData(const QCPBarDataMap &dataMap); void addData(const QCPBarData &data); void addData(double key, double value); void addData(const QVector &keys, const QVector &values); void removeDataBefore(double key); void removeDataAfter(double key); void removeData(double fromKey, double toKey); void removeData(double key); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QCPBarDataMap *mData; double mWidth; QPointer mBarBelow, mBarAbove; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // non-virtual methods: QPolygonF getBarPolygon(double key, double value) const; double getBaseValue(double key, bool positive) const; static void connectBars(QCPBars* lower, QCPBars* upper); friend class QCustomPlot; friend class QCPLegend; }; /*! \file */ class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(double key READ key WRITE setKey) Q_PROPERTY(double minimum READ minimum WRITE setMinimum) Q_PROPERTY(double lowerQuartile READ lowerQuartile WRITE setLowerQuartile) Q_PROPERTY(double median READ median WRITE setMedian) Q_PROPERTY(double upperQuartile READ upperQuartile WRITE setUpperQuartile) Q_PROPERTY(double maximum READ maximum WRITE setMaximum) Q_PROPERTY(QVector outliers READ outliers WRITE setOutliers) Q_PROPERTY(double width READ width WRITE setWidth) Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen) Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen) Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen) Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) /// \endcond public: explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); // getters: double key() const { return mKey; } double minimum() const { return mMinimum; } double lowerQuartile() const { return mLowerQuartile; } double median() const { return mMedian; } double upperQuartile() const { return mUpperQuartile; } double maximum() const { return mMaximum; } QVector outliers() const { return mOutliers; } double width() const { return mWidth; } double whiskerWidth() const { return mWhiskerWidth; } QPen whiskerPen() const { return mWhiskerPen; } QPen whiskerBarPen() const { return mWhiskerBarPen; } QPen medianPen() const { return mMedianPen; } QCPScatterStyle outlierStyle() const { return mOutlierStyle; } // setters: void setKey(double key); void setMinimum(double value); void setLowerQuartile(double value); void setMedian(double value); void setUpperQuartile(double value); void setMaximum(double value); void setOutliers(const QVector &values); void setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum); void setWidth(double width); void setWhiskerWidth(double width); void setWhiskerPen(const QPen &pen); void setWhiskerBarPen(const QPen &pen); void setMedianPen(const QPen &pen); void setOutlierStyle(const QCPScatterStyle &style); // non-property methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; protected: // property members: QVector mOutliers; double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; double mWidth; double mWhiskerWidth; QPen mWhiskerPen, mWhiskerBarPen, mMedianPen; QCPScatterStyle mOutlierStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; // introduced virtual methods: virtual void drawQuartileBox(QCPPainter *painter, QRectF *quartileBox=0) const; virtual void drawMedian(QCPPainter *painter) const; virtual void drawWhiskers(QCPPainter *painter) const; virtual void drawOutliers(QCPPainter *painter) const; friend class QCustomPlot; friend class QCPLegend; }; class QCP_LIB_DECL QCPColorMapData { public: QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); ~QCPColorMapData(); QCPColorMapData(const QCPColorMapData &other); QCPColorMapData &operator=(const QCPColorMapData &other); // getters: int keySize() const { return mKeySize; } int valueSize() const { return mValueSize; } QCPRange keyRange() const { return mKeyRange; } QCPRange valueRange() const { return mValueRange; } QCPRange dataBounds() const { return mDataBounds; } double data(double key, double value); double cell(int keyIndex, int valueIndex); // setters: void setSize(int keySize, int valueSize); void setKeySize(int keySize); void setValueSize(int valueSize); void setRange(const QCPRange &keyRange, const QCPRange &valueRange); void setKeyRange(const QCPRange &keyRange); void setValueRange(const QCPRange &valueRange); void setData(double key, double value, double z); void setCell(int keyIndex, int valueIndex, double z); // non-property methods: void recalculateDataBounds(); void clear(); void fill(double z); bool isEmpty() const { return mIsEmpty; } void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const; void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const; protected: // property members: int mKeySize, mValueSize; QCPRange mKeyRange, mValueRange; bool mIsEmpty; // non-property members: double *mData; QCPRange mDataBounds; bool mDataModified; friend class QCPColorMap; }; class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) /// \endcond public: explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); virtual ~QCPColorMap(); // getters: QCPColorMapData *data() const { return mMapData; } QCPRange dataRange() const { return mDataRange; } QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } bool interpolate() const { return mInterpolate; } bool tightBoundary() const { return mTightBoundary; } QCPColorGradient gradient() const { return mGradient; } QCPColorScale *colorScale() const { return mColorScale.data(); } // setters: void setData(QCPColorMapData *data, bool copy=false); Q_SLOT void setDataRange(const QCPRange &dataRange); Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); Q_SLOT void setGradient(const QCPColorGradient &gradient); void setInterpolate(bool enabled); void setTightBoundary(bool enabled); void setColorScale(QCPColorScale *colorScale); // non-property methods: void rescaleDataRange(bool recalculateDataBounds=false); Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); // reimplemented virtual methods: virtual void clearData(); virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; signals: void dataRangeChanged(QCPRange newRange); void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); void gradientChanged(QCPColorGradient newGradient); protected: // property members: QCPRange mDataRange; QCPAxis::ScaleType mDataScaleType; QCPColorMapData *mMapData; QCPColorGradient mGradient; bool mInterpolate; bool mTightBoundary; QPointer mColorScale; // non-property members: QImage mMapImage; QPixmap mLegendIcon; bool mMapImageInvalidated; // introduced virtual methods: virtual void updateMapImage(); // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; friend class QCustomPlot; friend class QCPLegend; }; class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: QCPItemStraightLine(QCustomPlot *parentPlot); virtual ~QCPItemStraightLine(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const point1; QCPItemPosition * const point2; protected: // property members: QPen mPen, mSelectedPen; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: double distToStraightLine(const QVector2D &point1, const QVector2D &vec, const QVector2D &point) const; QLineF getRectClippedStraightLine(const QVector2D &point1, const QVector2D &vec, const QRect &rect) const; QPen mainPen() const; }; class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: QCPItemLine(QCustomPlot *parentPlot); virtual ~QCPItemLine(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QCPLineEnding head() const { return mHead; } QCPLineEnding tail() const { return mTail; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setHead(const QCPLineEnding &head); void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const start; QCPItemPosition * const end; protected: // property members: QPen mPen, mSelectedPen; QCPLineEnding mHead, mTail; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; QPen mainPen() const; }; class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) /// \endcond public: QCPItemCurve(QCustomPlot *parentPlot); virtual ~QCPItemCurve(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QCPLineEnding head() const { return mHead; } QCPLineEnding tail() const { return mTail; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setHead(const QCPLineEnding &head); void setTail(const QCPLineEnding &tail); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const start; QCPItemPosition * const startDir; QCPItemPosition * const endDir; QCPItemPosition * const end; protected: // property members: QPen mPen, mSelectedPen; QCPLineEnding mHead, mTail; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: QPen mainPen() const; }; class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: QCPItemRect(QCustomPlot *parentPlot); virtual ~QCPItemRect(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemText : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) Q_PROPERTY(QString text READ text WRITE setText) Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) Q_PROPERTY(double rotation READ rotation WRITE setRotation) Q_PROPERTY(QMargins padding READ padding WRITE setPadding) /// \endcond public: QCPItemText(QCustomPlot *parentPlot); virtual ~QCPItemText(); // getters: QColor color() const { return mColor; } QColor selectedColor() const { return mSelectedColor; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } QFont font() const { return mFont; } QFont selectedFont() const { return mSelectedFont; } QString text() const { return mText; } Qt::Alignment positionAlignment() const { return mPositionAlignment; } Qt::Alignment textAlignment() const { return mTextAlignment; } double rotation() const { return mRotation; } QMargins padding() const { return mPadding; } // setters; void setColor(const QColor &color); void setSelectedColor(const QColor &color); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setFont(const QFont &font); void setSelectedFont(const QFont &font); void setText(const QString &text); void setPositionAlignment(Qt::Alignment alignment); void setTextAlignment(Qt::Alignment alignment); void setRotation(double degrees); void setPadding(const QMargins &padding); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const position; QCPItemAnchor * const topLeft; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottomRight; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QColor mColor, mSelectedColor; QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; QFont mFont, mSelectedFont; QString mText; Qt::Alignment mPositionAlignment; Qt::Alignment mTextAlignment; double mRotation; QMargins mPadding; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; QFont mainFont() const; QColor mainColor() const; QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) /// \endcond public: QCPItemEllipse(QCustomPlot *parentPlot); virtual ~QCPItemEllipse(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const topLeftRim; QCPItemAnchor * const top; QCPItemAnchor * const topRightRim; QCPItemAnchor * const right; QCPItemAnchor * const bottomRightRim; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeftRim; QCPItemAnchor * const left; QCPItemAnchor * const center; protected: enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) Q_PROPERTY(bool scaled READ scaled WRITE setScaled) Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) /// \endcond public: QCPItemPixmap(QCustomPlot *parentPlot); virtual ~QCPItemPixmap(); // getters: QPixmap pixmap() const { return mPixmap; } bool scaled() const { return mScaled; } Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } // setters; void setPixmap(const QPixmap &pixmap); void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio); void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const topLeft; QCPItemPosition * const bottomRight; QCPItemAnchor * const top; QCPItemAnchor * const topRight; QCPItemAnchor * const right; QCPItemAnchor * const bottom; QCPItemAnchor * const bottomLeft; QCPItemAnchor * const left; protected: enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; // property members: QPixmap mPixmap; QPixmap mScaledPixmap; bool mScaled; Qt::AspectRatioMode mAspectRatioMode; QPen mPen, mSelectedPen; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false); QRect getFinalRect(bool *flippedHorz=0, bool *flippedVert=0) const; QPen mainPen() const; }; class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(QBrush brush READ brush WRITE setBrush) Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) Q_PROPERTY(double size READ size WRITE setSize) Q_PROPERTY(TracerStyle style READ style WRITE setStyle) Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) /// \endcond public: /*! The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. \see setStyle */ enum TracerStyle { tsNone ///< The tracer is not visible ,tsPlus ///< A plus shaped crosshair with limited size ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect ,tsCircle ///< A circle ,tsSquare ///< A square }; Q_ENUMS(TracerStyle) QCPItemTracer(QCustomPlot *parentPlot); virtual ~QCPItemTracer(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } QBrush brush() const { return mBrush; } QBrush selectedBrush() const { return mSelectedBrush; } double size() const { return mSize; } TracerStyle style() const { return mStyle; } QCPGraph *graph() const { return mGraph; } double graphKey() const { return mGraphKey; } bool interpolating() const { return mInterpolating; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setBrush(const QBrush &brush); void setSelectedBrush(const QBrush &brush); void setSize(double size); void setStyle(TracerStyle style); void setGraph(QCPGraph *graph); void setGraphKey(double key); void setInterpolating(bool enabled); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; // non-virtual methods: void updatePosition(); QCPItemPosition * const position; protected: // property members: QPen mPen, mSelectedPen; QBrush mBrush, mSelectedBrush; double mSize; TracerStyle mStyle; QCPGraph *mGraph; double mGraphKey; bool mInterpolating; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); // non-virtual methods: QPen mainPen() const; QBrush mainBrush() const; }; class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem { Q_OBJECT /// \cond INCLUDE_QPROPERTIES Q_PROPERTY(QPen pen READ pen WRITE setPen) Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) Q_PROPERTY(double length READ length WRITE setLength) Q_PROPERTY(BracketStyle style READ style WRITE setStyle) /// \endcond public: enum BracketStyle { bsSquare ///< A brace with angled edges ,bsRound ///< A brace with round edges ,bsCurly ///< A curly brace ,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression }; QCPItemBracket(QCustomPlot *parentPlot); virtual ~QCPItemBracket(); // getters: QPen pen() const { return mPen; } QPen selectedPen() const { return mSelectedPen; } double length() const { return mLength; } BracketStyle style() const { return mStyle; } // setters; void setPen(const QPen &pen); void setSelectedPen(const QPen &pen); void setLength(double length); void setStyle(BracketStyle style); // reimplemented virtual methods: virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; QCPItemPosition * const left; QCPItemPosition * const right; QCPItemAnchor * const center; protected: // property members: enum AnchorIndex {aiCenter}; QPen mPen, mSelectedPen; double mLength; BracketStyle mStyle; // reimplemented virtual methods: virtual void draw(QCPPainter *painter); virtual QPointF anchorPixelPoint(int anchorId) const; // non-virtual methods: QPen mainPen() const; }; #endif // QCUSTOMPLOT_H ================================================ FILE: DynamicAudioNormalizerGUI/src/Main.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License 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/gpl-3.0.txt ////////////////////////////////////////////////////////////////////////////////// //Std #include #include //Qt #include #include #include #include #include #include #include #include #include #include //MDynamicAudioNormalizer API #include "DynamicAudioNormalizer.h" //Internal #include "3rd_party/qcustomplot.h" //Const static const int PRE_ALLOC_SIZE = 12000; static const QLatin1String g_title("Dynamic Audio Normalizer GUI"); typedef struct { QVector original; QVector minimal; QVector smoothed; } LogFileData; static void makeAxisBold(QCPAxis *axis) { QFont font = axis->labelFont(); font.setBold(true); axis->setLabelFont(font); } static QString readNextLine(QTextStream &textStream) { while ((!textStream.atEnd()) && (textStream.status() == QTextStream::Ok)) { const QString line = textStream.readLine().simplified(); if (!line.isEmpty()) { return line; } } return QString(); } static bool parseHeader(QWidget &parent, QTextStream &textStream, quint32 &channels, const uint32_t versionMajor, const uint32_t versionMinor) { static const QLatin1String REGEX_HEADER("^\\s*DynamicAudioNormalizer\\s+Logfile\\s+v(\\d).(\\d\\d)-(\\d)\\s*$"); static const QLatin1String REGEX_CHNNLS("^\\s*CHANNEL_COUNT\\s*:\\s*(\\d+)\\s*$"); QRegExp header(REGEX_HEADER, Qt::CaseInsensitive); QRegExp channelCount(REGEX_CHNNLS, Qt::CaseInsensitive); const QString headerLine = readNextLine(textStream); if(headerLine.isEmpty() || (header.indexIn(headerLine) < 0)) { QMessageBox::warning(&parent, g_title, QLatin1String("Invalid file: Header line could not be found!")); return false; } bool okay[2] = { false, false }; uint32_t fileVersion[2]; fileVersion[0] = header.cap(1).toUInt(&okay[0]); fileVersion[1] = header.cap(2).toUInt(&okay[1]); if ((!(okay[0] && okay[1])) || (fileVersion[0] != versionMajor) || (fileVersion[1] > versionMinor)) { QMessageBox::warning(&parent, g_title, QLatin1String("Invalid file: Unsupported file format version!")); return false; } const QString channelLine = readNextLine(textStream); if(channelLine.isEmpty() || (channelCount.indexIn(channelLine) < 0)) { QMessageBox::warning(&parent, g_title, QLatin1String("Invalid file: Number of channels could not be found!")); return false; } bool haveChannels = false; channels = channelCount.cap(1).toUInt(&haveChannels); if ((!haveChannels) || (channels < 1)) { QMessageBox::warning(&parent, g_title, QLatin1String("Invalid file: Number of channels is invalid!")); return false; } return true; /*success*/ } static bool parseLine(const quint32 channels, const QStringList &input, QVector &output) { const int minLength = qMin(input.count(), output.count()); QVector::Iterator outputIter = output.begin(); QStringList::ConstIterator inputIter = input.constBegin(); for (int i = 0; i < minLength; ++i) { bool okay = false; *(outputIter++) = (inputIter++)->toDouble(&okay); if (!okay) { return false; } } return true; /*success*/ } static void parseData(QTextStream &textStream, const quint32 channels, LogFileData *data, double &minValue, double &maxValue) { const QRegExp spaces(QLatin1String("\\s+")); QVector temp(channels * 3U); forever { const QString line = readNextLine(textStream); if(!line.isEmpty()) { const QStringList tokens = line.split(spaces, QString::SkipEmptyParts); if ((quint32)tokens.count() >= (channels * 3U)) { if (parseLine(channels, tokens, temp)) { QVector::ConstIterator tempIter = temp.constBegin(); for (quint32 c = 0; c < channels; c++) { data[c].original.append(*(tempIter++)); data[c].minimal .append(*(tempIter++)); data[c].smoothed.append(*(tempIter++)); minValue = qMin(qMin(minValue, data[c].original.back()), qMin(data[c].minimal.back(), data[c].smoothed.back())); maxValue = qMax(qMax(maxValue, data[c].original.back()), qMax(data[c].minimal.back(), data[c].smoothed.back())); } } } continue; } break; /*end of file*/ } } static void createGraph(QCustomPlot *const plot, QVector &steps, QVector &data, const Qt::GlobalColor &color, const Qt::PenStyle &style, const int width) { QCPGraph *graph = plot->addGraph(); QPen pen(color); pen.setStyle(style); pen.setWidth(width); graph->setPen(pen); graph->setData(steps, data); } static int dynamicNormalizerGuiMain(int argc, char* argv[]) { uint32_t versionMajor, versionMinor, versionPatch; MDynamicAudioNormalizer::getVersionInfo(versionMajor, versionMinor, versionPatch); const char *buildDate, *buildTime, *buildCompiler, *buildArch; bool buildDebug; MDynamicAudioNormalizer::getBuildInfo(&buildDate, &buildTime, &buildCompiler, &buildArch, buildDebug); //initialize application QApplication app(argc, argv); app.setWindowIcon(QIcon(QLatin1String(":/res/chart_curve.png"))); app.setStyle(new QPlastiqueStyle()); app.setStyleSheet(QLatin1String("QStatusBar::item{border:none}")); //create basic tab widget QMainWindow window; window.setWindowTitle(QString::fromLatin1("Dynamic Audio Normalizer - Log Viewer [%1]").arg(QString().sprintf("v%u.%02u-%u", versionMajor, versionMinor, versionPatch))); window.setMinimumSize(640, 480); window.setContentsMargins(5, 5, 5, 5); //create statusbar widget QStatusBar statusbar; QLabel info(QString("Copyright (c) 2014-%1 LoRd_MuldeR | License: GNU General Public License v3").arg(QString::fromLatin1(&buildDate[7]))); statusbar.addPermanentWidget(&info); window.setStatusBar(&statusbar); //show the window window.show(); //get arguments const QStringList args = app.arguments(); //choose input file const QString logFileName = (args.size() < 2) ? QFileDialog::getOpenFileName(&window, QLatin1String("Open Log File"), QString(), QLatin1String("Log File (*.log)")) : args.at(1); if(logFileName.isEmpty()) { return EXIT_FAILURE; } //check for existence if(!(QFileInfo(logFileName).exists() && QFileInfo(logFileName).isFile())) { QMessageBox::critical(&window, g_title, QLatin1String("Error: The specified log file could not be found!")); return EXIT_FAILURE; } //open the input file QFile logFile(logFileName); if(!logFile.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::critical(&window, g_title, QLatin1String("Error: The selected log file could not opened for reading!")); return EXIT_FAILURE; } //wrap into text stream QTextStream textStream(&logFile); textStream.setCodec("UTF-8"); quint32 channels = 0; double minValue = DBL_MAX; double maxValue = 0.0; //parse header if(!parseHeader(window, textStream, channels, versionMajor, versionMinor)) { QMessageBox::critical(&window, g_title, QLatin1String("Error: Failed to parse the header of the selected log file!\nProbably this file is corrupted or an unsupported type.")); return EXIT_FAILURE; } //allocate buffers QVector data(channels); for (quint32 c = 0; c < channels; c++) { data[c].original.reserve(PRE_ALLOC_SIZE); data[c].minimal .reserve(PRE_ALLOC_SIZE); data[c].smoothed.reserve(PRE_ALLOC_SIZE); } //load data parseData(textStream, channels, data.data(), minValue, maxValue); logFile.close(); //check data if((data[0].original.size() < 1) || (data[0].minimal.size() < 1) || (data[0].smoothed.size() < 1)) { QMessageBox::critical(&window, g_title, QLatin1String("Error: Failed to load data from log file.\nFile countains no valid data points!")); return EXIT_FAILURE; } //determine length of data quint32 length = UINT_MAX; for(quint32 c = 0; c < channels; c++) { length = qMin(length, (quint32)data[c].original.count()); length = qMin(length, (quint32)data[c].minimal .count()); length = qMin(length, (quint32)data[c].smoothed.count()); } //create x-axis steps QVector steps(length); for(quint32 i = 0; i < length; i++) { steps[i] = double(i); } //Create tab widget QTabWidget tabWidget(&window); window.setCentralWidget(&tabWidget); //now create the plots QVector plot(channels, NULL); for(quint32 c = 0; c < channels; c++) { //create new instance plot[c] = new QCustomPlot(&window); //init the legend plot[c]->legend->setVisible(true); plot[c]->legend->setFont(QFont(QLatin1String("Helvetica"), 9)); //create graph and assign data to it: createGraph(plot[c], steps, data[c].original, Qt::blue, Qt::SolidLine, 1); createGraph(plot[c], steps, data[c].minimal, Qt::green, Qt::SolidLine, 1); createGraph(plot[c], steps, data[c].smoothed, Qt::red, Qt::DashLine, 2); //set plot names plot[c]->graph(0)->setName(QLatin1String("Local Max. Gain")); plot[c]->graph(1)->setName(QLatin1String("Minimum Filtered")); plot[c]->graph(2)->setName(QLatin1String("Final Smoothed")); //set axes labels: plot[c]->xAxis->setLabel(QLatin1String("Frame #")); plot[c]->yAxis->setLabel(QLatin1String("Gain Factor")); makeAxisBold(plot[c]->xAxis); makeAxisBold(plot[c]->yAxis); //set axes ranges plot[c]->xAxis->setRange(0.0, length); plot[c]->yAxis->setRange(minValue - 0.25, maxValue + 0.25); plot[c]->yAxis->setScaleType(QCPAxis::stLinear); plot[c]->yAxis->setTickStep(1.0); plot[c]->yAxis->setAutoTickStep(false); //add title plot[c]->plotLayout()->insertRow(0); plot[c]->plotLayout()->addElement(0, 0, new QCPPlotTitle(plot[c], QString::fromLatin1("%1 (Channel %2/%3)").arg(QFileInfo(logFile).fileName(), QString::number(c+1), QString::number(channels)))); //show the plot plot[c]->replot(); tabWidget.addTab(plot[c], QString().sprintf("Channel #%u", c + 1)); } //run application window.showMaximized(); app.exec(); //clean-up for (QVector::Iterator iter = plot.begin(); iter != plot.end(); ++iter) { if (*iter) { delete *iter; *iter = NULL; } } return EXIT_SUCCESS; } int main(int argc, char* argv[]) { int exitCode = EXIT_SUCCESS; try { exitCode = dynamicNormalizerGuiMain(argc, argv); } catch(std::exception &e) { fprintf(stderr, "\n\nGURU MEDITATION: Unhandeled C++ exception error: %s\n\n", e.what()); exitCode = EXIT_FAILURE; } catch(...) { fprintf(stderr, "\n\nGURU MEDITATION: Unhandeled unknown C++ exception error!\n\n"); exitCode = EXIT_FAILURE; } return exitCode; } ================================================ FILE: DynamicAudioNormalizerGUI/src/WinMain.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Utility // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License 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/gpl-3.0.txt ////////////////////////////////////////////////////////////////////////////////// #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include //=================================================================== // WinMain entry point //=================================================================== static LONG WINAPI my_exception_handler(struct _EXCEPTION_POINTERS*) { FatalAppExitW(0, L"GURU MEDITATION: Unhandeled exception handler invoked, application will exit!\n"); TerminateProcess(GetCurrentProcess(), 666); return EXCEPTION_EXECUTE_HANDLER; } extern "C" { int mainCRTStartup(void); int win32EntryPoint(void) { #ifndef _DEBUG SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX); SetUnhandledExceptionFilter(my_exception_handler); #endif return mainCRTStartup(); } } #endif //_WIN32 ================================================ FILE: DynamicAudioNormalizerJNI/.classpath ================================================ ================================================ FILE: DynamicAudioNormalizerJNI/.project ================================================ DynamicAudioNormalizerJNI org.eclipse.jdt.core.javabuilder org.eclipse.jdt.core.javanature ================================================ FILE: DynamicAudioNormalizerJNI/build.xml ================================================ ================================================ FILE: DynamicAudioNormalizerJNI/generate_headers.bat ================================================ @echo off if not exist "%JAVA_HOME%\bin\javah.exe" ( echo Could not find 'javah.exe', please check your JDK_PATH environment variable! pause & exit ) echo Generating JNI headers, please stand by... echo. mkdir "%~dp0\include" 2> NUL del /F /Q "%~dp0\include\*.h" 2> NUL "%JAVA_HOME%\bin\javah.exe" -d "%~dp0\include" -cp "%~dp0\bin" com.muldersoft.dynaudnorm.JDynamicAudioNormalizer if not "%ERRORLEVEL%"=="0" ( echo. echo Whoops: Something went wrong !!! echo. goto TheEndMyFriend ) echo Completed. echo. :TheEndMyFriend pause ================================================ FILE: DynamicAudioNormalizerJNI/include/com_muldersoft_dynaudnorm_JDynamicAudioNormalizer.h ================================================ /* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class com_muldersoft_dynaudnorm_JDynamicAudioNormalizer */ #ifndef _Included_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer #define _Included_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif #endif ================================================ FILE: DynamicAudioNormalizerJNI/include/com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error.h ================================================ /* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error */ #ifndef _Included_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error #define _Included_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error #ifdef __cplusplus extern "C" { #endif #undef com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error_serialVersionUID #define com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error_serialVersionUID -3042686055658047285i64 #undef com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error_serialVersionUID #define com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error_serialVersionUID -3387516993124229948i64 #undef com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error_serialVersionUID #define com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error_serialVersionUID -7034897190745766939i64 #undef com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error_serialVersionUID #define com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Error_serialVersionUID 8560360516304094422i64 #ifdef __cplusplus } #endif #endif ================================================ FILE: DynamicAudioNormalizerJNI/include/com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Logger.h ================================================ /* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Logger */ #ifndef _Included_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Logger #define _Included_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_Logger #ifdef __cplusplus extern "C" { #endif #ifdef __cplusplus } #endif #endif ================================================ FILE: DynamicAudioNormalizerJNI/include/com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8.h ================================================ /* DO NOT EDIT THIS FILE - it is machine generated */ #include /* Header for class com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 */ #ifndef _Included_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 #define _Included_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 #ifdef __cplusplus extern "C" { #endif /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: getVersionInfo * Signature: ([I)Z */ JNIEXPORT jboolean JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_getVersionInfo (JNIEnv *, jobject, jintArray); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: getBuildInfo * Signature: (Ljava/util/Map;)Z */ JNIEXPORT jboolean JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_getBuildInfo (JNIEnv *, jobject, jobject); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: setLoggingHandler * Signature: (Lcom/muldersoft/dynaudnorm/JDynamicAudioNormalizer/Logger;)Z */ JNIEXPORT jboolean JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_setLoggingHandler (JNIEnv *, jobject, jobject); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: createInstance * Signature: (IIIIDDDDZZZ)I */ JNIEXPORT jint JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_createInstance (JNIEnv *, jobject, jint, jint, jint, jint, jdouble, jdouble, jdouble, jdouble, jboolean, jboolean, jboolean); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: destroyInstance * Signature: (I)Z */ JNIEXPORT jboolean JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_destroyInstance (JNIEnv *, jobject, jint); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: process * Signature: (I[[D[[DJ)J */ JNIEXPORT jlong JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_process (JNIEnv *, jobject, jint, jobjectArray, jobjectArray, jlong); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: processInplace * Signature: (I[[DJ)J */ JNIEXPORT jlong JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_processInplace (JNIEnv *, jobject, jint, jobjectArray, jlong); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: flushBuffer * Signature: (I[[D)J */ JNIEXPORT jlong JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_flushBuffer (JNIEnv *, jobject, jint, jobjectArray); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: reset * Signature: (I)Z */ JNIEXPORT jboolean JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_reset (JNIEnv *, jobject, jint); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: getConfiguration * Signature: (ILjava/util/Map;)Z */ JNIEXPORT jboolean JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_getConfiguration (JNIEnv *, jobject, jint, jobject); /* * Class: com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_NativeAPI_r8 * Method: getInternalDelay * Signature: (I)J */ JNIEXPORT jlong JNICALL Java_com_muldersoft_dynaudnorm_JDynamicAudioNormalizer_00024NativeAPI_1r8_getInternalDelay (JNIEnv *, jobject, jint); #ifdef __cplusplus } #endif #endif ================================================ FILE: DynamicAudioNormalizerJNI/makefile ================================================ ############################################################################## # Dynamic Audio Normalizer - Audio Processing Library # Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # http://www.gnu.org/licenses/lgpl-2.1.txt ############################################################################## ECHO=echo -e SHELL=/bin/bash ANT ?= ant ############################################################################## # Ant Checks ############################################################################## ifneq ($(MAKECMDGOALS),clean) ANT_CHECK = $(findstring Apache Ant,$(shell $(ANT) -version 2>&1)) ifneq ($(ANT_CHECK),Apache Ant) $(error Apache Ant not found. Please set ANT environment variable properly!) endif endif ############################################################################## # Rules ############################################################################## SOURCES_CPP = $(wildcard src/*.cpp) SOURCES_OBJ = $(patsubst %.cpp,%.o,$(SOURCES_CPP)) LIBRARY_OUT = lib/$(LIBRARY_NAME)-$(API_VERSION) LIBRARY_BIN = $(LIBRARY_OUT).so LIBRARY_DBG = $(LIBRARY_OUT)-DBG.so ############################################################################## # Rules ############################################################################## .PHONY: all clean #------------------------------------------------------------- # Compile #------------------------------------------------------------- all: build.xml @$(ECHO) "\e[1;36m[ANT] $<\e[0m" $(ANT) -buildfile $< #------------------------------------------------------------- # Clean #------------------------------------------------------------- clean: build.xml @$(ECHO) "\e[1;36m[ANT] $< clean\e[0m" $(ANT) -buildfile $< clean || echo "Ant clean failed!" rm -rfv ./bin rm -rfv ./out ================================================ FILE: DynamicAudioNormalizerJNI/samples/com/muldersoft/dynaudnorm/samples/AudioFileIO.java ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Java/JNI Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// package com.muldersoft.dynaudnorm.samples; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.ByteOrder; public class AudioFileIO { public enum PCMFileType { PCM_16BIT_LE, PCM_16BIT_BE, PCM_32BIT_LE, PCM_32BIT_BE, PCM_64BIT_LE, PCM_64BIT_BE, } private static class PCMFileBase { protected static ByteOrder getEndianess(final PCMFileType type) { switch(type) { case PCM_16BIT_LE: case PCM_32BIT_LE: case PCM_64BIT_LE: return ByteOrder.LITTLE_ENDIAN; case PCM_32BIT_BE: case PCM_16BIT_BE: case PCM_64BIT_BE: return ByteOrder.BIG_ENDIAN; default: throw new IllegalArgumentException(); } } protected static int getSampleSize(final PCMFileType type) { switch(type) { case PCM_16BIT_LE: case PCM_16BIT_BE: return 2; case PCM_32BIT_LE: case PCM_32BIT_BE: return 4; case PCM_64BIT_LE: case PCM_64BIT_BE: return 8; default: throw new IllegalArgumentException(); } } protected static double readSample(final PCMFileType type, final ByteBuffer input) { switch(type) { case PCM_16BIT_LE: case PCM_16BIT_BE: return ShortToDouble(input.getShort()); case PCM_32BIT_LE: case PCM_32BIT_BE: return input.getFloat(); case PCM_64BIT_LE: case PCM_64BIT_BE: return input.getDouble(); default: throw new IllegalArgumentException(); } } protected static ByteBuffer writeSample(final PCMFileType type, final ByteBuffer output, final double value) { switch(type) { case PCM_16BIT_LE: case PCM_16BIT_BE: return output.putShort(doubleToShort(value)); case PCM_32BIT_LE: case PCM_32BIT_BE: return output.putFloat((float)value); case PCM_64BIT_LE: case PCM_64BIT_BE: return output.putDouble(value); default: throw new IllegalArgumentException(); } } private static double ShortToDouble(final short val) { return ((double) val) / ((double) Short.MAX_VALUE); } private static short doubleToShort(final double val) { return (short) Math.round(Math.max(-1.0, Math.min(1.0, val)) * ((double) Short.MAX_VALUE)); } } public static class PCMFileReader extends PCMFileBase implements AutoCloseable { private final PCMFileType type; private final int channels; private final BufferedInputStream inputStream; private byte[] tempBuffer = null; public PCMFileReader(final String fileName, final int channels, final PCMFileType type) throws IOException { if((channels < 1) || (channels > 8)) { throw new IllegalArgumentException("Invalid number of channels!"); } this.type = type; this.channels = channels; inputStream = new BufferedInputStream(new FileInputStream(new File(fileName))); } public int read(double[][] buffer) throws IOException { if (buffer.length < channels) { throw new RuntimeException("Output array dimension must match channels!"); } int buffSize = Integer.MAX_VALUE; for(int c = 0; c < channels; c++) { if((buffSize = Math.min(buffSize, buffer[c].length)) < 1) { throw new RuntimeException("Output array length must be at least one!"); } } final int frameSize = getSampleSize(type) * channels; final int maxReadSize = buffSize * frameSize; if ((tempBuffer == null) || (tempBuffer.length < maxReadSize)) { tempBuffer = new byte[maxReadSize]; } final int byteCount = inputStream.read(tempBuffer, 0, maxReadSize); if((byteCount % frameSize) != 0) { throw new RuntimeException("Number of bytes is not a multiple of frame size!"); } final int sampleCount = byteCount / frameSize; if (sampleCount > 0) { ByteBuffer byteBuffer = ByteBuffer.wrap(tempBuffer); byteBuffer.order(getEndianess(type)); for (int i = 0; i < sampleCount; i++) { for (int c = 0; c < channels; c++) { buffer[c][i] = readSample(type, byteBuffer); } } } return sampleCount; } public void close() throws IOException { inputStream.close(); } } // ------------------------------------------------------------------------------------------------ // PCM File Writer // ------------------------------------------------------------------------------------------------ public static class PCMFileWriter extends PCMFileBase implements AutoCloseable { private final PCMFileType type; private final int channels; private final BufferedOutputStream outputStream; private byte[] tempBuffer = null; public PCMFileWriter(final String fileName, final int channels, final PCMFileType type) throws IOException { if((channels < 1) || (channels > 8)) { throw new IllegalArgumentException("Invalid number of channels!"); } this.type = type; this.channels = channels; outputStream = new BufferedOutputStream(new FileOutputStream(new File(fileName))); } public void write(double[][] buffer, final int sampleCount) throws IOException { if (buffer.length < channels) { throw new IOException("Input array dimension must match channels!"); } for(int c = 0; c < channels; c++) { if(buffer[c].length < sampleCount) { throw new RuntimeException("Input array length must be greater or equal to sampleCount!"); } } final int frameSize = getSampleSize(type) * channels; final int writeSize = sampleCount * frameSize; if ((tempBuffer == null) || (tempBuffer.length < writeSize)) { tempBuffer = new byte[writeSize]; } if (sampleCount > 0) { ByteBuffer byteBuffer = ByteBuffer.wrap(tempBuffer); byteBuffer.order(getEndianess(type)); for (int i = 0; i < sampleCount; i++) { for (int c = 0; c < channels; c++) { writeSample(type, byteBuffer, buffer[c][i]); } } } outputStream.write(tempBuffer, 0, writeSize); } public void flush() throws IOException { outputStream.flush(); } public void close() throws IOException { flush(); outputStream.close(); } } } ================================================ FILE: DynamicAudioNormalizerJNI/samples/com/muldersoft/dynaudnorm/samples/DynamicAudioNormalizerExample.java ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Java/JNI Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// package com.muldersoft.dynaudnorm.samples; import java.io.IOException; import java.security.NoSuchAlgorithmException; import java.util.Map; import com.muldersoft.dynaudnorm.JDynamicAudioNormalizer; public class DynamicAudioNormalizerExample { //Default arguments private static final int CHANNELS_DEFAULT = 2; private static final int SAMPLE_RATE_DEFAULT = 44100; private static final AudioFileIO.PCMFileType AUDIO_FORMAT_DEFAULT = AudioFileIO.PCMFileType.PCM_16BIT_LE; //Normalizer options private static final int FRAME_LEN = 500; //Frame length in MSec private static final int FILTER_SIZE = 31; //Filter size in frames //------------------------------------------------------------------------------------------------ // Print Logo //------------------------------------------------------------------------------------------------ private static void printLogo() { int [] version = null; Map buildInfo = null; try { try { version = JDynamicAudioNormalizer.getVersionInfo(); buildInfo = JDynamicAudioNormalizer.getBuildInfo(); } catch(Exception ex) { throw new Error("Failed to initialize DynamicAudioNormalizer library!", ex); } } finally { System.out.println("\n==========================================================================="); if((version != null) && (version.length >= 3)) { System.out.printf("Dynamic Audio Normalizer, Version %d.%02d-%d\n", version[0], version[1], version[2]); } else { System.out.println("Dynamic Audio Normalizer, Unknown Version"); } if((buildInfo != null) && buildInfo.containsKey("BuildDate")) { System.out.printf("Copyright (c) 2014-%s LoRd_MuldeR . Some rights reserved.\n", buildInfo.get("BuildDate").substring(7)); } else { System.out.println("Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved."); } System.out.println(); System.out.println("This program is free software: you can redistribute it and/or modify"); System.out.println("it under the terms of the GNU General Public License ."); System.out.println("Note that this program is distributed with ABSOLUTELY NO WARRANTY."); System.out.println("===========================================================================\n"); } } //------------------------------------------------------------------------------------------------ // Processing Loop //------------------------------------------------------------------------------------------------ public static void processFile(final String inputFile, final String outputFile, final int channles, final int sampleRate, final AudioFileIO.PCMFileType audioFormat) throws NoSuchAlgorithmException, IOException { // Open input and output files System.out.print("Opening input and out files..."); try(AudioFileIO.PCMFileReader reader = new AudioFileIO.PCMFileReader(inputFile, channles, audioFormat)) { try (AudioFileIO.PCMFileWriter writer = new AudioFileIO.PCMFileWriter(outputFile, channles, audioFormat)) { double[][] sampleBuffer = new double[channles][4096]; System.out.print(" Done!\nCreating normalizer instance..."); try(final JDynamicAudioNormalizer instance = new JDynamicAudioNormalizer(channles, sampleRate, FRAME_LEN, FILTER_SIZE, 0.95, 10.0, 0.0, 0.0, true, false, false)) { // Process samples System.out.print(" Done!\nProcessing input samples..."); int progressUpdate = 0; for (;;) { int sampleCount = 0; try { sampleCount = reader.read(sampleBuffer); } catch (IOException e) { throw new IOException("Failed to read data from input file!", e); } if (sampleCount > 0) { final long outputSamples = instance.processInplace(sampleBuffer, sampleCount); if (outputSamples > 0) { try { writer.write(sampleBuffer, (int) outputSamples); } catch (IOException e) { throw new IOException("Failed to write data to output file!", e); } } if(++progressUpdate >= 13) { progressUpdate = 0; System.out.print("."); } } if (sampleCount < sampleBuffer[0].length) { break; /* EOF reached */ } } // Flush pending samples System.out.print(" Done!\nFlushing remaining samples..."); for (;;) { final long outputSamples = instance.flushBuffer(sampleBuffer); if (outputSamples > 0) { try { writer.write(sampleBuffer, (int) outputSamples); } catch (IOException e) { throw new IOException("Failed to write data to output file!", e); } if(++progressUpdate >= 13) { progressUpdate = 0; System.out.print("."); } } else { break; /* No more samples */ } } // Reset System.out.print(" Done!\nResetting normalizer instance..."); instance.reset(); /* This is NOT normally required, but we do it here to test the reset() API */ // Close input and output System.out.print(" Done!\nShutting down..."); /*Implicitly, due to AutoCloseable*/ } } } // Finished System.out.println(" Done!\n\nAll done. Goodbye."); } //------------------------------------------------------------------------------------------------ // Main //------------------------------------------------------------------------------------------------ public static void main(final String [] args) { try { //Print program logo printLogo(); //Check number of arguments if(args.length < 2) { System.out.println("Usage:"); System.out.println(" java -jar Example.jar [ [ []]] "); System.exit(-1); } //Initialize arguments to default values int channels = CHANNELS_DEFAULT; int sampleRate = SAMPLE_RATE_DEFAULT; AudioFileIO.PCMFileType audioFormat = AUDIO_FORMAT_DEFAULT; //Parse optional arguments from command-line try { if(args.length > 2) { channels = Integer.parseInt(args[0]); if(args.length > 3) { sampleRate = Integer.parseInt(args[1]); if(args.length > 4) { audioFormat = AudioFileIO.PCMFileType.valueOf(args[2]); } } } } catch(Exception e) { throw new IllegalArgumentException("Invalid command-line argument given!", e); } //Process the audio file final int offset = Math.min(args.length, 5) - 2; processFile(args[offset], args[offset + 1], channels, sampleRate, audioFormat); } catch(Throwable e) { System.err.println("\n\nERROR: " + e.getMessage() + "\n"); e.printStackTrace(System.err); } } } ================================================ FILE: DynamicAudioNormalizerJNI/src/com/muldersoft/dynaudnorm/JDynamicAudioNormalizer.java ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Java/JNI Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// package com.muldersoft.dynaudnorm; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JDynamicAudioNormalizer implements AutoCloseable { //------------------------------------------------------------------------------------------------ // Exception class //------------------------------------------------------------------------------------------------ public static class Error extends RuntimeException { private static final long serialVersionUID = 8560360516304094422L; public Error(String string) { super(string); } } //------------------------------------------------------------------------------------------------ // Logging interface //------------------------------------------------------------------------------------------------ public static abstract class Logger { public abstract void log(final int level, final String message); } //------------------------------------------------------------------------------------------------ // Native API //------------------------------------------------------------------------------------------------ private static class NativeAPI_r8 { static NativeAPI_r8 nativeAPI = null; //Singelton public static synchronized NativeAPI_r8 getInstance() { if(nativeAPI == null) { nativeAPI = new NativeAPI_r8(); } return nativeAPI; } //Load native library at runtime private NativeAPI_r8() { try { final int coreVersion = getCoreVersion(); System.loadLibrary((coreVersion > 0) ? String.format("DynamicAudioNormalizerAPI-%d", coreVersion) : "DynamicAudioNormalizerAPI"); } catch(Throwable e) { handleError(e, "Failed to load native DynamicAudioNormalizerAPI library!"); } } //Detect the library "core" version private int getCoreVersion() { int coreVersion = -1; try { if(!System.getProperty("os.name").toLowerCase().startsWith("win")) { final Pattern pattern = Pattern.compile(".+\\$NativeAPI_r(\\d+)$"); final Matcher matcher = pattern.matcher(this.getClass().getName()); if(matcher.matches()) { coreVersion = Integer.parseInt(matcher.group(1)); } } } catch(Throwable e) { handleError(e, "Failed to determine DynamicAudioNormalizerAPI core version!"); } return coreVersion; } //Static Functions private native boolean getVersionInfo(final int versionInfo[]); private native boolean getBuildInfo(final Map buildInfo); private native boolean setLoggingHandler(final Logger logger); //Create or Destroy Instance private native int createInstance(final int channels, final int sampleRate, final int frameLenMsec, final int filterSize, final double peakValue, final double maxAmplification, final double targetRms, final double compressFactor, final boolean channelsCoupled, final boolean enableDCCorrection, final boolean altBoundaryMode); private native boolean destroyInstance(final int handle); //Processing Functions private native long process(final int handle, final double [][] samplesIn, final double [][] samplesOut, final long inputSize); private native long processInplace(final int handle, final double [][] samplesInOut, final long inputSize); private native long flushBuffer(final int handle, final double [][] samplesOut); private native boolean reset(final int handle); //Other Functions private native boolean getConfiguration(final int handle, final Map buildInfo); private native long getInternalDelay(final int handle); } //------------------------------------------------------------------------------------------------ // Static Functions //------------------------------------------------------------------------------------------------ public static synchronized int[] getVersionInfo() { boolean success = false; int[] versionInfo = new int[3]; try { success = NativeAPI_r8.getInstance().getVersionInfo(versionInfo); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(!success) { throw new Error("Failed to retrieve version info from native library!"); } return versionInfo; } public static synchronized Map getBuildInfo() { boolean success = false; Map buildInfo = new HashMap(); try { success = NativeAPI_r8.getInstance().getBuildInfo(buildInfo); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(!success) { throw new Error("Failed to retrieve build info from native library!"); } return buildInfo; } public static synchronized void setLoggingHandler(final Logger logger) { boolean success = false; try { success = NativeAPI_r8.getInstance().setLoggingHandler(logger); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(!success) { throw new Error("Failed to setup new logging handler!"); } } //------------------------------------------------------------------------------------------------ // Constructor, Close() and Finalizer //------------------------------------------------------------------------------------------------ private int m_instance = -1; public JDynamicAudioNormalizer(final int channels, final int sampleRate, final int frameLenMsec, final int filterSize, final double peakValue, final double maxAmplification, final double targetRms, final double compressFactor, final boolean channelsCoupled, final boolean enableDCCorrection, final boolean altBoundaryMode) { try { m_instance = NativeAPI_r8.getInstance().createInstance(channels, sampleRate, frameLenMsec, filterSize, peakValue, maxAmplification, targetRms, compressFactor, channelsCoupled, enableDCCorrection, altBoundaryMode); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(m_instance < 0) { throw new Error("Failed to create native DynamicAudioNormalizer instance!"); } } public synchronized void close() { if(m_instance >= 0) { boolean success = false; try { try { success = NativeAPI_r8.getInstance().destroyInstance(m_instance); } finally { m_instance = -1; } } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(!success) { throw new Error("Failed to destroy native DynamicAudioNormalizer instance!"); } } } protected synchronized void finalize() { close(); } //------------------------------------------------------------------------------------------------ // Processing Functions //------------------------------------------------------------------------------------------------ public synchronized long process(final double [][] samplesIn, final double [][] samplesOut, final long inputSize) { checkInstance(); /*make sure we are properly initialized*/ long outputSize = 0; try { outputSize = NativeAPI_r8.getInstance().process(m_instance, samplesIn, samplesOut, inputSize); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(outputSize < 0) { throw new Error("Failed to process the audio samples!"); } return outputSize; } public synchronized long processInplace(final double [][] samplesInOut, final long inputSize) { checkInstance(); /*make sure we are properly initialized*/ long outputSize = 0; try { outputSize = NativeAPI_r8.getInstance().processInplace(m_instance, samplesInOut, inputSize); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(outputSize < 0) { throw new Error("Failed to process the audio samples inplace!"); } return outputSize; } public synchronized long flushBuffer(final double [][] samplesOut) { checkInstance(); /*make sure we are properly initialized*/ long outputSize = 0; try { outputSize = NativeAPI_r8.getInstance().flushBuffer(m_instance, samplesOut); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(outputSize < 0) { throw new Error("Failed to flush samples from buffer!"); } return outputSize; } public synchronized void reset() { checkInstance(); /*make sure we are properly initialized*/ boolean success = false; try { success = NativeAPI_r8.getInstance().reset(m_instance); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(!success) { throw new Error("Failed to reset DynamicAudioNormalizerAPI instance!"); } } //------------------------------------------------------------------------------------------------ // Other Functions //------------------------------------------------------------------------------------------------ public synchronized Map getConfiguration() { checkInstance(); /*make sure we are properly initialized*/ boolean success = false; Map configuration = new HashMap(); try { success = NativeAPI_r8.getInstance().getConfiguration(m_instance, configuration); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(!success) { throw new Error("Failed to retrieve DynamicAudioNormalizerAPI configuration!"); } return configuration; } public synchronized long getInternalDelay() { checkInstance(); /*make sure we are properly initialized*/ long internalDelay = -1; try { internalDelay = NativeAPI_r8.getInstance().getInternalDelay(m_instance); } catch(Throwable e) { handleError(e, "Failed to call native DynamicAudioNormalizerAPI function!"); } if(internalDelay < 0) { throw new Error("Failed to retrieve DynamicAudioNormalizerAPI internal delay!"); } return internalDelay; } @Deprecated public synchronized int getHandle() { return m_instance; } //------------------------------------------------------------------------------------------------ // Internal functions //------------------------------------------------------------------------------------------------ private static void handleError(final Throwable e, final String message) { if(e.getClass() == Error.class) { throw (Error) e; /*pass through our own exceptions*/ } else { throw new Error(String.format("%s [Reason: %s, Message: \"%s\"]", message, e.getClass().getName(), e.getMessage())); } } private void checkInstance() { if(m_instance < 0) { throw new Error("Native DynamicAudioNormalizer object not created yet or released already!"); } } //------------------------------------------------------------------------------------------------ // Main //------------------------------------------------------------------------------------------------ public static void main(String [] args) { int [] ver = null; Exception error = null; try { ver = getVersionInfo(); } catch(Exception ex) { error = ex; } System.out.println("\n==========================================================================="); if((ver != null) && (ver.length >= 3)) { System.out.printf("Dynamic Audio Normalizer, Version %d.%02d-%d\n", ver[0], ver[1], ver[2]); } else { System.out.println("Dynamic Audio Normalizer, Unknown Version"); } System.out.println("Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved."); System.out.println(); System.out.println("This program is free software: you can redistribute it and/or modify"); System.out.println("it under the terms of the GNU General Public License ."); System.out.println("Note that this program is distributed with ABSOLUTELY NO WARRANTY."); System.out.println("===========================================================================\n"); if((error != null)) { System.out.printf("ERROR: %s\n%s\n", error.getClass().toString(), error.getMessage()); } else { System.out.println("That's all. Goodbye."); } } } ================================================ FILE: DynamicAudioNormalizerJNI/test/com/muldersoft/dynaudnorm/test/JDynamicAudioNormalizerTest.java ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Java/JNI Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// package com.muldersoft.dynaudnorm.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Formatter; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import com.muldersoft.dynaudnorm.JDynamicAudioNormalizer; import com.muldersoft.dynaudnorm.JDynamicAudioNormalizer.Logger; import com.muldersoft.dynaudnorm.samples.AudioFileIO; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class JDynamicAudioNormalizerTest { // ------------------------------------------------------------------------------------------------ // Randomization // ------------------------------------------------------------------------------------------------ private static void double2DArrayRandom(double[][] output) { final SecureRandom rand = new SecureRandom(); final double amp = Math.max(0.125, rand.nextDouble()); for (final double[] channel : output) { for (int i = 0; i < channel.length; ++i) { final double sign = rand.nextBoolean() ? 1.0 : (-1.0); channel[i] = amp *sign * rand.nextDouble(); } } } // ------------------------------------------------------------------------------------------------ // Hash Computation // ------------------------------------------------------------------------------------------------ public static String sha1sum(double[][] input) throws NoSuchAlgorithmException, IOException { final MessageDigest md = MessageDigest.getInstance("SHA-1"); return byteArrayToHex(md.digest(double2DArrayToBytes(input))); } private static byte[] double2DArrayToBytes(double[][] input) throws IOException { try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { try (DataOutputStream dos = new DataOutputStream(baos)) { for (final double[] channel : input) { for (final double d : channel) { dos.writeDouble(d); } } dos.flush(); return baos.toByteArray(); } } } private static String byteArrayToHex(final byte[] hash) { try (final Formatter formatter = new Formatter()) { for (byte b : hash) { formatter.format("%02X", b); } return formatter.toString(); } } // ------------------------------------------------------------------------------------------------ // Test Functions // ------------------------------------------------------------------------------------------------ @Before public void setUp() { System.out.println("\n============================= TEST BEGIN ============================="); } @After public void shutDown() { System.out.println("============================= TEST DONE! =============================\n"); } @Test public void test1_setLoggingHandler() { JDynamicAudioNormalizer.setLoggingHandler(new Logger() { public void log(final int level, final String message) { String label = "???"; switch (level) { case 0: label = "DBG"; break; case 1: label = "WRN"; break; case 2: label = "ERR"; break; } System.err.printf("[JDynAudNorm][%s] %s\n", label, message); } }); System.out.println("Message handler installed successfully."); } @Test public void test2_getVersionInfo() { final int[] versionInfo = JDynamicAudioNormalizer.getVersionInfo(); System.out.printf("Library Version: %d.%02d-%d\n", versionInfo[0], versionInfo[1], versionInfo[2]); } @Test public void test3_getBuildInfo() { final Map buildInfo = JDynamicAudioNormalizer.getBuildInfo(); for (final String key : buildInfo.keySet()) { System.out.println("Build Info: " + key + "=" + buildInfo.get(key)); } } @Test public void test4_getConfiguration() { JDynamicAudioNormalizer instance = new JDynamicAudioNormalizer(2, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, true, false, false); final Map buildInfo = instance.getConfiguration(); for (final String key : buildInfo.keySet()) { System.out.printf("Configuration: %s=%s\n", key, buildInfo.get(key)); } instance.close(); } @Test public void test5_getInternalDelay() { JDynamicAudioNormalizer instance = new JDynamicAudioNormalizer(2, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, true, false, false); final long delayedSamples = instance.getInternalDelay(); System.out.printf("Delayed Samples: %d\n", delayedSamples); instance.close(); } @Test @SuppressWarnings("deprecation") public void test6_constructorAndRelease() { final int MAX_ROUNDS = 512; final int MAX_INSTANCES = 56; for (int i = 0; i < MAX_ROUNDS; i++) { System.out.println("--------------------------------------------------------------------------"); System.out.printf("Round %d of %d\n", i + 1, MAX_ROUNDS); System.out.println("--------------------------------------------------------------------------"); Queue instances = new LinkedList(); // Constructor for (int k = 0; k < MAX_INSTANCES; k++) { JDynamicAudioNormalizer instance = new JDynamicAudioNormalizer(2, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, true, false, false); System.out.printf("Handle: %08X\n", instance.getHandle()); instances.add(instance); } // Process at least one chunk of data with every instance double[][] sampleBuffer = new double[2][4096]; for (Iterator k = instances.iterator(); k.hasNext(); /* next */) { k.next().processInplace(sampleBuffer, sampleBuffer[0].length); } // Release while (!instances.isEmpty()) { instances.poll().close(); } } } @Test public void test7_processRandomData() { final int MAX_PASS = 2; final int MAX_LENGTH = 9973; final double[] TARGET_RMS = { 0.0, 0.75 }; final double[] COMPRESS = { 0.0, 5.0 }; final boolean[] CCOUPLING = { true, false }; final boolean[] DCCORRECT = { false, true }; final boolean[] BOUNDARYM = { false, true }; for(int p = 0; p < MAX_PASS; ++p) { double[][] sampleBuffer = new double[2][4096]; try(final JDynamicAudioNormalizer instance = new JDynamicAudioNormalizer(2, 44100, 500, 31, 0.95, 10.0, TARGET_RMS[p], COMPRESS[p], CCOUPLING[p], DCCORRECT[p], BOUNDARYM[p])) { for(int i = 0; i < MAX_LENGTH; ++i) { if(i % 97 == 0) { System.out.printf("Pass %d of %d, Round %d of %d... [%.1f%%]\n", p+1, MAX_PASS, i, MAX_LENGTH, (((double)i) / MAX_LENGTH) * 100.0); } double2DArrayRandom(sampleBuffer); instance.processInplace(sampleBuffer, sampleBuffer[0].length); } System.out.printf("Pass %d of %d, Round %d of %d... [%.1f%%]\n", p+1, MAX_PASS, MAX_LENGTH, MAX_LENGTH, 100.0); } } } @Test public void test8_processAudioFile() throws NoSuchAlgorithmException, IOException { // Open input and output files System.out.println("Opening input and out files..."); try(AudioFileIO.PCMFileReader reader = new AudioFileIO.PCMFileReader("Input.pcm", 2, AudioFileIO.PCMFileType.PCM_16BIT_LE)) { try (AudioFileIO.PCMFileWriter writer = new AudioFileIO.PCMFileWriter("Output.pcm", 2, AudioFileIO.PCMFileType.PCM_16BIT_LE)) { double[][] sampleBuffer = new double[2][4096]; System.out.println("Creating normalizer instance..."); try(final JDynamicAudioNormalizer instance = new JDynamicAudioNormalizer(2, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, true, false, false)) { // Process samples System.out.println("Processing input samples..."); for (;;) { int sampleCount = 0; try { sampleCount = reader.read(sampleBuffer); } catch (IOException e) { fail("Failed to read from input file!"); } if (sampleCount > 0) { final long outputSamples = instance.processInplace(sampleBuffer, sampleCount); if (outputSamples > 0) { try { writer.write(sampleBuffer, (int) outputSamples); } catch (IOException e) { fail("Failed to write to output file!"); } } } if (sampleCount < sampleBuffer[0].length) { break; /* EOF reached */ } } // Flush pending samples System.out.println("Flushing remaining samples..."); for (;;) { final long outputSamples = instance.flushBuffer(sampleBuffer); if (outputSamples > 0) { try { writer.write(sampleBuffer, (int) outputSamples); } catch (IOException e) { fail("Failed to write to output file!"); } } else { break; /* No more samples */ } } // Reset System.out.println("Resetting normalizer instance..."); instance.reset(); /* This is NOT normally required, but we do it here to test the reset() API */ // Close input and output System.out.println("Shutting down..."); /*Implicitly, due to AutoCloseable*/ } } } // Finished System.out.println("Completed."); } @Test public void test9_processAudioFile_outOfPlace() throws NoSuchAlgorithmException, IOException { // Open input and output files System.out.println("Opening input and out files..."); try(AudioFileIO.PCMFileReader reader = new AudioFileIO.PCMFileReader("Input.pcm", 2, AudioFileIO.PCMFileType.PCM_16BIT_LE)) { try (AudioFileIO.PCMFileWriter writer = new AudioFileIO.PCMFileWriter("Output.pcm", 2, AudioFileIO.PCMFileType.PCM_16BIT_LE)) { double[][] sampleBufferSrc = new double[2][4096]; double[][] sampleBufferDst = new double[2][4096]; System.out.println("Creating normalizer instance..."); try(final JDynamicAudioNormalizer instance = new JDynamicAudioNormalizer(2, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, true, false, false)) { // Process samples System.out.println("Processing input samples..."); for (;;) { int sampleCount = 0; try { sampleCount = reader.read(sampleBufferSrc); } catch (IOException e) { fail("Failed to read from input file!"); } final String hashOrig = sha1sum(sampleBufferSrc); if (sampleCount > 0) { final long outputSamples = instance.process(sampleBufferSrc, sampleBufferDst, sampleCount); if (outputSamples > 0) { try { writer.write(sampleBufferDst, (int) outputSamples); } catch (IOException e) { fail("Failed to write to output file!"); } } } final String hashFinal = sha1sum(sampleBufferSrc); assertEquals("Input buffer contents have been distrubed!", hashOrig, hashFinal); if (sampleCount < sampleBufferSrc[0].length) { break; /* EOF reached */ } } // Flush pending samples System.out.println("Flushing remaining samples..."); for (;;) { final long outputSamples = instance.flushBuffer(sampleBufferDst); if (outputSamples > 0) { try { writer.write(sampleBufferDst, (int) outputSamples); } catch (IOException e) { fail("Failed to write to output file!"); } } else { break; /* No more samples */ } } // Reset System.out.println("Resetting normalizer instance..."); instance.reset(); /* This is NOT normally required, but we do it here to test the reset() API */ // Close input and output System.out.println("Shutting down..."); /*Implicitly, due to AutoCloseable*/ } } } // Finished System.out.println("Completed."); } } ================================================ FILE: DynamicAudioNormalizerNET/DynamicAudioNormalizerNET_VS2013.vcxproj ================================================  Debug Win32 Debug x64 Release_DLL Win32 Release_DLL x64 Release_Static Win32 Release_Static x64 {E1794071-AB51-45C7-B215-028F3DAA2219} v4.5 ManagedCProj DynamicAudioNormalizerNET DynamicAudioNormalizerNET DynamicLibrary true v120_xp true Unicode DynamicLibrary true v120_xp true Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ Level3 Disabled WIN32;_DEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MultiThreadedDebugDLL NoExtensions true Console LinkVerboseLib Level3 Disabled WIN32;_DEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MultiThreadedDebugDLL true Console LinkVerboseLib Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreadedDLL false true StreamingSIMDExtensions2 Fast false Console true true LinkVerboseLib Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreadedDLL false Fast true false Console true true LinkVerboseLib Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreaded true Fast false true StreamingSIMDExtensions2 false Console true true LinkVerboseLib Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreaded true false true Fast false Console true true LinkVerboseLib {376386ee-8268-47e3-a335-7663716e4c60} true true false true false ================================================ FILE: DynamicAudioNormalizerNET/DynamicAudioNormalizerNET_VS2013.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files Header Files Header Files ================================================ FILE: DynamicAudioNormalizerNET/DynamicAudioNormalizerNET_VS2015.vcxproj ================================================  Debug Win32 Debug x64 Release_DLL Win32 Release_DLL x64 Release_Static Win32 Release_Static x64 {E1794071-AB51-45C7-B215-028F3DAA2219} v4.5.2 ManagedCProj DynamicAudioNormalizerNET DynamicAudioNormalizerNET DynamicLibrary true v140_xp true Unicode DynamicLibrary true v140_xp true Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ Level3 Disabled WIN32;_DEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MultiThreadedDebugDLL NoExtensions true Console LinkVerboseLib Level3 Disabled WIN32;_DEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MultiThreadedDebugDLL true Console LinkVerboseLib Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreadedDLL false true StreamingSIMDExtensions2 Fast false Console true true LinkVerboseLib Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreadedDLL false Fast true false Console true true LinkVerboseLib Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreaded true Fast false true StreamingSIMDExtensions2 false Console true true LinkVerboseLib Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreaded true false true Fast false Console true true LinkVerboseLib {376386ee-8268-47e3-a335-7663716e4c60} true true false true false ================================================ FILE: DynamicAudioNormalizerNET/DynamicAudioNormalizerNET_VS2015.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files Header Files Header Files ================================================ FILE: DynamicAudioNormalizerNET/DynamicAudioNormalizerNET_VS2017.vcxproj ================================================  Debug Win32 Debug x64 Release_DLL Win32 Release_DLL x64 Release_Static Win32 Release_Static x64 {E1794071-AB51-45C7-B215-028F3DAA2219} v4.5.2 ManagedCProj DynamicAudioNormalizerNET DynamicAudioNormalizerNET 8.1 DynamicLibrary true v141_xp true Unicode DynamicLibrary true v141_xp true Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ Level3 Disabled WIN32;_DEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MultiThreadedDebugDLL NoExtensions true Console LinkVerboseLib Level3 Disabled WIN32;_DEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MultiThreadedDebugDLL true Console LinkVerboseLib Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreadedDLL false true StreamingSIMDExtensions2 Fast false Console true true LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreadedDLL false Fast true false Console true true LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreaded true Fast false true StreamingSIMDExtensions2 false Console true true LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 WIN32;NDEBUG;%(PreprocessorDefinitions) NotUsing $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include MaxSpeed AnySuitable true Speed true MultiThreaded true false true Fast false Console true true LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) {376386ee-8268-47e3-a335-7663716e4c60} true true false true false ================================================ FILE: DynamicAudioNormalizerNET/DynamicAudioNormalizerNET_VS2017.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Source Files Header Files Header Files Resource Files ================================================ FILE: DynamicAudioNormalizerNET/res/DynamicAudioNormalizerNET.rc ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "WinResrc.h" //"afxres.h" #define INC_DYNAUDNORM_VERSION_INTERNAL 0x22b4f8a9 #include "../DynamicAudioNormalizerShared/res/version.inc" ////////////////////////////////////////////////////////////////////////////////// // Neutral resources ////////////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) #ifdef _WIN32 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL #pragma code_page(1252) #endif //_WIN32 ////////////////////////////////////////////////////////////////////////////////// // Version ////////////////////////////////////////////////////////////////////////////////// VS_VERSION_INFO VERSIONINFO FILEVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH PRODUCTVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x3L #else FILEFLAGS 0x2L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ." VALUE "CompanyName", "LoRd_MuldeR " VALUE "FileDescription", "DynamicAudioNormalizer .NET Wrapper" VALUE "FileVersion", VER_DYNAUDNORM_STR VALUE "InternalName", "DynamicAudioNormalizerNET" VALUE "LegalCopyright", "Copyright (c) 2014-2019 LoRd_MuldeR " VALUE "LegalTrademarks", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License " VALUE "OriginalFilename", "DynamicAudioNormalizerNET.dll" VALUE "ProductName", "DynamicAudioNormalizer" VALUE "ProductVersion", VER_DYNAUDNORM_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // Neutral resources ================================================ FILE: DynamicAudioNormalizerNET/samples/DynamicAudioNormalizerExample.cs ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Microsoft.NET Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Reflection; using DynamicAudioNormalizer; namespace DynamicAudioNormalizer_Example { class SampleReader : IDisposable { public SampleReader(String fileName) { m_reader = new BinaryReader(File.OpenRead(fileName)); } public int read(double[,] samplesOut) { int channels = samplesOut.GetLength(0); int maxSamples = samplesOut.GetLength(1); for (int i = 0; i < maxSamples; i++) { for (int c = 0; c < channels; c++) { try { samplesOut[c, i] = (double) m_reader.ReadInt16() / 32767.0; } catch(EndOfStreamException) { return i; } } } return maxSamples; } public void Dispose() { m_reader.Dispose(); } private readonly BinaryReader m_reader; } class SampleWriter : IDisposable { public SampleWriter(String fileName) { m_writer = new BinaryWriter(File.OpenWrite(fileName)); } public void write(double[,] samplesIn, int sampleCount) { int channels = samplesIn.GetLength(0); for (int i = 0; i < sampleCount; i++) { for (int c = 0; c < channels; c++) { m_writer.Write((short)(samplesIn[c, i] * 32767.0)); } } } public void Dispose() { m_writer.Dispose(); } private readonly BinaryWriter m_writer; } class Program { static void Main(string[] args) { try { String version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); Console.WriteLine("DynamicAudioNormalizer.NET C# Example [{0}]\n", version); runTest(); GC.WaitForPendingFinalizers(); } catch (Exception e) { Console.WriteLine("\nFAILURE!!!\n\n" + e.GetType() + ": " + e.Message + "\n"); } } private static void runTest() { uint major, minor, patch; DynamicAudioNormalizerNET.getVersionInfo(out major, out minor, out patch); Console.WriteLine("Library Version {0}.{1}-{2}", major.ToString(), minor.ToString("D2"), minor, patch.ToString()); String date, time, compiler, arch; bool debug; DynamicAudioNormalizerNET.getBuildInfo(out date, out time, out compiler, out arch, out debug); Console.WriteLine("Date: {0}, Time: {1}, Compiler: {2}, Arch: {3}, {4}", date, time, compiler, arch, debug ? "DEBUG" : "Release"); DynamicAudioNormalizerNET.setLogger(delegate(int level, String message) { switch (level) { case 0: Console.WriteLine("[DynAudNorm][DBG] " + message); break; case 1: Console.WriteLine("[DynAudNorm][WRN] " + message); break; case 2: Console.WriteLine("[DynAudNorm][ERR] " + message); break; default: Console.WriteLine("[DynAudNorm][???] " + message); break; } }); using(DynamicAudioNormalizerNET instance = new DynamicAudioNormalizerNET(2, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, true, false, false)) { using (SampleReader reader = new SampleReader("Input.pcm")) { using (SampleWriter writer = new SampleWriter("Output.pcm")) { uint channels, sampleRate, frameLen, filterSize; instance.getConfiguration(out channels, out sampleRate, out frameLen, out filterSize); Console.WriteLine("channels: " + channels.ToString()); Console.WriteLine("sampleRate: " + sampleRate.ToString()); Console.WriteLine("frameLen: " + frameLen.ToString()); Console.WriteLine("filterSize: " + filterSize.ToString()); long internalDelay = instance.getInternalDelay(); Console.WriteLine("internalDelay: " + internalDelay.ToString()); process(reader, writer, instance); } } } } private static void process(SampleReader reader, SampleWriter writer, DynamicAudioNormalizerNET instance) { double[,] data = new double[2, 4096]; Console.WriteLine("Processing audio samples in-place..."); for(;;) { int inputSamples = reader.read(data); if(inputSamples > 0) { int outputSamples = (int)instance.processInplace(data, inputSamples); if(outputSamples > 0) { writer.write(data, outputSamples); } } if(inputSamples < data.GetLength(1)) { break; /*EOF*/ } } Console.WriteLine("Flushing remaining samples from buffer..."); for(;;) { int outputSamples = (int) instance.flushBuffer(data); if (outputSamples > 0) { writer.write(data, outputSamples); } if (outputSamples < 1) { break; /*EOF*/ } } Console.WriteLine("Resetting the normalizer instance..."); instance.reset(); //Just for testing, this NOT actually required here! Console.WriteLine("Finished."); } } } ================================================ FILE: DynamicAudioNormalizerNET/samples/DynamicAudioNormalizerExample.vb ================================================ REM ////////////////////////////////////////////////////////////////////////////////// REM // Dynamic Audio Normalizer - Microsoft.NET Wrapper REM // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. REM // REM // Permission is hereby granted, free of charge, to any person obtaining a copy REM // of this software and associated documentation files (the "Software"), to deal REM // in the Software without restriction, including without limitation the rights REM // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell REM // copies of the Software, and to permit persons to whom the Software is REM // furnished to do so, subject to the following conditions: REM // REM // The above copyright notice and this permission notice shall be included in REM // all copies or substantial portions of the Software. REM // REM // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR REM // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, REM // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE REM // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER REM // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, REM // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN REM // THE SOFTWARE. REM // REM // http://opensource.org/licenses/MIT REM ////////////////////////////////////////////////////////////////////////////////// Imports System.Reflection Imports DynamicAudioNormalizer Module DynamicAudioNormalizerExample REM -------------------------------------------------------------------------- REM AudioFileReader Class REM -------------------------------------------------------------------------- Class AudioFileReader Implements IDisposable Private Reader As IO.BinaryReader Public Sub New(FileName As String) Reader = New IO.BinaryReader(IO.File.OpenRead(FileName)) End Sub Protected Sub Dispose() Implements IDisposable.Dispose If Reader IsNot Nothing Then Reader.Dispose() End If End Sub Public Function Read(SamplesOut(,) As Double) As Long Dim Channels As Integer = SamplesOut.GetLength(0) Dim MaxSamples As Integer = SamplesOut.GetLength(1) For I As Long = 0 To MaxSamples - 1 For C As Long = 0 To Channels - 1 Try SamplesOut(C, I) = CType(Reader.ReadInt16(), Double) / 32767.0 Catch E As IO.EndOfStreamException Return I End Try Next Next Return MaxSamples End Function End Class REM -------------------------------------------------------------------------- REM AudioFileWriter Class REM -------------------------------------------------------------------------- Class AudioFileWriter Implements IDisposable Private Writer As IO.BinaryWriter Public Sub New(FileName As String) Writer = New IO.BinaryWriter(IO.File.OpenWrite(FileName)) End Sub Protected Sub Dispose() Implements IDisposable.Dispose If Writer IsNot Nothing Then Writer.Flush() Writer.Dispose() End If End Sub Public Sub Write(SamplesOut(,) As Double, SampleCount As Long) Dim Channels As Integer = SamplesOut.GetLength(0) For I As Long = 0 To SampleCount - 1 For C As Long = 0 To Channels - 1 Writer.Write(CType(SamplesOut(C, I) * 32767.0, Short)) Next Next End Sub End Class REM -------------------------------------------------------------------------- REM Logging Callback REM -------------------------------------------------------------------------- Private Sub LoggingHandler(Level As Int32, Message As String) Select Case Level Case 0 Console.WriteLine("[DynAudNorm][DBG] " & Message) Case 1 Console.WriteLine("[DynAudNorm][WRN] " & Message) Case 2 Console.WriteLine("[DynAudNorm][ERR] " & Message) Case Else Console.WriteLine("[DynAudNorm][???] " & Message) End Select End Sub REM -------------------------------------------------------------------------- REM Main Function REM -------------------------------------------------------------------------- Sub Main() Dim Version As String Version = Assembly.GetExecutingAssembly().GetName().Version.ToString() Console.WriteLine("DynamicAudioNormalizer.NET VisualBasic Example [" & Version & "]" & vbCrLf) Try DynamicAudioNormalizerNET.setLogger(AddressOf LoggingHandler) Dim MajorVer As UInteger = 0, MinorVer As UInteger = 0, PatchVer As UInteger = 0 DynamicAudioNormalizerNET.getVersionInfo(MajorVer, MinorVer, PatchVer) Console.WriteLine("Library Version: " & MajorVer & "." & Format(MinorVer, "##00") & "-" & PatchVer) Dim DateStr As String = "", TimeStr As String = "", CompilerStr As String = "", ArchStr As String = "", IsDebug As Boolean = False DynamicAudioNormalizerNET.getBuildInfo(DateStr, TimeStr, CompilerStr, ArchStr, IsDebug) Console.WriteLine("Library Build Date: " & DateStr) Console.WriteLine("Library Build Time: " & TimeStr) Console.WriteLine("Library Compiler: " & CompilerStr & " (" & ArchStr & ")") Console.WriteLine("Library Is Debug: " & IsDebug) Using Reader = New AudioFileReader("Input.pcm") Using Writer = New AudioFileWriter("Output.pcm") Using Instance = New DynamicAudioNormalizerNET(2, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, True, False, False) ProcessAudioFile(Instance, Reader, Writer) End Using End Using End Using Console.WriteLine("Test completed." & vbCrLf) Catch Except As Exception Console.WriteLine(vbCrLf & "FAILURE !!!") Console.WriteLine(vbCrLf & Except.GetType().ToString() & ": " & Except.Message & vbCrLf) End Try End Sub REM -------------------------------------------------------------------------- REM Processing Loop REM -------------------------------------------------------------------------- Private Sub ProcessAudioFile(Instance As DynamicAudioNormalizerNET, Reader As AudioFileReader, Writer As AudioFileWriter) Dim Channels As UInteger = 0, FilterSize As UInteger = 0, FrameLen As UInteger = 0, SampleRate As UInteger = 0 Instance.getConfiguration(Channels, FilterSize, FrameLen, SampleRate) Console.WriteLine("Channels: " & Channels) Console.WriteLine("FilterSize: " & FilterSize) Console.WriteLine("FrameLen: " & FrameLen) Console.WriteLine("SampleRate: " & SampleRate) Dim InternalDelay As Long = Instance.getInternalDelay() Console.WriteLine("InternalDelay: " & InternalDelay) REM Note: VisualBasic specifies the highest index value (i.e. Length - 1) rather than the Length, so the following creates a 2 x 4096 array! Dim AudioSamples = New Double(Channels - 1, 4095) {} Console.WriteLine("Processing audio samples, please wait...") While True Dim InputSamples = Reader.Read(AudioSamples) If InputSamples > 0 Then Dim OutputSamples = Instance.processInplace(AudioSamples, InputSamples) If OutputSamples > 0 Then Writer.Write(AudioSamples, OutputSamples) End If End If If InputSamples < AudioSamples.GetLength(1) Then REM End of file reached! Exit While End If End While Console.WriteLine("Flushing buffer, please wait...") While True Dim OutputSamples = Instance.flushBuffer(AudioSamples) If OutputSamples > 0 Then Writer.Write(AudioSamples, OutputSamples) Continue While End If REM No more samples to flush! Exit While End While REM Only for testing, not usually required! Instance.reset() End Sub End Module ================================================ FILE: DynamicAudioNormalizerNET/samples/DynamicAudioNormalizerExample_CS.csproj ================================================  Debug AnyCPU {AC5A5448-A96E-492C-AC9C-81986F418BBB} Exe Properties DynamicAudioNormalizerExample_CS DynamicAudioNormalizerExample_CS v4.0 512 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true true bin\x86\Debug\ DEBUG;TRACE full x86 prompt MinimumRecommendedRules.ruleset bin\x86\Release\ TRACE true pdbonly x86 prompt MinimumRecommendedRules.ruleset DynamicAudioNormalizer_Example.Program true bin\x64\Debug\ DEBUG;TRACE full x64 prompt MinimumRecommendedRules.ruleset bin\x64\Release\ TRACE true pdbonly x64 prompt MinimumRecommendedRules.ruleset False ..\..\bin\Win32\v140_xp\Release_DLL\DynamicAudioNormalizerNET.dll False Microsoft .NET Framework 4 %28x86 and x64%29 true False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 false False Windows Installer 4.5 true ================================================ FILE: DynamicAudioNormalizerNET/samples/DynamicAudioNormalizerExample_VB.vbproj ================================================  Debug AnyCPU {07C91D94-3626-46D4-8CAA-4A1548CEAAAE} Exe DynamicAudioNormalizerExample_VB.DynamicAudioNormalizerExample DynamicAudioNormalizerExample_VB DynamicAudioNormalizerExample_VB 512 Console v4.0 publish\ true Disk false Foreground 7 Days false false true 0 1.0.0.%2a false false true On Binary Off On true true true bin\x86\Debug\ DynamicAudioNormalizerExample_VB.xml 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 full x86 MinimumRecommendedRules.ruleset true bin\x86\Release\ DynamicAudioNormalizerExample_VB.xml true 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 pdbonly x86 MinimumRecommendedRules.ruleset true true true bin\x64\Debug\ DynamicAudioNormalizerExample_VB.xml 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 full x64 MinimumRecommendedRules.ruleset true bin\x64\Release\ DynamicAudioNormalizerExample_VB.xml true 42016,41999,42017,42018,42019,42032,42036,42020,42021,42022 pdbonly x64 MinimumRecommendedRules.ruleset ..\..\bin\Win32\v140_xp\Release_DLL\DynamicAudioNormalizerNET.dll False Microsoft .NET Framework 4 %28x86 and x64%29 true False .NET Framework 3.5 SP1 Client Profile false False .NET Framework 3.5 SP1 false False Windows Installer 4.5 true ================================================ FILE: DynamicAudioNormalizerNET/samples/DynamicAudioNormalizerExamples.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DynamicAudioNormalizerExample_CS", "DynamicAudioNormalizerExample_CS.csproj", "{AC5A5448-A96E-492C-AC9C-81986F418BBB}" EndProject Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "DynamicAudioNormalizerExample_VB", "DynamicAudioNormalizerExample_VB.vbproj", "{07C91D94-3626-46D4-8CAA-4A1548CEAAAE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {AC5A5448-A96E-492C-AC9C-81986F418BBB}.Debug|x64.ActiveCfg = Debug|x64 {AC5A5448-A96E-492C-AC9C-81986F418BBB}.Debug|x64.Build.0 = Debug|x64 {AC5A5448-A96E-492C-AC9C-81986F418BBB}.Debug|x86.ActiveCfg = Debug|x86 {AC5A5448-A96E-492C-AC9C-81986F418BBB}.Debug|x86.Build.0 = Debug|x86 {AC5A5448-A96E-492C-AC9C-81986F418BBB}.Release|x64.ActiveCfg = Release|x64 {AC5A5448-A96E-492C-AC9C-81986F418BBB}.Release|x64.Build.0 = Release|x64 {AC5A5448-A96E-492C-AC9C-81986F418BBB}.Release|x86.ActiveCfg = Release|x86 {AC5A5448-A96E-492C-AC9C-81986F418BBB}.Release|x86.Build.0 = Release|x86 {07C91D94-3626-46D4-8CAA-4A1548CEAAAE}.Debug|x64.ActiveCfg = Debug|x64 {07C91D94-3626-46D4-8CAA-4A1548CEAAAE}.Debug|x86.ActiveCfg = Debug|x64 {07C91D94-3626-46D4-8CAA-4A1548CEAAAE}.Release|x64.ActiveCfg = Release|x64 {07C91D94-3626-46D4-8CAA-4A1548CEAAAE}.Release|x64.Build.0 = Release|x64 {07C91D94-3626-46D4-8CAA-4A1548CEAAAE}.Release|x86.ActiveCfg = Release|x86 {07C91D94-3626-46D4-8CAA-4A1548CEAAAE}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: DynamicAudioNormalizerNET/samples/Properties/AssemblyInfo.cs ================================================ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DynamicAudioNormalizer.NET Example")] [assembly: AssemblyDescription("DynamicAudioNormalizer.NET Example")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("FSF")] [assembly: AssemblyProduct("DynamicAudioNormalizer.NET")] [assembly: AssemblyCopyright("Copyright © 2014-2019 LoRd_MuldeR ")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1e292d70-b972-463a-a55c-9274dfa9ffeb")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] ================================================ FILE: DynamicAudioNormalizerNET/samples/Properties/AssemblyInfo.vb ================================================ Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes ")> 'The following GUID is for the ID of the typelib if this project is exposed to COM ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ================================================ FILE: DynamicAudioNormalizerNET/src/AssemblyInfo.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Microsoft.NET Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// using namespace System; using namespace System::Reflection; using namespace System::Runtime::CompilerServices; using namespace System::Runtime::InteropServices; using namespace System::Security::Permissions; #include #define CORE_VERSION_MAKE_STR1(X) #X #define CORE_VERSION_MAKE_STR2(X) CORE_VERSION_MAKE_STR1(X) #define CORE_VERSION CORE_VERSION_MAKE_STR2(MDYNAMICAUDIONORMALIZER_CORE) // // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. // [assembly:AssemblyTitleAttribute(L"DynamicAudioNormalizerNET")]; [assembly:AssemblyDescriptionAttribute(L"DynamicAudioNormalizer .NET-Wrapper")]; [assembly:AssemblyConfigurationAttribute(L"")]; [assembly:AssemblyCompanyAttribute(L"Free Software Foundation")]; [assembly:AssemblyProductAttribute(L"DynamicAudioNormalizerNET")]; [assembly:AssemblyCopyrightAttribute(L"Copyright (c) 2014-2019 LoRd_MuldeR ")]; [assembly:AssemblyTrademarkAttribute(L"")]; [assembly:AssemblyCultureAttribute(L"")]; // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the value or you can default the Revision and Build Numbers // by using the '*' as shown below: // [assembly:AssemblyVersionAttribute(CORE_VERSION ".0.*")]; [assembly:ComVisible(false)]; [assembly:CLSCompliantAttribute(true)]; ================================================ FILE: DynamicAudioNormalizerNET/src/DynamicAudioNormalizerNET.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Microsoft.NET Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// #include "DynamicAudioNormalizerNET.h" #include #include #include using namespace System::Threading; /////////////////////////////////////////////////////////////////////////////// // Helper Functions /////////////////////////////////////////////////////////////////////////////// template static void INIT_ARRAY_2D(T *basePtr, T **outPtr, const int64_t dimOuter , const int64_t dimInner) { for(int64_t i = 0; i < dimOuter; i++) { outPtr[i] = basePtr; basePtr += dimInner; } } #define PIN_ARRAY_2D(ARRAY, TYPE) \ const int64_t ARRAY##_dimOuter = ARRAY->GetLongLength(0); \ const int64_t ARRAY##_dimInner = ARRAY->GetLongLength(1); \ TYPE **ARRAY##_ptr = (TYPE**) alloca(sizeof(TYPE*) * ((size_t) ARRAY##_dimOuter)); \ pin_ptr ARRAY##_pinned = &ARRAY[0,0]; \ INIT_ARRAY_2D(ARRAY##_pinned, ARRAY##_ptr, ARRAY##_dimOuter, ARRAY##_dimInner) #define TRY_CATCH(FUNC, ...) do \ { \ try \ { \ return p_##FUNC(__VA_ARGS__); \ } \ catch(...) \ { \ throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Unhandeled exception in native MDynamicAudioNormalizer function!"); \ } \ } \ while(0) #define TRY_CATCH_NORET(FUNC, ...) do \ { \ try \ { \ p_##FUNC(__VA_ARGS__); \ } \ catch(...) \ { \ throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Unhandeled exception in native MDynamicAudioNormalizer function!"); \ } \ } \ while(0) /////////////////////////////////////////////////////////////////////////////// // Logging Functions /////////////////////////////////////////////////////////////////////////////// namespace DynamicAudioNormalizer { private ref class Lock { public: Lock(Object ^ object) : m_object(object) { Monitor::Enter(m_object); } ~Lock() { Monitor::Exit(m_object); } private: Object ^m_object; }; private ref class LoggingSupport { public: static void log(const int &logLevel, const char *const message) { Lock lock(m_mutex); if(m_handler != nullptr) { try { m_handler->Invoke(logLevel, gcnew String(message)); } catch(...) { } } } static void setHandler(DynamicAudioNormalizerNET_Logger ^handler) { Lock lock(m_mutex); m_handler = handler; } private: static DynamicAudioNormalizerNET_Logger ^m_handler = nullptr; static Object^ m_mutex = gcnew Object(); }; } static void dotNetLoggingHandler(const int logLevel, const char *const message) { DynamicAudioNormalizer::LoggingSupport::log(logLevel, message); } /////////////////////////////////////////////////////////////////////////////// // Static Functions /////////////////////////////////////////////////////////////////////////////// void DynamicAudioNormalizer::DynamicAudioNormalizerNET::setLogger(DynamicAudioNormalizerNET_Logger ^logger) { LoggingSupport::setHandler(logger); MDynamicAudioNormalizer::setLogFunction(dotNetLoggingHandler); } void DynamicAudioNormalizer::DynamicAudioNormalizerNET::getVersionInfo([Out] uint32_t %major, [Out] uint32_t %minor, [Out] uint32_t %patch) { pin_ptr majorPtr = &major; pin_ptr minorPtr = &minor; pin_ptr patchPtr = &patch; MDynamicAudioNormalizer::getVersionInfo(*majorPtr, *minorPtr, *patchPtr); } void DynamicAudioNormalizer::DynamicAudioNormalizerNET::getBuildInfo([Out] String ^%date, [Out] String ^%time, [Out] String ^%compiler, [Out] String ^%arch, [Out] bool %debug) { const char *datePtr, *timePtr, *compilerPtr, *archPtr; bool debugRef; MDynamicAudioNormalizer::getBuildInfo(&datePtr, &timePtr, &compilerPtr, &archPtr, debugRef); date = gcnew String(datePtr); time = gcnew String(timePtr); compiler = gcnew String(compilerPtr); arch = gcnew String(archPtr); debug = debugRef; } /////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor /////////////////////////////////////////////////////////////////////////////// static MDynamicAudioNormalizer *createNewInstance(const uint32_t &channels, const uint32_t &sampleRate, const uint32_t &frameLenMsec, const uint32_t &filterSize, const double &peakValue, const double &maxAmplification, const double &targetRms, const double &compressFactor, const bool &channelsCoupled, const bool &enableDCCorrection, const bool &altBoundaryMode) { try { return new MDynamicAudioNormalizer(channels, sampleRate, frameLenMsec, filterSize, peakValue, maxAmplification, targetRms, compressFactor, channelsCoupled, enableDCCorrection, altBoundaryMode, NULL); } catch(...) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Creation of native MDynamicAudioNormalizer instance has failed!"); } } DynamicAudioNormalizer::DynamicAudioNormalizerNET::DynamicAudioNormalizerNET(const uint32_t channels, const uint32_t sampleRate, const uint32_t frameLenMsec, const uint32_t filterSize, const double peakValue, const double maxAmplification, const double targetRms, const double compressFactor, const bool channelsCoupled, const bool enableDCCorrection, const bool altBoundaryMode) : m_instace(createNewInstance(channels, sampleRate, frameLenMsec, filterSize, peakValue, maxAmplification, targetRms, compressFactor, channelsCoupled, enableDCCorrection, altBoundaryMode)) { bool initialized = false; try { initialized = m_instace->initialize(); } catch(...) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Initialization of native MDynamicAudioNormalizer instance has failed!"); } if(!initialized) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Initialization of native MDynamicAudioNormalizer instance has failed!"); } } DynamicAudioNormalizer::DynamicAudioNormalizerNET::~DynamicAudioNormalizerNET(void) { this->!DynamicAudioNormalizerNET(); GC::SuppressFinalize(this); } DynamicAudioNormalizer::DynamicAudioNormalizerNET::!DynamicAudioNormalizerNET(void) { try { delete m_instace; } catch(...) { throw gcnew System::Exception("Destruction of native MDynamicAudioNormalizer instance has failed!"); } } /////////////////////////////////////////////////////////////////////////////// // Processing Functions /////////////////////////////////////////////////////////////////////////////// int64_t DynamicAudioNormalizer::DynamicAudioNormalizerNET::process(array ^samplesIn, array ^samplesOut, const int64_t inputSize) { TRY_CATCH(process, samplesIn, samplesOut, inputSize); } int64_t DynamicAudioNormalizer::DynamicAudioNormalizerNET::p_process(array ^samplesIn, array ^samplesOut, const int64_t inputSize) { uint32_t channels, sampleRate, frameLen, filterSize; if (!m_instace->getConfiguration(channels, sampleRate, frameLen, filterSize)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Failed to retrieve configuration of native MDynamicAudioNormalizer instance!"); } PIN_ARRAY_2D(samplesIn, double); if ((samplesIn_dimOuter != channels) || (samplesIn_dimInner < inputSize)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Array dimension mismatch: Array must have dimension CHANNEL_COUNT x INPUT_SIZE!"); } PIN_ARRAY_2D(samplesOut, double); if ((samplesOut_dimOuter != channels) || (samplesOut_dimInner < inputSize)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Array dimension mismatch: Array must have dimension CHANNEL_COUNT x INPUT_SIZE!"); } int64_t outputSize = -1; if (!m_instace->process(samplesIn_ptr, samplesOut_ptr, inputSize, outputSize)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Native MDynamicAudioNormalizer instance failed to process samples!"); } return outputSize; } int64_t DynamicAudioNormalizer::DynamicAudioNormalizerNET::processInplace(array ^samplesInOut, const int64_t inputSize) { TRY_CATCH(processInplace, samplesInOut, inputSize); } int64_t DynamicAudioNormalizer::DynamicAudioNormalizerNET::p_processInplace(array ^samplesInOut, const int64_t inputSize) { uint32_t channels, sampleRate, frameLen, filterSize; if(!m_instace->getConfiguration(channels, sampleRate, frameLen, filterSize)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Failed to retrieve configuration of native MDynamicAudioNormalizer instance!"); } PIN_ARRAY_2D(samplesInOut, double); if((samplesInOut_dimOuter != channels) || (samplesInOut_dimInner < inputSize)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Array dimension mismatch: Array must have dimension CHANNEL_COUNT x INPUT_SIZE!"); } int64_t outputSize = -1; if(!m_instace->processInplace(samplesInOut_ptr, inputSize, outputSize)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Native MDynamicAudioNormalizer instance failed to process samples in-place!"); } return outputSize; } int64_t DynamicAudioNormalizer::DynamicAudioNormalizerNET::flushBuffer(array ^samplesInOut) { TRY_CATCH(flushBuffer, samplesInOut); } int64_t DynamicAudioNormalizer::DynamicAudioNormalizerNET::p_flushBuffer(array ^samplesOut) { uint32_t channels, sampleRate, frameLen, filterSize; if(!m_instace->getConfiguration(channels, sampleRate, frameLen, filterSize)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Failed to retrieve configuration of native MDynamicAudioNormalizer instance!"); } PIN_ARRAY_2D(samplesOut, double); if((samplesOut_dimOuter != channels) || (samplesOut_dimInner < 1)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Array dimension mismatch: Array must have dimension CHANNEL_COUNT x INPUT_SIZE!"); } int64_t outputSize = -1; if(!m_instace->flushBuffer(samplesOut_ptr, samplesOut_dimInner, outputSize)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Native MDynamicAudioNormalizer instance failed to flush the buffer!"); } return outputSize; } void DynamicAudioNormalizer::DynamicAudioNormalizerNET::reset(void) { TRY_CATCH_NORET(reset); } void DynamicAudioNormalizer::DynamicAudioNormalizerNET::p_reset(void) { if(!m_instace->reset()) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Failed to reset the native MDynamicAudioNormalizer instance!"); } } /////////////////////////////////////////////////////////////////////////////// // Other Functions /////////////////////////////////////////////////////////////////////////////// void DynamicAudioNormalizer::DynamicAudioNormalizerNET::getConfiguration([Out] uint32_t %channels, [Out] uint32_t %sampleRate, [Out] uint32_t %frameLen, [Out] uint32_t %filterSize) { TRY_CATCH_NORET(getConfiguration, channels, sampleRate, frameLen, filterSize); } void DynamicAudioNormalizer::DynamicAudioNormalizerNET::p_getConfiguration([Out] uint32_t %channels, [Out] uint32_t %sampleRate, [Out] uint32_t %frameLen, [Out] uint32_t %filterSize) { pin_ptr channelsPtr = &channels; pin_ptr sampleRatePtr = &sampleRate; pin_ptr frameLenPtr = &frameLen; pin_ptr filterSizePtr = &filterSize; if(!m_instace->getConfiguration(*channelsPtr, *sampleRatePtr, *frameLenPtr, *filterSizePtr)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Failed to get configuration of native MDynamicAudioNormalizer instance!"); } } int64_t DynamicAudioNormalizer::DynamicAudioNormalizerNET::getInternalDelay(void) { TRY_CATCH(getInternalDelay); } int64_t DynamicAudioNormalizer::DynamicAudioNormalizerNET::p_getInternalDelay(void) { int64_t delayInSamples; if(!m_instace->getInternalDelay(delayInSamples)) { throw gcnew DynamicAudioNormalizer::DynamicAudioNormalizerNET_Error("Failed to get internal delay of MDynamicAudioNormalizer instance!"); } return delayInSamples; } ================================================ FILE: DynamicAudioNormalizerNET/src/DynamicAudioNormalizerNET.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Microsoft.NET Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// #pragma once using namespace System; using namespace System::Runtime::InteropServices; #include namespace DynamicAudioNormalizer { public delegate void DynamicAudioNormalizerNET_Logger(int, String^); public ref struct DynamicAudioNormalizerNET_Error: public System::Exception { public: DynamicAudioNormalizerNET_Error(const char* message) : Exception(gcnew String(message)) {} }; public ref class DynamicAudioNormalizerNET { public: DynamicAudioNormalizerNET(const uint32_t channels, const uint32_t sampleRate, const uint32_t frameLenMsec, const uint32_t filterSize, const double peakValue, const double maxAmplification, const double targetRms, const double compressFactor, const bool channelsCoupled, const bool enableDCCorrection, const bool altBoundaryMode); ~DynamicAudioNormalizerNET(void); !DynamicAudioNormalizerNET(void); //Static static void getVersionInfo([Out] uint32_t %major, [Out] uint32_t %minor, [Out] uint32_t %patch); static void getBuildInfo([Out] String ^%date, [Out] String ^%time, [Out] String ^%compiler, [Out] String ^%arch, [Out] bool %debug); static void setLogger(DynamicAudioNormalizerNET_Logger ^test); //Processing int64_t process(array ^samplesIn, array ^samplesOut, const int64_t inputSize); int64_t processInplace(array ^samplesInOut, const int64_t inputSize); int64_t flushBuffer(array ^samplesInOut); void reset(void); //Other void getConfiguration([Out] uint32_t %channels, [Out] uint32_t %sampleRate, [Out] uint32_t %frameLen, [Out] uint32_t %filterSize); int64_t getInternalDelay(void); private: int64_t p_process(array ^samplesIn, array ^samplesOut, const int64_t inputSize); int64_t p_processInplace(array ^samplesInOut, const int64_t inputSize); int64_t p_flushBuffer(array ^samplesInOut); void p_reset(void); void p_getConfiguration([Out] uint32_t %channels, [Out] uint32_t %sampleRate, [Out] uint32_t %frameLen, [Out] uint32_t %filterSize); int64_t p_getInternalDelay(void); static DynamicAudioNormalizerNET_Logger ^m_logger; MDynamicAudioNormalizer *const m_instace; }; } ================================================ FILE: DynamicAudioNormalizerNET/src/resource.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Microsoft.NET Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by app.rc ================================================ FILE: DynamicAudioNormalizerPAS/DynamicAudioNormalizerPAS.cfg ================================================ -$A8 -$B- -$C+ -$D+ -$E- -$F- -$G+ -$H+ -$I+ -$J- -$K- -$L+ -$M- -$N+ -$O+ -$P+ -$Q- -$R- -$S- -$T- -$U- -$V+ -$W- -$X+ -$YD -$Z1 -cc -AWinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; -H+ -W+ -M -$M16384,1048576 -K$00400000 -LE"c:\program files (x86)\borland\delphi7\Projects\Bpl" -LN"c:\program files (x86)\borland\delphi7\Projects\Bpl" -w-UNSAFE_TYPE -w-UNSAFE_CODE -w-UNSAFE_CAST ================================================ FILE: DynamicAudioNormalizerPAS/DynamicAudioNormalizerPAS.dof ================================================ [FileVersion] Version=7.0 [Compiler] A=8 B=0 C=1 D=1 E=0 F=0 G=1 H=1 I=1 J=0 K=0 L=1 M=0 N=1 O=1 P=1 Q=0 R=0 S=0 T=0 U=0 V=1 W=0 X=1 Y=1 Z=1 ShowHints=1 ShowWarnings=1 UnitAliases=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; NamespacePrefix= SymbolDeprecated=1 SymbolLibrary=1 SymbolPlatform=1 UnitLibrary=1 UnitPlatform=1 UnitDeprecated=1 HResultCompat=1 HidingMember=1 HiddenVirtual=1 Garbage=1 BoundsError=1 ZeroNilCompat=1 StringConstTruncated=1 ForLoopVarVarPar=1 TypedConstVarPar=1 AsgToTypedConst=1 CaseLabelRange=1 ForVariable=1 ConstructingAbstract=1 ComparisonFalse=1 ComparisonTrue=1 ComparingSignedUnsigned=1 CombiningSignedUnsigned=1 UnsupportedConstruct=1 FileOpen=1 FileOpenUnitSrc=1 BadGlobalSymbol=1 DuplicateConstructorDestructor=1 InvalidDirective=1 PackageNoLink=1 PackageThreadVar=1 ImplicitImport=1 HPPEMITIgnored=1 NoRetVal=1 UseBeforeDef=1 ForLoopVarUndef=1 UnitNameMismatch=1 NoCFGFileFound=1 MessageDirective=1 ImplicitVariants=1 UnicodeToLocale=1 LocaleToUnicode=1 ImagebaseMultiple=1 SuspiciousTypecast=1 PrivatePropAccessor=1 UnsafeType=0 UnsafeCode=0 UnsafeCast=0 [Linker] MapFile=0 OutputObjs=0 ConsoleApp=0 DebugInfo=0 RemoteSymbols=0 MinStackSize=16384 MaxStackSize=1048576 ImageBase=4194304 ExeDescription= [Directories] OutputDir= UnitOutputDir= PackageDLLOutputDir= PackageDCPOutputDir= SearchPath= Packages=vcl;rtl;vclx;indy;vclie;xmlrtl;inetdbbde;inet;inetdbxpress;dbrtl;soaprtl;dsnap;VclSmp;dbexpress;vcldb;dbxcds;inetdb;bdertl;vcldbx;adortl;teeui;teedb;tee;ibxpress;visualclx;visualdbclx;vclactnband;vclshlctrls;dclOfficeXP Conditionals= DebugSourceDirs= UsePackages=0 [Parameters] RunParams= HostApplication= Launcher= UseLauncher=0 DebugCWD=E:\DeLpHi\DynamicNormalizer\bin\Win32\Release_DLL [Language] ActiveLang= ProjectLang= RootDir= [Version Info] IncludeVerInfo=0 AutoIncBuild=0 MajorVer=1 MinorVer=0 Release=0 Build=0 Debug=0 PreRelease=0 Special=0 Private=0 DLL=0 Locale=1031 CodePage=1252 [Version Info Keys] CompanyName= FileDescription= FileVersion=1.0.0.0 InternalName= LegalCopyright= LegalTrademarks= OriginalFilename= ProductName= ProductVersion=1.0.0.0 Comments= [HistoryLists\hlUnitAliases] Count=1 Item0=WinTypes=Windows;WinProcs=Windows;DbiTypes=BDE;DbiProcs=BDE;DbiErrs=BDE; ================================================ FILE: DynamicAudioNormalizerPAS/DynamicAudioNormalizerPAS.dpr ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Delphi/Pascal Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// program DynamicAudioNormalizerPAS; uses Forms, DynamicAudioNormalizerExample in 'src\DynamicAudioNormalizerExample.pas' {DynamicAudioNormalizerTestApp}, DynamicAudioNormalizer in 'include\DynamicAudioNormalizer.pas'; {$R *.res} begin Application.Initialize; Application.Title := 'Dynamic Audio Normalizer Testbed'; Application.CreateForm(TDynamicAudioNormalizerTestApp, DynamicAudioNormalizerTestApp); Application.Run; end. ================================================ FILE: DynamicAudioNormalizerPAS/include/DynamicAudioNormalizer.pas ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Delphi/Pascal Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// // ******************************************************************************* // NOTE: This code was developed and tested with Borland Delphi 7.1 Professional // ******************************************************************************* unit DynamicAudioNormalizer; //============================================================================= interface //============================================================================= uses SysUtils; type TDoubleArray = array of Double; type TLoggingFunction = procedure(const level: LongInt; const text: PAnsiChar); cdecl; PLoggingFunction = ^TLoggingFunction; type TDynamicAudioNormalizer = class(TObject) public //Constructor & Destructor constructor Create(const channels: LongWord; const sampleRate: LongWord; const frameLenMsec: LongWord; const filterSize: LongWord; const peakValue: Double; const maxAmplification: Double; const targetRms: Double; const compressFactor: Double; const channelsCoupled: Boolean; const enableDCCorrection: Boolean; const altBoundaryMode: Boolean); destructor Destroy; override; //Processing Functions function Process(samplesIn: Array of TDoubleArray; samplesOut: Array of TDoubleArray; const sampleCount: Int64): Int64; function ProcessInplace(samplesInOut: Array of TDoubleArray; const sampleCount: Int64): Int64; function FlushBuffer(samplesOut: Array of TDoubleArray): Int64; procedure Reset; //Utility Functions procedure GetConfiguration(var channels: LongWord; var sampleRate: LongWord; var frameLen: LongWord; var filterSize: LongWord); function GetInternalDelay: Int64; //Static Functions class function SetLogFunction(const logFunction: PLoggingFunction): PLoggingFunction; class procedure GetVersionInfo(var major: LongWord; var minor: LongWord; var patch: LongWord); class procedure GetBuildInfo(var date: PAnsiChar; var time: PAnsiChar; var compiler: PAnsiChar; var arch: PAnsiChar; var debug: LongBool); private instance: Pointer; end; //============================================================================= implementation //============================================================================= const DynamicAudioNormalizerTag = '_r8'; const DynamicAudioNormalizerDLL = 'DynamicAudioNormalizerAPI.dll'; const DynamicAudioNormalizerPre = 'MDynamicAudioNormalizer_'; //----------------------------------------------------------------------------- // Native Functions //----------------------------------------------------------------------------- function DynAudNorm_CreateInstance(const channels: LongWord; const sampleRate: LongWord; const frameLenMsec: LongWord; const filterSize: LongWord; const peakValue: Double; const maxAmplification: Double; const targetRms: Double; const compressFactor: Double; const channelsCoupled: LongBool; const enableDCCorrection: LongBool; const altBoundaryMode: LongBool; const logFile: Pointer): Pointer; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'createInstance' + DynamicAudioNormalizerTag); procedure DynAudNorm_DestroyInstance(var handle: Pointer); cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'destroyInstance' + DynamicAudioNormalizerTag); function DynAudNorm_Process(const handle: Pointer; const samplesIn: Pointer; const samplesOut: Pointer; const inputSize: Int64; var outputSize: Int64): LongBool; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'processInplace' + DynamicAudioNormalizerTag); function DynAudNorm_ProcessInplace(const handle: Pointer; const samplesInOut: Pointer; const inputSize: Int64; var outputSize: Int64): LongBool; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'processInplace' + DynamicAudioNormalizerTag); function DynAudNorm_FlushBuffer(const handle: Pointer; const samplesOut: Pointer; const bufferSize: Int64; var outputSize: Int64): LongBool; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'flushBuffer' + DynamicAudioNormalizerTag); function DynAudNorm_GetConfiguration(const handle: Pointer; var channels: LongWord; var sampleRate: LongWord; var frameLen: LongWord; var filterSize: LongWord): LongBool; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'getConfiguration' + DynamicAudioNormalizerTag); function DynAudNorm_Reset(const handle: Pointer): LongBool; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'reset' + DynamicAudioNormalizerTag); function DynAudNorm_GetInternalDelay(const handle: Pointer; var delayInSamples: Int64): LongBool; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'getInternalDelay' + DynamicAudioNormalizerTag); function DynAudNorm_SetLogFunction(const logFunction: PLoggingFunction): PLoggingFunction; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'setLogFunction' + DynamicAudioNormalizerTag); function DynAudNorm_GetVersionInfo(var major: LongWord; var minor: LongWord; var patch: LongWord): LongBool; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'getVersionInfo' + DynamicAudioNormalizerTag); function DynAudNorm_GetBuildInfo(var date: PAnsiChar; var time: PAnsiChar; var compiler: PAnsiChar; var arch: PAnsiChar; var debug: LongBool): LongBool; cdecl; external DynamicAudioNormalizerDLL name (DynamicAudioNormalizerPre + 'getBuildInfo' + DynamicAudioNormalizerTag); //----------------------------------------------------------------------------- // Static Functions //----------------------------------------------------------------------------- class procedure TDynamicAudioNormalizer.GetVersionInfo(var major: LongWord; var minor: LongWord; var patch: LongWord); begin if not DynAudNorm_GetVersionInfo(major, minor, patch) then begin Raise Exception.Create('Failed to retrieve library version info!'); end; end; class procedure TDynamicAudioNormalizer.GetBuildInfo(var date: PAnsiChar; var time: PAnsiChar; var compiler: PAnsiChar; var arch: PAnsiChar; var debug: LongBool); begin if not DynAudNorm_GetBuildInfo(date, time, compiler, arch, debug) then begin Raise Exception.Create('Failed to retrieve library build configuration!'); end; end; class function TDynamicAudioNormalizer.SetLogFunction(const logFunction: PLoggingFunction): PLoggingFunction; begin Result := DynAudNorm_SetLogFunction(logFunction); end; //----------------------------------------------------------------------------- // Constructor & Destructor //----------------------------------------------------------------------------- constructor TDynamicAudioNormalizer.Create(const channels: LongWord; const sampleRate: LongWord; const frameLenMsec: LongWord; const filterSize: LongWord; const peakValue: Double; const maxAmplification: Double; const targetRms: Double; const compressFactor: Double; const channelsCoupled: Boolean; const enableDCCorrection: Boolean; const altBoundaryMode: Boolean); begin instance := DynAudNorm_CreateInstance(channels, sampleRate, frameLenMsec, filterSize, peakValue, maxAmplification, targetRms, compressFactor, channelsCoupled, enableDCCorrection, altBoundaryMode, nil); if not Assigned(instance) then begin Raise Exception.Create('Failed to create DynamicAudioNormalizer instance!'); end; end; destructor TDynamicAudioNormalizer.Destroy; begin if Assigned(instance) then begin DynAudNorm_DestroyInstance(instance); if Assigned(instance) then begin Raise Exception.Create('Failed to destroy DynamicAudioNormalizer instance!'); end; end; inherited; {Parent Destructor} end; //----------------------------------------------------------------------------- // Processing Functions //----------------------------------------------------------------------------- function TDynamicAudioNormalizer.Process(samplesIn: Array of TDoubleArray; samplesOut: Array of TDoubleArray; const sampleCount: Int64): Int64; var bufferIn, bufferOut: Array of Pointer; i: LongWord; channels, sampleRate, frameLen, filterSize: LongWord; outputSize: Int64; begin if not Assigned(instance) then begin Raise Exception.Create('Native instance not created yet!'); end; GetConfiguration(channels, sampleRate, frameLen, filterSize); if Length(samplesIn) <> Integer(channels) then begin Raise Exception.Create('Array dimension doesn''t match channel count!'); end; if Length(samplesOut) <> Integer(channels) then begin Raise Exception.Create('Array dimension doesn''t match channel count!'); end; SetLength(bufferIn, Length(samplesIn)); SetLength(bufferOut, Length(samplesOut)); for i := 0 to Length(samplesIn)-1 do begin if Length(samplesIn[i]) < sampleCount then begin Raise Exception.Create('Array length is smaller than specified sample count!'); end; if Length(samplesOut[i]) < sampleCount then begin Raise Exception.Create('Array length is smaller than specified sample count!'); end; bufferIn[i] := @samplesIn [i][0]; bufferOut[i] := @samplesOut[i][0]; end; if not DynAudNorm_Process(instance, @bufferIn[0], @bufferOut[0], sampleCount, outputSize) then begin Raise Exception.Create('Failed to process samples in-place!'); end; Result := outputSize; end; function TDynamicAudioNormalizer.ProcessInplace(samplesInOut: Array of TDoubleArray; const sampleCount: Int64): Int64; var buffer: Array of Pointer; i: LongWord; channels, sampleRate, frameLen, filterSize: LongWord; outputSize: Int64; begin if not Assigned(instance) then begin Raise Exception.Create('Native instance not created yet!'); end; GetConfiguration(channels, sampleRate, frameLen, filterSize); if Length(samplesInOut) <> Integer(channels) then begin Raise Exception.Create('Array dimension doesn''t match channel count!'); end; SetLength(buffer, Length(samplesInOut)); for i := 0 to Length(samplesInOut)-1 do begin if Length(samplesInOut[i]) < sampleCount then begin Raise Exception.Create('Array length is smaller than specified sample count!'); end; buffer[i] := @samplesInOut[i][0]; end; if not DynAudNorm_ProcessInplace(instance, @buffer[0], sampleCount, outputSize) then begin Raise Exception.Create('Failed to process samples in-place!'); end; Result := outputSize; end; function TDynamicAudioNormalizer.FlushBuffer(samplesOut: Array of TDoubleArray): Int64; var buffer: Array of Pointer; i: LongWord; channels, sampleRate, frameLen, filterSize: LongWord; outputSize: Int64; begin if not Assigned(instance) then begin Raise Exception.Create('Native instance not created yet!'); end; GetConfiguration(channels, sampleRate, frameLen, filterSize); if Length(samplesOut) <> Integer(channels) then begin Raise Exception.Create('Array dimension doesn''t match channel count!'); end; SetLength(buffer, Length(samplesOut)); for i := 0 to Length(samplesOut)-1 do begin if Length(samplesOut[i]) <> Length(samplesOut[0]) then begin Raise Exception.Create('Lengths of "inner" array''s are *not* inconsistent!'); end; buffer[i] := @samplesOut[i][0]; end; if not DynAudNorm_FlushBuffer(instance, @buffer[0], Length(samplesOut[0]), outputSize) then begin Raise Exception.Create('Failed to flush samples from buffer!'); end; Result := outputSize; end; procedure TDynamicAudioNormalizer.Reset; begin if not Assigned(instance) then begin Raise Exception.Create('Native instance not created yet!'); end; if not DynAudNorm_Reset(instance) then begin Raise Exception.Create('Failed to reset DynamicAudioNormalizer instance!'); end; end; //----------------------------------------------------------------------------- // Utility Functions //----------------------------------------------------------------------------- procedure TDynamicAudioNormalizer.GetConfiguration(var channels: LongWord; var sampleRate: LongWord; var frameLen: LongWord; var filterSize: LongWord); begin if not Assigned(instance) then begin Raise Exception.Create('Native instance not created yet!'); end; if not DynAudNorm_GetConfiguration(instance, channels, sampleRate, frameLen, filterSize) then begin Raise Exception.Create('Failed to get current configuration!'); end; end; function TDynamicAudioNormalizer.GetInternalDelay: Int64; begin if not Assigned(instance) then begin Raise Exception.Create('Native instance not created yet!'); end; if not DynAudNorm_GetInternalDelay(instance, Result) then begin Raise Exception.Create('Failed to get current configuration!'); end; end; end. ================================================ FILE: DynamicAudioNormalizerPAS/src/DynamicAudioNormalizerExample.dfm ================================================ object DynamicAudioNormalizerTestApp: TDynamicAudioNormalizerTestApp Left = 618 Top = 301 BorderIcons = [biSystemMenu, biMinimize] BorderStyle = bsSingle Caption = 'DynAudNorm Testbed' ClientHeight = 145 ClientWidth = 267 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object ButtonTest1: TButton Left = 8 Top = 8 Width = 249 Height = 25 Caption = 'Create and Destory many instances' TabOrder = 0 OnClick = ButtonTest1Click end object ButtonExit: TButton Left = 8 Top = 112 Width = 249 Height = 25 Caption = 'Exit' TabOrder = 1 OnClick = ButtonExitClick end object ButtonTest2: TButton Left = 8 Top = 40 Width = 249 Height = 25 Caption = 'Process complete Audio File' TabOrder = 2 OnClick = ButtonTest2Click end object ProgressBar1: TProgressBar Left = 8 Top = 80 Width = 249 Height = 17 Smooth = True TabOrder = 3 end object ApplicationEvents1: TApplicationEvents OnException = ApplicationEvents1Exception Left = 8 Top = 72 end object XPManifest1: TXPManifest Left = 40 Top = 72 end object OpenDialog: TOpenDialog DefaultExt = 'pcm' Filter = 'Raw PCM data (*.pcm)|*.pcm' Options = [ofHideReadOnly, ofNoChangeDir, ofPathMustExist, ofFileMustExist, ofEnableSizing] Title = 'Select Source File' Left = 72 Top = 72 end object SaveDialog: TSaveDialog DefaultExt = 'pcm' Filter = 'Raw PCM data (*.pcm)|*.pcm' Options = [ofOverwritePrompt, ofHideReadOnly, ofNoChangeDir, ofPathMustExist, ofEnableSizing] Title = 'Select Output File' Left = 104 Top = 72 end end ================================================ FILE: DynamicAudioNormalizerPAS/src/DynamicAudioNormalizerExample.pas ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Delphi/Pascal Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// unit DynamicAudioNormalizerExample; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AppEvnts, Math, DateUtils, ComCtrls, XPMan; type TDynamicAudioNormalizerTestApp = class(TForm) ButtonTest1: TButton; ButtonExit: TButton; ButtonTest2: TButton; ApplicationEvents1: TApplicationEvents; ProgressBar1: TProgressBar; XPManifest1: TXPManifest; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; procedure ButtonTest1Click(Sender: TObject); procedure ButtonExitClick(Sender: TObject); procedure ButtonTest2Click(Sender: TObject); procedure ApplicationEvents1Exception(Sender: TObject; E: Exception); procedure FormCreate(Sender: TObject); private LastUpdate: TDateTime; procedure StartStopTest(const start: boolean); procedure UpdateProgress; public { Public-Deklarationen } end; var DynamicAudioNormalizerTestApp: TDynamicAudioNormalizerTestApp; implementation uses DynamicAudioNormalizer; {$R *.dfm} //----------------------------------------------------------------------------- // Log Callback //----------------------------------------------------------------------------- {WARNING: This function must use 'cdecl' calling convention!} procedure loggingHandler(const level: LongInt; const text: PAnsiChar); cdecl; var tag: String; begin case level of 0: tag := 'DBG'; 1: tag := 'WRN'; 2: tag := 'ERR'; else tag := '???'; end; WriteLn(Format('[DynAudNorm][%s] %s', [tag, text])); end; //----------------------------------------------------------------------------- // Helper Functions //----------------------------------------------------------------------------- procedure TDynamicAudioNormalizerTestApp.UpdateProgress; begin if ProgressBar1.Position < ProgressBar1.Max then begin ProgressBar1.StepBy(1); LastUpdate := Now; end else begin if MilliSecondsBetween(Now, LastUpdate) >= 997 then begin ProgressBar1.Position := 0; LastUpdate := Now; end end; Application.ProcessMessages; end; procedure TDynamicAudioNormalizerTestApp.StartStopTest(const start: boolean); var i: Integer; begin if start then begin for i := 0 to Self.ControlCount-1 do begin Self.Controls[i].Enabled := False; end; ProgressBar1.Position := 0; end else begin MessageBeep(1000); for i := 0 to Self.ControlCount-1 do begin Self.Controls[i].Enabled := True; end; ProgressBar1.Position := ProgressBar1.Max; end; end; //----------------------------------------------------------------------------- // Misc Functions //----------------------------------------------------------------------------- procedure TDynamicAudioNormalizerTestApp.FormCreate(Sender: TObject); var major, minor, patch: LongWord; date, time, compiler, arch: PAnsiChar; debug: LongBool; begin LastUpdate := Now; TDynamicAudioNormalizer.GetVersionInfo(major, minor, patch); WriteLn(Format('Library Version: %s', [StringReplace(Format('%u.%02u-%u', [major, minor, patch]), ' ', '0', [rfReplaceAll])])); TDynamicAudioNormalizer.GetBuildInfo(date, time, compiler, arch, debug); WriteLn(Format('Build: Date=%s; Time=%s; Compiler=%s; Arch=%s; Debug=%s'#10, [date, time, compiler, arch, BoolToStr(debug)])); TDynamicAudioNormalizer.SetLogFunction(@loggingHandler); end; procedure TDynamicAudioNormalizerTestApp.ButtonExitClick(Sender: TObject); begin Application.Terminate; end; procedure TDynamicAudioNormalizerTestApp.ApplicationEvents1Exception(Sender: TObject; E: Exception); begin MessageBox(self.Handle, @E.Message[1], 'ERROR', MB_ICONERROR or MB_TOPMOST); ExitProcess(DWORD(-1)); end; //----------------------------------------------------------------------------- // TEST #1 //----------------------------------------------------------------------------- procedure TDynamicAudioNormalizerTestApp.ButtonTest1Click(Sender: TObject); const rounds = 97; instances = 16; var normalizer: Array [1..instances] of TDynamicAudioNormalizer; i,k: Cardinal; begin StartStopTest(True); for k := 1 to rounds do begin WriteLn('Round ' + IntToStr(k) + ' of ' + IntToStr(rounds) + '.'); for i := 1 to instances do begin normalizer[i] := TDynamicAudioNormalizer.Create(2, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, True, False, False); if i mod 4 = 0 then UpdateProgress; end; for i := 1 to instances do begin FreeAndNil(normalizer[i]); if i mod 4 = 0 then UpdateProgress; end; end; WriteLn('Done.'#10); StartStopTest(False); MessageBox(self.WindowHandle, 'Test completed successfully.', PAnsiChar(self.Caption), MB_ICONINFORMATION); end; //----------------------------------------------------------------------------- // TEST #2 //----------------------------------------------------------------------------- procedure TDynamicAudioNormalizerTestApp.ButtonTest2Click(Sender: TObject); const frameSize = 4096; channelCount = 2; MAX_SHORT: Double = 32767.0; var samples: Array of TDoubleArray; buffer: array[0..((channelCount*frameSize)-1)] of SmallInt; inputFile, outputFile: THandle; normalizer: TDynamicAudioNormalizer; i, j, k, q: Cardinal; readSize, writeSize, bytesWritten: Cardinal; begin {========================= SELECT FILES ========================} if not OpenDialog.Execute then begin Exit; end; if not SaveDialog.Execute then begin Exit; end; {============================ SETUP ============================} StartStopTest(True); SetLength(samples, channelCount, frameSize); WriteLn('Open I/O files...'); inputFile := CreateFile(PAnsiChar(OpenDialog.Files[0]), GENERIC_READ, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); outputFile := CreateFile(PAnsiChar(SaveDialog.Files[0]), GENERIC_WRITE, 0, nil, CREATE_ALWAYS, 0, 0); if (inputFile = INVALID_HANDLE_VALUE) or (outputFile = INVALID_HANDLE_VALUE) then begin Raise Exception.Create('Failed to open input/output files!'); end; WriteLn('Creating normalizer instance...'); normalizer := TDynamicAudioNormalizer.Create(channelCount, 44100, 500, 31, 0.95, 10.0, 0.0, 0.0, True, False, False); WriteLn('Internal delay: ' + IntToStr(normalizer.GetInternalDelay)); {=========================== PROCESS ===========================} WriteLn('Processing, please wait...'); for q := 0 to 2147483647 do begin if not ReadFile(inputFile, buffer, frameSize * channelCount * SizeOf(SmallInt), readSize, nil) then begin Raise Exception.Create('Read operation has failed!'); end; readSize := readSize div (channelCount * SizeOf(SmallInt)); if readSize > 0 then begin k := 0; for i := 0 to (readSize-1) do begin for j := 0 to (channelCount-1) do begin samples[j][i] := buffer[k] / MAX_SHORT; k := k + 1; end; end; end; writeSize := normalizer.ProcessInplace(samples, readSize); //WriteLn('Result: readSize=' + IntToStr(readSize) + '; writeSize=' + IntToStr(writeSize)); if writeSize > 0 then begin k := 0; for i := 0 to (writeSize-1) do begin for j := 0 to (channelCount-1) do begin buffer[k] := SmallInt(Round(Max(-1.0,Min(1.0,samples[j][i])) * MAX_SHORT)); k := k + 1; end; end; if not WriteFile(outputFile, buffer, writeSize * channelCount * SizeOf(SmallInt), bytesWritten, nil) then begin Raise Exception.Create('Write operation has failed!'); end; end; if readSize < frameSize then begin Break; {End of File} end; if q mod 32 = 0 then begin UpdateProgress; end; end; {============================ FLUSH ============================} WriteLn('Flushing buffer, please wait...'); for q := 0 to 2147483647 do begin writeSize := normalizer.FlushBuffer(samples); if writeSize > 0 then begin k := 0; for i := 0 to (writeSize-1) do begin for j := 0 to (channelCount-1) do begin buffer[k] := SmallInt(Round(Max(-1.0,Min(1.0,samples[j][i])) * MAX_SHORT)); k := k + 1; end; end; if not WriteFile(outputFile, buffer, writeSize * channelCount * SizeOf(SmallInt), bytesWritten, nil) then begin Raise Exception.Create('Write operation has failed!'); end; end; if writeSize < 1 then begin Break; {No more samples left} end; if q mod 32 = 0 then begin UpdateProgress; end; end; {============================ CLOSE ============================} WriteLn('Shutting down...'); normalizer.Reset(); {Just to make sure that the Reset() function works} {============================ RESET ============================} FreeAndNil(normalizer); FlushFileBuffers(outputFile); CloseHandle(inputFile); CloseHandle(outputFile); WriteLn('Done.'#10); StartStopTest(False); MessageBox(self.WindowHandle, 'Test completed successfully.', PAnsiChar(self.Caption), MB_ICONINFORMATION); end; end. ================================================ FILE: DynamicAudioNormalizerPYD/DynamicAudioNormalizerPYD_VS2013.vcxproj ================================================  Debug Win32 Release_DLL Win32 Debug x64 Release_DLL x64 Release_Static Win32 Release_Static x64 {376386ee-8268-47e3-a335-7663716e4c60} {5ACB9827-9D3A-4C59-A948-8505D1544A8E} Win32Proj DynamicAudioNormalizerPYD 8.1 DynamicAudioNormalizerPYD DynamicLibrary true v120_xp Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary true v120_xp Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL NoExtensions Windows true $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 Disabled _DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL Windows true $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreadedDLL false Fast StreamingSIMDExtensions2 $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false Fast $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true StreamingSIMDExtensions2 Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreadedDLL false Fast $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false Fast $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib ================================================ FILE: DynamicAudioNormalizerPYD/DynamicAudioNormalizerPYD_VS2013.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files ================================================ FILE: DynamicAudioNormalizerPYD/DynamicAudioNormalizerPYD_VS2015.vcxproj ================================================  Debug Win32 Release_DLL Win32 Debug x64 Release_DLL x64 Release_Static Win32 Release_Static x64 {376386ee-8268-47e3-a335-7663716e4c60} {5ACB9827-9D3A-4C59-A948-8505D1544A8E} Win32Proj DynamicAudioNormalizerPYD 8.1 DynamicAudioNormalizerPYD DynamicLibrary true v140_xp Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary true v140_xp Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL NoExtensions Windows true $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 Disabled _DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL Windows true $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreadedDLL false Fast StreamingSIMDExtensions2 $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false Fast $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true StreamingSIMDExtensions2 Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreadedDLL false Fast $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false Fast $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib ================================================ FILE: DynamicAudioNormalizerPYD/DynamicAudioNormalizerPYD_VS2015.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files ================================================ FILE: DynamicAudioNormalizerPYD/DynamicAudioNormalizerPYD_VS2017.vcxproj ================================================  Debug Win32 Release_DLL Win32 Debug x64 Release_DLL x64 Release_Static Win32 Release_Static x64 {376386ee-8268-47e3-a335-7663716e4c60} {5ACB9827-9D3A-4C59-A948-8505D1544A8E} Win32Proj DynamicAudioNormalizerPYD 7.0 DynamicAudioNormalizerPYD DynamicLibrary true v141_xp Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary true v141_xp Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ .pyd Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL NoExtensions Windows true $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 Disabled _DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL Windows true $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib Level3 MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreadedDLL false Fast StreamingSIMDExtensions2 $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false Fast $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true StreamingSIMDExtensions2 Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 MaxSpeed true true NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreadedDLL false Fast $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 MaxSpeed true true NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERPYD_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false Fast $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\..\Prerequisites\Python3\include;%(AdditionalIncludeDirectories) AnySuitable Speed true true Windows true true false $(SolutionDir)\..\Prerequisites\Python3\lib\$(Platform);%(AdditionalLibraryDirectories) %(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) ================================================ FILE: DynamicAudioNormalizerPYD/DynamicAudioNormalizerPYD_VS2017.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Resource Files ================================================ FILE: DynamicAudioNormalizerPYD/include/DynamicAudioNormalizer.py ================================================ ################################################################################## # Dynamic Audio Normalizer - Python Wrapper # Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # 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 OR COPYRIGHT HOLDERS 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. # # http://opensource.org/licenses/MIT ################################################################################## #import stdlib modules import sys #define API version DYNAMIC_AUDIONORMALIZER_API = 8 #import the native "C" module try: import DynamicAudioNormalizerPYD except: pass #error checking if (not 'DynamicAudioNormalizerPYD' in locals()) or (not hasattr(DynamicAudioNormalizerPYD, 'getCoreVersion')): raise SystemError("The native DynamicAudioNormalizerPYD module is *not* available. Please make sure that 'DynamicAudioNormalizerPYD.pyd' has been installed correctly!") #version checking if DynamicAudioNormalizerPYD.getCoreVersion() != DYNAMIC_AUDIONORMALIZER_API: raise SystemError("The native DynamicAudioNormalizerPYD module uses an *unsupported* API version. Please install the matching 'DynamicAudioNormalizerPYD.pyd' library!") #---------------------------------------------------------------------- # DynamicAudioNormalizer #---------------------------------------------------------------------- class PyDynamicAudioNormalizer: """Wrapper class around the DynamicAudioNormalizerPYD library""" def __str__(self): versionInfo = self.getVersion() buildStr = "built: {} {}, compiler: {}, arch: {}, {}".format(*versionInfo[1]) configStr = "channels={}, samplingRate={}, frameLen={}, filterSize={}".format(*self.getConfig()) return "DynamicAudioNormalizer v{}.{}-{} [{}][{}]]".format(*versionInfo[0], buildStr, configStr) def __init__(self, channels, samplerate, filterSize=31, frameLen=500, peakValue=0.95, maxAmplification=10.0, targetRms=0.0, compressFactor=0.0, channelsCoupled=True, enableDCCorrection=False, altBoundaryMode=False): self._channels = int(channels) self._samplerate = int(samplerate) self._frameLen = int(frameLen) self._filterSize = int(filterSize) self._peakValue = float(peakValue) self._maxAmplification = float(maxAmplification) self._targetRms = float(targetRms) self._compressFactor = float(compressFactor) self._channelsCoupled = not (not channelsCoupled) self._enableDCCorrection = not (not enableDCCorrection) self._altBoundaryMode = not (not altBoundaryMode) self._instance = None def __enter__(self): options = (self._peakValue, self._maxAmplification, self._targetRms, self._compressFactor, self._channelsCoupled, self._enableDCCorrection, self._altBoundaryMode) self._instance = DynamicAudioNormalizerPYD.createInstance(self._channels, self._samplerate, self._frameLen, self._filterSize, *options) return self def __exit__(self, type, value, traceback): if not self._instance: raise RuntimeError("Instance not initialized!") DynamicAudioNormalizerPYD.destroyInstance(self._instance) self._instance = None def __del__(self): if self._instance: print("RESOURCE LEAK: DynamicAudioNormalizer object was not de-initialized properly!", file=sys.stderr) def getConfiguration(self): if not self._instance: raise RuntimeError("Instance not initialized!") return DynamicAudioNormalizerPYD.getConfiguration(self._instance) def getInternalDelay(self): if not self._instance: raise RuntimeError("Instance not initialized!") return DynamicAudioNormalizerPYD.getInternalDelay(self._instance) def process(self, samplesIn, samplesOut, count): if not self._instance: raise RuntimeError("Instance not initialized!") return DynamicAudioNormalizerPYD.process(self._instance, samplesIn, samplesOut, count) def processInplace(self, samplesInOut, count): if not self._instance: raise RuntimeError("Instance not initialized!") return DynamicAudioNormalizerPYD.processInplace(self._instance, samplesInOut, count) def flushBuffer(self, samplesOut): if not self._instance: raise RuntimeError("Instance not initialized!") return DynamicAudioNormalizerPYD.flushBuffer(self._instance, samplesOut) @staticmethod def setLogFunction(callback): return DynamicAudioNormalizerPYD.setLogFunction(callback) @staticmethod def getVersion(): return DynamicAudioNormalizerPYD.getVersionInfo() ================================================ FILE: DynamicAudioNormalizerPYD/makefile ================================================ ############################################################################## # Dynamic Audio Normalizer - Audio Processing Library # Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # http://www.gnu.org/licenses/lgpl-2.1.txt ############################################################################## ECHO=echo -e SHELL=/bin/bash PYTHON_INC ?= $(shell python3 -c "from distutils import sysconfig; print(sysconfig.get_python_inc())" || echo "/usr/include/python3.5") ############################################################################## # Constants ############################################################################## LIBRARY_NAME := DynamicAudioNormalizerPYD ifndef API_VERSION $(error API_VERSION variable is not set!) endif ############################################################################## # Python Checks ############################################################################## ifneq ($(MAKECMDGOALS),clean) PY_CHECK := $(shell [ -f $(PYTHON_INC)/Python.h ] && echo true || echo false) ifneq ($(PY_CHECK),true) $(error File "Python.h" not found in PYTHON_INC path!) endif endif ############################################################################## # Flags ############################################################################## DEBUG_BUILD ?= 0 MARCH ?= native ifeq ($(DEBUG_BUILD), 1) CONFIG_NAME = Debug CXXFLAGS = -g -O0 -D_DEBUG else CONFIG_NAME = Release CXXFLAGS = -O3 -Wall -ffast-math -mfpmath=sse -msse -fomit-frame-pointer -fno-tree-vectorize -DNDEBUG -march=$(MARCH) endif ifneq ($(findstring MINGW,$(shell uname -s)),MINGW) CXXFLAGS += -fPIC endif CXXFLAGS += -std=gnu++11 CXXFLAGS += -fvisibility=hidden CXXFLAGS += -I./src CXXFLAGS += -I../DynamicAudioNormalizerAPI/include CXXFLAGS += -I../DynamicAudioNormalizerShared/include CXXFLAGS += -I$(PYTHON_INC) ifneq ($(findstring MINGW,$(shell uname -s)),MINGW) LDXFLAGS += -Wl,-rpath,'$$ORIGIN' endif LDXFLAGS += -L../DynamicAudioNormalizerAPI/lib LDXFLAGS += -lDynamicAudioNormalizerAPI-$(API_VERSION) ifeq ($(shell uname), Darwin) PYTHON_LIB := $(shell python3 -c "from distutils import sysconfig; print(sysconfig.get_config_var('LIBDIR'))") PYTHON_VERSION := $(shell python3 -c "from distutils import sysconfig; print(sysconfig.get_config_var('VERSION'))") LDXFLAGS += -lpython$(PYTHON_VERSION) -L$(PYTHON_LIB) endif ############################################################################## # File Names ############################################################################## ifeq ($(findstring MINGW,$(shell uname -s)),MINGW) SO_EXT = pyd LDXFLAGS += -Wl,--out-implib,$@.a SHAREDFLAG = -shared else ifeq ($(shell uname), Darwin) SO_EXT = so # SHAREDFLAG = -dynamiclib SHAREDFLAG = -shared else SO_EXT = so SHAREDFLAG = -shared endif SOURCES_CPP = $(wildcard src/*.cpp) SOURCES_OBJ = $(patsubst %.cpp,%.o,$(SOURCES_CPP)) LIBRARY_OUT = lib/$(LIBRARY_NAME) LIBRARY_BIN = $(LIBRARY_OUT).$(SO_EXT) LIBRARY_DBG = $(LIBRARY_OUT)-DBG.$(SO_EXT) ############################################################################## # Rules ############################################################################## .PHONY: all clean all: $(LIBRARY_DBG) $(LIBRARY_BIN) #------------------------------------------------------------- # Link & Strip #------------------------------------------------------------- $(LIBRARY_BIN): $(SOURCES_OBJ) @$(ECHO) "\e[1;36m[STR] $@\e[0m" @mkdir -p $(dir $@) g++ $(SHAREDFLAG) -g0 -o $@ $+ $(LDXFLAGS) ifeq ($(shell uname), Darwin) install_name_tool -id "@rpath/$(notdir $@)" $@ strip -u -r -x $@ else strip --strip-unneeded $@ endif $(LIBRARY_DBG): $(SOURCES_OBJ) @$(ECHO) "\e[1;36m[LNK] $@\e[0m" @mkdir -p $(dir $@) g++ $(SHAREDFLAG) -o $@ $+ $(LDXFLAGS) ifeq ($(shell uname), Darwin) install_name_tool -id "@rpath/$(notdir $@)" $@ endif #------------------------------------------------------------- # Compile #------------------------------------------------------------- %.o: %.cpp @$(ECHO) "\e[1;36m[CXX] $<\e[0m" @mkdir -p $(dir $@) g++ $(CXXFLAGS) -c $< -o $@ #------------------------------------------------------------- # Clean #------------------------------------------------------------- clean: rm -fv $(SOURCES_OBJ) rm -rfv ./lib ================================================ FILE: DynamicAudioNormalizerPYD/res/DynamicAudioNormalizerPYD.rc ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "WinResrc.h" //"afxres.h" #define INC_DYNAUDNORM_VERSION_INTERNAL 0x22b4f8a9 #include "../DynamicAudioNormalizerShared/res/version.inc" ////////////////////////////////////////////////////////////////////////////////// // Neutral resources ////////////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) #ifdef _WIN32 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL #pragma code_page(1252) #endif //_WIN32 ////////////////////////////////////////////////////////////////////////////////// // Version ////////////////////////////////////////////////////////////////////////////////// VS_VERSION_INFO VERSIONINFO FILEVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH PRODUCTVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x3L #else FILEFLAGS 0x2L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ." VALUE "CompanyName", "LoRd_MuldeR " VALUE "FileDescription", "DynamicAudioNormalizer Python Wrapper" VALUE "FileVersion", VER_DYNAUDNORM_STR VALUE "InternalName", "DynamicAudioNormalizerPYD" VALUE "LegalCopyright", "Copyright (c) 2014-2019 LoRd_MuldeR " VALUE "LegalTrademarks", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License " VALUE "OriginalFilename", "DynamicAudioNormalizerPYD.dll" VALUE "ProductName", "DynamicAudioNormalizer" VALUE "ProductVersion", VER_DYNAUDNORM_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // Neutral resources ================================================ FILE: DynamicAudioNormalizerPYD/samples/DynamicAudioNormalizerExample.py ================================================ ################################################################################## # Dynamic Audio Normalizer - Python Wrapper # Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # 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 OR COPYRIGHT HOLDERS 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. # # http://opensource.org/licenses/MIT ################################################################################## #import stdlib modules import sys import os import datetime import array #import PyDynamicAudioNormalizer from DynamicAudioNormalizer import PyDynamicAudioNormalizer #import Wave Reader and Writer from WaveFileUtils import WaveFileReader from WaveFileUtils import WaveFileWriter #---------------------------------------------------------------------- # Utility Functions #---------------------------------------------------------------------- def alloc_sample_buffers(channles, length): buffers = () for i in range(0, channles): arr = array.array('d') for j in range(0, length): arr.append(0.0) buffers += (arr,) return buffers #---------------------------------------------------------------------- # Logging Callback #---------------------------------------------------------------------- logfile = None def my_log_func(level, message): if logfile: logfile.write("[{}][{}] {}\n".format(datetime.datetime.utcnow().isoformat(), int(level), message)) logfile.flush() #---------------------------------------------------------------------- # Processing Loop #---------------------------------------------------------------------- def normalize_samples(wav_reader, wav_writer, logfile, config): print(" Done!\nInitializing...", end = '', flush = True) if logfile: PyDynamicAudioNormalizer.setLogFunction(my_log_func) with PyDynamicAudioNormalizer(wav_reader.getChannels(), wav_reader.getSamplerate(), *config) as normalizer: indicator, buffersIn, buffersOut = 0, alloc_sample_buffers(wav_reader.getChannels(), 4096), alloc_sample_buffers(wav_reader.getChannels(), 4096) print(" Done!\nProcessing audio samples...", end = '', flush = True) while True: count = wav_reader.read(buffersIn) if count: count = normalizer.process(buffersIn, buffersOut, count) if count: wav_writer.write(buffersOut, count) indicator += 1 if indicator >= 7: print('.', end = '', flush = True) indicator = 0 continue break; print(" Done!\nFlushing buffers...", end = '', flush = True) while True: count = normalizer.flushBuffer(buffersOut) if count: wav_writer.write(buffersOut, count) indicator += 1 if indicator >= 7: print('.', end = '', flush = True) indicator = 0 continue break; print(' Done!\n') #---------------------------------------------------------------------- # Main #---------------------------------------------------------------------- version = PyDynamicAudioNormalizer.getVersion() print("Dynamic Audio Normalizer, Version {}.{}-{} [{}]".format(*version[0], version[1][4])) print("Copyright (c) 2014-{} LoRd_MuldeR . Some rights reserved.".format(version[1][0][7:])) print("Built on {} at {} with {} for Python-{}.\n".format(*version[1])) if (len(sys.argv) >= 5): config = (int(sys.argv[1]), int(sys.argv[2])) source_file = os.path.abspath(sys.argv[3]) output_file = os.path.abspath(sys.argv[4]) elif (len(sys.argv) >= 4): config = (int(sys.argv[1]),) source_file = os.path.abspath(sys.argv[2]) output_file = os.path.abspath(sys.argv[3]) elif (len(sys.argv) >= 3): config = () source_file = os.path.abspath(sys.argv[1]) output_file = os.path.abspath(sys.argv[2]) else: print("Usage:\n {} {} [[] frameLen] \n".format(os.path.basename(sys.executable), os.path.basename(__file__)), file=sys.stderr) sys.exit(1) if not os.path.isfile(source_file): print("Input file \"{}\" not found!\n".format(source_file), file=sys.stderr) sys.exit(1) print("Source file: \"{}\"".format(source_file)) print("Output file: \"{}\"".format(output_file)) logfilePath = os.environ.get('LOGFILE') if logfilePath: print("Report file: \"{}\"".format(logfilePath)) logfile = open(logfilePath, 'w') else: logfile = None print("\nOpening input and output files...", end = '', flush = True) with WaveFileReader(source_file) as wav_reader: with WaveFileWriter(output_file, wav_reader.getChannels(), wav_reader.getSampleWidth(), wav_reader.getSamplerate()) as wav_writer: normalize_samples(wav_reader, wav_writer, logfile, config) print('All is done. Goodbye.') if logfile: logfile.close() ================================================ FILE: DynamicAudioNormalizerPYD/samples/WaveFileUtils.py ================================================ ################################################################################## # Dynamic Audio Normalizer - Python Wrapper # Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # 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 OR COPYRIGHT HOLDERS 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. # # http://opensource.org/licenses/MIT ################################################################################## #import stdlib modules import sys import math import struct import wave #---------------------------------------------------------------------- # Wave Audio Base #---------------------------------------------------------------------- class _WaveFileBase: """Base class for Wave file sample processing""" _THRESHOLD = math.sqrt(2.0) def _unpack_samples(self, samples, buffers, channels, sampwidth): cidx, sidx = 0, 0 type = self._get_sample_type(sampwidth) for sample in struct.iter_unpack(type[0], samples): if type[1] > self._THRESHOLD: buffers[cidx][sidx] = float(sample[0]) / float(type[1]) else: buffers[cidx][sidx] = float(sample[0]) cidx += 1 if cidx >= channels: cidx, sidx = 0, sidx + 1 return sidx def _repack_samples(self, buffers, channels, sampwidth, length): type = self._get_sample_type(sampwidth) samples = bytearray(channels * length * sampwidth) offset = 0 for sidx in range(0, length): for cidx in range(0, channels): if type[1] > self._THRESHOLD: value = int(round(buffers[cidx][sidx] * type[1])) else: value = buffers[cidx][sidx] struct.pack_into(type[0], samples, offset, value) offset += sampwidth return samples def _minimum_buff_length(self, buffers): result = sys.maxsize for b in buffers: result = min(result, len(b)) if result < 1: raise ValueError("Buffer length is zero!") return result def _get_sample_type(self, sampwidth): if sampwidth == 2: return (' self._minimum_buff_length(buffers): raise RuntimeError("Length exceeds size of buffer!") samples = self._repack_samples(buffers, self._channels, self._samplewidth, length) if samples: return self._wavefile.writeframes(samples) return None ================================================ FILE: DynamicAudioNormalizerPYD/src/DynamicAudioNormalizerPYD.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Python Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// //Dynamic Audio Normalizer API #include //Python API #include //Commons #include #include //Version check #if PY_MAJOR_VERSION != 3 #error Python 3 is reuired for this file to be compiled! #endif //CRT #include #include #include /////////////////////////////////////////////////////////////////////////////// // Helper Macros /////////////////////////////////////////////////////////////////////////////// #define PY_METHOD_DECL(X) PyMethodWrap_##X #define PY_METHOD_IMPL(X) static PyObject *PyMethodImpl_##X(PyObject *const self, PyObject *const args) #define PY_BOOLIFY(X) ((X) ? true : false) #define PY_ULONG(X) static_cast((X)) #define PY_INIT_LNG(X,Y) (((X) && PyLong_Check((X))) ? ((uint32_t)PyLong_AsUnsignedLong((X))) : (Y)) #define PY_INIT_FLT(X,Y) (((X) && PyFloat_Check((X))) ? PyFloat_AsDouble((X)) : (Y)) #define PY_INIT_BLN(X,Y) (((X) && PyBool_Check((X))) ? PY_BOOLIFY(PyObject_IsTrue((X))) : (Y)) #define PY_EXCEPTION(X) do \ { \ if (!PyErr_Occurred()) \ { \ PyErr_SetString(PyExc_RuntimeError, (X)); \ } \ } \ while(0) static void PY_FREE(PyObject **const obj) { Py_XDECREF(*obj); *obj = NULL; } /////////////////////////////////////////////////////////////////////////////// // Logging /////////////////////////////////////////////////////////////////////////////// static PyObject *g_log_callback = NULL; static MY_CRITSEC_INIT(g_logging_mutex); static int log_callback_set(PyObject *const callback) { int result = (-1); if ((callback) && PyCallable_Check(callback)) { MY_CRITSEC_ENTER(g_logging_mutex); result = (g_log_callback) ? 0 : 1; PY_FREE(&g_log_callback); g_log_callback = callback; Py_INCREF(g_log_callback); MY_CRITSEC_LEAVE(g_logging_mutex); } return result; } static void log_callback_invoke(const int logLevel, const char *const message) { PyObject *callback; MY_CRITSEC_ENTER(g_logging_mutex); callback = g_log_callback; MY_CRITSEC_LEAVE(g_logging_mutex); if (callback) { if (PyObject *const result = PyObject_CallFunction(callback, "is", logLevel, message)) { Py_DECREF(result); /*discard result*/ } } } /////////////////////////////////////////////////////////////////////////////// // Global Initialization /////////////////////////////////////////////////////////////////////////////// static uint64_t g_initialized = 0L; static MY_CRITSEC_INIT(g_initalization_mutex); static PyObject *g_arrayClass = NULL; static bool global_init_function(void) { bool success = false; if (PyObject *const arrayModule = PyImport_ImportModule("array")) { if (PyObject *arrayClass = PyObject_GetAttrString(arrayModule, "array")) { if ((success = PyType_Check(arrayClass))) { std::swap(g_arrayClass, arrayClass); } Py_XDECREF(arrayClass); } Py_XDECREF(arrayModule); } return success; } static bool global_exit_function(void) { log_callback_set(NULL); PY_FREE(&g_arrayClass); return true; } static bool global_init(void) { bool success = false; MY_CRITSEC_ENTER(g_initalization_mutex); if ((success = (g_initialized ? true : global_init_function()))) { g_initialized++; } MY_CRITSEC_LEAVE(g_initalization_mutex); return success; } static bool global_exit(void) { bool success = false; MY_CRITSEC_ENTER(g_initalization_mutex); if (g_initialized) { success = (--g_initialized) ? true : global_exit_function(); } MY_CRITSEC_LEAVE(g_initalization_mutex); return success; } /////////////////////////////////////////////////////////////////////////////// // Instance Management /////////////////////////////////////////////////////////////////////////////// static std::unordered_set g_instances; static MY_CRITSEC_INIT(g_instance_mutex); static MDynamicAudioNormalizer *instance_add(MDynamicAudioNormalizer *const instance) { MY_CRITSEC_ENTER(g_instance_mutex); g_instances.insert(instance); MY_CRITSEC_LEAVE(g_instance_mutex); return instance; } static MDynamicAudioNormalizer *instance_remove(MDynamicAudioNormalizer *const instance) { MY_CRITSEC_ENTER(g_instance_mutex); const std::unordered_set::iterator iter = g_instances.find(instance); if (iter != g_instances.end()) { g_instances.erase(iter); } MY_CRITSEC_LEAVE(g_instance_mutex); return instance; } static bool instance_check(MDynamicAudioNormalizer *const instance) { bool result; MY_CRITSEC_ENTER(g_instance_mutex); result = (g_instances.find(instance) != g_instances.end()); MY_CRITSEC_LEAVE(g_instance_mutex); return result; } static MDynamicAudioNormalizer *PY2INSTANCE(PyObject *const obj) { if (obj && PyLong_Check(obj)) { if (MDynamicAudioNormalizer *const instance = reinterpret_cast(PyLong_AsVoidPtr(obj))) { if (instance_check(instance)) { return instance; } } } PY_EXCEPTION("Invalid MDynamicAudioNormalizer handle value!"); return (NULL); } /////////////////////////////////////////////////////////////////////////////// // Buffer Management /////////////////////////////////////////////////////////////////////////////// class PyBufferWrapper { public: PyBufferWrapper(PyObject *const data, const uint32_t count, const bool writable) : m_count(count), m_length(UINT32_MAX) { memset(m_buffers, 0, sizeof(double*) * MAX_BUFFERS); memset(m_views, 0, sizeof(Py_buffer) * MAX_BUFFERS); if (!((data) && PyTuple_Check(data))) { PY_EXCEPTION("Input Python object does not appear to be a tuple!"); throw std::invalid_argument("Invalid buffer object!"); } if (!((count > 0) && (count <= MAX_BUFFERS) && (static_cast(PyTuple_Size(data)) >= count))) { PY_EXCEPTION("Input tuple does not have the required minimum size!"); throw std::invalid_argument("Invalid buffer count!"); } PyObject *pyArrays[MAX_BUFFERS]; for (uint32_t c = 0; c < count; ++c) { if (!(pyArrays[c] = PyTuple_GetItem(data, static_cast(c)))) { PY_EXCEPTION("Failed to obtain the n-th element of the given input tuple!"); throw std::invalid_argument("PyTuple_GetItem() error!"); } if (PyObject_IsInstance(pyArrays[c], g_arrayClass) <= 0) { PY_EXCEPTION("The n-th element of the given tuple is not an array object!"); throw std::invalid_argument("PyObject_IsInstance() error!"); } } for (uint32_t c = 0; c < count; ++c) { if (!PyObject_CheckBuffer(pyArrays[c])) { PY_EXCEPTION("The provided array object does not support the 'buffer' protocol!"); releaseBuffers(); throw std::invalid_argument("PyObject_CheckBuffer() error!"); } if (PyObject_GetBuffer(pyArrays[c], &m_views[c], (writable ? PyBUF_WRITABLE : 0)) < 0) { PY_EXCEPTION("Failed to get the internal buffer from array object!"); releaseBuffers(); throw std::invalid_argument("PyObject_GetBuffer() error!"); } if (m_views[c].itemsize != sizeof(double)) { PY_EXCEPTION("The provided array has an invalid item size! Not 'double' array?"); releaseBuffers(); throw std::invalid_argument("Py_buffer.itemsize is invalid!"); } if ((m_length = std::min(m_length, static_cast(m_views[c].len / m_views[c].itemsize))) < 1) { PY_EXCEPTION("The size of the provided buffers is way too small!"); releaseBuffers(); throw std::invalid_argument("Py_buffer.len is invalid!"); } if (!(m_buffers[c] = reinterpret_cast(m_views[c].buf))) { PY_EXCEPTION("Pointer to the arrays's buffer appears to be NULL!"); releaseBuffers(); throw std::invalid_argument("Py_buffer.buf is invalid!"); } } } ~PyBufferWrapper(void) { releaseBuffers(); } uint32_t getLength(void) const { return m_length; } double *const *getBuffer(void) const { return m_buffers; } private: static const uint32_t MAX_BUFFERS = 8; const uint32_t m_count; uint32_t m_length; double *m_buffers[MAX_BUFFERS]; Py_buffer m_views[MAX_BUFFERS]; void releaseBuffers(void) { for (uint32_t k = 0; k < m_count; ++k) { if ((m_views[k].buf) && (m_views[k].obj)) { PyBuffer_Release(&m_views[k]); } } memset(m_buffers, 0, sizeof(double*) * MAX_BUFFERS); memset(m_views, 0, sizeof(Py_buffer) * MAX_BUFFERS); } PyBufferWrapper& operator=(const PyBufferWrapper&) { throw 666; } PyBufferWrapper(const PyBufferWrapper&):m_count(0) { throw 666; } }; /////////////////////////////////////////////////////////////////////////////// // Method Implementation /////////////////////////////////////////////////////////////////////////////// PY_METHOD_IMPL(CreateInstance) { //Perform gloabl initialization first if (!global_init()) { PY_EXCEPTION("Global library initialization has failed!"); return (NULL); } //Unpack the function arguments (references are "borrowed"!) PyObject *pyChannels = NULL, *pySampleRate = NULL, *pyFrameLenMsec = NULL, *pyFilterSize = NULL, *pyPeakValue = NULL, *pyMaxAmplification = NULL, *pyTargetRms = NULL, *pyCompressFactor = NULL, *pyChannelsCoupled = NULL, *pyEnableDCCorrection = NULL, *pyAltBoundaryMode = NULL; if (!PyArg_UnpackTuple(args, "create", 2, 11, &pyChannels, &pySampleRate, &pyFrameLenMsec, &pyFilterSize, &pyPeakValue, &pyMaxAmplification, &pyTargetRms, &pyCompressFactor, &pyChannelsCoupled, &pyEnableDCCorrection, &pyAltBoundaryMode)) { PY_EXCEPTION("Failed to unpack MDynamicAudioNormalizer arguments!"); global_exit(); return (NULL); } //Parse the input parameters const uint32_t channels = PY_INIT_LNG(pyChannels, 0L ); const uint32_t sampleRate = PY_INIT_LNG(pySampleRate, 0L ); const uint32_t frameLenMsec = PY_INIT_LNG(pyFrameLenMsec, 500L ); const uint32_t filterSize = PY_INIT_LNG(pyFilterSize, 31L ); const double peakValue = PY_INIT_FLT(pyPeakValue, 0.95); const double maxAmplification = PY_INIT_FLT(pyMaxAmplification, 10. ); const double targetRms = PY_INIT_FLT(pyTargetRms, 0. ); const double compressFactor = PY_INIT_FLT(pyCompressFactor, 0. ); const bool channelsCoupled = PY_INIT_BLN(pyChannelsCoupled , true); const bool enableDCCorrection = PY_INIT_BLN(pyEnableDCCorrection, false); const bool altBoundaryMode = PY_INIT_BLN(pyAltBoundaryMode, false); //Validate parameters if (PyErr_Occurred() || (!channels) || (!sampleRate)) { PY_EXCEPTION("Invalid or incomplete MDynamicAudioNormalizer arguments!"); global_exit(); return (NULL); } //Create and initialize the instance if (MDynamicAudioNormalizer *const instance = new MDynamicAudioNormalizer(channels, sampleRate, frameLenMsec, filterSize, peakValue, maxAmplification, targetRms, compressFactor, channelsCoupled, enableDCCorrection, altBoundaryMode)) { if (instance->initialize()) { return PyLong_FromVoidPtr(instance_add(instance)); } PY_EXCEPTION("Failed to initialize MDynamicAudioNormalizer instance!"); delete instance; } //Failure PY_EXCEPTION("Failed to create MDynamicAudioNormalizer instance!"); global_exit(); return (NULL); } PY_METHOD_IMPL(DestroyInstance) { if (MDynamicAudioNormalizer *const instance = PY2INSTANCE(args)) { delete instance_remove(instance); global_exit(); Py_RETURN_TRUE; } PY_EXCEPTION("Failed to destory MDynamicAudioNormalizer instance!"); return (NULL); } PY_METHOD_IMPL(GetConfiguration) { if (MDynamicAudioNormalizer *const instance = PY2INSTANCE(args)) { uint32_t channels, sampleRate, frameLen, filterSize; if (instance->getConfiguration(channels, sampleRate, frameLen, filterSize)) { if (PyObject *const result = Py_BuildValue("kkkk", PY_ULONG(channels), PY_ULONG(sampleRate), PY_ULONG(frameLen), PY_ULONG(filterSize))) { return result; } } } PY_EXCEPTION("Failed to get MDynamicAudioNormalizer configuration!"); return (NULL); } PY_METHOD_IMPL(GetInternalDelay) { if (MDynamicAudioNormalizer *const instance = PY2INSTANCE(args)) { int64_t delayInSamples; if (instance->getInternalDelay(delayInSamples)) { return PyLong_FromLongLong(static_cast(delayInSamples)); } } PY_EXCEPTION("Failed to get MDynamicAudioNormalizer internal delay!"); return (NULL); } PY_METHOD_IMPL(ProcessInplace) { long long inputSize = -1LL; PyObject *pyInstance = NULL, *pySamplesInOut = NULL; if (!PyArg_ParseTuple(args, "OOK", &pyInstance, &pySamplesInOut, &inputSize)) { return NULL; } if (MDynamicAudioNormalizer *const instance = PY2INSTANCE(pyInstance)) { uint32_t channels, ignored[3]; if (!instance->getConfiguration(channels, ignored[0], ignored[1], ignored[2])) { PY_EXCEPTION("Failed to get number of channels from instance!"); return (NULL); } try { PyBufferWrapper samplesInOut(pySamplesInOut, channels, true); if (static_cast(inputSize) > static_cast(samplesInOut.getLength())) { PY_EXCEPTION("Specified input size exceeds the size of the given array!"); return (NULL); } int64_t outputSize; if(instance->processInplace(samplesInOut.getBuffer(), static_cast(inputSize), outputSize)) { return PyLong_FromLongLong(static_cast(outputSize)); } } catch (const std::invalid_argument&) { PY_EXCEPTION("Failed to get buffers from inpout arrays!"); return (NULL); } } PY_EXCEPTION("Failed to process audio samples in-place!"); return (NULL); } PY_METHOD_IMPL(Process) { long long inputSize = -1LL; PyObject *pyInstance = NULL, *pySamplesIn = NULL, *pySamplesOut = NULL; if (!PyArg_ParseTuple(args, "OOOK", &pyInstance, &pySamplesIn, &pySamplesOut, &inputSize)) { return NULL; } if (MDynamicAudioNormalizer *const instance = PY2INSTANCE(pyInstance)) { uint32_t channels, ignored[3]; if (!instance->getConfiguration(channels, ignored[0], ignored[1], ignored[2])) { PY_EXCEPTION("Failed to get number of channels from instance!"); return (NULL); } try { PyBufferWrapper samplesIn(pySamplesIn, channels, false); if (static_cast(inputSize) > static_cast(samplesIn.getLength())) { PY_EXCEPTION("Specified input size exceeds the size of the given array!"); return (NULL); } PyBufferWrapper samplesOut(pySamplesOut, channels, true); if (static_cast(inputSize) > static_cast(samplesOut.getLength())) { PY_EXCEPTION("Specified input size exceeds the size of the given array!"); return (NULL); } int64_t outputSize; if (instance->process(samplesIn.getBuffer(), samplesOut.getBuffer(), static_cast(inputSize), outputSize)) { return PyLong_FromLongLong(static_cast(outputSize)); } } catch (const std::invalid_argument&) { PY_EXCEPTION("Failed to get buffers from inpout arrays!"); return (NULL); } } PY_EXCEPTION("Failed to process audio samples in-place!"); return (NULL); } PY_METHOD_IMPL(FlushBuffer) { PyObject *pyInstance = NULL, *pySamplesOut = NULL; if (!PyArg_ParseTuple(args, "OO", &pyInstance, &pySamplesOut)) { return NULL; } if (MDynamicAudioNormalizer *const instance = PY2INSTANCE(pyInstance)) { uint32_t channels, ignored[3]; if (!instance->getConfiguration(channels, ignored[0], ignored[1], ignored[2])) { PY_EXCEPTION("Failed to get number of channels from instance!"); return (NULL); } try { PyBufferWrapper samplesOut(pySamplesOut, channels, true); int64_t outputSize; if (instance->flushBuffer(samplesOut.getBuffer(), samplesOut.getLength(), outputSize)) { return PyLong_FromLongLong(static_cast(outputSize)); } } catch (const std::invalid_argument&) { PY_EXCEPTION("Failed to get buffers from inpout arrays!"); return (NULL); } } PY_EXCEPTION("Failed to process audio samples in-place!"); return (NULL); } PY_METHOD_IMPL(SetLogFunction) { const int result = log_callback_set(args); if (result >= 0) { if (result > 0) { MDynamicAudioNormalizer::setLogFunction(log_callback_invoke); } Py_RETURN_TRUE; } PY_EXCEPTION("Given argument doesn't appear to be callable!"); return (NULL); } PY_METHOD_IMPL(GetVersionInfo) { const char *date, *time, *compiler, *arch; uint32_t versionMajor, versionMinor, versionPatch; bool debug; MDynamicAudioNormalizer::getVersionInfo(versionMajor, versionMinor, versionPatch); MDynamicAudioNormalizer::getBuildInfo(&date, &time, &compiler, &arch, debug); PyObject *const pyVersionInfo = Py_BuildValue("III", static_cast(versionMajor), static_cast(versionMinor), static_cast(versionPatch)); PyObject *const pyBuildInfo = Py_BuildValue("sssss", date, time, compiler, arch, debug ? "DEBUG" : "RELEASE"); PyObject *result = NULL; if ((pyVersionInfo) && (pyBuildInfo)) { result = PyTuple_Pack(2, pyVersionInfo, pyBuildInfo); } Py_XDECREF(pyVersionInfo); Py_XDECREF(pyBuildInfo); return result; } PY_METHOD_IMPL(GetCoreVersion) { return PyLong_FromUnsignedLong(static_cast(MDYNAMICAUDIONORMALIZER_CORE)); } /////////////////////////////////////////////////////////////////////////////// // Method Wrappers /////////////////////////////////////////////////////////////////////////////// #define PY_METHOD_WRAP(X) \ static PyObject *PyMethodWrap_##X(PyObject *const self, PyObject *const args) \ { \ try \ { \ return PyMethodImpl_##X(self, args); \ } \ catch (...) \ { \ PyErr_SetString(PyExc_SystemError, "Internal C++ exception error!"); \ return NULL; \ } \ } PY_METHOD_WRAP(CreateInstance) PY_METHOD_WRAP(DestroyInstance) PY_METHOD_WRAP(GetConfiguration) PY_METHOD_WRAP(GetInternalDelay) PY_METHOD_WRAP(Process) PY_METHOD_WRAP(ProcessInplace) PY_METHOD_WRAP(FlushBuffer) PY_METHOD_WRAP(SetLogFunction) PY_METHOD_WRAP(GetVersionInfo) PY_METHOD_WRAP(GetCoreVersion) /////////////////////////////////////////////////////////////////////////////// // Module Definition /////////////////////////////////////////////////////////////////////////////// static PyMethodDef DynamicAudioNormalizer_Methods[] = { { "createInstance", PY_METHOD_DECL(CreateInstance), METH_VARARGS, "Create a new MDynamicAudioNormalizer instance and initialize it." }, { "destroyInstance", PY_METHOD_DECL(DestroyInstance), METH_O, "Destroy an existing MDynamicAudioNormalizer instance." }, { "getConfiguration", PY_METHOD_DECL(GetConfiguration), METH_O, "Get the configuration of an existing MDynamicAudioNormalizer instance." }, { "getInternalDelay", PY_METHOD_DECL(GetInternalDelay), METH_O, "Get the internal delay of an existing MDynamicAudioNormalizer instance." }, { "processInplace", PY_METHOD_DECL(ProcessInplace), METH_VARARGS, "Process next chunk audio samples, in-place." }, { "process", PY_METHOD_DECL(Process), METH_VARARGS, "Process next chunk audio samples, out-of-place." }, { "flushBuffer", PY_METHOD_DECL(FlushBuffer), METH_VARARGS, "Flushes pending samples out of the MDynamicAudioNormalizer instance." }, { "setLogFunction", PY_METHOD_DECL(SetLogFunction), METH_O, "Set the callback function for log messages. This is a \"static\" method." }, { "getVersionInfo", PY_METHOD_DECL(GetVersionInfo), METH_NOARGS, "Returns version and build info. This is a \"static\" method." }, { "getCoreVersion", PY_METHOD_DECL(GetCoreVersion), METH_NOARGS, "Returns the API version. This is a \"static\" method." }, { NULL, NULL, 0, NULL } }; static struct PyModuleDef PyDynamicAudioNormalizer_ModuleDef = { PyModuleDef_HEAD_INIT, "DynamicAudioNormalizerPYD", "", -1, DynamicAudioNormalizer_Methods }; #ifdef __GNUC__ #pragma GCC visibility push(default) #endif //__GNUC__ PyMODINIT_FUNC PyInit_DynamicAudioNormalizerPYD(void) { return PyModule_Create(&PyDynamicAudioNormalizer_ModuleDef); } #ifdef __GNUC__ #pragma GCC visibility pop #endif //__GNUC__ ================================================ FILE: DynamicAudioNormalizerShared/include/Common.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #if defined(_DEBUG) && !defined(NDEBUG) #define DYNAUDNORM_DEBUG (1) #elif defined(NDEBUG) && !defined(_DEBUG) #define DYNAUDNORM_DEBUG (0) #else #error Inconsistent debug defines detected! #endif #define DYNAUDNORM_NS MDynamicAudioNormalizer_InternalStuff #define MY_DELETE(X) do \ { \ if((X)) \ { \ delete (X); \ (X) = NULL; \ } \ } \ while(0) #define MY_DELETE_ARRAY(X) do \ { \ if((X)) \ { \ delete [] (X); \ (X) = NULL; \ } \ } \ while(0) #define MY_FREE(X) do \ { \ if((X)) \ { \ free(X); \ (X) = NULL; \ } \ } \ while(0) ================================================ FILE: DynamicAudioNormalizerShared/include/Threads.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #pragma once #if (defined(__cplusplus) && (__cplusplus >= 201103L)) || (defined(_MSC_VER) && (_MSC_VER >= 1800)) #define HAVE_STDC11_MUTEX_SUPPORT 1 #else #define HAVE_STDC11_MUTEX_SUPPORT 0 #endif // ---------------------------------------------- // C++11 Mutex // ---------------------------------------------- #if(HAVE_STDC11_MUTEX_SUPPORT) //Std mutex #include //Init #define MY_CRITSEC_DECL(X) std::mutex X #define MY_CRITSEC_INIT(X) std::mutex X //Functions #define MY_CRITSEC_ENTER(X) (X).lock() #define MY_CRITSEC_LEAVE(X) (X).unlock() // ---------------------------------------------- // Pthread Mutex // ---------------------------------------------- #else //HAVE_STDC11_MUTEX_SUPPORT //Static lib support #if defined(_WIN32) && defined(_MT) #define PTW32_STATIC_LIB 1 #endif //VS2015 compile fix #if (_MSC_VER >= 1900) && !defined(_CRT_NO_TIME_T) #define _TIMESPEC_DEFINED 1 #endif //PThread #include //Init #define MY_CRITSEC_DECL(X) pthread_mutex_t X #define MY_CRITSEC_INIT(X) pthread_mutex_t X = PTHREAD_MUTEX_INITIALIZER //Lock #define MY_CRITSEC_ENTER(X) do \ { \ if(pthread_mutex_lock(&(X)) != 0) \ { \ abort(); \ } \ } \ while(0) //Un-lock #define MY_CRITSEC_LEAVE(X) do \ { \ if(pthread_mutex_unlock(&(X)) != 0) \ { \ abort(); \ } \ } \ while(0) #endif //HAVE_STDC11_MUTEX_SUPPORT ================================================ FILE: DynamicAudioNormalizerShared/res/compat.manifest ================================================ ================================================ FILE: DynamicAudioNormalizerShared/res/version.inc ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #if INC_DYNAUDNORM_VERSION_INTERNAL != 0x22b4f8a9 #error "Please do *not* include this file directly; include 'Version.h' instead!" #endif ////////////////////////////////////////////////////////////////////////////////// // Version Info ////////////////////////////////////////////////////////////////////////////////// #define VER_DYNAUDNORM_MAJOR 2 #define VER_DYNAUDNORM_MINOR_HI 1 #define VER_DYNAUDNORM_MINOR_LO 1 #define VER_DYNAUDNORM_PATCH 1 ////////////////////////////////////////////////////////////////////////////////// // Helper macros (aka: having fun with the C pre-processor) ////////////////////////////////////////////////////////////////////////////////// #define ___VER_DYNAUDNORM_STR___(X) #X #define __VER_DYNAUDNORM_STR__(W,X,Y,Z) ___VER_DYNAUDNORM_STR___(v##W.X##Y-Z) #define _VER_DYNAUDNORM_STR_(W,X,Y,Z) __VER_DYNAUDNORM_STR__(W,X,Y,Z) #define VER_DYNAUDNORM_STR _VER_DYNAUDNORM_STR_(VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH) #define __VER_DYNAUDNORM_MINOR__(X,Y) ((10U * (X)) + (Y)) #define _VER_DYNAUDNORM_MINOR_(X,Y) __VER_DYNAUDNORM_MINOR__(X,Y) #define VER_DYNAUDNORM_MINOR _VER_DYNAUDNORM_MINOR_(VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO) ================================================ FILE: DynamicAudioNormalizerSoX/DynamicAudioNormalizerSoX.c ================================================ /* ================================================================================== */ /* Dynamic Audio Normalizer - SoX Effect Wrapper */ /* Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining a copy */ /* of this software and associated documentation files (the "Software"), to deal */ /* in the Software without restriction, including without limitation the rights */ /* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */ /* copies of the Software, and to permit persons to whom the Software is */ /* furnished to do so, subject to the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be included in */ /* all copies or substantial portions of the Software. */ /* */ /* 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 OR COPYRIGHT HOLDERS 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. */ /* */ /* http://opensource.org/licenses/MIT */ /* ================================================================================== */ /*Shut up warnings*/ #define _CRT_SECURE_NO_WARNINGS /*printf() macros*/ #ifndef __STDC_FORMAT_MACROS #define __STDC_FORMAT_MACROS 1 #endif /*SoX internal stuff*/ #include "sox_i.h" /*Win32 Unicode support*/ #ifdef _WIN32 #include "unicode_support.h" #else #define lsx_fopen(X,Y) fopen((X),(Y)) #endif /*_WIN32*/ /*StdLib*/ #include #include #include #include /*Linkage*/ #if defined(_MSC_VER) && defined(_MT) #define MDYNAMICAUDIONORMALIZER_STATIC static const char *LINKAGE = "Static"; #else static const char *LINKAGE = "Shared"; #endif /*Dynamic Audio Normalizer*/ #include /* ================================================================================== */ /* Private Data */ /* ================================================================================== */ typedef struct { uint32_t frameLenMsec; uint32_t filterSize; double peakValue; double maxAmplification; double targetRms; double compressFactor; int channelsCoupled; int enableDCCorrection; int altBoundaryMode; FILE *logFile; } settings_t; typedef struct { settings_t settings; MDynamicAudioNormalizer_Handle *instance; double **temp; size_t tempSize; } priv_t; /* ================================================================================== */ /* Internal Functions */ /* ================================================================================== */ static int parseArgInt(const char *const str, uint32_t *parameter, const uint32_t min_val, const uint32_t max_val) { uint32_t temp; if(sscanf(str, "%u", &temp) == 1) { *parameter = max(min_val, min(max_val, temp)); return 1; } lsx_fail("Failed to parse integral value `%s'", str); return 0; } static int parseArgDbl(const char *const str, double *parameter, const double min_val, const double max_val) { double temp; if(sscanf(str, "%lf", &temp) == 1) { *parameter = max(min_val, min(max_val, temp)); return 1; } lsx_fail("Failed to parse floating point value `%s'", str); return 0; } #define TRY_PARSE(TYPE, PARAM, MIN, MAX) do \ { \ if(!parseArg##TYPE(optstate.arg, &(PARAM), (MIN), (MAX))) \ { \ return 0; \ } \ } \ while(0) static void dynaudnorm_defaults(settings_t *settings) { memset(settings, 0, sizeof(settings_t)); settings->frameLenMsec = 500; settings->filterSize = 31; settings->peakValue = 0.95; settings->maxAmplification = 10.0; settings->targetRms = 0.0; settings->compressFactor = 0.0; settings->channelsCoupled = 1; settings->enableDCCorrection = 0; settings->altBoundaryMode = 0; } static int dynaudnorm_parse_args(settings_t *settings, int argc, char **argv) { static const char *const opts = "+f:g:p:m:r:ncbs:l:"; lsx_getopt_t optstate; char c; lsx_getopt_init(argc, argv, opts, NULL, lsx_getopt_flag_opterr, 1, &optstate); while((c = lsx_getopt(&optstate)) != -1) { switch(tolower(c)) { case 'f': TRY_PARSE(Int, settings->frameLenMsec, 10, 8000); break; case 'g': TRY_PARSE(Int, settings->filterSize, 3, 301); settings->filterSize += ((settings->filterSize + 1) % 2); break; case 'p': TRY_PARSE(Dbl, settings->peakValue, 0.0, 1.0); break; case 'm': TRY_PARSE(Dbl, settings->maxAmplification, 1.0, 100.0); break; case 'r': TRY_PARSE(Dbl, settings->targetRms, 0.0, 1.0); break; case 'n': settings->channelsCoupled = 0; break; case 'c': settings->enableDCCorrection = 1; break; case 'b': settings->altBoundaryMode = 1; break; case 's': TRY_PARSE(Dbl, settings->compressFactor, 0.0, 30.0); break; case 'l': if(!settings->logFile) { settings->logFile = lsx_fopen(optstate.arg, "w"); if(!settings->logFile) { lsx_warn("Failed to open logfile `%s'", optstate.arg); } } break; default: return 0; } } return 1; } static void dynaudnorm_deinterleave(double **temp, const sox_sample_t *const in, const size_t samples_per_channel, const unsigned channels) { size_t i, c, in_pos = 0; for(i = 0; i < samples_per_channel; i++) { for(c = 0; c < channels; c++) { temp[c][i] = ((double)in[in_pos++]) / ((double)SOX_INT32_MAX); } } } static void dynaudnorm_interleave(sox_sample_t *const out, const double *const *const temp, const size_t samples_per_channel, const unsigned channels) { size_t i, c, out_pos = 0; for(i = 0; i < samples_per_channel; i++) { for(c = 0; c < channels; c++) { out[out_pos++] = (sox_sample_t) round(min(1.0, max(-1.0, temp[c][i])) * ((double)SOX_INT32_MAX)); } } } static void dynaudnorm_print(sox_effect_t *effp, const char *const fmt, ...) { if(effp->global_info->global_info->output_message_handler) { va_list arg_list; va_start(arg_list, fmt); vfprintf(stderr, fmt, arg_list); va_end(arg_list); } } static void dynaudnorm_log(const int logLevel, const char *const message) { switch(logLevel) { case 0: lsx_report("%s", message); break; case 1: lsx_warn("%s", message); break; case 2: lsx_fail("%s", message); break; } } static void dynaudnorm_update_buffsize(const sox_effect_t *const effp, priv_t *const p, const size_t input_samples) { size_t c; if(input_samples > p->tempSize) { lsx_warn("Increasing buffer size: %" PRIu64 " -> %" PRIu64, (uint64_t)p->tempSize, (uint64_t)input_samples); for(c = 0; c < effp->in_signal.channels; c++) { p->temp[c] = lsx_realloc(p->temp[c], input_samples * sizeof(double)); } p->tempSize = input_samples; } } /* ================================================================================== */ /* SoX Callback Functions */ /* ================================================================================== */ static int dynaudnorm_kill(sox_effect_t *effp) { lsx_report("dynaudnorm_kill()"); lsx_report("flows=%" PRIu64 ", flow=%" PRIu64 , (uint64_t)effp->flows, (uint64_t)effp->flow); return SOX_SUCCESS; } static int dynaudnorm_create(sox_effect_t *effp, int argc, char **argv) { priv_t *const p = (priv_t *)effp->priv; lsx_report("dynaudnorm_create()"); lsx_report("flows=%" PRIu64 ", flow=%" PRIu64 , (uint64_t)effp->flows, (uint64_t)effp->flow); memset(effp->priv, 0, sizeof(priv_t)); dynaudnorm_defaults(&p->settings); if(!dynaudnorm_parse_args(&p->settings, argc, argv)) { return lsx_usage(effp); } return SOX_SUCCESS; } static int dynaudnorm_stop(sox_effect_t *effp) { priv_t *const p = (priv_t *)effp->priv; size_t c; lsx_report("dynaudnorm_stop()"); if(p->instance) { MDYNAMICAUDIONORMALIZER_FUNCTION(destroyInstance)(&p->instance); p->instance = NULL; } if(p->settings.logFile) { fclose(p->settings.logFile); p->settings.logFile = NULL; } if(p->temp) { for(c = 0; c < effp->in_signal.channels; c++) { free(p->temp[c]); p->temp[c] = NULL; } free(p->temp); p->temp = NULL; } return SOX_SUCCESS; } static int dynaudnorm_start(sox_effect_t *effp) { priv_t *const p = (priv_t *)effp->priv; lsx_report("dynaudnorm_start()"); lsx_report("flows=%" PRIu64 ", flow=%" PRIu64 ", in_signal.rate=%.2f, in_signal.channels=%" PRIu64, (uint64_t)effp->flows, (uint64_t)effp->flow, effp->in_signal.rate, (uint64_t)effp->in_signal.channels); if((effp->flow == 0) && (effp->global_info->global_info->verbosity > 1)) { uint32_t versionMajor, versionMinor, versionPatch; const char *buildDate, *buildTime, *buildCompiler, *buildArch; int buildDebug; MDYNAMICAUDIONORMALIZER_FUNCTION(getVersionInfo)(&versionMajor, &versionMinor, &versionPatch); MDYNAMICAUDIONORMALIZER_FUNCTION(getBuildInfo)(&buildDate, &buildTime, &buildCompiler, &buildArch, &buildDebug); dynaudnorm_print(effp, "\n---------------------------------------------------------------------------\n"); dynaudnorm_print(effp, "Dynamic Audio Normalizer (SoX Wrapper), Version %u.%02u-%u, %s\n", versionMajor, versionMinor, versionPatch, LINKAGE); dynaudnorm_print(effp, "Copyright (c) 2019 LoRd_MuldeR . Some rights reserved.\n"); dynaudnorm_print(effp, "Built on %s at %s with %s for %s.\n\n", buildDate, buildTime, buildCompiler, buildArch); dynaudnorm_print(effp, "This program is free software: you can redistribute it and/or modify\n"); dynaudnorm_print(effp, "it under the terms of the GNU General Public License .\n"); dynaudnorm_print(effp, "Note that this program is distributed with ABSOLUTELY NO WARRANTY.\n"); dynaudnorm_print(effp, "---------------------------------------------------------------------------\n\n"); } p->tempSize = (size_t) max(ceil(effp->in_signal.rate), 8192.0); /*initial buffer size is one second*/ p->instance = MDYNAMICAUDIONORMALIZER_FUNCTION(createInstance) ( effp->in_signal.channels, (uint32_t) round(effp->in_signal.rate), p->settings.frameLenMsec, p->settings.filterSize, p->settings.peakValue, p->settings.maxAmplification, p->settings.targetRms, p->settings.compressFactor, p->settings.channelsCoupled, p->settings.enableDCCorrection, p->settings.altBoundaryMode, p->settings.logFile ); if(p->instance) { size_t c; p->temp = (double**) lsx_calloc(effp->in_signal.channels, sizeof(double*)); for(c = 0; c < effp->in_signal.channels; c++) { p->temp[c] = (double*) lsx_calloc(p->tempSize, sizeof(double)); } } return (p->instance) ? SOX_SUCCESS : SOX_EINVAL; } static int dynaudnorm_flow(sox_effect_t *effp, const sox_sample_t *ibuf, sox_sample_t *obuf, size_t *isamp, size_t *osamp) { priv_t *const p = (priv_t *)effp->priv; const size_t input_samples = min((*isamp), (*osamp)) / effp->in_signal.channels; /*this is per channel!*/ int64_t output_samples = 0; lsx_debug("dynaudnorm_flow()"); dynaudnorm_update_buffsize(effp, p, input_samples); if(input_samples > 0) { dynaudnorm_deinterleave(p->temp, ibuf, input_samples, effp->in_signal.channels); if(!MDYNAMICAUDIONORMALIZER_FUNCTION(processInplace)(p->instance, p->temp, ((int64_t) input_samples), &output_samples)) { return SOX_EOF; } if(output_samples > 0) { dynaudnorm_interleave(obuf, ((const double**) p->temp), ((size_t) output_samples), effp->in_signal.channels); } } *isamp = (size_t)(input_samples * effp->in_signal.channels); *osamp = (size_t)(output_samples * effp->in_signal.channels); return SOX_SUCCESS; } static int dynaudnorm_drain(sox_effect_t * effp, sox_sample_t * obuf, size_t * osamp) { priv_t *const p = (priv_t *)effp->priv; const size_t input_samples = (*osamp) / effp->in_signal.channels; /*this is per channel!*/ int64_t output_samples = 0; lsx_debug("dynaudnorm_drain()"); dynaudnorm_update_buffsize(effp, p, input_samples); if(input_samples > 0) { if(!MDYNAMICAUDIONORMALIZER_FUNCTION(flushBuffer)(p->instance, p->temp, ((int64_t) input_samples), &output_samples)) { return SOX_EOF; } if(output_samples > 0) { dynaudnorm_interleave(obuf, ((const double**) p->temp), ((size_t) output_samples), effp->in_signal.channels); } } else { lsx_warn("drain() was called with zero-size output buffer!"); } *osamp = (size_t)(output_samples * effp->in_signal.channels); return SOX_SUCCESS; } /* ================================================================================== */ /* SoX Public API */ /* ================================================================================== */ sox_effect_handler_t const * lsx_dynaudnorm_effect_fn(void) { static sox_effect_handler_t handler = { "dynaudnorm", NULL, SOX_EFF_MCHAN, dynaudnorm_create, dynaudnorm_start, dynaudnorm_flow, dynaudnorm_drain, dynaudnorm_stop, dynaudnorm_kill, sizeof(priv_t) }; static char const * lines[] = { "[options]", "", "Algorithm Tweaks:", " -f Frame length, in milliseconds", " -g Gauss filter size, in frames", " -p Target peak magnitude, 0.1-1.0", " -m Maximum gain factor", " -r Target RMS value", " -n Disable channel coupling", " -c Enable the DC bias correction", " -b Use alternative boundary mode", " -s Compress the input data", "", "Diagnostics:", " -l Create a log file", "", "", "Please refer to the manual for a detailed explanation!" }; static char *usage; handler.usage = lsx_usage_lines(&usage, lines, array_length(lines)); MDYNAMICAUDIONORMALIZER_FUNCTION(setLogFunction)(dynaudnorm_log); return &handler; } ================================================ FILE: DynamicAudioNormalizerSoX/INFO.txt ================================================ Dynamic Audio Normalizer - SoX Wrapper ====================================== The purpose of the SoX Wrapper is integrating the Dynamic Audio Normalizer into the SoX (Sound eXchange) application, a versatile audio editor and converter. Build Instructions ------------------ How to build SoX with the Dynamic Audio Normalizer effect: 1. Download the latest SoX sources from the official SoX web-site (http://sox.sourceforge.net/) 2. Use CMake to generate solution/project files, as usually 3. Open the SoX solution and add the provided source code file "DynamicAudioNormalizerSoX.c" to the "libsox" project 4. In the "libsox" project settings, add the directory "DynamicAudioNormalizerAPI\include" to the Additional Include Directories paths 5. In the "libsox" project settings, add "DynamicAudioNormalizerAPI.lib" to the Additional Dependencies 6. Open the file "src\effects.h" and insert the following line at the suitable position: EFFECT(dynaudnorm) 7. Now (re)build SoX! Usage Instructions ------------------ With SoX, the Dynamic Audio Normalizer effect can be invoked like this: > sox.exe dynaudnorm [options] e.o.f. ================================================ FILE: DynamicAudioNormalizerSoX/extra/main.c ================================================ int main( int argc, char **argv ) { int sox_argc; char **sox_argv; int exit_code; lsx_init_console(); lsx_init_commandline_arguments(&sox_argc, &sox_argv); exit_code = sox_main(sox_argc, sox_argv); lsx_uninit_console(); lsx_free_commandline_arguments(&sox_argc, &sox_argv); return exit_code; } ================================================ FILE: DynamicAudioNormalizerSoX/extra/unicode_support.c ================================================ /* Copyright (c) 2004-2012 LoRd_MuldeR File: unicode_support.c This file was originally part of a patch included with LameXP, released under the same license as the original audio tools. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64 #include "unicode_support.h" #include #include static UINT g_old_output_cp = ((UINT)-1); static char *utf16_to_utf8(const wchar_t *input) { char *Buffer; int BuffSize = 0, Result = 0; BuffSize = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL); Buffer = (char*) malloc(sizeof(char) * BuffSize); if(Buffer) { Result = WideCharToMultiByte(CP_UTF8, 0, input, -1, Buffer, BuffSize, NULL, NULL); } return ((Result > 0) && (Result <= BuffSize)) ? Buffer : NULL; } static char *utf16_to_ansi(const wchar_t *input) { char *Buffer; int BuffSize = 0, Result = 0; BuffSize = WideCharToMultiByte(CP_ACP, 0, input, -1, NULL, 0, NULL, NULL); Buffer = (char*) malloc(sizeof(char) * BuffSize); if(Buffer) { Result = WideCharToMultiByte(CP_ACP, 0, input, -1, Buffer, BuffSize, NULL, NULL); } return ((Result > 0) && (Result <= BuffSize)) ? Buffer : NULL; } static wchar_t *utf8_to_utf16(const char *input) { wchar_t *Buffer; int BuffSize = 0, Result = 0; BuffSize = MultiByteToWideChar(CP_UTF8, 0, input, -1, NULL, 0); Buffer = (wchar_t*) malloc(sizeof(wchar_t) * BuffSize); if(Buffer) { Result = MultiByteToWideChar(CP_UTF8, 0, input, -1, Buffer, BuffSize); } return ((Result > 0) && (Result <= BuffSize)) ? Buffer : NULL; } void lsx_init_commandline_arguments(int *argc, char ***argv) { int i, nArgs; LPWSTR *szArglist; szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); if(NULL == szArglist) { fprintf(stderr, "\nFATAL: CommandLineToArgvW failed\n\n"); exit(-1); } *argv = (char**) malloc(sizeof(char*) * nArgs); *argc = nArgs; if(NULL == *argv) { fprintf(stderr, "\nFATAL: Malloc failed\n\n"); exit(-1); } for(i = 0; i < nArgs; i++) { (*argv)[i] = utf16_to_utf8(szArglist[i]); if(NULL == (*argv)[i]) { fprintf(stderr, "\nFATAL: utf16_to_utf8 failed\n\n"); exit(-1); } } LocalFree(szArglist); } void lsx_free_commandline_arguments(int *argc, char ***argv) { int i = 0; if(*argv != NULL) { for(i = 0; i < *argc; i++) { if((*argv)[i] != NULL) { free((*argv)[i]); (*argv)[i] = NULL; } } free(*argv); *argv = NULL; } } FILE *lsx_fopen(const char *filename_utf8, const char *mode_utf8) { FILE *ret = NULL; wchar_t *filename_utf16 = utf8_to_utf16(filename_utf8); wchar_t *mode_utf16 = utf8_to_utf16(mode_utf8); if(filename_utf16 && mode_utf16) { FILE *fh = NULL; int err = _wfopen_s(&fh, filename_utf16, mode_utf16); if(err == 0) ret = fh; } if(filename_utf16) free(filename_utf16); if(mode_utf16) free(mode_utf16); return ret; } int lsx_stat(const char *path_utf8, struct _stat *buf) { int ret = -1; wchar_t *path_utf16 = utf8_to_utf16(path_utf8); if(path_utf16) { ret = _wstat(path_utf16, buf); free(path_utf16); } return ret; } int lsx_unlink(const char *path_utf8) { int ret = -1; wchar_t *path_utf16 = utf8_to_utf16(path_utf8); if(path_utf16) { ret = _wunlink(path_utf16); free(path_utf16); } return ret; } void lsx_init_console(void) { g_old_output_cp = GetConsoleOutputCP(); SetConsoleOutputCP(CP_UTF8); } void lsx_uninit_console(void) { if(g_old_output_cp != ((UINT)-1)) { SetConsoleOutputCP(g_old_output_cp); } } #endif ================================================ FILE: DynamicAudioNormalizerSoX/extra/unicode_support.h ================================================ /* Copyright (c) 2004-2019 LoRd_MuldeR File: unicode_support.h This file was originally part of a patch included with LameXP, released under the same license as the original audio tools. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef UNICODE_SUPPORT_H_INCLUDED #define UNICODE_SUPPORT_H_INCLUDED #include #include #define WIN_UNICODE 1 //char *utf16_to_utf8(const wchar_t *input); //char *utf16_to_ansi(const wchar_t *input); //wchar_t *utf8_to_utf16(const char *input); void lsx_init_commandline_arguments(int *argc, char ***argv); void lsx_free_commandline_arguments(int *argc, char ***argv); FILE *lsx_fopen(const char *filename_utf8, const char *mode_utf8); int lsx_stat(const char *path_utf8, struct _stat *buf); int lsx_unlink(const char *path_utf8); void lsx_init_console(void); void lsx_uninit_console(void); #endif ================================================ FILE: DynamicAudioNormalizerSoX/patch/SoX-v14.4.2-Patch1-UnicodeSupport+BuildFix.diff ================================================ src/effects_i.c | 3 +- src/formats.c | 51 ++++++------- src/libsox_i.c | 7 +- src/noiseprof.c | 3 +- src/sox.c | 31 ++++++-- src/unicode_support.c | 199 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/unicode_support.h | 46 ++++++++++++ 7 files changed, 304 insertions(+), 36 deletions(-) diff --git a/src/effects_i.c b/src/effects_i.c index 685e962c..deee4443 100644 --- a/src/effects_i.c +++ b/src/effects_i.c @@ -20,6 +20,7 @@ #define LSX_EFF_ALIAS #include "sox_i.h" +#include "unicode_support.h" #include #include @@ -463,7 +464,7 @@ FILE * lsx_open_input_file(sox_effect_t * effp, char const * filename, sox_bool effp->global_info->global_info->stdin_in_use_by = effp->handler.name; file = stdin; } - else if (!(file = fopen(filename, text_mode ? "r" : "rb"))) { + else if (!(file = lsx_fopen(filename, text_mode ? "r" : "rb"))) { lsx_fail("couldn't open file %s: %s", filename, strerror(errno)); return NULL; } diff --git a/src/formats.c b/src/formats.c index 724a4cda..b6cecfff 100644 --- a/src/formats.c +++ b/src/formats.c @@ -19,6 +19,7 @@ */ #include "sox_i.h" +#include "unicode_support.h" #include #include @@ -401,32 +402,32 @@ static FILE * xfopen(char const * identifier, char const * mode, lsx_io_type * i #endif return f; } - return fopen(identifier, mode); + return lsx_fopen(identifier, mode); } /* Hack to rewind pipes (a small amount). * Works by resetting the FILE buffer pointer */ -static void UNUSED rewind_pipe(FILE * fp) -{ -/* _FSTDIO is for Torek stdio (i.e. most BSD-derived libc's) - * In theory, we no longer need to check _NEWLIB_VERSION or __APPLE__ */ -#if defined _FSTDIO || defined _NEWLIB_VERSION || defined __APPLE__ - fp->_p -= PIPE_AUTO_DETECT_SIZE; - fp->_r += PIPE_AUTO_DETECT_SIZE; -#elif defined __GLIBC__ - fp->_IO_read_ptr = fp->_IO_read_base; -#elif defined _MSC_VER || defined _WIN32 || defined _WIN64 || \ - defined _ISO_STDIO_ISO_H || defined __sgi - fp->_ptr = fp->_base; -#else - /* To fix this #error, either simply remove the #error line and live without - * file-type detection with pipes, or add support for your compiler in the - * lines above. Test with cat monkey.wav | ./sox --info - */ - #error FIX NEEDED HERE - #define NO_REWIND_PIPE - (void)fp; -#endif -} +//static void UNUSED rewind_pipe(FILE * fp) +//{ +///* _FSTDIO is for Torek stdio (i.e. most BSD-derived libc's) +// * In theory, we no longer need to check _NEWLIB_VERSION or __APPLE__ */ +//#if defined _FSTDIO || defined _NEWLIB_VERSION || defined __APPLE__ +// fp->_p -= PIPE_AUTO_DETECT_SIZE; +// fp->_r += PIPE_AUTO_DETECT_SIZE; +//#elif defined __GLIBC__ +// fp->_IO_read_ptr = fp->_IO_read_base; +//#elif defined _MSC_VER || defined _WIN32 || defined _WIN64 || \ +// defined _ISO_STDIO_ISO_H || defined __sgi +// fp->_ptr = fp->_base; +//#else +// /* To fix this #error, either simply remove the #error line and live without +// * file-type detection with pipes, or add support for your compiler in the +// * lines above. Test with cat monkey.wav | ./sox --info - */ +// #error FIX NEEDED HERE +// #define NO_REWIND_PIPE +// (void)fp; +//#endif +//} static sox_format_t * open_read( char const * path, @@ -853,8 +854,8 @@ static sox_format_t * open_write( ft->fp = stdout; } else { - struct stat st; - if (!stat(path, &st) && (st.st_mode & S_IFMT) == S_IFREG && + struct _stat st; + if (!lsx_stat(path, &st) && (st.st_mode & S_IFMT) == S_IFREG && (overwrite_permitted && !overwrite_permitted(path))) { lsx_fail("permission to overwrite `%s' denied", path); goto error; @@ -864,7 +865,7 @@ static sox_format_t * open_write( buffer? fmemopen(buffer, buffer_size, "w+b") : buffer_ptr? open_memstream(buffer_ptr, buffer_size_ptr) : #endif - fopen(path, "w+b"); + lsx_fopen(path, "w+b"); if (ft->fp == NULL) { lsx_fail("can't open output file `%s': %s", path, strerror(errno)); goto error; diff --git a/src/libsox_i.c b/src/libsox_i.c index a5afb8e8..f834136f 100644 --- a/src/libsox_i.c +++ b/src/libsox_i.c @@ -20,6 +20,7 @@ #include "sox_i.h" +#include "unicode_support.h" #ifdef HAVE_IO_H #include @@ -48,8 +49,8 @@ #ifdef WIN32 static int check_dir(char * buf, size_t buflen, char const * name) { - struct stat st; - if (!name || stat(name, &st) || (st.st_mode & S_IFMT) != S_IFDIR) + struct _stat st; + if (!name || lsx_stat(name, &st) || (st.st_mode & S_IFMT) != S_IFDIR) { return 0; } @@ -102,7 +103,7 @@ FILE * lsx_tmpfile(void) fildes = mkstemp(name); #ifdef HAVE_UNISTD_H lsx_debug(FAKE_MKSTEMP "mkstemp, name=%s (unlinked)", name); - unlink(name); + lsx_unlink(name); #else lsx_debug(FAKE_MKSTEMP "mkstemp, name=%s (O_TEMPORARY)", name); #endif diff --git a/src/noiseprof.c b/src/noiseprof.c index 8fe6d4fa..fd798ca0 100644 --- a/src/noiseprof.c +++ b/src/noiseprof.c @@ -19,6 +19,7 @@ */ #include "noisered.h" +#include "unicode_support.h" #include #include @@ -75,7 +76,7 @@ static int sox_noiseprof_start(sox_effect_t * effp) effp->global_info->global_info->stdout_in_use_by = effp->handler.name; data->output_file = stdout; } - else if ((data->output_file = fopen(data->output_filename, "wb")) == NULL) { + else if ((data->output_file = lsx_fopen(data->output_filename, "wb")) == NULL) { lsx_fail("Couldn't open profile file %s: %s", data->output_filename, strerror(errno)); return SOX_EOF; } diff --git a/src/sox.c b/src/sox.c index fcdac94d..ebfaf600 100644 --- a/src/sox.c +++ b/src/sox.c @@ -24,6 +24,7 @@ #include "soxconfig.h" #include "sox.h" #include "util.h" +#include "unicode_support.h" #include #include @@ -238,10 +239,10 @@ static void cleanup(void) if (file_count) { if (ofile->ft) { if (!success && ofile->ft->io_type == lsx_io_file) { /* If we failed part way through */ - struct stat st; /* writing a normal file, remove it. */ - if (!stat(ofile->ft->filename, &st) && + struct _stat st; /* writing a normal file, remove it. */ + if (!lsx_stat(ofile->ft->filename, &st) && (st.st_mode & S_IFMT) == S_IFREG) - unlink(ofile->ft->filename); + lsx_unlink(ofile->ft->filename); } sox_close(ofile->ft); /* Assume we can unlink a file before closing it. */ } @@ -905,7 +906,7 @@ static char * * strtoargv(char * s, int * argc) static void read_user_effects(char const *filename) { - FILE *file = fopen(filename, "r"); + FILE *file = lsx_fopen(filename, "r"); const size_t buffer_size_step = 1024; size_t buffer_size = buffer_size_step; char *s = lsx_malloc(buffer_size); /* buffer for one input line */ @@ -1272,6 +1273,7 @@ static void display_status(sox_bool all_done) } if (all_done) fputc('\n', stderr); + fflush(stderr); } #ifdef HAVE_TERMIOS_H @@ -2136,7 +2138,7 @@ static void read_comment_file(sox_comments_t * comments, char const * const file int c; size_t text_length = 100; char * text = lsx_malloc(text_length + 1); - FILE * file = fopen(filename, "r"); + FILE * file = lsx_fopen(filename, "r"); if (file == NULL) { lsx_fail("Cannot open comment file `%s'", filename); @@ -2848,7 +2850,7 @@ static sox_bool cmp_comment_text(char const * c1, char const * c2) return c1 && c2 && !strcasecmp(c1, c2); } -int main(int argc, char **argv) +static int sox_main(int argc, char **argv) { size_t i; char mybase[6]; @@ -3051,3 +3053,20 @@ int main(int argc, char **argv) return 0; } + +int main(int argc, char **argv) +{ + int sox_argc; + char **sox_argv; + int exit_code; + + lsx_init_console(); + lsx_init_commandline_arguments(&sox_argc, &sox_argv); + + exit_code = sox_main(sox_argc, sox_argv); + + lsx_uninit_console(); + lsx_free_commandline_arguments(&sox_argc, &sox_argv); + + return exit_code; +} diff --git a/src/unicode_support.c b/src/unicode_support.c new file mode 100644 index 00000000..f89aa7b5 --- /dev/null +++ b/src/unicode_support.c @@ -0,0 +1,199 @@ +/* Copyright (c) 2004-2015 LoRd_MuldeR + File: unicode_support.c + + This file was originally part of a patch included with LameXP, + released under the same license as the original audio tools. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#if defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64 + +#include "unicode_support.h" + +#include +#include + +static UINT g_old_output_cp = ((UINT)-1); + +static char *utf16_to_utf8(const wchar_t *input) +{ + char *Buffer; + int BuffSize = 0, Result = 0; + + BuffSize = WideCharToMultiByte(CP_UTF8, 0, input, -1, NULL, 0, NULL, NULL); + Buffer = (char*) malloc(sizeof(char) * BuffSize); + if(Buffer) + { + Result = WideCharToMultiByte(CP_UTF8, 0, input, -1, Buffer, BuffSize, NULL, NULL); + } + + return ((Result > 0) && (Result <= BuffSize)) ? Buffer : NULL; +} + +static char *utf16_to_ansi(const wchar_t *input) +{ + char *Buffer; + int BuffSize = 0, Result = 0; + + BuffSize = WideCharToMultiByte(CP_ACP, 0, input, -1, NULL, 0, NULL, NULL); + Buffer = (char*) malloc(sizeof(char) * BuffSize); + if(Buffer) + { + Result = WideCharToMultiByte(CP_ACP, 0, input, -1, Buffer, BuffSize, NULL, NULL); + } + + return ((Result > 0) && (Result <= BuffSize)) ? Buffer : NULL; +} + +static wchar_t *utf8_to_utf16(const char *input) +{ + wchar_t *Buffer; + int BuffSize = 0, Result = 0; + + BuffSize = MultiByteToWideChar(CP_UTF8, 0, input, -1, NULL, 0); + Buffer = (wchar_t*) malloc(sizeof(wchar_t) * BuffSize); + if(Buffer) + { + Result = MultiByteToWideChar(CP_UTF8, 0, input, -1, Buffer, BuffSize); + } + + return ((Result > 0) && (Result <= BuffSize)) ? Buffer : NULL; +} + +void lsx_init_commandline_arguments(int *argc, char ***argv) +{ + int i, nArgs; + LPWSTR *szArglist; + + szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs); + + if(NULL == szArglist) + { + fprintf(stderr, "\nFATAL: CommandLineToArgvW failed\n\n"); + exit(-1); + } + + *argv = (char**) malloc(sizeof(char*) * nArgs); + *argc = nArgs; + + if(NULL == *argv) + { + fprintf(stderr, "\nFATAL: Malloc failed\n\n"); + exit(-1); + } + + for(i = 0; i < nArgs; i++) + { + (*argv)[i] = utf16_to_utf8(szArglist[i]); + if(NULL == (*argv)[i]) + { + fprintf(stderr, "\nFATAL: utf16_to_utf8 failed\n\n"); + exit(-1); + } + } + + LocalFree(szArglist); +} + +void lsx_free_commandline_arguments(int *argc, char ***argv) +{ + int i = 0; + + if(*argv != NULL) + { + for(i = 0; i < *argc; i++) + { + if((*argv)[i] != NULL) + { + free((*argv)[i]); + (*argv)[i] = NULL; + } + } + free(*argv); + *argv = NULL; + } +} + +FILE *lsx_fopen(const char *filename_utf8, const char *mode_utf8) +{ + FILE *ret = NULL; + wchar_t *filename_utf16 = utf8_to_utf16(filename_utf8); + wchar_t *mode_utf16 = utf8_to_utf16(mode_utf8); + + if(filename_utf16 && mode_utf16) + { + FILE *fh = NULL; + int err = _wfopen_s(&fh, filename_utf16, mode_utf16); + if(err == 0) ret = fh; + } + + if(filename_utf16) free(filename_utf16); + if(mode_utf16) free(mode_utf16); + + return ret; +} + +int lsx_stat(const char *path_utf8, struct _stat *buf) +{ + int ret = -1; + + wchar_t *path_utf16 = utf8_to_utf16(path_utf8); + if(path_utf16) + { + ret = _wstat(path_utf16, buf); + free(path_utf16); + } + + return ret; +} + +int lsx_unlink(const char *path_utf8) +{ + int ret = -1; + + wchar_t *path_utf16 = utf8_to_utf16(path_utf8); + if(path_utf16) + { + ret = _wunlink(path_utf16); + free(path_utf16); + } + + return ret; +} + +void lsx_init_console(void) +{ + g_old_output_cp = GetConsoleOutputCP(); + SetConsoleOutputCP(CP_UTF8); +} + +void lsx_uninit_console(void) +{ + if(g_old_output_cp != ((UINT)-1)) + { + SetConsoleOutputCP(g_old_output_cp); + } +} + +#endif \ No newline at end of file diff --git a/src/unicode_support.h b/src/unicode_support.h new file mode 100644 index 00000000..6abd0b38 --- /dev/null +++ b/src/unicode_support.h @@ -0,0 +1,46 @@ +/* Copyright (c) 2004-2015 LoRd_MuldeR + File: unicode_support.h + + This file was originally part of a patch included with LameXP, + released under the same license as the original audio tools. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions + are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR + CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +#ifndef UNICODE_SUPPORT_H_INCLUDED +#define UNICODE_SUPPORT_H_INCLUDED + +#include +#include + +#define WIN_UNICODE 1 + +void lsx_init_commandline_arguments(int *argc, char ***argv); +void lsx_free_commandline_arguments(int *argc, char ***argv); +FILE *lsx_fopen(const char *filename_utf8, const char *mode_utf8); +int lsx_stat(const char *path_utf8, struct _stat *buf); +int lsx_unlink(const char *path_utf8); +void lsx_init_console(void); +void lsx_uninit_console(void); + +#endif \ No newline at end of file ================================================ FILE: DynamicAudioNormalizerSoX/patch/SoX-v14.4.2-Patch2-AddDynAudNormEffect.diff ================================================ src/DynamicAudioNormalizerSoX.c | 479 ++++++++++++++++++++++++++++++++++++++++ src/effects.h | 1 + 2 files changed, 480 insertions(+) diff --git a/src/DynamicAudioNormalizerSoX.c b/src/DynamicAudioNormalizerSoX.c new file mode 100644 index 00000000..4c0bc728 --- /dev/null +++ b/src/DynamicAudioNormalizerSoX.c @@ -0,0 +1,479 @@ +/* ================================================================================== */ +/* Dynamic Audio Normalizer - SoX Effect Wrapper */ +/* Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. */ +/* */ +/* Permission is hereby granted, free of charge, to any person obtaining a copy */ +/* of this software and associated documentation files (the "Software"), to deal */ +/* in the Software without restriction, including without limitation the rights */ +/* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell */ +/* copies of the Software, and to permit persons to whom the Software is */ +/* furnished to do so, subject to the following conditions: */ +/* */ +/* The above copyright notice and this permission notice shall be included in */ +/* all copies or substantial portions of the Software. */ +/* */ +/* 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 OR COPYRIGHT HOLDERS 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. */ +/* */ +/* http://opensource.org/licenses/MIT */ +/* ================================================================================== */ + +/*Shut up warnings*/ +#define _CRT_SECURE_NO_WARNINGS + +/*printf() macros*/ +#ifndef __STDC_FORMAT_MACROS +#define __STDC_FORMAT_MACROS 1 +#endif + +/*SoX internal stuff*/ +#include "sox_i.h" + +/*Win32 Unicode support*/ +#ifdef _WIN32 +#include "unicode_support.h" +#else +#define lsx_fopen(X,Y) fopen((X),(Y)) +#endif /*_WIN32*/ + +/*StdLib*/ +#include +#include +#include +#include + +/*Linkage*/ +#if defined(_MSC_VER) && defined(_MT) +#define MDYNAMICAUDIONORMALIZER_STATIC +static const char *LINKAGE = "Static"; +#else +static const char *LINKAGE = "Shared"; +#endif + +/*Dynamic Audio Normalizer*/ +#include + +/* ================================================================================== */ +/* Private Data */ +/* ================================================================================== */ + +typedef struct +{ + uint32_t frameLenMsec; + uint32_t filterSize; + double peakValue; + double maxAmplification; + double targetRms; + double compressFactor; + int channelsCoupled; + int enableDCCorrection; + int altBoundaryMode; + FILE *logFile; +} +settings_t; + +typedef struct +{ + settings_t settings; + MDynamicAudioNormalizer_Handle *instance; + double **temp; + size_t tempSize; +} +priv_t; + +/* ================================================================================== */ +/* Internal Functions */ +/* ================================================================================== */ + +static int parseArgInt(const char *const str, uint32_t *parameter, const uint32_t min_val, const uint32_t max_val) +{ + uint32_t temp; + if(sscanf(str, "%u", &temp) == 1) + { + *parameter = max(min_val, min(max_val, temp)); + return 1; + } + lsx_fail("Failed to parse integral value `%s'", str); + return 0; +} + +static int parseArgDbl(const char *const str, double *parameter, const double min_val, const double max_val) +{ + double temp; + if(sscanf(str, "%lf", &temp) == 1) + { + *parameter = max(min_val, min(max_val, temp)); + return 1; + } + lsx_fail("Failed to parse floating point value `%s'", str); + return 0; +} + +#define TRY_PARSE(TYPE, PARAM, MIN, MAX) do \ +{ \ + if(!parseArg##TYPE(optstate.arg, &(PARAM), (MIN), (MAX))) \ + { \ + return 0; \ + } \ +} \ +while(0) + +static void dynaudnorm_defaults(settings_t *settings) +{ + memset(settings, 0, sizeof(settings_t)); + + settings->frameLenMsec = 500; + settings->filterSize = 31; + settings->peakValue = 0.95; + settings->maxAmplification = 10.0; + settings->targetRms = 0.0; + settings->compressFactor = 0.0; + settings->channelsCoupled = 1; + settings->enableDCCorrection = 0; + settings->altBoundaryMode = 0; +} + +static int dynaudnorm_parse_args(settings_t *settings, int argc, char **argv) +{ + static const char *const opts = "+f:g:p:m:r:ncbs:l:"; + lsx_getopt_t optstate; char c; + lsx_getopt_init(argc, argv, opts, NULL, lsx_getopt_flag_opterr, 1, &optstate); + + while((c = lsx_getopt(&optstate)) != -1) + { + switch(tolower(c)) + { + case 'f': + TRY_PARSE(Int, settings->frameLenMsec, 10, 8000); + break; + case 'g': + TRY_PARSE(Int, settings->filterSize, 3, 301); + settings->filterSize += ((settings->filterSize + 1) % 2); + break; + case 'p': + TRY_PARSE(Dbl, settings->peakValue, 0.0, 1.0); + break; + case 'm': + TRY_PARSE(Dbl, settings->maxAmplification, 1.0, 100.0); + break; + case 'r': + TRY_PARSE(Dbl, settings->targetRms, 0.0, 1.0); + break; + case 'n': + settings->channelsCoupled = 0; + break; + case 'c': + settings->enableDCCorrection = 1; + break; + case 'b': + settings->altBoundaryMode = 1; + break; + case 's': + TRY_PARSE(Dbl, settings->compressFactor, 0.0, 30.0); + break; + case 'l': + if(!settings->logFile) + { + settings->logFile = lsx_fopen(optstate.arg, "w"); + if(!settings->logFile) + { + lsx_warn("Failed to open logfile `%s'", optstate.arg); + } + } + break; + default: + return 0; + } + } + + return 1; +} + +static void dynaudnorm_deinterleave(double **temp, const sox_sample_t *const in, const size_t samples_per_channel, const unsigned channels) +{ + size_t i, c, in_pos = 0; + + for(i = 0; i < samples_per_channel; i++) + { + for(c = 0; c < channels; c++) + { + temp[c][i] = ((double)in[in_pos++]) / ((double)SOX_INT32_MAX); + } + } +} + +static void dynaudnorm_interleave(sox_sample_t *const out, const double *const *const temp, const size_t samples_per_channel, const unsigned channels) +{ + size_t i, c, out_pos = 0; + + for(i = 0; i < samples_per_channel; i++) + { + for(c = 0; c < channels; c++) + { + out[out_pos++] = (sox_sample_t) round(min(1.0, max(-1.0, temp[c][i])) * ((double)SOX_INT32_MAX)); + } + } +} + +static void dynaudnorm_print(sox_effect_t *effp, const char *const fmt, ...) +{ + if(effp->global_info->global_info->output_message_handler) + { + va_list arg_list; + va_start(arg_list, fmt); + vfprintf(stderr, fmt, arg_list); + va_end(arg_list); + } +} + +static void dynaudnorm_log(const int logLevel, const char *const message) +{ + switch(logLevel) + { + case 0: + lsx_report("%s", message); + break; + case 1: + lsx_warn("%s", message); + break; + case 2: + lsx_fail("%s", message); + break; + } +} + +static void dynaudnorm_update_buffsize(const sox_effect_t *const effp, priv_t *const p, const size_t input_samples) +{ + size_t c; + if(input_samples > p->tempSize) + { + lsx_warn("Increasing buffer size: %" PRIu64 " -> %" PRIu64, (uint64_t)p->tempSize, (uint64_t)input_samples); + for(c = 0; c < effp->in_signal.channels; c++) + { + p->temp[c] = lsx_realloc(p->temp[c], input_samples * sizeof(double)); + } + p->tempSize = input_samples; + } +} + +/* ================================================================================== */ +/* SoX Callback Functions */ +/* ================================================================================== */ + +static int dynaudnorm_kill(sox_effect_t *effp) +{ + lsx_report("dynaudnorm_kill()"); + lsx_report("flows=%" PRIu64 ", flow=%" PRIu64 , (uint64_t)effp->flows, (uint64_t)effp->flow); + return SOX_SUCCESS; +} + +static int dynaudnorm_create(sox_effect_t *effp, int argc, char **argv) +{ + priv_t *const p = (priv_t *)effp->priv; + + lsx_report("dynaudnorm_create()"); + lsx_report("flows=%" PRIu64 ", flow=%" PRIu64 , (uint64_t)effp->flows, (uint64_t)effp->flow); + + memset(effp->priv, 0, sizeof(priv_t)); + dynaudnorm_defaults(&p->settings); + + if(!dynaudnorm_parse_args(&p->settings, argc, argv)) + { + return lsx_usage(effp); + } + + return SOX_SUCCESS; +} + +static int dynaudnorm_stop(sox_effect_t *effp) +{ + priv_t *const p = (priv_t *)effp->priv; + size_t c; + + lsx_report("dynaudnorm_stop()"); + + if(p->instance) + { + MDYNAMICAUDIONORMALIZER_FUNCTION(destroyInstance)(&p->instance); + p->instance = NULL; + } + + if(p->settings.logFile) + { + fclose(p->settings.logFile); + p->settings.logFile = NULL; + } + + if(p->temp) + { + for(c = 0; c < effp->in_signal.channels; c++) + { + free(p->temp[c]); + p->temp[c] = NULL; + } + free(p->temp); + p->temp = NULL; + } + + return SOX_SUCCESS; +} + +static int dynaudnorm_start(sox_effect_t *effp) +{ + priv_t *const p = (priv_t *)effp->priv; + + lsx_report("dynaudnorm_start()"); + lsx_report("flows=%" PRIu64 ", flow=%" PRIu64 ", in_signal.rate=%.2f, in_signal.channels=%" PRIu64, (uint64_t)effp->flows, (uint64_t)effp->flow, effp->in_signal.rate, (uint64_t)effp->in_signal.channels); + + if((effp->flow == 0) && (effp->global_info->global_info->verbosity > 1)) + { + uint32_t versionMajor, versionMinor, versionPatch; + const char *buildDate, *buildTime, *buildCompiler, *buildArch; int buildDebug; + + MDYNAMICAUDIONORMALIZER_FUNCTION(getVersionInfo)(&versionMajor, &versionMinor, &versionPatch); + MDYNAMICAUDIONORMALIZER_FUNCTION(getBuildInfo)(&buildDate, &buildTime, &buildCompiler, &buildArch, &buildDebug); + + dynaudnorm_print(effp, "\n---------------------------------------------------------------------------\n"); + dynaudnorm_print(effp, "Dynamic Audio Normalizer (SoX Wrapper), Version %u.%02u-%u, %s\n", versionMajor, versionMinor, versionPatch, LINKAGE); + dynaudnorm_print(effp, "Copyright (c) 2019 LoRd_MuldeR . Some rights reserved.\n"); + dynaudnorm_print(effp, "Built on %s at %s with %s for %s.\n\n", buildDate, buildTime, buildCompiler, buildArch); + dynaudnorm_print(effp, "This program is free software: you can redistribute it and/or modify\n"); + dynaudnorm_print(effp, "it under the terms of the GNU General Public License .\n"); + dynaudnorm_print(effp, "Note that this program is distributed with ABSOLUTELY NO WARRANTY.\n"); + dynaudnorm_print(effp, "---------------------------------------------------------------------------\n\n"); + } + + p->tempSize = (size_t) max(ceil(effp->in_signal.rate), 8192.0); /*initial buffer size is one second*/ + + p->instance = MDYNAMICAUDIONORMALIZER_FUNCTION(createInstance) + ( + effp->in_signal.channels, + (uint32_t) round(effp->in_signal.rate), + p->settings.frameLenMsec, + p->settings.filterSize, + p->settings.peakValue, + p->settings.maxAmplification, + p->settings.targetRms, + p->settings.compressFactor, + p->settings.channelsCoupled, + p->settings.enableDCCorrection, + p->settings.altBoundaryMode, + p->settings.logFile + ); + + if(p->instance) + { + size_t c; + p->temp = (double**) lsx_calloc(effp->in_signal.channels, sizeof(double*)); + for(c = 0; c < effp->in_signal.channels; c++) + { + p->temp[c] = (double*) lsx_calloc(p->tempSize, sizeof(double)); + } + } + + return (p->instance) ? SOX_SUCCESS : SOX_EINVAL; +} + +static int dynaudnorm_flow(sox_effect_t *effp, const sox_sample_t *ibuf, sox_sample_t *obuf, size_t *isamp, size_t *osamp) +{ + priv_t *const p = (priv_t *)effp->priv; + const size_t input_samples = min((*isamp), (*osamp)) / effp->in_signal.channels; /*this is per channel!*/ + int64_t output_samples = 0; + + lsx_debug("dynaudnorm_flow()"); + dynaudnorm_update_buffsize(effp, p, input_samples); + + if(input_samples > 0) + { + dynaudnorm_deinterleave(p->temp, ibuf, input_samples, effp->in_signal.channels); + if(!MDYNAMICAUDIONORMALIZER_FUNCTION(processInplace)(p->instance, p->temp, ((int64_t) input_samples), &output_samples)) + { + return SOX_EOF; + } + if(output_samples > 0) + { + dynaudnorm_interleave(obuf, ((const double**) p->temp), ((size_t) output_samples), effp->in_signal.channels); + } + } + + + *isamp = (size_t)(input_samples * effp->in_signal.channels); + *osamp = (size_t)(output_samples * effp->in_signal.channels); + + return SOX_SUCCESS; +} + +static int dynaudnorm_drain(sox_effect_t * effp, sox_sample_t * obuf, size_t * osamp) +{ + priv_t *const p = (priv_t *)effp->priv; + const size_t input_samples = (*osamp) / effp->in_signal.channels; /*this is per channel!*/ + int64_t output_samples = 0; + + lsx_debug("dynaudnorm_drain()"); + dynaudnorm_update_buffsize(effp, p, input_samples); + + if(input_samples > 0) + { + if(!MDYNAMICAUDIONORMALIZER_FUNCTION(flushBuffer)(p->instance, p->temp, ((int64_t) input_samples), &output_samples)) + { + return SOX_EOF; + } + if(output_samples > 0) + { + dynaudnorm_interleave(obuf, ((const double**) p->temp), ((size_t) output_samples), effp->in_signal.channels); + } + } + else + { + lsx_warn("drain() was called with zero-size output buffer!"); + } + + *osamp = (size_t)(output_samples * effp->in_signal.channels); + return SOX_SUCCESS; +} + +/* ================================================================================== */ +/* SoX Public API */ +/* ================================================================================== */ + +sox_effect_handler_t const * lsx_dynaudnorm_effect_fn(void) +{ + static sox_effect_handler_t handler = + { + "dynaudnorm", NULL, SOX_EFF_MCHAN, + dynaudnorm_create, dynaudnorm_start, dynaudnorm_flow, dynaudnorm_drain, dynaudnorm_stop, dynaudnorm_kill, sizeof(priv_t) + }; + + static char const * lines[] = + { + "[options]", + "", + "Algorithm Tweaks:", + " -f Frame length, in milliseconds", + " -g Gauss filter size, in frames", + " -p Target peak magnitude, 0.1-1.0", + " -m Maximum gain factor", + " -r Target RMS value", + " -n Disable channel coupling", + " -c Enable the DC bias correction", + " -b Use alternative boundary mode", + " -s Compress the input data", + "", + "Diagnostics:", + " -l Create a log file", + "", + "", + "Please refer to the manual for a detailed explanation!" + }; + + static char *usage; + handler.usage = lsx_usage_lines(&usage, lines, array_length(lines)); + + MDYNAMICAUDIONORMALIZER_FUNCTION(setLogFunction)(dynaudnorm_log); + return &handler; +} diff --git a/src/effects.h b/src/effects.h index 450a5c2c..773b63bd 100644 --- a/src/effects.h +++ b/src/effects.h @@ -33,6 +33,7 @@ EFFECT(dither) EFFECT(divide) EFFECT(downsample) + EFFECT(dynaudnorm) EFFECT(earwax) EFFECT(echo) EFFECT(echos) ================================================ FILE: DynamicAudioNormalizerVST/DynamicAudioNormalizerVST.def ================================================ EXPORTS VSTPluginMain main=VSTPluginMain ================================================ FILE: DynamicAudioNormalizerVST/DynamicAudioNormalizerVST_VS2013.vcxproj ================================================  Debug Win32 Debug x64 Release_DLL Win32 Release_DLL x64 Release_Static Win32 Release_Static x64 {376386ee-8268-47e3-a335-7663716e4c60} true true false true false {A30375E8-AEF7-4531-B372-02328E0B9D43} Win32Proj DynamicAudioNormalizerVST DynamicAudioNormalizerVST DynamicLibrary true v120_xp Unicode DynamicLibrary true v120_xp Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ NotUsing Level3 Disabled WIN32;_CRT_SECURE_NO_WARNINGS;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL NoExtensions Windows true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib NotUsing Level3 Disabled WIN32;_CRT_SECURE_NO_WARNINGS;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL Windows true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded MultiThreaded MultiThreadedDebugDLL MultiThreadedDLL false StreamingSIMDExtensions2 Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded MultiThreaded MultiThreadedDebugDLL MultiThreadedDLL false Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false StreamingSIMDExtensions2 Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib ================================================ FILE: DynamicAudioNormalizerVST/DynamicAudioNormalizerVST_VS2013.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {16f87057-2e94-42db-82e2-14293070dd05} {3ef921b0-70be-490e-8a3f-696f0a68e420} Source Files\VST 2.x SDK Source Files\VST 2.x SDK Source Files\VST 2.x SDK Source Files Source Files Header Files\VST 2.x SDK Header Files\VST 2.x SDK Header Files\VST 2.x SDK Header Files Header Files ================================================ FILE: DynamicAudioNormalizerVST/DynamicAudioNormalizerVST_VS2015.vcxproj ================================================  Debug Win32 Debug x64 Release_DLL Win32 Release_DLL x64 Release_Static Win32 Release_Static x64 {376386ee-8268-47e3-a335-7663716e4c60} true true false true false {A30375E8-AEF7-4531-B372-02328E0B9D43} Win32Proj DynamicAudioNormalizerVST DynamicAudioNormalizerVST DynamicLibrary true v140_xp Unicode DynamicLibrary true v140_xp Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ NotUsing Level3 Disabled WIN32;_CRT_SECURE_NO_WARNINGS;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL NoExtensions Windows true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib NotUsing Level3 Disabled WIN32;_CRT_SECURE_NO_WARNINGS;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL Windows true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded MultiThreaded MultiThreadedDebugDLL MultiThreadedDLL false StreamingSIMDExtensions2 Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded MultiThreaded MultiThreadedDebugDLL MultiThreadedDLL false Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false StreamingSIMDExtensions2 Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib ================================================ FILE: DynamicAudioNormalizerVST/DynamicAudioNormalizerVST_VS2015.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {16f87057-2e94-42db-82e2-14293070dd05} {3ef921b0-70be-490e-8a3f-696f0a68e420} Source Files\VST 2.x SDK Source Files\VST 2.x SDK Source Files\VST 2.x SDK Source Files Source Files Header Files\VST 2.x SDK Header Files\VST 2.x SDK Header Files\VST 2.x SDK Header Files Header Files ================================================ FILE: DynamicAudioNormalizerVST/DynamicAudioNormalizerVST_VS2017.vcxproj ================================================  Debug Win32 Debug x64 Release_DLL Win32 Release_DLL x64 Release_Static Win32 Release_Static x64 {376386ee-8268-47e3-a335-7663716e4c60} true true false true false {A30375E8-AEF7-4531-B372-02328E0B9D43} Win32Proj DynamicAudioNormalizerVST DynamicAudioNormalizerVST 7.0 DynamicLibrary true v141_xp Unicode DynamicLibrary true v141_xp Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ NotUsing Level3 Disabled WIN32;_CRT_SECURE_NO_WARNINGS;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL NoExtensions Windows true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib NotUsing Level3 Disabled WIN32;_CRT_SECURE_NO_WARNINGS;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) MultiThreadedDebugDLL Windows true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded MultiThreaded MultiThreadedDebugDLL MultiThreadedDLL false StreamingSIMDExtensions2 Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded MultiThreaded MultiThreadedDebugDLL MultiThreadedDLL false Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false StreamingSIMDExtensions2 Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 NotUsing MaxSpeed true true WIN32;_CRT_SECURE_NO_WARNINGS;NDEBUG;_WINDOWS;_USRDLL;MDYNAMICAUDIONORMALIZER_STATIC;DYNAMICAUDIONORMALIZERVST_EXPORTS;%(PreprocessorDefinitions) MultiThreaded false Fast AnySuitable Speed true $(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\etc\vst_sdk;%(AdditionalIncludeDirectories) true Windows false true true $(ProjectDir)\DynamicAudioNormalizerVST.def Psapi.lib;%(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) ================================================ FILE: DynamicAudioNormalizerVST/DynamicAudioNormalizerVST_VS2017.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms {16f87057-2e94-42db-82e2-14293070dd05} {3ef921b0-70be-490e-8a3f-696f0a68e420} Source Files\VST 2.x SDK Source Files\VST 2.x SDK Source Files\VST 2.x SDK Source Files Source Files Header Files\VST 2.x SDK Header Files\VST 2.x SDK Header Files\VST 2.x SDK Header Files Header Files Resource Files ================================================ FILE: DynamicAudioNormalizerVST/res/DynamicAudioNormalizerVST.rc ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "WinResrc.h" //"afxres.h" #define INC_DYNAUDNORM_VERSION_INTERNAL 0x22b4f8a9 #include "../DynamicAudioNormalizerShared/res/version.inc" ////////////////////////////////////////////////////////////////////////////////// // Neutral resources ////////////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) #ifdef _WIN32 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL #pragma code_page(1252) #endif //_WIN32 ////////////////////////////////////////////////////////////////////////////////// // Version ////////////////////////////////////////////////////////////////////////////////// VS_VERSION_INFO VERSIONINFO FILEVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH PRODUCTVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x3L #else FILEFLAGS 0x2L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ." VALUE "CompanyName", "LoRd_MuldeR " VALUE "FileDescription", "DynamicAudioNormalizer VST Plugin" VALUE "FileVersion", VER_DYNAUDNORM_STR VALUE "InternalName", "DynamicAudioNormalizerVST" VALUE "LegalCopyright", "Copyright (c) 2014-2019 LoRd_MuldeR " VALUE "LegalTrademarks", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License " VALUE "OriginalFilename", "DynamicAudioNormalizerVST.dll" VALUE "ProductName", "DynamicAudioNormalizer" VALUE "ProductVersion", VER_DYNAUDNORM_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // Neutral resources ================================================ FILE: DynamicAudioNormalizerVST/src/DynamicAudioNormalizerVST.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - VST 2.x Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// // ACKNOWLEDGEMENT: // (1) VST PlugIn Interface Technology by Steinberg Media Technologies GmbH. // (2) VST is a trademark of Steinberg Media Technologies GmbH. ////////////////////////////////////////////////////////////////////////////////// #include "DynamicAudioNormalizerVST.h" //Dynamic Audio Normalizer API #include //Internal #include #include #include "Spooky.h" //Standard Library #include #include #include //Win32 API #ifdef _WIN32 #define NOMINMAX 1 #define WIN32_LEAN_AND_MEAN 1 #define PSAPI_VERSION 1 #include #include #endif //Enable extra logging output? #undef DEBUG_LOGGING //Constants static const VstInt32 CHANNEL_COUNT = 2; static const VstInt32 PARAMETER_COUNT = 8; static const VstInt32 PROGRAM_COUNT = 8; //Default static const char *DEFAULT_NAME = "#$!__DEFAULT__!$#"; static const size_t INITIAL_BUFFER_SIZE = 8192; //Reg key static const wchar_t *REGISTRY_PATH = L"Software\\MuldeR\\DynAudNorm\\VST"; //Critical Section static char g_loggingBuffer[1024]; static MY_CRITSEC_INIT(g_loggingMutex); //Enumerations enum { PARAM_REALVAL = 0, PARAM_INTEGER = 1, PARAM_BOOLEAN = 2 } param_type_t; //Seed values #ifdef _M_X64 static const uint64_t SEED_VALU1 = 0xC11D908A35A625A5, SEED_VALU2 = 0x5E57D080BCD2EAED; #else static const uint64_t SEED_VALU1 = 0x24575239D116386B, SEED_VALU2 = 0xE03BDD5B975F47D0; #endif //Debugging outputs #ifdef DEBUG_LOGGING #define DEBUG_LOG(...) outputMessage(__VA_ARGS__) #else #define DEBUG_LOG(...) ((void)0) #endif //DEBUG_LOGGING /////////////////////////////////////////////////////////////////////////////// // Helper functions /////////////////////////////////////////////////////////////////////////////// static void outputMessage(const char *const format, ...) { MY_CRITSEC_ENTER(g_loggingMutex); va_list argList; va_start(argList, format); vsnprintf_s(g_loggingBuffer, 1024, _TRUNCATE, format, argList); va_end(argList); OutputDebugStringA(g_loggingBuffer); MY_CRITSEC_LEAVE(g_loggingMutex); } static void logFunction(const int logLevel, const char *const message) { switch (logLevel) { case MDynamicAudioNormalizer::LOG_LEVEL_DBG: outputMessage("[DynAudNorm_VST] NFO: %s\n", message); break; case MDynamicAudioNormalizer::LOG_LEVEL_WRN: outputMessage("[DynAudNorm_VST] WRN: %s\n", message); break; case MDynamicAudioNormalizer::LOG_LEVEL_ERR: outputMessage("[DynAudNorm_VST] ERR: %s\n", message); break; default: outputMessage("[DynAudNorm_VST] DBG: %s\n", message); break; } } static void showErrorMsg(const char *const text) { MessageBoxA(NULL, text, "Dynamic Audio Normalizer", MB_ICONSTOP | MB_TOPMOST | MB_TASKMODAL); } static DWORD regValueGet(const wchar_t *const name) { DWORD result = 0; HKEY hKey = NULL; if(RegCreateKeyExW(HKEY_CURRENT_USER, REGISTRY_PATH, 0, NULL, 0, KEY_READ, NULL, &hKey, NULL) == ERROR_SUCCESS) { DWORD type = 0, value = 0, size = sizeof(DWORD); if(RegQueryValueExW(hKey, name, 0, &type, ((LPBYTE) &value), &size) == ERROR_SUCCESS) { if((type == REG_DWORD) && (size == sizeof(DWORD))) { result = value; } } RegCloseKey(hKey); } return result; } static bool regValueSet(const wchar_t *const name, const DWORD &value) { bool result = false; HKEY hKey = NULL; if(RegCreateKeyExW(HKEY_CURRENT_USER, REGISTRY_PATH, 0, NULL, 0, KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS) { if(RegSetValueExW(hKey, name, 0, REG_DWORD, ((LPBYTE) &value), sizeof(DWORD)) == ERROR_SUCCESS) { result = true; } RegCloseKey(hKey); } return result; } static bool getAppUuid(wchar_t *const uuidOut, const size_t &size) { if(size < 1) { return false; } wchar_t executableFilePath[512]; if(GetProcessImageFileNameW(GetCurrentProcess(), executableFilePath, 512) < 1) { wcsncpy_s(executableFilePath, 512, L"Lorem ipsum dolor sit amet, consetetur sadipscing elitr!", _TRUNCATE); } uint64_t hash1 = SEED_VALU1, hash2 = SEED_VALU2; hash128(executableFilePath, &hash1, &hash2); _snwprintf_s(uuidOut, size, _TRUNCATE, L"{%016llX-%016llX}", hash1, hash2); return true; } static VstInt32 getPlugUuid(void) { uint32_t major, minor, patch; MDynamicAudioNormalizer::getVersionInfo(major, minor, patch); wchar_t identifier[128]; _snwprintf_s(identifier, 128, _TRUNCATE, L"muldersoft.com::DynamicAudioNormalizerVST::%u.%02u.%u", major, minor, patch); uint64_t hash1 = SEED_VALU1, hash2 = SEED_VALU2; hash128(identifier, &hash1, &hash2); const VstInt32 hash32_pt1 = static_cast(((hash1 ^ hash2) & 0xFFFFFFFF00000000ui64) >> 32); const VstInt32 hash32_pt2 = static_cast((hash1 ^ hash2) & 0x00000000FFFFFFFFui64); return hash32_pt1 ^ hash32_pt2; } template static T *allocBuffer(size_t size) { T *buffer = NULL; try { buffer = new T[size]; } catch(...) { outputMessage("[DynAudNorm_VST] ERR: Allocation of size %u failed!", static_cast(sizeof(T) * size)); showErrorMsg("Memory allocation has failed: Out of memory!"); _exit(0xC0000017); } return buffer; } static double applyStepSize(const double &val, const double &step) { return (round(val / step) * step); } static double param2value(const double &min, const double &val, const double &max, const double &stepSize) { const double offset = std::min(1.0, std::max(0.0, val)) * (max - min); return min + ((stepSize > DBL_EPSILON) ? applyStepSize(offset, stepSize) : offset); } static float value2param(const double &min, const double &val, const double &max) { const double targt = std::min(max, std::max(min, double(val))); return static_cast((targt - min) / (max - min)); } static void value2string(char *text, const double &val, const double &min, const int &type, const bool &minDisable) { if(minDisable && (fabs(val - min) < DBL_EPSILON)) { _snprintf_s(text, kVstMaxParamStrLen, _TRUNCATE, "(OFF)"); return; } switch(type) { case PARAM_REALVAL: _snprintf_s(text, kVstMaxParamStrLen, _TRUNCATE, "%.2f", val); break; case PARAM_INTEGER: _snprintf_s(text, kVstMaxParamStrLen, _TRUNCATE, "%d", static_cast(val)); break; case PARAM_BOOLEAN: _snprintf_s(text, kVstMaxParamStrLen, _TRUNCATE, "%s", (val >= 0.5) ? "ON" : "OFF"); break; default: _snprintf_s(text, kVstMaxParamStrLen, _TRUNCATE, "N/A"); } } static uint32_t value2integer(const double &val) { return static_cast(round(val)); } static bool value2boolean(const double &val) { return (val >= 0.5); } /////////////////////////////////////////////////////////////////////////////// // Program Class /////////////////////////////////////////////////////////////////////////////// struct DynamicAudioNormalizerVST_Program { char name[kVstMaxProgNameLen + 1]; float param[PARAMETER_COUNT]; }; /////////////////////////////////////////////////////////////////////////////// // Private Data /////////////////////////////////////////////////////////////////////////////// class DynamicAudioNormalizerVST_PrivateData { friend class DynamicAudioNormalizerVST; public: DynamicAudioNormalizerVST_PrivateData(void) { this->instance = NULL; this->programs = NULL; this->temp[0] = this->temp[1] = NULL; this->tempSize = 0; } ~DynamicAudioNormalizerVST_PrivateData(void) { } protected: MDynamicAudioNormalizer *instance; DynamicAudioNormalizerVST_Program *programs; double *temp[2]; size_t tempSize; }; /////////////////////////////////////////////////////////////////////////////// // Constructor & Destructor /////////////////////////////////////////////////////////////////////////////// DynamicAudioNormalizerVST::DynamicAudioNormalizerVST(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, PROGRAM_COUNT, PARAMETER_COUNT), p(new DynamicAudioNormalizerVST_PrivateData()) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::DynamicAudioNormalizerVST()"); const VstInt32 uniqueId = getPlugUuid(); setNumInputs(CHANNEL_COUNT); // stereo in setNumOutputs(CHANNEL_COUNT); // stereo out setUniqueID(uniqueId); // identify canProcessReplacing(); // supports replacing output canDoubleReplacing(); // supports double precision processing noTail(false); // does have Tail! p->programs = allocBuffer(PROGRAM_COUNT); for(VstInt32 i = 0; i < PROGRAM_COUNT; i++) { vst_strncpy(p->programs[i].name, DEFAULT_NAME, kVstMaxProgNameLen); for(VstInt32 j = 0; j < PARAMETER_COUNT; j++) { p->programs[i].param[j] = getParameterDefault(j); } } for(size_t i = 0; i < 2; i++) { p->temp[i] = allocBuffer(INITIAL_BUFFER_SIZE); } p->tempSize = INITIAL_BUFFER_SIZE; setProgram(0); } DynamicAudioNormalizerVST::~DynamicAudioNormalizerVST() { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::~DynamicAudioNormalizerVST()"); if(p->instance) { delete p->instance; p->instance = NULL; } if(p->tempSize > 0) { for(size_t i = 0; i < 2; i++) { delete [] (p->temp[i]); p->temp[i] = NULL; } p->tempSize = 0; } if (p->programs) { delete[] p->programs; p->programs = NULL; } delete p; } /////////////////////////////////////////////////////////////////////////////// // Program Handling /////////////////////////////////////////////////////////////////////////////// void DynamicAudioNormalizerVST::setProgram(VstInt32 program) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::setProgramName(%d)", program); AudioEffectX::setProgram(std::min(PROGRAM_COUNT-1, std::max(0, program))); forceUpdateParameters(); } void DynamicAudioNormalizerVST::setProgramName (char* name) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::setProgramName()"); vst_strncpy(p->programs[curProgram].name, name, kVstMaxProgNameLen); } void DynamicAudioNormalizerVST::getProgramName (char* name) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getProgramName()"); if(strcmp(p->programs[curProgram].name, DEFAULT_NAME) == 0) { _snprintf_s(name, kVstMaxProgNameLen, _TRUNCATE, "Preset #%u", curProgram + 1); } else { vst_strncpy(name, p->programs[curProgram].name, kVstMaxProgNameLen); } } bool DynamicAudioNormalizerVST::getProgramNameIndexed(VstInt32 category, VstInt32 index, char* text) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getProgramNameIndexed(%d)", index); if ((index >= 0) && (index < PROGRAM_COUNT)) { if (strcmp(p->programs[index].name, DEFAULT_NAME) == 0) { _snprintf_s(text, kVstMaxProgNameLen, _TRUNCATE, "Preset #%u", index + 1); } else { vst_strncpy(text, p->programs[index].name, kVstMaxProgNameLen); } return true; } else { vst_strncpy(text, "N/A", kVstMaxProgNameLen); return false; } } /////////////////////////////////////////////////////////////////////////////// // Parameter Handling /////////////////////////////////////////////////////////////////////////////// static const struct { const char *paramName; const char *labelName; const double minValue; const double defValue; const double maxValue; const int contentType; const bool minDisable; const double stepSize; } PARAM_PROPERTIES[PARAMETER_COUNT] = { { "FrameLen", "MSec", 100.00, 500.00, 1000.00, PARAM_INTEGER, false, 1.00 }, { "FltrSize", "Frames", 3.00, 31.00, 63.00, PARAM_INTEGER, false, 2.00 }, { "PeakVal", "%", 10.00, 95.00, 100.00, PARAM_REALVAL, false, 0.00 }, { "MaxAmpl", "x", 1.00, 10.00, 50.00, PARAM_REALVAL, false, 0.00 }, { "TrgtRMS", "%", 0.00, 0.00, 100.00, PARAM_REALVAL, true, 0.00 }, { "Compress", "sigma", 0.00, 0.00, 25.00, PARAM_REALVAL, true, 0.00 }, { "ChanCpld", "", 0.00, 1.00, 1.00, PARAM_BOOLEAN, false, 1.00 }, { "DCCorrct", "", 0.00, 0.00, 1.00, PARAM_BOOLEAN, false, 1.00 } }; void DynamicAudioNormalizerVST::getParameterName (VstInt32 index, char* label) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getParameterName(%d)", index); if ((index >= 0) && (index < PARAMETER_COUNT)) { vst_strncpy(label, PARAM_PROPERTIES[index].paramName, kVstMaxParamStrLen); } else { vst_strncpy(label, "N/A", kVstMaxParamStrLen); } } void DynamicAudioNormalizerVST::getParameterLabel (VstInt32 index, char* label) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getParameterLabel(%d)", index); if ((index >= 0) && (index < PARAMETER_COUNT)) { vst_strncpy(label, PARAM_PROPERTIES[index].labelName, kVstMaxParamStrLen); } else { vst_strncpy(label, "N/A", kVstMaxParamStrLen); } } void DynamicAudioNormalizerVST::setParameter (VstInt32 index, float value) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::setParameter(%d, %.2f)", index, value); if ((index >= 0) && (index < PARAMETER_COUNT)) { p->programs[curProgram].param[index] = std::min(1.0f, std::max(0.0f, value)); } } float DynamicAudioNormalizerVST::getParameter(VstInt32 index) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getParameter(%d)", index); if ((index >= 0) && (index < PARAMETER_COUNT)) { return p->programs[curProgram].param[index]; } return -1.0; } double DynamicAudioNormalizerVST::getParameterValue(VstInt32 index) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getParameterValue(%d)", index); if ((index >= 0) && (index < PARAMETER_COUNT)) { return param2value(PARAM_PROPERTIES[index].minValue, p->programs[curProgram].param[index], PARAM_PROPERTIES[index].maxValue, PARAM_PROPERTIES[index].stepSize); } return -1.0; } float DynamicAudioNormalizerVST::getParameterDefault(VstInt32 index) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getParameterDefault(%d)", index); if ((index >= 0) && (index < PARAMETER_COUNT)) { return value2param(PARAM_PROPERTIES[index].minValue, PARAM_PROPERTIES[index].defValue, PARAM_PROPERTIES[index].maxValue); } return -1.0; } void DynamicAudioNormalizerVST::getParameterDisplay(VstInt32 index, char* text) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getParameterDisplay(%d)", index); text[0] = '\0'; if ((index >= 0) && (index < PARAMETER_COUNT)) { value2string(text, getParameterValue(index), PARAM_PROPERTIES[index].minValue, PARAM_PROPERTIES[index].contentType, PARAM_PROPERTIES[index].minDisable); } } /////////////////////////////////////////////////////////////////////////////// // Effect Info /////////////////////////////////////////////////////////////////////////////// bool DynamicAudioNormalizerVST::getEffectName (char* name) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getEffectName()"); uint32_t major, minor, patch; MDynamicAudioNormalizer::getVersionInfo(major, minor, patch); _snprintf_s(name, kVstMaxEffectNameLen, _TRUNCATE, "DynamicAudioNormalizer %u.%02u-%u", major, minor, patch); return true; } bool DynamicAudioNormalizerVST::getProductString (char* text) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getProductString()"); uint32_t major, minor, patch; MDynamicAudioNormalizer::getVersionInfo(major, minor, patch); _snprintf_s(text, kVstMaxProductStrLen, _TRUNCATE, "DynamicAudioNormalizer_%u", (100U * major) + minor); return true; } bool DynamicAudioNormalizerVST::getVendorString (char* text) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getVendorString()"); static const char *vendorName = "LoRd_MuldeR"; _snprintf_s(text, kVstMaxVendorStrLen, _TRUNCATE, "%s", vendorName); return true; } VstInt32 DynamicAudioNormalizerVST::getVendorVersion () { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getVendorVersion()"); uint32_t major, minor, patch; MDynamicAudioNormalizer::getVersionInfo(major, minor, patch); return (major * 1000U) + (minor * 10U) + patch; } VstPlugCategory DynamicAudioNormalizerVST::getPlugCategory(void) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getPlugCategory()"); return kPlugCategEffect; } /////////////////////////////////////////////////////////////////////////////// // State Handling /////////////////////////////////////////////////////////////////////////////// void DynamicAudioNormalizerVST::open(void) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::open()"); forceUpdateParameters(); } void DynamicAudioNormalizerVST::close(void) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::close()"); if(p->instance) { outputMessage("[DynAudNorm_VST] ISANITY: Host called close() after resume() *without* intermittent susped() call -> workaround actived!"); suspend(); } } void DynamicAudioNormalizerVST::resume(void) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::resume()"); if(p->instance) { outputMessage("[DynAudNorm_VST] ISANITY: Host called resume() repeatedly *without* intermittent susped() call -> workaround actived!"); suspend(); } if(createNewInstance(static_cast(round(getSampleRate())))) { int64_t delayInSamples; if(p->instance->getInternalDelay(delayInSamples)) { setInitialDelay(static_cast(std::min(delayInSamples, int64_t(INT32_MAX)))); } } } void DynamicAudioNormalizerVST::suspend(void) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::suspend()"); if(p->instance) { delete p->instance; p->instance = NULL; } } /////////////////////////////////////////////////////////////////////////////// // Audio Processing /////////////////////////////////////////////////////////////////////////////// void DynamicAudioNormalizerVST::processReplacing(float** inputs, float** outputs, VstInt32 sampleFrames) { DEBUG_LOG("[DynAudNorm_VST] ENTER >>> processReplacing()"); if(sampleFrames < 1) { return; /*number of samples is zero or even negative!*/ } if(!p->instance) { outputMessage("[DynAudNorm_VST] ISANITY: Host called processReplacing() *before* resume() has been called -> workaround actived!"); resume(); } updateBufferSize(sampleFrames); readInputSamplesFlt(inputs, sampleFrames); int64_t outputSamples; if(!p->instance->processInplace(p->temp, sampleFrames, outputSamples)) { showErrorMsg("Dynamic Audio Normalizer processing failed!"); DEBUG_LOG("[DynAudNorm_VST] LEAVE <<< processReplacing()"); return; } DEBUG_LOG("InputSamples/OutputSamples: %llu/%llu --> %llu", int64_t(sampleFrames), outputSamples, int64_t(sampleFrames) - outputSamples); writeOutputSamplesFlt(outputs, sampleFrames, outputSamples); DEBUG_LOG("[DynAudNorm_VST] LEAVE <<< processReplacing()"); } void DynamicAudioNormalizerVST::processDoubleReplacing (double** inputs, double** outputs, VstInt32 sampleFrames) { DEBUG_LOG("[DynAudNorm_VST] ENTER >>> processDoubleReplacing()"); if(sampleFrames < 1) { return; /*number of samples is zero or even negative!*/ } if(!p->instance) { outputMessage("[DynAudNorm_VST] ISANITY: Host called processReplacing() *before* resume() has been called -> workaround actived!"); resume(); } updateBufferSize(sampleFrames); readInputSamplesDbl(inputs, sampleFrames); int64_t outputSamples; if(!p->instance->processInplace(p->temp, sampleFrames, outputSamples)) { showErrorMsg("Dynamic Audio Normalizer processing failed!"); DEBUG_LOG("[DynAudNorm_VST] LEAVE <<< processDoubleReplacing()"); return; } writeOutputSamplesDbl(outputs, sampleFrames, outputSamples); DEBUG_LOG("[DynAudNorm_VST] LEAVE <<< processDoubleReplacing()"); } VstInt32 DynamicAudioNormalizerVST::getGetTailSize(void) { outputMessage("[DynAudNorm_VST] DynamicAudioNormalizerVST::getGetTailSize()"); if(p->instance) { int64_t delayInSamples; if(p->instance->getInternalDelay(delayInSamples)) { return static_cast(delayInSamples); } } return 0; } /////////////////////////////////////////////////////////////////////////////// // Internal Functions /////////////////////////////////////////////////////////////////////////////// bool DynamicAudioNormalizerVST::createNewInstance(const uint32_t sampleRate) { if(p->instance) { showErrorMsg("Dynamic Audio Normalizer instance already created!"); return true; } const DynamicAudioNormalizerVST_Program *const currentProg = &p->programs[curProgram]; try { p->instance = new MDynamicAudioNormalizer ( CHANNEL_COUNT, sampleRate, value2integer(getParameterValue(0)), value2integer(getParameterValue(1)), getParameterValue(2) / 100.0, getParameterValue(3), getParameterValue(4) / 100.0, getParameterValue(5), value2boolean(getParameterValue(6)), value2boolean(getParameterValue(7)) ); } catch(...) { showErrorMsg("Failed to create Dynamic Audio Normalizer instance!"); return false; } if(!p->instance->initialize()) { showErrorMsg("Dynamic Audio Normalizer initialization has failed!"); return false; } return true; } void DynamicAudioNormalizerVST::updateBufferSize(const size_t requiredSize) { if(p->tempSize < requiredSize) { outputMessage("[DynAudNorm_VST] WRN: Increasing internal buffer size: %u -> %u", ((unsigned int)p->tempSize), ((unsigned int)requiredSize)); for(size_t i = 0; i < 2; i++) { if(p->tempSize > 0) { delete [] (p->temp[i]); } try { p->temp[i] = allocBuffer(requiredSize); } catch(...) { outputMessage("[DynAudNorm_VST] ERR: Allocation of size %u failed!", (unsigned int)(sizeof(double) * requiredSize)); showErrorMsg("Memory allocation has failed: Out of memory!"); _exit(0xC0000017); } } p->tempSize = requiredSize; } } void DynamicAudioNormalizerVST::readInputSamplesFlt(const float *const *const inputs, const int64_t sampleCount) { for(size_t c = 0; c < 2; c++) { for(int64_t i = 0; i < sampleCount; i++) { p->temp[c][i] = inputs[c][i]; } } } void DynamicAudioNormalizerVST::readInputSamplesDbl(const double *const *const inputs, const int64_t sampleCount) { for(size_t c = 0; c < 2; c++) { memcpy(&p->temp[c][0], &inputs[c][0], sizeof(double) * size_t(sampleCount)); } } void DynamicAudioNormalizerVST::writeOutputSamplesFlt(float *const *const outputs, const int64_t requiredSamples, const int64_t availableSamples) { if(availableSamples == 0) { for(size_t c = 0; c < 2; c++) { memset(&outputs[c][0], 0, sizeof(float) * size_t(requiredSamples)); } } else if(availableSamples < requiredSamples) { const int64_t offset = requiredSamples - availableSamples; for(size_t c = 0; c < 2; c++) { memset(&outputs[c][0], 0, sizeof(float) * size_t(offset)); float *outPtr = &outputs[c][offset]; for(int64_t i = 0; i < availableSamples; i++) { *(outPtr++) = static_cast(p->temp[c][i]); } } } else if(availableSamples == requiredSamples) { for(size_t c = 0; c < 2; c++) { for(int64_t i = 0; i < availableSamples; i++) { outputs[c][i] = static_cast(p->temp[c][i]); } } } else { showErrorMsg("Number of output samples exceeds output buffer size!"); } } void DynamicAudioNormalizerVST::writeOutputSamplesDbl(double *const *const outputs, const int64_t requiredSamples, const int64_t availableSamples) { if(availableSamples == 0) { for(size_t c = 0; c < 2; c++) { memset(&outputs[c][0], 0, sizeof(double) * size_t(requiredSamples)); } } else if(availableSamples < requiredSamples) { const int64_t offset = requiredSamples - availableSamples; for(size_t c = 0; c < 2; c++) { memset(&outputs[c][0], 0, sizeof(double) * size_t(offset)); memcpy(&outputs[c][offset], &p->temp[c][0], sizeof(double) * size_t(availableSamples)); } } else if(availableSamples == requiredSamples) { for(size_t c = 0; c < 2; c++) { memcpy(&outputs[c][0], &p->temp[c][0], sizeof(double) * size_t(availableSamples)); } } else { showErrorMsg("Number of output samples exceeds output buffer size!"); } } void DynamicAudioNormalizerVST::forceUpdateParameters(void) { for(VstInt32 i = 0; i < PARAMETER_COUNT; i++) { beginEdit(i); setParameterAutomated(i, p->programs[curProgram].param[i]); endEdit(i); } } /////////////////////////////////////////////////////////////////////////////// // Create Instance /////////////////////////////////////////////////////////////////////////////// static int8_t g_initialized = -1; static MY_CRITSEC_INIT(g_createEffMutex); static void appendStr(wchar_t *buffer, const size_t &size, const wchar_t *const text, ...) { wchar_t temp[128]; va_list argList; va_start(argList, text); _vsnwprintf_s(temp, 128, _TRUNCATE, text, argList); va_end(argList); wcsncat_s(buffer, size, temp, _TRUNCATE); } static bool showAboutScreen(const uint32_t & major, const uint32_t & minor, const uint32_t & patch, const char *const date, const char *const time, const char *const compiler, const char *const arch, const bool &debug) { wchar_t text[1024] = { '\0' }; appendStr(text, 1024, L"Dynamic Audio Normalizer, VST Wrapper, Version %u.%02u-%u, %s\n", major, minor, patch, (debug ? L"DEBGU" : L"Release")); appendStr(text, 1024, L"Copyright (c) 2014-%S LoRd_MuldeR .\n", &date[7]); appendStr(text, 1024, L"Built on %S at %S with %S for %S.\n\n", date, time, compiler, arch); appendStr(text, 1024, L"This library is free software; you can redistribute it and/or\n"); appendStr(text, 1024, L"modify it under the terms of the GNU Lesser General Public\n"); appendStr(text, 1024, L"License as published by the Free Software Foundation; either\n"); appendStr(text, 1024, L"version 2.1 of the License, or (at your option) any later version.\n\n"); appendStr(text, 1024, L"This library is distributed in the hope that it will be useful,\n"); appendStr(text, 1024, L"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); appendStr(text, 1024, L"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"); appendStr(text, 1024, L"Lesser General Public License for more details.\n\n"); appendStr(text, 1024, L"Please click 'OK' if you agree to the above notice or 'Cancel' otherwise...\n"); return (MessageBoxW(NULL, text, L"Dynamic Audio Normalizer", MB_SYSTEMMODAL | MB_OKCANCEL | MB_DEFBUTTON2) == IDOK); } static bool initializeCoreLibrary(void) { MDynamicAudioNormalizer::setLogFunction(logFunction); uint32_t major, minor, patch; MDynamicAudioNormalizer::getVersionInfo(major, minor, patch); outputMessage("[DynAudNorm_VST] Dynamic Audio Normalizer VST-Wrapper (v%u.%02u-%u)", major, minor, patch); wchar_t appUuid[64]; if(getAppUuid(appUuid, 64)) { const DWORD version = (1000u * major) + (10u * minor) + patch; if(regValueGet(appUuid) != version) { const char *date, *time, *compiler, *arch; bool debug; MDynamicAudioNormalizer::getBuildInfo(&date, &time, &compiler, &arch, debug); if(!showAboutScreen(major, minor, patch, date, time, compiler, arch, debug)) { return false; } regValueSet(appUuid, version); } } return true; } AudioEffect* createEffectInstance(audioMasterCallback audioMaster) { MY_CRITSEC_ENTER(g_createEffMutex); AudioEffect *effectInstance = NULL; if(g_initialized < 0) { g_initialized = initializeCoreLibrary() ? 1 : 0; } if(g_initialized > 0) { effectInstance = new DynamicAudioNormalizerVST(audioMaster); } MY_CRITSEC_LEAVE(g_createEffMutex); return effectInstance; } ================================================ FILE: DynamicAudioNormalizerVST/src/DynamicAudioNormalizerVST.h ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - VST 2.x Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////// // ACKNOWLEDGEMENT: // (1) VST PlugIn Interface Technology by Steinberg Media Technologies GmbH. // (2) VST is a trademark of Steinberg Media Technologies GmbH. ////////////////////////////////////////////////////////////////////////////////// #ifndef DYNAMICAUDIONORMALIZERVST_H #define DYNAMICAUDIONORMALIZERVST_H //VST SDK includes #include "public.sdk/source/vst2.x/audioeffectx.h" //Forward declaration class DynamicAudioNormalizerVST_PrivateData; //Standard Lib #include class DynamicAudioNormalizerVST : public AudioEffectX { public: DynamicAudioNormalizerVST(audioMasterCallback audioMaster); ~DynamicAudioNormalizerVST(); virtual void open(void); virtual void close(void); virtual void suspend(void); virtual void resume(void); // Processing virtual void processReplacing (float** inputs, float** outputs, VstInt32 sampleFrames); virtual void processDoubleReplacing (double** inputs, double** outputs, VstInt32 sampleFrames); virtual VstInt32 getGetTailSize(void); // Program virtual void setProgram(VstInt32 program); virtual void setProgramName (char* name); virtual void getProgramName (char* name); virtual bool getProgramNameIndexed(VstInt32 category, VstInt32 index, char* text); // Parameters virtual void setParameter(VstInt32 index, float value); virtual float getParameter(VstInt32 index); virtual float getParameterDefault(VstInt32 index); virtual double getParameterValue(VstInt32 index); virtual void getParameterLabel(VstInt32 index, char* label); virtual void getParameterDisplay(VstInt32 index, char* text); virtual void getParameterName(VstInt32 index, char* text); // Information virtual bool getEffectName (char* name); virtual bool getVendorString (char* text); virtual bool getProductString (char* text); virtual VstInt32 getVendorVersion(void); virtual VstPlugCategory getPlugCategory(void); private: bool createNewInstance(const uint32_t sampleRate); void updateBufferSize(const size_t requiredSize); void readInputSamplesFlt(const float *const *const inputs, const int64_t sampleCount); void readInputSamplesDbl(const double *const *const inputs, const int64_t sampleCount); void writeOutputSamplesFlt(float *const *const outputs, const int64_t requiredSamples, const int64_t availableSamples); void writeOutputSamplesDbl(double *const *const outputs, const int64_t requiredSamples, const int64_t availableSamples); void forceUpdateParameters(void); DynamicAudioNormalizerVST_PrivateData *const p; }; #endif //DYNAMICAUDIONORMALIZERVST_H ================================================ FILE: DynamicAudioNormalizerVST/src/Spooky.cpp ================================================ // Spooky Hash // A 128-bit noncryptographic hash, for checksums and table lookup // By Bob Jenkins. Public domain. // // This is a stripped-down version derived from the original source code. Find the original code at: // http://burtleburtle.net/bob/hash/spooky.html #include "Spooky.h" #include #define ALLOW_UNALIGNED_READS 1 static const size_t sc_numVars = 12; static const size_t sc_blockSize = sc_numVars*8; static const size_t sc_bufSize = 2*sc_blockSize; static const uint64_t sc_const = 0xdeadbeefdeadbeefLL; static inline uint64_t Rot64(uint64_t x, int k) { return (x << k) | (x >> (64 - k)); } static inline void Mix ( const uint64_t *data, uint64_t &s0, uint64_t &s1, uint64_t & s2, uint64_t & s3, uint64_t &s4, uint64_t &s5, uint64_t & s6, uint64_t & s7, uint64_t &s8, uint64_t &s9, uint64_t &s10, uint64_t &s11 ) { s0 += data[0]; s2 ^= s10; s11 ^= s0; s0 = Rot64(s0, 11); s11 += s1; s1 += data[1]; s3 ^= s11; s0 ^= s1; s1 = Rot64(s1, 32); s0 += s2; s2 += data[2]; s4 ^= s0; s1 ^= s2; s2 = Rot64(s2, 43); s1 += s3; s3 += data[3]; s5 ^= s1; s2 ^= s3; s3 = Rot64(s3, 31); s2 += s4; s4 += data[4]; s6 ^= s2; s3 ^= s4; s4 = Rot64(s4, 17); s3 += s5; s5 += data[5]; s7 ^= s3; s4 ^= s5; s5 = Rot64(s5, 28); s4 += s6; s6 += data[6]; s8 ^= s4; s5 ^= s6; s6 = Rot64(s6, 39); s5 += s7; s7 += data[7]; s9 ^= s5; s6 ^= s7; s7 = Rot64(s7, 57); s6 += s8; s8 += data[8]; s10 ^= s6; s7 ^= s8; s8 = Rot64(s8, 55); s7 += s9; s9 += data[9]; s11 ^= s7; s8 ^= s9; s9 = Rot64(s9, 54); s8 += s10; s10 += data[10]; s0 ^= s8; s9 ^= s10; s10 = Rot64(s10, 22); s9 += s11; s11 += data[11]; s1 ^= s9; s10 ^= s11; s11 = Rot64(s11, 46); s10 += s0; } static inline void ShortMix(uint64_t &h0, uint64_t &h1, uint64_t &h2, uint64_t &h3) { h2 = Rot64(h2,50); h2 += h3; h0 ^= h2; h3 = Rot64(h3,52); h3 += h0; h1 ^= h3; h0 = Rot64(h0,30); h0 += h1; h2 ^= h0; h1 = Rot64(h1,41); h1 += h2; h3 ^= h1; h2 = Rot64(h2,54); h2 += h3; h0 ^= h2; h3 = Rot64(h3,48); h3 += h0; h1 ^= h3; h0 = Rot64(h0,38); h0 += h1; h2 ^= h0; h1 = Rot64(h1,37); h1 += h2; h3 ^= h1; h2 = Rot64(h2,62); h2 += h3; h0 ^= h2; h3 = Rot64(h3,34); h3 += h0; h1 ^= h3; h0 = Rot64(h0, 5); h0 += h1; h2 ^= h0; h1 = Rot64(h1,36); h1 += h2; h3 ^= h1; } static inline void ShortEnd(uint64_t &h0, uint64_t &h1, uint64_t &h2, uint64_t &h3) { h3 ^= h2; h2 = Rot64(h2,15); h3 += h2; h0 ^= h3; h3 = Rot64(h3,52); h0 += h3; h1 ^= h0; h0 = Rot64(h0,26); h1 += h0; h2 ^= h1; h1 = Rot64(h1,51); h2 += h1; h3 ^= h2; h2 = Rot64(h2,28); h3 += h2; h0 ^= h3; h3 = Rot64(h3, 9); h0 += h3; h1 ^= h0; h0 = Rot64(h0,47); h1 += h0; h2 ^= h1; h1 = Rot64(h1,54); h2 += h1; h3 ^= h2; h2 = Rot64(h2,32); h3 += h2; h0 ^= h3; h3 = Rot64(h3,25); h0 += h3; h1 ^= h0; h0 = Rot64(h0,63); h1 += h0; } static void Short(const void *message, size_t length, uint64_t *hash1, uint64_t *hash2) { uint64_t buf[2 * sc_numVars]; union { const uint8_t *p8; uint32_t *p32; uint64_t *p64; size_t i; } u; u.p8 = (const uint8_t *)message; if (!ALLOW_UNALIGNED_READS && (u.i & 0x7)) { memcpy(buf, message, length); u.p64 = buf; } size_t remainder = length % 32; uint64_t a = *hash1; uint64_t b = *hash2; uint64_t c = sc_const; uint64_t d = sc_const; if (length > 15) { const uint64_t *end = u.p64 + (length / 32) * 4; // handle all complete sets of 32 bytes for (; u.p64 < end; u.p64 += 4) { c += u.p64[0]; d += u.p64[1]; ShortMix(a, b, c, d); a += u.p64[2]; b += u.p64[3]; } //Handle the case of 16+ remaining bytes. if (remainder >= 16) { c += u.p64[0]; d += u.p64[1]; ShortMix(a, b, c, d); u.p64 += 2; remainder -= 16; } } // Handle the last 0..15 bytes, and its length d += ((uint64_t)length) << 56; switch (remainder) { case 15: d += ((uint64_t)u.p8[14]) << 48; case 14: d += ((uint64_t)u.p8[13]) << 40; case 13: d += ((uint64_t)u.p8[12]) << 32; case 12: d += u.p32[2]; c += u.p64[0]; break; case 11: d += ((uint64_t)u.p8[10]) << 16; case 10: d += ((uint64_t)u.p8[9]) << 8; case 9: d += (uint64_t)u.p8[8]; case 8: c += u.p64[0]; break; case 7: c += ((uint64_t)u.p8[6]) << 48; case 6: c += ((uint64_t)u.p8[5]) << 40; case 5: c += ((uint64_t)u.p8[4]) << 32; case 4: c += u.p32[0]; break; case 3: c += ((uint64_t)u.p8[2]) << 16; case 2: c += ((uint64_t)u.p8[1]) << 8; case 1: c += (uint64_t)u.p8[0]; break; case 0: c += sc_const; d += sc_const; } ShortEnd(a, b, c, d); *hash1 = a; *hash2 = b; } static inline void EndPartial ( uint64_t &h0, uint64_t &h1, uint64_t & h2, uint64_t & h3, uint64_t &h4, uint64_t &h5, uint64_t & h6, uint64_t & h7, uint64_t &h8, uint64_t &h9, uint64_t &h10, uint64_t &h11 ) { h11+= h1; h2 ^= h11; h1 = Rot64( h1,44); h0 += h2; h3 ^= h0; h2 = Rot64( h2,15); h1 += h3; h4 ^= h1; h3 = Rot64( h3,34); h2 += h4; h5 ^= h2; h4 = Rot64( h4,21); h3 += h5; h6 ^= h3; h5 = Rot64( h5,38); h4 += h6; h7 ^= h4; h6 = Rot64( h6,33); h5 += h7; h8 ^= h5; h7 = Rot64( h7,10); h6 += h8; h9 ^= h6; h8 = Rot64( h8,13); h7 += h9; h10 ^= h7; h9 = Rot64( h9,38); h8 += h10; h11 ^= h8; h10 = Rot64(h10,53); h9 += h11; h0 ^= h9; h11 = Rot64(h11,42); h10+= h0; h1 ^= h10; h0 = Rot64( h0,54); } static inline void End ( const uint64_t *data, uint64_t &h0, uint64_t &h1, uint64_t &h2, uint64_t & h3, uint64_t &h4, uint64_t &h5, uint64_t &h6, uint64_t & h7, uint64_t &h8, uint64_t &h9, uint64_t &h10, uint64_t &h11 ) { h0 += data[0]; h1 += data[1]; h2 += data [2]; h3 += data [3]; h4 += data[4]; h5 += data[5]; h6 += data [6]; h7 += data [7]; h8 += data[8]; h9 += data[9]; h10 += data[10]; h11 += data[11]; EndPartial(h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); EndPartial(h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); EndPartial(h0,h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11); } void hash128(const void *const message, size_t length, uint64_t *hash1, uint64_t *hash2) { if (length < sc_bufSize) { Short(message, length, hash1, hash2); return; } uint64_t h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11; uint64_t buf[sc_numVars]; uint64_t *end; union { const uint8_t *p8; uint64_t *p64; size_t i; } u; size_t remainder; h0 = h3 = h6 = h9 = *hash1; h1 = h4 = h7 = h10 = *hash2; h2 = h5 = h8 = h11 = sc_const; u.p8 = (const uint8_t *)message; end = u.p64 + (length / sc_blockSize)*sc_numVars; // handle all whole sc_blockSize blocks of bytes if (ALLOW_UNALIGNED_READS || ((u.i & 0x7) == 0)) { while (u.p64 < end) { Mix(u.p64, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11); u.p64 += sc_numVars; } } else { while (u.p64 < end) { memcpy(buf, u.p64, sc_blockSize); Mix(buf, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11); u.p64 += sc_numVars; } } // handle the last partial block of sc_blockSize bytes remainder = (length - ((const uint8_t*)end - (const uint8_t*)message)); memcpy(buf, end, remainder); memset(((uint8_t*)buf) + remainder, 0, sc_blockSize - remainder); ((uint8_t*)buf)[sc_blockSize - 1] = (uint8_t)((uint32_t)remainder); // do some final mixing End(buf, h0, h1, h2, h3, h4, h5, h6, h7, h8, h9, h10, h11); *hash1 = h0; *hash2 = h1; } void hash128(const wchar_t *const message, uint64_t *hash1, uint64_t *hash2) { hash128(message, wcslen(message) * sizeof(wchar_t), hash1, hash2); } ================================================ FILE: DynamicAudioNormalizerVST/src/Spooky.h ================================================ // Spooky Hash // A 128-bit noncryptographic hash, for checksums and table lookup // By Bob Jenkins. Public domain. // // This is a stripped-down version derived from the original source code. Find the original code at: // http://burtleburtle.net/bob/hash/spooky.html #include #include void hash128(const void *const message, size_t length, uint64_t *hash1, uint64_t *hash2); void hash128(const wchar_t *const message, uint64_t *hash1, uint64_t *hash2); ================================================ FILE: DynamicAudioNormalizerWA5/DynamicAudioNormalizerWA5_VS2013.vcxproj ================================================  Debug Win32 Release_DLL Win32 Release_Static Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14} Win32Proj DynamicAudioNormalizerWA5 DynamicAudioNormalizerWA5 DynamicLibrary true v120_xp Unicode DynamicLibrary false v120_xp true Unicode DynamicLibrary false v120_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ NotUsing Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERWA5_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\etc\winamp_sdk\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include MultiThreadedDebugDLL NoExtensions Windows true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\shared %(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERWA5_EXPORTS;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\etc\winamp_sdk\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include MultiThreaded MultiThreaded MultiThreaded false Fast AnySuitable Speed true true StreamingSIMDExtensions2 Windows true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\static %(AdditionalDependencies) false LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERWA5_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\etc\winamp_sdk\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include MultiThreadedDLL false Fast AnySuitable Speed true true StreamingSIMDExtensions2 Windows false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\shared %(AdditionalDependencies) LinkVerboseLib {376386ee-8268-47e3-a335-7663716e4c60} ================================================ FILE: DynamicAudioNormalizerWA5/DynamicAudioNormalizerWA5_VS2013.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files ================================================ FILE: DynamicAudioNormalizerWA5/DynamicAudioNormalizerWA5_VS2015.vcxproj ================================================  Debug Win32 Release_DLL Win32 Release_Static Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14} Win32Proj DynamicAudioNormalizerWA5 DynamicAudioNormalizerWA5 DynamicLibrary true v140_xp Unicode DynamicLibrary false v140_xp true Unicode DynamicLibrary false v140_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ NotUsing Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERWA5_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\etc\winamp_sdk\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include MultiThreadedDebugDLL NoExtensions Windows true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\shared %(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERWA5_EXPORTS;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\etc\winamp_sdk\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include MultiThreaded MultiThreaded MultiThreaded false Fast AnySuitable Speed true true StreamingSIMDExtensions2 Windows true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\static %(AdditionalDependencies) false LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERWA5_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\etc\winamp_sdk\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include MultiThreadedDLL false Fast AnySuitable Speed true true StreamingSIMDExtensions2 Windows false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\shared %(AdditionalDependencies) LinkVerboseLib {376386ee-8268-47e3-a335-7663716e4c60} true true false true false ================================================ FILE: DynamicAudioNormalizerWA5/DynamicAudioNormalizerWA5_VS2015.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files ================================================ FILE: DynamicAudioNormalizerWA5/DynamicAudioNormalizerWA5_VS2017.vcxproj ================================================  Debug Win32 Release_DLL Win32 Release_Static Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14} Win32Proj DynamicAudioNormalizerWA5 DynamicAudioNormalizerWA5 8.1 DynamicLibrary true v141_xp Unicode DynamicLibrary false v141_xp true Unicode DynamicLibrary false v141_xp true Unicode true $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ false $(SolutionDir)\bin\$(Platform)\$(PlatformToolset)\$(Configuration)\ $(SolutionDir)\obj\$(ProjectName)\$(Platform)\$(PlatformToolset)\$(Configuration)\ NotUsing Level3 Disabled WIN32;_DEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERWA5_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\etc\winamp_sdk\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include MultiThreadedDebugDLL NoExtensions Windows true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\shared %(AdditionalDependencies) LinkVerboseLib Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERWA5_EXPORTS;MDYNAMICAUDIONORMALIZER_STATIC;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\etc\winamp_sdk\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include MultiThreaded MultiThreaded MultiThreaded false Fast AnySuitable Speed true true StreamingSIMDExtensions2 Windows true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\static %(AdditionalDependencies) false LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) Level3 NotUsing MaxSpeed true true WIN32;NDEBUG;_WINDOWS;_USRDLL;DYNAMICAUDIONORMALIZERWA5_EXPORTS;%(PreprocessorDefinitions) $(SolutionDir)\DynamicAudioNormalizerAPI\include;$(SolutionDir)\DynamicAudioNormalizerShared\include;$(SolutionDir)\etc\winamp_sdk\include;$(SolutionDir)\..\Prerequisites\PthreadsW32\include MultiThreadedDLL false Fast AnySuitable Speed true true StreamingSIMDExtensions2 Windows false true true $(SolutionDir)\..\Prerequisites\PthreadsW32\lib\$(Platform)\shared %(AdditionalDependencies) LinkVerboseLib $(SolutionDir)DynamicAudioNormalizerShared\res\compat.manifest %(AdditionalManifestFiles) {376386ee-8268-47e3-a335-7663716e4c60} true true false true false ================================================ FILE: DynamicAudioNormalizerWA5/DynamicAudioNormalizerWA5_VS2017.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files Resource Files ================================================ FILE: DynamicAudioNormalizerWA5/res/DynamicAudioNormalizerWA5.rc ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Audio Processing Library // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // http://www.gnu.org/licenses/lgpl-2.1.txt ////////////////////////////////////////////////////////////////////////////////// #include "WinResrc.h" //"afxres.h" #define INC_DYNAUDNORM_VERSION_INTERNAL 0x22b4f8a9 #include "../DynamicAudioNormalizerShared/res/version.inc" ////////////////////////////////////////////////////////////////////////////////// // Neutral resources ////////////////////////////////////////////////////////////////////////////////// #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) #ifdef _WIN32 LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL #pragma code_page(1252) #endif //_WIN32 ////////////////////////////////////////////////////////////////////////////////// // Version ////////////////////////////////////////////////////////////////////////////////// VS_VERSION_INFO VERSIONINFO FILEVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH PRODUCTVERSION VER_DYNAUDNORM_MAJOR,VER_DYNAUDNORM_MINOR_HI,VER_DYNAUDNORM_MINOR_LO,VER_DYNAUDNORM_PATCH FILEFLAGSMASK 0x17L #ifdef _DEBUG FILEFLAGS 0x3L #else FILEFLAGS 0x2L #endif FILEOS 0x40004L FILETYPE 0x2L FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "000004b0" BEGIN VALUE "Comments", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License ." VALUE "CompanyName", "LoRd_MuldeR " VALUE "FileDescription", "DynamicAudioNormalizer Winamp Plugin" VALUE "FileVersion", VER_DYNAUDNORM_STR VALUE "InternalName", "DynamicAudioNormalizerWA5" VALUE "LegalCopyright", "Copyright (c) 2014-2019 LoRd_MuldeR " VALUE "LegalTrademarks", "This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License " VALUE "OriginalFilename", "DynamicAudioNormalizerWA5.dll" VALUE "ProductName", "DynamicAudioNormalizer" VALUE "ProductVersion", VER_DYNAUDNORM_STR END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x0, 1200 END END #endif // Neutral resources ================================================ FILE: DynamicAudioNormalizerWA5/src/DynamicAudioNormalizerWA5.cpp ================================================ ////////////////////////////////////////////////////////////////////////////////// // Dynamic Audio Normalizer - Winamp DSP Wrapper // Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // 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 OR COPYRIGHT HOLDERS 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. // // http://opensource.org/licenses/MIT ////////////////////////////////////////////////////////////////////////////////// //Stdlib #include #include #include #include //Win32 #define NOMINMAX 1 #define WIN32_LEAN_AND_MEAN 1 #include //Winamp #include #include //Internal #include #include //Dynamic Audio Normalizer API #include //DLL exports #define DLL_EXPORT __declspec(dllexport) //Reg key static const wchar_t *REGISTRY_BASEPATH = L"Software\\MuldeR\\DynAudNorm\\WA5"; static const wchar_t *REGISTRY_VERSION = L"Version"; static const wchar_t *REGISTRY_FRAMELEN = L"FrameLenMsec"; static const wchar_t *REGISTRY_FLTRSIZE = L"FilterSize"; //Defaults static const DWORD FRAMELEN_DEFAULT = 500; static const DWORD FLTRSIZE_DEFAULT = 31; //Critical Section static char g_loggingBuffer[1024]; static MY_CRITSEC_INIT(g_loggingMutex); //Forward declarations static void config(struct winampDSPModule*); static int init(struct winampDSPModule*); static void quit(struct winampDSPModule*); static int modify_samples(struct winampDSPModule*, short int*, int, int, int, int); static winampDSPModule *getModule(int); static int sf(int); static bool showAboutScreen(const uint32_t&, const uint32_t&, const uint32_t&, const char *const, const char *const, const char *const, const char *const, const bool&, const bool &config); //Const static const size_t MAX_CHANNELS = 12; /////////////////////////////////////////////////////////////////////////////// // Global Data /////////////////////////////////////////////////////////////////////////////// static char g_description[256] = { '\0' }; static winampDSPHeader g_header = { DSP_HDRVER + 1, "Dynamic Audio Normalizer [" __DATE__ "]", getModule, sf }; static winampDSPModule g_module = { g_description, NULL, // hwndParent NULL, // hDllInstance config, init, modify_samples, quit }; static struct { uint32_t sampleRate; uint32_t bitsPerSample; uint32_t channels; } g_properties = { 44100, 16, 2 }; static volatile WNDPROC g_oldWndProc = NULL; static volatile LONG g_forceReset = 0; static volatile DWORD g_lastResetTick = 0; /////////////////////////////////////////////////////////////////////////////// // Helper functions /////////////////////////////////////////////////////////////////////////////// static void outputMessage(const char *const format, ...) { MY_CRITSEC_ENTER(g_loggingMutex); va_list argList; va_start(argList, format); vsnprintf_s(g_loggingBuffer, 1024, _TRUNCATE, format, argList); va_end(argList); OutputDebugStringA(g_loggingBuffer); MY_CRITSEC_LEAVE(g_loggingMutex); } static void logFunction(const int logLevel, const char *const message) { switch (logLevel) { case MDynamicAudioNormalizer::LOG_LEVEL_DBG: outputMessage("[DynAudNorm_WA5] NFO: %s\n", message); break; case MDynamicAudioNormalizer::LOG_LEVEL_WRN: outputMessage("[DynAudNorm_WA5] WRN: %s\n", message); break; case MDynamicAudioNormalizer::LOG_LEVEL_ERR: outputMessage("[DynAudNorm_WA5] ERR: %s\n", message); break; default: outputMessage("[DynAudNorm_WA5] DBG: %s\n", message); break; } } static void showErrorMsg(const char *const text) { MessageBoxA(NULL, text, "Dynamic Audio Normalizer", MB_ICONSTOP | MB_TOPMOST | MB_TASKMODAL); } static DWORD regValueGet(const wchar_t *const name) { DWORD result = 0; HKEY hKey = NULL; if(RegCreateKeyExW(HKEY_CURRENT_USER, REGISTRY_BASEPATH, 0, NULL, 0, KEY_READ, NULL, &hKey, NULL) == ERROR_SUCCESS) { DWORD type = 0, value = 0, size = sizeof(DWORD); if(RegQueryValueExW(hKey, name, 0, &type, ((LPBYTE) &value), &size) == ERROR_SUCCESS) { if((type == REG_DWORD) && (size == sizeof(DWORD))) { result = value; } } RegCloseKey(hKey); } return result; } static bool regValueSet(const wchar_t *const name, const DWORD &value) { bool result = false; HKEY hKey = NULL; if(RegCreateKeyExW(HKEY_CURRENT_USER, REGISTRY_BASEPATH, 0, NULL, 0, KEY_WRITE, NULL, &hKey, NULL) == ERROR_SUCCESS) { if(RegSetValueExW(hKey, name, 0, REG_DWORD, ((LPBYTE) &value), sizeof(DWORD)) == ERROR_SUCCESS) { result = true; } RegCloseKey(hKey); } return result; } static double *allocBuffer(size_t size) { double *buffer = NULL; try { buffer = new double[size]; } catch(...) { outputMessage("[DynAudNorm_WA5] ERR: Allocation of size %u failed!", static_cast(sizeof(double) * size)); showErrorMsg("Memory allocation has failed: Out of memory!"); _exit(0xC0000017); } return buffer; } /////////////////////////////////////////////////////////////////////////////// // Internal Functions /////////////////////////////////////////////////////////////////////////////// static MDynamicAudioNormalizer *g_instance = NULL; static size_t g_sampleBufferSize = 0; static double *g_sampleBuffer[MAX_CHANNELS]; static void updateBufferSize(const int &numsamples) { if(size_t(numsamples) > g_sampleBufferSize) { if(g_sampleBufferSize > 0) { for(int c = 0; c < MAX_CHANNELS; c++) { delete [] (g_sampleBuffer[c]); g_sampleBuffer[c] = NULL; } } for(int c = 0; c < MAX_CHANNELS; c++) { g_sampleBuffer[c] = allocBuffer(numsamples); } g_sampleBufferSize = numsamples; } } static void deinterleave(const short int *const input, const int &numsamples, const int &bps, const int &nch) { updateBufferSize(numsamples); if(bps == 16) { const short int *ptr = input; for(int i = 0; i < numsamples; i++) { for(int c = 0; c < nch; c++) { g_sampleBuffer[c][i] = std::min(1.0, std::max(-1.0, (double(*(ptr++)) / double(SHRT_MAX)))); } } } else if(bps == 8) { const int8_t *ptr = reinterpret_cast(input); for(int i = 0; i < numsamples; i++) { for(int c = 0; c < nch; c++) { g_sampleBuffer[c][i] = std::min(1.0, std::max(-1.0, (double(*(ptr++)) / double(INT8_MAX)))); } } } else { showErrorMsg("Unsupported bit-depth detected!"); } } static void interleave(short int *const output, const int &numsamples, const int &bps, const int &nch) { updateBufferSize(numsamples); if(bps == 16) { short int *ptr = output; for(int i = 0; i < numsamples; i++) { for(int c = 0; c < nch; c++) { *(ptr++) = static_cast(std::max(double(SHRT_MIN), std::min(double(SHRT_MAX), round(g_sampleBuffer[c][i] * double(SHRT_MAX))))); } } } else if(bps == 8) { int8_t *ptr = reinterpret_cast(output); for(int i = 0; i < numsamples; i++) { for(int c = 0; c < nch; c++) { *(ptr++) = static_cast(std::max(double(INT8_MIN), std::min(double(INT8_MAX), round(g_sampleBuffer[c][i] * double(INT8_MAX))))); } } } else { showErrorMsg("Unsupported bit-depth detected!"); } } static bool createNewInstance(const uint32_t sampleRate, const uint32_t channelCount) { if(g_instance) { delete g_instance; g_instance = NULL; } const DWORD optionFrameLen = regValueGet(REGISTRY_FRAMELEN); const DWORD optionFltrSize = regValueGet(REGISTRY_FLTRSIZE); try { g_instance = new MDynamicAudioNormalizer ( channelCount, sampleRate, optionFrameLen ? optionFrameLen : FRAMELEN_DEFAULT, optionFltrSize ? optionFltrSize : FLTRSIZE_DEFAULT ); } catch(...) { showErrorMsg("Failed to create Dynamic Audio Normalizer instance!"); return false; } if(!g_instance->initialize()) { showErrorMsg("Dynamic Audio Normalizer initialization has failed!"); return false; } return true; } static bool detectWinampVersion(const HWND &hwndParent) { unsigned long winampVersion = 0; unsigned long winampVersionMajor = 0; unsigned long winampVersionMinor = 0; if(SendMessageTimeout(hwndParent, WM_WA_IPC, 0, IPC_GETVERSION, SMTO_ABORTIFHUNG, 5000, &winampVersion)) { if((winampVersion >= 0x5000) && (winampVersion <= 0xFFFFF)) { winampVersionMajor = (winampVersion >> 0xC); winampVersionMinor = (winampVersion & 0xFF); } } else { winampVersion = 0xFFFFFFFF; } outputMessage("[DynAudNorm_WA5] Winamp version is: 0x%X (v%X.%02X)", winampVersion, winampVersionMajor, winampVersionMinor); if(winampVersionMajor < 1) { showErrorMsg("Failed to detect Winamp version. Please use Winamp 5.0 or newer!"); return false; } if(winampVersionMajor < 5) { showErrorMsg("Your Winamp version is too old. Please use Winamp 5.0 or newer!"); return false; } return true; } static LRESULT CALLBACK winampWindowHook(const HWND hwnd, const UINT uMsg, const WPARAM wParam, const LPARAM lParam) { if ((lParam == IPC_CB_MISC) && ((wParam == IPC_CB_MISC_STATUS) || (wParam == IPC_CB_MISC_TITLE))) { InterlockedIncrement(&g_forceReset); } if (g_oldWndProc) { return g_oldWndProc(hwnd, uMsg, wParam, lParam); } return 0L; } /////////////////////////////////////////////////////////////////////////////// // Public Functions /////////////////////////////////////////////////////////////////////////////// static void config(struct winampDSPModule *this_mod) { outputMessage("[DynAudNorm_WA5] WinampDSP::config(%p)", this_mod); uint32_t major, minor, patch; MDynamicAudioNormalizer::getVersionInfo(major, minor, patch); const char *date, *time, *compiler, *arch; bool debug; MDynamicAudioNormalizer::getBuildInfo(&date, &time, &compiler, &arch, debug); showAboutScreen(major, minor, patch, date, time, compiler, arch, debug, true); } static int init(struct winampDSPModule *this_mod) { outputMessage("[DynAudNorm_WA5] WinampDSP::init(%p)", this_mod); detectWinampVersion(this_mod->hwndParent); if(g_sampleBufferSize == 0) { for(int c = 0; c < MAX_CHANNELS; c++) { g_sampleBuffer[c] = allocBuffer(1024); } g_sampleBufferSize = 1024; } if(!createNewInstance(g_properties.sampleRate, g_properties.channels)) { return 1; } if (!(g_oldWndProc = (WNDPROC)SetWindowLong(this_mod->hwndParent, GWL_WNDPROC, (LONG_PTR)winampWindowHook))) { outputMessage("[DynAudNorm_WA5] WARNING: Failed to hook Winamp window!"); } return 0; } static void quit(struct winampDSPModule *this_mod) { outputMessage("[DynAudNorm_WA5] WinampDSP::quit(%p)", this_mod); if (g_oldWndProc) { if (SetWindowLong(this_mod->hwndParent, GWL_WNDPROC, (LONG_PTR)g_oldWndProc)) { g_oldWndProc = NULL; } } if(g_sampleBufferSize > 0) { for(int c = 0; c < MAX_CHANNELS; c++) { delete [] (g_sampleBuffer[c]); g_sampleBuffer[c] = NULL; } g_sampleBufferSize = 0; } } static int modify_samples(struct winampDSPModule *this_mod, short int *samples, int numsamples, int bps, int nch, int srate) { if(numsamples < 1) { outputMessage("[DynAudNorm_WA5] Sample count is zero or negative -> nothing to do!"); return 0; } if(nch > MAX_CHANNELS) { showErrorMsg("Maximum channel count has been exceeded!"); return 0; } if((!g_instance) || (g_properties.bitsPerSample != bps) || (g_properties.channels != nch) || (g_properties.sampleRate != srate)) { outputMessage("[DynAudNorm_WA5] WinampDSP::modify_samples(mod=%p, num=%d, bps=%d, nch=%d, srate=%d)", this_mod, numsamples, bps, nch, srate); g_properties.bitsPerSample = bps; g_properties.channels = nch; g_properties.sampleRate = srate; if(!createNewInstance(g_properties.sampleRate, g_properties.channels)) { return 0; /*creating instance failed!*/ } } else if (InterlockedExchange(&g_forceReset, 0L) > 0L) { const DWORD tickCount = GetTickCount(); if ((tickCount < g_lastResetTick) || ((tickCount - g_lastResetTick) > 250L)) { if (g_lastResetTick) { outputMessage("[DynAudNorm_WA5] Reset has been triggered!"); g_instance->reset(); } g_lastResetTick = tickCount; } } deinterleave(samples, numsamples, bps, nch); int64_t outputSize; g_instance->processInplace(g_sampleBuffer, numsamples, outputSize); interleave(samples, static_cast(outputSize), bps, nch); return static_cast(outputSize); } /////////////////////////////////////////////////////////////////////////////// // Winamp DSP API /////////////////////////////////////////////////////////////////////////////// static int8_t g_initialized = -1; static MY_CRITSEC_INIT(g_createEffMutex); static void appendStr(wchar_t *buffer, const size_t &size, const wchar_t *const text, ...) { wchar_t temp[128]; va_list argList; va_start(argList, text); _vsnwprintf_s(temp, 128, _TRUNCATE, text, argList); va_end(argList); wcsncat_s(buffer, size, temp, _TRUNCATE); } static bool showAboutScreen(const uint32_t &major, const uint32_t &minor, const uint32_t &patch, const char *const date, const char *const time, const char *const compiler, const char *const arch, const bool &debug, const bool &config) { wchar_t text[1024] = { '\0' }; appendStr(text, 1024, L"Dynamic Audio Normalizer, Winamp Wrapper, Version %u.%02u-%u, %s\n", major, minor, patch, (debug ? L"DEBGU" : L"Release")); appendStr(text, 1024, L"Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved.\n"); appendStr(text, 1024, L"Built on %S at %S with %S for %S.\n\n", date, time, compiler, arch); appendStr(text, 1024, L"This library is free software; you can redistribute it and/or\n"); appendStr(text, 1024, L"modify it under the terms of the GNU Lesser General Public\n"); appendStr(text, 1024, L"License as published by the Free Software Foundation; either\n"); appendStr(text, 1024, L"version 2.1 of the License, or (at your option) any later version.\n\n"); appendStr(text, 1024, L"This library is distributed in the hope that it will be useful,\n"); appendStr(text, 1024, L"but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); appendStr(text, 1024, L"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"); appendStr(text, 1024, L"Lesser General Public License for more details.\n"); if(config) { MessageBoxW(NULL, text, L"Dynamic Audio Normalizer", MB_TOPMOST | MB_TASKMODAL | MB_OK); return true; } else { appendStr(text, 1024, L"\nPlease click 'OK' if you agree to the above notice or 'Cancel' otherwise...\n"); const int ret = MessageBoxW(NULL, text, L"Dynamic Audio Normalizer", MB_TOPMOST | MB_TASKMODAL | MB_OKCANCEL | MB_DEFBUTTON2); return (ret == IDOK); } } static bool initializeCoreLibrary(void) { MDynamicAudioNormalizer::setLogFunction(logFunction); uint32_t major, minor, patch; MDynamicAudioNormalizer::getVersionInfo(major, minor, patch); outputMessage("[DynAudNorm_WA5] Dynamic Audio Normalizer Winamp-Wrapper (v%u.%02u-%u)", major, minor, patch); _snprintf_s(g_description, 256, _TRUNCATE, "Dynamic Audio Normalizer v%u.%02u-%u [by LoRd_MuldeR]", major, minor, patch); const DWORD version = (1000u * major) + (10u * minor) + patch; if(regValueGet(REGISTRY_VERSION) != version) { const char *date, *time, *compiler, *arch; bool debug; MDynamicAudioNormalizer::getBuildInfo(&date, &time, &compiler, &arch, debug); if(!showAboutScreen(major, minor, patch, date, time, compiler, arch, debug, false)) { return false; } regValueSet(REGISTRY_VERSION, version); regValueSet(REGISTRY_FRAMELEN, FRAMELEN_DEFAULT); regValueSet(REGISTRY_FLTRSIZE, FLTRSIZE_DEFAULT); } return true; } static winampDSPModule *getModule(int which) { outputMessage("[DynAudNorm_WA5] WinampDSP::getModule(%d)", which); winampDSPModule *module = NULL; MY_CRITSEC_ENTER(g_createEffMutex); if(which == 0) { if(g_initialized < 0) { g_initialized = initializeCoreLibrary() ? 1 : 0; } if(g_initialized > 0) { module = &g_module; } } MY_CRITSEC_LEAVE(g_createEffMutex); return module; } static int sf(int v) /*Note: The "sf" function was copied 1:1 from the example code, I have NO clue what it does!*/ { int res; res = v * (unsigned long)1103515245; res += (unsigned long)13293; res &= (unsigned long)0x7FFFFFFF; res ^= v; return res; } extern "C" DLL_EXPORT winampDSPHeader *winampDSPGetHeader2() { outputMessage("[DynAudNorm_WA5] WinampDSP::winampDSPGetHeader2()"); return &g_header; } ================================================ FILE: DynamicAudioNormalizer_VS2013.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 VisualStudioVersion = 12.0.30723.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerCLI", "DynamicAudioNormalizerCLI\DynamicAudioNormalizerCLI_VS2013.vcxproj", "{5B755CC3-EC17-490F-AE82-CBC16E2EB143}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerAPI", "DynamicAudioNormalizerAPI\DynamicAudioNormalizerAPI_VS2013.vcxproj", "{376386EE-8268-47E3-A335-7663716E4C60}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerGUI", "DynamicAudioNormalizerGUI\DynamicAudioNormalizerGUI_VS2013.vcxproj", "{131C921A-7144-4C1D-9C97-57C43FA83DFE}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerVST", "DynamicAudioNormalizerVST\DynamicAudioNormalizerVST_VS2013.vcxproj", "{A30375E8-AEF7-4531-B372-02328E0B9D43}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerWA5", "DynamicAudioNormalizerWA5\DynamicAudioNormalizerWA5_VS2013.vcxproj", "{4C09B776-E4AC-4459-9CEA-086011A0BA14}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerNET", "DynamicAudioNormalizerNET\DynamicAudioNormalizerNET_VS2013.vcxproj", "{E1794071-AB51-45C7-B215-028F3DAA2219}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerPYD", "DynamicAudioNormalizerPYD\DynamicAudioNormalizerPYD_VS2013.vcxproj", "{5ACB9827-9D3A-4C59-A948-8505D1544A8E}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Release_DLL|Win32 = Release_DLL|Win32 Release_DLL|x64 = Release_DLL|x64 Release_Static|Win32 = Release_Static|Win32 Release_Static|x64 = Release_Static|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Debug|Win32.ActiveCfg = Debug|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Debug|Win32.Build.0 = Debug|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Debug|x64.ActiveCfg = Debug|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_DLL|x64.ActiveCfg = Release_DLL|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_Static|Win32.Build.0 = Release_Static|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_Static|x64.ActiveCfg = Release_Static|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|Win32.ActiveCfg = Debug|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|Win32.Build.0 = Debug|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|x64.ActiveCfg = Debug|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|x64.Build.0 = Debug|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|x64.Build.0 = Release_DLL|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|Win32.Build.0 = Release_Static|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|x64.ActiveCfg = Release_Static|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|x64.Build.0 = Release_Static|x64 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Debug|Win32.ActiveCfg = Debug|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Debug|Win32.Build.0 = Debug|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Debug|x64.ActiveCfg = Debug|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_DLL|x64.ActiveCfg = Release_DLL|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_Static|Win32.Build.0 = Release_Static|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_Static|x64.ActiveCfg = Release_Static|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|Win32.ActiveCfg = Debug|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|Win32.Build.0 = Debug|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|x64.ActiveCfg = Debug|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|x64.Build.0 = Debug|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|x64.Build.0 = Release_DLL|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|Win32.Build.0 = Release_Static|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|x64.ActiveCfg = Release_Static|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|x64.Build.0 = Release_Static|x64 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Debug|Win32.ActiveCfg = Debug|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Debug|Win32.Build.0 = Debug|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Debug|x64.ActiveCfg = Debug|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_DLL|x64.ActiveCfg = Release_DLL|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_Static|Win32.Build.0 = Release_Static|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_Static|x64.ActiveCfg = Release_Static|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|Win32.ActiveCfg = Debug|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|Win32.Build.0 = Debug|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|x64.ActiveCfg = Debug|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|x64.Build.0 = Debug|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|x64.Build.0 = Release_DLL|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_Static|x64.ActiveCfg = Release_Static|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|Win32.ActiveCfg = Debug|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|Win32.Build.0 = Debug|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|x64.ActiveCfg = Debug|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|x64.Build.0 = Debug|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|x64.Build.0 = Release_DLL|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|Win32.Build.0 = Release_Static|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|x64.ActiveCfg = Release_Static|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|x64.Build.0 = Release_Static|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: DynamicAudioNormalizer_VS2015.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 14 VisualStudioVersion = 14.0.25420.1 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerCLI", "DynamicAudioNormalizerCLI\DynamicAudioNormalizerCLI_VS2015.vcxproj", "{5B755CC3-EC17-490F-AE82-CBC16E2EB143}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerAPI", "DynamicAudioNormalizerAPI\DynamicAudioNormalizerAPI_VS2015.vcxproj", "{376386EE-8268-47E3-A335-7663716E4C60}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerGUI", "DynamicAudioNormalizerGUI\DynamicAudioNormalizerGUI_VS2015.vcxproj", "{131C921A-7144-4C1D-9C97-57C43FA83DFE}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerVST", "DynamicAudioNormalizerVST\DynamicAudioNormalizerVST_VS2015.vcxproj", "{A30375E8-AEF7-4531-B372-02328E0B9D43}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerWA5", "DynamicAudioNormalizerWA5\DynamicAudioNormalizerWA5_VS2015.vcxproj", "{4C09B776-E4AC-4459-9CEA-086011A0BA14}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerNET", "DynamicAudioNormalizerNET\DynamicAudioNormalizerNET_VS2015.vcxproj", "{E1794071-AB51-45C7-B215-028F3DAA2219}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerPYD", "DynamicAudioNormalizerPYD\DynamicAudioNormalizerPYD_VS2015.vcxproj", "{5ACB9827-9D3A-4C59-A948-8505D1544A8E}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Release_DLL|Win32 = Release_DLL|Win32 Release_DLL|x64 = Release_DLL|x64 Release_Static|Win32 = Release_Static|Win32 Release_Static|x64 = Release_Static|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Debug|Win32.ActiveCfg = Debug|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Debug|Win32.Build.0 = Debug|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Debug|x64.ActiveCfg = Debug|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_DLL|x64.ActiveCfg = Release_DLL|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_Static|Win32.Build.0 = Release_Static|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_Static|x64.ActiveCfg = Release_Static|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|Win32.ActiveCfg = Debug|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|Win32.Build.0 = Debug|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|x64.ActiveCfg = Debug|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|x64.Build.0 = Debug|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|x64.Build.0 = Release_DLL|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|Win32.Build.0 = Release_Static|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|x64.ActiveCfg = Release_Static|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|x64.Build.0 = Release_Static|x64 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Debug|Win32.ActiveCfg = Debug|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Debug|Win32.Build.0 = Debug|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Debug|x64.ActiveCfg = Debug|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_DLL|x64.ActiveCfg = Release_DLL|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_Static|Win32.Build.0 = Release_Static|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_Static|x64.ActiveCfg = Release_Static|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|Win32.ActiveCfg = Debug|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|Win32.Build.0 = Debug|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|x64.ActiveCfg = Debug|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|x64.Build.0 = Debug|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|x64.Build.0 = Release_DLL|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|Win32.Build.0 = Release_Static|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|x64.ActiveCfg = Release_Static|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|x64.Build.0 = Release_Static|x64 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Debug|Win32.ActiveCfg = Debug|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Debug|Win32.Build.0 = Debug|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Debug|x64.ActiveCfg = Debug|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_DLL|x64.ActiveCfg = Release_DLL|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_Static|Win32.Build.0 = Release_Static|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_Static|x64.ActiveCfg = Release_Static|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|Win32.ActiveCfg = Debug|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|Win32.Build.0 = Debug|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|x64.ActiveCfg = Debug|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|x64.Build.0 = Debug|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|x64.Build.0 = Release_DLL|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_Static|x64.ActiveCfg = Release_Static|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|Win32.ActiveCfg = Debug|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|Win32.Build.0 = Debug|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|x64.ActiveCfg = Debug|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|x64.Build.0 = Debug|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|x64.Build.0 = Release_DLL|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|Win32.Build.0 = Release_Static|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|x64.ActiveCfg = Release_Static|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|x64.Build.0 = Release_Static|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: DynamicAudioNormalizer_VS2017.props ================================================ false $(XPDeprecationWarning) ================================================ FILE: DynamicAudioNormalizer_VS2017.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.26430.16 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerCLI", "DynamicAudioNormalizerCLI\DynamicAudioNormalizerCLI_VS2017.vcxproj", "{5B755CC3-EC17-490F-AE82-CBC16E2EB143}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerAPI", "DynamicAudioNormalizerAPI\DynamicAudioNormalizerAPI_VS2017.vcxproj", "{376386EE-8268-47E3-A335-7663716E4C60}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerGUI", "DynamicAudioNormalizerGUI\DynamicAudioNormalizerGUI_VS2017.vcxproj", "{131C921A-7144-4C1D-9C97-57C43FA83DFE}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerVST", "DynamicAudioNormalizerVST\DynamicAudioNormalizerVST_VS2017.vcxproj", "{A30375E8-AEF7-4531-B372-02328E0B9D43}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerWA5", "DynamicAudioNormalizerWA5\DynamicAudioNormalizerWA5_VS2017.vcxproj", "{4C09B776-E4AC-4459-9CEA-086011A0BA14}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerNET", "DynamicAudioNormalizerNET\DynamicAudioNormalizerNET_VS2017.vcxproj", "{E1794071-AB51-45C7-B215-028F3DAA2219}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "DynamicAudioNormalizerPYD", "DynamicAudioNormalizerPYD\DynamicAudioNormalizerPYD_VS2017.vcxproj", "{5ACB9827-9D3A-4C59-A948-8505D1544A8E}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Release_DLL|Win32 = Release_DLL|Win32 Release_DLL|x64 = Release_DLL|x64 Release_Static|Win32 = Release_Static|Win32 Release_Static|x64 = Release_Static|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Debug|Win32.ActiveCfg = Debug|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Debug|Win32.Build.0 = Debug|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Debug|x64.ActiveCfg = Debug|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_DLL|x64.ActiveCfg = Release_DLL|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_Static|Win32.Build.0 = Release_Static|Win32 {5B755CC3-EC17-490F-AE82-CBC16E2EB143}.Release_Static|x64.ActiveCfg = Release_Static|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|Win32.ActiveCfg = Debug|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|Win32.Build.0 = Debug|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|x64.ActiveCfg = Debug|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Debug|x64.Build.0 = Debug|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_DLL|x64.Build.0 = Release_DLL|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|Win32.Build.0 = Release_Static|Win32 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|x64.ActiveCfg = Release_Static|x64 {376386EE-8268-47E3-A335-7663716E4C60}.Release_Static|x64.Build.0 = Release_Static|x64 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Debug|Win32.ActiveCfg = Debug|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Debug|Win32.Build.0 = Debug|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Debug|x64.ActiveCfg = Debug|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_DLL|x64.ActiveCfg = Release_DLL|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_Static|Win32.Build.0 = Release_Static|Win32 {131C921A-7144-4C1D-9C97-57C43FA83DFE}.Release_Static|x64.ActiveCfg = Release_Static|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|Win32.ActiveCfg = Debug|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|Win32.Build.0 = Debug|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|x64.ActiveCfg = Debug|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Debug|x64.Build.0 = Debug|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_DLL|x64.Build.0 = Release_DLL|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|Win32.Build.0 = Release_Static|Win32 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|x64.ActiveCfg = Release_Static|x64 {A30375E8-AEF7-4531-B372-02328E0B9D43}.Release_Static|x64.Build.0 = Release_Static|x64 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Debug|Win32.ActiveCfg = Debug|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Debug|Win32.Build.0 = Debug|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Debug|x64.ActiveCfg = Debug|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_DLL|x64.ActiveCfg = Release_DLL|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_Static|Win32.Build.0 = Release_Static|Win32 {4C09B776-E4AC-4459-9CEA-086011A0BA14}.Release_Static|x64.ActiveCfg = Release_Static|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|Win32.ActiveCfg = Debug|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|Win32.Build.0 = Debug|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|x64.ActiveCfg = Debug|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Debug|x64.Build.0 = Debug|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_DLL|x64.Build.0 = Release_DLL|x64 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {E1794071-AB51-45C7-B215-028F3DAA2219}.Release_Static|x64.ActiveCfg = Release_Static|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|Win32.ActiveCfg = Debug|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|Win32.Build.0 = Debug|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|x64.ActiveCfg = Debug|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Debug|x64.Build.0 = Debug|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|Win32.ActiveCfg = Release_DLL|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|Win32.Build.0 = Release_DLL|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|x64.ActiveCfg = Release_DLL|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_DLL|x64.Build.0 = Release_DLL|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|Win32.ActiveCfg = Release_Static|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|Win32.Build.0 = Release_Static|Win32 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|x64.ActiveCfg = Release_Static|x64 {5ACB9827-9D3A-4C59-A948-8505D1544A8E}.Release_Static|x64.Build.0 = Release_Static|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ================================================ FILE: LICENSE-GPL2.html ================================================ GNU General Public License v2.0 - GNU Project - Free Software Foundation (FSF)

GNU GENERAL PUBLIC LICENSE

Version 2, June 1991

Copyright (C) 1989, 1991 Free Software Foundation, Inc.  
51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things.

To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software.

Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations.

Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all.

The precise terms and conditions for copying, distribution and modification follow.

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does.

1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program.

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.

2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:

a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License.
c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program.

In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.

3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following:

a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.

If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code.

4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it.

6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License.

7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.

8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.

9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation.

10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

NO WARRANTY

11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.

one line to give the program's name and an idea of what it does.
Copyright (C) yyyy  name of author

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this when it starts in an interactive mode:

Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
type `show w'.  This is free software, and you are welcome
to redistribute it under certain conditions; type `show c' 
for details.

The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names:

Yoyodyne, Inc., hereby disclaims all copyright
interest in the program `Gnomovision'
(which makes passes at compilers) written 
by James Hacker.

signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice

This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.

================================================ FILE: LICENSE-GPL3.html ================================================ GNU General Public License v3.0 - GNU Project - Free Software Foundation (FSF)

GNU GENERAL PUBLIC LICENSE

Version 3, 29 June 2007

Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

Preamble

The GNU General Public License is a free, copyleft license for software and other kinds of works.

The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.

When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.

To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.

For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.

Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.

For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.

Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.

Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.

The precise terms and conditions for copying, distribution and modification follow.

TERMS AND CONDITIONS

0. Definitions.

“This License” refers to version 3 of the GNU General Public License.

“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.

“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.

To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.

A “covered work” means either the unmodified Program or a work based on the Program.

To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.

To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.

An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.

1. Source Code.

The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.

A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.

The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.

The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.

The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.

The Corresponding Source for a work in source code form is that same work.

2. Basic Permissions.

All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.

You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.

Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.

3. Protecting Users' Legal Rights From Anti-Circumvention Law.

No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.

When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.

4. Conveying Verbatim Copies.

You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.

You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.

5. Conveying Modified Source Versions.

You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

  • a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
  • b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
  • c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
  • d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.

A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.

6. Conveying Non-Source Forms.

You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:

  • a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
  • b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
  • c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
  • d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
  • e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.

A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.

A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.

“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.

If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).

The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.

Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.

7. Additional Terms.

“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.

When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.

Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:

  • a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
  • b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
  • c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
  • d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
  • e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
  • f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.

All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.

If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.

Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.

8. Termination.

You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).

However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.

Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.

Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.

9. Acceptance Not Required for Having Copies.

You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.

10. Automatic Licensing of Downstream Recipients.

Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.

An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.

You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.

11. Patents.

A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.

A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.

Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.

In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.

If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.

If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.

A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.

Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.

12. No Surrender of Others' Freedom.

If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.

13. Use with the GNU Affero General Public License.

Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.

14. Revised Versions of this License.

The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.

If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.

Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.

15. Disclaimer of Warranty.

THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

16. Limitation of Liability.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

17. Interpretation of Sections 15 and 16.

If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Programs

If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.

To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License 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/>.

Also add information on how to contact you by electronic and paper mail.

If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.

You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.

The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

================================================ FILE: LICENSE-LGPL.html ================================================ GNU Lesser General Public License v2.1 - GNU Project - Free Software Foundation (FSF)

GNU LESSER GENERAL PUBLIC LICENSE

Version 2.1, February 1999

Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.

[This is the first released version of the Lesser GPL.  It also counts
 as the successor of the GNU Library Public License, version 2, hence
 the version number 2.1.]

Preamble

The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users.

This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below.

When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things.

To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it.

For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights.

We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library.

To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others.

Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license.

Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs.

When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library.

We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances.

For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License.

In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system.

Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library.

The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run.

TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you".

A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables.

The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".)

"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library.

Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does.

1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library.

You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee.

2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions:

  • a) The modified work must itself be a software library.
  • b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change.
  • c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License.
  • d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful.

    (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.)

These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library.

In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License.

3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices.

Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy.

This option is useful when you wish to copy part of the code of the Library into a program that is not a library.

4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange.

If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code.

5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License.

However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables.

When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law.

If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.)

Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself.

6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications.

You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things:

  • a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.)
  • b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with.
  • c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution.
  • d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place.
  • e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy.

For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable.

It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute.

7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things:

  • a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above.
  • b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.

8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.

9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it.

10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License.

11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library.

If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances.

It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice.

This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License.

12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License.

13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation.

14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally.

NO WARRANTY

15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

END OF TERMS AND CONDITIONS

How to Apply These Terms to Your New Libraries

If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License).

To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.

one line to give the library's name and an idea of what it does.
Copyright (C) year  name of author

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library 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
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Also add information on how to contact you by electronic and paper mail.

You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names:

Yoyodyne, Inc., hereby disclaims all copyright interest in
the library `Frob' (a library for tweaking knobs) written
by James Random Hacker.

signature of Ty Coon, 1 April 1990
Ty Coon, President of Vice

That's all there is to it!

================================================ FILE: Makefile ================================================ ############################################################################## # Dynamic Audio Normalizer # Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version, but always including the *additional* # restrictions defined in the "License.txt" file. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # http://www.gnu.org/licenses/gpl-2.0.txt ############################################################################## ECHO=echo -e SHELL=/bin/bash MODE ?= full PANDOC ?= pandoc ############################################################################## # Constants ############################################################################## LIBRARY_NAME := DynamicAudioNormalizerAPI PROGRAM_NAME := DynamicAudioNormalizerCLI LOGVIEW_NAME := DynamicAudioNormalizerGUI JNIWRAP_NAME := DynamicAudioNormalizerJNI PYDWRAP_NAME := DynamicAudioNormalizerPYD PASWRAP_NAME := DynamicAudioNormalizerPAS BUILD_DATE := $(shell date +%Y-%m-%d) BUILD_TIME := $(shell date +%H:%M:%S) BUILD_TAG := $(addprefix /tmp/,$(shell echo $$RANDOM$$RANDOM$$RANDOM)) TARGET_PATH := ./bin/$(BUILD_DATE) OUTPUT_FILE := $(abspath ./bin/DynamicAudioNormalizer.$(BUILD_DATE).tbz2) PANDOC_FLAGS := markdown_github+pandoc_title_block+header_attributes+implicit_figures JARS_PATH := tmp/jars # Version info VER_MAJOR = $(shell sed -n 's/.*DYNAUDNORM_NS::VERSION_MAJOR\s*=\s*\([0-9]*\).*/\1/p' < ./DynamicAudioNormalizerAPI/src/Version.cpp) VER_MINOR = $(shell sed -n 's/.*DYNAUDNORM_NS::VERSION_MINOR\s*=\s*\([0-9]*\).*/\1/p' < ./DynamicAudioNormalizerAPI/src/Version.cpp) VER_PATCH = $(shell sed -n 's/.*DYNAUDNORM_NS::VERSION_PATCH\s*=\s*\([0-9]*\).*/\1/p' < ./DynamicAudioNormalizerAPI/src/Version.cpp) # API Version export API_VERSION := $(shell sed -n 's/.*define MDYNAMICAUDIONORMALIZER_CORE \([0-9]*\).*/\1/p' < ./DynamicAudioNormalizerAPI/include/DynamicAudioNormalizer.h) ############################################################################## # Projects ############################################################################## MY_PROJECTS := NONE ifeq ($(MODE),full) MY_PROJECTS := API CLI GUI JNI PYD export ENABLE_JNI := true endif ifeq ($(MODE),no-gui) MY_PROJECTS := API CLI JNI PYD export ENABLE_JNI := true endif ifeq ($(MODE),minimal) MY_PROJECTS := API CLI export ENABLE_JNI := false endif ifeq ($(MY_PROJECTS),NONE) $(error Invalid MODE value: $(MODE)) endif ############################################################################## # Rules ############################################################################## BUILD_PROJECTS = $(addprefix DynamicAudioNormalizer,$(MY_PROJECTS)) CLEAN_PROJECTS = $(addprefix CleanUp,$(BUILD_PROJECTS)) .PHONY: all clean $(BUILD_PROJECTS) $(CLEAN_PROJECTS) DeployBinaries CopyAllBinaries CreateDocuments CreateTagFile all: $(BUILD_PROJECTS) DeployBinaries @$(ECHO) "\n\e[1;32mComplete.\e[0m\n" clean: $(CLEAN_PROJECTS) CleanBinaries @$(ECHO) "\n\e[1;32mComplete.\e[0m\n" #------------------------------------------------------------- # Clean #------------------------------------------------------------- $(CLEAN_PROJECTS): @$(ECHO) "\n\e[1;31m-----------------------------------------------------------------------------\e[0m" @$(ECHO) "\e[1;31mClean: $(patsubst Clean%,%,$@)\e[0m" @$(ECHO) "\e[1;31m-----------------------------------------------------------------------------\n\e[0m" make -C ./$(patsubst CleanUp%,%,$@) clean CleanBinaries: @$(ECHO) "\n\e[1;31m-----------------------------------------------------------------------------\e[0m" @$(ECHO) "\e[1;31mClean\e[0m" @$(ECHO) "\e[1;31m-----------------------------------------------------------------------------\n\e[0m" rm -rfv ./bin #------------------------------------------------------------- # Build #------------------------------------------------------------- $(BUILD_PROJECTS): @$(ECHO) "\n\e[1;34m-----------------------------------------------------------------------------\e[0m" @$(ECHO) "\e[1;34mBuild: $@\e[0m" @$(ECHO) "\e[1;34m-----------------------------------------------------------------------------\n\e[0m" make -C ./$@ #------------------------------------------------------------- # Deploy #------------------------------------------------------------- DeployBinaries: CopyAllBinaries CreateDocuments CreateTagFile @$(ECHO) "\n\e[1;34m-----------------------------------------------------------------------------\e[0m" @$(ECHO) "\e[1;34mDeploy\e[0m" @$(ECHO) "\e[1;34m-----------------------------------------------------------------------------\n\e[0m" rm -f $(OUTPUT_FILE) pushd $(TARGET_PATH) ; tar -vcjf $(OUTPUT_FILE) * ; popd CreateTagFile: @$(ECHO) "\n\e[1;34m-----------------------------------------------------------------------------\e[0m" @$(ECHO) "\e[1;34mBuild Tag\e[0m" @$(ECHO) "\e[1;34m-----------------------------------------------------------------------------\n\e[0m" echo "Dynamic Audio Normalizer" > $(BUILD_TAG) echo "Copyright (C) 2014-$(shell date +%Y) LoRd_MuldeR . Some rights reserved." >> $(BUILD_TAG) echo "" >> $(BUILD_TAG) echo "Version $$(printf %d.%02d-%d $(VER_MAJOR) $(VER_MINOR) $(VER_PATCH)). Built on $(BUILD_DATE), at $(BUILD_TIME)" >> $(BUILD_TAG) echo "" >> $(BUILD_TAG) g++ --version | head -n1 | sed 's/^/Compiler version: /' >> $(BUILD_TAG) ifeq ($(shell uname), Darwin) uname -v | sed 's/^/Build platform: /' >> $(BUILD_TAG) echo "System description: Darwin" >> $(BUILD_TAG) else uname -srmo | sed 's/^/Build platform: /' >> $(BUILD_TAG) (lsb_release -s -d || ([ -n "$$MSYSTEM" ] && echo "$$MSYSTEM") || echo "Unknown") | sed 's/\"//g' | sed 's/^/System description: /' >> $(BUILD_TAG) endif echo "" >> $(BUILD_TAG) echo "This library is free software; you can redistribute it and/or" >> $(BUILD_TAG) echo "modify it under the terms of the GNU Lesser General Public" >> $(BUILD_TAG) echo "License as published by the Free Software Foundation; either" >> $(BUILD_TAG) echo "version 2.1 of the License, or (at your option) any later version." >> $(BUILD_TAG) echo "" >> $(BUILD_TAG) echo "This library is distributed in the hope that it will be useful," >> $(BUILD_TAG) echo "but WITHOUT ANY WARRANTY; without even the implied warranty of" >> $(BUILD_TAG) echo "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU" >> $(BUILD_TAG) echo "Lesser General Public License for more details." >> $(BUILD_TAG) mkdir -p $(TARGET_PATH) mv -f $(BUILD_TAG) $(TARGET_PATH)/BUILD_TAG CopyAllBinaries: @$(ECHO) "\n\e[1;34m-----------------------------------------------------------------------------\e[0m" @$(ECHO) "\e[1;34mCopy Binaries\e[0m" @$(ECHO) "\e[1;34m-----------------------------------------------------------------------------\n\e[0m" rm -rf $(TARGET_PATH) mkdir -p $(TARGET_PATH)/include mkdir -p $(TARGET_PATH)/samples/java mkdir -p $(TARGET_PATH)/samples/python mkdir -p $(TARGET_PATH)/samples/pascal cp $(PROGRAM_NAME)/bin/$(PROGRAM_NAME).* $(TARGET_PATH) cp $(LIBRARY_NAME)/lib/lib$(LIBRARY_NAME)-$(API_VERSION).* $(TARGET_PATH) cp $(LOGVIEW_NAME)/bin/$(LOGVIEW_NAME).* $(TARGET_PATH) || $(ECHO) "\e[1;33mWARNING: File \"$(LOGVIEW_NAME)\" not found!\e[0m" cp $(JNIWRAP_NAME)/out/$(JNIWRAP_NAME).jar $(TARGET_PATH) || $(ECHO) "\e[1;33mWARNING: File \"$(JNIWRAP_NAME).jar\" not found!\e[0m" cp $(PYDWRAP_NAME)/lib/$(PYDWRAP_NAME).so $(TARGET_PATH) || $(ECHO) "\e[1;33mWARNING: File \"$(PYDWRAP_NAME).so\" not found!\e[0m" cp $(LIBRARY_NAME)/include/*.h $(TARGET_PATH)/include cp $(PYDWRAP_NAME)/include/*.py $(TARGET_PATH)/include cp $(PASWRAP_NAME)/include/*.pas $(TARGET_PATH)/include cp $(JNIWRAP_NAME)/samples/com/muldersoft/dynaudnorm/samples/*.java $(TARGET_PATH)/samples/java cp $(PYDWRAP_NAME)/samples/*.py $(TARGET_PATH)/samples/python cp $(PASWRAP_NAME)/src/*.pas $(TARGET_PATH)/samples/pascal cp $(PASWRAP_NAME)/src/*.dfm $(TARGET_PATH)/samples/pascal cp ./LICENSE-*.html $(TARGET_PATH) CreateDocuments: @$(ECHO) "\n\e[1;34m-----------------------------------------------------------------------------\e[0m" @$(ECHO) "\e[1;34mCreate Documents\e[0m" @$(ECHO) "\e[1;34m-----------------------------------------------------------------------------\n\e[0m" wget -N -P $(JARS_PATH) https://repo1.maven.org/maven2/com/yahoo/platform/yui/yuicompressor/2.4.8/yuicompressor-2.4.8.jar wget -N -P $(JARS_PATH) https://repo1.maven.org/maven2/com/googlecode/htmlcompressor/htmlcompressor/1.5.2/htmlcompressor-1.5.2.jar mkdir -p $(TARGET_PATH)/img/dyauno $(PANDOC) --from $(PANDOC_FLAGS) --to html5 --toc -N --standalone -H ./img/dyauno/Style.inc ./README.md | java -jar $(JARS_PATH)/htmlcompressor-1.5.2.jar --compress-css -o $(TARGET_PATH)/README.html test -s $(TARGET_PATH)/README.html || (rm -f $(TARGET_PATH)/README.html; cp ./README.md $(TARGET_PATH)/README.md) cp ./img/dyauno/*.png $(TARGET_PATH)/img/dyauno ================================================ FILE: README.md ================================================ % ![](img/dyauno/DynAudNorm.png) Dynamic Audio Normalizer % by LoRd_MuldeR <> | # Introduction # **★ *Free/libre software · This software is provided 100% free of charge · No adware or spyware!* ★** **Dynamic Audio Normalizer** is a library for *advanced* [audio normalization](http://en.wikipedia.org/wiki/Audio_normalization) purposes. It applies a certain amount of gain to the input audio in order to bring its peak magnitude to a target level (e.g. 0 dBFS). However, in contrast to more "simple" normalization algorithms, the Dynamic Audio Normalizer *dynamically* re-adjusts the gain factor to the input audio. This allows for applying extra gain to the "quiet" sections of the audio while avoiding distortions or clipping the "loud" sections. In other words: The Dynamic Audio Normalizer will "even out" the volume of quiet and loud sections, in the sense that the volume of each section is brought to the same target level. Note, however, that the Dynamic Audio Normalizer achieves this goal *without* applying "dynamic range compressing". It will retain 100% of the dynamic range *within* each "local" region of the audio file. The *Dynamic Audio Normalizer* is available as a small standalone [command-line](http://en.wikipedia.org/wiki/Command-line_interface) utility and also as an effect in the [SoX](http://sox.sourceforge.net/) audio processor as well as in the [FFmpeg](https://ffmpeg.org/) audio/video converter. Furthermore, it can be integrated into your favourite DAW (digital audio workstation), as a [VST](http://de.wikipedia.org/wiki/Virtual_Studio_Technology) plug-in, or into your favourite media player, as a [Winamp](http://www.winamp.com/) plug-in. Last but not least, the "core" library can be integrated into custom applications easily, thanks to a straightforward [API](http://en.wikipedia.org/wiki/Application_programming_interface) (application programming interface). The "native" API is written in *C++*, but language [bindings](http://en.wikipedia.org/wiki/Language_binding) for *C99*, *Microsoft.NET*, *Java*, *Python* and *Pascal* are provided. # How It Works # A "standard" (non-dynamic) audio normalization algorithm applies the same *constant* amount of gain to *all* samples in the file. Consequently, the gain factor must be chosen in a way that won't cause clipping (distortion), even for the input sample that has the highest magnitude. So if `S_max` denotes the highest magnitude sample in the *whole* input audio and ``Peak`` is the desired peak magnitude, then the gain factor will be chosen as `G=Peak/abs(S_max)`. This works fine, as long as the volume of the input audio is constant, more or less. If, however, the volume of the input audio varies significantly over time – as is the case with many "real world" recordings – the standard normalization algorithm will *not* give satisfying result. That's because the "loud" parts can *not* be amplified any further (without distortions) and thus the "quiet" parts will remain quiet too. **Dynamic Audio Normalizer** solves this problem by processing the input audio in small chunks, referred to as *frames*. A frame typically has a length 500 milliseconds, but the frame size can be adjusted as needed. The Dynamic Audio Normalizer then finds the highest magnitude sample *within* each frame, individually and independently. Next, it computes the maximum possible gain factor (without distortions) for each individual frame. So, if ``S_max[n]`` denotes the highest magnitude sample within the *n*-th frame, then the maximum possible gain factor for the *n*-th frame will be `G[n]=Peak/abs(S_max[n])`. Unfortunately, simply amplifying each frame with its own "local" maximum gain factor `G[n]` would **not** produce a satisfying overall result either. That's because the maximum gain factors can vary *strongly* and *unsteadily* between neighboring frames! Therefore, applying the maximum possible gain to each frame *without* taking neighboring frames into account would result in a strong *dynamic range compression* – which not only has a tendency to destroy the "vividness" of the audio but could also result in the "pumping" effect, i.e fast changes of the gain factor that become clearly noticeable to the listener. ## Dynamic Normalization Algorithm ## The Dynamic Audio Normalizer tries to avoid these issues by applying an advanced *dynamic* normalization algorithm. Essentially, when processing a particular frame, it also takes into account a certain *neighborhood* around the current frame, i.e. the frames *preceding* and *succeeding* the current frame will be considered as well. However, while information about "past" frames can simply be stored as long as they are needed, information about "future" frames are *not* normally available. A simple approach to solve this issue would be using a *2-Pass* algorithm, but this would require processing the entire audio file *twice* – which also makes stream processing impossible. The Dynamic Audio Normalizer uses a different approach instead: It employs a tall "look ahead" buffer. This means that that all audio frames will progress trough an internal [*FIFO*](http://en.wikipedia.org/wiki/FIFO) (first in, first out) buffer. The size of this buffer is chosen sufficiently large, so that a frame's *complete* neighborhood, including the *subsequent* frames, will already be present in the buffer when *that* particular frame is being processed. The "look ahead" buffer eliminates the need for 2-Pass processing and thus gives an improved performance. It also makes stream processing possible. With information about the frame's neighborhood available, a [*Gaussian* smoothing kernel](http://en.wikipedia.org/wiki/Gaussian_blur) can be applied on those gain factors. Put simply, this smoothing filter "mixes" the gain factor of the ``n``-th frames with those of its *preceding* frames (`n-1`, `n-2`, …) as well as with its *subsequent* frames (`n+1`, `n+2`, …) – where "nearby" frames have a stronger influence (weight), while "distant" frames have a declining influence. This way, abrupt changes of the gain factor are avoided and, instead, we get *smooth transitions* of the gain factor over time. Furthermore, since the filter also takes into account *future* frames, Dynamic Audio Normalizer avoids applying strong gain to "quiet" frames located shortly before "loud" frames. In other words, Dynamic Audio Normalizer adjusts the gain factor *early* and thus nicely prevents distortions or abrupt gain changes. One more challenge to consider is that applying the Gaussian smoothing kernel alone can *not* solve all problems. That's because the smoothing kernel will *not* only smoothen *increasing* gain factors but also *declining* ones! If, for example, a very "loud" frame follows immediately after a sequence of "quiet" frames, the smoothing causes the gain factor to decrease early but slowly. As a result, the *filtered* gain factor of the "loud" frame could actually turn out to be *higher* than its (local) maximum gain factor – which results in distortion, if not taken care of! For this reason, the Dynamic Audio Normalizer *additionally* applies a "minimum" filter, i.e. a filter that replaces each gain factor with the *smallest* value within the neighborhood. This is done *before* the Gaussian smoothing kernel in order to ensure that all gain transitions will remain smooth. The following example shows the results from a "real world" audio recording that has been processed by the Dynamic Audio Normalizer algorithm. The chart shows the maximum local gain factors for each individual frame (blue) as well as the minimum filtered gain factors (green) and the *final* smoothened gain factors (orange). Note the very "smooth" progression of the final gain factors. At the same time, the maximum local gain factors are approached as closely as possible. Last but not least note that the smoothened gain factors *never* exceed the maximum local gain factor, which prevents distortions. ![Progression of the gain factors for each audio frame](img/dyauno/Chart.png) ## Intra-Frame Normalization ## So far it has been discussed how the "optimal" gain factor for each frame is determined. However, since each frame contains a large number of samples – at a typical sampling rate of 44,100 Hz and a standard frame size of 500 milliseconds we have 22,050 samples per frame – it is also required to infer the gain factor for each individual sample *within* the frame. The most simple approach, of course, would be applying the *same* gain factor to *all* samples in a certain frame. But this would also lead to abrupt changes of the gain factor at each frame boundary, while the gain factor remains completely constant within the frames. A better approach, as implemented in the Dynamic Audio Normalizer, is *interpolating* the per-sample gain factors. In particular, the Dynamic Audio Normalizer applies a straight-forward *linear interpolation*, which is used to compute the gain factors for the samples of the `n`-th frame from the gain factors `G'[n-1]`, `G'[n]` and `G'[n+1]` – where `G'[k]` denotes the gain factor of the `k`-th frame. The following graph shows how the per-sample gain factors (orange) are interpolated from the gain factors of the *preceding* (`G'[n-1]`, green), *current* (`G'[n]`, blue) and *subsequent* (`G'[n+1]`, purple) frame. ![Linear interpolation of the per-sample gain factors](img/dyauno/Interpolation.png) ## Real World Results (Example) ## Finally, the following waveform view illustrates how the volume of a "real world" audio recording has been harmonized by the Dynamic Audio Normalizer. The upper graph shows the unprocessed original recording while the lower graph shows the output as created by the Dynamic Audio Normalizer. As can be seen, the significant volume variation between the "loud" and the "quiet" parts that existed in the original recording has been rectified – to a great extent – while the dynamics within each section of the input have been retained. Also, there is absolutely **no** clipping or distortion in the "loud" sections. ![Waveform *before* (top) and *after* (bottom) processing with the Dynamic Audio Normalizer](img/dyauno/Waveform.png) # Download & Installation # Dynamic Audio Normalizer can be downloaded from one of the following *official* mirror sites: * https://github.com/lordmulder/DynamicAudioNormalizer/releases/latest * https://bitbucket.org/muldersoft/dynamic-audio-normalizer/downloads * https://sourceforge.net/projects/muldersoft/files/Dynamic%20Audio%20Normalizer/ * https://www.mediafire.com/folder/flrb14nitnh8i/Dynamic_Audio_Normalizer * https://www.assembla.com/spaces/dynamicaudionormalizer/documents **Note:** Windows binaries are provided in the compressed *ZIP* format. Simply use [7-Zip](http://www.7-zip.org/) or a similar tool to unzip *all* files to new/empty directory. If in doubt, Windows users should download the "static" version. That's it! ## System Requirements ## The Dynamic Audio Normalizer "core" library and CLI front-end are written in plain C++11 and therefore do **not** have any system requirements, except for a conforming C++ compiler. Currently, the Microsoft Visual C++ compiler and the GNU Compiler Collection (GCC) are actively supported. Other compilers should work too, but this cannot be guaranteed. *Pre-compiled* binaries are provided for the *Windows* and *GNU/Linux* platforms. The 32-Bit Windows binaries should work on Windows XP (with Service Pack 2) or any later version (32-Bit or 64-Bit), while the 64-Bit Windows binaries require the "x64" edition of Windows Vista or any later 64-Bit Windows. Linux binaries are provided for some popular distributions (latest "Long Term Support" version at the time of release). Those Linux binaries *may* work on other distributions too, or not. Therefore, Linux users are generally recommended to compile the Dynamic Audio Normalizer themselves, from the source codes. All *pre-compiled* binaries have been optimized for processors that support *at least* the [*SSE2*](https://en.wikipedia.org/wiki/SSE2) instruction set, so an SSE2-enabled processor (Pentium 4, Athlon 64, or later) is required. For *legacy* processors you will need to compile Dynamic Audio Normalizer and all the third-party libraries *yourself*, from the sources – with appropriate compiler settings. ## Dependencies The Dynamic Audio Normalizer depends on some *third-party* libraries. Those libraries need to be present at runtime! How to obtain the required *third-party* libraries, if not already installed, depends on the operating system. ### Windows For the *Windows* platform, the release packages already contain *all* required third-party libraries. We provide separate **Static** and **DLL** packages though. The "Static" binaries have all the required libraries *built-in* (including third-party libraries and C-Runtime) and thus they do *not* depend on any separate DLL files. At the same time, the "DLL" package contains separate DLL files for the Dynamic Audio Normalizer "core" library as well as for the required third-party libraries and the C-Runtime. If you don't understand what this means, then simply go with the "Static" version. If you are a programmer and you want to invoke the Dynamic Audio Normalizer "core" library from your own program, then you need to go with the "DLL" version. ### Linux For the *Linux* platform, the release packages do ***not*** contain any third-party libraries. That's because, on Linux, it is highly recommended to install those libraries via the *package manager*. Usually, most of the required third-party libraries will already be installed on your Linux-based system, but some may need to be installed explicitly. The details depend on the particular Linux distribution and on the particular package manager. We give examples for [*Ubuntu*](https://www.ubuntu.com/), [*openSUSE*](https://www.opensuse.org/) and [*CentOS*](https://www.centos.org/) here: * **Ubuntu 16.04 LTS**: ``` sudo apt install libsndfile1 libmpg123-0 libqtgui4 ``` * **openSUSE Leap 42.2**: ``` sudo zypper addrepo \ http://download.opensuse.org/repositories/multimedia:libs/openSUSE_Leap_42.2/multimedia:libs.repo sudo zypper refresh sudo zypper install libsndfile1 libmpg123-0 libqt4-x11 ``` * **CentOS/RHEL 7.3**: ``` sudo yum -y install epel-release sudo rpm -Uvh http://li.nux.ro/download/nux/dextop/el7/x86_64/nux-dextop-release-0-5.el7.nux.noarch.rpm sudo yum install libsndfile libmpg123 qt-x11 ``` **Note:** There are some additional *indirect* dependencies that will be resolved automatically by the package manager. ### Mac OS X There is preliminary support for building on Mac OS X: ``` brew cask install java brew install python3 brew install libsndfile mpg123 brew install ant pandoc wget export JAVA_HOME=$(/usr/libexec/java_home) make MODE=no-gui ``` ## Package Contents ## The following files are included in the Dynamic Audio Normalizer release package (Windows, "DLL" version): api-ms-win-* - Microsoft Universal CRT redistributable DynamicAudioNormalizer.h - Header file for the Dynamic Audio Normalizer library DynamicAudioNormalizer.pas - Pascal wrapper for the Dynamic Audio Normalizer library DynamicAudioNormalizerAPI.dll - Dynamic Audio Normalizer core library (shared) DynamicAudioNormalizerAPI.lib - Import library for the Dynamic Audio Normalizer library DynamicAudioNormalizerCLI.exe - Dynamic Audio Normalizer command-line application DynamicAudioNormalizerGUI.exe - Dynamic Audio Normalizer log viewer application DynamicAudioNormalizerJNI.jar - Java wrapper for the Dynamic Audio Normalizer library DynamicAudioNormalizerNET.dll - .NET wrapper for the Dynamic Audio Normalizer library DynamicAudioNormalizerSoX.exe - SoX binary with included Dynamic Audio Normalizer effect DynamicAudioNormalizerVST.dll - Dynamic Audio Normalizer VST wrapper library libmpg123.dll - libmpg123 library, used for reading MPEG audio files libsndfile-1.dll - libsndfile library, used for reading/writing audio files msvcp140.dll - Visual C++ 2015 runtime library redistributable pthreadVC2.dll - POSIX threading library, used for thread management QtCore4.dll - Qt library, used to create the graphical user interfaces QtGui4.dll - Qt library, used to create the graphical user interfaces README.html - The README file ucrtbase.dll - Microsoft Universal CRT redistributable vcruntime140.dll - Visual C++ 2015 runtime library redistributable **Note:** Standard binaries are *32-Bit* (x86), though *64-Bit* (AMD64/EM64T) versions can be found in the `x64` sub-folder. # Command-Line Usage # The Dynamic Audio Normalizer *standalone* program can be invoked via [command-line interface](http://en.wikipedia.org/wiki/Command-line_interface) (CLI), which can be done either *manually* from the [command prompt](http://en.wikipedia.org/wiki/Command_Prompt) or *automatically* (scripted), e.g. by using a [batch](http://en.wikipedia.org/wiki/Batch_file) file. ## Basic Command-Line Syntax ## The basic Dynamic Audio Normalizer command-line syntax is as follows: ``` DynamicAudioNormalizerCLI.exe -i <;input_file> -o [options] ``` Note that the *input* file (option `-i` or `--input`) and the *output* file (option `-o` or `--output`) always have to be specified, while all other parameters are optional. But take care, an existing output file will be *overwritten* silently! Also note that the Dynamic Audio Normalizer uses [libsndfile](http://www.mega-nerd.com/libsndfile/) for input/output, so a wide range of file formats (WAV, W64, FLAC, Ogg/Vorbis, AIFF, AU/SND, etc) as well as various sample types (ranging from 8-Bit INT to 64-Bit FP) are supported. However, *libsndfile* can **not** read MP2 (MPEG Audio Layer II) or MP3 (MPEG Audio Layer III) files, so [libmpg123](https://www.mpg123.de/) will be used for reading files that "look" like MP2 or MP3 data. You can specify `-d` option to select the desired decoder library explicitly. By default, the Dynamic Audio Normalizer program will *guess* the output file format from the file extension of the specified output file. This can be overwritten by using the `-t` option. To create a FLAC file, e.g., you can specify `-t flac`. Passing "raw" PCM data via [pipe](http://en.wikipedia.org/wiki/Pipeline_%28Unix%29) is supported. Specify the file name ``"-"`` in order to read from or write to the [stdin](http://en.wikipedia.org/wiki/Standard_streams) or [stdout](http://en.wikipedia.org/wiki/Standard_streams), respectively. When reading from the *stdin*, you have to specify the *input* sample format, channel count and sampling rate! For a list of *all* available options, see the [list below](#command-line-options) or run ``DynamicAudioNormalizerCLI.exe --help`` from the command prompt. Also, refer to the [**configuration**](#configuration) chapter for more details on the Dynamic Audio Normalizer parameters! ## Command-Line Options The following Dynamic Audio Normalizer command-line options are available: * **Input/Output:** ``` -i --input Input audio file [required] -d --input-lib Input decoder library [default: auto-detect] -o --output Output audio file [required] -t --output-fmt Output format [default: auto-detect] -u --output-bps Output bits per sample [default: like input] ``` * **Algorithm Tweaks:** ``` -f --frame-len Frame length, in milliseconds [default: 500] -g --gauss-size Gauss filter size, in frames [default: 31] -p --peak Target peak magnitude, 0.1-1 [default: 0.95] -m --max-gain Maximum gain factor [default: 10.00] -r --target-rms Target RMS value [default: 0.00] -n --no-coupling Disable channel coupling [default: on] -c --correct-dc Enable the DC bias correction [default: off] -b --alt-boundary Use alternative boundary mode [default: off] -s --compress Compress the input data [default: 0.00] ``` * **Diagnostics:** ``` -v --verbose Output additional diagnostic info -l --log-file Create a log file -h --help Print *this* help screen ``` * **Raw Data Options:** ``` --input-bits Bits per sample, e.g. '16' or '32' --input-chan Number of channels, e.g. '2' for Stereo --input-rate Sample rate in Hertz, e.g. '44100' ``` ## Command-Line Usage Examples ## Here are some examples on how to invoke the Dynamic Audio Normalizer command-line program: * Read input from Wave file and write output to a Wave file again: ``` DynamicAudioNormalizerCLI.exe -i "in_original.wav" -o "out_normalized.wav" ``` * Read input from *stdin* (input is provided by [FFmpeg](http://ffmpeg.org/about.html) via pipe) and write output to Wave file: ``` ffmpeg.exe -i "movie.mkv" -loglevel quiet -vn -f s16le -c:a pcm_s16le - | DynamicAudioNormalizerCLI.exe -i - --input-bits 16 --input-chan 2 --input-rate 48000 -o "output.wav" ``` * Read input from Wave file and write output to *stdout* (output is passed to [FFmpeg](http://ffmpeg.org/about.html) via pipe): ``` DynamicAudioNormalizerCLI.exe -i "input.wav" -o - | ffmpeg.exe -loglevel quiet -f s16le -ar 44100 -ac 2 -i - -c:a libmp3lame -qscale:a 2 "output.mp3" ``` # SoX/FFmpeg Usage The Dynamic Audio Normalizer library is *integrated* in the **SoX** and **FFmpeg** command-line applications! ## SoX Integration Usage ## As an alternative to the Dynamic Audio Normalizer command-line front-end, the Dynamic Audio Normalizer library may also be used as an effect in [**SoX** (Sound eXchange)](http://sox.sourceforge.net/), a versatile audio editor and converter. Note, however, that *standard* SoX distributions do **not** currently support the Dynamic Audio Normalizer. Instead, a special *patched* build of SoX that has the Dynamic Audio Normalizer effect enabled is required! When using SoX, the Dynamic Audio Normalizer can be invoked by adding the "dynaudnorm" effect to your chain: ``` DynamicAudioNormalizerSoX.exe -S "in_original.wav" -o "out_normalized.wav" dynaudnorm [options] ``` For details about the SoX command-line syntax, please refer to the offical [SoX documentation](http://sox.sourceforge.net/sox.html), or simply type ``--help-effect dynaudnorm`` in order to make SoX print a list of available options. ## FFmpeg Integration Usage ## Furthermore, the Dynamic Audio Normalizer is available as an audio filter in [**FFmpeg**](https://www.ffmpeg.org/), a complete, cross-platform solution to record, convert and stream audio and video. Thanks to *Paul B Mahol* for porting Dynamic Audio Normalizer to FFmpeg. Since the Dynamic Audio Normalizer has been committed to the official FFmpeg codebase, you can use *any* FFmpeg binary. Just be sure to grab an *up-to-date* FFmpeg that has the "dynaudnorm" filter integrated. Windows users can download ready-made FFmpeg binaries [here](http://ffmpeg.zeranoe.com/builds/). Linux users install FFmpeg from the package manager of their distribution or [build](https://trac.ffmpeg.org/wiki/CompilationGuide/Ubuntu) it themselves. If the FFmpeg included with your distribution is too old, find recent Linux binaries [here](http://johnvansickle.com/ffmpeg/). When using FFmpeg, the Dynamic Audio Normalizer can be invoked by adding the "dynaudnorm" filter via `-af` switch: ``` ffmpeg.exe -i "in_original.wav" -af dynaudnorm "out_normalized.wav" ``` For details about the FFmpeg command-line syntax, please refer to the [FFmpeg documentation](https://ffmpeg.org/ffmpeg-filters.html#dynaudnorm), see the [FFmpeg filtering guide](https://trac.ffmpeg.org/wiki/FilteringGuide), or type ``ffmpeg.exe -h full | more`` for a list of available options. # VST Plug-In Usage # **VST PlugIn Interface Technology by Steinberg Media Technologies GmbH. VST is a trademark of Steinberg Media Technologies GmbH.** ![VSTLogo](img/dyauno/VSTLogo.png "VST Logo") The Dynamic Audio Normalizer is also available in the form of a [**VST** (Virtual Studio Technology) plug-in](http://en.wikipedia.org/wiki/Virtual_Studio_Technology). The VST plug-in interface technology, developed by Steinberg Media Technologies, provides a way of integrating arbitrary audio effects (and instruments) into arbitrary applications – provided that the audio effect is available in the form of a VST plug-in and provided that the application supports "hosting" VST plug-ins. An application capable of loading and using VST plug-ins is referred to as a *VST host*. This means that the Dynamic Audio Normalizer can be used as an effect in *any* VST host. Note that VST is widely supported in [DAWs (Digital Audio Workstations)](http://en.wikipedia.org/wiki/Digital_audio_workstation) nowadays, including most of the popular Wave Editors. Therefore, the provided Dynamic Audio Normalizer VST plug-in can be integrated into all of these applications easily. Note that most VST hosts provide a graphical user interface to configure the VST plug-in. The screen capture below shows the Dynamic Audio Normalizer as it appears in the *Acoustica* software by Acon AS. The options exposed by the VST plug-in are identical to those exposed by the [CLI](#command-line-usage) version. ![The Dynamic Audio Normalizer *VST Plug-In* interface (in Acoustica 6.0, Copyright © 2014 Acon AS)](img/dyauno/VSTPlugInConf.png) ## Install Instructions ## The exact steps that are required to load, activate and configure a VST plug-in differ from application to application. However, it will generally be required to make the application "recognize" the new VST plug-in, i.e. ``DynamicAudioNormalizerVST.dll`` first. Most applications will either pick up the VST plug-in from the *global* VST directory – usually located at ``C:\Program Files (x86)\Steinberg\Vstplugins`` on Windows – or provide an option to choose the directory from where to load the VST plug-in. This means that, depending on the individual application, you will either need to copy the Dynamic Audio Normalizer VST plug-in into the *global* VST directory *or* tell the application where the Dynamic Audio Normalizer VST plug-in is located. Note that, with some applications, it may also be required to *explicitly* scan for new VST pluig-ins. See the manual for details! The screen capture bellow shows the situation in the *Acoustica 6.0* software by Acon AS. Here we simply open the "VST Directories" dialogue from the "Plug-Ins" menu, then *add* the Dynamic Audio Normalizer directory and finally click "OK". ![Setting up the new *VST Plug-In* directory (in Acoustica 6.0, Copyright © 2014 Acon AS)](img/dyauno/VSTPlugInDirs.png "Dynamic Audio Normalizer – VST Plug-In") Furthermore, note that – unless you are using the *static* build of the Dynamic Audio Normalizer – the VST plug-in DLL, i.e. ``DynamicAudioNormalizerVST.dll``, also requires the Dynamic Audio Normalizer *core* library, i.e. ``DynamicAudioNormalizerAPI.dll``. This means that the *core* library **must** be made available to the VST host *in addition* to the VST plug-in itself. Otherwise, loading the VST plug-in DLL is going to fail! Copying the *core* library to the same directory, where the VST plug-in DLL, is located generally is **not** sufficient. Instead, the *core* library must be located in one of those directories that are checked for additional DLL dependencies (see [**here**](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586%28v=vs.85%29.aspx#standard_search_order_for_desktop_applications) for details). Therefore, it is *recommended* to copy the ``DynamicAudioNormalizerAPI.dll`` file into the same directory where the VST host's "main" executable (EXE file) is located. **Important:** Please note that Dynamic Audio Normalizer VST plug-in uses the VST interface version 2.x, which is the most widely supported VST version at this time. VST interface version 3.x is *not* currently used, supported or required. Also note that *32-Bit* (x86) VST host application can only work with *32-Bit* VST plug-ins and, similarly, *64-Bit* (AMD64/Intel64) VST host application can only work with *64-Bit* VST plug-ins. Depending on the "bitness" of your individual VST host application, always the suitable VST plug-in DLL file, 32- or 64-Bit, must be chosen! ## Known VST Limitations ## The algorithm used by the Dynamic Audio Normalizer uses a "look ahead" buffer. This necessarily requires that – at the beginning of the process – we read a certain minimum number of *input* samples before the first *output* samples can be computed. With a more flexible effect interface, like the one used by [SoX](http://sox.sourceforge.net/), the plug-in could request as many input samples from the host application as required, before it starts returning output samples. The *VST* interface, however, is rather limited in this regard: VST *enforces* that the plug-in process the audio in small chunks. The size of these chunks is *dictated* by the host application. Furthermore, VST *enforces* that the plug-in returns the corresponding output samples for each chunk of audio data *immediately* – the VST host won't provide the next chunk of input samples until the VST plug-in has returned the output samples for the previous chunk. To the best of our knowledge, there is **no** way to request even more input samples from the VST host! Consequently, the **only** known way to realize a "look ahead" buffer with VST is actually delaying all audio samples and returning some "silent" samples at the beginning. At least, VST provides the VST plug-in with a method to *report* its delay to the VST host application. Unfortunately, to the best of our knowledge, the VST specification lacks a detailed description on how a host application is required to deal with such a delay. This means that the actual behavior totally depends on the individual host application! Anyway, it is clear that, if a VST plug-in reports a delay of N samples, an audio editor **shall** discard the *first* N samples returned by that plug-in. Also, the audio editor **shall** feed N samples of additional "dummy" data to the plug-in at the very end of the process – in order to flush the pending output samples. In practice, however, it turns out that, while *some* audio editors show the "correct" behavior, others do **not**. Those audio editors seem to *ignore* the plug-in's delay, so the audio file will end up shifted and truncated! The Dynamic Audio Normalizer VST plug-in *does* report its delay to the VST host application. Thus, if you encounter shifted and/or truncated audio after the processing, this means that there is a **bug** in the VST host application. And, sadly, the plug-in can do absolutely *nothing* about this. Below, there is a non-exhaustive list of audio editors with *proper* VST support. Those have been tested to work correctly. There also is a list of audio editors with *known problems*. Those should **not** be used for VST processing, until the respective developers have fixed the issue… ### List of functioning VST Hosts ### {-} Incomplete list of VST hosts that have been tested to *work correctly* with the Dynamic Audio Normalizer VST plug-in: * **[Audacity](http://sourceforge.net/projects/audacity/files/audacity/) v2.1.2, by Audacity Team**  |  **recommended!** - Status: VST support working - License: free/libre OpenSource software - *Note: See [**here**](http://wiki.audacityteam.org/wiki/VST_Plug-ins) for install instructions and make sure that the "Buffer Delay Compensation" option is enabled!* * **[Acoustica](http://acondigital.com/products/acoustica-audio-editor/) v6.0 (Build 19), by Acon AS**  |  **recommended!** - Status: VST support working - License: Proprietary, free "basic" edition available * **[GoldWave](http://www.goldwave.com/) v5.70, by GoldWave Inc.** - Status: VST support working - License: Proprietary, fully functional "evaluation" version available - *Note: There currently is a VST regression in version 6.x that inserts silence at the beginning of the file!* * **[Audition](https://creative.adobe.com/products/audition) (formerly "Cool Edit Pro") v10.0.1, by Adobe Systems Inc.** - Status: VST support working - License: Proprietary, free *trial* version available * **[WaveLab](http://www.steinberg.net/en/products/wavelab/start.html) v9.0, by Steinberg Media Technologies GmbH** - Status: VST support working - License: Proprietary, free *trial* version available * **[REAPER](http://www.reaper.fm/) v5.33, by Cockos Inc.** - Status: VST support working - License: Proprietary, free *trial* version available * **[Sound Forge Pro](http://www.magix-audio.com/de/sound-forge/), by Magix (formerly Sony)** - Status: VST support working - License: Proprietary, free *trial* version available *Disclaimer: There is absolutely **no** guarantee for the completeness or correctness of the above information!* ### List of problematic VST Hosts ### {-} List of VST hosts with *known problems* that do **not** work correctly with VST plug-ins like the Dynamic Audio Normalizer: * **[Waveosaur](http://www.wavosaur.com/) v1.2.0** - Status: VST support broken → audio will be shifted and truncated - License: Proprietary, freeware version available * **[Ocenaudio](http://www.ocenaudio.com.br/) v3.2.2** - Status: VST support broken → audio will be shifted and truncated + some plug-in settings are displayed incorrectly - License: Proprietary, freeware version available * **[WavePad](http://www.nch.com.au/wavepad/) v6.53, by NCH Software** - Status: VST support broken → audio will be shifted and truncated + doesn't expose the plug-in's settings - License: Proprietary, freeware version available * **[Nero WaveEditor](http://www.nero.com/enu/downloads/) v12.5, by Nero AG** - Status: VST support broken → application crashes when trying to load *any* VST plug-in for some unknown reason - License: Proprietary, freeware version available * **[Audiodope](http://www.audiodope.org/) v0.26**, by Audiodope team - Status: VST support broken → audio will be shifted and truncated + plug-in settings are displayed incorrectly - License: Proprietary, freeware version available * **[Dexster Audio Editor](http://www.dexster.net/) v4.5, by Softdiv** - Status: VST support broken → audio will be shifted and truncated + doesn't expose the plug-in's settings - License: Proprietary, free *trial* version available * **[AudioDirector](http://www.cyberlink.com/products/audiodirector/features_en_US.html) v7.0, by CyberLink Corp** - Status: VST support broken → audio will be shifted and truncated by a very large amount - License: Proprietary, free *trial* version available *Disclaimer: There is absolutely **no** guarantee for the completeness or correctness of the above information!* *If you are the developer of one of the "problematic" tools and you are interested in fixing the problem in your product, or if you have already fixed the problem in the meantime, then please let us know, so that we can update the information…* # Winamp Plug-In Usage # The Dynamic Audio Normalizer is also available in the form of a **DSP/Effect** plug-in for [Winamp](http://www.winamp.com/), the popular media player created by Nullsoft. This way, the Dynamic Audio Normalizer can be applied to your audio files during playback, in *real-time*. ![The Winamp DSP/Effect plug-in (Winamp is Copyright © 1997-2013 Nullsoft, Inc)](img/dyauno/WAPlugIn.png) ## Install Instructions ## If you have **not** installed the ***latest*** version of Winamp yet, please update your Winamp installation first. Although the development of Winamp seems to be discontinued and its future remains uncertain at this point, you can still download the *last* Winamp release (as of January 2017), which is *Winamp 5.666 "Redux"*, from one of the following download mirrors: * * * * Be sure to grab the *patched* (aka "Redux") edition of Winamp 5.666, which has some security issues fixed and some defunct "online" features removed. Older versions are generally *not* recommended and may *not* work with the plug-in! Once the *latest* version of Winamp 5.x is installed, simply copy the provided Winamp plug-in file ``DynamicAudioNormalizerWA5.dll`` into the directory for Winamp *DSP/Effect* plug-ins. By default, that is the sub-directory ``Plugins`` *inside* your Winamp installation directory. So, if Winamp was installed at ``C:\Program Files (x86)\Winamp``, the *default* plug-in directory would be ``C:\Program Files (x86)\Winamp\Plugins``. If you have installed Winamp to a *different* directory or if you have changed the plug-in directory to a *different* location (see the Winamp "Perferences" dialogue), then please adjust the path accordingly! Note that copying the plug-in DLL into the ``Plugins`` directory may require administrative privileges. That's because ``C:\Program Files (x86)`` is a protected system directory. Also note that the plug-in DLL **must** be *renamed* to ``dsp_dynaudnorm.dll`` in order to make Winmap recognize the DLL. Any other file name of your choice will work just as well, as long as it starts with the ``dsp_`` prefix. Once the plug-in DLL file is located at the correct place, e.g. ``C:\Program Files (x86)\Winamp\Plugins\dsp_dynaudnorm.dll``, it should appear in the Winamp "Preferences" dialogue after the next restart. More specifically, you should find the "Dynamic Audio Normalizer" plug-in on the "Plug-ins" → "DSP/Effect" page. Simply select the desired plug-in from the list of available *DSP/Effect* plug-ins and it will be active from now on. Furthermore, note that – unless you are using the *static* build of the Dynamic Audio Normalizer – the Winamp plug-in DLL also requires the Dynamic Audio Normalizer *core* library, i.e. ``DynamicAudioNormalizerAPI.dll``. This means that the *core* library **must** be made available to Winamp *in addition* to the DSP/Effect plug-in itself. Otherwise, loading the DSP/Effect plug-in DLL is going to fail! Though, copying the *core* library to the same directory, where the plug-in DLL is located, i.e. the ``Plugins`` directory, generally is **not** sufficient. Instead, the *core* library must be located in one of those directories that are checked for additional DLL dependencies (see [**here**](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586%28v=vs.85%29.aspx#standard_search_order_for_desktop_applications) for details). Therefore, it is *recommended* to copy the ``DynamicAudioNormalizerAPI.dll`` file into the same directory where the Winamp "main" executable (EXE file) is located. ## Registry Settings The Dynamic Audio Normalizer plug-in for Winamp does *not* currently provide a configuration dialogue. However, the most important settings are stored in the Windows registry and can be edited using the Registry Editor (`regedit.exe`): * The settings are stored under the following key: ``` HKEY_CURRENT_USER\Software\MuldeR\DynAudNorm\WA5 ``` * The following reg-values are currently supported: - **`FilterSize`**: Controlls the [*Gaussian filter window size*](#gaussian-filter-window-size), in frames (DWORD) - **`FrameLenMsec`**: Controlls the [*frame length*](#frame-length), in milliseconds (DWORD) **Note:** If any of the registry values do not exist yet, simply create them. Restart Winamp to make your changes take effect! ## Known Limitations ## Unfortunately, the programming interface (API) that Winamp offers to *DSP/Effect* plug-in is ***very*** limited. In particular, Winamp does **not** report to the plug-in when playback starts or stops, it does **not** report to the plug-in when switching to another track, and it does **not** report to the plug-in when seeking within the current track. Also, in **none** of the aforementioned situations Winamp is going to re-initialize the plug-in. Instead, Winamp just feeds the plug-in with an "unbroken" stream of audio samples – even when the user seeks to a different position in the current track or switches to a completely different track. Consequently, it is **not** technically possible for the plug-in to "flush" its internal buffer in the relevant situations! As a result, users will experience a delay of approximately 15 seconds when the Dynamic Audio Normalizer plug-in for Winamp is active. If, for example, you move the slider on Winamp's seek bar, it will take about 15 seconds until you actually hear the audio from the new position. Similarly, if you switch to another track, it will take about 15 seconds until you actually hear the audio from the new track. *To make it clear again:* Only the Winamp developers could fix this annoyance – by providing DSP/Effect plug-in developers with a more suitable API. However, given the current state of Winamp development, this is unlikely to happen. # Configuration # This chapter describes the configuration options that can be used to tweak the behavior of the Dynamic Audio Normalizer. While the default parameter of the Dynamic Audio Normalizer have been chosen to give satisfying results for a wide range of audio sources, it can be advantageous to adapt the parameters to the individual audio file as well as to your personal preferences. The *default* settings have been chosen rather "conservative", so that the dynamics of the audio are preserved well. People who desire a more "aggressive" effect should try using a *smaller* [*filter size*](#gaussian-filter-window-size), or enable [*input compression*](#input-compression). ## Gaussian Filter Window Size ## Probably the most important parameter of the Dynamic Audio Normalizer is the "window size" of the Gaussian smoothing filter. It can be controlled with the **``--gauss-size``** option. The filter's window size is specified in *frames*, centered around the current frame. For the sake of simplicity, this must be an *odd* number. Consequently, the default value of **31** takes into account the current frame, as well as the *15* preceding frames and the *15* subsequent frames. Using a *larger* Gaussian window size results in a *stronger* smoothing effect and thus in *less* gain variation, i.e. slower gain adaptation. Conversely, using a *smaller* Gaussian window size results in a *weaker* smoothing effect and thus in *more* gain variation, i.e. faster gain adaptation. In other words, the more you *increase* this value, the more the Dynamic Audio Normalizer will behave like a "traditional" (non-dynamic) normalization filter. On the contrary, the more you *decrease* this value, the more "aggressively" the Dynamic Audio Normalizer will behave, i.e. more like a dynamic range *compressor*. The following graph illustrates the effect of different Gaussian window sizes – *11* (orange), *31* (green), and *61* (purple) frames – on the progression of the final filtered gain factor. ![The effect of different "window sizes" of the Gaussian smoothing filter](img/dyauno/FilterSize.png) ## Target Peak Magnitude ## The target peak magnitude specifies the highest permissible magnitude level for the *normalized* audio file. It is controlled by the **``--peak``** option. Since the Dynamic Audio Normalizer represents audio samples as floating point values in the *-1.0* to *1.0* range – regardless of the input and output audio format – this value must be in the *0.0* to *1.0* range. Consequently, the value *1.0* is equal to [0 dBFS](http://en.wikipedia.org/wiki/DBFS), i.e. the maximum possible digital signal level (± 32767 in a 16-Bit file). The Dynamic Audio Normalizer will try to approach the target peak magnitude as closely as possible, but at the same time it also makes sure that the normalized signal will *never* exceed the peak magnitude. A frame's maximum local gain factor is imposed directly by the target peak magnitude. The default value is **0.95** and thus leaves a [headroom](http://en.wikipedia.org/wiki/Headroom_%28audio_signal_processing%29) of *5%*. It is **not** recommended to go *above* this value! ## Channel Coupling ## By default, the Dynamic Audio Normalizer will amplify all channels by the same amount. This means the *same* gain factor will be applied to *all* channels, i.e. the maximum possible gain factor is determined by the "loudest" channel. In particular, the highest magnitude sample for the `n`-th frame is defined as `S_max[n]=Max(s_max[n][1],s_max[n][2],…,s_max[n][C])`, where `s_max[n][k]` denotes the highest magnitude sample in the `k`-th channel and `C` is the channel count. The gain factor for *all* channels is then derived from `S_max[n]`. This is referred to as *channel coupling* and for most audio files it gives the desired result. Therefore, channel coupling is *enabled* by default. However, in some recordings, it may happen that the volume of the different channels is *uneven*, e.g. one channel may be "quieter" than the other one(s). In this case, the **`--no-coupling`** option can be used to *disable* the channel coupling. This way, the gain factor will be determined *independently* for each channel `k`, depending only on the individual channel's highest magnitude sample `s_max[n][k]`. This allows for harmonizing the volume of the different channels. The following wave view illustrates the effect of channel coupling: It shows an input file with *uneven* channel volumes (left), the same file after normalization with channel coupling *enabled* (center) and again after normalization with channel coupling *disabled* (right). ![The effect of *channel coupling*](img/dyauno/Coupling.png) ## DC Bias Correction## An audio signal (in the time domain) is a sequence of sample values. In the Dynamic Audio Normalizer these sample values are represented in the *-1.0* to *1.0* range, regardless of the original input format. Normally, the audio signal, or "waveform", should be centered around the *zero point*. That means if we calculate the *mean* value of all samples in a file, or in a single frame, then the result should be *0.0* or at least very close to that value. If, however, there is a significant deviation of the mean value from *0.0*, in either positive or negative direction, this is referred to as a [*DC bias*](http://en.wikipedia.org/wiki/DC_bias) or *DC offset*. Since a DC bias is clearly undesirable, the Dynamic Audio Normalizer provides optional *DC bias correction*, which can be enabled using the **``--correct-dc``** switch. With DC bias correction *enabled*, the Dynamic Audio Normalizer will determine the mean value, or "DC correction" offset, of each input frame and *subtract* that value from all of the frame's sample values – which ensures those samples are centered around *0.0* again. Also, in order to avoid "gaps" at the frame boundaries, the DC correction offset values will be interpolated smoothly between neighbouring frames. The following wave view illustrates the effect of DC bias correction: It shows an input file with positive DC bias (left), the same file after normalization with DC bias correction *disabled* (center) and again after normalization with DC bias correction *enabled* (right). ![The effect of *DC Bias Correction*](img/dyauno/DCCorrection.png) ## Maximum Gain Factor ## The Dynamic Audio Normalizer determines the maximum possible (local) gain factor for each input frame, i.e. the maximum gain factor that does *not* result in clipping or distortion. The maximum gain factor is determined by the frame's highest magnitude sample. However, the Dynamic Audio Normalizer *additionally* bounds the frame's maximum gain factor by a predetermined (global) *maximum gain factor*. This is done in order to avoid "extreme" gain factors in silent, or almost silent, frames. By default, the *maximum gain factor* is **10.0**, but it can be adjusted using the **``--max-gain``** switch. For most input files the default value should be sufficient, and it usually is **not** recommended to increase this value above the default. Though, for input files with a rather low overall volume level, it may be necessary to allow even higher gain factors. Be aware, however, that the Dynamic Audio Normalizer does *not* simply apply a "hard" threshold (i.e. it does *not* simply cut off values above the threshold). Instead, a "sigmoid" thresholding function will be applied on the final gain factors, as depicted in the following chart. This way, the gain factors will smoothly approach the threshold value, but they will *never* exceed that value. ![The Gain Factor Threshold-Function](img/dyauno/Threshold.png) ## Target RMS Value ## By default, the Dynamic Audio Normalizer performs "peak" normalization. This means that the maximum local gain factor for each frame is defined (only) by the frame's highest magnitude sample (the "loudest" peak). This way, the samples can be amplified as much as possible *without* exceeding the maximum signal level, i.e. *without* clipping. Optionally, however, the Dynamic Audio Normalizer can also take into account the frame's [*root mean square*](http://en.wikipedia.org/wiki/Root_mean_square), or, in short, **RMS**. In electrical engineering, the RMS is commonly used to determine the *power* of a time-varying signal. It is therefore considered that the RMS is a better approximation of the "perceived loudness" than just looking at the signal's peak magnitude. Consequently, by adjusting all frames to a *constant* RMS value, a *uniform* "perceived loudness" can be established. With the Dynamic Audio Normalizer, RMS processing can be enabled using the **``--target-rms``** switch. This specifies the desired RMS value, in the *0.0* to *1.0* range. There is **no** default value, because RMS processing is *disabled* by default. If a target RMS value has been specified, a frame's local gain factor is defined as the factor that would result in exactly *that* RMS value. Note, however, that the maximum local gain factor is still restricted by the frame's highest magnitude sample, in order to prevent clipping. The following chart shows the same file normalized *without* (green) and *with* (orange) RMS processing enabled. ![Root Mean Square (RMS) processing example](img/dyauno/RMS.png) ## Frame Length ## The Dynamic Audio Normalizer processes the input audio in small chunks, referred to as *frames*. This is required, because a *peak magnitude* has no meaning for just a single sample value. Instead, we need to determine the peak magnitude for a contiguous sequence of sample values. While a "standard" normalizer would simply use the peak magnitude of the *complete* file, the Dynamic Audio Normalizer determines the peak magnitude *individually* for each frame. The length of a frame is specified in milliseconds. By default, the Dynamic Audio Normalizer uses a frame length of **500** milliseconds, which has been found to give good results with most files, but it can be adjusted using the **``--frame-len``** switch. Note that the exact frame length, in number of samples, will be determined automatically, based on the sampling rate of the individual input audio file. ## Boundary Mode ## As explained before, the Dynamic Audio Normalizer takes into account a certain neighbourhood around each frame. This includes the *preceding* frames as well as the *subsequent* frames. However, for the "boundary" frames, located at the very beginning and at the very end of the audio file, **not** all neighbouring frames are available. In particular, for the *first* few frames in the audio file, the preceding frames are *not* known. And, similarly, for the *last* few frames in the audio file, the subsequent frames are *not* known. Thus, the question arises which gain factors should be assumed for the *missing* frames in the "boundary" region. The Dynamic Audio Normalizer implements two modes to deal with this situation. The *default* boundary mode assumes a gain factor of exactly *1.0* for the missing frames, resulting in a smooth "fade in" and "fade out" at the beginning and at the end of the file, respectively. The *alternative* boundary mode can be enabled by using the **``--alt-boundary``** switch. The latter mode assumes that the missing frames at the *beginning* of the file have the same gain factor as the very *first* available frame. It furthermore assumes that the missing frames at the *end* of the file have same gain factor as the very *last* frame. The following chart illustrates the difference between the *default* (green) and the *alternative* (red) boundary mode. Note hat, for simplicity's sake, a file containing *constant* volume white noise was used as input here. ![Default boundary mode vs. alternative boundary mode](img/dyauno/Boundary.png) ## Input Compression ## By default, the Dynamic Audio Normalizer does **not** apply "traditional" compression. This means that signal peaks will **not** be pruned and thus the *full* dynamic range will be retained within each local neighbourhood. However, in some cases it may be desirable to *combine* the Dynamic Audio Normalizer's normalization algorithm with a more "traditional" compression. For this purpose, the Dynamic Audio Normalizer provides an *optional* compression (thresholding) function. It is disabled by default and can be enabled by using the **``--compress``** switch. If (and only if) the compression feature is enabled, all input frames will be processed by a [*soft knee*](https://mdn.mozillademos.org/files/5113/WebAudioKnee.png) thresholding function *prior to* the actual normalization process. Put simply, the thresholding function is going to prune all samples whose magnitude exceeds a certain threshold value. However, the Dynamic Audio Normalizer does *not* simply apply a fixed threshold value. Instead, the threshold value will be adjusted for each individual frame. More specifically, the threshold for a specific input frame is defined as ``T = μ + (c · σ)``, where **μ** is the *mean* of all sample magnitudes in the current frame, **σ** is the *standard deviation* of those sample magnitudes and **c** is the parameter controlled by the user. Note that, assuming the samples magnitudes are following (roughly) a [normal distribution](http://content.answcdn.com/main/content/img/barrons/accounting/New/images/normaldistribution2.jpg), about 68% of the sample values will be within the **μ ± σ** range, about 95% of the sample values will be within the **μ ± 2σ** range and more than 99% of the sample values will be within the **μ ± 3σ** range. Consequently, a parameter of **c = 2** will prune about 5% of the frame's highest magnitude samples, a parameter of **c = 3** will prune about 1% of the frame's highest magnitude samples, and so on. In general, *smaller* parameters result in *stronger* compression, and vice versa. Values below *3.0* are **not** recommended, because audible distortion may appear! The following waveform view illustrates the effect of the input compression feature: It shows the same input file *before* (upper view) and *after* (lower view) the thresholding function has been applied. Please note that, for the sake of clarity, the actual normalization process has been *disabled* in the following chart. Under normal circumstances, the normalization process is applied immediately after the thresholding function. ![The effect of the input compression (thresholding) function](img/dyauno/Compression-1.png) ## Write Log File ## Optionally, the Dynamic Audio Normalizer can create a log file. The log file name is specified using the **``--log-file``** option. If that option is *not* used, then *no* log file will be written. The log file uses a simple text format. The file starts with a header, followed by a list of gain factors. In that list, there is one line per frame. In each line, the *first* column contains the maximum local gain factor, the *second* column contains the minimum filtered gain factor, and the *third* column contains the final smoothed gain factor. This sequence is repeated once per channel. DynamicAudioNormalizer Logfile v2.00-5 CHANNEL_COUNT:2 10.00000 8.59652 5.07585 10.00000 8.59652 5.07585 8.59652 8.59652 5.64167 8.59652 8.59652 5.64167 9.51783 8.59652 6.17045 9.51783 8.59652 6.17045 ... The log file can be displayed as a graphical chart using, for example, the *Log Viewer* application (DynamicAudioNormalizerGUI) that is included with the Dynamic Audio Normalizer: ![Dynamic Audio Normalizer - Log Viewer](img/dyauno/LogViewer.png) # API Documentation # This chapter describes the **MDynamicAudioNormalizer** application programming interface (API). The API specified in this document allows software developer to call the *Dynamic Audio Normalizer* library from their own programs. ## Language Bindings ## The Dynamic Audio Normalizer "core" library is written in [***C++***](http://en.wikipedia.org/wiki/C%2B%2B). Therefore the *native* application programming interface (API) is provided in the form of a *C++* class. Furthermore, language bindings for the [***Microsoft.NET***]() platform (*C#*, *VB.NET*, etc.) as well as for [***Java***](http://en.wikipedia.org/wiki/Java_%28programming_language%29) (JRE 1.7 or later), [***Python***](https://www.python.org/) (CPython 3.0 or later) and [***Object Pascal***](http://en.wikipedia.org/wiki/Object_Pascal) (*Delphi 7.0* or later) are provided. For each of these languages, a suitable "wrapper" is provided, which exposes – to the greatest extend possible – the same functions as the native *C++* class. Calls to the language-specific wrapper will be forwarded, *internally*, to the corresponding native method of to the underlying *C++* class. Native library calls are handled *transparently* by the individual language wrapper, so that application developers do **not** need to worry about interoperability issues. In particular, the language wrapper will take care of data marshalling as well as the management of the native *MDynamicAudioNormalizer* instances. ### C++ interface *C++* applications shall use the native **MDynamicAudioNormalizer** C++ class *directly*, which is declared in the `DynamicAudioNormalizerAPI.h` header file. It is implemented by the shared library `DynamicAudioNormalizerAPI.dll` (Windows) or `libDynamicAudioNormalizerAPI-X.so` (Linux). A detailed description of the *C++* class is given [*below*](#function-reference). ***Note***: On the Windows platform, you will need to link your binary against the *import* library `DynamicAudioNormalizerAPI.lib`. ### C99 interface *C* applications can use the *C99* "wrapper" functions, which are also declared in the `DynamicAudioNormalizerAPI.h` header file. Those "wrapper" functions are implemented by the shared library `DynamicAudioNormalizerAPI.dll` (Windows) or `libDynamicAudioNormalizerAPI-X.so` (Linux), just like the native *C++* interface. There exists a corresponding *C99* "wrapper" function for each method of the native *C++* class. The "wrapper" functions provide the same functionality and take the same parameters as the underlying *C++* methods, except that an additional [*handle*](http://en.wikipedia.org/wiki/Handle_%28computing%29) parameter needs to be passed to each "wrapper" function. The handle corresponds to the "this" pointer that is *implicitly* passed to C++ methods. The *C*-only functions `createInstance()` and `destroyInstance()` correspond to the *C++* class' constructor and destructor, respectively. ***Note***: On the Windows platform, you will need to link your binary against the *import* library `DynamicAudioNormalizerAPI.lib`. ### Microsoft.NET interface *Microsoft.NET* (*C#*, *VB.NET*, etc.) applications can use the **DynamicAudioNormalizerNET** [*C++/CLI*](http://en.wikipedia.org/wiki/C%2B%2B/CLI) "wrapper" class, which is implemented by the `DynamicAudioNormalizerNET.dll` assembly. There exists an equivalent method in the *C++/CLI* "wrapper" class for each method of the native *C++* class. Note, however, that the `DynamicAudioNormalizerNET.dll` assembly is really just a thin "wrapper" and it requires the *native* "core" library `DynamicAudioNormalizerAPI.dll` at runtime! ### Java interface *Java* applications can use the **JDynamicAudioNormalizer** [*JNI*](https://en.wikipedia.org/wiki/Java_Native_Interface) "wrapper" class, which is implemented by the `DynamicAudioNormalizerJNI.jar` library. There exists an equivalent method in the *JNI* "wrapper" class for each method of the native *C++* class. Note, however, that the `DynamicAudioNormalizerJNI.jar` *JNI* "wrapper" requires the *native* "core" library `DynamicAudioNormalizerAPI.dll` (Windows) or `libDynamicAudioNormalizerAPI-X.so` (Linux) at runtime! ### Python interface *Python* applications can use our [*C extension for CPython*](https://docs.python.org/3/extending/building.html), which is implemented by the `DynamicAudioNormalizerAPI.pyd` library. We also provide the **PyDynamicAudioNormalizer** *Python* "wrapper" class for convenience, which is declared in the `DynamicAudioNormalizer.py` module. There exists an equivalent method in the *Python* "wrapper" class for each method of the native *C++* class. Note, however, that the `DynamicAudioNormalizerJNI.pyd` *C extension* module requires the *native* "core" library `DynamicAudioNormalizerAPI.dll` (Windows) or `libDynamicAudioNormalizerAPI-X.so` (Linux) at runtime! ### Object Pascal interface *Object Pascal* (Delphi) applications can use the **TDynamicAudioNormalizer** [*Object Pascal*](https://en.wikipedia.org/wiki/Object_Pascal) "wrapper" class, which is implemented by the `DynamicAudioNormalizer.pas` unit file. There exists an equivalent method in the *Object Pascal* "wrapper" class for each method of the native *C++* class. Note, however, that the `DynamicAudioNormalizer.pas` *Object Pascal* "wrapper" is built on top of the *C99* API and it requires the *native* library `DynamicAudioNormalizerAPI.dll` at runtime! ## Thread Safety ## All methods of the `MDynamicAudioNormalizer` class are [*reentrant*](https://doc.qt.io/qt-4.8/threads-reentrancy.html#reentrancy), but **not** [*thread-safe*](https://doc.qt.io/qt-4.8/threads-reentrancy.html#thread-safety)! Hence, it ***is*** safe to use the MDynamicAudioNormalizer class in *multi-threaded* applications, but **only** as long as each thread uses its "own" separate MDynamicAudioNormalizer instance. In other words, it is *strictly forbidden* to call the *same* MDynamicAudioNormalizer instance *concurrently* from *different* threads. But it ***is*** admissible to call *distinct* MDynamicAudioNormalizer instances *concurrently* from *different* threads – provided that each thread will access *only* its "own" instance. If the *same* MDynamicAudioNormalizer instance needs to be accessed by *different* threads, then the calling application is responsible for *serializing* each and every call to that instance, e.g. by means of a Mutex; otherwise **undefined behavior** follows! There is *one* notable exception from the above restrictions: The **static** methods of the `MDynamicAudioNormalizer` class as well as the `createInstance()` function of the "C99" API ***are*** perfectly *thread-safe*. No synchronization is needed for those. ## Quick Start Guide ## The following listing summarizes the steps that an application needs to follow when using the API: 1. Create a new *MDynamicAudioNormalizer* instance. This allocates required resources. 2. Call the ``initialize()`` method, *once*, in order to initialize the MDynamicAudioNormalizer instance. 3. Call the ``processInplace()`` method, *in a loop*, until all input samples have been processed. - **Note:** At the beginning, this function returns *less* output samples than input samples have been passed. Samples are guaranteed to be returned in FIFO order, but there is a certain "delay"; call `getInternalDelay()` for details. 4. Call the ``flushBuffer()`` method, *in a loop*, until all the pending "delayed" output samples have been flushed. 5. Destroy the *MDynamicAudioNormalizer* instance. This will free up all allocated resources. *Note:* The Dynamic Audio Normalizer library processes audio samples, but it does **not** provide any audio I/O capabilities. Reading or writing the audio samples from or to an audio file is up to the application. A library like [libsndfile](http://www.mega-nerd.com/libsndfile/) is helpful! ## Function Reference ## ### MDynamicAudioNormalizer::MDynamicAudioNormalizer() ### {-} ``` MDynamicAudioNormalizer( const uint32_t channels, const uint32_t sampleRate, const uint32_t frameLenMsec, const uint32_t filterSize, const double peakValue, const double maxAmplification, const double targetRms, const bool channelsCoupled, const bool enableDCCorrection, const bool altBoundaryMode, FILE *const logFile ); ``` Constructor. Creates a new *MDynamicAudioNormalizer* instance and sets up the normalization parameters. **Parameters:** * *channels*: The number of channels in the input/output audio stream (e.g. **2** for Stereo). * *sampleRate*: The sampling rate of the input/output audio stream, in Hertz (e.g. **44100** for "CD Quality"). * *frameLenMsec*: The [frame length](#frame-length), in milliseconds. A typical value is **500** milliseconds. * *filterSize*: The ["window size"](#gaussian-filter-window-size) of the Gaussian filter, in frames. Must be an *odd* number. (default: **31**). * *peakValue*: Specifies the [peak magnitude](#target-peak-magnitude) for normalized audio, in the **0.0** to **1.0** range (default: **0.95**). * *maxAmplification*: Specifies the [maximum gain factor](#maximum-gain-factor). Must be greater than **1.0** (default: **10.0**). * *targetRms*: Specifies the [target RMS](#target-rms-value) value. Must be in the **0.0** to **1.0** range, **0.0** means *disabled* (default: **0.0**). * *channelsCoupled*: Set to **true** in order to enable [channel coupling](#channel-coupling), or to **false** otherwise (default: **true**). * *enableDCCorrection*: Set to **true** in order to enable [DC correction](#dc-bias-correction), or to **false** otherwise (default: **false**). * *altBoundaryMode*: Set to **true** in order to enable the alternative [boundary mode](#boundary-mode) (default: **false**). * *logFile*: An open **FILE*** handle with *write* access to be used for [logging](#write-log-file), or **NULL** to disable logging. ### MDynamicAudioNormalizer::~MDynamicAudioNormalizer() ### {-} ``` virtual ~MDynamicAudioNormalizer(void); ``` Destructor. Destroys the *MDynamicAudioNormalizer* instance and releases all memory that it occupied. ### MDynamicAudioNormalizer::initialize() ### {-} ``` bool initialize(void); ``` Initializes the MDynamicAudioNormalizer instance. Validates the parameters and allocates the required memory buffers. This function *must* be called once for each new MDynamicAudioNormalizer instance. It *must* be called *before the `processInplace()` function can be called for the first time. Do **not** call `processInplace()`, if this function has failed! **Return value:** * Returns `true` if everything was successful or `false` if something went wrong. ### MDynamicAudioNormalizer::process() ### {-} ``` bool process( const double **samplesIn, double **samplesOut, int64_t inputSize, int64_t &outputSize ); ``` This is the "main" processing function. It shall be called *in a loop* until all input audio samples have been processed. The function works "out-of-place": It *reads* the original input samples from the specified `samplesIn` buffer and then *writes* the normalized output samples, if any, back into the `samplesOut` buffer. The content of `samplesIn` will be preserved. ***Note:*** A call to this function reads *all* provided input samples from the buffer, but the number of output samples that are written back to the buffer may actually be *smaller* than the number of input samples that have been read! The pending samples are buffered internally and will be returned in a subsequent call. In other words, samples are returned with a certain "delay". This means that the *i*-th output sample does **not** necessarily correspond to the *i*-th input sample! Still, the samples are returned in strict [FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)) order. The exact delay can be determined by calling the `getInternalDelay()` function. At the end of the process, when all input samples have been read, to application shall call `flushBuffer()` in order to *flush* all pending samples. **Parameters:** * *samplesIn*: The input buffer. This buffer contains the original input samples to be read. It will be treated as a *read-only* buffer. The *i*-th input sample for the *c*-th channel is assumed to be stored at `samplesIn[c][i]`, as a double-precision floating point number. All indices are *zero*-based. All sample values live in the **-1.0** to **+1.0** range. * *samplesOut*: The output buffer. The processed output samples will be written back to this buffer. Its initial contents will therefore be *overwritten*. The *i*-th output sample for the *c*-th channel will be stored at `samplesOut[c][i]`. The size of the buffer must be sufficient! All indices are *zero*-based. All sample values live in the **-1.0** to **+1.0** range. * *inputSize*: The number of original *input* samples that are available in the `samplesIn` buffer, per channel. This also specifies the *maximum* number of output samples that can be written back to the `samplesOut` buffer. * *outputSize*: Receives the number of *output* samples that have actually been written back to the `samplesOut` buffer, per channel. Please note that this value can be *smaller* than the `inputSize` value. It can even be *zero*! **Return value:** * Returns `true` if everything was successful or `false` if something went wrong. ### MDynamicAudioNormalizer::processInplace() ### {-} ``` bool processInplace( double **samplesInOut, int64_t inputSize, int64_t &outputSize ); ``` This is the "main" processing function. It shall be called *in a loop* until all input audio samples have been processed. The function works "in-place": It *reads* the original input samples from the specified buffer and then *writes* the normalized output samples, if any, back into the *same* buffer. So, the content of `samplesInOut` will **not** be preserved! ***Note:*** A call to this function reads *all* provided input samples from the buffer, but the number of output samples that are written back to the buffer may actually be *smaller* than the number of input samples that have been read! The pending samples are buffered internally and will be returned in a subsequent call. In other words, samples are returned with a certain "delay". This means that the *i*-th output sample does **not** necessarily correspond to the *i*-th input sample! Still, the samples are returned in strict [FIFO](https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)) order. The exact delay can be determined by calling the `getInternalDelay()` function. At the end of the process, when all input samples have been read, to application shall call `flushBuffer()` in order to *flush* all pending samples. **Parameters:** * *samplesInOut*: The input/output buffer. This buffer initially contains the original input samples to be read. Also, the processed output samples will be written back to this buffer. The *i*-th input sample for the *c*-th channel is assumed to be stored at `samplesInOut[c][i]`, as a double-precision floating point number. The output samples, if any, will be stored at the corresponding locations, thus *overwriting* the input data. Consequently, the *i*-th output sample for the *c*-th channel will be stored at `samplesInOut[c][i]`. All indices are *zero*-based. All sample values live in the **-1.0** to **+1.0** range. * *inputSize*: The number of original *input* samples that are available in the `samplesInOut` buffer, per channel. This also specifies the *maximum* number of output samples that can be written back to the buffer. * *outputSize*: Receives the number of *output* samples that have actually been written back to the `samplesInOut` buffer, per channel. Please note that this value can be *smaller* than the `inputSize` value. It can even be *zero*! **Return value:** * Returns `true` if everything was successful or `false` if something went wrong. ### MDynamicAudioNormalizer::flushBuffer() ### {-} ``` bool flushBuffer( double **samplesOut, const int64_t bufferSize, int64_t &outputSize ); ``` This function shall be called at the end of the process, after all input samples have been processed via `processInplace()` function, in order to flush the *pending* samples from the internal buffer. It writes the next pending output samples into the output buffer, in FIFO order, if and only if there are still any pending output samples left in the internal buffer. Once this function has been called, you must call `reset()` before the `processInplace()` function may be called again! If this function returns fewer output samples than the specified output buffer size, then this indicates that the internal buffer is empty now. **Parameters:** * *samplesOut*: The output buffer that will receive the normalized output samples. The *i*-th output sample for the *c*-th channel will be stored at `samplesOut[c][i]`. All indices are *zero*-based. All sample values live in the **-1.0** to **+1.0** range. * *bufferSize*: Specifies the *maximum* number of output samples to be stored in the output buffer. * *outputSize*: Receives the number of *output* samples that have actually been written to the `samplesOut` buffer. Please note that this value can be *smaller* than `bufferSize` size, if no more pending samples are left. It can even be *zero*! **Return value:** * Returns ``true`` if everything was successfull or ``false`` if something went wrong. ### MDynamicAudioNormalizer::reset() ### {-} ``` bool reset(void); ``` Resets the internal state of the *MDynamicAudioNormalizer* instance. It normally is **not** required or recommended to call this function! The only exception here is: If you really want to process *multiple* independent audio files with the *same* normalizer instance, then you *must* call the `reset()` function *after* all samples of the **current** audio file have been processed (and all of its pending samples have been flushed), but *before* processing the first sample of the **next** audio file. **Return value:** * Returns ``true`` if everything was successfull or ``false`` if something went wrong. ### MDynamicAudioNormalizer::getConfiguration() ### {-} ``` bool getConfiguration( uint32_t &channels, uint32_t &sampleRate, uint32_t &frameLen, uint32_t &filterSize ); ``` This is a convenience function to retrieve the current configuration of an existing *MDynamicAudioNormalizer* instance. **Parameters:** * *channels*: Receives the number of channels that was set in the constructor. * *sampleRate*: Receives the sampling rate, in Hertz, that was set in the constructor. * *frameLen*: Receives the current frame length, in samples (**not** milliseconds). * *filterSize*: Receives the Gaussian filter size, in frames, that was set in the constructor. **Return value:** * Returns ``true`` if everything was successfull or ``false`` if something went wrong. ### MDynamicAudioNormalizer::getInternalDelay() ### {-} ``` bool getInternalDelay( int64_t &delayInSamples, ); ``` This function can be used to determine the internal "delay" of the *MDynamicAudioNormalizer* instance. This is the (maximum) number of samples, per channel, that will be buffered internally. The `processInplace()` function will **not** return any output samples, until (at least) *this* number of input samples have been read. This also specifies the (maximum) number of samples, per channel, that need to be flushed from the internal buffer, at the end of the process, using the `flushBuffer()` function. **Parameters:** * *delayInSamples*: Receives the size of the internal buffer, in samples (per channel). **Return value:** * Returns ``true`` if everything was successful or ``false`` if something went wrong. ### MDynamicAudioNormalizer::getVersionInfo() [static] ### {-} ``` static void getVersionInfo( uint32_t &major, uint32_t &minor, uint32_t &patch ); ``` This *static* function can be called to determine the Dynamic Audio Normalizer library version. **Parameters:** * *major*: Receives the major version number. Currently this value is **2**. * *minor*: Receives the minor version number. Value will be in the **0** to **99** range. * *patch*: Receives the patch level. Value will be in the **0** to **9** range. ### MDynamicAudioNormalizer::getBuildInfo() [static] ### {-} ``` static void getBuildInfo( const char **date, const char **time, const char **compiler, const char **arch, bool &debug ); ``` This *static* function can be called to determine more detailed information about the specific Dynamic Audio Normalizer build. **Parameters:** * *date*: Receives a pointer to a *read-only* string buffer containing the build date, standard `__DATE__` format. * *time*: Receives a pointer to a *read-only* string buffer containing the build time, standard `__TIME__` format. * *compiler*: Receives a pointer to a *read-only* string buffer containing the compiler identifier (e.g. `MSVC 2013.2`). * *arch*: Receives a pointer to a *read-only* string buffer containing the architecture identifier (e.g. `x86` or `x64`). * *debug*: Will be set to `true` if this is a ***debug*** build; otherwise it will be set to `false`. ### MDynamicAudioNormalizer::setLogFunction() [static] ### {-} ``` static LogFunction *setLogFunction( LogFunction *const logFunction ); ``` This *static* function can be called to register a *callback* function that will be called by the Dynamic Audio Normalizer in order to provide additional log messages. Note that initially **no** callback function will be registered. This means that until a callback function is registered by the application, all log messages will be *discarded*. It is recommend to register your callback function *before* creating the first *MDynamicAudioNormalizer* instance. Also note that at most one callback function can be registered. Registering another callback function replaces the previous one. However, since a pointer to the previous callback function will be returned, multiple callback function can be chained – simply call the previous callback from the new one. **Parameters:** * *logFunction*: A pointer to the new callback function to be registered. This can be ``NULL`` to disable logging entirely. **Return value:** * Returns a pointer to the *previous* callback function. This can be `NULL`, if **no** callback function was registered before. #### Callback Function #### {-} The signature of the callback function must be *exactly* as follows, with standard `cdecl` calling convention: ``` void LogFunction( const int logLevel, const char *const message ); ``` **Parameters:** * *logLevel*: Specifies the "level" of the current log message. This can be either `LOG_LEVEL_DBG = 0`, `LOG_LEVEL_WRN = 1` or `LOG_LEVEL_ERR = 2`. The application may evaluate this value to filter the log messages according to their importance. Log messages of level `LOG_LEVEL_DBG` are for debugging purposes, log messages of level `LOG_LEVEL_WRN` indicate potential problems, and log messages of level `LOG_LEVEL_ERR` indicate serious errors. * *message*: The log message. This is a pointer to a buffer, which contains a NULL-terminated C string. The character encoding of the string is UTF-8. The application should regard this string buffer as *read-only*. Also, this buffer remains valid *only* until the callback function returns. Do **not** save a pointer to this buffer! If you need to retain the log message *after* the callback function returns, it must be *copied*, e.g. via ``strcpy()`` or ``strdup()``, into a *separate* buffer. # Source Code # The source code of the Dynamic Audio Normalizer is available from one of the official [**Git**](http://git-scm.com/) repository mirrors: * ``https://github.com/lordmulder/DynamicAudioNormalizer.git``   ([Browse](https://github.com/lordmulder/DynamicAudioNormalizer)) * ``https://bitbucket.org/muldersoft/dynamic-audio-normalizer.git``   ([Browse](https://bitbucket.org/muldersoft/dynamic-audio-normalizer/overview)) * ``https://gitlab.com/dynamic-audio-normalizer/dynamic-audio-normalizer.git``   ([Browse](https://gitlab.com/dynamic-audio-normalizer/dynamic-audio-normalizer/tree/master)) * ``https://git.assembla.com/dynamicaudionormalizer.git``   ([Browse](https://www.assembla.com/code/dynamicaudionormalizer/git/nodes)) * ``https://muldersoft.codebasehq.com/dynamicaudionormalizer/dynamicaudionormalizer.git``   ([Browse](https://muldersoft.codebasehq.com/changelog/dynamicaudionormalizer/dynamicaudionormalizer)) * ``https://repo.or.cz/DynamicAudioNormalizer.git``   ([Browse](http://repo.or.cz/w/DynamicAudioNormalizer.git)) ## Supported Build Environments ## The following build environments are currently supported: * **Microsoft Windows** with Visual C++, tested with [*Visual Studio 2013*](http://www.visualstudio.com/) and [*Visual Studio 2015*](http://www.visualstudio.com/): - You can build *Dynamic Audio Normalizer* by using the provided *solution* file: `DynamicAudioNormalizer.sln` - Optionally, you may run the deployment script `z_build.bat`, which will build the application in various configurations also create deployment packages. Note that you may need to edit the paths in the build script first! - Be sure that your environment variables `JAVA_HOME` (JDK path) and `QTDIR` (Qt4 path) are set correctly! * **Linux** with GCC/G++ and GNU Make, tested under [*Ubuntu 16.04 LTS*](https://www.ubuntu.com/) and [*openSUSE Leap 42.2*](https://www.opensuse.org/): - You can build *Dynamic Audio Normalizer* by invoking the provided *Makefile* via `make` command. We assume that the essential build tools (*make*, *g++*, *libc*, etc), as contained in Debian's `build-essential` package, are installed. - Optionally, you may pass the `MODE=no-gui` or `MODE=mininmal` options to Make in order to build the software *without* the GUI program or to create a *minimal* build (core library + CLI front-end only), respectively - Be sure that your environment variables `JAVA_HOME` (JDK path) and `QTDIR` (Qt4 path) are set correctly! ## Build Prerequisites ## Building the *Dynamic Audio Normalizer* requires some third-party tools and libraries: * [*POSIX Threads (PThreads)*](http://en.wikipedia.org/wiki/POSIX_Threads) is *always* required (on Windows use [*pthreads-w32*](https://www.sourceware.org/pthreads-win32/), by Ross P. Johnson) * [*libsndfile*](http://www.mega-nerd.com/libsndfile/), by Erik de Castro Lopo, is required for building the command-line program * [*libmpg123*](https://www.mpg123.de/), by Michael Hipp et al., is required for building the command-line program * [*Qt Framework*](http://qt-project.org/), by Qt Project, is required for building the log viewer GUI program (recommended version: Qt 4.x) * [*Java Develpment Kit (JDK)*](http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html), by Oracle, is required for building the JNI bindings (recommended version: JDK 8) * [*Ant*](http://ant.apache.org/), by Apache Software Foundation, is required for building the JNI bindings (recommended version: 1.9.x) * [*VST SDK v2.4*](http://www.steinberg.de/en/company/developer.html), by Steinberg GmbH, is required for building the VST plug-in (it's still included in the VST 3.x SDK!) * [*Winamp SDK*](http://forums.winamp.com/showthread.php?t=252090), by Nullsoft Inc, is required for building the Winamp plug-in (recommended version: 5.55) * [*Pandoc*](http://johnmacfarlane.net/pandoc/), by John MacFarlane, is required for generating the HTML documentation * [*UPX*](http://upx.sourceforge.net/), by Markus Franz Xaver Johannes Oberhumer et al., is required for "packing" the libraries/executables ### Windows ### **Windows** developers are recommended to download our pre-compiled "all-in-one" prerequisites package: * * ### Linux ### **Linux** developers install prerequisites via package manager. We give examples for [*Ubuntu*](https://www.ubuntu.com/), [*openSUSE*](https://www.opensuse.org/) and [*CentOS*](https://www.centos.org/) here: * **Ubuntu 16.04 LTS**: * `sudo apt install build-essential` * `sudo apt install openjdk-8-jdk python3-dev` * `sudo apt install libsndfile-dev libmpg123-dev qt4-default` * `sudo apt install ant pandoc wget` * **openSUSE Leap 42.2**: * `sudo zypper install -t pattern devel_basis` * `sudo zypper install gcc-c++ java-1_8_0-openjdk-devel python3-devel` * `sudo zypper install libsndfile-devel mpg123-devel libqt4-devel` * `sudo zypper install ant pandoc wget` * ***Note:*** The [*mutlimedia:libs*](http://download.opensuse.org/repositories/multimedia:/color_management/openSUSE_Leap_42.2/) repository is required for the *mpg123-devel* package! * **CentOS/RHEL 7.3**: * `sudo yum groupinstall "Development Tools"` * `sudo yum install java-1.8.0-openjdk-devel python3-devel` * `sudo yum install libsndfile-devel libmpg123-devel qt-devel` * `sudo yum install ant pandoc wget` * ***Note:*** The [*EPEL*](https://fedoraproject.org/wiki/EPEL) and [*Nux Dextop*](https://li.nux.ro/repos.html) repositories are required for some packages! # Changelog # ## Version 2.11 (2019-01-03) ## {-} * Core library: Fixed a potential crash due to dereferencing a possibly invalidated iterator * Core library: Use C++11 `std::mutex`, if supported → removes the dependency PThread library * CLI front-end: Added support for decoding Opus input files via *libopusfile* library * CLI front-end: Added new CLI option `--output-bps` to specify the desired *output* bit-depth * Winamp plug-in: Some fixes and improvements; removed old workarounds * Windows binaries: Updated the included libsndfile version to 1.0.28 (2017-04-02) * Windows binaries: Updated build environment to Visual Studio 2017.9 (MSVC 14.16) ## Version 2.10 (2017-04-14) ## {-} * Core library: Added `process()` function, i.e. an "out-of-place" version of `processInplace()` * Implemented [Python](https://www.python.org/) API → Dynamic Audio Normalizer can be used in, e .g., *Python*-based applications * CLI front-end: Added new CLI option `-t` to explicitly specify the desired *output* format * CLI front-end: Added new CLI option `-d` to explicitly specify the desired *input* library * CLI front-end: Added support for decoding input files via *libmpg123* library * CLI front-end: Implemented automatic/heuristic selection of the suitable *input* library * CLI front-end: Properly handle input files that provide more (or less) samples than what was projected * Windows binaries: Updated the included *libsndfile* version to 1.0.27 (2016-06-19) * Windows binaries: Updated build environment to Visual Studio 2015 (MSVC 14.0) ## Version 2.09 (2016-08-01) ## {-} * Core library: Improved pre-filling code in order to avoid possible clipping at the very beginning ## Version 2.08 (2015-01-20) ## {-} * CLI front-end: Very short files (shorter than Gaussian window size) are now handled properly * Core library: Fixed case when ``flushBuffer()`` is called *before* internal buffer is filled entirely * Core library: Workaround for the [*FMA3 bug*](https://connect.microsoft.com/VisualStudio/feedback/details/987093/x64-log-function-uses-vpsrlq-avx-instruction-without-regard-to-operating-system-so-it-crashes-on-vista-x64) in the Microsoft Visual C++ 2013 runtime libraries * Makefile: Various improvements ## Version 2.07 (2014-11-01) ## {-} * Implemented [.NET](http://en.wikipedia.org/wiki/.NET_Framework) API → Dynamic Audio Normalizer can be used in, e .g., *C#*-based applications * Implemented [JNI](http://en.wikipedia.org/wiki/Java_Native_Interface) API → Dynamic Audio Normalizer can be used in *Java*-based applications * Implemented [Pascal](http://en.wikipedia.org/wiki/Object_Pascal) API → Dynamic Audio Normalizer can be used in *Pascal*-based applications * Core library: Added new ``getConfiguration()`` API to retrieve the *active* configuration params * Core library: Fixed a bug that caused the gain factors to *not* progress as "smoothly" as intended ## Version 2.06 (2014-09-22) ## {-} * Implemented [Winamp](http://www.winamp.com/) wrapper → Dynamic Audio Normalizer can now be used as Winamp plug-in * VST wrapper: Fixed potential audio corruptions due to the occasional insertion of "silent" samples * VST wrapper: Fixed a potential "double free" crash in the VST wrapper code * Core library: Fixed `reset()` API to actually work as expected (some state was *not* cleared before) * Core library: Make sure the number of delayed samples remains *constant* throughout the process ## Version 2.05 (2014-09-10) ## {-} * Significant overhaul of the *compression* (thresholding) function * Implemented [VST](http://en.wikipedia.org/wiki/Virtual_Studio_Technology) wrapper → Dynamic Audio Normalizer can now be integrated in any VST host * Added *64-Bit* library and VST plug-in binaries to the Windows release packages * No longer use ``__declspec(thread)``, because it can crash libraries on Windows XP ([details](http://www.nynaeve.net/?p=187)) ## Version 2.04 (2014-08-25) ## {-} * Added an optional input *compression* (thresholding) function * Implemented [SoX](http://sox.sourceforge.net/) wrapper → Dynamic Audio Normalizer can now be used as a SoX effect * Improved internal handling of "raw" PCM data ## Version 2.03 (2014-08-11) ## {-} * Implemented an *optional* RMS-based normalization mode * Added support for "raw" (headerless) audio data * Added pipeline support, i.e. reading from *stdin* or writing to *stdout* * Enabled FLAC/Vorbis support in the *static* Win32 binaries * Various fixes and minor improvements ## Version 2.02 (2014-08-03) ## {-} * Update license → core library is now released under LGPL v2.1 * Enabled FLAC *output* in the command-line program * Show legend in the log viewer program * Some minor documentation and build file updates * There are **no** code changes in the core library in this release ## Version 2.01 (2014-08-01) ## {-} * Added graphical log viewer application to the distribution package * Improved the threshold function for the handling of the maximum gain factor limit * Added a new mode for handling the "boundary" frames (disabled by default) * Much improved the format of the log file ## Version 2.00 (2014-07-26) ## {-} * Implemented a large lookahead buffer, which eliminates the need of 2-Pass processing * Dynamic Audio Normalizer now works with a *single* processing pass → results in up to 2× speed-up! * Removed the ``setPass()`` API, because it is *not* applicable any more * Added new ``flushBuffer()`` API, which provides a cleaner method of flushing the pending frames * Added new ``reset()`` API, which can be used to reset the internal state of the normalizer instance * Added new ``setLogFunction`` API, which can be used to set up a custom logging callback function * There should be **no** changes of the normalized audio output in this release whatsoever ## Version 1.03 (2014-07-09) ## {-} * Added *static* library configuration to Visual Studio solution * Various compatibility fixes for Linux/GCC * Added Makefiles for Linux/GCC, tested under Ubuntu 14.04 LTS * There are **no** functional changes in this release ## Version 1.02 (2014-07-06) ## {-} * First public release of the Dynamic Audio Normalizer. # Frequently Asked Questions (FAQ) ## Q: How does DynAudNorm differ from dynamic range compression? ## {-} A traditional [*audio compressor*](http://en.wikipedia.org/wiki/Dynamic_range_compression) will prune all samples whose magnitude is above a certain threshold. In particular, the portion of the sample's magnitude that is above the pre-defined threshold will be reduced by a certain *ratio*, typically *2:1* or *4:1*. In other words, the signal *peaks* will be *flattened*, while all samples below the threshold are passed through unmodified. This leaves a certain "headroom", i.e. after flattening the signal peaks the maximum magnitude remaining in the *compressed* file will be lower than in the original. For example, if we apply *2:1* reduction to all samples above a threshold of *80%*, then the maximum remaining magnitude will be at *90%*, leaving a headroom of *10%*. After the compression has been applied, the resulting sample values will (usually) be amplified again, by a certain *fixed* gain factor. This factor will be chosen as high as possible *without* exceeding the maximum allowable signal level, similar to a traditional *normalizer*. Clearly, the compression allows for a much stronger amplification of the signal than what would be possible otherwise. However, due to the *flattening* of the signal peaks, the *dynamic range*, i.e. the ratio between the largest and smallest sample value, will be *reduced* significantly – which has a strong tendency to destroy the "vividness" of the audio signal! The excessive use of dynamic range compression in many recent productions is also known as the ["loudness war"](https://www.youtube.com/watch?v=3Gmex_4hreQ). The following waveform view shows an audio signal prior to dynamic range compression (left), after the compression step (center) and after the subsequent amplification step (right). It can be seen that the original audio had a *large* dynamic range, with each drumbeat causing a significant peak. It can also be seen how those peeks have been *eliminated* for the most part after the compression. This makes the drum sound much *less* catchy! Last but not least, it can be seen that the final amplified audio now appears much "louder" than the original, but the dynamics are mostly gone… ![Example of dynamic range compression](img/dyauno/Compression-2.png) In contrast, the Dynamic Audio Normalizer also implements dynamic range compression *of some sort*, but it does **not** prune signal peaks above a *fixed* threshold. Actually it does **not** prune any signal peaks at all! Furthermore, it does **not** amplify the samples by a *fixed* gain factor. Instead, an "optimal" gain factor will be chosen for each *frame*. And, since a frame's gain factor is bounded by the highest magnitude sample within that frame, **100%** of the dynamic range will be preserved *within* each frame! The Dynamic Audio Normalizer only performs a "dynamic range compression" in the sense that the gain factors are *dynamically* adjusted over time, allowing "quieter" frames to get a stronger amplification than "louder" frames. This means that the volume differences between the "quiet" and the "loud" parts of an audio recording will be *harmonized* – but still the *full* dynamic range is being preserved within each of these parts. Finally, the Gaussian filter applied by the Dynamic Audio Normalizer ensures that any changes of the gain factor between neighbouring frames will be smooth and seamlessly, avoiding noticeable "jumps" of the audio volume. ## Q: Why does DynAudNorm *not* seem to change my audio at all? ## {-} If you think that the Dynamic Audio Normalizer is *not* working properly, because it (seemingly) did *not* change your audio at all, you are almost certainly having the *wrong* expectations and the Dynamic Audio Normalizer actually ***is*** working just as it is supposed to work! Please keep in mind, that the Dynamic Audio Normalizer does *not* use compression, by default, which means that all local "peaks" are perfectly preserved. Also, the Dynamic Audio Normalizer *never* amplifies your audio more than what would bring the "loudest" local peak up to the threshold, i.e. *no* peak is ever allowed to exceed the threshold. Furthermore – and that is the important part – the Dynamic Audio Normalizer does **not** simply amplify each *frame* to its local maximum! Instead, it employs a Gaussian filter in order to "smooth" the amplification factors between neighboring frames, which ensures natural volume transitions and avoids noticeable "jumps" of the volume. But this also means that, due to the Gaussian smoothing filter, a particular *frame* may (and often will!) be amplified **less** than what its *local* maximum would allow. Consequently, if the Dynamic Audio Normalizer did *not* change your audio in a noticeable way, it probably means that your audio simply could *not* be amplified any further – with the current Dynamic Audio Normalizer settings. This is **not** a "problem", it is just how the Dynamic Audio Normalizer is designed to work! Also keep in mind that the *default* settings of the Dynamic Audio Normalizer have been chosen rather "conservative", in order to make sure that the filter will *not* hurt the dynamics of the audio. Still, if you think that the Dynamic Audio Normalizer should be acting more "aggressively", you can try tweaking the settings. There are two settings that you may wish to adjust: Try a *smaller* [**filter size**](#gaussian-filter-window-size), or throw in some [**input compression**](#input-compression). The *smaller* the filter size, the *faster* (more aggressively) the filter is going to react. At the same time, *compression* may help to reduce "outstanding" peaks that prevent higher amplification, but too much compression may easily hurt audio quality! ## Q: How to *not* harmonize the "quiet" and "loud" parts? ## {-} If you do *not* want the "quiet" and the "loud" parts of your audio to be harmonized, then the Dynamic Audio Normalizer simply may *not* be the right tool for what you are trying to achieve. It was purposely designed to work like that. Nonetheless, by using a larger [filter size](#gaussian-filter-window-size), the Dynamic Audio Normalizer may be configured to act more similar to a "traditional" normalization filter. ## Q: Why do I get audio reader warnings about more/less samples? ## {-} This warning indicates that the audio reader delivered more/less audio samples than what was initially projected. For most file formats, the projected number of audio samples should be *accurate*, in which case the warning may actually indicate an I/O error. When processing MPEG audio files, however, the projected number of audio samples is only a *rough estimate*. That's because MPEG audio files, like `.mp2` or `.mp3` files, do **not** use a proper file format; they are just a "loose" collection of MPEG frames. Consequently, there is **no** way to accurately determine the number of samples in an MPEG audio file, except for decoding the *entire* file – which would be way too slow. That's why MPEG audio decoders, like ***libmpg123***, will try to *estimate* the total number of samples from the first couple of MPEG frames. Of course, this is **not** always accurate. Consequently, when working with MPEG audio files, the warning about more/less audio samples than what was initially projected being read from the input file is most likely **not** a reason for concern; the warning can safely be *ignored* in that case. But, if the warning occurs with *other* types of audio files, please take care, since there probably was an I/O error! *Note:* The Dynamic Audio Normalizer considers a discrepancy of the audio sample count of more than *25%* as critical error. ## Q: Why does the program crash with GURU MEDITATION error? ## {-} This error message indicates that the program has encountered a serious problem. On possible reason is that your processor does **not** support the [SSE2](http://en.wikipedia.org/wiki/SSE2) instruction set. That's because the official Dynamic Audio Normalizer binaries have been compiled with SSE and SSE2 code enabled – like pretty much any compiler does *by default* nowadays. So without SSE2 support, the program cannot run, obviosuly. This can be fixed either by upgrading your system to a less antiquated processor, or by recompiling Dynamic Audio Normalizer from the sources with SSE2 code generation *disabled*. Note that SSE2 is supported by the Pentium 4 and Athon 64 processors as well as **all** later processors. Also *every* 64-Bit supports SSE2, because [x86-64](http://en.wikipedia.org/wiki/X86-64) has adopted SSE2 as "core" instructions. That means that *every processor from the last decade* almost certainly supports SSE2. If your processor *does* support SSE2, but you still get the above error message, you probably have found a bug. In this case it is highly recommended to create a *debug build* and use a [debugger](http://en.wikipedia.org/wiki/Debugger) in order to track down the cause of the problem. # License Terms # This chapter lists the licenses that apply to the individual components of the Dynamic Audio Normalizer software. ## Dynamic Audio Normalizer Library ## The Dynamic Audio Normalizer **library** (DynamicAudioNormalizerAPI) is released under the ***GNU Lesser General Public License, Version 2.1***. Dynamic Audio Normalizer - Audio Processing Library Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ## Dynamic Audio Normalizer CLI ## The Dynamic Audio Normalizer **command-line program** (DynamicAudioNormalizerCLI) is released under the ***GNU General Public License, Version 2***. Dynamic Audio Normalizer - Audio Processing Utility Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. ## Dynamic Audio Normalizer GUI ## The Dynamic Audio Normalizer **log viewer program** (DynamicAudioNormalizerGUI) is released under the ***GNU General Public License, Version 3***. Dynamic Audio Normalizer - Audio Processing Utility Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ## Dynamic Audio Normalizer Plug-In Wrapper ## The Dynamic Audio Normalizer **plug-in** wrappers for *SoX*, *VST* and *Winamp* are released under the ***MIT/X11 License***. Dynamic Audio Normalizer - Audio Processing Utility Copyright (c) 2014-2019 LoRd_MuldeR . Some rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 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 OR COPYRIGHT HOLDERS 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. # Acknowledgement # The Dynamic Audio Normalizer **CLI program** (DynamicAudioNormalizerCLI) incorporates the following *third-party* software: * [**libsndfile**](http://www.mega-nerd.com/libsndfile/) C library for reading and writing files containing sampled sound through one standard library interface Copyright (C) 1999-2016 Erik de Castro Lopo *Applicable license:* GNU Lesser General Public License, Version 2.1 * [**libmpg123**]() C library for decoding of MPEG 1.0/2.0/2.5 layer I/II/III audio streams to interleaved PCM Copyright (C) 1995-2016 by Michael Hipp, Thomas Orgis, Patrick Dehne, Jonathan Yong and others. *Applicable license:* GNU Lesser General Public License, Version 2.1 The Dynamic Audio Normalizer **log viewer** (DynamicAudioNormalizerGUI) incorporates the following *third-party* software: * [**Qt Framework**](http://qt-project.org/) Cross-platform application and UI framework for developers using C++ or QML, a CSS & JavaScript like language Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies) *Applicable license:* GNU Lesser General Public License, Version 2.1 * [**QCustomPlot**](http://www.qcustomplot.com/) Qt C++ widget for plotting and data visualization that focuses on making good looking, publication quality 2D plots Copyright (C) 2011-2014 Emanuel Eichhammer *Applicable license:* GNU General Public License, Version 3 The Dynamic Audio Normalizer **VST wrapper** (DynamicAudioNormalizerVST) incorporates the following *third-party* software: * [**Spooky Hash V2**](http://burtleburtle.net/bob/hash/spooky.html) Public domain noncryptographic hash function producing well-distributed 128-bit hash values Created by Bob Jenkins, 2012. *Applicable license:* None / Public Domain The Dynamic Audio Normalizer can operate as a **plug-in** (effect) using the following *third-party* technologies: * [**Sound eXchange**](http://sox.sourceforge.net/) Cross-platform command line utility that can convert various formats of computer audio files in to other formats Copyright (C) 1998-2009 Chris Bagwell and SoX contributors * [**Virtual Studio Technology (VST 2.x)**](http://en.wikipedia.org/wiki/Virtual_Studio_Technology) Software interface that integrates software audio synthesizer and effect Plug-ins with audio editors and recording systems. Copyright (C) 2006 Steinberg Media Technologies. All Rights Reserved. **VST PlugIn Interface Technology by Steinberg Media Technologies GmbH. VST is a trademark of Steinberg Media Technologies GmbH.** * [**Winamp**](http://www.winamp.com/) Popular media player for Windows, Android, and OS X that supports extensibility with plug-ins and skins. Copyright (C) 1997-2013 Nullsoft, Inc. All Rights Reserved.     e.o.f. ================================================ FILE: etc/vst_sdk/VST_SDK_INFO.txt ================================================ VST SDK Installation Instructions ================================= Please put the VST SDK files (v2.4) into this directory. These files are NOT redistributed for legal reasons, but can be downloaded from the Steinberg web-site: http://www.steinberg.net/en/company/developers.html After you have extracted the VST SDK files (v2.4), there should be *two* sub-directories inside the "vst_sdk" directory: (1) "pluginterfaces" (2) "public.sdk" Note that VST v3.x is not currently used or supported, however the v3.x SDK also includes the required v2.4 files. Acknowledgement: ---------------- (1) VST PlugIn Interface Technology by Steinberg Media Technologies GmbH. (2) VST is a trademark of Steinberg Media Technologies GmbH. ================================================ FILE: etc/winamp_sdk/LICENSE.txt ================================================ Copyright 1999-2001 Nullsoft, Inc. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Brennan Underwood brennan@nullsoft.com ================================================ FILE: etc/winamp_sdk/include/winamp_dsp.h ================================================ #ifndef NULLSOFT_WINAMP_DSP_H #define NULLSOFT_WINAMP_DSP_H // DSP plugin interface // notes: // any window that remains in foreground should optimally pass unused // keystrokes to the parent (winamp's) window, so that the user // can still control it. As for storing configuration, // Configuration data should be stored in \plugin.ini // (look at the vis plugin for configuration code) typedef struct winampDSPModule { char *description; // description HWND hwndParent; // parent window (filled in by calling app) HINSTANCE hDllInstance; // instance handle to this DLL (filled in by calling app) void (*Config)(struct winampDSPModule *this_mod); // configuration dialog (if needed) int (*Init)(struct winampDSPModule *this_mod); // 0 on success, creates window, etc (if needed) // modify waveform samples: returns number of samples to actually write // (typically numsamples, but no more than twice numsamples, and no less than half numsamples) // numsamples should always be at least 128. should, but I'm not sure int (*ModifySamples)(struct winampDSPModule *this_mod, short int *samples, int numsamples, int bps, int nch, int srate); void (*Quit)(struct winampDSPModule *this_mod); // called when unloading void *userData; // user data, optional } winampDSPModule; typedef struct { int version; // DSP_HDRVER char *description; // description of library winampDSPModule* (*getModule)(int); // module retrieval function int (*sf)(int key); // DSP_HDRVER == 0x21 } winampDSPHeader; // exported symbols #ifdef USE_DSP_HDR_HWND typedef winampDSPHeader* (*winampDSPGetHeaderType)(HWND); #define DSP_HDRVER 0x22 #else typedef winampDSPHeader* (*winampDSPGetHeaderType)(HWND); // header version: 0x20 == 0.20 == winamp 2.0 #define DSP_HDRVER 0x20 #endif // return values from the winampUninstallPlugin(HINSTANCE hdll, HWND parent, int param) // which determine if we can uninstall the plugin immediately or on winamp restart #define DSP_PLUGIN_UNINSTALL_NOW 0x0 #define DSP_PLUGIN_UNINSTALL_REBOOT 0x1 // // uninstall support was added from 5.0+ and uninstall now support from 5.5+ // it is down to you to ensure that if uninstall now is returned that it will not cause a crash // (ie don't use if you've been subclassing the main window) // Version note: // // Added passing of Winamp's main hwnd in the call to the exported winampDSPHeader() // which allows for primarily the use of localisation features with the bundled plugins. // If you want to use the new version then either you can edit you version of dsp.h or // you can add USE_DSP_HDR_HWND to your project's defined list or before use of dsp.h // #endif ================================================ FILE: etc/winamp_sdk/include/winamp_ipc.h ================================================ /* ** Copyright (C) 1997-2008 Nullsoft, Inc. ** ** This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held ** liable for any damages arising from the use of this software. ** ** Permission is granted to anyone to use this software for any purpose, including commercial applications, and to ** alter it and redistribute it freely, subject to the following restrictions: ** ** 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. ** If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. ** ** 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. ** ** 3. This notice may not be removed or altered from any source distribution. ** */ #ifndef _WA_IPC_H_ #define _WA_IPC_H_ #include #include #if (_MSC_VER <= 1200) typedef int intptr_t; #endif /* ** This is the modern replacement for the classic 'frontend.h'. Most of these ** updates are designed for in-process use, i.e. from a plugin. ** */ /* Most of the IPC_* messages involve sending the message in the form of: ** result = SendMessage(hwnd_winamp,WM_WA_IPC,(parameter),IPC_*); ** Where different then this is specified (typically with WM_COPYDATA variants) ** ** When you use SendMessage(hwnd_winamp,WM_WA_IPC,(parameter),IPC_*) and specify a IPC_* ** which is not currently implemented/supported by the Winamp version being used then it ** will return 1 for 'result'. This is a good way of helping to check if an api being ** used which returns a function pointer, etc is even going to be valid. */ #define WM_WA_IPC WM_USER #define WINAMP_VERSION_MAJOR(winampVersion) ((winampVersion & 0x0000FF00) >> 12) #define WINAMP_VERSION_MINOR(winampVersion) (winampVersion & 0x000000FF) // returns, i.e. 0x12 for 5.12 and 0x10 for 5.1... #define IPC_GETVERSION 0 /* int version = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION); ** ** The version returned will be 0x20yx for Winamp 2.yx. ** Versions previous to Winamp 2.0 typically (but not always) use 0x1zyx for 1.zx. ** Just a bit weird but that's the way it goes. ** ** For Winamp 5.x it uses the format 0x50yx for Winamp 5.yx ** e.g. 5.01 -> 0x5001 ** 5.09 -> 0x5009 ** 5.1 -> 0x5010 ** ** Notes: For 5.02 this api will return the same value as for a 5.01 build. ** For 5.07 this api will return the same value as for a 5.06 build. */ #define IPC_GETVERSIONSTRING 1 #define IPC_GETREGISTEREDVERSION 770 /* (requires Winamp 5.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETREGISTEREDVERSION); ** ** This will open the Winamp Preferences and show the Winamp Pro page. */ typedef struct { const char *filename; const char *title; int length; } enqueueFileWithMetaStruct; // send this to a IPC_PLAYFILE in a non WM_COPYDATA, // and you get the nice desired result. if title is NULL, it is treated as a "thing", // otherwise it's assumed to be a file (for speed) typedef struct { const wchar_t *filename; const wchar_t *title; int length; } enqueueFileWithMetaStructW; #define IPC_PLAYFILE 100 // dont be fooled, this is really the same as enqueufile #define IPC_ENQUEUEFILE 100 #define IPC_PLAYFILEW 1100 #define IPC_ENQUEUEFILEW 1100 /* This is sent as a WM_COPYDATA with IPC_PLAYFILE as the dwData member and the string ** of the file / playlist to be enqueued into the playlist editor as the lpData member. ** This will just enqueue the file or files since you can use this to enqueue a playlist. ** It will not clear the current playlist or change the playback state. ** ** COPYDATASTRUCT cds = {0}; ** cds.dwData = IPC_ENQUEUEFILE; ** cds.lpData = (void*)"c:\\test\\folder\\test.mp3"; ** cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char ** SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds); ** ** ** With 2.9+ and all of the 5.x versions you can send this as a normal WM_WA_IPC ** (non WM_COPYDATA) with an enqueueFileWithMetaStruct as the param. ** If the title member is null then it is treated as a "thing" otherwise it will be ** assumed to be a file (for speed). ** ** enqueueFileWithMetaStruct eFWMS = {0}; ** eFWMS.filename = "c:\\test\\folder\\test.mp3"; ** eFWMS.title = "Whipping Good"; ** eFWMS.length = 300; // this is the number of seconds for the track ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&eFWMS,IPC_ENQUEUEFILE); */ #define IPC_DELETE 101 #define IPC_DELETE_INT 1101 /* SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_DELETE); ** Use this api to clear Winamp's internal playlist. ** You should not need to use IPC_DELETE_INT since it is used internally by Winamp when ** it is dealing with some lame Windows Explorer issues (hard to believe that!). */ #define IPC_STARTPLAY 102 #define IPC_STARTPLAY_INT 1102 /* SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_STARTPLAY); ** Sending this will start playback and is almost the same as hitting the play button. ** The IPC_STARTPLAY_INT version is used internally and you should not need to use it ** since it won't be any fun. */ #define IPC_CHDIR 103 /* This is sent as a WM_COPYDATA type message with IPC_CHDIR as the dwData value and the ** directory you want to change to as the lpData member. ** ** COPYDATASTRUCT cds = {0}; ** cds.dwData = IPC_CHDIR; ** cds.lpData = (void*)"c:\\download"; ** cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char ** SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds); ** ** The above example will make Winamp change to the directory 'C:\download'. */ #define IPC_ISPLAYING 104 /* int res = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISPLAYING); ** This is sent to retrieve the current playback state of Winamp. ** If it returns 1, Winamp is playing. ** If it returns 3, Winamp is paused. ** If it returns 0, Winamp is not playing. */ #define IPC_GETOUTPUTTIME 105 /* int res = SendMessage(hwnd_winamp,WM_WA_IPC,mode,IPC_GETOUTPUTTIME); ** This api can return two different sets of information about current playback status. ** ** If mode = 0 then it will return the position (in ms) of the currently playing track. ** Will return -1 if Winamp is not playing. ** ** If mode = 1 then it will return the current track length (in seconds). ** Will return -1 if there are no tracks (or possibly if Winamp cannot get the length). ** ** If mode = 2 then it will return the current track length (in milliseconds). ** Will return -1 if there are no tracks (or possibly if Winamp cannot get the length). */ #define IPC_JUMPTOTIME 106 /* (requires Winamp 1.60+) ** SendMessage(hwnd_winamp,WM_WA_IPC,ms,IPC_JUMPTOTIME); ** This api sets the current position (in milliseconds) for the currently playing song. ** The resulting playback position may only be an approximate time since some playback ** formats do not provide exact seeking e.g. mp3 ** This returns -1 if Winamp is not playing, 1 on end of file, or 0 if it was successful. */ #define IPC_GETMODULENAME 109 #define IPC_EX_ISRIGHTEXE 666 /* usually shouldnt bother using these, but here goes: ** send a WM_COPYDATA with IPC_GETMODULENAME, and an internal ** flag gets set, which if you send a normal WM_WA_IPC message with ** IPC_EX_ISRIGHTEXE, it returns whether or not that filename ** matches. lame, I know. */ #define IPC_WRITEPLAYLIST 120 /* (requires Winamp 1.666+) ** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_WRITEPLAYLIST); ** ** IPC_WRITEPLAYLIST will write the current playlist to '\\Winamp.m3u' and ** will also return the current playlist position (see IPC_GETLISTPOS). ** ** This is kinda obsoleted by some of the newer 2.x api items but it still is good for ** use with a front-end program (instead of a plug-in) and you want to see what is in the ** current playlist. ** ** This api will only save out extended file information in the #EXTINF entry if Winamp ** has already read the data such as if the file was played of scrolled into view. If ** Winamp has not read the data then you will only find the file with its filepath entry ** (as is the base requirements for a m3u playlist). */ #define IPC_SETPLAYLISTPOS 121 /* (requires Winamp 2.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,position,IPC_SETPLAYLISTPOS) ** IPC_SETPLAYLISTPOS sets the playlist position to the specified 'position'. ** It will not change playback status or anything else. It will just set the current ** position in the playlist and will update the playlist view if necessary. ** ** If you use SendMessage(hwnd_winamp,WM_COMMAND,MAKEWPARAM(WINAMP_BUTTON2,0),0); ** after using IPC_SETPLAYLISTPOS then Winamp will start playing the file at 'position'. */ #define IPC_SETVOLUME 122 /* (requires Winamp 2.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,volume,IPC_SETVOLUME); ** IPC_SETVOLUME sets the volume of Winamp (between the range of 0 to 255). ** ** If you pass 'volume' as -666 then the message will return the current volume. ** int curvol = SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETVOLUME); */ #define IPC_GETVOLUME(hwnd_winamp) SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETVOLUME) /* (requires Winamp 2.0+) ** int curvol = IPC_GETVOLUME(hwnd_winamp); ** This will return the current volume of Winamp or */ #define IPC_SETPANNING 123 /* (requires Winamp 2.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,panning,IPC_SETPANNING); ** IPC_SETPANNING sets the panning of Winamp from 0 (left) to 255 (right). ** ** At least in 5.x+ this works from -127 (left) to 127 (right). ** ** If you pass 'panning' as -666 to this api then it will return the current panning. ** int curpan = SendMessage(hwnd_winamp,WM_WA_IPC,-666,IPC_SETPANNING); */ #define IPC_GETLISTLENGTH 124 /* (requires Winamp 2.0+) ** int length = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTLENGTH); ** IPC_GETLISTLENGTH returns the length of the current playlist as the number of tracks. */ #define IPC_GETLISTPOS 125 /* (requires Winamp 2.05+) ** int pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS); ** IPC_GETLISTPOS returns the current playlist position (which is shown in the playlist ** editor as a differently coloured text entry e.g is yellow for the classic skin). ** ** This api is a lot like IPC_WRITEPLAYLIST but a lot faster since it does not have to ** write out the whole of the current playlist first. */ #define IPC_GETINFO 126 /* (requires Winamp 2.05+) ** int inf=SendMessage(hwnd_winamp,WM_WA_IPC,mode,IPC_GETINFO); ** IPC_GETINFO returns info about the current playing song. The value ** it returns depends on the value of 'mode'. ** Mode Meaning ** ------------------ ** 0 Samplerate, in kilohertz (i.e. 44) ** 1 Bitrate (i.e. 128) ** 2 Channels (i.e. 2) ** 3 (5+) Video LOWORD=w HIWORD=h ** 4 (5+) > 65536, string (video description) ** 5 (5.25+) Samplerate, in hertz (i.e. 44100) */ #define IPC_GETEQDATA 127 /* (requires Winamp 2.05+) ** int data=SendMessage(hwnd_winamp,WM_WA_IPC,pos,IPC_GETEQDATA); ** IPC_GETEQDATA queries the status of the EQ. ** The value returned depends on what 'pos' is set to: ** Value Meaning ** ------------------ ** 0-9 The 10 bands of EQ data. 0-63 (+20db - -20db) ** 10 The preamp value. 0-63 (+20db - -20db) ** 11 Enabled. zero if disabled, nonzero if enabled. ** 12 Autoload. zero if disabled, nonzero if enabled. */ #define IPC_SETEQDATA 128 /* (requires Winamp 2.05+) ** SendMessage(hwnd_winamp,WM_WA_IPC,pos,IPC_GETEQDATA); ** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SETEQDATA); ** IPC_SETEQDATA sets the value of the last position retrieved ** by IPC_GETEQDATA. This is pretty lame, and we should provide ** an extended version that lets you do a MAKELPARAM(pos,value). ** someday... new (2.92+): if the high byte is set to 0xDB, then the third byte specifies which band, and the bottom word specifies the value. */ #define IPC_ADDBOOKMARK 129 #define IPC_ADDBOOKMARKW 131 /* (requires Winamp 2.4+) ** This is sent as a WM_COPYDATA using IPC_ADDBOOKMARK as the dwData value and the ** directory you want to change to as the lpData member. This will add the specified ** file / url to the Winamp bookmark list. ** ** COPYDATASTRUCT cds = {0}; ** cds.dwData = IPC_ADDBOOKMARK; ** cds.lpData = (void*)"http://www.blah.com/listen.pls"; ** cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char ** SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds); ** ** ** In Winamp 5.0+ we use this as a normal WM_WA_IPC and the string is null separated as ** the filename and then the title of the entry. ** ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(char*)"filename\0title\0",IPC_ADDBOOKMARK); ** ** This will notify the library / bookmark editor that a bookmark was added. ** Note that using this message in this context does not actually add the bookmark. ** Do not use, it is essentially just a notification type message :) */ #define IPC_INSTALLPLUGIN 130 /* This is not implemented (and is very unlikely to be done due to safety concerns). ** If it was then you could do a WM_COPYDATA with a path to a .wpz and it would then ** install the plugin for you. ** ** COPYDATASTRUCT cds = {0}; ** cds.dwData = IPC_INSTALLPLUGIN; ** cds.lpData = (void*)"c:\\path\\to\\file.wpz"; ** cds.cbData = lstrlen((char*)cds.lpData)+1; // include space for null char ** SendMessage(hwnd_winamp,WM_COPYDATA,0,(LPARAM)&cds); */ #define IPC_RESTARTWINAMP 135 /* (requires Winamp 2.2+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_RESTARTWINAMP); ** IPC_RESTARTWINAMP will restart Winamp (isn't that obvious ? :) ) ** If this fails to make Winamp start after closing then there is a good chance one (or ** more) of the currently installed plugins caused Winamp to crash on exit (either as a ** silent crash or a full crash log report before it could call itself start again. */ #define IPC_ISFULLSTOP 400 /* (requires winamp 2.7+ I think) ** int ret=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISFULLSTOP); ** This is useful for when you're an output plugin and you want to see if the stop/close ** happening is a full stop or if you are just between tracks. This returns non zero if ** it is a full stop or zero if it is just a new track. ** benski> i think it's actually the other way around - ** !0 for EOF and 0 for user pressing stop */ #define IPC_INETAVAILABLE 242 /* (requires Winamp 2.05+) ** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INETAVAILABLE); ** IPC_INETAVAILABLE will return 1 if an Internet connection is available for Winamp and ** relates to the internet connection type setting on the main general preferences page ** in the Winamp preferences. */ #define IPC_UPDTITLE 243 /* (requires Winamp 2.2+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_UPDTITLE); ** IPC_UPDTITLE will ask Winamp to update the information about the current title and ** causes GetFileInfo(..) in the input plugin associated with the current playlist entry ** to be called. This can be called such as when an input plugin is buffering a file so ** that it can cause the buffer percentage to appear in the playlist. */ #define IPC_REFRESHPLCACHE 247 /* (requires Winamp 2.2+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_REFRESHPLCACHE); ** IPC_REFRESHPLCACHE will flush the playlist cache buffer and you send this if you want ** Winamp to go refetch the titles for all of the entries in the current playlist. ** ** 5.3+: pass a wchar_t * string in wParam, and it'll do a strnicmp() before clearing the cache */ #define IPC_GET_SHUFFLE 250 /* (requires Winamp 2.4+) ** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_SHUFFLE); ** IPC_GET_SHUFFLE returns the status of the shuffle option. ** If set then it will return 1 and if not set then it will return 0. */ #define IPC_GET_REPEAT 251 /* (requires Winamp 2.4+) ** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_REPEAT); ** IPC_GET_REPEAT returns the status of the repeat option. ** If set then it will return 1 and if not set then it will return 0. */ #define IPC_SET_SHUFFLE 252 /* (requires Winamp 2.4+) ** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_SHUFFLE); ** IPC_SET_SHUFFLE sets the status of the shuffle option. ** If 'value' is 1 then shuffle is turned on. ** If 'value' is 0 then shuffle is turned off. */ #define IPC_SET_REPEAT 253 /* (requires Winamp 2.4+) ** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_REPEAT); ** IPC_SET_REPEAT sets the status of the repeat option. ** If 'value' is 1 then shuffle is turned on. ** If 'value' is 0 then shuffle is turned off. */ #define IPC_ENABLEDISABLE_ALL_WINDOWS 259 // 0xdeadbeef to disable /* (requires Winamp 2.9+) ** SendMessage(hwnd_winamp,WM_WA_IPC,(enable?0:0xdeadbeef),IPC_ENABLEDISABLE_ALL_WINDOWS); ** Sending this message with 0xdeadbeef as the param will disable all winamp windows and ** any other values will enable all of the Winamp windows again. When disabled you won't ** get any response on clicking or trying to do anything to the Winamp windows. If the ** taskbar icon is shown then you may still have control ;) */ #define IPC_GETWND 260 /* (requires Winamp 2.9+) ** HWND h=SendMessage(hwnd_winamp,WM_WA_IPC,IPC_GETWND_xxx,IPC_GETWND); ** returns the HWND of the window specified. */ #define IPC_GETWND_EQ 0 // use one of these for the param #define IPC_GETWND_PE 1 #define IPC_GETWND_MB 2 #define IPC_GETWND_VIDEO 3 #define IPC_ISWNDVISIBLE 261 // same param as IPC_GETWND /************************************************************************ ***************** in-process only (WE LOVE PLUGINS) ************************************************************************/ #define IPC_SETSKINW 199 #define IPC_SETSKIN 200 /* (requires Winamp 2.04+, only usable from plug-ins (not external apps)) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)"skinname",IPC_SETSKIN); ** IPC_SETSKIN sets the current skin to "skinname". Note that skinname ** can be the name of a skin, a skin .zip file, with or without path. ** If path isn't specified, the default search path is the winamp skins ** directory. */ #define IPC_GETSKIN 201 #define IPC_GETSKINW 1201 /* (requires Winamp 2.04+, only usable from plug-ins (not external apps)) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)skinname_buffer,IPC_GETSKIN); ** IPC_GETSKIN puts the directory where skin bitmaps can be found ** into skinname_buffer. ** skinname_buffer must be MAX_PATH characters in length. ** When using a .zip'd skin file, it'll return a temporary directory ** where the ZIP was decompressed. */ #define IPC_EXECPLUG 202 /* (requires Winamp 2.04+, only usable from plug-ins (not external apps)) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)"vis_file.dll",IPC_EXECPLUG); ** IPC_EXECPLUG executes a visualization plug-in pointed to by WPARAM. ** the format of this string can be: ** "vis_whatever.dll" ** "vis_whatever.dll,0" // (first mod, file in winamp plug-in dir) ** "C:\\dir\\vis_whatever.dll,1" */ #define IPC_GETPLAYLISTFILE 211 #define IPC_GETPLAYLISTFILEW 214 /* (requires Winamp 2.04+, only usable from plug-ins (not external apps)) ** char *name=SendMessage(hwnd_winamp,WM_WA_IPC,index,IPC_GETPLAYLISTFILE); ** IPC_GETPLAYLISTFILE gets the filename of the playlist entry [index]. ** returns a pointer to it. returns NULL on error. */ #define IPC_GETPLAYLISTTITLE 212 #define IPC_GETPLAYLISTTITLEW 213 /* (requires Winamp 2.04+, only usable from plug-ins (not external apps)) ** char *name=SendMessage(hwnd_winamp,WM_WA_IPC,index,IPC_GETPLAYLISTTITLE); ** ** IPC_GETPLAYLISTTITLE gets the title of the playlist entry [index]. ** returns a pointer to it. returns NULL on error. */ #define IPC_GETHTTPGETTER 240 /* retrieves a function pointer to a HTTP retrieval function. ** if this is unsupported, returns 1 or 0. ** the function should be: ** int (*httpRetrieveFile)(HWND hwnd, char *url, char *file, char *dlgtitle); ** if you call this function, with a parent window, a URL, an output file, and a dialog title, ** it will return 0 on successful download, 1 on error. */ #define IPC_GETHTTPGETTERW 1240 /* int (*httpRetrieveFileW)(HWND hwnd, char *url, wchar_t *file, wchar_t *dlgtitle); */ #define IPC_MBOPEN 241 /* (requires Winamp 2.05+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_MBOPEN); ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)url,IPC_MBOPEN); ** IPC_MBOPEN will open a new URL in the minibrowser. if url is NULL, it will open the Minibrowser window. */ #define IPC_CHANGECURRENTFILE 245 /* (requires Winamp 2.05+) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)file,IPC_CHANGECURRENTFILE); ** IPC_CHANGECURRENTFILE will set the current playlist item. */ #define IPC_CHANGECURRENTFILEW 1245 /* (requires Winamp 5.3+) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)file,IPC_CHANGECURRENTFILEW); ** IPC_CHANGECURRENTFILEW will set the current playlist item. */ #define IPC_GETMBURL 246 /* (requires Winamp 2.2+) ** char buffer[4096]; // Urls can be VERY long ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)buffer,IPC_GETMBURL); ** IPC_GETMBURL will retrieve the current Minibrowser URL into buffer. ** buffer must be at least 4096 bytes long. */ #define IPC_MBBLOCK 248 /* (requires Winamp 2.4+) ** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_MBBLOCK); ** ** IPC_MBBLOCK will block the Minibrowser from updates if value is set to 1 */ #define IPC_MBOPENREAL 249 /* (requires Winamp 2.4+) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)url,IPC_MBOPENREAL); ** ** IPC_MBOPENREAL works the same as IPC_MBOPEN except that it will works even if ** IPC_MBBLOCK has been set to 1 */ #define IPC_ADJUST_OPTIONSMENUPOS 280 /* (requires Winamp 2.9+) ** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_OPTIONSMENUPOS); ** moves where winamp expects the Options menu in the main menu. Useful if you wish to insert a ** menu item above the options/skins/vis menus. */ #define IPC_GET_HMENU 281 /* (requires Winamp 2.9+) ** HMENU hMenu=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)0,IPC_GET_HMENU); ** values for data: ** 0 : main popup menu ** 1 : main menubar file menu ** 2 : main menubar options menu ** 3 : main menubar windows menu ** 4 : main menubar help menu ** other values will return NULL. */ #define IPC_GET_EXTENDED_FILE_INFO 290 //pass a pointer to the following struct in wParam #define IPC_GET_EXTENDED_FILE_INFO_HOOKABLE 296 /* (requires Winamp 2.9+) ** to use, create an extendedFileInfoStruct, point the values filename and metadata to the ** filename and metadata field you wish to query, and ret to a buffer, with retlen to the ** length of that buffer, and then SendMessage(hwnd_winamp,WM_WA_IPC,&struct,IPC_GET_EXTENDED_FILE_INFO); ** the results should be in the buffer pointed to by ret. ** returns 1 if the decoder supports a getExtendedFileInfo method */ typedef struct { const char *filename; const char *metadata; char *ret; size_t retlen; } extendedFileInfoStruct; #define IPC_GET_BASIC_FILE_INFO 291 //pass a pointer to the following struct in wParam typedef struct { const char *filename; int quickCheck; // set to 0 to always get, 1 for quick, 2 for default (if 2, quickCheck will be set to 0 if quick wasnot used) // filled in by winamp int length; char *title; int titlelen; } basicFileInfoStruct; #define IPC_GET_BASIC_FILE_INFOW 1291 //pass a pointer to the following struct in wParam typedef struct { const wchar_t *filename; int quickCheck; // set to 0 to always get, 1 for quick, 2 for default (if 2, quickCheck will be set to 0 if quick wasnot used) // filled in by winamp int length; wchar_t *title; int titlelen; } basicFileInfoStructW; #define IPC_GET_EXTLIST 292 //returns doublenull delimited. GlobalFree() it when done. if data is 0, returns raw extlist, if 1, returns something suitable for getopenfilename #define IPC_GET_EXTLISTW 1292 // wide char version of above #define IPC_INFOBOX 293 typedef struct { HWND parent; char *filename; } infoBoxParam; #define IPC_INFOBOXW 1293 typedef struct { HWND parent; const wchar_t *filename; } infoBoxParamW; #define IPC_SET_EXTENDED_FILE_INFO 294 //pass a pointer to the a extendedFileInfoStruct in wParam /* (requires Winamp 2.9+) ** to use, create an extendedFileInfoStruct, point the values filename and metadata to the ** filename and metadata field you wish to write in ret. (retlen is not used). and then ** SendMessage(hwnd_winamp,WM_WA_IPC,&struct,IPC_SET_EXTENDED_FILE_INFO); ** returns 1 if the metadata is supported ** Call IPC_WRITE_EXTENDED_FILE_INFO once you're done setting all the metadata you want to update */ #define IPC_WRITE_EXTENDED_FILE_INFO 295 /* (requires Winamp 2.9+) ** writes all the metadata set thru IPC_SET_EXTENDED_FILE_INFO to the file ** returns 1 if the file has been successfully updated, 0 if error */ #define IPC_FORMAT_TITLE 297 typedef struct { char *spec; // NULL=default winamp spec void *p; char *out; int out_len; char * (*TAGFUNC)(const char * tag, void * p); //return 0 if not found void (*TAGFREEFUNC)(char * tag,void * p); } waFormatTitle; #define IPC_FORMAT_TITLE_EXTENDED 298 // similiar to IPC_FORMAT_TITLE, but falls back to Winamp's %tags% if your passed tag function doesn't handle it typedef struct { const wchar_t *filename; int useExtendedInfo; // set to 1 if you want the Title Formatter to query the input plugins for any tags that your tag function fails on const wchar_t *spec; // NULL=default winamp spec void *p; wchar_t *out; int out_len; wchar_t * (*TAGFUNC)(const wchar_t * tag, void * p); //return 0 if not found, -1 for empty tag void (*TAGFREEFUNC)(wchar_t *tag, void *p); } waFormatTitleExtended; #define IPC_COPY_EXTENDED_FILE_INFO 299 typedef struct { const char *source; const char *dest; } copyFileInfoStruct; #define IPC_COPY_EXTENDED_FILE_INFOW 1299 typedef struct { const wchar_t *source; const wchar_t *dest; } copyFileInfoStructW; typedef struct { int (*inflateReset)(void *strm); int (*inflateInit_)(void *strm,const char *version, int stream_size); int (*inflate)(void *strm, int flush); int (*inflateEnd)(void *strm); unsigned long (*crc32)(unsigned long crc, const unsigned char *buf, unsigned int len); } wa_inflate_struct; #define IPC_GETUNCOMPRESSINTERFACE 331 /* returns a function pointer to uncompress(). ** int (*uncompress)(unsigned char *dest, unsigned long *destLen, const unsigned char *source, unsigned long sourceLen); ** right out of zlib, useful for decompressing zlibbed data. ** if you pass the parm of 0x10100000, it will return a wa_inflate_struct * to an inflate API. */ typedef struct _prefsDlgRec { HINSTANCE hInst; // dll instance containing the dialog resource int dlgID; // resource identifier of the dialog void *proc; // window proceedure for handling the dialog defined as // LRESULT CALLBACK PrefsPage(HWND,UINT,WPARAM,LPARAM) char *name; // name shown for the prefs page in the treelist intptr_t where; // section in the treelist the prefs page is to be added to // 0 for General Preferences // 1 for Plugins // 2 for Skins // 3 for Bookmarks (no longer in the 5.0+ prefs) // 4 for Prefs (the old 'Setup' section - no longer in 5.0+) intptr_t _id; struct _prefsDlgRec *next; // no longer implemented as a linked list, now used by Winamp for other means } prefsDlgRec; typedef struct _prefsDlgRecW { HINSTANCE hInst; // dll instance containing the dialog resource int dlgID; // resource identifier of the dialog void *proc; // window proceedure for handling the dialog defined as // LRESULT CALLBACK PrefsPage(HWND,UINT,WPARAM,LPARAM) wchar_t *name; // name shown for the prefs page in the treelist intptr_t where; // section in the treelist the prefs page is to be added to // 0 for General Preferences // 1 for Plugins // 2 for Skins // 3 for Bookmarks (no longer in the 5.0+ prefs) // 4 for Prefs (the old 'Setup' section - no longer in 5.0+) intptr_t _id; struct _prefsDlgRec *next; // no longer implemented as a linked list, now used by Winamp for other means } prefsDlgRecW; #define IPC_ADD_PREFS_DLG 332 #define IPC_ADD_PREFS_DLGW 1332 #define IPC_REMOVE_PREFS_DLG 333 /* (requires Winamp 2.9+) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_ADD_PREFS_DLG); ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_REMOVE_PREFS_DLG); ** ** IPC_ADD_PREFS_DLG: ** To use this you need to allocate a prefsDlgRec structure (either on the heap or with ** some global data but NOT on the stack) and then initialise the members of the structure ** (see the definition of the prefsDlgRec structure above). ** ** hInst - dll instance of where the dialog resource is located. ** dlgID - id of the dialog resource. ** proc - dialog window procedure for the prefs dialog. ** name - name of the prefs page as shown in the preferences list. ** where - see above for the valid locations the page can be added. ** ** Then you do SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_ADD_PREFS_DLG); ** ** example: ** ** prefsDlgRec* prefsRec = 0; ** prefsRec = GlobalAlloc(GPTR,sizeof(prefsDlgRec)); ** prefsRec->hInst = hInst; ** prefsRec->dlgID = IDD_PREFDIALOG; ** prefsRec->name = "Pref Page"; ** prefsRec->where = 0; ** prefsRec->proc = PrefsPage; ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_ADD_PREFS_DLG); ** ** ** IPC_REMOVE_PREFS_DLG: ** To use you pass the address of the same prefsRec you used when adding the prefs page ** though you shouldn't really ever have to do this but it's good to clean up after you ** when you're plugin is being unloaded. ** ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_REMOVE_PREFS_DLG); ** ** IPC_ADD_PREFS_DLGW ** requires Winamp 5.53+ */ #define IPC_OPENPREFSTOPAGE 380 /* SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&prefsRec,IPC_OPENPREFSTOPAGE); ** ** There are two ways of opening a preferences page. ** ** The first is to pass an id of a builtin preferences page (see below for ids) or a ** &prefsDlgRec of the preferences page to open and this is normally done if you are ** opening a prefs page you added yourself. ** ** If the page id does not or the &prefsRec is not valid then the prefs dialog will be ** opened to the first page available (usually the Winamp Pro page). ** ** (requires Winamp 5.04+) ** Passing -1 for param will open the preferences dialog to the last page viewed. ** ** Note: v5.0 to 5.03 had a bug in this api ** ** On the first call then the correct prefs page would be opened to but on the next call ** the prefs dialog would be brought to the front but the page would not be changed to the ** specified. ** In 5.04+ it will change to the prefs page specified if the prefs dialog is already open. */ /* Builtin Preference page ids (valid for 5.0+) ** (stored in the lParam member of the TVITEM structure from the tree item) ** ** These can be useful if you want to detect a specific prefs page and add things to it ** yourself or something like that ;) ** ** Winamp Pro 20 ** General Preferences 0 ** File Types 1 ** Playlist 23 ** Titles 21 ** Playback 42 (added in 5.25) ** Station Info 41 (added in 5.11 & removed in 5.5) ** Video 24 ** Localization 25 (added in 5.5) ** Skins 40 ** Classic Skins 22 ** Plugins 30 ** Input 31 ** Output 32 ** Visualisation 33 ** DSP/Effect 34 ** General Purpose 35 ** ** Note: ** Custom page ids begin from 60 ** The value of the normal custom pages (Global Hotkeys, Jump To File, etc) is not ** guaranteed since it depends on the order in which the plugins are loaded which can ** change on different systems. ** ** Global Hotkeys, Jump To File, Media Library (under General Preferences and child pages), ** Media Library (under Plugins), Portables, CD Ripping and Modern Skins are custom pages ** created by the plugins shipped with Winamp. */ #define IPC_GETINIFILE 334 /* (requires Winamp 2.9+) ** char *ini=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETINIFILE); ** This returns a pointer to the full file path of winamp.ini. ** ** char ini_path[MAX_PATH] = {0}; ** ** void GetIniFilePath(HWND hwnd){ ** if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION) >= 0x2900){ ** // this gets the string of the full ini file path ** lstrcpyn(ini_path,(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETINIFILE),sizeof(ini_path)); ** } ** else{ ** char* p = ini_path; ** p += GetModuleFileName(0,ini_path,sizeof(ini_path)) - 1; ** while(p && *p != '.'){p--;} ** lstrcpyn(p+1,"ini",sizeof(ini_path)); ** } ** } */ #define IPC_GETINIDIRECTORY 335 /* (requires Winamp 2.9+) ** char *dir=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETINIDIRECTORY); ** This returns a pointer to the directory where winamp.ini can be found and is ** useful if you want store config files but you don't want to use winamp.ini. */ #define IPC_GETPLUGINDIRECTORY 336 /* (requires Winamp 5.11+) ** char *plugdir=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETPLUGINDIRECTORY); ** This returns a pointer to the directory where Winamp has its plugins stored and is ** useful if you want store config files in plugins.ini in the plugins folder or for ** accessing any local files in the plugins folder. */ #define IPC_GETM3UDIRECTORY 337 /* (requires Winamp 5.11+) ** char *m3udir=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETM3UDIRECTORY); ** This returns a pointer to the directory where winamp.m3u (and winamp.m3u8 if supported) is stored in. */ #define IPC_GETM3UDIRECTORYW 338 /* (requires Winamp 5.3+) ** wchar_t *m3udirW=(wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETM3UDIRECTORYW); ** This returns a pointer to the directory where winamp.m3u (and winamp.m3u8 if supported) is stored in. */ #define IPC_SPAWNBUTTONPOPUP 361 // param = // 0 = eject // 1 = previous // 2 = next // 3 = pause // 4 = play // 5 = stop #define IPC_OPENURLBOX 360 /* (requires Winamp 5.0+) ** HGLOBAL hglobal = (HGLOBAL)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_OPENURLBOX); ** You pass a hwnd for the dialog to be parented to (which modern skin support uses). ** This will return a HGLOBAL that needs to be freed with GlobalFree() if this worked. */ #define IPC_OPENFILEBOX 362 /* (requires Winamp 5.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_OPENFILEBOX); ** You pass a hwnd for the dialog to be parented to (which modern skin support uses). */ #define IPC_OPENDIRBOX 363 /* (requires Winamp 5.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_OPENDIRBOX); ** You pass a hwnd for the dialog to be parented to (which modern skin support uses). */ #define IPC_SETDIALOGBOXPARENT 364 /* (requires Winamp 5.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)parent,IPC_SETDIALOGBOXPARENT); ** Pass 'parent' as the window which will be used as the parent for a number of the built ** in Winamp dialogs and is useful when you are taking over the whole of the UI so that ** the dialogs will not appear at the bottom right of the screen since the main winamp ** window is located at 3000x3000 by gen_ff when this is used. Call this again with ** parent = null to reset the parent back to the orginal Winamp window. */ #define IPC_GETDIALOGBOXPARENT 365 /* (requires Winamp 5.51+) ** HWND hwndParent = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)0, IPC_GETDIALOGBOXPARENT); ** hwndParent can/must be passed to all modal dialogs (including MessageBox) thats uses winamp as a parent */ #define IPC_UPDATEDIALOGBOXPARENT 366 /* (requires Winamp 5.53+) ** if you previous called IPC_SETDIALOGBOXPARENT, call this every time your window resizes */ #define IPC_DRO_MIN 401 // reserved for DrO #define IPC_SET_JTF_COMPARATOR 409 /* pass me an int (__cdecl *)(const char *, const char *) in wParam */ #define IPC_SET_JTF_COMPARATOR_W 410 /* pass me an int (__cdecl *)(const wchar_t *, const wchar_t *) in wParam ... maybe someday :) */ #define IPC_SET_JTF_DRAWTEXT 416 #define IPC_DRO_MAX 499 // pass 0 for a copy of the skin HBITMAP // pass 1 for name of font to use for playlist editor likeness // pass 2 for font charset // pass 3 for font size #define IPC_GET_GENSKINBITMAP 503 typedef struct { HWND me; //hwnd of the window #define EMBED_FLAGS_NORESIZE 0x1 // set this bit to keep window from being resizable #define EMBED_FLAGS_NOTRANSPARENCY 0x2 // set this bit to make gen_ff turn transparency off for this window #define EMBED_FLAGS_NOWINDOWMENU 0x4 // set this bit to prevent gen_ff from automatically adding your window to the right-click menu #define EMBED_FLAGS_GUID 0x8 // (5.31+) call SET_EMBED_GUID(yourEmbedWindowStateStruct, GUID) to define a GUID for this window #define SET_EMBED_GUID(windowState, windowGUID) { windowState->flags |= EMBED_FLAGS_GUID; *((GUID *)&windowState->extra_data[4])=windowGUID; } #define GET_EMBED_GUID(windowState) (*((GUID *)&windowState->extra_data[4])) int flags; // see above RECT r; void *user_ptr; // for application use int extra_data[64]; // for internal winamp use } embedWindowState; #define IPC_GET_EMBEDIF 505 /* (requires Winamp 2.9+) ** HWND myframe = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&wa_wnd,IPC_GET_EMBEDIF); ** ** or ** ** HWND myframe = 0; ** HWND (*embed)(embedWindowState *params)=0; ** *(void**)&embed = (void*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_EMBEDIF); ** myframe = embed(&wa_wnd); ** ** You pass an embedWindowState* and it will return a hwnd for the frame window or if you ** pass wParam as null then it will return a HWND embedWindow(embedWindowState *); */ #define IPC_SKINWINDOW 534 typedef struct __SKINWINDOWPARAM { HWND hwndToSkin; GUID windowGuid; } SKINWINDOWPARAM; #define IPC_EMBED_ENUM 532 typedef struct embedEnumStruct { int (*enumProc)(embedWindowState *ws, struct embedEnumStruct *param); // return 1 to abort int user_data; // or more :) } embedEnumStruct; // pass #define IPC_EMBED_ISVALID 533 /* (requires Winamp 2.9+) ** int valid = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)embedhwnd,IPC_EMBED_ISVALID); ** Pass a hwnd in the wParam to this to check if the hwnd is a valid embed window or not. */ #define IPC_CONVERTFILE 506 /* (requires Winamp 2.92+) ** Converts a given file to a different format (PCM, MP3, etc...) ** To use, pass a pointer to a waFileConvertStruct struct ** This struct can be either on the heap or some global ** data, but NOT on the stack. At least, until the conversion is done. ** ** eg: SendMessage(hwnd_winamp,WM_WA_IPC,&myConvertStruct,IPC_CONVERTFILE); ** ** Return value: ** 0: Can't start the conversion. Look at myConvertStruct->error for details. ** 1: Conversion started. Status messages will be sent to the specified callbackhwnd. ** Be sure to call IPC_CONVERTFILE_END when your callback window receives the ** IPC_CB_CONVERT_DONE message. */ typedef struct { char *sourcefile; // "c:\\source.mp3" char *destfile; // "c:\\dest.pcm" intptr_t destformat[8]; // like 'PCM ',srate,nch,bps. //hack alert! you can set destformat[6]=mmioFOURCC('I','N','I',' '); and destformat[7]=(int)my_ini_file; (where my_ini_file is a char*) HWND callbackhwnd; // window that will receive the IPC_CB_CONVERT notification messages //filled in by winamp.exe char *error; //if IPC_CONVERTFILE returns 0, the reason will be here int bytes_done; //you can look at both of these values for speed statistics int bytes_total; int bytes_out; int killswitch; // don't set it manually, use IPC_CONVERTFILE_END intptr_t extra_data[64]; // for internal winamp use } convertFileStruct; #define IPC_CONVERTFILEW 515 // (requires Winamp 5.36+) typedef struct { wchar_t *sourcefile; // "c:\\source.mp3" wchar_t *destfile; // "c:\\dest.pcm" intptr_t destformat[8]; // like 'PCM ',srate,nch,bps. //hack alert! you can set destformat[6]=mmioFOURCC('I','N','I',' '); and destformat[7]=(int)my_ini_file; (where my_ini_file is a char*) HWND callbackhwnd; // window that will receive the IPC_CB_CONVERT notification messages //filled in by winamp.exe wchar_t *error; //if IPC_CONVERTFILE returns 0, the reason will be here int bytes_done; //you can look at both of these values for speed statistics int bytes_total; int bytes_out; int killswitch; // don't set it manually, use IPC_CONVERTFILE_END intptr_t extra_data[64]; // for internal winamp use } convertFileStructW; #define IPC_CONVERTFILE_END 507 /* (requires Winamp 2.92+) ** Stop/ends a convert process started from IPC_CONVERTFILE ** You need to call this when you receive the IPC_CB_CONVERTDONE message or when you ** want to abort a conversion process ** ** eg: SendMessage(hwnd_winamp,WM_WA_IPC,&myConvertStruct,IPC_CONVERTFILE_END); ** ** No return value */ #define IPC_CONVERTFILEW_END 516 // (requires Winamp 5.36+) typedef struct { HWND hwndParent; int format; //filled in by winamp.exe HWND hwndConfig; int extra_data[8]; //hack alert! you can set extra_data[6]=mmioFOURCC('I','N','I',' '); and extra_data[7]=(int)my_ini_file; (where my_ini_file is a char*) } convertConfigStruct; #define IPC_CONVERT_CONFIG 508 #define IPC_CONVERT_CONFIG_END 509 typedef struct { void (*enumProc)(intptr_t user_data, const char *desc, int fourcc); intptr_t user_data; } converterEnumFmtStruct; #define IPC_CONVERT_CONFIG_ENUMFMTS 510 /* (requires Winamp 2.92+) */ typedef struct { char cdletter; char *playlist_file; HWND callback_hwnd; //filled in by winamp.exe char *error; } burnCDStruct; #define IPC_BURN_CD 511 /* (requires Winamp 5.0+) */ typedef struct { convertFileStruct *cfs; int priority; } convertSetPriority; #define IPC_CONVERT_SET_PRIORITY 512 typedef struct { convertFileStructW *cfs; int priority; } convertSetPriorityW; #define IPC_CONVERT_SET_PRIORITYW 517 // (requires Winamp 5.36+) typedef struct { unsigned int format; //fourcc value char *item; // config item, eg "bitrate" char *data; // buffer to recieve, or buffer that contains the data int len; // length of the data buffer (only used when getting a config item) char *configfile; // config file to read from } convertConfigItem; #define IPC_CONVERT_CONFIG_SET_ITEM 513 // returns TRUE if successful #define IPC_CONVERT_CONFIG_GET_ITEM 514 // returns TRUE if successful typedef struct { const char *filename; char *title; // 2048 bytes int length; int force_useformatting; // can set this to 1 if you want to force a url to use title formatting shit } waHookTitleStruct; #define IPC_HOOK_TITLES 850 /* (requires Winamp 5.0+) ** If you hook this message and modify the information then make sure to return TRUE. ** If you don't hook the message then make sure you pass it on through the subclass chain. ** ** LRESULT CALLBACK WinampWndProc(HWND hwnd, UINT umsg, WPARAM wParam, LPARAM lParam) ** { ** LRESULT ret = CallWindowProc((WNDPROC)WinampProc,hwnd,umsg,wParam,lParam); ** ** if(message==WM_WA_IPC && lParam==IPC_HOOK_TITLES) ** { ** waHookTitleStruct *ht = (waHookTitleStruct *) wParam; ** // Doing ATF stuff with ht->title, whatever... ** return TRUE; ** } ** return ret; ** } */ typedef struct { const wchar_t *filename; wchar_t *title; // 2048 characters int length; int force_useformatting; // can set this to 1 if you want to force a url to use title formatting shit } waHookTitleStructW; #define IPC_HOOK_TITLESW 851 /* (requires Winamp 5.3+) ** See information on IPC_HOOK_TITLES for how to process this. */ #define IPC_GETSADATAFUNC 800 // 0: returns a char *export_sa_get() that returns 150 bytes of data // 1: returns a export_sa_setreq(int want); #define IPC_GETVUDATAFUNC 801 // 0: returns a int export_vu_get(int channel) that returns 0-255 (or -1 for bad channel) #define IPC_ISMAINWNDVISIBLE 900 /* (requires Winamp 5.0+) ** int visible=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISMAINWNDVISIBLE); ** You send this to Winamp to query if the main window is visible or not such as by ** unchecking the option in the main right-click menu. If the main window is visible then ** this will return 1 otherwise it returns 0. */ typedef struct { int numElems; int *elems; HBITMAP bm; // set if you want to override } waSetPlColorsStruct; #define IPC_SETPLEDITCOLORS 920 /* (requires Winamp 5.0+) ** This is sent by gen_ff when a modern skin is being loaded to set the colour scheme for ** the playlist editor. When sent numElems is usually 6 and matches with the 6 possible ** colours which are provided be pledit.txt from the classic skins. The elems array is ** defined as follows: ** ** elems = 0 => normal text ** elems = 1 => current text ** elems = 2 => normal background ** elems = 3 => selected background ** elems = 4 => minibroswer foreground ** elems = 5 => minibroswer background ** ** if(uMsg == WM_WA_IPC && lParam == IPC_SETPLEDITCOLORS) ** { ** waSetPlColorsStruct* colStr = (waSetPlColorsStruct*)wp; ** if(colStr) ** { ** // set or inspect the colours being used (basically for gen_ff's benefit) ** } ** } */ typedef struct { HWND wnd; int xpos; // in screen coordinates int ypos; } waSpawnMenuParms; // waSpawnMenuParms2 is used by the menubar submenus typedef struct { HWND wnd; int xpos; // in screen coordinates int ypos; int width; int height; } waSpawnMenuParms2; // the following IPC use waSpawnMenuParms as parameter #define IPC_SPAWNEQPRESETMENU 933 #define IPC_SPAWNFILEMENU 934 //menubar #define IPC_SPAWNOPTIONSMENU 935 //menubar #define IPC_SPAWNWINDOWSMENU 936 //menubar #define IPC_SPAWNHELPMENU 937 //menubar #define IPC_SPAWNPLAYMENU 938 //menubar #define IPC_SPAWNPEFILEMENU 939 //menubar #define IPC_SPAWNPEPLAYLISTMENU 940 //menubar #define IPC_SPAWNPESORTMENU 941 //menubar #define IPC_SPAWNPEHELPMENU 942 //menubar #define IPC_SPAWNMLFILEMENU 943 //menubar #define IPC_SPAWNMLVIEWMENU 944 //menubar #define IPC_SPAWNMLHELPMENU 945 //menubar #define IPC_SPAWNPELISTOFPLAYLISTS 946 #define WM_WA_SYSTRAY WM_USER+1 /* This is sent by the system tray when an event happens (you might want to simulate it). ** ** if(uMsg == WM_WA_SYSTRAY) ** { ** switch(lParam) ** { ** // process the messages sent from the tray ** } ** } */ #define WM_WA_MPEG_EOF WM_USER+2 /* Input plugins send this when they are done playing back the current file to inform ** Winamp or anyother installed plugins that the current ** ** if(uMsg == WM_WA_MPEG_EOF) ** { ** // do what is needed here ** } */ //// video stuff #define IPC_IS_PLAYING_VIDEO 501 // returns >1 if playing, 0 if not, 1 if old version (so who knows):) #define IPC_GET_IVIDEOOUTPUT 500 // see below for IVideoOutput interface #define VIDEO_MAKETYPE(A,B,C,D) ((A) | ((B)<<8) | ((C)<<16) | ((D)<<24)) #define VIDUSER_SET_INFOSTRING 0x1000 #define VIDUSER_GET_VIDEOHWND 0x1001 #define VIDUSER_SET_VFLIP 0x1002 #define VIDUSER_SET_TRACKSELINTERFACE 0x1003 // give your ITrackSelector interface as param2 #define VIDUSER_OPENVIDEORENDERER 0x1004 #define VIDUSER_CLOSEVIDEORENDERER 0x1005 #define VIDUSER_GETPOPUPMENU 0x1006 #define VIDUSER_SET_INFOSTRINGW 0x1007 typedef struct { int w; int h; int vflip; double aspectratio; unsigned int fmt; } VideoOpenStruct; #ifndef NO_IVIDEO_DECLARE #ifdef __cplusplus class VideoOutput; class SubsItem; #ifndef _NSV_DEC_IF_H_ struct YV12_PLANE { unsigned char* baseAddr; long rowBytes; } ; struct YV12_PLANES { YV12_PLANE y; YV12_PLANE u; YV12_PLANE v; }; #endif class IVideoOutput { public: virtual ~IVideoOutput() { } virtual int open(int w, int h, int vflip, double aspectratio, unsigned int fmt)=0; virtual void setcallback(LRESULT (*msgcallback)(void *token, HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam), void *token) { (void)token; (void)msgcallback; /* to eliminate warning C4100 */ } virtual void close()=0; virtual void draw(void *frame)=0; virtual void drawSubtitle(SubsItem *item) {UNREFERENCED_PARAMETER(item); } virtual void showStatusMsg(const char *text) {UNREFERENCED_PARAMETER(text); } virtual int get_latency() { return 0; } virtual void notifyBufferState(int bufferstate) { UNREFERENCED_PARAMETER(bufferstate); } /* 0-255*/ virtual INT_PTR extended(INT_PTR param1, INT_PTR param2, INT_PTR param3) { UNREFERENCED_PARAMETER(param1); UNREFERENCED_PARAMETER(param2); UNREFERENCED_PARAMETER(param3); return 0; } // Dispatchable, eat this! }; class ITrackSelector { public: virtual int getNumAudioTracks()=0; virtual void enumAudioTrackName(int n, const char *buf, int size)=0; virtual int getCurAudioTrack()=0; virtual int getNumVideoTracks()=0; virtual void enumVideoTrackName(int n, const char *buf, int size)=0; virtual int getCurVideoTrack()=0; virtual void setAudioTrack(int n)=0; virtual void setVideoTrack(int n)=0; }; #endif //cplusplus #endif//NO_IVIDEO_DECLARE // these messages are callbacks that you can grab by subclassing the winamp window // wParam = #define IPC_CB_WND_EQ 0 // use one of these for the param #define IPC_CB_WND_PE 1 #define IPC_CB_WND_MB 2 #define IPC_CB_WND_VIDEO 3 #define IPC_CB_WND_MAIN 4 #define IPC_CB_ONSHOWWND 600 #define IPC_CB_ONHIDEWND 601 #define IPC_CB_GETTOOLTIP 602 #define IPC_CB_MISC 603 #define IPC_CB_MISC_TITLE 0 // start of playing/stop/pause #define IPC_CB_MISC_VOLUME 1 // volume/pan #define IPC_CB_MISC_STATUS 2 // start playing/stop/pause/ffwd/rwd #define IPC_CB_MISC_EQ 3 #define IPC_CB_MISC_INFO 4 #define IPC_CB_MISC_VIDEOINFO 5 #define IPC_CB_MISC_TITLE_RATING 6 // (5.5+ for when the rating is changed via the songticker menu on current file) /* Example of using IPC_CB_MISC_STATUS to detect the start of track playback with 5.x ** ** if(lParam == IPC_CB_MISC && wParam == IPC_CB_MISC_STATUS) ** { ** if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISPLAYING) == 1 && ** !SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETOUTPUTTIME)) ** { ** char* file = (char*)SendMessage(hwnd_winamp,WM_WA_IPC, ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS),IPC_GETPLAYLISTFILE); ** // only output if a valid file was found ** if(file) ** { ** MessageBox(hwnd_winamp,file,"starting",0); ** // or do something else that you need to do ** } ** } ** } */ #define IPC_CB_CONVERT_STATUS 604 // param value goes from 0 to 100 (percent) #define IPC_CB_CONVERT_DONE 605 #define IPC_ADJUST_FFWINDOWSMENUPOS 606 /* (requires Winamp 2.9+) ** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_FFWINDOWSMENUPOS); ** This will move where Winamp expects the freeform windows in the menubar windows main ** menu. This is useful if you wish to insert a menu item above extra freeform windows. */ #define IPC_ISDOUBLESIZE 608 /* (requires Winamp 5.0+) ** int dsize=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISDOUBLESIZE); ** You send this to Winamp to query if the double size mode is enabled or not. ** If it is on then this will return 1 otherwise it will return 0. */ #define IPC_ADJUST_FFOPTIONSMENUPOS 609 /* (requires Winamp 2.9+) ** int newpos=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)adjust_offset,IPC_ADJUST_FFOPTIONSMENUPOS); ** moves where winamp expects the freeform preferences item in the menubar windows main ** menu. This is useful if you wish to insert a menu item above the preferences item. ** ** Note: This setting was ignored by gen_ff until it was fixed in 5.1 ** gen_ff would assume thatthe menu position was 11 in all cases and so when you ** had two plugins attempting to add entries into the main right click menu it ** would cause the 'colour themes' submenu to either be incorrectly duplicated or ** to just disappear.instead. */ #define IPC_GETTIMEDISPLAYMODE 610 /* (requires Winamp 5.0+) ** int mode=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETTIMEDISPLAYMODE); ** This will return the status of the time display i.e. shows time elapsed or remaining. ** This returns 0 if Winamp is displaying time elapsed or 1 for the time remaining. */ #define IPC_SETVISWND 611 /* (requires Winamp 5.0+) ** int viswnd=(HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)viswnd,IPC_SETVISWND); ** This allows you to set a window to receive the following message commands (which are ** used as part of the modern skin integration). ** When you have finished or your visualisation is closed then send wParam as zero to ** ensure that things are correctly tidied up. */ /* The following messages are received as the LOWORD(wParam) of the WM_COMMAND message. ** See %SDK%\winamp\wa5vis.txt for more info about visualisation integration in Winamp. */ #define ID_VIS_NEXT 40382 #define ID_VIS_PREV 40383 #define ID_VIS_RANDOM 40384 #define ID_VIS_FS 40389 #define ID_VIS_CFG 40390 #define ID_VIS_MENU 40391 #define IPC_GETVISWND 612 /* (requires Winamp 5.0+) ** int viswnd=(HWND)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVISWND); ** This returns a HWND to the visualisation command handler window if set by IPC_SETVISWND. */ #define IPC_ISVISRUNNING 613 /* (requires Winamp 5.0+) ** int visrunning=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_ISVISRUNNING); ** This will return 1 if a visualisation is currently running and 0 if one is not running. */ #define IPC_CB_VISRANDOM 628 // param is status of random #define IPC_SETIDEALVIDEOSIZE 614 /* (requires Winamp 5.0+) ** This is sent by Winamp back to itself so it can be trapped and adjusted as needed with ** the desired width in HIWORD(wParam) and the desired height in LOWORD(wParam). ** ** if(uMsg == WM_WA_IPC){ ** if(lParam == IPC_SETIDEALVIDEOSIZE){ ** wParam = MAKEWPARAM(height,width); ** } ** } */ #define IPC_GETSTOPONVIDEOCLOSE 615 /* (requires Winamp 5.0+) ** int sovc=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETSTOPONVIDEOCLOSE); ** This will return 1 if 'stop on video close' is enabled and 0 if it is disabled. */ #define IPC_SETSTOPONVIDEOCLOSE 616 /* (requires Winamp 5.0+) ** int sovc=SendMessage(hwnd_winamp,WM_WA_IPC,enabled,IPC_SETSTOPONVIDEOCLOSE); ** Set enabled to 1 to enable and 0 to disable the 'stop on video close' option. */ typedef struct { HWND hwnd; int uMsg; WPARAM wParam; LPARAM lParam; } transAccelStruct; #define IPC_TRANSLATEACCELERATOR 617 /* (requires Winamp 5.0+) ** (deprecated as of 5.53x+) */ typedef struct { int cmd; int x; int y; int align; } windowCommand; // send this as param to an IPC_PLCMD, IPC_MBCMD, IPC_VIDCMD #define IPC_CB_ONTOGGLEAOT 618 #define IPC_GETPREFSWND 619 /* (requires Winamp 5.0+) ** HWND prefs = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETPREFSWND); ** This will return a handle to the preferences dialog if it is open otherwise it will ** return zero. A simple check with the OS api IsWindow(..) is a good test if it's valid. ** ** e.g. this will open (or close if already open) the preferences dialog and show if we ** managed to get a valid ** SendMessage(hwnd_winamp,WM_COMMAND,MAKEWPARAM(WINAMP_OPTIONS_PREFS,0),0); ** MessageBox(hwnd_winamp,(IsWindow((HWND)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETPREFSWND))?"Valid":"Not Open"),0,MB_OK); */ #define IPC_SET_PE_WIDTHHEIGHT 620 /* (requires Winamp 5.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)&point,IPC_SET_PE_WIDTHHEIGHT); ** You pass a pointer to a POINT structure which holds the width and height and Winamp ** will set the playlist editor to that size (this is used by gen_ff on skin changes). ** There does not appear to be any bounds limiting with this so it is possible to create ** a zero size playlist editor window (which is a pretty silly thing to do). */ #define IPC_GETLANGUAGEPACKINSTANCE 621 /* (requires Winamp 5.0+) ** HINSTANCE hInst = (HINSTANCE)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLANGUAGEPACKINSTANCE); ** This will return the HINSTANCE to the currently used language pack file for winamp.exe ** ** (5.5+) ** If you pass 1 in wParam then you will have zero returned if a language pack is in use. ** if(!SendMessage(hwnd_winamp,WM_WA_IPC,1,IPC_GETLANGUAGEPACKINSTANCE)){ ** // winamp is currently using a language pack ** } ** ** If you pass 2 in wParam then you will get the path to the language pack folder. ** wchar_t* lngpackfolder = (wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,2,IPC_GETLANGUAGEPACKINSTANCE); ** ** If you pass 3 in wParam then you will get the path to the currently extracted language pack. ** wchar_t* lngpack = (wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,3,IPC_GETLANGUAGEPACKINSTANCE); ** ** If you pass 4 in wParam then you will get the name of the currently used language pack. ** wchar_t* lngname = (char*)SendMessage(hwnd_winamp,WM_WA_IPC,4,IPC_GETLANGUAGEPACKINSTANCE); */ #define LANG_IDENT_STR 0 #define LANG_LANG_CODE 1 #define LANG_COUNTRY_CODE 2 /* ** (5.51+) ** If you pass 5 in LOWORD(wParam) then you will get the ident string/code string ** (based on the param passed in the HIWORD(wParam) of the currently used language pack. ** The string returned with LANG_IDENT_STR is used to represent the language that the ** language pack is intended for following ISO naming conventions for consistancy. ** ** wchar_t* ident_str = (wchar_t*)SendMessage(hwnd_winamp,WM_WA_IPC,MAKEWPARAM(5,LANG_XXX),IPC_GETLANGUAGEPACKINSTANCE); ** ** e.g. ** For the default language it will return the following for the different LANG_XXX codes ** LANG_IDENT_STR -> "en-US" (max buffer size of this is 9 wchar_t) ** LANG_LANG_CODE -> "en" (language code) ** LANG_COUNTRY_CODE -> "US" (country code) ** ** On pre 5.51 installs you can get LANG_IDENT_STR using the following method ** (you'll have to custom process the string returned if you want the langugage or country but that's easy ;) ) ** ** #define LANG_PACK_LANG_ID 65534 (if you don't have lang.h) ** HINSTANCE hInst = (HINSTANCE)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLANGUAGEPACKINSTANCE); ** TCHAR buffer[9] = {0}; ** LoadString(hInst,LANG_PACK_LANG_ID,buffer,sizeof(buffer)); ** ** ** ** The following example shows how using the basic api will allow you to load the playlist ** context menu resource from the currently loaded language pack or it will fallback to ** the default winamp.exe instance. ** ** HINSTANCE lang = (HINSTANCE)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLANGUAGEPACKINSTANCE); ** HMENU popup = GetSubMenu(GetSubMenu((LoadMenu(lang?lang:GetModuleHandle(0),MAKEINTRESOURCE(101))),2),5); ** // do processing as needed on the menu before displaying it ** TrackPopupMenuEx(orig,TPM_LEFTALIGN|TPM_LEFTBUTTON|TPM_RIGHTBUTTON,rc.left,rc.bottom,hwnd_owner,0); ** DestroyMenu(popup); ** ** If you need a specific menu handle then look at IPC_GET_HMENU for more information. */ #define IPC_CB_PEINFOTEXT 622 // data is a string, ie: "04:21/45:02" #define IPC_CB_OUTPUTCHANGED 623 // output plugin was changed in config #define IPC_GETOUTPUTPLUGIN 625 /* (requires Winamp 5.0+) ** char* outdll = (char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETOUTPUTPLUGIN); ** This returns a string of the current output plugin's dll name. ** e.g. if the directsound plugin was selected then this would return 'out_ds.dll'. */ #define IPC_SETDRAWBORDERS 626 /* (requires Winamp 5.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,enabled,IPC_SETDRAWBORDERS); ** Set enabled to 1 to enable and 0 to disable drawing of the playlist editor and winamp ** gen class windows (used by gen_ff to allow it to draw its own window borders). */ #define IPC_DISABLESKINCURSORS 627 /* (requires Winamp 5.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,enabled,IPC_DISABLESKINCURSORS); ** Set enabled to 1 to enable and 0 to disable the use of skinned cursors. */ #define IPC_GETSKINCURSORS 628 /* (requires Winamp 5.36+) ** data = (WACURSOR)cursorId. (check wa_dlg.h for values) */ #define IPC_CB_RESETFONT 629 #define IPC_IS_FULLSCREEN 630 /* (requires Winamp 5.0+) ** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_FULLSCREEN); ** This will return 1 if the video or visualisation is in fullscreen mode or 0 otherwise. */ #define IPC_SET_VIS_FS_FLAG 631 /* (requires Winamp 5.0+) ** A vis should send this message with 1/as param to notify winamp that it has gone to or has come back from fullscreen mode */ #define IPC_SHOW_NOTIFICATION 632 #define IPC_GETSKININFO 633 #define IPC_GETSKININFOW 1633 /* (requires Winamp 5.0+) ** This is a notification message sent to the main Winamp window by itself whenever it ** needs to get information to be shown about the current skin in the 'Current skin ** information' box on the main Skins page in the Winamp preferences. ** ** When this notification is received and the current skin is one you are providing the ** support for then you return a valid buffer for Winamp to be able to read from with ** information about it such as the name of the skin file. ** ** if(uMsg == WM_WA_IPC && lParam == IPC_GETSKININFO){ ** if(is_our_skin()){ ** return is_our_skin_name(); ** } ** } */ #define IPC_GET_MANUALPLADVANCE 634 /* (requires Winamp 5.03+) ** int val=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_MANUALPLADVANCE); ** IPC_GET_MANUALPLADVANCE returns the status of the Manual Playlist Advance. ** If enabled this will return 1 otherwise it will return 0. */ #define IPC_SET_MANUALPLADVANCE 635 /* (requires Winamp 5.03+) ** SendMessage(hwnd_winamp,WM_WA_IPC,value,IPC_SET_MANUALPLADVANCE); ** IPC_SET_MANUALPLADVANCE sets the status of the Manual Playlist Advance option. ** Set value = 1 to turn it on and value = 0 to turn it off. */ #define IPC_GET_NEXT_PLITEM 636 /* (requires Winamp 5.04+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_EOF_GET_NEXT_PLITEM); ** ** Sent to Winamp's main window when an item has just finished playback or the next ** button has been pressed and requesting the new playlist item number to go to. ** ** Subclass this message in your application to return the new item number. ** Return -1 for normal Winamp operation (default) or the new item number in ** the playlist to be played instead of the originally selected next track. ** ** This is primarily provided for the JTFE plugin (gen_jumpex.dll). */ #define IPC_GET_PREVIOUS_PLITEM 637 /* (requires Winamp 5.04+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_EOF_GET_PREVIOUS_PLITEM); ** ** Sent to Winamp's main window when the previous button has been pressed and Winamp is ** requesting the new playlist item number to go to. ** ** Return -1 for normal Winamp operation (default) or the new item number in ** the playlist to be played instead of the originally selected previous track. ** ** This is primarily provided for the JTFE plugin (gen_jumpex.dll). */ #define IPC_IS_WNDSHADE 638 /* (requires Winamp 5.04+) ** int is_shaded=SendMessage(hwnd_winamp,WM_WA_IPC,wnd,IPC_IS_WNDSHADE); ** Pass 'wnd' as an id as defined for IPC_GETWND or pass -1 to query the status of the ** main window. This returns 1 if the window is in winshade mode and 0 if it is not. ** Make sure you only test for this on a 5.04+ install otherwise you get a false result. ** (See the notes about unhandled WM_WA_IPC messages). */ #define IPC_SETRATING 639 /* (requires Winamp 5.04+ with ML) ** int rating=SendMessage(hwnd_winamp,WM_WA_IPC,rating,IPC_SETRATING); ** This will allow you to set the 'rating' on the current playlist entry where 'rating' ** is an integer value from 0 (no rating) to 5 (5 stars). ** ** The following example should correctly allow you to set the rating for any specified ** playlist entry assuming of course that you're trying to get a valid playlist entry. ** ** void SetPlaylistItemRating(int item_to_set, int rating_to_set){ ** int cur_pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS); ** SendMessage(hwnd_winamp,WM_WA_IPC,item_to_set,IPC_SETPLAYLISTPOS); ** SendMessage(hwnd_winamp,WM_WA_IPC,rating_to_set,IPC_SETRATING); ** SendMessage(hwnd_winamp,WM_WA_IPC,cur_pos,IPC_SETPLAYLISTPOS); ** } */ #define IPC_GETRATING 640 /* (requires Winamp 5.04+ with ML) ** int rating=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETRATING); ** This returns the current playlist entry's rating between 0 (no rating) to 5 (5 stars). ** ** The following example should correctly allow you to get the rating for any specified ** playlist entry assuming of course that you're trying to get a valid playlist entry. ** ** int GetPlaylistItemRating(int item_to_get, int rating_to_set){ ** int cur_pos=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETLISTPOS), rating = 0; ** SendMessage(hwnd_winamp,WM_WA_IPC,item_to_get,IPC_SETPLAYLISTPOS); ** rating = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETRATING); ** SendMessage(hwnd_winamp,WM_WA_IPC,cur_pos,IPC_SETPLAYLISTPOS); ** return rating; ** } */ #define IPC_GETNUMAUDIOTRACKS 641 /* (requires Winamp 5.04+) ** int n = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETNUMAUDIOTRACKS); ** This will return the number of audio tracks available from the currently playing item. */ #define IPC_GETNUMVIDEOTRACKS 642 /* (requires Winamp 5.04+) ** int n = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETNUMVIDEOTRACKS); ** This will return the number of video tracks available from the currently playing item. */ #define IPC_GETAUDIOTRACK 643 /* (requires Winamp 5.04+) ** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETAUDIOTRACK); ** This will return the id of the current audio track for the currently playing item. */ #define IPC_GETVIDEOTRACK 644 /* (requires Winamp 5.04+) ** int cur = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVIDEOTRACK); ** This will return the id of the current video track for the currently playing item. */ #define IPC_SETAUDIOTRACK 645 /* (requires Winamp 5.04+) ** SendMessage(hwnd_winamp,WM_WA_IPC,track,IPC_SETAUDIOTRACK); ** This allows you to switch to a new audio track (if supported) in the current playing file. */ #define IPC_SETVIDEOTRACK 646 /* (requires Winamp 5.04+) ** SendMessage(hwnd_winamp,WM_WA_IPC,track,IPC_SETVIDEOTRACK); ** This allows you to switch to a new video track (if supported) in the current playing file. */ #define IPC_PUSH_DISABLE_EXIT 647 /* (requires Winamp 5.04+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_PUSH_DISABLE_EXIT); ** This will let you disable or re-enable the UI exit functions (close button, context ** menu, alt-f4). Remember to call IPC_POP_DISABLE_EXIT when you are done doing whatever ** was required that needed to prevent exit otherwise you have to kill the Winamp process. */ #define IPC_POP_DISABLE_EXIT 648 /* (requires Winamp 5.04+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_POP_DISABLE_EXIT); ** See IPC_PUSH_DISABLE_EXIT */ #define IPC_IS_EXIT_ENABLED 649 /* (requires Winamp 5.04+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_EXIT_ENABLED); ** This will return 0 if the 'exit' option of Winamp's menu is disabled and 1 otherwise. */ #define IPC_IS_AOT 650 /* (requires Winamp 5.04+) ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_IS_AOT); ** This will return the status of the always on top flag. ** Note: This may not match the actual TOPMOST window flag while another fullscreen ** application is focused if the user has the 'Disable always on top while fullscreen ** applications are focused' option under the General Preferences page is checked. */ #define IPC_USES_RECYCLEBIN 651 /* (requires Winamp 5.09+) ** int use_bin=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USES_RECYCLEBIN); ** This will return 1 if the deleted file should be sent to the recycle bin or ** 0 if deleted files should be deleted permanently (default action for < 5.09). ** ** Note: if you use this on pre 5.09 installs of Winamp then it will return 1 which is ** not correct but is due to the way that SendMessage(..) handles un-processed messages. ** Below is a quick case for checking if the returned value is correct. ** ** if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USES_RECYCLEBIN) && ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETVERSION)>=0x5009) ** { ** // can safely follow the option to recycle the file ** } ** else * { ** // need to do a permanent delete of the file ** } */ #define IPC_FLUSHAUDITS 652 /* ** SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_FLUSHAUDITS); ** ** Will flush any pending audits in the global audits queue ** */ #define IPC_GETPLAYITEM_START 653 #define IPC_GETPLAYITEM_END 654 #define IPC_GETVIDEORESIZE 655 #define IPC_SETVIDEORESIZE 656 #define IPC_INITIAL_SHOW_STATE 657 /* (requires Winamp 5.36+) ** int show_state = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INITIAL_SHOW_STATE); ** returns the processed value of nCmdShow when Winamp was started ** (see MSDN documentation the values passed to WinMain(..) for what this should be) ** ** e.g. ** if(SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_INITIAL_SHOW_STATE) == SW_SHOWMINIMIZED){ ** // we are starting minimised so process as needed (keep our window hidden) ** } ** ** Useful for seeing if winamp was run minimised on startup so you can act accordingly. ** On pre-5.36 versions this will effectively return SW_NORMAL/SW_SHOWNORMAL due to the ** handling of unknown apis returning 1 from Winamp. */ // >>>>>>>>>>> Next is 658 #define IPC_PLCMD 1000 #define PLCMD_ADD 0 #define PLCMD_REM 1 #define PLCMD_SEL 2 #define PLCMD_MISC 3 #define PLCMD_LIST 4 //#define IPC_MBCMD 1001 #define MBCMD_BACK 0 #define MBCMD_FORWARD 1 #define MBCMD_STOP 2 #define MBCMD_RELOAD 3 #define MBCMD_MISC 4 #define IPC_VIDCMD 1002 #define VIDCMD_FULLSCREEN 0 #define VIDCMD_1X 1 #define VIDCMD_2X 2 #define VIDCMD_LIB 3 #define VIDPOPUP_MISC 4 //#define IPC_MBURL 1003 //sets the URL //#define IPC_MBGETCURURL 1004 //copies the current URL into wParam (have a 4096 buffer ready) //#define IPC_MBGETDESC 1005 //copies the current URL description into wParam (have a 4096 buffer ready) //#define IPC_MBCHECKLOCFILE 1006 //checks that the link file is up to date (otherwise updates it). wParam=parent HWND //#define IPC_MBREFRESH 1007 //refreshes the "now playing" view in the library //#define IPC_MBGETDEFURL 1008 //copies the default URL into wParam (have a 4096 buffer ready) #define IPC_STATS_LIBRARY_ITEMCNT 1300 // updates library count status /* ** IPC's in the message range 2000 - 3000 are reserved internally for freeform messages. ** These messages are taken from ff_ipc.h which is part of the Modern skin integration. */ #define IPC_FF_FIRST 2000 #define IPC_FF_COLOURTHEME_CHANGE IPC_FF_ONCOLORTHEMECHANGED #define IPC_FF_ONCOLORTHEMECHANGED IPC_FF_FIRST + 3 /* ** This is a notification message sent when the user changes the colour theme in a Modern ** skin and can also be detected when the Modern skin is first loaded as the gen_ff plugin ** applies relevant settings and styles (like the colour theme). ** ** The value of wParam is the name of the new color theme being switched to. ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(const char*)colour_theme_name,IPC_FF_ONCOLORTHEMECHANGED); ** ** (IPC_FF_COLOURTHEME_CHANGE is the name i (DrO) was using before getting a copy of ** ff_ipc.h with the proper name in it). */ #define IPC_FF_ISMAINWND IPC_FF_FIRST + 4 /* ** int ismainwnd = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)test_wnd,IPC_FF_ISMAINWND); ** ** This allows you to determine if the window handle passed to it is a modern skin main ** window or not. If it is a main window or any of its windowshade variants then it will ** return 1. ** ** Because of the way modern skins are implemented, it is possible for this message to ** return a positive test result for a number of window handles within the current Winamp ** process. This appears to be because you can have a visible main window, a compact main ** window and also a winshaded version. ** ** The following code example below is one way of seeing how this api works since it will ** enumerate all windows related to Winamp at the time and allows you to process as ** required when a detection happens. ** ** ** EnumThreadWindows(GetCurrentThreadId(),enumWndProc,0); ** ** BOOL CALLBACK enumWndProc(HWND hwnd, LPARAM lParam){ ** ** if(SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)hwnd,IPC_FF_ISMAINWND)){ ** // do processing in here ** // or continue the enum for other main windows (if they exist) ** // and just comment out the line below ** return 0; ** } ** return 1; ** } */ #define IPC_FF_GETCONTENTWND IPC_FF_FIRST + 5 /* ** HWND wa2embed = (HWND)SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(HWND)test_wnd,IPC_FF_GETCONTENTWND); ** ** This will return the Winamp 2 window that is embedded in the window's container ** i.e. if hwnd is the playlist editor windowshade hwnd then it will return the Winamp 2 ** playlist editor hwnd. ** ** If no content is found such as the window has nothing embedded then this will return ** the hwnd passed to it. */ #define IPC_FF_NOTIFYHOTKEY IPC_FF_FIRST + 6 /* ** This is a notification message sent when the user uses a global hotkey combination ** which had been registered with the gen_hotkeys plugin. ** ** The value of wParam is the description of the hotkey as passed to gen_hotkeys. ** SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(const char*)hotkey_desc,IPC_FF_NOTIFYHOTKEY); */ #define IPC_FF_LAST 3000 /* ** General IPC messages in Winamp ** ** All notification messages appear in the lParam of the main window message proceedure. */ #define IPC_GETDROPTARGET 3001 /* (requires Winamp 5.0+) ** IDropTarget* IDrop = (IDropTarget*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GETDROPTARGET); ** ** You call this to retrieve a copy of the IDropTarget interface which Winamp created for ** handling external drag and drop operations on to it's Windows. This is only really ** useful if you're providing an alternate interface and want your Windows to provide the ** same drag and drop support as Winamp normally provides the user. Check out MSDN or ** your prefered search facility for more information about the IDropTarget interface and ** what's needed to handle it in your own instance. */ #define IPC_PLAYLIST_MODIFIED 3002 /* (requires Winamp 5.0+) ** This is a notification message sent to the main Winamp window whenever the playlist is ** modified in any way e.g. the addition/removal of a playlist entry. ** ** It is not a good idea to do large amounts of processing in this notification since it ** will slow down Winamp as playlist entries are modified (especially when you're adding ** in a large playlist). ** ** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYLIST_MODIFIED) ** { ** // do what you need to do here ** } */ #define IPC_PLAYING_FILE 3003 /* (requires Winamp 5.0+) ** This is a notification message sent to the main Winamp window when playback begins for ** a file. This passes the full filepath in the wParam of the message received. ** ** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYING_FILE) ** { ** // do what you need to do here, e.g. ** process_file((char*)wParam); ** } */ #define IPC_PLAYING_FILEW 13003 /* (requires Winamp 5.0+) ** This is a notification message sent to the main Winamp window when playback begins for ** a file. This passes the full filepath in the wParam of the message received. ** ** if(uMsg == WM_WA_IPC && lParam == IPC_PLAYING_FILEW) ** { ** // do what you need to do here, e.g. ** process_file((wchar_t*)wParam); ** } */ #define IPC_FILE_TAG_MAY_HAVE_UPDATED 3004 #define IPC_FILE_TAG_MAY_HAVE_UPDATEDW 3005 /* (requires Winamp 5.0+) ** This is a notification message sent to the main Winamp window when a file's tag ** (e.g. id3) may have been updated. This appears to be sent when the InfoBox(..) function ** of the associated input plugin returns a 1 (which is the file information dialog/editor ** call normally). ** ** if(uMsg == WM_WA_IPC && lParam == IPC_FILE_TAG_MAY_HAVE_UPDATED) ** { ** // do what you need to do here, e.g. ** update_info_on_file_update((char*)wParam); ** } */ #define IPC_ALLOW_PLAYTRACKING 3007 /* (requires Winamp 5.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,allow,IPC_ALLOW_PLAYTRACKING); ** Send allow as nonzero to allow play tracking and zero to disable the mode. */ #define IPC_HOOK_OKTOQUIT 3010 /* (requires Winamp 5.0+) ** This is a notification message sent to the main Winamp window asking if it's okay to ** close or not. Return zero to prevent Winamp from closing or return anything non-zero ** to allow Winamp to close. ** ** The best implementation of this option is to let the message pass through to the ** original window proceedure since another plugin may want to have a say in the matter ** with regards to Winamp closing. ** ** if(uMsg == WM_WA_IPC && lParam == IPC_HOOK_OKTOQUIT) ** { ** // do what you need to do here, e.g. ** if(no_shut_down()) ** { ** return 1; ** } ** } */ #define IPC_WRITECONFIG 3011 /* (requires Winamp 5.0+) ** SendMessage(hwnd_winamp,WM_WA_IPC,write_type,IPC_WRITECONFIG); ** ** Send write_type as 2 to write all config settings and the current playlist. ** ** Send write_type as 1 to write the playlist and common settings. ** This won't save the following ini settings:: ** ** defext, titlefmt, proxy, visplugin_name, dspplugin_name, check_ft_startup, ** visplugin_num, pe_fontsize, visplugin_priority, visplugin_autoexec, dspplugin_num, ** sticon, splash, taskbar, dropaotfs, ascb_new, ttips, riol, minst, whichicon, ** whichicon2, addtolist, snap, snaplen, parent, hilite, disvis, rofiob, shownumsinpl, ** keeponscreen, eqdsize, usecursors, fixtitles, priority, shuffle_morph_rate, ** useexttitles, bifont, inet_mode, ospb, embedwnd_freesize, no_visseh ** (the above was valid for 5.1) ** ** Send write_type as 0 to write the common and less common settings and no playlist. */ #define IPC_UPDATE_URL 3012 // pass the URL (char *) in lparam, will be free()'d on done. #define IPC_GET_RANDFUNC 3015 // returns a function to get a random number /* (requires Winamp 5.1+) ** int (*randfunc)(void) = (int(*)(void))SendMessage(plugin.hwndParent,WM_WA_IPC,0,IPC_GET_RANDFUNC); ** if(randfunc && randfunc != 1){ ** randfunc(); ** } ** ** This will return a positive 32-bit number (essentially 31-bit). ** The check for a returned value of 1 is because that's the default return value from ** SendMessage(..) when it is not handled so is good to check for it in this situation. */ #define IPC_METADATA_CHANGED 3017 /* (requires Winamp 5.1+) ** int changed=SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)(char*)field,IPC_METADATA_CHANGED); ** a plugin can SendMessage this to winamp if internal metadata has changes. ** wParam should be a char * of what field changed ** ** Currently used for internal actions (and very few at that) the intent of this api is ** to allow a plugin to call it when metadata has changed in the current playlist entry ** e.g.a new id3v2 tag was found in a stream ** ** The wparam value can either be NULL or a pointer to an ansi string for the metadata ** which has changed. This can be thought of as an advanced version of IPC_UPDTITLE and ** could be used to allow for update of the current title when a specific tag changed. ** ** Not recommended to be used since there is not the complete handling implemented in ** Winamp for it at the moment. */ #define IPC_SKIN_CHANGED 3018 /* (requires Winamp 5.1+) ** This is a notification message sent to the main Winamp window by itself whenever ** the skin in use is changed. There is no information sent by the wParam for this. ** ** if(message == WM_WA_IPC && lparam == IPC_SKIN_CHANGED) ** { ** // do what you need to do to handle skin changes, e.g. call WADlg_init(hwnd_winamp); ** } */ #define IPC_REGISTER_LOWORD_COMMAND 3019 /* (requires Winamp 5.1+) ** WORD id = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_REGISTER_LOWORD_COMMAND); ** This will assign you a unique id for making your own commands such as for extra menu ** entries. The starting value returned by this message will potentially change as and ** when the main resource file of Winamp is updated with extra data so assumptions cannot ** be made on what will be returned and plugin loading order will affect things as well. ** 5.33+ ** If you want to reserve more than one id, you can pass the number of ids required in wParam */ #define IPC_GET_DISPATCH_OBJECT 3020 // gets winamp main IDispatch * (for embedded webpages) #define IPC_GET_UNIQUE_DISPATCH_ID 3021 // gives you a unique dispatch ID that won't conflict with anything in winamp's IDispatch * #define IPC_ADD_DISPATCH_OBJECT 3022 // add your own dispatch object into winamp's. This lets embedded webpages access your functions // pass a pointer to DispatchInfo (see below). Winamp makes a copy of all this data so you can safely delete it later typedef struct { wchar_t *name; // filled in by plugin, make sure it's a unicode string!! (i.e. L"myObject" instead of "myObject). struct IDispatch *dispatch; // filled in by plugin DWORD id; // filled in by winamp on return } DispatchInfo; // see IPC_JSAPI2_GET_DISPATCH_OBJECT for version 2 of the Dispatchable scripting interface #define IPC_GET_PROXY_STRING 3023 /* (requires Winamp 5.11+) ** char* proxy_string=(char*)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_PROXY_STRING); ** This will return the same string as is shown on the General Preferences page. */ #define IPC_USE_REGISTRY 3024 /* (requires Winamp 5.11+) ** int reg_enabled=SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_USE_REGISTRY); ** This will return 0 if you should leave your grubby hands off the registry (i.e. for ** lockdown mode). This is useful if Winamp is run from a USB drive and you can't alter ** system settings, etc. */ #define IPC_GET_API_SERVICE 3025 /* (requires Winamp 5.12+) ** api_service* api_service = (api_service)SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_GET_API_SERVICE); ** This api will return Winamp's api_service pointer (which is what Winamp3 used, heh). ** If this api is not supported in the Winamp version that is being used at the time then ** the returned value from this api will be 1 which is a good version check. ** ** As of 5.12 there is support for .w5s plugins which reside in %WinampDir%\System and ** are intended for common code that can be shared amongst other plugins e.g. jnetlib.w5s ** which contains jnetlib in one instance instead of being duplicated multiple times in ** all of the plugins which need internet access. ** ** Details on the .w5s specifications will come at some stage (possibly). */ typedef struct { const wchar_t *filename; const wchar_t *metadata; wchar_t *ret; size_t retlen; } extendedFileInfoStructW; #define IPC_GET_EXTENDED_FILE_INFOW 3026 /* (requires Winamp 5.13+) ** Pass a pointer to the above struct in wParam */ #define IPC_GET_EXTENDED_FILE_INFOW_HOOKABLE 3027 #define IPC_SET_EXTENDED_FILE_INFOW 3028 /* (requires Winamp 5.13+) ** Pass a pointer to the above struct in wParam */ #define IPC_PLAYLIST_GET_NEXT_SELECTED 3029 /* (requires 5.2+) ** int pl_item = SendMessage(hwnd_winamp,WM_WA_IPC,start,IPC_PLAYLIST_GET_NEXT_SELECTED); ** ** This works just like the ListView_GetNextItem(..) macro for ListView controls. ** 'start' is the index of the playlist item that you want to begin the search after or ** set this as -1 for the search to begin with the first item of the current playlist. ** ** This will return the index of the selected playlist according to the 'start' value or ** it returns -1 if there is no selection or no more selected items according to 'start'. ** ** Quick example: ** ** int sel = -1; ** // keep incrementing the start of the search so we get all of the selected entries ** while((sel = SendMessage(hwnd_winamp,WM_WA_IPC,sel,IPC_PLAYLIST_GET_NEXT_SELECTED))!=-1){ ** // show the playlist file entry of the selected item(s) if there were any ** MessageBox(hwnd_winamp,(char*)SendMessage(hwnd_winamp,WM_WA_IPC,sel,IPC_GETPLAYLISTFILE),0,0); ** } */ #define IPC_PLAYLIST_GET_SELECTED_COUNT 3030 /* (requires 5.2+) ** int selcnt = SendMessage(hwnd_winamp,WM_WA_IPC,0,IPC_PLAYLIST_GET_SELECTED_COUNT); ** This will return the number of selected playlist entries. */ #define IPC_GET_PLAYING_FILENAME 3031 // returns wchar_t * of the currently playing filename #define IPC_OPEN_URL 3032 // send either ANSI or Unicode string (it'll figure it out, but it MUST start with "h"!, so don't send ftp:// or anything funny) // you can also send this one from another process via WM_COPYDATA (unicode only) #define IPC_USE_UXTHEME_FUNC 3033 /* (requires Winamp 5.35+) ** int ret = SendMessage(hwnd_winamp,WM_WA_IPC,param,IPC_USE_UXTHEME_FUNC); ** param can be IPC_ISWINTHEMEPRESENT or IPC_ISAEROCOMPOSITIONACTIVE or a valid hwnd. ** ** If you pass a hwnd then it will apply EnableThemeDialogTexture(ETDT_ENABLETAB) ** so your tabbed dialogs can use the correct theme (on supporting OSes ie XP+). ** ** Otherwise this will return a value based on the param passed (as defined below). ** For compatability, the return value will be zero on success (as 1 is returned ** for unsupported ipc calls on older Winamp versions) */ #define IPC_ISWINTHEMEPRESENT 0 /* This will return 0 if uxtheme.dll is present ** int isthemethere = !SendMessage(hwnd_winamp,WM_WA_IPC,IPC_ISWINTHEMEPRESENT,IPC_USE_UXTHEME_FUNC); */ #define IPC_ISAEROCOMPOSITIONACTIVE 1 /* This will return 0 if aero composition is active ** int isaero = !SendMessage(hwnd_winamp,WM_WA_IPC,IPC_ISAEROCOMPOSITIONACTIVE,IPC_USE_UXTHEME_FUNC); */ #define IPC_GET_PLAYING_TITLE 3034 // returns wchar_t * of the current title #define IPC_CANPLAY 3035 // pass const wchar_t *, returns an in_mod * or 0 typedef struct { // fill these in... size_t size; // init to sizeof(artFetchData) HWND parent; // parent window of the dialogue // fill as much of these in as you can, otherwise leave them 0 const wchar_t *artist; const wchar_t *album; int year, amgArtistId, amgAlbumId; int showCancelAll; // if set to 1, this shows a "Cancel All" button on the dialogue // winamp will fill these in if the call returns successfully: void* imgData; // a buffer filled with compressed image data. free with WASABI_API_MEMMGR->sysFree() int imgDataLen; // the size of the buffer wchar_t type[10]; // eg: "jpg" const wchar_t *gracenoteFileId; // if you know it } artFetchData; #define IPC_FETCH_ALBUMART 3036 /* pass an artFetchData*. This will show a dialog guiding the use through choosing art, and return when it's finished ** return values: ** 1: error showing dialog ** 0: success ** -1: cancel was pressed ** -2: cancel all was pressed */ #define IPC_JSAPI2_GET_DISPATCH_OBJECT 3037 /* pass your service's unique ID, as a wchar_t * string, in wParam ** Winamp will copy the string, so don't worry about keeping it around ** An IDispatch * object will be returned (cast the return value from SendMessage) ** This IDispatch can be used for scripting/automation/VB interaction ** Pass to IE via IDocHostUIHandler::GetExternal and it will become window.external in javscript */ #define IPC_REGISTER_WINAMP_IPCMESSAGE 65536 /* (requires Winamp 5.0+) ** DWORD id = SendMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)name,IPC_REGISTER_WINAMP_IPCMESSAGE); ** The value 'id' returned is > 65536 and is incremented on subsequent calls for unique ** 'name' values passed to it. By using the same 'name' in different plugins will allow a ** common runtime api to be provided for the currently running instance of Winamp ** e.g. ** PostMessage(hwnd_winamp,WM_WA_IPC,(WPARAM)my_param,registered_ipc); ** Have a look at wa_hotkeys.h for an example on how this api is used in practice for a ** custom WM_WA_IPC message. ** ** if(uMsg == WM_WA_IPC && lParam == id_from_register_winamp_ipcmessage){ ** // do things ** } */ #endif//_WA_IPC_H_ ================================================ FILE: img/dyauno/Style.inc ================================================ ================================================ FILE: z_build.bat ================================================ @echo off setlocal enabledelayedexpansion REM /////////////////////////////////////////////////////////////////////////// REM // Set Paths REM /////////////////////////////////////////////////////////////////////////// set "MSVC_PATH=C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC" set "TOOLS_VER=141" set "SLN_SUFFX=VS2017" REM ############################################### REM # DO NOT MODIFY ANY LINES BELOW THIS LINE !!! # REM ############################################### REM /////////////////////////////////////////////////////////////////////////// REM // Check environment REM /////////////////////////////////////////////////////////////////////////// if not exist "%MSVC_PATH%\vcvarsall.bat" ( if not exist "%MSVC_PATH%\Auxiliary\Build\vcvarsall.bat" ( echo MSVC compiler not found. Please check your MSVC_PATH var^^! goto BuildError ) ) if not exist "%QTDIR%\bin\moc.exe" ( echo Qt could not be found. Please check your QTDIR var^^! goto BuildError ) if not exist "%QTDIR%\include\QtCore\qglobal.h" ( echo Qt could not be found. Please check your QTDIR var^^! goto BuildError ) if not exist "%JAVA_HOME%\bin\java.exe" ( echo JDK could not be found. Please check your JAVA_HOME var^^! goto BuildError ) if not exist "%JAVA_HOME%\lib\tools.jar" ( echo JDK could not be found. Please check your JAVA_HOME var^^! goto BuildError ) if not exist "%JAVA_HOME%\include\jni.h" ( echo JDK could not be found. Please check your JAVA_HOME var^^! goto BuildError ) if not exist "%~dp0\..\Prerequisites\README.txt" ( echo Prerequisites not found. Repair your build environment^^! goto BuildError ) REM /////////////////////////////////////////////////////////////////////////// REM // Setup environment REM /////////////////////////////////////////////////////////////////////////// set "ANT_HOME=%~dp0\..\Prerequisites\Ant" set "PATH=%QTDIR%\bin;%JAVA_HOME%\bin;%ANT_HOME%\bin;%PATH%" if exist "%MSVC_PATH%\vcvarsall.bat" ( call "%MSVC_PATH%\vcvarsall.bat" x86 ) else ( if exist "%MSVC_PATH%\Auxiliary\Build\vcvarsall.bat" ( call "%MSVC_PATH%\Auxiliary\Build\vcvarsall.bat" x86 ) ) if not exist "%VCINSTALLDIR%\bin\cl.exe" ( if not exist "%VCToolsInstallDir%\bin\Hostx64\x86\cl.exe" ( echo MSVC compiler not found. Please check your MSVC_PATH var^^! goto BuildError ) ) REM /////////////////////////////////////////////////////////////////////////// REM // Get current date and time (in ISO format) REM /////////////////////////////////////////////////////////////////////////// set "ISO_DATE=" set "ISO_TIME=" if not exist "%~dp0\..\Prerequisites\GnuWin32\date.exe" goto BuildError for /F "tokens=1,2 delims=:" %%a in ('"%~dp0\..\Prerequisites\GnuWin32\date.exe" +ISODATE:%%Y-%%m-%%d') do ( if "%%a"=="ISODATE" set "ISO_DATE=%%b" ) for /F "tokens=1,2,3,4 delims=:" %%a in ('"%~dp0\..\Prerequisites\GnuWin32\date.exe" +ISOTIME:%%T') do ( if "%%a"=="ISOTIME" set "ISO_TIME=%%b:%%c:%%d" ) if "%ISO_DATE%"=="" goto BuildError if "%ISO_TIME%"=="" goto BuildError REM /////////////////////////////////////////////////////////////////////////// REM // Detect version number REM /////////////////////////////////////////////////////////////////////////// set "VER_MAJOR=" set "VER_MINOR=" set "VER_PATCH=" for /F "tokens=1,2,3" %%a in (%~dp0\DynamicAudioNormalizerShared\res\version.inc) do ( if "%%a"=="#define" ( if "%%b"=="VER_DYNAUDNORM_MAJOR" set "VER_MAJOR=%%c" if "%%b"=="VER_DYNAUDNORM_MINOR_HI" set "VER_MINOR=%%c!VER_MINOR!" if "%%b"=="VER_DYNAUDNORM_MINOR_LO" set "VER_MINOR=!VER_MINOR!%%c" if "%%b"=="VER_DYNAUDNORM_PATCH" set "VER_PATCH=%%c" ) ) if "%VER_MAJOR%"=="" goto BuildError if "%VER_MINOR%"=="" goto BuildError if "%VER_PATCH%"=="" goto BuildError REM /////////////////////////////////////////////////////////////////////////// REM // Clean Binaries REM /////////////////////////////////////////////////////////////////////////// for /d %%d in (%~dp0\bin\*) do (rmdir /S /Q "%%~d") for /d %%d in (%~dp0\obj\*) do (rmdir /S /Q "%%~d") REM /////////////////////////////////////////////////////////////////////////// REM // Build the binaries REM /////////////////////////////////////////////////////////////////////////// for %%c in (DLL, Static) do ( for %%p in (Win32, x64) do ( echo --------------------------------------------------------------------- echo BEGIN BUILD [%%p/Release_%%c] echo --------------------------------------------------------------------- MSBuild.exe /property:Platform=%%p /property:Configuration=Release_%%c /target:clean "%~dp0\DynamicAudioNormalizer_%SLN_SUFFX%.sln" if not "!ERRORLEVEL!"=="0" goto BuildError MSBuild.exe /property:Platform=%%p /property:Configuration=Release_%%c /target:rebuild "%~dp0\DynamicAudioNormalizer_%SLN_SUFFX%.sln" if not "!ERRORLEVEL!"=="0" goto BuildError MSBuild.exe /property:Platform=%%p /property:Configuration=Release_%%c /target:build "%~dp0\DynamicAudioNormalizer_%SLN_SUFFX%.sln" if not "!ERRORLEVEL!"=="0" goto BuildError ) ) call "%ANT_HOME%\bin\ant.bat" -buildfile "%~dp0\DynamicAudioNormalizerJNI\build.xml" if not "!ERRORLEVEL!"=="0" goto BuildError REM /////////////////////////////////////////////////////////////////////////// REM // Copy program files REM /////////////////////////////////////////////////////////////////////////// set "PACK_PATH=%TMP%\~%RANDOM%%RANDOM%.tmp" mkdir "%PACK_PATH%" for %%c in (DLL, Static) do ( echo --------------------------------------------------------------------- echo BEGIN PACKAGING [Release_%%c] echo --------------------------------------------------------------------- mkdir "%PACK_PATH%\%%c" mkdir "%PACK_PATH%\%%c\x64" mkdir "%PACK_PATH%\%%c\img" mkdir "%PACK_PATH%\%%c\img\dyauno" mkdir "%PACK_PATH%\%%c\include" mkdir "%PACK_PATH%\%%c\samples" mkdir "%PACK_PATH%\%%c\samples\python" copy "%~dp0\bin\Win32\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerCLI.exe" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\Win32\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerGUI.exe" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\Win32\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerPYD.pyd" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\x64\.\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerPYD.pyd" "%PACK_PATH%\%%c\x64" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\Win32\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerVST.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\x64\.\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerVST.dll" "%PACK_PATH%\%%c\x64" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\Win32\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerWA5.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerPYD\include\*.py" "%PACK_PATH%\%%c\include" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerPYD\samples\*.py" "%PACK_PATH%\%%c\samples\python" if not "!ERRORLEVEL!"=="0" goto BuildError if /I "%%c"=="DLL" ( mkdir "%PACK_PATH%\%%c\redist" mkdir "%PACK_PATH%\%%c\samples\delphi" mkdir "%PACK_PATH%\%%c\samples\dotNet" mkdir "%PACK_PATH%\%%c\samples\java" copy "%~dp0\bin\Win32\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerAPI.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\Win32\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerAPI.lib" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\Win32\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerNET.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\x64\.\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerAPI.dll" "%PACK_PATH%\%%c\x64" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\x64\.\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerAPI.lib" "%PACK_PATH%\%%c\x64" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\bin\x64\.\v%TOOLS_VER%_xp\Release_%%c\DynamicAudioNormalizerNET.dll" "%PACK_PATH%\%%c\x64" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerAPI\include\*.h" "%PACK_PATH%\%%c\include" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerPAS\include\*.pas" "%PACK_PATH%\%%c\include" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerJNI\out\*.jar" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\..\Prerequisites\LibSndFile\bin\Win32\libsndfile-1.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\..\Prerequisites\LibMpg123\bin\Win32\libmpg123.v%TOOLS_VER%_xp.dll" "%PACK_PATH%\%%c\libmpg123.dll" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\..\Prerequisites\XiphAudioLibs\bin\Win32\libopus.v%TOOLS_VER%_xp.dll" "%PACK_PATH%\%%c\libopus.dll" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\..\Prerequisites\XiphAudioLibs\bin\Win32\libopusfile.v%TOOLS_VER%_xp.dll" "%PACK_PATH%\%%c\libopusfile.dll" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\..\Prerequisites\XiphAudioLibs\bin\Win32\libogg.v%TOOLS_VER%_xp.dll" "%PACK_PATH%\%%c\libogg.dll" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\..\Prerequisites\Qt4\v%TOOLS_VER%_xp\Shared\bin\QtGui4.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\..\Prerequisites\Qt4\v%TOOLS_VER%_xp\Shared\bin\QtCore4.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerNET\samples\*.cs" "%PACK_PATH%\%%c\samples\dotNet" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerNET\samples\*.vb" "%PACK_PATH%\%%c\samples\dotNet" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerPAS\src\*.pas" "%PACK_PATH%\%%c\samples\delphi" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerPAS\src\*.dfm" "%PACK_PATH%\%%c\samples\delphi" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\DynamicAudioNormalizerJNI\samples\com\muldersoft\dynaudnorm\samples\*.java" "%PACK_PATH%\%%c\samples\java" if not "!ERRORLEVEL!"=="0" goto BuildError if %TOOLS_VER% GEQ 140 ( if %TOOLS_VER% GEQ 141 ( copy "%VCToolsRedistDir%\x86\Microsoft.VC%TOOLS_VER%.CRT\*.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%VCToolsRedistDir%\x64\Microsoft.VC%TOOLS_VER%.CRT\*.dll" "%PACK_PATH%\%%c\x64" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%VCToolsRedistDir%\vcredist_*.exe" "%PACK_PATH%\%%c\redist" if not "!ERRORLEVEL!"=="0" goto BuildError ) else ( copy "%MSVC_PATH%\redist\x86\Microsoft.VC%TOOLS_VER%.CRT\*.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%MSVC_PATH%\redist\x64\Microsoft.VC%TOOLS_VER%.CRT\*.dll" "%PACK_PATH%\%%c\x64" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%MSVC_PATH%\redist\1033\vcredist_*.exe" "%PACK_PATH%\%%c\redist" if not "!ERRORLEVEL!"=="0" goto BuildError ) copy "%~dp0\..\Prerequisites\MSVC\redist\ucrt\DLLs\x86\*.dll" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\..\Prerequisites\MSVC\redist\ucrt\DLLs\x64\*.dll" "%PACK_PATH%\%%c\x64" if not "!ERRORLEVEL!"=="0" goto BuildError ) ) copy "%~dp0\LICENSE-LGPL.html" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\LICENSE-GPL2.html" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\LICENSE-GPL3.html" "%PACK_PATH%\%%c" if not "!ERRORLEVEL!"=="0" goto BuildError copy "%~dp0\img\dyauno\*.png" "%PACK_PATH%\%%c\img\dyauno" if not "!ERRORLEVEL!"=="0" goto BuildError "%~dp0\..\Prerequisites\Pandoc\pandoc.exe" --from markdown_github+pandoc_title_block+header_attributes+implicit_figures --to html5 --toc -N --standalone -H "%~dp0\..\Prerequisites\Pandoc\css\github-pandoc.inc" "%~dp0\README.md" | "%JAVA_HOME%\bin\java.exe" -jar "%~dp0\..\Prerequisites\HTMLCompressor\bin\htmlcompressor-1.5.3.jar" --compress-css -o "%PACK_PATH%\%%c\README.html" if not "!ERRORLEVEL!"=="0" goto BuildError ) REM /////////////////////////////////////////////////////////////////////////// REM // Compress REM /////////////////////////////////////////////////////////////////////////// for %%c in (Static) do ( for %%i in (DynamicAudioNormalizerCLI.exe,DynamicAudioNormalizerGUI.exe,DynamicAudioNormalizerPYD.pyd,DynamicAudioNormalizerVST.dll,DynamicAudioNormalizerWA5.dll) do ( "%~dp0\..\Prerequisites\UPX\upx.exe" --best "%PACK_PATH%\%%c\%%~i" if not "!ERRORLEVEL!"=="0" goto BuildError ) for %%i in (DynamicAudioNormalizerPYD.pyd,DynamicAudioNormalizerVST.dll) do ( "%~dp0\..\Prerequisites\UPX\upx.exe" --best "%PACK_PATH%\%%c\x64\%%~i" if not "!ERRORLEVEL!"=="0" goto BuildError ) ) REM /////////////////////////////////////////////////////////////////////////// REM // Create version tag REM /////////////////////////////////////////////////////////////////////////// echo Dynamic Audio Normalizer> "%PACK_PATH%\BUILD_TAG" echo Copyright (c) 2014-2019 LoRd_MuldeR ^. Some rights reserved.>> "%PACK_PATH%\BUILD_TAG" echo.>> "%PACK_PATH%\BUILD_TAG" echo Version %VER_MAJOR%.%VER_MINOR%-%VER_PATCH%. Built on %ISO_DATE%, at %ISO_TIME%>> "%PACK_PATH%\BUILD_TAG" echo.>> "%PACK_PATH%\BUILD_TAG" cl.exe 2>&1 | "%~dp0\..\Prerequisites\GnuWin32\head.exe" -n1 | "%~dp0\..\Prerequisites\GnuWin32\sed.exe" -e "/^$/d" -e "s/^/Compiler version: /">> "%PACK_PATH%\BUILD_TAG" ver 2>&1 | "%~dp0\..\Prerequisites\GnuWin32\sed.exe" -e "/^$/d" -e "s/^/Build platform: /">> "%PACK_PATH%\BUILD_TAG" echo.>> "%PACK_PATH%\BUILD_TAG" echo This library is free software; you can redistribute it and/or>> "%PACK_PATH%\BUILD_TAG" echo modify it under the terms of the GNU Lesser General Public>> "%PACK_PATH%\BUILD_TAG" echo License as published by the Free Software Foundation; either>> "%PACK_PATH%\BUILD_TAG" echo version 2.1 of the License, or (at your option) any later version.>> "%PACK_PATH%\BUILD_TAG" echo.>> "%PACK_PATH%\BUILD_TAG" echo This library is distributed in the hope that it will be useful,>> "%PACK_PATH%\BUILD_TAG" echo but WITHOUT ANY WARRANTY; without even the implied warranty of>> "%PACK_PATH%\BUILD_TAG" echo MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU>> "%PACK_PATH%\BUILD_TAG" echo Lesser General Public License for more details.>> "%PACK_PATH%\BUILD_TAG" REM /////////////////////////////////////////////////////////////////////////// REM // Attributes REM /////////////////////////////////////////////////////////////////////////// for %%c in (DLL, Static) do ( attrib +R "%PACK_PATH%\%%c\*" attrib +R "%PACK_PATH%\%%c\x64\*" attrib +R "%PACK_PATH%\%%c\img\dyauno\*" if /I "%%c"=="DLL" ( attrib +R "%PACK_PATH%\%%c\include\*" ) ) REM /////////////////////////////////////////////////////////////////////////// REM // Generate outfile name REM /////////////////////////////////////////////////////////////////////////// mkdir "%~dp0\out" 2> NUL set "OUT_NAME=DynamicAudioNormalizer.%ISO_DATE%" :CheckOutName for %%c in (DLL, Static) do ( if exist "%~dp0\out\%OUT_NAME%.%%c.zip" ( set "OUT_NAME=%OUT_NAME%.new" goto CheckOutName ) ) REM /////////////////////////////////////////////////////////////////////////// REM // Build the package REM /////////////////////////////////////////////////////////////////////////// for %%c in (DLL, Static) do ( copy "%PACK_PATH%\BUILD_TAG" "%PACK_PATH%\%%c" pushd "%PACK_PATH%\%%c" "%~dp0\..\Prerequisites\GnuWin32\zip.exe" -9 -r -z "%~dp0\out\%OUT_NAME%.%%c.zip" "*.*" < "%PACK_PATH%\BUILD_TAG" popd attrib +R "%~dp0\out\%OUT_NAME%.%%c.zip" ) REM Clean up! rmdir /Q /S "%PACK_PATH%" REM /////////////////////////////////////////////////////////////////////////// REM // COMPLETE REM /////////////////////////////////////////////////////////////////////////// echo. echo Build completed. echo. pause goto:eof REM /////////////////////////////////////////////////////////////////////////// REM // FAILED REM /////////////////////////////////////////////////////////////////////////// :BuildError echo. echo Build has failed ^^!^^!^^! echo. pause ================================================ FILE: z_test.bat ================================================ @echo off set "WAV2PNG=D:\Temp\Downloads\wav2png.exe" set "CONVERT=D:\ImageMagick-6.9.0-Q16\convert.exe" rmdir /Q /S "%~dp0\tmp" 2> NUL mkdir "%~dp0\tmp" call:runTest default call:runTest dc-corr --correct-dc call:runTest alt-bnd --alt-boundary call:runTest dcc+alt --correct-dc --alt-boundary call:runTest rms-val --target-rms 0.2 call:runTest dcc+rms --correct-dc --target-rms 0.2 goto:done :: ============================================================================ :runTest echo ########################################################################### echo Test: %1 echo Args: %2 %3 %4 %5 %6 %7 %8 %9 echo ########################################################################### for %%f in (%~dp0\test\*.wav) do ( echo. echo =========================================================================== echo %%~nxf echo =========================================================================== echo. "%~dp0\bin\Win32\Release_Static\DynamicAudioNormalizerCLI.exe" -i "%%~f" -o "%~dp0\tmp\%%~nf.%1.wav" -l "%~dp0\tmp\%%~nf.%1.log" %2 %3 %4 %5 %6 %7 %8 %9 "%WAV2PNG%" --width 1920 -o "%~dp0\tmp\~%%~nf.%1.A.png" "%%~f" "%WAV2PNG%" --width 1920 -o "%~dp0\tmp\~%%~nf.%1.B.png" "%~dp0\tmp\%%~nf.%1.wav" "%CONVERT%" "%~dp0\tmp\~%%~nf.%1.A.png" "%~dp0\tmp\~%%~nf.%1.B.png" -append "%~dp0\tmp\%%~nf.%1.png" del "%~dp0\tmp\~%%~nf.%1.?.png" ) echo. echo. exit /b :: ============================================================================ :done echo Test Completed. echo. pause