The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

1134 lines
44KB

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