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.

1101 lines
42KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the ISC license
  7. http://www.isc.org/downloads/software-support-policy/isc-license/
  8. Permission to use, copy, modify, and/or distribute this software for any
  9. purpose with or without fee is hereby granted, provided that the above
  10. copyright notice and this permission notice appear in all copies.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  12. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  14. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  15. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  16. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  17. OF THIS SOFTWARE.
  18. ==============================================================================
  19. */
  20. #ifndef WATER_AUDIOSAMPLEBUFFER_H_INCLUDED
  21. #define WATER_AUDIOSAMPLEBUFFER_H_INCLUDED
  22. #include "../memory/HeapBlock.h"
  23. #include "CarlaMathUtils.hpp"
  24. namespace water {
  25. //==============================================================================
  26. /**
  27. A multi-channel buffer of floating point audio samples.
  28. @see AudioSampleBuffer
  29. */
  30. class AudioSampleBuffer
  31. {
  32. public:
  33. //==============================================================================
  34. /** Creates an empty buffer with 0 channels and 0 length. */
  35. AudioSampleBuffer() noexcept
  36. : numChannels (0), size (0), allocatedBytes (0),
  37. channels (static_cast<float**> (preallocatedChannelSpace)),
  38. isClear (false)
  39. {
  40. }
  41. //==============================================================================
  42. /** Creates a buffer with a specified number of channels and samples.
  43. The contents of the buffer will initially be undefined, so use clear() to
  44. set all the samples to zero.
  45. The buffer will allocate its memory internally, and this will be released
  46. when the buffer is deleted. If the memory can't be allocated, this will
  47. throw a std::bad_alloc exception.
  48. */
  49. AudioSampleBuffer (int numChannelsToAllocate,
  50. int numSamplesToAllocate) noexcept
  51. : numChannels (numChannelsToAllocate),
  52. size (numSamplesToAllocate)
  53. {
  54. CARLA_SAFE_ASSERT_RETURN (size >= 0,);
  55. CARLA_SAFE_ASSERT_RETURN (numChannels >= 0,);
  56. allocateData();
  57. }
  58. /** Creates a buffer using a pre-allocated block of memory.
  59. Note that if the buffer is resized or its number of channels is changed, it
  60. will re-allocate memory internally and copy the existing data to this new area,
  61. so it will then stop directly addressing this memory.
  62. @param dataToReferTo a pre-allocated array containing pointers to the data
  63. for each channel that should be used by this buffer. The
  64. buffer will only refer to this memory, it won't try to delete
  65. it when the buffer is deleted or resized.
  66. @param numChannelsToUse the number of channels to use - this must correspond to the
  67. number of elements in the array passed in
  68. @param numSamples the number of samples to use - this must correspond to the
  69. size of the arrays passed in
  70. */
  71. AudioSampleBuffer (float* const* dataToReferTo,
  72. int numChannelsToUse,
  73. int numSamples) noexcept
  74. : numChannels (numChannelsToUse),
  75. size (numSamples),
  76. allocatedBytes (0)
  77. {
  78. CARLA_SAFE_ASSERT_RETURN (dataToReferTo != nullptr,);
  79. CARLA_SAFE_ASSERT_RETURN (numChannelsToUse >= 0 && numSamples >= 0,);
  80. allocateChannels (dataToReferTo, 0);
  81. }
  82. /** Creates a buffer using a pre-allocated block of memory.
  83. Note that if the buffer is resized or its number of channels is changed, it
  84. will re-allocate memory internally and copy the existing data to this new area,
  85. so it will then stop directly addressing this memory.
  86. @param dataToReferTo a pre-allocated array containing pointers to the data
  87. for each channel that should be used by this buffer. The
  88. buffer will only refer to this memory, it won't try to delete
  89. it when the buffer is deleted or resized.
  90. @param numChannelsToUse the number of channels to use - this must correspond to the
  91. number of elements in the array passed in
  92. @param startSample the offset within the arrays at which the data begins
  93. @param numSamples the number of samples to use - this must correspond to the
  94. size of the arrays passed in
  95. */
  96. AudioSampleBuffer (float* const* dataToReferTo,
  97. int numChannelsToUse,
  98. int startSample,
  99. int numSamples) noexcept
  100. : numChannels (numChannelsToUse),
  101. size (numSamples),
  102. allocatedBytes (0),
  103. isClear (false)
  104. {
  105. CARLA_SAFE_ASSERT_RETURN (dataToReferTo != nullptr,);
  106. CARLA_SAFE_ASSERT_RETURN (numChannelsToUse >= 0 && startSample >= 0 && numSamples >= 0,);
  107. allocateChannels (dataToReferTo, startSample);
  108. }
  109. /** Copies another buffer.
  110. This buffer will make its own copy of the other's data, unless the buffer was created
  111. using an external data buffer, in which case boths buffers will just point to the same
  112. shared block of data.
  113. */
  114. AudioSampleBuffer (const AudioSampleBuffer& other) noexcept
  115. : numChannels (other.numChannels),
  116. size (other.size),
  117. allocatedBytes (other.allocatedBytes)
  118. {
  119. if (allocatedBytes == 0)
  120. {
  121. allocateChannels (other.channels, 0);
  122. }
  123. else
  124. {
  125. allocateData();
  126. if (other.isClear)
  127. {
  128. clear();
  129. }
  130. else
  131. {
  132. for (int i = 0; i < numChannels; ++i)
  133. carla_copyFloats (channels[i], other.channels[i], size);
  134. }
  135. }
  136. }
  137. /** Copies another buffer onto this one.
  138. This buffer's size will be changed to that of the other buffer.
  139. */
  140. AudioSampleBuffer& operator= (const AudioSampleBuffer& other) noexcept
  141. {
  142. if (this != &other)
  143. {
  144. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  145. if (other.isClear)
  146. {
  147. clear();
  148. }
  149. else
  150. {
  151. isClear = false;
  152. for (int i = 0; i < numChannels; ++i)
  153. carla_copyFloats (channels[i], other.channels[i], size);
  154. }
  155. }
  156. return *this;
  157. }
  158. /** Destructor.
  159. This will free any memory allocated by the buffer.
  160. */
  161. ~AudioSampleBuffer() noexcept {}
  162. #if WATER_COMPILER_SUPPORTS_MOVE_SEMANTICS
  163. /** Move constructor */
  164. AudioSampleBuffer (AudioSampleBuffer&& other) noexcept
  165. : numChannels (other.numChannels),
  166. size (other.size),
  167. allocatedBytes (other.allocatedBytes),
  168. channels (other.channels),
  169. allocatedData (static_cast<HeapBlock<char, true>&&> (other.allocatedData)),
  170. isClear (other.isClear)
  171. {
  172. memcpy (preallocatedChannelSpace, other.preallocatedChannelSpace, sizeof (preallocatedChannelSpace));
  173. other.numChannels = 0;
  174. other.size = 0;
  175. other.allocatedBytes = 0;
  176. }
  177. /** Move assignment */
  178. AudioSampleBuffer& operator= (AudioSampleBuffer&& other) noexcept
  179. {
  180. numChannels = other.numChannels;
  181. size = other.size;
  182. allocatedBytes = other.allocatedBytes;
  183. channels = other.channels;
  184. allocatedData = static_cast<HeapBlock<char, true>&&> (other.allocatedData);
  185. isClear = other.isClear;
  186. memcpy (preallocatedChannelSpace, other.preallocatedChannelSpace, sizeof (preallocatedChannelSpace));
  187. other.numChannels = 0;
  188. other.size = 0;
  189. other.allocatedBytes = 0;
  190. return *this;
  191. }
  192. #endif
  193. //==============================================================================
  194. /** Returns the number of channels of audio data that this buffer contains.
  195. @see getSampleData
  196. */
  197. int getNumChannels() const noexcept { return numChannels; }
  198. /** Returns the number of samples allocated in each of the buffer's channels.
  199. @see getSampleData
  200. */
  201. int getNumSamples() const noexcept { return size; }
  202. /** Returns a pointer to an array of read-only samples in one of the buffer's channels.
  203. For speed, this doesn't check whether the channel number is out of range,
  204. so be careful when using it!
  205. If you need to write to the data, do NOT call this method and const_cast the
  206. result! Instead, you must call getWritePointer so that the buffer knows you're
  207. planning on modifying the data.
  208. */
  209. const float* getReadPointer (int channelNumber) const noexcept
  210. {
  211. jassert (isPositiveAndBelow (channelNumber, numChannels));
  212. return channels [channelNumber];
  213. }
  214. /** Returns a pointer to an array of read-only samples in one of the buffer's channels.
  215. For speed, this doesn't check whether the channel number or index are out of range,
  216. so be careful when using it!
  217. If you need to write to the data, do NOT call this method and const_cast the
  218. result! Instead, you must call getWritePointer so that the buffer knows you're
  219. planning on modifying the data.
  220. */
  221. const float* getReadPointer (int channelNumber, int sampleIndex) const noexcept
  222. {
  223. jassert (isPositiveAndBelow (channelNumber, numChannels));
  224. jassert (isPositiveAndBelow (sampleIndex, size));
  225. return channels [channelNumber] + sampleIndex;
  226. }
  227. /** Returns a writeable pointer to one of the buffer's channels.
  228. For speed, this doesn't check whether the channel number is out of range,
  229. so be careful when using it!
  230. Note that if you're not planning on writing to the data, you should always
  231. use getReadPointer instead.
  232. */
  233. float* getWritePointer (int channelNumber) noexcept
  234. {
  235. jassert (isPositiveAndBelow (channelNumber, numChannels));
  236. isClear = false;
  237. return channels [channelNumber];
  238. }
  239. /** Returns a writeable pointer to one of the buffer's channels.
  240. For speed, this doesn't check whether the channel number or index are out of range,
  241. so be careful when using it!
  242. Note that if you're not planning on writing to the data, you should
  243. use getReadPointer instead.
  244. */
  245. float* getWritePointer (int channelNumber, int sampleIndex) noexcept
  246. {
  247. jassert (isPositiveAndBelow (channelNumber, numChannels));
  248. jassert (isPositiveAndBelow (sampleIndex, size));
  249. isClear = false;
  250. return channels [channelNumber] + sampleIndex;
  251. }
  252. /** Returns an array of pointers to the channels in the buffer.
  253. Don't modify any of the pointers that are returned, and bear in mind that
  254. these will become invalid if the buffer is resized.
  255. */
  256. const float** getArrayOfReadPointers() const noexcept { return const_cast<const float**> (channels); }
  257. /** Returns an array of pointers to the channels in the buffer.
  258. Don't modify any of the pointers that are returned, and bear in mind that
  259. these will become invalid if the buffer is resized.
  260. */
  261. float** getArrayOfWritePointers() noexcept { isClear = false; return channels; }
  262. //==============================================================================
  263. /** Changes the buffer's size or number of channels.
  264. This can expand or contract the buffer's length, and add or remove channels.
  265. If keepExistingContent is true, it will try to preserve as much of the
  266. old data as it can in the new buffer.
  267. If clearExtraSpace is true, then any extra channels or space that is
  268. allocated will be also be cleared. If false, then this space is left
  269. uninitialised.
  270. If avoidReallocating is true, then changing the buffer's size won't reduce the
  271. amount of memory that is currently allocated (but it will still increase it if
  272. the new size is bigger than the amount it currently has). If this is false, then
  273. a new allocation will be done so that the buffer uses takes up the minimum amount
  274. of memory that it needs.
  275. If the required memory can't be allocated, this will throw a std::bad_alloc exception.
  276. */
  277. void setSize (int newNumChannels,
  278. int newNumSamples,
  279. bool keepExistingContent = false,
  280. bool clearExtraSpace = false,
  281. bool avoidReallocating = false) noexcept
  282. {
  283. jassert (newNumChannels >= 0);
  284. jassert (newNumSamples >= 0);
  285. if (newNumSamples != size || newNumChannels != numChannels)
  286. {
  287. const size_t allocatedSamplesPerChannel = ((size_t) newNumSamples + 3) & ~3u;
  288. const size_t channelListSize = ((sizeof (float*) * (size_t) (newNumChannels + 1)) + 15) & ~15u;
  289. const size_t newTotalBytes = ((size_t) newNumChannels * (size_t) allocatedSamplesPerChannel * sizeof (float))
  290. + channelListSize + 32;
  291. if (keepExistingContent)
  292. {
  293. HeapBlock<char, true> newData;
  294. newData.allocate (newTotalBytes, clearExtraSpace || isClear);
  295. const size_t numSamplesToCopy = (size_t) jmin (newNumSamples, size);
  296. float** const newChannels = reinterpret_cast<float**> (newData.getData());
  297. float* newChan = reinterpret_cast<float*> (newData + channelListSize);
  298. for (int j = 0; j < newNumChannels; ++j)
  299. {
  300. newChannels[j] = newChan;
  301. newChan += allocatedSamplesPerChannel;
  302. }
  303. if (! isClear)
  304. {
  305. const int numChansToCopy = jmin (numChannels, newNumChannels);
  306. for (int i = 0; i < numChansToCopy; ++i)
  307. carla_copyFloats (newChannels[i], channels[i], (int) numSamplesToCopy);
  308. }
  309. allocatedData.swapWith (newData);
  310. allocatedBytes = newTotalBytes;
  311. channels = newChannels;
  312. }
  313. else
  314. {
  315. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  316. {
  317. if (clearExtraSpace || isClear)
  318. allocatedData.clear (newTotalBytes);
  319. }
  320. else
  321. {
  322. allocatedBytes = newTotalBytes;
  323. allocatedData.allocate (newTotalBytes, clearExtraSpace || isClear);
  324. channels = reinterpret_cast<float**> (allocatedData.getData());
  325. }
  326. float* chan = reinterpret_cast<float*> (allocatedData + channelListSize);
  327. for (int i = 0; i < newNumChannels; ++i)
  328. {
  329. channels[i] = chan;
  330. chan += allocatedSamplesPerChannel;
  331. }
  332. }
  333. channels [newNumChannels] = 0;
  334. size = newNumSamples;
  335. numChannels = newNumChannels;
  336. }
  337. }
  338. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  339. There's also a constructor that lets you specify arrays like this, but this
  340. lets you change the channels dynamically.
  341. Note that if the buffer is resized or its number of channels is changed, it
  342. will re-allocate memory internally and copy the existing data to this new area,
  343. so it will then stop directly addressing this memory.
  344. @param dataToReferTo a pre-allocated array containing pointers to the data
  345. for each channel that should be used by this buffer. The
  346. buffer will only refer to this memory, it won't try to delete
  347. it when the buffer is deleted or resized.
  348. @param newNumChannels the number of channels to use - this must correspond to the
  349. number of elements in the array passed in
  350. @param newNumSamples the number of samples to use - this must correspond to the
  351. size of the arrays passed in
  352. */
  353. void setDataToReferTo (float** dataToReferTo,
  354. const int newNumChannels,
  355. const int newNumSamples) noexcept
  356. {
  357. jassert (dataToReferTo != nullptr);
  358. jassert (newNumChannels >= 0 && newNumSamples >= 0);
  359. if (allocatedBytes != 0)
  360. {
  361. allocatedBytes = 0;
  362. allocatedData.free();
  363. }
  364. numChannels = newNumChannels;
  365. size = newNumSamples;
  366. allocateChannels (dataToReferTo, 0);
  367. jassert (! isClear);
  368. }
  369. /** Resizes this buffer to match the given one, and copies all of its content across.
  370. The source buffer can contain a different floating point type, so this can be used to
  371. convert between 32 and 64 bit float buffer types.
  372. */
  373. void makeCopyOf (const AudioSampleBuffer& other, bool avoidReallocating = false)
  374. {
  375. setSize (other.getNumChannels(), other.getNumSamples(), false, false, avoidReallocating);
  376. if (other.hasBeenCleared())
  377. {
  378. clear();
  379. }
  380. else
  381. {
  382. for (int chan = 0; chan < numChannels; ++chan)
  383. {
  384. float* const dest = channels[chan];
  385. const float* const src = other.getReadPointer (chan);
  386. for (int i = 0; i < size; ++i)
  387. dest[i] = static_cast<float> (src[i]);
  388. }
  389. }
  390. }
  391. //==============================================================================
  392. /** Clears all the samples in all channels. */
  393. void clear() noexcept
  394. {
  395. if (! isClear)
  396. {
  397. for (int i = 0; i < numChannels; ++i)
  398. carla_zeroFloats (channels[i], size);
  399. isClear = true;
  400. }
  401. }
  402. /** Clears a specified region of all the channels.
  403. For speed, this doesn't check whether the channel and sample number
  404. are in-range, so be careful!
  405. */
  406. void clear (int startSample,
  407. int numSamples) noexcept
  408. {
  409. jassert (startSample >= 0 && startSample + numSamples <= size);
  410. if (! isClear)
  411. {
  412. if (startSample == 0 && numSamples == size)
  413. isClear = true;
  414. for (int i = 0; i < numChannels; ++i)
  415. carla_zeroFloats (channels[i] + startSample, numSamples);
  416. }
  417. }
  418. /** Clears a specified region of just one channel.
  419. For speed, this doesn't check whether the channel and sample number
  420. are in-range, so be careful!
  421. */
  422. void clear (int channel,
  423. int startSample,
  424. int numSamples) noexcept
  425. {
  426. jassert (isPositiveAndBelow (channel, numChannels));
  427. jassert (startSample >= 0 && startSample + numSamples <= size);
  428. if (! isClear)
  429. carla_zeroFloats (channels [channel] + startSample, numSamples);
  430. }
  431. /** Returns true if the buffer has been entirely cleared.
  432. Note that this does not actually measure the contents of the buffer - it simply
  433. returns a flag that is set when the buffer is cleared, and which is reset whenever
  434. functions like getWritePointer() are invoked. That means the method does not take
  435. any time, but it may return false negatives when in fact the buffer is still empty.
  436. */
  437. bool hasBeenCleared() const noexcept { return isClear; }
  438. //==============================================================================
  439. /** Returns a sample from the buffer.
  440. The channel and index are not checked - they are expected to be in-range. If not,
  441. an assertion will be thrown, but in a release build, you're into 'undefined behaviour'
  442. territory.
  443. */
  444. float getSample (int channel, int sampleIndex) const noexcept
  445. {
  446. jassert (isPositiveAndBelow (channel, numChannels));
  447. jassert (isPositiveAndBelow (sampleIndex, size));
  448. return *(channels [channel] + sampleIndex);
  449. }
  450. /** Sets a sample in the buffer.
  451. The channel and index are not checked - they are expected to be in-range. If not,
  452. an assertion will be thrown, but in a release build, you're into 'undefined behaviour'
  453. territory.
  454. */
  455. void setSample (int destChannel, int destSample, float newValue) noexcept
  456. {
  457. jassert (isPositiveAndBelow (destChannel, numChannels));
  458. jassert (isPositiveAndBelow (destSample, size));
  459. *(channels [destChannel] + destSample) = newValue;
  460. isClear = false;
  461. }
  462. /** Adds a value to a sample in the buffer.
  463. The channel and index are not checked - they are expected to be in-range. If not,
  464. an assertion will be thrown, but in a release build, you're into 'undefined behaviour'
  465. territory.
  466. */
  467. void addSample (int destChannel, int destSample, float valueToAdd) noexcept
  468. {
  469. jassert (isPositiveAndBelow (destChannel, numChannels));
  470. jassert (isPositiveAndBelow (destSample, size));
  471. *(channels [destChannel] + destSample) += valueToAdd;
  472. isClear = false;
  473. }
  474. /** Applies a gain multiple to a region of one channel.
  475. For speed, this doesn't check whether the channel and sample number
  476. are in-range, so be careful!
  477. */
  478. void applyGain (int channel,
  479. int startSample,
  480. int numSamples,
  481. float gain) noexcept
  482. {
  483. jassert (isPositiveAndBelow (channel, numChannels));
  484. jassert (startSample >= 0 && startSample + numSamples <= size);
  485. if (gain != 1.0f && ! isClear)
  486. {
  487. float* const d = channels [channel] + startSample;
  488. if (carla_isZero (gain))
  489. carla_zeroFloats (d, numSamples);
  490. else
  491. carla_multiply (d, gain, numSamples);
  492. }
  493. }
  494. /** Applies a gain multiple to a region of all the channels.
  495. For speed, this doesn't check whether the sample numbers
  496. are in-range, so be careful!
  497. */
  498. void applyGain (int startSample,
  499. int numSamples,
  500. float gain) noexcept
  501. {
  502. for (int i = 0; i < numChannels; ++i)
  503. applyGain (i, startSample, numSamples, gain);
  504. }
  505. /** Applies a gain multiple to all the audio data. */
  506. void applyGain (float gain) noexcept
  507. {
  508. applyGain (0, size, gain);
  509. }
  510. /** Applies a range of gains to a region of a channel.
  511. The gain that is applied to each sample will vary from
  512. startGain on the first sample to endGain on the last Sample,
  513. so it can be used to do basic fades.
  514. For speed, this doesn't check whether the sample numbers
  515. are in-range, so be careful!
  516. */
  517. void applyGainRamp (int channel,
  518. int startSample,
  519. int numSamples,
  520. float startGain,
  521. float endGain) noexcept
  522. {
  523. if (! isClear)
  524. {
  525. if (startGain == endGain)
  526. {
  527. applyGain (channel, startSample, numSamples, startGain);
  528. }
  529. else
  530. {
  531. jassert (isPositiveAndBelow (channel, numChannels));
  532. jassert (startSample >= 0 && startSample + numSamples <= size);
  533. const float increment = (endGain - startGain) / numSamples;
  534. float* d = channels [channel] + startSample;
  535. while (--numSamples >= 0)
  536. {
  537. *d++ *= startGain;
  538. startGain += increment;
  539. }
  540. }
  541. }
  542. }
  543. /** Applies a range of gains to a region of all channels.
  544. The gain that is applied to each sample will vary from
  545. startGain on the first sample to endGain on the last Sample,
  546. so it can be used to do basic fades.
  547. For speed, this doesn't check whether the sample numbers
  548. are in-range, so be careful!
  549. */
  550. void applyGainRamp (int startSample,
  551. int numSamples,
  552. float startGain,
  553. float endGain) noexcept
  554. {
  555. for (int i = 0; i < numChannels; ++i)
  556. applyGainRamp (i, startSample, numSamples, startGain, endGain);
  557. }
  558. /** Adds samples from another buffer to this one.
  559. @param destChannel the channel within this buffer to add the samples to
  560. @param destStartSample the start sample within this buffer's channel
  561. @param source the source buffer to add from
  562. @param sourceChannel the channel within the source buffer to read from
  563. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  564. @param numSamples the number of samples to process
  565. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  566. added to this buffer's samples
  567. @see copyFrom
  568. */
  569. void addFrom (int destChannel,
  570. int destStartSample,
  571. const AudioSampleBuffer& source,
  572. int sourceChannel,
  573. int sourceStartSample,
  574. int numSamples,
  575. float gainToApplyToSource = (float) 1) noexcept
  576. {
  577. jassert (&source != this || sourceChannel != destChannel);
  578. jassert (isPositiveAndBelow (destChannel, numChannels));
  579. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  580. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  581. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  582. if (gainToApplyToSource != 0.0f && numSamples > 0 && ! source.isClear)
  583. {
  584. float* const d = channels [destChannel] + destStartSample;
  585. const float* const s = source.channels [sourceChannel] + sourceStartSample;
  586. if (isClear)
  587. {
  588. isClear = false;
  589. if (gainToApplyToSource != 1.0f)
  590. carla_copyWithMultiply (d, s, gainToApplyToSource, numSamples);
  591. else
  592. carla_copyFloats (d, s, numSamples);
  593. }
  594. else
  595. {
  596. if (gainToApplyToSource != 1.0f)
  597. carla_addWithMultiply (d, s, gainToApplyToSource, numSamples);
  598. else
  599. carla_add (d, s, numSamples);
  600. }
  601. }
  602. }
  603. /** Adds samples from an array of floats to one of the channels.
  604. @param destChannel the channel within this buffer to add the samples to
  605. @param destStartSample the start sample within this buffer's channel
  606. @param source the source data to use
  607. @param numSamples the number of samples to process
  608. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  609. added to this buffer's samples
  610. @see copyFrom
  611. */
  612. void addFrom (int destChannel,
  613. int destStartSample,
  614. const float* source,
  615. int numSamples,
  616. float gainToApplyToSource = (float) 1) noexcept
  617. {
  618. jassert (isPositiveAndBelow (destChannel, numChannels));
  619. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  620. jassert (source != nullptr);
  621. if (gainToApplyToSource != 0.0f && numSamples > 0)
  622. {
  623. float* const d = channels [destChannel] + destStartSample;
  624. if (isClear)
  625. {
  626. isClear = false;
  627. if (gainToApplyToSource != 1.0f)
  628. carla_copyWithMultiply (d, source, gainToApplyToSource, numSamples);
  629. else
  630. carla_copyFloats (d, source, numSamples);
  631. }
  632. else
  633. {
  634. if (gainToApplyToSource != 1.0f)
  635. carla_addWithMultiply (d, source, gainToApplyToSource, numSamples);
  636. else
  637. carla_add (d, source, numSamples);
  638. }
  639. }
  640. }
  641. /** Adds samples from an array of floats, applying a gain ramp to them.
  642. @param destChannel the channel within this buffer to add the samples to
  643. @param destStartSample the start sample within this buffer's channel
  644. @param source the source data to use
  645. @param numSamples the number of samples to process
  646. @param startGain the gain to apply to the first sample (this is multiplied with
  647. the source samples before they are added to this buffer)
  648. @param endGain the gain to apply to the final sample. The gain is linearly
  649. interpolated between the first and last samples.
  650. */
  651. void addFromWithRamp (int destChannel,
  652. int destStartSample,
  653. const float* source,
  654. int numSamples,
  655. float startGain,
  656. float endGain) noexcept
  657. {
  658. jassert (isPositiveAndBelow (destChannel, numChannels));
  659. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  660. jassert (source != nullptr);
  661. if (startGain == endGain)
  662. {
  663. addFrom (destChannel, destStartSample, source, numSamples, startGain);
  664. }
  665. else
  666. {
  667. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  668. {
  669. isClear = false;
  670. const float increment = (endGain - startGain) / numSamples;
  671. float* d = channels [destChannel] + destStartSample;
  672. while (--numSamples >= 0)
  673. {
  674. *d++ += startGain * *source++;
  675. startGain += increment;
  676. }
  677. }
  678. }
  679. }
  680. /** Copies samples from another buffer to this one.
  681. @param destChannel the channel within this buffer to copy the samples to
  682. @param destStartSample the start sample within this buffer's channel
  683. @param source the source buffer to read from
  684. @param sourceChannel the channel within the source buffer to read from
  685. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  686. @param numSamples the number of samples to process
  687. @see addFrom
  688. */
  689. void copyFrom (int destChannel,
  690. int destStartSample,
  691. const AudioSampleBuffer& source,
  692. int sourceChannel,
  693. int sourceStartSample,
  694. int numSamples) noexcept
  695. {
  696. jassert (&source != this || sourceChannel != destChannel);
  697. jassert (isPositiveAndBelow (destChannel, numChannels));
  698. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  699. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  700. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  701. if (numSamples > 0)
  702. {
  703. if (source.isClear)
  704. {
  705. if (! isClear)
  706. carla_zeroFloats (channels [destChannel] + destStartSample, numSamples);
  707. }
  708. else
  709. {
  710. isClear = false;
  711. carla_copyFloats (channels [destChannel] + destStartSample,
  712. source.channels [sourceChannel] + sourceStartSample,
  713. numSamples);
  714. }
  715. }
  716. }
  717. /** Copies samples from an array of floats into one of the channels.
  718. @param destChannel the channel within this buffer to copy the samples to
  719. @param destStartSample the start sample within this buffer's channel
  720. @param source the source buffer to read from
  721. @param numSamples the number of samples to process
  722. @see addFrom
  723. */
  724. void copyFrom (int destChannel,
  725. int destStartSample,
  726. const float* source,
  727. int numSamples) noexcept
  728. {
  729. jassert (isPositiveAndBelow (destChannel, numChannels));
  730. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  731. jassert (source != nullptr);
  732. if (numSamples > 0)
  733. {
  734. isClear = false;
  735. carla_copyFloats (channels [destChannel] + destStartSample, source, numSamples);
  736. }
  737. }
  738. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  739. @param destChannel the channel within this buffer to copy the samples to
  740. @param destStartSample the start sample within this buffer's channel
  741. @param source the source buffer to read from
  742. @param numSamples the number of samples to process
  743. @param gain the gain to apply
  744. @see addFrom
  745. */
  746. void copyFrom (int destChannel,
  747. int destStartSample,
  748. const float* source,
  749. int numSamples,
  750. float gain) noexcept
  751. {
  752. jassert (isPositiveAndBelow (destChannel, numChannels));
  753. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  754. jassert (source != nullptr);
  755. if (numSamples > 0)
  756. {
  757. float* const d = channels [destChannel] + destStartSample;
  758. if (gain != 1.0f)
  759. {
  760. if (gain == 0)
  761. {
  762. if (! isClear)
  763. carla_zeroFloats (d, numSamples);
  764. }
  765. else
  766. {
  767. isClear = false;
  768. carla_copyWithMultiply (d, source, gain, numSamples);
  769. }
  770. }
  771. else
  772. {
  773. isClear = false;
  774. carla_copyFloats (d, source, numSamples);
  775. }
  776. }
  777. }
  778. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  779. @param destChannel the channel within this buffer to copy the samples to
  780. @param destStartSample the start sample within this buffer's channel
  781. @param source the source buffer to read from
  782. @param numSamples the number of samples to process
  783. @param startGain the gain to apply to the first sample (this is multiplied with
  784. the source samples before they are copied to this buffer)
  785. @param endGain the gain to apply to the final sample. The gain is linearly
  786. interpolated between the first and last samples.
  787. @see addFrom
  788. */
  789. void copyFromWithRamp (int destChannel,
  790. int destStartSample,
  791. const float* source,
  792. int numSamples,
  793. float startGain,
  794. float endGain) noexcept
  795. {
  796. jassert (isPositiveAndBelow (destChannel, numChannels));
  797. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  798. jassert (source != nullptr);
  799. if (startGain == endGain)
  800. {
  801. copyFrom (destChannel, destStartSample, source, numSamples, startGain);
  802. }
  803. else
  804. {
  805. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  806. {
  807. isClear = false;
  808. const float increment = (endGain - startGain) / numSamples;
  809. float* d = channels [destChannel] + destStartSample;
  810. while (--numSamples >= 0)
  811. {
  812. *d++ = startGain * *source++;
  813. startGain += increment;
  814. }
  815. }
  816. }
  817. }
  818. #if 0
  819. /** Returns a Range indicating the lowest and highest sample values in a given section.
  820. @param channel the channel to read from
  821. @param startSample the start sample within the channel
  822. @param numSamples the number of samples to check
  823. */
  824. Range<float> findMinMax (int channel,
  825. int startSample,
  826. int numSamples) const noexcept
  827. {
  828. jassert (isPositiveAndBelow (channel, numChannels));
  829. jassert (startSample >= 0 && startSample + numSamples <= size);
  830. if (isClear)
  831. return Range<float>();
  832. return FloatVectorOperations::findMinAndMax (channels [channel] + startSample, numSamples);
  833. }
  834. /** Finds the highest absolute sample value within a region of a channel. */
  835. float getMagnitude (int channel,
  836. int startSample,
  837. int numSamples) const noexcept
  838. {
  839. jassert (isPositiveAndBelow (channel, numChannels));
  840. jassert (startSample >= 0 && startSample + numSamples <= size);
  841. if (isClear)
  842. return 0.0f;
  843. const Range<float> r (findMinMax (channel, startSample, numSamples));
  844. return jmax (r.getStart(), -r.getStart(), r.getEnd(), -r.getEnd());
  845. }
  846. /** Finds the highest absolute sample value within a region on all channels. */
  847. float getMagnitude (int startSample,
  848. int numSamples) const noexcept
  849. {
  850. float mag = 0.0f;
  851. if (! isClear)
  852. for (int i = 0; i < numChannels; ++i)
  853. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  854. return mag;
  855. }
  856. /** Returns the root mean squared level for a region of a channel. */
  857. float getRMSLevel (int channel,
  858. int startSample,
  859. int numSamples) const noexcept
  860. {
  861. jassert (isPositiveAndBelow (channel, numChannels));
  862. jassert (startSample >= 0 && startSample + numSamples <= size);
  863. if (numSamples <= 0 || channel < 0 || channel >= numChannels || isClear)
  864. return 0.0f;
  865. const float* const data = channels [channel] + startSample;
  866. double sum = 0.0;
  867. for (int i = 0; i < numSamples; ++i)
  868. {
  869. const float sample = data [i];
  870. sum += sample * sample;
  871. }
  872. return (float) std::sqrt (sum / numSamples);
  873. }
  874. /** Reverses a part of a channel. */
  875. void reverse (int channel, int startSample, int numSamples) const noexcept
  876. {
  877. jassert (isPositiveAndBelow (channel, numChannels));
  878. jassert (startSample >= 0 && startSample + numSamples <= size);
  879. if (! isClear)
  880. std::reverse (channels[channel] + startSample,
  881. channels[channel] + startSample + numSamples);
  882. }
  883. /** Reverses a part of the buffer. */
  884. void reverse (int startSample, int numSamples) const noexcept
  885. {
  886. for (int i = 0; i < numChannels; ++i)
  887. reverse (i, startSample, numSamples);
  888. }
  889. #endif
  890. private:
  891. //==============================================================================
  892. int numChannels, size;
  893. size_t allocatedBytes;
  894. float** channels;
  895. HeapBlock<char, true> allocatedData;
  896. float* preallocatedChannelSpace [32];
  897. bool isClear;
  898. void allocateData()
  899. {
  900. const size_t channelListSize = sizeof (float*) * (size_t) (numChannels + 1);
  901. allocatedBytes = (size_t) numChannels * (size_t) size * sizeof (float) + channelListSize + 32;
  902. allocatedData.malloc (allocatedBytes);
  903. channels = reinterpret_cast<float**> (allocatedData.getData());
  904. float* chan = (float*) (allocatedData + channelListSize);
  905. for (int i = 0; i < numChannels; ++i)
  906. {
  907. channels[i] = chan;
  908. chan += size;
  909. }
  910. channels [numChannels] = nullptr;
  911. isClear = false;
  912. }
  913. void allocateChannels (float* const* const dataToReferTo, int offset)
  914. {
  915. jassert (offset >= 0);
  916. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  917. if (numChannels < (int) numElementsInArray (preallocatedChannelSpace))
  918. {
  919. channels = static_cast<float**> (preallocatedChannelSpace);
  920. }
  921. else
  922. {
  923. allocatedData.malloc ((size_t) numChannels + 1, sizeof (float*));
  924. channels = reinterpret_cast<float**> (allocatedData.getData());
  925. }
  926. for (int i = 0; i < numChannels; ++i)
  927. {
  928. // you have to pass in the same number of valid pointers as numChannels
  929. jassert (dataToReferTo[i] != nullptr);
  930. channels[i] = dataToReferTo[i] + offset;
  931. }
  932. channels [numChannels] = nullptr;
  933. isClear = false;
  934. }
  935. };
  936. }
  937. #endif // WATER_AUDIOSAMPLEBUFFER_H_INCLUDED