Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

546 lines
19KB

  1. #ifndef STK_STK_H
  2. #define STK_STK_H
  3. #include <string>
  4. #include <iostream>
  5. #include <sstream>
  6. #include <vector>
  7. #include <cstdlib>
  8. /*! \namespace stk
  9. \brief The STK namespace.
  10. Most Stk classes are defined within the STK namespace. Exceptions
  11. to this include the classes RtAudio, RtMidi, and RtError.
  12. */
  13. namespace stk {
  14. /***************************************************/
  15. /*! \class Stk
  16. \brief STK base class
  17. Nearly all STK classes inherit from this class.
  18. The global sample rate and rawwave path variables
  19. can be queried and modified via Stk. In addition,
  20. this class provides error handling and
  21. byte-swapping functions.
  22. The Synthesis ToolKit in C++ (STK) is a set of open source audio
  23. signal processing and algorithmic synthesis classes written in the
  24. C++ programming language. STK was designed to facilitate rapid
  25. development of music synthesis and audio processing software, with
  26. an emphasis on cross-platform functionality, realtime control,
  27. ease of use, and educational example code. STK currently runs
  28. with realtime support (audio and MIDI) on Linux, Macintosh OS X,
  29. and Windows computer platforms. Generic, non-realtime support has
  30. been tested under NeXTStep, Sun, and other platforms and should
  31. work with any standard C++ compiler.
  32. STK WWW site: http://ccrma.stanford.edu/software/stk/
  33. The Synthesis ToolKit in C++ (STK)
  34. Copyright (c) 1995-2011 Perry R. Cook and Gary P. Scavone
  35. Permission is hereby granted, free of charge, to any person
  36. obtaining a copy of this software and associated documentation files
  37. (the "Software"), to deal in the Software without restriction,
  38. including without limitation the rights to use, copy, modify, merge,
  39. publish, distribute, sublicense, and/or sell copies of the Software,
  40. and to permit persons to whom the Software is furnished to do so,
  41. subject to the following conditions:
  42. The above copyright notice and this permission notice shall be
  43. included in all copies or substantial portions of the Software.
  44. Any person wishing to distribute modifications to the Software is
  45. asked to send the modifications to the original developer so that
  46. they can be incorporated into the canonical version. This is,
  47. however, not a binding provision of this license.
  48. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  49. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  50. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  51. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
  52. ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
  53. CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  54. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  55. */
  56. /***************************************************/
  57. //#define _STK_DEBUG_
  58. // Most data in STK is passed and calculated with the
  59. // following user-definable floating-point type. You
  60. // can change this to "float" if you prefer or perhaps
  61. // a "long double" in the future.
  62. typedef double StkFloat;
  63. //! STK error handling class.
  64. /*!
  65. This is a fairly abstract exception handling class. There could
  66. be sub-classes to take care of more specific error conditions ... or
  67. not.
  68. */
  69. class StkError
  70. {
  71. public:
  72. enum Type {
  73. STATUS,
  74. WARNING,
  75. DEBUG_PRINT,
  76. MEMORY_ALLOCATION,
  77. MEMORY_ACCESS,
  78. FUNCTION_ARGUMENT,
  79. FILE_NOT_FOUND,
  80. FILE_UNKNOWN_FORMAT,
  81. FILE_ERROR,
  82. PROCESS_THREAD,
  83. PROCESS_SOCKET,
  84. PROCESS_SOCKET_IPADDR,
  85. AUDIO_SYSTEM,
  86. MIDI_SYSTEM,
  87. UNSPECIFIED
  88. };
  89. protected:
  90. std::string message_;
  91. Type type_;
  92. public:
  93. //! The constructor.
  94. StkError(const std::string& message, Type type = StkError::UNSPECIFIED)
  95. : message_(message), type_(type) {}
  96. //! The destructor.
  97. virtual ~StkError(void) {};
  98. //! Prints thrown error message to stderr.
  99. virtual void printMessage(void) { std::cerr << '\n' << message_ << "\n\n"; }
  100. //! Returns the thrown error message type.
  101. virtual const Type& getType(void) { return type_; }
  102. //! Returns the thrown error message string.
  103. virtual const std::string& getMessage(void) { return message_; }
  104. //! Returns the thrown error message as a C string.
  105. virtual const char *getMessageCString(void) { return message_.c_str(); }
  106. };
  107. class Stk
  108. {
  109. public:
  110. typedef unsigned long StkFormat;
  111. static const StkFormat STK_SINT8; /*!< -128 to +127 */
  112. static const StkFormat STK_SINT16; /*!< -32768 to +32767 */
  113. static const StkFormat STK_SINT24; /*!< Lower 3 bytes of 32-bit signed integer. */
  114. static const StkFormat STK_SINT32; /*!< -2147483648 to +2147483647. */
  115. static const StkFormat STK_FLOAT32; /*!< Normalized between plus/minus 1.0. */
  116. static const StkFormat STK_FLOAT64; /*!< Normalized between plus/minus 1.0. */
  117. //! Static method that returns the current STK sample rate.
  118. static StkFloat sampleRate( void ) { return srate_; }
  119. //! Static method that sets the STK sample rate.
  120. /*!
  121. The sample rate set using this method is queried by all STK
  122. classes that depend on its value. It is initialized to the
  123. default SRATE set in Stk.h. Many STK classes use the sample rate
  124. during instantiation. Therefore, if you wish to use a rate that
  125. is different from the default rate, it is imperative that it be
  126. set \e BEFORE STK objects are instantiated. A few classes that
  127. make use of the global STK sample rate are automatically notified
  128. when the rate changes so that internal class data can be
  129. appropriately updated. However, this has not been fully
  130. implemented. Specifically, classes that appropriately update
  131. their own data when either a setFrequency() or noteOn() function
  132. is called do not currently receive the automatic notification of
  133. rate change. If the user wants a specific class instance to
  134. ignore such notifications, perhaps in a multi-rate context, the
  135. function Stk::ignoreSampleRateChange() should be called.
  136. */
  137. static void setSampleRate( StkFloat rate );
  138. //! A function to enable/disable the automatic updating of class data when the STK sample rate changes.
  139. /*!
  140. This function allows the user to enable or disable class data
  141. updates in response to global sample rate changes on a class by
  142. class basis.
  143. */
  144. void ignoreSampleRateChange( bool ignore = true ) { ignoreSampleRateChange_ = ignore; };
  145. //! Static method that returns the current rawwave path.
  146. static std::string rawwavePath(void) { return rawwavepath_; }
  147. //! Static method that sets the STK rawwave path.
  148. static void setRawwavePath( std::string path );
  149. //! Static method that byte-swaps a 16-bit data type.
  150. static void swap16( unsigned char *ptr );
  151. //! Static method that byte-swaps a 32-bit data type.
  152. static void swap32( unsigned char *ptr );
  153. //! Static method that byte-swaps a 64-bit data type.
  154. static void swap64( unsigned char *ptr );
  155. //! Static cross-platform method to sleep for a number of milliseconds.
  156. static void sleep( unsigned long milliseconds );
  157. //! Static method to check whether a value is within a specified range.
  158. static bool inRange( StkFloat value, StkFloat min, StkFloat max ) {
  159. if ( value < min ) return false;
  160. else if ( value > max ) return false;
  161. else return true;
  162. }
  163. //! Static function for error reporting and handling using c-strings.
  164. static void handleError( const char *message, StkError::Type type );
  165. //! Static function for error reporting and handling using c++ strings.
  166. static void handleError( std::string message, StkError::Type type );
  167. //! Toggle display of WARNING and STATUS messages.
  168. static void showWarnings( bool status ) { showWarnings_ = status; }
  169. //! Toggle display of error messages before throwing exceptions.
  170. static void printErrors( bool status ) { printErrors_ = status; }
  171. private:
  172. static StkFloat srate_;
  173. static std::string rawwavepath_;
  174. static bool showWarnings_;
  175. static bool printErrors_;
  176. static std::vector<Stk *> alertList_;
  177. protected:
  178. static std::ostringstream oStream_;
  179. bool ignoreSampleRateChange_;
  180. //! Default constructor.
  181. Stk( void );
  182. //! Class destructor.
  183. virtual ~Stk( void );
  184. //! This function should be implemented in subclasses that depend on the sample rate.
  185. virtual void sampleRateChanged( StkFloat newRate, StkFloat oldRate );
  186. //! Add class pointer to list for sample rate change notification.
  187. void addSampleRateAlert( Stk *ptr );
  188. //! Remove class pointer from list for sample rate change notification.
  189. void removeSampleRateAlert( Stk *ptr );
  190. //! Internal function for error reporting that assumes message in \c oStream_ variable.
  191. void handleError( StkError::Type type );
  192. };
  193. /***************************************************/
  194. /*! \class StkFrames
  195. \brief An STK class to handle vectorized audio data.
  196. This class can hold single- or multi-channel audio data. The data
  197. type is always StkFloat and the channel format is always
  198. interleaved. In an effort to maintain efficiency, no
  199. out-of-bounds checks are performed in this class unless
  200. _STK_DEBUG_ is defined.
  201. Internally, the data is stored in a one-dimensional C array. An
  202. indexing operator is available to set and retrieve data values.
  203. Alternately, one can use pointers to access the data, using the
  204. index operator to get an address for a particular location in the
  205. data:
  206. StkFloat* ptr = &myStkFrames[0];
  207. Note that this class can also be used as a table with interpolating
  208. lookup.
  209. Possible future improvements in this class could include functions
  210. to convert to and return other data types.
  211. by Perry R. Cook and Gary P. Scavone, 1995-2011.
  212. */
  213. /***************************************************/
  214. class StkFrames
  215. {
  216. public:
  217. //! The default constructor initializes the frame data structure to size zero.
  218. StkFrames( unsigned int nFrames = 0, unsigned int nChannels = 0 );
  219. //! Overloaded constructor that initializes the frame data to the specified size with \c value.
  220. StkFrames( const StkFloat& value, unsigned int nFrames, unsigned int nChannels );
  221. //! The destructor.
  222. ~StkFrames();
  223. // A copy constructor.
  224. StkFrames( const StkFrames& f );
  225. // Assignment operator that returns a reference to self.
  226. StkFrames& operator= ( const StkFrames& f );
  227. //! Subscript operator that returns a reference to element \c n of self.
  228. /*!
  229. The result can be used as an lvalue. This reference is valid
  230. until the resize function is called or the array is destroyed. The
  231. index \c n must be between 0 and size less one. No range checking
  232. is performed unless _STK_DEBUG_ is defined.
  233. */
  234. StkFloat& operator[] ( size_t n );
  235. //! Subscript operator that returns the value at element \c n of self.
  236. /*!
  237. The index \c n must be between 0 and size less one. No range
  238. checking is performed unless _STK_DEBUG_ is defined.
  239. */
  240. StkFloat operator[] ( size_t n ) const;
  241. //! Assignment by sum operator into self.
  242. /*!
  243. The dimensions of the argument are expected to be the same as
  244. self. No range checking is performed unless _STK_DEBUG_ is
  245. defined.
  246. */
  247. void operator+= ( StkFrames& f );
  248. //! Assignment by product operator into self.
  249. /*!
  250. The dimensions of the argument are expected to be the same as
  251. self. No range checking is performed unless _STK_DEBUG_ is
  252. defined.
  253. */
  254. void operator*= ( StkFrames& f );
  255. //! Channel / frame subscript operator that returns a reference.
  256. /*!
  257. The result can be used as an lvalue. This reference is valid
  258. until the resize function is called or the array is destroyed. The
  259. \c frame index must be between 0 and frames() - 1. The \c channel
  260. index must be between 0 and channels() - 1. No range checking is
  261. performed unless _STK_DEBUG_ is defined.
  262. */
  263. StkFloat& operator() ( size_t frame, unsigned int channel );
  264. //! Channel / frame subscript operator that returns a value.
  265. /*!
  266. The \c frame index must be between 0 and frames() - 1. The \c
  267. channel index must be between 0 and channels() - 1. No range checking
  268. is performed unless _STK_DEBUG_ is defined.
  269. */
  270. StkFloat operator() ( size_t frame, unsigned int channel ) const;
  271. //! Return an interpolated value at the fractional frame index and channel.
  272. /*!
  273. This function performs linear interpolation. The \c frame
  274. index must be between 0.0 and frames() - 1. The \c channel index
  275. must be between 0 and channels() - 1. No range checking is
  276. performed unless _STK_DEBUG_ is defined.
  277. */
  278. StkFloat interpolate( StkFloat frame, unsigned int channel = 0 ) const;
  279. //! Returns the total number of audio samples represented by the object.
  280. size_t size() const { return size_; };
  281. //! Returns \e true if the object size is zero and \e false otherwise.
  282. bool empty() const;
  283. //! Resize self to represent the specified number of channels and frames.
  284. /*!
  285. Changes the size of self based on the number of frames and
  286. channels. No element assignment is performed. No memory
  287. deallocation occurs if the new size is smaller than the previous
  288. size. Further, no new memory is allocated when the new size is
  289. smaller or equal to a previously allocated size.
  290. */
  291. void resize( size_t nFrames, unsigned int nChannels = 1 );
  292. //! Resize self to represent the specified number of channels and frames and perform element initialization.
  293. /*!
  294. Changes the size of self based on the number of frames and
  295. channels, and assigns \c value to every element. No memory
  296. deallocation occurs if the new size is smaller than the previous
  297. size. Further, no new memory is allocated when the new size is
  298. smaller or equal to a previously allocated size.
  299. */
  300. void resize( size_t nFrames, unsigned int nChannels, StkFloat value );
  301. //! Return the number of channels represented by the data.
  302. unsigned int channels( void ) const { return nChannels_; };
  303. //! Return the number of sample frames represented by the data.
  304. unsigned int frames( void ) const { return nFrames_; };
  305. //! Set the sample rate associated with the StkFrames data.
  306. /*!
  307. By default, this value is set equal to the current STK sample
  308. rate at the time of instantiation.
  309. */
  310. void setDataRate( StkFloat rate ) { dataRate_ = rate; };
  311. //! Return the sample rate associated with the StkFrames data.
  312. /*!
  313. By default, this value is set equal to the current STK sample
  314. rate at the time of instantiation.
  315. */
  316. StkFloat dataRate( void ) const { return dataRate_; };
  317. private:
  318. StkFloat *data_;
  319. StkFloat dataRate_;
  320. size_t nFrames_;
  321. unsigned int nChannels_;
  322. size_t size_;
  323. size_t bufferSize_;
  324. };
  325. inline bool StkFrames :: empty() const
  326. {
  327. if ( size_ > 0 ) return false;
  328. else return true;
  329. }
  330. inline StkFloat& StkFrames :: operator[] ( size_t n )
  331. {
  332. #if defined(_STK_DEBUG_)
  333. if ( n >= size_ ) {
  334. std::ostringstream error;
  335. error << "StkFrames::operator[]: invalid index (" << n << ") value!";
  336. Stk::handleError( error.str(), StkError::MEMORY_ACCESS );
  337. }
  338. #endif
  339. return data_[n];
  340. }
  341. inline StkFloat StkFrames :: operator[] ( size_t n ) const
  342. {
  343. #if defined(_STK_DEBUG_)
  344. if ( n >= size_ ) {
  345. std::ostringstream error;
  346. error << "StkFrames::operator[]: invalid index (" << n << ") value!";
  347. Stk::handleError( error.str(), StkError::MEMORY_ACCESS );
  348. }
  349. #endif
  350. return data_[n];
  351. }
  352. inline StkFloat& StkFrames :: operator() ( size_t frame, unsigned int channel )
  353. {
  354. #if defined(_STK_DEBUG_)
  355. if ( frame >= nFrames_ || channel >= nChannels_ ) {
  356. std::ostringstream error;
  357. error << "StkFrames::operator(): invalid frame (" << frame << ") or channel (" << channel << ") value!";
  358. Stk::handleError( error.str(), StkError::MEMORY_ACCESS );
  359. }
  360. #endif
  361. return data_[ frame * nChannels_ + channel ];
  362. }
  363. inline StkFloat StkFrames :: operator() ( size_t frame, unsigned int channel ) const
  364. {
  365. #if defined(_STK_DEBUG_)
  366. if ( frame >= nFrames_ || channel >= nChannels_ ) {
  367. std::ostringstream error;
  368. error << "StkFrames::operator(): invalid frame (" << frame << ") or channel (" << channel << ") value!";
  369. Stk::handleError( error.str(), StkError::MEMORY_ACCESS );
  370. }
  371. #endif
  372. return data_[ frame * nChannels_ + channel ];
  373. }
  374. inline void StkFrames :: operator+= ( StkFrames& f )
  375. {
  376. #if defined(_STK_DEBUG_)
  377. if ( f.frames() != nFrames_ || f.channels() != nChannels_ ) {
  378. std::ostringstream error;
  379. error << "StkFrames::operator+=: frames argument must be of equal dimensions!";
  380. Stk::handleError( error.str(), StkError::MEMORY_ACCESS );
  381. }
  382. #endif
  383. StkFloat *fptr = &f[0];
  384. StkFloat *dptr = data_;
  385. for ( unsigned int i=0; i<size_; i++ )
  386. *dptr++ += *fptr++;
  387. }
  388. inline void StkFrames :: operator*= ( StkFrames& f )
  389. {
  390. #if defined(_STK_DEBUG_)
  391. if ( f.frames() != nFrames_ || f.channels() != nChannels_ ) {
  392. std::ostringstream error;
  393. error << "StkFrames::operator*=: frames argument must be of equal dimensions!";
  394. Stk::handleError( error.str(), StkError::MEMORY_ACCESS );
  395. }
  396. #endif
  397. StkFloat *fptr = &f[0];
  398. StkFloat *dptr = data_;
  399. for ( unsigned int i=0; i<size_; i++ )
  400. *dptr++ *= *fptr++;
  401. }
  402. // Here are a few other useful typedefs.
  403. typedef unsigned short UINT16;
  404. typedef unsigned int UINT32;
  405. typedef signed short SINT16;
  406. typedef signed int SINT32;
  407. typedef float FLOAT32;
  408. typedef double FLOAT64;
  409. // The default sampling rate.
  410. const StkFloat SRATE = 44100.0;
  411. // The default real-time audio input and output buffer size. If
  412. // clicks are occuring in the input and/or output sound stream, a
  413. // larger buffer size may help. Larger buffer sizes, however, produce
  414. // more latency.
  415. const unsigned int RT_BUFFER_SIZE = 512;
  416. // The default rawwave path value is set with the preprocessor
  417. // definition RAWWAVE_PATH. This can be specified as an argument to
  418. // the configure script, in an integrated development environment, or
  419. // below. The global STK rawwave path variable can be dynamically set
  420. // with the Stk::setRawwavePath() function. This value is
  421. // concatenated to the beginning of all references to rawwave files in
  422. // the various STK core classes (ex. Clarinet.cpp). If you wish to
  423. // move the rawwaves directory to a different location in your file
  424. // system, you will need to set this path definition appropriately.
  425. #if !defined(RAWWAVE_PATH)
  426. #define RAWWAVE_PATH "../../rawwaves/"
  427. #endif
  428. const StkFloat PI = 3.14159265358979;
  429. const StkFloat TWO_PI = 2 * PI;
  430. const StkFloat ONE_OVER_128 = 0.0078125;
  431. #if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_MM__)
  432. #define __OS_WINDOWS__
  433. #define __STK_REALTIME__
  434. #elif defined(__LINUX_OSS__) || defined(__LINUX_ALSA__) || defined(__UNIX_JACK__)
  435. #define __OS_LINUX__
  436. #define __STK_REALTIME__
  437. #elif defined(__IRIX_AL__)
  438. #define __OS_IRIX__
  439. #elif defined(__MACOSX_CORE__) || defined(__UNIX_JACK__)
  440. #define __OS_MACOSX__
  441. #define __STK_REALTIME__
  442. #endif
  443. } // stk namespace
  444. #endif