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.

1107 lines
43KB

  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 getSampleData
  194. */
  195. int getNumChannels() const noexcept { return numChannels; }
  196. /** Returns the number of samples allocated in each of the buffer's channels.
  197. @see getSampleData
  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 newNumSamples the number of samples to use - this must correspond to the
  349. size of the arrays passed in
  350. */
  351. void setDataToReferTo (Type** dataToReferTo,
  352. const int newNumChannels,
  353. const int newNumSamples) noexcept
  354. {
  355. jassert (dataToReferTo != nullptr);
  356. jassert (newNumChannels >= 0 && newNumSamples >= 0);
  357. if (allocatedBytes != 0)
  358. {
  359. allocatedBytes = 0;
  360. allocatedData.free();
  361. }
  362. numChannels = newNumChannels;
  363. size = newNumSamples;
  364. allocateChannels (dataToReferTo, 0);
  365. jassert (! isClear);
  366. }
  367. /** Resizes this buffer to match the given one, and copies all of its content across.
  368. The source buffer can contain a different floating point type, so this can be used to
  369. convert between 32 and 64 bit float buffer types.
  370. */
  371. template <typename OtherType>
  372. void makeCopyOf (const AudioBuffer<OtherType>& other, bool avoidReallocating = false)
  373. {
  374. setSize (other.getNumChannels(), other.getNumSamples(), false, false, avoidReallocating);
  375. if (other.hasBeenCleared())
  376. {
  377. clear();
  378. }
  379. else
  380. {
  381. for (int chan = 0; chan < numChannels; ++chan)
  382. {
  383. Type* const dest = channels[chan];
  384. const OtherType* const src = other.getReadPointer (chan);
  385. for (int i = 0; i < size; ++i)
  386. dest[i] = static_cast<Type> (src[i]);
  387. }
  388. }
  389. }
  390. //==============================================================================
  391. /** Clears all the samples in all channels. */
  392. void clear() noexcept
  393. {
  394. if (! isClear)
  395. {
  396. for (int i = 0; i < numChannels; ++i)
  397. FloatVectorOperations::clear (channels[i], size);
  398. isClear = true;
  399. }
  400. }
  401. /** Clears a specified region of all the channels.
  402. For speed, this doesn't check whether the channel and sample number
  403. are in-range, so be careful!
  404. */
  405. void clear (int startSample,
  406. int numSamples) noexcept
  407. {
  408. jassert (startSample >= 0 && startSample + numSamples <= size);
  409. if (! isClear)
  410. {
  411. if (startSample == 0 && numSamples == size)
  412. isClear = true;
  413. for (int i = 0; i < numChannels; ++i)
  414. FloatVectorOperations::clear (channels[i] + startSample, numSamples);
  415. }
  416. }
  417. /** Clears a specified region of just one channel.
  418. For speed, this doesn't check whether the channel and sample number
  419. are in-range, so be careful!
  420. */
  421. void clear (int channel,
  422. int startSample,
  423. int numSamples) noexcept
  424. {
  425. jassert (isPositiveAndBelow (channel, numChannels));
  426. jassert (startSample >= 0 && startSample + numSamples <= size);
  427. if (! isClear)
  428. FloatVectorOperations::clear (channels [channel] + startSample, numSamples);
  429. }
  430. /** Returns true if the buffer has been entirely cleared.
  431. Note that this does not actually measure the contents of the buffer - it simply
  432. returns a flag that is set when the buffer is cleared, and which is reset whenever
  433. functions like getWritePointer() are invoked. That means the method does not take
  434. any time, but it may return false negatives when in fact the buffer is still empty.
  435. */
  436. bool hasBeenCleared() const noexcept { return isClear; }
  437. //==============================================================================
  438. /** Returns a sample from the buffer.
  439. The channel and index are not checked - they are expected to be in-range. If not,
  440. an assertion will be thrown, but in a release build, you're into 'undefined behaviour'
  441. territory.
  442. */
  443. Type getSample (int channel, int sampleIndex) const noexcept
  444. {
  445. jassert (isPositiveAndBelow (channel, numChannels));
  446. jassert (isPositiveAndBelow (sampleIndex, size));
  447. return *(channels [channel] + sampleIndex);
  448. }
  449. /** Sets a sample in the buffer.
  450. The channel and index are not checked - they are expected to be in-range. If not,
  451. an assertion will be thrown, but in a release build, you're into 'undefined behaviour'
  452. territory.
  453. */
  454. void setSample (int destChannel, int destSample, Type newValue) noexcept
  455. {
  456. jassert (isPositiveAndBelow (destChannel, numChannels));
  457. jassert (isPositiveAndBelow (destSample, size));
  458. *(channels [destChannel] + destSample) = newValue;
  459. isClear = false;
  460. }
  461. /** Adds a value to a sample in 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. void addSample (int destChannel, int destSample, Type valueToAdd) noexcept
  467. {
  468. jassert (isPositiveAndBelow (destChannel, numChannels));
  469. jassert (isPositiveAndBelow (destSample, size));
  470. *(channels [destChannel] + destSample) += valueToAdd;
  471. isClear = false;
  472. }
  473. /** Applies a gain multiple to a region of one channel.
  474. For speed, this doesn't check whether the channel and sample number
  475. are in-range, so be careful!
  476. */
  477. void applyGain (int channel,
  478. int startSample,
  479. int numSamples,
  480. Type gain) noexcept
  481. {
  482. jassert (isPositiveAndBelow (channel, numChannels));
  483. jassert (startSample >= 0 && startSample + numSamples <= size);
  484. if (gain != 1.0f && ! isClear)
  485. {
  486. Type* const d = channels [channel] + startSample;
  487. if (gain == 0.0f)
  488. FloatVectorOperations::clear (d, numSamples);
  489. else
  490. FloatVectorOperations::multiply (d, gain, numSamples);
  491. }
  492. }
  493. /** Applies a gain multiple to a region of all the channels.
  494. For speed, this doesn't check whether the sample numbers
  495. are in-range, so be careful!
  496. */
  497. void applyGain (int startSample,
  498. int numSamples,
  499. Type gain) noexcept
  500. {
  501. for (int i = 0; i < numChannels; ++i)
  502. applyGain (i, startSample, numSamples, gain);
  503. }
  504. /** Applies a gain multiple to all the audio data. */
  505. void applyGain (Type gain) noexcept
  506. {
  507. applyGain (0, size, gain);
  508. }
  509. /** Applies a range of gains to a region of a channel.
  510. The gain that is applied to each sample will vary from
  511. startGain on the first sample to endGain on the last Sample,
  512. so it can be used to do basic fades.
  513. For speed, this doesn't check whether the sample numbers
  514. are in-range, so be careful!
  515. */
  516. void applyGainRamp (int channel,
  517. int startSample,
  518. int numSamples,
  519. Type startGain,
  520. Type endGain) noexcept
  521. {
  522. if (! isClear)
  523. {
  524. if (startGain == endGain)
  525. {
  526. applyGain (channel, startSample, numSamples, startGain);
  527. }
  528. else
  529. {
  530. jassert (isPositiveAndBelow (channel, numChannels));
  531. jassert (startSample >= 0 && startSample + numSamples <= size);
  532. const Type increment = (endGain - startGain) / numSamples;
  533. Type* d = channels [channel] + startSample;
  534. while (--numSamples >= 0)
  535. {
  536. *d++ *= startGain;
  537. startGain += increment;
  538. }
  539. }
  540. }
  541. }
  542. /** Applies a range of gains to a region of all channels.
  543. The gain that is applied to each sample will vary from
  544. startGain on the first sample to endGain on the last Sample,
  545. so it can be used to do basic fades.
  546. For speed, this doesn't check whether the sample numbers
  547. are in-range, so be careful!
  548. */
  549. void applyGainRamp (int startSample,
  550. int numSamples,
  551. Type startGain,
  552. Type endGain) noexcept
  553. {
  554. for (int i = 0; i < numChannels; ++i)
  555. applyGainRamp (i, startSample, numSamples, startGain, endGain);
  556. }
  557. /** Adds samples from another buffer to this one.
  558. @param destChannel the channel within this buffer to add the samples to
  559. @param destStartSample the start sample within this buffer's channel
  560. @param source the source buffer to add from
  561. @param sourceChannel the channel within the source buffer to read from
  562. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  563. @param numSamples the number of samples to process
  564. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  565. added to this buffer's samples
  566. @see copyFrom
  567. */
  568. void addFrom (int destChannel,
  569. int destStartSample,
  570. const AudioBuffer& source,
  571. int sourceChannel,
  572. int sourceStartSample,
  573. int numSamples,
  574. Type gainToApplyToSource = (Type) 1) noexcept
  575. {
  576. jassert (&source != this || sourceChannel != destChannel);
  577. jassert (isPositiveAndBelow (destChannel, numChannels));
  578. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  579. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  580. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  581. if (gainToApplyToSource != 0.0f && numSamples > 0 && ! source.isClear)
  582. {
  583. Type* const d = channels [destChannel] + destStartSample;
  584. const Type* const s = source.channels [sourceChannel] + sourceStartSample;
  585. if (isClear)
  586. {
  587. isClear = false;
  588. if (gainToApplyToSource != 1.0f)
  589. FloatVectorOperations::copyWithMultiply (d, s, gainToApplyToSource, numSamples);
  590. else
  591. FloatVectorOperations::copy (d, s, numSamples);
  592. }
  593. else
  594. {
  595. if (gainToApplyToSource != 1.0f)
  596. FloatVectorOperations::addWithMultiply (d, s, gainToApplyToSource, numSamples);
  597. else
  598. FloatVectorOperations::add (d, s, numSamples);
  599. }
  600. }
  601. }
  602. /** Adds samples from an array of floats to one of the channels.
  603. @param destChannel the channel within this buffer to add the samples to
  604. @param destStartSample the start sample within this buffer's channel
  605. @param source the source data to use
  606. @param numSamples the number of samples to process
  607. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  608. added to this buffer's samples
  609. @see copyFrom
  610. */
  611. void addFrom (int destChannel,
  612. int destStartSample,
  613. const Type* source,
  614. int numSamples,
  615. Type gainToApplyToSource = (Type) 1) noexcept
  616. {
  617. jassert (isPositiveAndBelow (destChannel, numChannels));
  618. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  619. jassert (source != nullptr);
  620. if (gainToApplyToSource != 0.0f && numSamples > 0)
  621. {
  622. Type* const d = channels [destChannel] + destStartSample;
  623. if (isClear)
  624. {
  625. isClear = false;
  626. if (gainToApplyToSource != 1.0f)
  627. FloatVectorOperations::copyWithMultiply (d, source, gainToApplyToSource, numSamples);
  628. else
  629. FloatVectorOperations::copy (d, source, numSamples);
  630. }
  631. else
  632. {
  633. if (gainToApplyToSource != 1.0f)
  634. FloatVectorOperations::addWithMultiply (d, source, gainToApplyToSource, numSamples);
  635. else
  636. FloatVectorOperations::add (d, source, numSamples);
  637. }
  638. }
  639. }
  640. /** Adds samples from an array of floats, applying a gain ramp to them.
  641. @param destChannel the channel within this buffer to add the samples to
  642. @param destStartSample the start sample within this buffer's channel
  643. @param source the source data to use
  644. @param numSamples the number of samples to process
  645. @param startGain the gain to apply to the first sample (this is multiplied with
  646. the source samples before they are added to this buffer)
  647. @param endGain the gain to apply to the final sample. The gain is linearly
  648. interpolated between the first and last samples.
  649. */
  650. void addFromWithRamp (int destChannel,
  651. int destStartSample,
  652. const Type* source,
  653. int numSamples,
  654. Type startGain,
  655. Type endGain) noexcept
  656. {
  657. jassert (isPositiveAndBelow (destChannel, numChannels));
  658. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  659. jassert (source != nullptr);
  660. if (startGain == endGain)
  661. {
  662. addFrom (destChannel, destStartSample, source, numSamples, startGain);
  663. }
  664. else
  665. {
  666. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  667. {
  668. isClear = false;
  669. const Type increment = (endGain - startGain) / numSamples;
  670. Type* d = channels [destChannel] + destStartSample;
  671. while (--numSamples >= 0)
  672. {
  673. *d++ += startGain * *source++;
  674. startGain += increment;
  675. }
  676. }
  677. }
  678. }
  679. /** Copies samples from another buffer to this one.
  680. @param destChannel the channel within this buffer to copy the samples to
  681. @param destStartSample the start sample within this buffer's channel
  682. @param source the source buffer to read from
  683. @param sourceChannel the channel within the source buffer to read from
  684. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  685. @param numSamples the number of samples to process
  686. @see addFrom
  687. */
  688. void copyFrom (int destChannel,
  689. int destStartSample,
  690. const AudioBuffer& source,
  691. int sourceChannel,
  692. int sourceStartSample,
  693. int numSamples) noexcept
  694. {
  695. jassert (&source != this || sourceChannel != destChannel);
  696. jassert (isPositiveAndBelow (destChannel, numChannels));
  697. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  698. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  699. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  700. if (numSamples > 0)
  701. {
  702. if (source.isClear)
  703. {
  704. if (! isClear)
  705. FloatVectorOperations::clear (channels [destChannel] + destStartSample, numSamples);
  706. }
  707. else
  708. {
  709. isClear = false;
  710. FloatVectorOperations::copy (channels [destChannel] + destStartSample,
  711. source.channels [sourceChannel] + sourceStartSample,
  712. numSamples);
  713. }
  714. }
  715. }
  716. /** Copies samples from an array of floats into one of the channels.
  717. @param destChannel the channel within this buffer to copy the samples to
  718. @param destStartSample the start sample within this buffer's channel
  719. @param source the source buffer to read from
  720. @param numSamples the number of samples to process
  721. @see addFrom
  722. */
  723. void copyFrom (int destChannel,
  724. int destStartSample,
  725. const Type* source,
  726. int numSamples) noexcept
  727. {
  728. jassert (isPositiveAndBelow (destChannel, numChannels));
  729. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  730. jassert (source != nullptr);
  731. if (numSamples > 0)
  732. {
  733. isClear = false;
  734. FloatVectorOperations::copy (channels [destChannel] + destStartSample, source, numSamples);
  735. }
  736. }
  737. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  738. @param destChannel the channel within this buffer to copy the samples to
  739. @param destStartSample the start sample within this buffer's channel
  740. @param source the source buffer to read from
  741. @param numSamples the number of samples to process
  742. @param gain the gain to apply
  743. @see addFrom
  744. */
  745. void copyFrom (int destChannel,
  746. int destStartSample,
  747. const Type* source,
  748. int numSamples,
  749. Type gain) noexcept
  750. {
  751. jassert (isPositiveAndBelow (destChannel, numChannels));
  752. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  753. jassert (source != nullptr);
  754. if (numSamples > 0)
  755. {
  756. Type* const d = channels [destChannel] + destStartSample;
  757. if (gain != 1.0f)
  758. {
  759. if (gain == 0)
  760. {
  761. if (! isClear)
  762. FloatVectorOperations::clear (d, numSamples);
  763. }
  764. else
  765. {
  766. isClear = false;
  767. FloatVectorOperations::copyWithMultiply (d, source, gain, numSamples);
  768. }
  769. }
  770. else
  771. {
  772. isClear = false;
  773. FloatVectorOperations::copy (d, source, numSamples);
  774. }
  775. }
  776. }
  777. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  778. @param destChannel the channel within this buffer to copy the samples to
  779. @param destStartSample the start sample within this buffer's channel
  780. @param source the source buffer to read from
  781. @param numSamples the number of samples to process
  782. @param startGain the gain to apply to the first sample (this is multiplied with
  783. the source samples before they are copied to this buffer)
  784. @param endGain the gain to apply to the final sample. The gain is linearly
  785. interpolated between the first and last samples.
  786. @see addFrom
  787. */
  788. void copyFromWithRamp (int destChannel,
  789. int destStartSample,
  790. const Type* source,
  791. int numSamples,
  792. Type startGain,
  793. Type endGain) noexcept
  794. {
  795. jassert (isPositiveAndBelow (destChannel, numChannels));
  796. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  797. jassert (source != nullptr);
  798. if (startGain == endGain)
  799. {
  800. copyFrom (destChannel, destStartSample, source, numSamples, startGain);
  801. }
  802. else
  803. {
  804. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  805. {
  806. isClear = false;
  807. const Type increment = (endGain - startGain) / numSamples;
  808. Type* d = channels [destChannel] + destStartSample;
  809. while (--numSamples >= 0)
  810. {
  811. *d++ = startGain * *source++;
  812. startGain += increment;
  813. }
  814. }
  815. }
  816. }
  817. /** Returns a Range indicating the lowest and highest sample values in a given section.
  818. @param channel the channel to read from
  819. @param startSample the start sample within the channel
  820. @param numSamples the number of samples to check
  821. */
  822. Range<Type> findMinMax (int channel,
  823. int startSample,
  824. int numSamples) const noexcept
  825. {
  826. jassert (isPositiveAndBelow (channel, numChannels));
  827. jassert (startSample >= 0 && startSample + numSamples <= size);
  828. if (isClear)
  829. return Range<Type>();
  830. return FloatVectorOperations::findMinAndMax (channels [channel] + startSample, numSamples);
  831. }
  832. /** Finds the highest absolute sample value within a region of a channel. */
  833. Type getMagnitude (int channel,
  834. int startSample,
  835. int numSamples) const noexcept
  836. {
  837. jassert (isPositiveAndBelow (channel, numChannels));
  838. jassert (startSample >= 0 && startSample + numSamples <= size);
  839. if (isClear)
  840. return 0.0f;
  841. const Range<Type> r (findMinMax (channel, startSample, numSamples));
  842. return jmax (r.getStart(), -r.getStart(), r.getEnd(), -r.getEnd());
  843. }
  844. /** Finds the highest absolute sample value within a region on all channels. */
  845. Type getMagnitude (int startSample,
  846. int numSamples) const noexcept
  847. {
  848. Type mag = 0.0f;
  849. if (! isClear)
  850. for (int i = 0; i < numChannels; ++i)
  851. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  852. return mag;
  853. }
  854. /** Returns the root mean squared level for a region of a channel. */
  855. Type getRMSLevel (int channel,
  856. int startSample,
  857. int numSamples) const noexcept
  858. {
  859. jassert (isPositiveAndBelow (channel, numChannels));
  860. jassert (startSample >= 0 && startSample + numSamples <= size);
  861. if (numSamples <= 0 || channel < 0 || channel >= numChannels || isClear)
  862. return 0.0f;
  863. const Type* const data = channels [channel] + startSample;
  864. double sum = 0.0;
  865. for (int i = 0; i < numSamples; ++i)
  866. {
  867. const Type sample = data [i];
  868. sum += sample * sample;
  869. }
  870. return (Type) std::sqrt (sum / numSamples);
  871. }
  872. /** Reverses a part of a channel. */
  873. void reverse (int channel, int startSample, int numSamples) const noexcept
  874. {
  875. jassert (isPositiveAndBelow (channel, numChannels));
  876. jassert (startSample >= 0 && startSample + numSamples <= size);
  877. if (! isClear)
  878. std::reverse (channels[channel] + startSample,
  879. channels[channel] + startSample + numSamples);
  880. }
  881. /** Reverses a part of the buffer. */
  882. void reverse (int startSample, int numSamples) const noexcept
  883. {
  884. for (int i = 0; i < numChannels; ++i)
  885. reverse (i, startSample, numSamples);
  886. }
  887. private:
  888. //==============================================================================
  889. int numChannels, size;
  890. size_t allocatedBytes;
  891. Type** channels;
  892. HeapBlock<char, true> allocatedData;
  893. Type* preallocatedChannelSpace [32];
  894. bool isClear;
  895. void allocateData()
  896. {
  897. const size_t channelListSize = sizeof (Type*) * (size_t) (numChannels + 1);
  898. allocatedBytes = (size_t) numChannels * (size_t) size * sizeof (Type) + channelListSize + 32;
  899. allocatedData.malloc (allocatedBytes);
  900. channels = reinterpret_cast<Type**> (allocatedData.getData());
  901. Type* chan = (Type*) (allocatedData + channelListSize);
  902. for (int i = 0; i < numChannels; ++i)
  903. {
  904. channels[i] = chan;
  905. chan += size;
  906. }
  907. channels [numChannels] = nullptr;
  908. isClear = false;
  909. }
  910. void allocateChannels (Type* const* const dataToReferTo, int offset)
  911. {
  912. jassert (offset >= 0);
  913. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  914. if (numChannels < (int) numElementsInArray (preallocatedChannelSpace))
  915. {
  916. channels = static_cast<Type**> (preallocatedChannelSpace);
  917. }
  918. else
  919. {
  920. allocatedData.malloc ((size_t) numChannels + 1, sizeof (Type*));
  921. channels = reinterpret_cast<Type**> (allocatedData.getData());
  922. }
  923. for (int i = 0; i < numChannels; ++i)
  924. {
  925. // you have to pass in the same number of valid pointers as numChannels
  926. jassert (dataToReferTo[i] != nullptr);
  927. channels[i] = dataToReferTo[i] + offset;
  928. }
  929. channels [numChannels] = nullptr;
  930. isClear = false;
  931. }
  932. JUCE_LEAK_DETECTOR (AudioBuffer)
  933. };
  934. //==============================================================================
  935. /**
  936. A multi-channel buffer of 32-bit floating point audio samples.
  937. This typedef is here for backwards compatibility with the older AudioSampleBuffer
  938. class, which was fixed for 32-bit data, but is otherwise the same as the new
  939. templated AudioBuffer class.
  940. @see AudioBuffer
  941. */
  942. typedef AudioBuffer<float> AudioSampleBuffer;