CSL  6.0
CGestalt.h
Go to the documentation of this file.
1 ///
2 /// CGestalt.h -- the CSL 6.0 CGestalt (system utility) class specification,
3 /// system constants, logging, and utility methods; SAFE_MALLOC/SAFE_FREE macros
4 /// The logging system has a number of print methods that use the printf var-args format
5 /// and can be filtered on verbosity.
6 ///
7 /// There's a variety of random-number functions.
8 ///
9 /// The timer sleep methods are interruptable with a global flag.
10 ///
11 /// The MVC Observer/Subject or dependency pattern classes are also here.
12 ///
13 /// See the copyright notice and acknowledgment of authors in the file COPYRIGHT
14 ///
15 
16 #ifndef CSL_Gestalt_H
17 #define CSL_Gestalt_H
18 
19 #include "CSL_Types.h" // The system default values are defined there
20 #include "CSL_Exceptions.h" // The system default values are defined there
21 
22 #include <stdarg.h> // for va_arg, vaList, etc.
23 #include <string>
24 
25 #ifdef USE_JUCE
26  #include "JuceHeader.h"
27 // #include "modules/juce_core/time/juce_Time.h"
28  #include <sys/time.h>
29 #else
30  #include <sys/time.h>
31 #endif
32 
33 namespace csl {
34 
35 ///
36 /// The CSL system defaults class
37 ///
38 
39 class CGestalt {
40 
41 public: // Accessor (getter/setter) methods
42 
43  static unsigned frameRate(); ///< default frame rate
44  static float frameRateF(); ///< default frame rate as a float
45  static void setFrameRate(unsigned frameRate);
46  static sample framePeriod(); ///< default frame rate
47 
48  static unsigned numInChannels(); ///< default number of input channels
49  static void setNumInChannels(unsigned numChannels);
50 
51  static unsigned numOutChannels(); ///< default number of output channels
52  static void setNumOutChannels(unsigned numChannels);
53 
54  static unsigned blockSize(); ///< the default block size
55  static void setBlockSize(unsigned blockSize);
56 
57  static unsigned maxBufferFrames(); ///< the max num frames that can be requested
58  static void setMaxBufferFrames(unsigned numFrames);
59 
60  static unsigned maxSndFileFrames(); ///< the max num frames that can be cached
61  static void setMaxSndFileFrames(unsigned numFrames);
62 
63  static unsigned sndFileFrames(); ///< the default num frames that are cached
64  static void setSndFileFrames(unsigned numFrames);
65 
66  static unsigned verbosity(); ///< the default logging verbosity
67  static void setVerbosity(unsigned verbosity); // (0 = only fatal errors, 1 = warnings,
68  // 2 = most msgs, 3 = include info msgs)
69 
70  static unsigned loggingPeriod(); ///< the default logging period
71  static void setLoggingPeriod(unsigned loggingPeriod);
72 
73  static unsigned outPort(); ///< the default RemoteIO output port
74  static void setOutPort(unsigned outPort);
75 
76  static std::string dataFolder(); ///< the default directory for test data
77  static void setDataFolder(std::string dFolder); ///< typ. "~/Code/CSL/CSL_Data/"
78 
79  static bool stopNow(); ///< flag to stop threads and timers
80  static void setStopNow();
81  static void clearStopNow();
82 
83  static std::string initFileText(char key); ///< read/write the init file (typ. ~/.cslrc)
84  static void storeToInitFile(char key, std::string data);
85 
86  static std::string sndFileName(); ///< pick a new sound file name to use based on OUT_SFILE_NAME
87 
88  static unsigned screenWidth(); ///< current screen width
89  static void setScreenWidth(unsigned numPixels);
90  static unsigned screenHeight(); ///< current screen height
91  static void setScreenHeight(unsigned numPixels);
92 
93 };
94 
95 /////////////////////////////////////////////////////////////////////////
96 ///
97 /// Useful Macros
98 ///
99 
100 /// SAFE_MALLOC = safe malloc using new operator
101 /// used like: SAFE_MALLOC(mSampleBuffer, sample, mWindowSize);
102 
103 #define SAFE_MALLOC(ptr, type, len) \
104  ptr = new type[len]; \
105  if ((char *) ptr == NULL) \
106  throw MemoryError("can't allocate buffer")
107 
108 /// Matrix allocate
109 /// SAFE_MATMALLOC(mRealSpectrum, FloatArray, mNumFrames, float, mWinSize);
110 /// SAFE_MATMALLOC(mSpectBands, FloatArray, mNumFrames, float, NUM_BANDS)
111 
112 #define SAFE_MATMALLOC(ptr, mtype, num, type, len) \
113  ptr = new mtype[num]; \
114  if ((char *) ptr == NULL) \
115  throw MemoryError("can't allocate buffer"); \
116  for (unsigned i = 0; i < num; i++) { \
117  ptr[i] = new type[len]; \
118  if ((char *) ptr[i] == NULL) \
119  throw MemoryError("can't allocate buffer"); \
120  }
121 
122 /// Structure allocate
123 /// SAFE_STRUCTMALLOC(mRealSpectrum, FloatArray, mNumFrames, float);
124 
125 #define SAFE_STRUCTMALLOC(ptr, mtype, num, type) \
126  ptr = new mtype[num]; \
127  if ((char *) ptr == NULL) \
128  throw MemoryError("can't allocate buffer"); \
129  for (unsigned i = 0; i < num; i++) { \
130  ptr[i] = new type; \
131  if ((char *) ptr[i] == NULL) \
132  throw MemoryError("can't allocate buffer"); \
133  }
134 
135 // Safe free and matrix version
136 
137 #define SAFE_FREE(ptr) \
138  if (ptr) \
139  delete[] ptr
140 
141 #define SAFE_MATFREE(ptr, num) \
142  for (unsigned i = 0; i < num; i++) { \
143  if (ptr[i]) \
144  delete[] ptr[i]; \
145  } \
146  delete[] ptr
147 
148 /////////////////////////////////////////////////////////////////////////
149 ///
150 /// Logging functions are standard C functions
151 ///
152 
153 #ifdef CSL_ENUMS
154 typedef enum { ///< Enumeration for log message severity level
155  kLogInfo, ///< you can filter on this.
159 } LogLevel;
160 #else
161  #define kLogInfo 0
162  #define kLogWarning 1
163  #define kLogError 2
164  #define kLogFatal 3
165  typedef int LogLevel;
166 #endif
167 
168 ///
169 /// These are the public logging messages
170 ///
171 
172 void logMsg(const char * format, ...); ///< default is kLogInfo severity
173 void logMsg(LogLevel level, const char* format, ...);
174 
175 void logMsgNN(const char * format, ...); ///< no-newline versions
176 void logMsgNN(LogLevel level, const char* format, ...);
177 
178 void logLine(); ///< Log the file & line #
179 void logURL(); ///< log file/line as a URL
180 
181 void vlogMsg(bool cz, LogLevel level, const char * format, va_list args);
182 
183 
184 /////////////////////////////////////////////////////////////////////////
185 ///
186 /// Misc. global functions in the csl namespace
187 ///
188 
189 /// Sleep for micro-seconds, milli-seconds or seconds
190 /// These are interruptable and return true if interrupted; false for normal termination
191 
192 bool sleepUsec(float dur); ///< sleep for dur usec, msec or sec
193 bool sleepMsec(float dur);
194 bool sleepSec(float dur);
195 
196 Timestamp timeNow(); ///< high-accuracy system or IO time in ticks
197 float fTimeNow(); ///< system or IO time in seconds
198 
199 /// Which kind of accurate timer to use?
200 
201 // #define C_TIME Time::getHighResolutionTicks()
202 #define C_TIME juce::Time::getMillisecondCounter()
203 
204 ///
205 /// A variety of useful random-number functions
206 ///
207 
208 float fRandZ(void); ///< 0 - 1 (name: zero)
209 float fRand1(void); ///< -1 - 1 (one)
210 float fRandV(float val); ///< 0 - v (val)
211 
212 float fRandM(float minV, float maxV); ///< min - max (min/max)
213 float fRandR(float base, float range); ///< b +- (r * b) (range)
214 float fRandB(float base, float range); ///< b +- r (base)
215 
216 /// Integer rands
217 
218 int iRandV(int val); ///< 0 - v (val)
219 int iRandM(int minV, int maxV); ///< min - max (min/max)
220 int iRandB(int base, int range); ///< b +- r (base)
221 
222 // Bool coin-toss rands
223 
224 bool coin(); ///< Answer true or false
225 bool coin(float bias); ///< Answer with a bias (1 --> always true)
226 
227 
228 /// MIDI Conversions
229 
230 /// keyToFreq -- converts from MIDI key numbers (1 - 127) to frequency in Hz.
231 
232 float keyToFreq(unsigned midiKey);
233 
234 /// freqToKey -- converts from frequency in Hz to MIDI key #
235 
236 unsigned freqToKey(float frequency);
237 
238 
239 /////////////////////////////////////////////////////////////////////////
240 ///
241 /// MVC Observer/Subject or dependency pattern
242 /// Advanced version with filtered observer updates
243 ///
244 
245 class Observer; ///< Forward declaration
246 typedef std::vector <Observer *> ObserverVector;
247 
248 ///
249 /// The Model/Observable/Subject class; instances of its subclasses should send themselves,
250 /// this->changed(some_data);
251 /// on "relevant" state changes; the code they inherit (from Model) manages updating the list
252 /// of observer/dependent objects in that they each receive
253 /// update(some_data);
254 /// and can access the model-passed data (the model might pass "this").
255 ///
256 /// Note the addition of timers, so observers can request no more than a certain rate of updates.
257 
258 class Model {
259 public:
260  Model() : mHasObservers(false), mHasObserverMap(false), mUpdateTime(0), mPeriod(0) { }; ///< constructor
261  virtual ~Model() { /* no-op */ }; ///< (possibly notify obersvers on my death)
262 
263  void attachObserver(Observer *); ///< register/remove observers
264  void detachObserver(Observer *);
265 
266  void changed(void * argument); ///< this is what I send to myself to notify my observers;
267  /// It's not overridden in general.
268  /// It results in the observers receiving update() calls
269  ///< override evaluate to filter updates to the observer map
270  virtual int evaluate(void * argument) { return 0; };
271 
272 private:
273  ObserverVector mObservers; ///< the private vector of observers
274  std::map<int, ObserverVector> mObsMap; ///< the private map-by-key of observers
275  bool mHasObservers; ///< whether there are any observers (for fast checking)
276  bool mHasObserverMap; ///< whether there are any observers (for fast checking)
277  float mUpdateTime; ///< when I last updated
278  float mPeriod; ///< update rate in sec
279 };
280 
281 ///
282 /// CSL Observer/Dependent/Monitor class -- instances receive update() messages from "models"
283 /// and handle some argument, which may be the model's "this" pointer, or any other data.
284 ///
285 /// Subclasses must override the update() method to do their stuff -- grabbing a data buffer,
286 /// operating on their model, or displaying something.
287 ///
288 /// The mPeriod is the requested period for updates.
289 ///
290 /// The mKey is an int value for the model's evaluate() function to filter updates
291 /// i.e., if the model implements evaluate(void*), and its return value is non-zero and
292 /// matches the observer's key, then an update will be sent. An example of using this is
293 /// a MIDI IO object's channel filtering for MIDI listeners (observers).
294 ///
295 
296 class Observer {
297 public:
298  Observer() { mPeriod = 0; mKey = 0; }; ///< constructor
299  virtual ~Observer() { }; ///< virtual destructor (don't notify or delete
300  /// observers in this version)
301  float mPeriod; ///< max update rate
302  int mKey; ///< key selector (e.g., MIDI chan)
303  /// I receive update() mesages from my model;
304  virtual void update(void * arg) = 0; ///< this will be implemented in subclasses.
305 };
306 
307 } // end of namespace
308 
309 #endif
void logMsg(const char *format,...)
These are the public logging messages.
Definition: CGestalt.cpp:292
static unsigned verbosity()
the default logging verbosity
Definition: CGestalt.cpp:60
float fRandV(float val)
0 - v (val)
Definition: CGestalt.cpp:444
static void setMaxSndFileFrames(unsigned numFrames)
Definition: CGestalt.cpp:90
static std::string initFileText(char key)
read/write the init file (typ. ~/.cslrc)
Definition: CGestalt.cpp:126
The Model/Observable/Subject class; instances of its subclasses should send themselves, this->changed(some_data); on "relevant" state changes; the code they inherit (from Model) manages updating the list of observer/dependent objects in that they each receive update(some_data); and can access the model-passed data (the model might pass "this").
Definition: CGestalt.h:258
static void setMaxBufferFrames(unsigned numFrames)
Definition: CGestalt.cpp:89
bool sleepMsec(float dur)
Definition: CGestalt.cpp:372
static unsigned screenWidth()
current screen width
Definition: CGestalt.cpp:66
AdditiveInstrument.h – Sum-of-sines synthesis instrument class.
Definition: Accessor.h:17
static void setScreenWidth(unsigned numPixels)
Definition: CGestalt.cpp:103
static unsigned sndFileFrames()
the default num frames that are cached
Definition: CGestalt.cpp:55
static std::string sndFileName()
pick a new sound file name to use based on OUT_SFILE_NAME
Definition: CGestalt.cpp:186
static void storeToInitFile(char key, std::string data)
Definition: CGestalt.cpp:145
ObserverVector mObservers
the private vector of observers
Definition: CGestalt.h:270
virtual void update(void *arg)=0
this will be implemented in subclasses.
static unsigned maxSndFileFrames()
the max num frames that can be cached
Definition: CGestalt.cpp:56
CSL Observer/Dependent/Monitor class – instances receive update() messages from "models" and handle ...
Definition: CGestalt.h:296
bool mHasObserverMap
whether there are any observers (for fast checking)
Definition: CGestalt.h:276
static unsigned numOutChannels()
default number of output channels
Definition: CGestalt.cpp:59
static bool stopNow()
flag to stop threads and timers
Definition: CGestalt.cpp:64
static unsigned loggingPeriod()
the default logging period
Definition: CGestalt.cpp:61
static unsigned maxBufferFrames()
the max num frames that can be requested
Definition: CGestalt.cpp:54
unsigned long Timestamp
Timestamp type: we assume that we can get the host's best guess at the IO word clock (normally passed...
Definition: CSL_Types.h:261
static sample framePeriod()
default frame rate
Definition: CGestalt.cpp:53
void logURL()
log file/line as a URL
Definition: CGestalt.cpp:328
static unsigned screenHeight()
current screen height
Definition: CGestalt.cpp:67
void changed(void *argument)
this is what I send to myself to notify my observers; It's not overridden in general. It results in the observers receiving update() calls < override evaluate to filter updates to the observer map
Definition: CGestalt.cpp:540
bool mHasObservers
whether there are any observers (for fast checking)
Definition: CGestalt.h:275
static void setNumOutChannels(unsigned numChannels)
Definition: CGestalt.cpp:94
float keyToFreq(unsigned midiKey)
MIDI Conversions.
Definition: CGestalt.cpp:483
static float frameRateF()
default frame rate as a float
Definition: CGestalt.cpp:52
The CSL system defaults class.
Definition: CGestalt.h:39
static void setNumInChannels(unsigned numChannels)
Definition: CGestalt.cpp:93
static void clearStopNow()
Definition: CGestalt.cpp:101
static unsigned blockSize()
the default block size
Definition: CGestalt.cpp:57
bool coin()
Answer true or false.
Definition: CGestalt.cpp:470
std::map< int, ObserverVector > mObsMap
the private map-by-key of observers
Definition: CGestalt.h:274
float mPeriod
virtual destructor (don't notify or delete observers in this version)
Definition: CGestalt.h:299
virtual ~Model()
constructor
Definition: CGestalt.h:261
float fRandM(float minV, float maxV)
min - max (min/max)
Definition: CGestalt.cpp:426
virtual int evaluate(void *argument)
Definition: CGestalt.h:270
float sample
(could be changed to int, or double)
Definition: CSL_Types.h:191
static void setLoggingPeriod(unsigned loggingPeriod)
Definition: CGestalt.cpp:96
float fRandB(float base, float range)
b +- r (base)
Definition: CGestalt.cpp:438
static unsigned frameRate()
default frame rate
Definition: CGestalt.cpp:51
static void setBlockSize(unsigned blockSize)
Definition: CGestalt.cpp:92
LogLevel
Logging functions are standard C functions.
Definition: CGestalt.h:154
unsigned freqToKey(float frequency)
freqToKey – converts from frequency in Hz to MIDI key #
Definition: CGestalt.cpp:490
static unsigned numInChannels()
default number of input channels
Definition: CGestalt.cpp:58
float mUpdateTime
when I last updated
Definition: CGestalt.h:277
int iRandV(int val)
Integer rands.
Definition: CGestalt.cpp:452
void vlogMsg(bool cz, LogLevel level, const char *format, va_list args)
Definition: CGestalt.cpp:234
static void setSndFileFrames(unsigned numFrames)
Definition: CGestalt.cpp:91
static void setFrameRate(unsigned frameRate)
Definition: CGestalt.cpp:81
bool sleepSec(float dur)
Definition: CGestalt.cpp:379
int iRandM(int minV, int maxV)
min - max (min/max)
Definition: CGestalt.cpp:458
static void setVerbosity(unsigned verbosity)
Definition: CGestalt.cpp:95
void detachObserver(Observer *)
Definition: CGestalt.cpp:518
float fRandZ(void)
A variety of useful random-number functions.
Definition: CGestalt.cpp:414
void attachObserver(Observer *)
(possibly notify obersvers on my death)
Definition: CGestalt.cpp:502
int mKey
key selector (e.g., MIDI chan) I receive update() mesages from my model;
Definition: CGestalt.h:302
static void setScreenHeight(unsigned numPixels)
Definition: CGestalt.cpp:104
float fTimeNow()
system or IO time in seconds
Definition: CGestalt.cpp:398
void logMsgNN(const char *format,...)
no-newline versions
Definition: CGestalt.cpp:299
bool sleepUsec(float dur)
Misc. global functions in the csl namespace.
Definition: CGestalt.cpp:345
std::vector< Observer * > ObserverVector
Forward declaration.
Definition: CGestalt.h:245
float mPeriod
update rate in sec
Definition: CGestalt.h:278
Enumeration for log message severity level.
Definition: CGestalt.h:155
static unsigned outPort()
the default RemoteIO output port
Definition: CGestalt.cpp:62
virtual ~Observer()
constructor
Definition: CGestalt.h:299
float fRand1(void)
-1 - 1 (one)
Definition: CGestalt.cpp:420
static void setStopNow()
Definition: CGestalt.cpp:100
int iRandB(int base, int range)
b +- r (base)
Definition: CGestalt.cpp:464
Timestamp timeNow()
high-accuracy system or IO time in ticks
Definition: CGestalt.cpp:386
float fRandR(float base, float range)
b +- (r * b) (range)
Definition: CGestalt.cpp:432
static void setDataFolder(std::string dFolder)
typ. "~/Code/CSL/CSL_Data/"
Definition: CGestalt.cpp:98
void logLine()
Log the file & line #.
Definition: CGestalt.cpp:322
static std::string dataFolder()
the default directory for test data
Definition: CGestalt.cpp:71
static void setOutPort(unsigned outPort)
Definition: CGestalt.cpp:97