-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPluginAudioLevelBeta.cpp
1682 lines (1475 loc) · 46.6 KB
/
PluginAudioLevelBeta.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (C) 2014 Rainmeter Project Developers
*
* This Source Code Form is subject to the terms of the GNU General Public
* License; either version 2 of the License, or (at your option) any later
* version. If a copy of the GPL was not distributed with this file, You can
* obtain one at <https://www.gnu.org/licenses/gpl-2.0.html>. */
#include <Windows.h>
#include <cstdio>
#include <AudioClient.h>
#include <AudioPolicy.h>
#include <MMDeviceApi.h>
#include <FunctionDiscoveryKeys_devpkey.h>
#include <VersionHelpers.h>
#include <cmath>
#include <cassert>
#include <vector>
#include <thread>
#include <chrono>
#include <avrt.h>
#pragma comment(lib, "Avrt.lib")
#include "../../API/RainmeterAPI.h"
#include "pffft/pffft.h"
// Overview: Audio level measurement from the Window Core Audio API
// See: http://msdn.microsoft.com/en-us/library/windows/desktop/dd370800%28v=vs.85%29.aspx
// Sample skin:
/*
[mAudio_Raw]
Measure=Plugin
Plugin=AudioLevel.dll
Port=Output
[mAudio_RMS_L]
Measure=Plugin
Plugin=AudioLevel.dll
Parent=mAudio_Raw
Type=RMS
Channel=L
[mAudio_RMS_R]
Measure=Plugin
Plugin=AudioLevel.dll
Parent=mAudio_Raw
Type=RMS
Channel=R
*/
#define WINDOWS_BUG_WORKAROUND 1
#define TWOPI (2 * 3.14159265358979323846)
#define EXIT_ON_ERROR(hres) if (FAILED(hres)) { goto Exit; }
#define SAFE_RELEASE(p) if ((p) != NULL) { (p)->Release(); (p) = NULL; }
#define CLAMP01(x) max(0.0, min(1.0, (x)))
struct Measure
{
enum Port
{
PORT_OUTPUT,
PORT_INPUT,
};
enum Channel
{
CHANNEL_FL,
CHANNEL_FR,
CHANNEL_C,
CHANNEL_LFE,
CHANNEL_BL,
CHANNEL_BR,
CHANNEL_SL,
CHANNEL_SR,
CHANNEL_SUM,
MAX_CHANNELS
};
enum Type
{
TYPE_RMS,
TYPE_PEAK,
TYPE_FFT,
TYPE_WAVE,
TYPE_BAND,
TYPE_WAVEBAND,
TYPE_FFTFREQ,
TYPE_BANDFREQ,
TYPE_FORMAT,
TYPE_DEV_STATUS,
TYPE_DEV_NAME,
TYPE_DEV_ID,
TYPE_DEV_LIST,
TYPE_BUFFERSTATUS,
// ... //
NUM_TYPES
};
enum Format
{
FMT_INVALID,
FMT_PCM_S16,
FMT_PCM_F32,
// ... //
NUM_FORMATS
};
struct BandInfo
{
float freq;
float x;
};
Port m_port; // port specifier (parsed from options)
Channel m_channel; // channel specifier (parsed from options)
Type m_type; // data type specifier (parsed from options)
Format m_format; // format specifier (detected in init)
int m_envRMS[2]; // RMS attack/decay times in ms (parsed from options)
int m_envPeak[2]; // peak attack/decay times in ms (parsed from options)
int m_envFFT[2]; // FFT attack/decay times in ms (parsed from options)
int m_fftSize; // size of FFT (parsed from options)
int m_fftBufferSize; // size of FFT with zero-padding (parsed from options)
int m_fftIdx; // FFT index to retrieve (parsed from options)
int m_waveIdx; // WAVE index to retrieve (parsed from options)
int m_nBands; // number of frequency bands (parsed from options)
int m_bandIdx; // band index to retrieve (parsed from options)
int m_smoothing; // smoothing level (parsed from options)
int m_smoothingMode; // smoothing mode (parsed from options)
int m_waveSize; // size of WAVE (parsed from options)
int m_ringBufferSize; // size of the ring buffer for FFT and WAVE
int m_dynamicVolume; // enable dynamic volume (parsed from options)
UINT32 m_nFramesNext; // number of frames obtained on the UpdateParent call
UINT32 m_nSilentFrames; // number of silent frames, used to calculate when to stop updating
double m_gainRMS; // RMS gain (parsed from options)
double m_gainPeak; // peak gain (parsed from options)
double m_freqMin; // min freq for band measurement
double m_freqMax; // max freq for band measurement
double m_sensitivity; // dB range for FFT/Band return values (parsed from options)
Measure* m_parent; // parent measure, if any
void* m_skin; // skin pointer
void* m_rm; // rainmeter pointer
LPCWSTR m_rmName; // measure name
IMMDeviceEnumerator* m_enum; // audio endpoint enumerator
IMMDevice* m_dev; // audio endpoint device
WAVEFORMATEX m_wfxR; // audio format request info
WAVEFORMATEX* m_wfx; // audio format info
IAudioClient* m_clAudio; // audio client instance
IAudioCaptureClient* m_clCapture; // capture client instance
IAudioClient* m_clBugAudio; // audio client for loopback events
#if (WINDOWS_BUG_WORKAROUND)
IAudioRenderClient* m_clBugRender; // render client for dummy silent channel
#endif
HANDLE m_hReadyEvent; // buffer-event handle to receive notifications
HANDLE m_hStopEvent; // skin closed handle to receive notifications
HANDLE m_hTask; // Multimedia Class Scheduler Service task
std::thread* m_updateLoopThread; // thread for running the update loop
std::chrono::system_clock::time_point
m_lastUpdate; // time of last rainmeter update
std::chrono::duration<double>
m_waitUpdate; // time to wait between updates
std::chrono::duration<double>
m_overheadUpdate; // time that has been waited too long since last update
double m_updatesPerSecond; // updates per second
WCHAR m_reqID[64]; // requested device ID (parsed from options)
WCHAR m_devName[64]; // device friendly name (detected in init)
WCHAR m_msgUpdate[256]; // rainmeter update command
float m_kRMS[2]; // RMS attack/decay filter constants
float m_kPeak[2]; // peak attack/decay filter constants
float m_kFFT[2]; // FFT attack/decay filter constants
float* m_bufChunk; // buffer for latest data chunk copy
float m_rms[MAX_CHANNELS]; // current RMS levels
float m_peak[MAX_CHANNELS]; // current peak levels
float m_fftMeanSquare; // used for dynamic volume
PFFFT_Setup* m_fftCfg; // FFT states for each channel
float* m_ringBuffer; // ring buffer for audio data
float* m_fftOut; // buffer for FFT output
float* m_fftKWdw; // window function coefficients
float* m_ringBufOut; // buffer for audio data from the ring buffer
float* m_fftTmpOut; // temp FFT processing buffer
int m_ringBufW; // write index for input ring buffers
float* m_bandFreq; // buffer of band max frequencies
float* m_bandOut; // buffer of band values
float* m_bandTmpOut; // temp buffer of band values
float* m_waveBandOut; // buffer of wave values
float* m_waveOut; // temp buffer of wave values
float* m_waveBandTmpOut; // 2nd temp buffer of wave values
float m_df; // delta freqency between two bins
float m_dw; // delta waveform values between two bands
float m_fftScalar; // FFT scalar
float m_bandScalar; // band scalar
float m_waveScalar; // wave scalar
float m_smoothingScalar; // smoothing scalar
Measure() :
m_port(PORT_OUTPUT),
m_channel(CHANNEL_SUM),
m_type(TYPE_RMS),
m_format(FMT_INVALID),
m_fftSize(0),
m_fftBufferSize(0),
m_fftIdx(-1),
m_fftScalar(0),
m_nBands(0),
m_bandIdx(-1),
m_bandScalar(0),
m_df(0),
m_dw(0),
m_smoothing(0),
m_smoothingMode(0),
m_smoothingScalar(0),
m_waveSize(0),
m_waveIdx(0),
m_waveScalar(0),
m_ringBufferSize(0),
m_nFramesNext(0),
m_nSilentFrames(0),
m_dynamicVolume(0),
m_gainRMS(1.0),
m_gainPeak(1.0),
m_freqMin(20.0),
m_freqMax(20000.0),
m_sensitivity(0.0),
m_parent(NULL),
m_skin(NULL),
m_rm(NULL),
m_rmName(NULL),
m_enum(NULL),
m_dev(NULL),
m_wfxR({ 0 }),
m_wfx(NULL),
m_clAudio(NULL),
m_clCapture(NULL),
m_clBugAudio(NULL),
#if (WINDOWS_BUG_WORKAROUND)
m_clBugRender(NULL),
#endif
m_hReadyEvent(NULL),
m_hStopEvent(NULL),
m_hTask(NULL),
m_updateLoopThread(NULL),
m_waitUpdate(NULL),
m_overheadUpdate(NULL),
m_fftKWdw(NULL),
m_ringBufOut(NULL),
m_fftTmpOut(NULL),
m_ringBufW(0),
m_bandFreq(NULL)
{
m_envRMS[0] = 300;
m_envRMS[1] = 300;
m_envPeak[0] = 50;
m_envPeak[1] = 2500;
m_envFFT[0] = 300;
m_envFFT[1] = 300;
m_reqID[0] = '\0';
m_devName[0] = '\0';
m_msgUpdate[0] = '\0';
m_kRMS[0] = 0.0f;
m_kRMS[1] = 0.0f;
m_kPeak[0] = 0.0f;
m_kPeak[1] = 0.0f;
m_kFFT[0] = 0.0f;
m_kFFT[1] = 0.0f;
m_fftMeanSquare = 0.0f;
m_fftCfg = NULL;
m_bufChunk = NULL;
m_ringBuffer = NULL;
m_fftOut = NULL;
m_bandOut = NULL;
m_bandTmpOut = NULL;
m_waveBandOut = NULL;
m_waveOut = NULL;
m_waveBandTmpOut = NULL;
}
HRESULT DeviceInit();
void DeviceRelease();
HRESULT UpdateParent();
void DoCaptureLoop();
};
float pcmScalar = 1.0f / 0x7fff;
const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
const IID IID_IAudioClient = __uuidof(IAudioClient);
//const IID IID_IAudioClient3 = __uuidof(IAudioClient3);
const IID IID_IAudioCaptureClient = __uuidof(IAudioCaptureClient);
const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);
std::vector<Measure*> s_parents;
void Measure::DoCaptureLoop()
{
// register thread with MMCSS
DWORD nTaskIndex = 0;
m_hTask = AvSetMmThreadCharacteristics(L"Pro Audio", &nTaskIndex);
if (!(m_hTask && AvSetMmThreadPriority(m_hTask, AVRT_PRIORITY_CRITICAL)))
{
DWORD dwErr = GetLastError();
RmLog(m_rm, LOG_WARNING, L"Failed to start multimedia task.");
return;
}
HANDLE waitArray[2] = { m_hReadyEvent, m_hStopEvent };
while (1)
{
if (WAIT_OBJECT_0 != WaitForMultipleObjects(ARRAYSIZE(waitArray), waitArray, FALSE, INFINITE))
return;
// update parent seperated from measure update function
HRESULT hr = UpdateParent();
switch (hr)
{
case S_OK:
// everything is fine, update measures
// wait specified time (to not spam update calls)
if (m_updatesPerSecond > 0)
{
auto now = std::chrono::system_clock::now();
auto elapsed = now - m_lastUpdate;
auto waitTime = m_waitUpdate;// - m_overheadUpdate;
if (elapsed >= waitTime)
{
// overheadUpdate should correct the overhead time making the update rate more accurate
// but i cant tell the difference and i dont know if it helps or does the opposite
// so i leave it disabled until i investigated further
//m_overheadUpdate = elapsed - waitTime;
//if (m_overheadUpdate > m_waitUpdate) {
// m_overheadUpdate = std::chrono::duration<double>(0);
//}
m_lastUpdate = now;
RmExecute(m_skin, m_msgUpdate);
}
}
// update as fast as possible
else if (m_updatesPerSecond < 0 && m_updatesPerSecond >= -1)
{
RmExecute(m_skin, m_msgUpdate);
}
break;
case S_FALSE:
// silence detected, no need to update
break;
case AUDCLNT_E_BUFFER_ERROR:
case AUDCLNT_E_DEVICE_INVALIDATED:
case AUDCLNT_E_SERVICE_NOT_RUNNING:
// error detected, release device
DeviceRelease();
break;
}
}
}
/**
* Create and initialize a measure instance. Creates WASAPI loopback
* device if not a child measure.
*
* @param[out] data Pointer address in which to return measure instance.
* @param[in] rm Rainmeter context.
*/
PLUGIN_EXPORT void Initialize(void** data, void* rm)
{
Measure* m = new Measure;
m->m_skin = RmGetSkin(rm);
m->m_rmName = RmGetMeasureName(rm);
*data = m;
// parse parent specifier, if appropriate
LPCWSTR parentName = RmReadString(rm, L"Parent", L"");
if (*parentName)
{
// match parent using measure name and skin handle
std::vector<Measure*>::const_iterator iter = s_parents.begin();
for (; iter != s_parents.end(); ++iter)
{
if (_wcsicmp((*iter)->m_rmName, parentName) == 0 &&
(*iter)->m_skin == m->m_skin &&
!(*iter)->m_parent)
{
m->m_parent = (*iter);
return;
}
}
RmLogF(rm, LOG_ERROR, L"Couldn't find Parent measure '%s'.", parentName);
}
// this is a parent measure - add it to the global list
s_parents.push_back(m);
// parse port specifier
LPCWSTR port = RmReadString(rm, L"Port", L"");
if (port && *port)
{
if (_wcsicmp(port, L"Output") == 0)
{
m->m_port = Measure::PORT_OUTPUT;
}
else if (_wcsicmp(port, L"Input") == 0)
{
m->m_port = Measure::PORT_INPUT;
}
else
{
RmLogF(rm, LOG_ERROR, L"Invalid Port '%s', must be one of: Output or Input.", port);
}
}
_snwprintf_s(m->m_msgUpdate, _TRUNCATE, L"!UpdateMeasure %s", m->m_rmName);
// create the enumerator
EXIT_ON_ERROR(CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)& m->m_enum));
// parse requested device ID (optional)
LPCWSTR reqID = RmReadString(rm, L"ID", L"");
if (reqID)
{
_snwprintf_s(m->m_reqID, _TRUNCATE, L"%s", reqID);
}
// if a specific ID was requested, search for that one, otherwise get the default
if (*m->m_reqID)
{
HRESULT hr = m->m_enum->GetDevice(m->m_reqID, &m->m_dev);
if (hr != S_OK)
{
WCHAR msg[256];
_snwprintf_s(msg, _TRUNCATE, L"Audio %s device '%s' not found (error 0x%08x).",
m->m_port == Measure::PORT_OUTPUT ? L"output" : L"input", m->m_reqID, hr);
RmLog(rm, LOG_WARNING, msg);
}
}
else
{
EXIT_ON_ERROR(m->m_enum->GetDefaultAudioEndpoint(m->m_port == Measure::PORT_OUTPUT ? eRender : eCapture, eConsole, &m->m_dev));
}
// init the device (if it fails, log debug message and quit)
if (m->DeviceInit() == S_OK)
{
return;
}
Exit:
SAFE_RELEASE(m->m_enum);
}
/**
* Destroy the measure instance.
*
* @param[in] data Measure instance pointer.
*/
PLUGIN_EXPORT void Finalize(void* data)
{
Measure* m = (Measure*)data;
if (!m->m_parent)
{
SetEvent(m->m_hStopEvent);
m->DeviceRelease();
SAFE_RELEASE(m->m_enum);
std::vector<Measure*>::iterator iter = std::find(s_parents.begin(), s_parents.end(), m);
s_parents.erase(iter);
}
delete m;
}
/**
* (Re-)parse parameters from .ini file.
*
* @param[in] data Measure instance pointer.
* @param[in] rm Rainmeter context.
* @param[out] maxValue ?
*/
PLUGIN_EXPORT void Reload(void* data, void* rm, double* maxValue)
{
static const LPCWSTR s_typeName[Measure::NUM_TYPES] =
{
L"RMS", // TYPE_RMS
L"Peak", // TYPE_PEAK
L"FFT", // TYPE_FFT
L"Wave", // TYPE_WAVE
L"Band", // TYPE_BAND
L"WaveBand", // TYPE_WAVEBAND
L"FFTFreq", // TYPE_FFTFREQ
L"BandFreq", // TYPE_BANDFREQ
L"Format", // TYPE_FORMAT
L"DeviceStatus", // TYPE_DEV_STATUS
L"DeviceName", // TYPE_DEV_NAME
L"DeviceID", // TYPE_DEV_ID
L"DeviceList", // TYPE_DEV_LIST
L"BufferStatus" // TYPE_BUFFERSTATUS
};
static const LPCWSTR s_chanName[Measure::MAX_CHANNELS][3] =
{
{ L"L", L"FL", L"0", }, // CHANNEL_FL
{ L"R", L"FR", L"1", }, // CHANNEL_FR
{ L"C", L"", L"2", }, // CHANNEL_C
{ L"LFE", L"Sub", L"3", }, // CHANNEL_LFE
{ L"BL", L"", L"4", }, // CHANNEL_BL
{ L"BR", L"", L"5", }, // CHANNEL_BR
{ L"SL", L"", L"6", }, // CHANNEL_SL
{ L"SR", L"", L"7", }, // CHANNEL_SR
{ L"Sum", L"Avg", L"", }, // CHANNEL_SUM
};
Measure* m = (Measure*)data;
// parse data type
LPCWSTR type = RmReadString(rm, L"Type", L"");
if (*type)
{
int iType;
for (iType = 0; iType < Measure::NUM_TYPES; ++iType)
{
if (_wcsicmp(type, s_typeName[iType]) == 0)
{
m->m_type = (Measure::Type)iType;
break;
}
}
if (iType >= Measure::NUM_TYPES)
{
WCHAR msg[512];
WCHAR* d = msg;
d += _snwprintf_s(d, (sizeof(msg) + (UINT32)msg - (UINT32)d) / sizeof(WCHAR), _TRUNCATE,
L"Invalid Type '%s', must be one of:", type);
for (int i = 0; i < Measure::NUM_TYPES; ++i)
{
d += _snwprintf_s(d, (sizeof(msg) + (UINT32)msg - (UINT32)d) / sizeof(WCHAR), _TRUNCATE,
L"%s%s%s", i ? L", " : L" ", i == (Measure::NUM_TYPES - 1) ? L"or " : L"", s_typeName[i]);
}
d += _snwprintf_s(d, (sizeof(msg) + (UINT32)msg - (UINT32)d) / sizeof(WCHAR), _TRUNCATE, L".");
RmLogF(rm, LOG_ERROR, msg);
}
}
// parse channel specifier
LPCWSTR channel = RmReadString(rm, L"Channel", L"");
if (*channel)
{
bool found = false;
for (int iChan = 0; iChan <= Measure::CHANNEL_SUM && !found; ++iChan)
{
for (int j = 0; j < 3; ++j)
{
if (_wcsicmp(channel, s_chanName[iChan][j]) == 0)
{
m->m_channel = (Measure::Channel)iChan;
found = true;
break;
}
}
}
if (!found)
{
WCHAR msg[512];
WCHAR* d = msg;
d += _snwprintf_s(d, (sizeof(msg) + (UINT32)msg - (UINT32)d) / sizeof(WCHAR), _TRUNCATE,
L"Invalid Channel '%s', must be an integer between 0 and %d, or one of:", channel, Measure::MAX_CHANNELS - 2);
for (int i = 0; i <= Measure::CHANNEL_SUM; ++i)
{
d += _snwprintf_s(d, (sizeof(msg) + (UINT32)msg - (UINT32)d) / sizeof(WCHAR), _TRUNCATE,
L"%s%s%s", i ? L", " : L" ", i == Measure::CHANNEL_SUM ? L"or " : L"", s_chanName[i][0]);
}
d += _snwprintf_s(d, (sizeof(msg) + (UINT32)msg - (UINT32)d) / sizeof(WCHAR), _TRUNCATE, L".");
RmLogF(rm, LOG_ERROR, msg);
}
}
// parse envelope, fft and band values on parents only
if (!m->m_parent)
{
int fftSize = RmReadInt(rm, L"FFTSize", m->m_fftSize);
int fftBufferSize = max(m->m_fftSize, RmReadInt(rm, L"FFTBufferSize", m->m_fftBufferSize));
int nBands = RmReadInt(rm, L"Bands", m->m_nBands);
int smoothing = max(0, RmReadInt(rm, L"Smoothing", m->m_smoothing));
double freqMin = max(0.0, RmReadDouble(rm, L"FreqMin", m->m_freqMin));
double freqMax = max(0.0, RmReadDouble(rm, L"FreqMax", m->m_freqMax));
int waveSize = RmReadInt(rm, L"WAVESize", m->m_waveSize);
// if one of these values changed, reinitialize
if (m->m_fftSize != fftSize ||
m->m_fftBufferSize != fftBufferSize ||
m->m_freqMin != freqMin ||
m->m_freqMax != freqMax ||
m->m_waveSize != waveSize ||
m->m_nBands != nBands ||
m->m_smoothing != smoothing)
{
// initialize FFT data
if (m->m_fftSize < 0 || m->m_fftSize & 1)
{
RmLogF(rm, LOG_ERROR, L"Invalid FFTSize %ld: must be an even integer >= 0. (powers of 2 work best)", fftSize);
fftSize = 0;
}
m->m_fftSize = fftSize;
m->m_fftBufferSize = fftBufferSize;
// initialize WAVE data
if (m->m_waveSize < 0 || m->m_waveSize & 1)
{
RmLogF(rm, LOG_ERROR, L"Invalid WAVESize %ld: must be an even integer >= 0.", waveSize);
waveSize = 0;
}
m->m_waveSize = waveSize;
m->m_ringBufferSize = max(fftSize, waveSize);
// initialize frequency bands
if (nBands < 0)
{
RmLogF(rm, LOG_ERROR, L"Invalid Bands %ld: must be an integer >= 0.", nBands);
nBands = 0;
}
m->m_nBands = nBands;
// initialize smoothing
m->m_smoothing = smoothing;
if (m->m_smoothing)
{
m->m_smoothingScalar = 1.0f / ((float)m->m_smoothing * 2.0f + 1.0f);
}
// initialize min/max frequency
m->m_freqMin = freqMin;
m->m_freqMax = freqMax;
// setup ring buffer
if (m->m_ringBufferSize)
{
m->m_ringBuffer = (float*)calloc(m->m_ringBufferSize * sizeof(float), 1);
m->m_ringBufOut = (float*)calloc(max(m->m_ringBufferSize, m->m_fftBufferSize) * sizeof(float), 1);
}
// setup FFT buffers
if (m->m_fftSize)
{
m->m_fftKWdw = (float*)calloc(m->m_fftSize * sizeof(float), 1);
m->m_fftCfg = pffft_new_setup(m->m_fftBufferSize, pffft_transform_t::PFFFT_REAL);
m->m_fftTmpOut = (float*)calloc(m->m_fftBufferSize * 2 * sizeof(float), 1);
m->m_fftOut = (float*)calloc(m->m_fftBufferSize * sizeof(float), 1);
m->m_fftScalar = (float)(1.0 / sqrt(m->m_fftSize));
m->m_df = (float)m->m_wfx->nSamplesPerSec / m->m_fftBufferSize;
// zero-padding - https://jackschaedler.github.io/circles-sines-signals/zeropadding.html
for (int iBin = 0; iBin < m->m_fftBufferSize; ++iBin) m->m_ringBufOut[iBin] = 0.0;
// calculate window function coefficients (http://en.wikipedia.org/wiki/Window_function#Hann_.28Hanning.29_window)
for (unsigned int iBin = 1; iBin < m->m_fftSize; ++iBin)
m->m_fftKWdw[iBin] = (float)(0.5 * (1.0 - cos(TWOPI * iBin / (m->m_fftSize + 1)))); // periodic version for FFT/spectral analysis
m->m_fftKWdw[0] = 0.0;
// calculate band frequencies and allocate band output buffers
if (m->m_nBands)
{
m->m_bandFreq = (float*)malloc(m->m_nBands * sizeof(float));
const double step = pow(2.0, (log(m->m_freqMax / m->m_freqMin) / m->m_nBands) / log(2.0));
m->m_bandFreq[0] = (float)(m->m_freqMin * step);
m->m_bandScalar = 2.0f / (float)m->m_wfx->nSamplesPerSec;
m->m_bandOut = (float*)calloc(m->m_nBands * sizeof(float), 1);
for (int iBand = 1; iBand < m->m_nBands; ++iBand)
{
m->m_bandFreq[iBand] = (float)(m->m_bandFreq[iBand - 1] * step);
}
if (m->m_smoothing)
{
m->m_bandTmpOut = (float*)calloc(m->m_nBands * sizeof(float), 1);
}
}
}
// setup WAVE buffers
if (m->m_waveSize)
{
m->m_waveOut = (float*)calloc(m->m_waveSize * sizeof(float), 1);
if (m->m_nBands)
{
m->m_dw = (float)m->m_waveSize / (float)m->m_nBands;
m->m_waveScalar = (float)(1.0f / m->m_dw);
m->m_waveBandOut = (float*)calloc(m->m_nBands * sizeof(float), 1);
// smoothing needs an additional temp buffer
if (m->m_smoothing)
{
m->m_waveBandTmpOut = (float*)calloc(m->m_nBands * sizeof(float), 1);
}
}
}
}
// values that dont need fft/band reinitialization
m->m_dynamicVolume = max(0, RmReadInt(rm, L"DynamicVolume", m->m_dynamicVolume));
m->m_smoothingMode = min(max(0, RmReadInt(rm, L"SmoothingMode", m->m_smoothingMode)), 2);
// update wait time
m->m_updatesPerSecond = min(240, RmReadDouble(rm, L"UpdatesPerSecond", -1));
if (m->m_updatesPerSecond > 0) {
m->m_waitUpdate = std::chrono::duration<double>(1 / m->m_updatesPerSecond);
}
// (re)parse envelope values
m->m_envRMS[0] = max(0, RmReadInt(rm, L"RMSAttack", m->m_envRMS[0]));
m->m_envRMS[1] = max(0, RmReadInt(rm, L"RMSDecay", m->m_envRMS[1]));
m->m_envPeak[0] = max(0, RmReadInt(rm, L"PeakAttack", m->m_envPeak[0]));
m->m_envPeak[1] = max(0, RmReadInt(rm, L"PeakDecay", m->m_envPeak[1]));
m->m_envFFT[0] = max(0, RmReadInt(rm, L"FFTAttack", m->m_envFFT[0]));
m->m_envFFT[1] = max(0, RmReadInt(rm, L"FFTDecay", m->m_envFFT[1]));
// (re)parse gain constants
m->m_gainRMS = max(0.0, RmReadDouble(rm, L"RMSGain", m->m_gainRMS));
m->m_gainPeak = max(0.0, RmReadDouble(rm, L"PeakGain", m->m_gainPeak));
m->m_sensitivity = 10 * log10(m->m_fftSize); // default dynamic range/noise floor
m->m_sensitivity = 10 / max(1.0, RmReadDouble(rm, L"Sensitivity", m->m_sensitivity));
// regenerate filter constants
if (m->m_wfx)
{
const double freq = m->m_wfx->nSamplesPerSec;
m->m_kRMS[0] = (float)exp(log10(0.01) / (freq * (double)m->m_envRMS[0] * 0.001));
m->m_kRMS[1] = (float)exp(log10(0.01) / (freq * (double)m->m_envRMS[1] * 0.001));
m->m_kPeak[0] = (float)exp(log10(0.01) / (freq * (double)m->m_envPeak[0] * 0.001));
m->m_kPeak[1] = (float)exp(log10(0.01) / (freq * (double)m->m_envPeak[1] * 0.001));
if (m->m_fftSize)
{
m->m_kFFT[0] = (float)exp(log10(0.01) / (freq * 0.001 * (double)m->m_envFFT[0] * 0.001));
m->m_kFFT[1] = (float)exp(log10(0.01) / (freq * 0.001 * (double)m->m_envFFT[1] * 0.001));
}
}
if (!m->m_updateLoopThread && m->m_updatesPerSecond != -2)
{
// create separate thread with event-driven update loop
m->m_updateLoopThread = new std::thread(&Measure::DoCaptureLoop, m);
m->m_updateLoopThread->detach();
}
else if (m->m_updateLoopThread && m->m_updatesPerSecond == -2)
{
SetEvent(m->m_hStopEvent);
//m->m_updateLoopThread->join();
//delete m->m_updateLoopThread;
}
}
// parse FFT index request
m->m_fftIdx = max(0, RmReadInt(rm, L"FFTIdx", m->m_fftIdx));
m->m_fftIdx = m->m_parent ?
min(m->m_parent->m_fftBufferSize / 2, m->m_fftIdx) :
min(m->m_fftBufferSize / 2, m->m_fftIdx);
// parse WAVE index request
m->m_waveIdx = max(0, RmReadInt(rm, L"WaveIdx", m->m_waveIdx));
m->m_waveIdx = m->m_parent ?
min(m->m_parent->m_waveSize, m->m_waveIdx) :
min(m->m_waveSize, m->m_waveIdx);
// parse band index request
m->m_bandIdx = max(0, RmReadInt(rm, L"BandIdx", m->m_bandIdx));
m->m_bandIdx = m->m_parent ?
min(m->m_parent->m_nBands, m->m_bandIdx) :
min(m->m_nBands, m->m_bandIdx);
}
/**
* Update the measure.
*
* @param[in] data Measure instance pointer.
* @return Latest value - typically an audio level between 0.0 and 1.0.
*/
PLUGIN_EXPORT double Update(void* data)
{
Measure* m = (Measure*)data;
Measure* parent = m->m_parent ? m->m_parent : m;
// rainmeter style update loop - not recommended
if (!m->m_parent && m->m_updatesPerSecond == -2)
{
HRESULT hr = m->UpdateParent();
switch (hr)
{
case S_OK:
// everything is fine, update measures
break;
case S_FALSE:
// silence detected, but ignore to still update other types of measures like FFTFREQ
break;
case AUDCLNT_E_BUFFER_ERROR:
case AUDCLNT_E_DEVICE_INVALIDATED:
case AUDCLNT_E_SERVICE_NOT_RUNNING:
// error detected, release device
m->DeviceRelease();
return 0.0;
}
}
switch (m->m_type)
{
case Measure::TYPE_BAND:
if (parent->m_clCapture && parent->m_nBands && m->m_bandIdx < parent->m_nBands)
{
return parent->m_bandOut[m->m_bandIdx];
}
break;
case Measure::TYPE_WAVEBAND:
if (parent->m_clCapture && parent->m_nBands && parent->m_waveSize && m->m_bandIdx < parent->m_nBands)
{
return parent->m_waveBandOut[m->m_bandIdx];
}
break;
case Measure::TYPE_FFT:
if (parent->m_clCapture && parent->m_fftBufferSize && m->m_fftIdx < parent->m_fftBufferSize)
{
return max(0, parent->m_sensitivity * log10(CLAMP01(parent->m_fftOut[m->m_fftIdx])) + 1.0);
}
break;
case Measure::TYPE_FFTFREQ:
if (parent->m_clCapture && parent->m_fftBufferSize && m->m_fftIdx <= (parent->m_fftBufferSize * 0.5))
{
return ((float)m->m_fftIdx) * m->m_df;
}
break;
case Measure::TYPE_BANDFREQ:
if (parent->m_clCapture && parent->m_nBands && m->m_bandIdx < parent->m_nBands)
{
return parent->m_bandFreq[m->m_bandIdx];
}
break;
case Measure::TYPE_WAVE:
if (parent->m_clCapture && parent->m_waveSize && m->m_waveIdx < parent->m_waveSize)
{
return parent->m_waveOut[m->m_waveIdx];
}
break;
case Measure::TYPE_RMS:
if (parent->m_clCapture && parent->m_rms)
{
return CLAMP01(sqrt(parent->m_rms[m->m_channel]) * parent->m_gainRMS);
}
break;
case Measure::TYPE_PEAK:
if (parent->m_clCapture && parent->m_peak)
{
return CLAMP01(parent->m_peak[m->m_channel] * parent->m_gainPeak);
}
break;
case Measure::TYPE_DEV_STATUS:
if (parent->m_dev)
{
DWORD state;
if (parent->m_dev->GetState(&state) == S_OK && state == DEVICE_STATE_ACTIVE)
{
return 1.0;
}
}
break;
case Measure::TYPE_BUFFERSTATUS:
if (parent->m_nFramesNext > 0)
{
return parent->m_nFramesNext;
}
break;
}
return 0.0;
}
/**
* Indicates that the application working directory will not be reset by the plugin.
*/
PLUGIN_EXPORT void OverrideDirectory()
{
}
/**
* Get a string value from the measure.
*
* @param[in] data Measure instance pointer.
* @return String value - must be copied out by the caller.
*/
PLUGIN_EXPORT LPCWSTR GetString(void* data)
{
Measure* m = (Measure*)data;
Measure* parent = m->m_parent ? m->m_parent : m;
static WCHAR buffer[4096];
const WCHAR* s_fmtName[Measure::NUM_FORMATS] =
{
L"<invalid>", // FMT_INVALID
L"PCM 16b", // FMT_PCM_S16
L"PCM 32b", // FMT_PCM_F32
};
buffer[0] = '\0';
switch (m->m_type)
{
default:
// return NULL for any numeric values, so Rainmeter can auto-convert them.
return NULL;
case Measure::TYPE_FORMAT:
if (parent->m_wfx)
{
_snwprintf_s(buffer, _TRUNCATE, L"%dHz %s %dch", parent->m_wfx->nSamplesPerSec,
s_fmtName[parent->m_format], parent->m_wfx->nChannels);
}
break;
case Measure::TYPE_DEV_NAME:
return parent->m_devName;
case Measure::TYPE_DEV_ID:
if (parent->m_dev)
{
LPWSTR pwszID = NULL;
if (parent->m_dev->GetId(&pwszID) == S_OK)
{
_snwprintf_s(buffer, _TRUNCATE, L"%s", pwszID);
CoTaskMemFree(pwszID);
}
}
break;
case Measure::TYPE_DEV_LIST:
if (parent->m_enum)
{
IMMDeviceCollection* collection = NULL;
if (parent->m_enum->EnumAudioEndpoints(parent->m_port == Measure::PORT_OUTPUT ? eRender : eCapture,
DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED, &collection) == S_OK)
{
WCHAR* d = &buffer[0];
UINT nDevices;
collection->GetCount(&nDevices);
for (ULONG iDevice = 0; iDevice < nDevices; ++iDevice)
{
IMMDevice* device = NULL;
IPropertyStore* props = NULL;
if (collection->Item(iDevice, &device) == S_OK && device->OpenPropertyStore(STGM_READ, &props) == S_OK)
{
LPWSTR id = NULL;
PROPVARIANT varName;
PropVariantInit(&varName);
if (device->GetId(&id) == S_OK && props->GetValue(PKEY_Device_FriendlyName, &varName) == S_OK)
{
d += _snwprintf_s(d, (sizeof(buffer) + (UINT32)buffer - (UINT32)d) / sizeof(WCHAR), _TRUNCATE,
L"%s%s: %s", iDevice > 0 ? L"\n" : L"", id, varName.pwszVal);
}
if (id) CoTaskMemFree(id);
PropVariantClear(&varName);
}
SAFE_RELEASE(props);
SAFE_RELEASE(device);
}
}
SAFE_RELEASE(collection);
}
break;