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.

593 lines
20KB

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