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.

1321 lines
53KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. //==============================================================================
  20. /**
  21. A multi-channel buffer containing floating point audio samples.
  22. @tags{Audio}
  23. */
  24. template <typename Type>
  25. class AudioBuffer
  26. {
  27. public:
  28. //==============================================================================
  29. /** Creates an empty buffer with 0 channels and 0 length. */
  30. AudioBuffer() noexcept
  31. : channels (static_cast<Type**> (preallocatedChannelSpace))
  32. {
  33. }
  34. //==============================================================================
  35. /** Creates a buffer with a specified number of channels and samples.
  36. The contents of the buffer will initially be undefined, so use clear() to
  37. set all the samples to zero.
  38. The buffer will allocate its memory internally, and this will be released
  39. when the buffer is deleted. If the memory can't be allocated, this will
  40. throw a std::bad_alloc exception.
  41. */
  42. AudioBuffer (int numChannelsToAllocate,
  43. int numSamplesToAllocate)
  44. : numChannels (numChannelsToAllocate),
  45. size (numSamplesToAllocate)
  46. {
  47. jassert (size >= 0 && numChannels >= 0);
  48. allocateData();
  49. }
  50. /** Creates a buffer using a pre-allocated block of memory.
  51. Note that if the buffer is resized or its number of channels is changed, it
  52. will re-allocate memory internally and copy the existing data to this new area,
  53. so it will then stop directly addressing this memory.
  54. @param dataToReferTo a pre-allocated array containing pointers to the data
  55. for each channel that should be used by this buffer. The
  56. buffer will only refer to this memory, it won't try to delete
  57. it when the buffer is deleted or resized.
  58. @param numChannelsToUse the number of channels to use - this must correspond to the
  59. number of elements in the array passed in
  60. @param numSamples the number of samples to use - this must correspond to the
  61. size of the arrays passed in
  62. */
  63. AudioBuffer (Type* const* dataToReferTo,
  64. int numChannelsToUse,
  65. int numSamples)
  66. : numChannels (numChannelsToUse),
  67. size (numSamples)
  68. {
  69. jassert (dataToReferTo != nullptr);
  70. jassert (numChannelsToUse >= 0 && numSamples >= 0);
  71. allocateChannels (dataToReferTo, 0);
  72. }
  73. /** Creates a buffer using a pre-allocated block of memory.
  74. Note that if the buffer is resized or its number of channels is changed, it
  75. will re-allocate memory internally and copy the existing data to this new area,
  76. so it will then stop directly addressing this memory.
  77. @param dataToReferTo a pre-allocated array containing pointers to the data
  78. for each channel that should be used by this buffer. The
  79. buffer will only refer to this memory, it won't try to delete
  80. it when the buffer is deleted or resized.
  81. @param numChannelsToUse the number of channels to use - this must correspond to the
  82. number of elements in the array passed in
  83. @param startSample the offset within the arrays at which the data begins
  84. @param numSamples the number of samples to use - this must correspond to the
  85. size of the arrays passed in
  86. */
  87. AudioBuffer (Type* const* dataToReferTo,
  88. int numChannelsToUse,
  89. int startSample,
  90. int numSamples)
  91. : numChannels (numChannelsToUse),
  92. size (numSamples)
  93. {
  94. jassert (dataToReferTo != nullptr);
  95. jassert (numChannelsToUse >= 0 && startSample >= 0 && numSamples >= 0);
  96. allocateChannels (dataToReferTo, startSample);
  97. }
  98. /** Copies another buffer.
  99. This buffer will make its own copy of the other's data, unless the buffer was created
  100. using an external data buffer, in which case both buffers will just point to the same
  101. shared block of data.
  102. */
  103. AudioBuffer (const AudioBuffer& other)
  104. : numChannels (other.numChannels),
  105. size (other.size),
  106. allocatedBytes (other.allocatedBytes)
  107. {
  108. if (allocatedBytes == 0)
  109. {
  110. allocateChannels (other.channels, 0);
  111. }
  112. else
  113. {
  114. allocateData();
  115. if (other.isClear)
  116. {
  117. clear();
  118. }
  119. else
  120. {
  121. for (int i = 0; i < numChannels; ++i)
  122. FloatVectorOperations::copy (channels[i], other.channels[i], size);
  123. }
  124. }
  125. }
  126. /** Copies another buffer onto this one.
  127. This buffer's size will be changed to that of the other buffer.
  128. */
  129. AudioBuffer& operator= (const AudioBuffer& other)
  130. {
  131. if (this != &other)
  132. {
  133. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  134. if (other.isClear)
  135. {
  136. clear();
  137. }
  138. else
  139. {
  140. isClear = false;
  141. for (int i = 0; i < numChannels; ++i)
  142. FloatVectorOperations::copy (channels[i], other.channels[i], size);
  143. }
  144. }
  145. return *this;
  146. }
  147. /** Destructor.
  148. This will free any memory allocated by the buffer.
  149. */
  150. ~AudioBuffer() = default;
  151. /** Move constructor. */
  152. AudioBuffer (AudioBuffer&& other) noexcept
  153. : numChannels (other.numChannels),
  154. size (other.size),
  155. allocatedBytes (other.allocatedBytes),
  156. allocatedData (std::move (other.allocatedData)),
  157. isClear (other.isClear)
  158. {
  159. if (numChannels < (int) numElementsInArray (preallocatedChannelSpace))
  160. {
  161. channels = preallocatedChannelSpace;
  162. for (int i = 0; i < numChannels; ++i)
  163. preallocatedChannelSpace[i] = other.channels[i];
  164. }
  165. else
  166. {
  167. channels = other.channels;
  168. }
  169. other.numChannels = 0;
  170. other.size = 0;
  171. other.allocatedBytes = 0;
  172. }
  173. /** Move assignment. */
  174. AudioBuffer& operator= (AudioBuffer&& other) noexcept
  175. {
  176. numChannels = other.numChannels;
  177. size = other.size;
  178. allocatedBytes = other.allocatedBytes;
  179. allocatedData = std::move (other.allocatedData);
  180. isClear = other.isClear;
  181. if (numChannels < (int) numElementsInArray (preallocatedChannelSpace))
  182. {
  183. channels = preallocatedChannelSpace;
  184. for (int i = 0; i < numChannels; ++i)
  185. preallocatedChannelSpace[i] = other.channels[i];
  186. }
  187. else
  188. {
  189. channels = other.channels;
  190. }
  191. other.numChannels = 0;
  192. other.size = 0;
  193. other.allocatedBytes = 0;
  194. return *this;
  195. }
  196. //==============================================================================
  197. /** Returns the number of channels of audio data that this buffer contains.
  198. @see getNumSamples, getReadPointer, getWritePointer
  199. */
  200. int getNumChannels() const noexcept { return numChannels; }
  201. /** Returns the number of samples allocated in each of the buffer's channels.
  202. @see getNumChannels, getReadPointer, getWritePointer
  203. */
  204. int getNumSamples() const noexcept { return size; }
  205. /** Returns a pointer to an array of read-only samples in one of the buffer's channels.
  206. For speed, this doesn't check whether the channel number is out of range,
  207. so be careful when using it!
  208. If you need to write to the data, do NOT call this method and const_cast the
  209. result! Instead, you must call getWritePointer so that the buffer knows you're
  210. planning on modifying the data.
  211. */
  212. const Type* getReadPointer (int channelNumber) const noexcept
  213. {
  214. jassert (isPositiveAndBelow (channelNumber, numChannels));
  215. return channels[channelNumber];
  216. }
  217. /** Returns a pointer to an array of read-only samples in one of the buffer's channels.
  218. For speed, this doesn't check whether the channel number or index are out of range,
  219. so be careful when using it!
  220. If you need to write to the data, do NOT call this method and const_cast the
  221. result! Instead, you must call getWritePointer so that the buffer knows you're
  222. planning on modifying the data.
  223. */
  224. const Type* getReadPointer (int channelNumber, int sampleIndex) const noexcept
  225. {
  226. jassert (isPositiveAndBelow (channelNumber, numChannels));
  227. jassert (isPositiveAndBelow (sampleIndex, size));
  228. return channels[channelNumber] + sampleIndex;
  229. }
  230. /** Returns a writeable pointer to one of the buffer's channels.
  231. For speed, this doesn't check whether the channel number is out of range,
  232. so be careful when using it!
  233. Note that if you're not planning on writing to the data, you should always
  234. use getReadPointer instead.
  235. This will mark the buffer as not cleared and the hasBeenCleared method will return
  236. false after this call. If you retain this write pointer and write some data to
  237. the buffer after calling its clear method, subsequent clear calls will do nothing.
  238. To avoid this either call this method each time you need to write data, or use the
  239. setNotClear method to force the internal cleared flag to false.
  240. @see setNotClear
  241. */
  242. Type* getWritePointer (int channelNumber) noexcept
  243. {
  244. jassert (isPositiveAndBelow (channelNumber, numChannels));
  245. isClear = false;
  246. return channels[channelNumber];
  247. }
  248. /** Returns a writeable pointer to one of the buffer's channels.
  249. For speed, this doesn't check whether the channel number or index are out of range,
  250. so be careful when using it!
  251. Note that if you're not planning on writing to the data, you should
  252. use getReadPointer instead.
  253. This will mark the buffer as not cleared and the hasBeenCleared method will return
  254. false after this call. If you retain this write pointer and write some data to
  255. the buffer after calling its clear method, subsequent clear calls will do nothing.
  256. To avoid this either call this method each time you need to write data, or use the
  257. setNotClear method to force the internal cleared flag to false.
  258. @see setNotClear
  259. */
  260. Type* getWritePointer (int channelNumber, int sampleIndex) noexcept
  261. {
  262. jassert (isPositiveAndBelow (channelNumber, numChannels));
  263. jassert (isPositiveAndBelow (sampleIndex, size));
  264. isClear = false;
  265. return channels[channelNumber] + sampleIndex;
  266. }
  267. /** Returns an array of pointers to the channels in the buffer.
  268. Don't modify any of the pointers that are returned, and bear in mind that
  269. these will become invalid if the buffer is resized.
  270. */
  271. const Type* const* getArrayOfReadPointers() const noexcept { return channels; }
  272. /** Returns an array of pointers to the channels in the buffer.
  273. Don't modify any of the pointers that are returned, and bear in mind that
  274. these will become invalid if the buffer is resized.
  275. This will mark the buffer as not cleared and the hasBeenCleared method will return
  276. false after this call. If you retain this write pointer and write some data to
  277. the buffer after calling its clear method, subsequent clear calls will do nothing.
  278. To avoid this either call this method each time you need to write data, or use the
  279. setNotClear method to force the internal cleared flag to false.
  280. @see setNotClear
  281. */
  282. Type* const* getArrayOfWritePointers() noexcept { isClear = false; return channels; }
  283. //==============================================================================
  284. /** Changes the buffer's size or number of channels.
  285. This can expand or contract the buffer's length, and add or remove channels.
  286. Note that if keepExistingContent and avoidReallocating are both true, then it will
  287. only avoid reallocating if neither the channel count or length in samples increase.
  288. If the required memory can't be allocated, this will throw a std::bad_alloc exception.
  289. @param newNumChannels the new number of channels.
  290. @param newNumSamples the new number of samples.
  291. @param keepExistingContent if this is true, it will try to preserve as much of the
  292. old data as it can in the new buffer.
  293. @param clearExtraSpace if this is true, then any extra channels or space that is
  294. allocated will be also be cleared. If false, then this space is left
  295. uninitialised.
  296. @param avoidReallocating if this is true, then changing the buffer's size won't reduce the
  297. amount of memory that is currently allocated (but it will still
  298. increase it if the new size is bigger than the amount it currently has).
  299. If this is false, then a new allocation will be done so that the buffer
  300. uses takes up the minimum amount of memory that it needs.
  301. */
  302. void setSize (int newNumChannels,
  303. int newNumSamples,
  304. bool keepExistingContent = false,
  305. bool clearExtraSpace = false,
  306. bool avoidReallocating = false)
  307. {
  308. jassert (newNumChannels >= 0);
  309. jassert (newNumSamples >= 0);
  310. if (newNumSamples != size || newNumChannels != numChannels)
  311. {
  312. auto allocatedSamplesPerChannel = ((size_t) newNumSamples + 3) & ~3u;
  313. auto channelListSize = ((static_cast<size_t> (1 + newNumChannels) * sizeof (Type*)) + 15) & ~15u;
  314. auto newTotalBytes = ((size_t) newNumChannels * (size_t) allocatedSamplesPerChannel * sizeof (Type))
  315. + channelListSize + 32;
  316. if (keepExistingContent)
  317. {
  318. if (avoidReallocating && newNumChannels <= numChannels && newNumSamples <= size)
  319. {
  320. // no need to do any remapping in this case, as the channel pointers will remain correct!
  321. }
  322. else
  323. {
  324. HeapBlock<char, true> newData;
  325. newData.allocate (newTotalBytes, clearExtraSpace || isClear);
  326. auto numSamplesToCopy = (size_t) jmin (newNumSamples, size);
  327. auto newChannels = unalignedPointerCast<Type**> (newData.get());
  328. auto newChan = unalignedPointerCast<Type*> (newData + channelListSize);
  329. for (int j = 0; j < newNumChannels; ++j)
  330. {
  331. newChannels[j] = newChan;
  332. newChan += allocatedSamplesPerChannel;
  333. }
  334. if (! isClear)
  335. {
  336. auto numChansToCopy = jmin (numChannels, newNumChannels);
  337. for (int i = 0; i < numChansToCopy; ++i)
  338. FloatVectorOperations::copy (newChannels[i], channels[i], (int) numSamplesToCopy);
  339. }
  340. allocatedData.swapWith (newData);
  341. allocatedBytes = newTotalBytes;
  342. channels = newChannels;
  343. }
  344. }
  345. else
  346. {
  347. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  348. {
  349. if (clearExtraSpace || isClear)
  350. allocatedData.clear (newTotalBytes);
  351. }
  352. else
  353. {
  354. allocatedBytes = newTotalBytes;
  355. allocatedData.allocate (newTotalBytes, clearExtraSpace || isClear);
  356. channels = unalignedPointerCast<Type**> (allocatedData.get());
  357. }
  358. auto* chan = unalignedPointerCast<Type*> (allocatedData + channelListSize);
  359. for (int i = 0; i < newNumChannels; ++i)
  360. {
  361. channels[i] = chan;
  362. chan += allocatedSamplesPerChannel;
  363. }
  364. }
  365. channels[newNumChannels] = nullptr;
  366. size = newNumSamples;
  367. numChannels = newNumChannels;
  368. }
  369. }
  370. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  371. There's also a constructor that lets you specify arrays like this, but this
  372. lets you change the channels dynamically.
  373. Note that if the buffer is resized or its number of channels is changed, it
  374. will re-allocate memory internally and copy the existing data to this new area,
  375. so it will then stop directly addressing this memory.
  376. The hasBeenCleared method will return false after this call.
  377. @param dataToReferTo a pre-allocated array containing pointers to the data
  378. for each channel that should be used by this buffer. The
  379. buffer will only refer to this memory, it won't try to delete
  380. it when the buffer is deleted or resized.
  381. @param newNumChannels the number of channels to use - this must correspond to the
  382. number of elements in the array passed in
  383. @param newStartSample the offset within the arrays at which the data begins
  384. @param newNumSamples the number of samples to use - this must correspond to the
  385. size of the arrays passed in
  386. */
  387. void setDataToReferTo (Type* const* dataToReferTo,
  388. int newNumChannels,
  389. int newStartSample,
  390. int newNumSamples)
  391. {
  392. jassert (dataToReferTo != nullptr);
  393. jassert (newNumChannels >= 0 && newNumSamples >= 0);
  394. if (allocatedBytes != 0)
  395. {
  396. allocatedBytes = 0;
  397. allocatedData.free();
  398. }
  399. numChannels = newNumChannels;
  400. size = newNumSamples;
  401. allocateChannels (dataToReferTo, newStartSample);
  402. jassert (! isClear);
  403. }
  404. /** Makes this buffer point to a pre-allocated set of channel data arrays.
  405. There's also a constructor that lets you specify arrays like this, but this
  406. lets you change the channels dynamically.
  407. Note that if the buffer is resized or its number of channels is changed, it
  408. will re-allocate memory internally and copy the existing data to this new area,
  409. so it will then stop directly addressing this memory.
  410. The hasBeenCleared method will return false after this call.
  411. @param dataToReferTo a pre-allocated array containing pointers to the data
  412. for each channel that should be used by this buffer. The
  413. buffer will only refer to this memory, it won't try to delete
  414. it when the buffer is deleted or resized.
  415. @param newNumChannels the number of channels to use - this must correspond to the
  416. number of elements in the array passed in
  417. @param newNumSamples the number of samples to use - this must correspond to the
  418. size of the arrays passed in
  419. */
  420. void setDataToReferTo (Type* const* dataToReferTo,
  421. int newNumChannels,
  422. int newNumSamples)
  423. {
  424. setDataToReferTo (dataToReferTo, newNumChannels, 0, newNumSamples);
  425. }
  426. /** Resizes this buffer to match the given one, and copies all of its content across.
  427. The source buffer can contain a different floating point type, so this can be used to
  428. convert between 32 and 64 bit float buffer types.
  429. The hasBeenCleared method will return false after this call if the other buffer
  430. contains data.
  431. */
  432. template <typename OtherType>
  433. void makeCopyOf (const AudioBuffer<OtherType>& other, bool avoidReallocating = false)
  434. {
  435. setSize (other.getNumChannels(), other.getNumSamples(), false, false, avoidReallocating);
  436. if (other.hasBeenCleared())
  437. {
  438. clear();
  439. }
  440. else
  441. {
  442. isClear = false;
  443. for (int chan = 0; chan < numChannels; ++chan)
  444. {
  445. auto* dest = channels[chan];
  446. auto* src = other.getReadPointer (chan);
  447. for (int i = 0; i < size; ++i)
  448. dest[i] = static_cast<Type> (src[i]);
  449. }
  450. }
  451. }
  452. //==============================================================================
  453. /** Clears all the samples in all channels and marks the buffer as cleared.
  454. This method will do nothing if the buffer has been marked as cleared (i.e. the
  455. hasBeenCleared method returns true.)
  456. @see hasBeenCleared, setNotClear
  457. */
  458. void clear() noexcept
  459. {
  460. if (! isClear)
  461. {
  462. for (int i = 0; i < numChannels; ++i)
  463. {
  464. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4661)
  465. FloatVectorOperations::clear (channels[i], size);
  466. JUCE_END_IGNORE_WARNINGS_MSVC
  467. }
  468. isClear = true;
  469. }
  470. }
  471. /** Clears a specified region of all the channels.
  472. This will mark the buffer as cleared if the entire buffer contents are cleared.
  473. For speed, this doesn't check whether the channel and sample number
  474. are in-range, so be careful!
  475. This method will do nothing if the buffer has been marked as cleared (i.e. the
  476. hasBeenCleared method returns true.)
  477. @see hasBeenCleared, setNotClear
  478. */
  479. void clear (int startSample, int numSamples) noexcept
  480. {
  481. jassert (startSample >= 0 && numSamples >= 0 && startSample + numSamples <= size);
  482. if (! isClear)
  483. {
  484. for (int i = 0; i < numChannels; ++i)
  485. FloatVectorOperations::clear (channels[i] + startSample, numSamples);
  486. isClear = (startSample == 0 && numSamples == size);
  487. }
  488. }
  489. /** Clears a specified region of just one channel.
  490. For speed, this doesn't check whether the channel and sample number
  491. are in-range, so be careful!
  492. This method will do nothing if the buffer has been marked as cleared (i.e. the
  493. hasBeenCleared method returns true.)
  494. @see hasBeenCleared, setNotClear
  495. */
  496. void clear (int channel, int startSample, int numSamples) noexcept
  497. {
  498. jassert (isPositiveAndBelow (channel, numChannels));
  499. jassert (startSample >= 0 && numSamples >= 0 && startSample + numSamples <= size);
  500. if (! isClear)
  501. FloatVectorOperations::clear (channels[channel] + startSample, numSamples);
  502. }
  503. /** Returns true if the buffer has been entirely cleared.
  504. Note that this does not actually measure the contents of the buffer - it simply
  505. returns a flag that is set when the buffer is cleared, and which is reset whenever
  506. functions like getWritePointer are invoked. That means the method is quick, but it
  507. may return false negatives when in fact the buffer is still empty.
  508. */
  509. bool hasBeenCleared() const noexcept { return isClear; }
  510. /** Forces the internal cleared flag of the buffer to false.
  511. This may be useful in the case where you are holding on to a write pointer and call
  512. the clear method before writing some data. You can then use this method to mark the
  513. buffer as containing data so that subsequent clear calls will succeed. However a
  514. better solution is to call getWritePointer each time you need to write data.
  515. */
  516. void setNotClear() noexcept { isClear = false; }
  517. //==============================================================================
  518. /** Returns a sample from the buffer.
  519. The channel and index are not checked - they are expected to be in-range. If not,
  520. an assertion will be thrown, but in a release build, you're into 'undefined behaviour'
  521. territory.
  522. */
  523. Type getSample (int channel, int sampleIndex) const noexcept
  524. {
  525. jassert (isPositiveAndBelow (channel, numChannels));
  526. jassert (isPositiveAndBelow (sampleIndex, size));
  527. return *(channels[channel] + sampleIndex);
  528. }
  529. /** Sets a sample in the buffer.
  530. The channel and index are not checked - they are expected to be in-range. If not,
  531. an assertion will be thrown, but in a release build, you're into 'undefined behaviour'
  532. territory.
  533. The hasBeenCleared method will return false after this call.
  534. */
  535. void setSample (int destChannel, int destSample, Type newValue) noexcept
  536. {
  537. jassert (isPositiveAndBelow (destChannel, numChannels));
  538. jassert (isPositiveAndBelow (destSample, size));
  539. *(channels[destChannel] + destSample) = newValue;
  540. isClear = false;
  541. }
  542. /** Adds a value to a sample in the buffer.
  543. The channel and index are not checked - they are expected to be in-range. If not,
  544. an assertion will be thrown, but in a release build, you're into 'undefined behaviour'
  545. territory.
  546. The hasBeenCleared method will return false after this call.
  547. */
  548. void addSample (int destChannel, int destSample, Type valueToAdd) noexcept
  549. {
  550. jassert (isPositiveAndBelow (destChannel, numChannels));
  551. jassert (isPositiveAndBelow (destSample, size));
  552. *(channels[destChannel] + destSample) += valueToAdd;
  553. isClear = false;
  554. }
  555. /** Applies a gain multiple to a region of one channel.
  556. For speed, this doesn't check whether the channel and sample number
  557. are in-range, so be careful!
  558. */
  559. void applyGain (int channel, int startSample, int numSamples, Type gain) noexcept
  560. {
  561. jassert (isPositiveAndBelow (channel, numChannels));
  562. jassert (startSample >= 0 && numSamples >= 0 && startSample + numSamples <= size);
  563. if (! approximatelyEqual (gain, Type (1)) && ! isClear)
  564. {
  565. auto* d = channels[channel] + startSample;
  566. if (approximatelyEqual (gain, Type()))
  567. FloatVectorOperations::clear (d, numSamples);
  568. else
  569. FloatVectorOperations::multiply (d, gain, numSamples);
  570. }
  571. }
  572. /** Applies a gain multiple to a region of all the channels.
  573. For speed, this doesn't check whether the sample numbers
  574. are in-range, so be careful!
  575. */
  576. void applyGain (int startSample, int numSamples, Type gain) noexcept
  577. {
  578. for (int i = 0; i < numChannels; ++i)
  579. applyGain (i, startSample, numSamples, gain);
  580. }
  581. /** Applies a gain multiple to all the audio data. */
  582. void applyGain (Type gain) noexcept
  583. {
  584. applyGain (0, size, gain);
  585. }
  586. /** Applies a range of gains to a region of a channel.
  587. The gain that is applied to each sample will vary from
  588. startGain on the first sample to endGain on the last Sample,
  589. so it can be used to do basic fades.
  590. For speed, this doesn't check whether the sample numbers
  591. are in-range, so be careful!
  592. */
  593. void applyGainRamp (int channel, int startSample, int numSamples,
  594. Type startGain, Type endGain) noexcept
  595. {
  596. if (! isClear)
  597. {
  598. if (approximatelyEqual (startGain, endGain))
  599. {
  600. applyGain (channel, startSample, numSamples, startGain);
  601. }
  602. else
  603. {
  604. jassert (isPositiveAndBelow (channel, numChannels));
  605. jassert (startSample >= 0 && numSamples >= 0 && startSample + numSamples <= size);
  606. const auto increment = (endGain - startGain) / (float) numSamples;
  607. auto* d = channels[channel] + startSample;
  608. while (--numSamples >= 0)
  609. {
  610. *d++ *= startGain;
  611. startGain += increment;
  612. }
  613. }
  614. }
  615. }
  616. /** Applies a range of gains to a region of all channels.
  617. The gain that is applied to each sample will vary from
  618. startGain on the first sample to endGain on the last Sample,
  619. so it can be used to do basic fades.
  620. For speed, this doesn't check whether the sample numbers
  621. are in-range, so be careful!
  622. */
  623. void applyGainRamp (int startSample, int numSamples,
  624. Type startGain, Type endGain) noexcept
  625. {
  626. for (int i = 0; i < numChannels; ++i)
  627. applyGainRamp (i, startSample, numSamples, startGain, endGain);
  628. }
  629. /** Adds samples from another buffer to this one.
  630. The hasBeenCleared method will return false after this call if samples have
  631. been added.
  632. @param destChannel the channel within this buffer to add the samples to
  633. @param destStartSample the start sample within this buffer's channel
  634. @param source the source buffer to add from
  635. @param sourceChannel the channel within the source buffer to read from
  636. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  637. @param numSamples the number of samples to process
  638. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  639. added to this buffer's samples
  640. @see copyFrom
  641. */
  642. void addFrom (int destChannel,
  643. int destStartSample,
  644. const AudioBuffer& source,
  645. int sourceChannel,
  646. int sourceStartSample,
  647. int numSamples,
  648. Type gainToApplyToSource = Type (1)) noexcept
  649. {
  650. jassert (&source != this
  651. || sourceChannel != destChannel
  652. || sourceStartSample + numSamples <= destStartSample
  653. || destStartSample + numSamples <= sourceStartSample);
  654. jassert (isPositiveAndBelow (destChannel, numChannels));
  655. jassert (destStartSample >= 0 && numSamples >= 0 && destStartSample + numSamples <= size);
  656. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  657. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  658. if (! approximatelyEqual (gainToApplyToSource, (Type) 0) && numSamples > 0 && ! source.isClear)
  659. {
  660. auto* d = channels[destChannel] + destStartSample;
  661. auto* s = source.channels[sourceChannel] + sourceStartSample;
  662. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4661)
  663. if (isClear)
  664. {
  665. isClear = false;
  666. if (! approximatelyEqual (gainToApplyToSource, Type (1)))
  667. FloatVectorOperations::copyWithMultiply (d, s, gainToApplyToSource, numSamples);
  668. else
  669. FloatVectorOperations::copy (d, s, numSamples);
  670. }
  671. else
  672. {
  673. if (! approximatelyEqual (gainToApplyToSource, Type (1)))
  674. FloatVectorOperations::addWithMultiply (d, s, gainToApplyToSource, numSamples);
  675. else
  676. FloatVectorOperations::add (d, s, numSamples);
  677. }
  678. JUCE_END_IGNORE_WARNINGS_MSVC
  679. }
  680. }
  681. /** Adds samples from an array of floats to one of the channels.
  682. The hasBeenCleared method will return false after this call if samples have
  683. been added.
  684. @param destChannel the channel within this buffer to add the samples to
  685. @param destStartSample the start sample within this buffer's channel
  686. @param source the source data to use
  687. @param numSamples the number of samples to process
  688. @param gainToApplyToSource an optional gain to apply to the source samples before they are
  689. added to this buffer's samples
  690. @see copyFrom
  691. */
  692. void addFrom (int destChannel,
  693. int destStartSample,
  694. const Type* source,
  695. int numSamples,
  696. Type gainToApplyToSource = Type (1)) noexcept
  697. {
  698. jassert (isPositiveAndBelow (destChannel, numChannels));
  699. jassert (destStartSample >= 0 && numSamples >= 0 && destStartSample + numSamples <= size);
  700. jassert (source != nullptr);
  701. if (! approximatelyEqual (gainToApplyToSource, Type()) && numSamples > 0)
  702. {
  703. auto* d = channels[destChannel] + destStartSample;
  704. if (isClear)
  705. {
  706. isClear = false;
  707. if (! approximatelyEqual (gainToApplyToSource, Type (1)))
  708. FloatVectorOperations::copyWithMultiply (d, source, gainToApplyToSource, numSamples);
  709. else
  710. FloatVectorOperations::copy (d, source, numSamples);
  711. }
  712. else
  713. {
  714. if (! approximatelyEqual (gainToApplyToSource, Type (1)))
  715. FloatVectorOperations::addWithMultiply (d, source, gainToApplyToSource, numSamples);
  716. else
  717. FloatVectorOperations::add (d, source, numSamples);
  718. }
  719. }
  720. }
  721. /** Adds samples from an array of floats, applying a gain ramp to them.
  722. The hasBeenCleared method will return false after this call if samples have
  723. been added.
  724. @param destChannel the channel within this buffer to add the samples to
  725. @param destStartSample the start sample within this buffer's channel
  726. @param source the source data to use
  727. @param numSamples the number of samples to process
  728. @param startGain the gain to apply to the first sample (this is multiplied with
  729. the source samples before they are added to this buffer)
  730. @param endGain The gain that would apply to the sample after the final sample.
  731. The gain that applies to the final sample is
  732. (numSamples - 1) / numSamples * (endGain - startGain). This
  733. ensures a continuous ramp when supplying the same value in
  734. endGain and startGain in subsequent blocks. The gain is linearly
  735. interpolated between the first and last samples.
  736. */
  737. void addFromWithRamp (int destChannel,
  738. int destStartSample,
  739. const Type* source,
  740. int numSamples,
  741. Type startGain,
  742. Type endGain) noexcept
  743. {
  744. if (approximatelyEqual (startGain, endGain))
  745. {
  746. addFrom (destChannel, destStartSample, source, numSamples, startGain);
  747. }
  748. else
  749. {
  750. jassert (isPositiveAndBelow (destChannel, numChannels));
  751. jassert (destStartSample >= 0 && numSamples >= 0 && destStartSample + numSamples <= size);
  752. jassert (source != nullptr);
  753. if (numSamples > 0)
  754. {
  755. isClear = false;
  756. const auto increment = (endGain - startGain) / (Type) numSamples;
  757. auto* d = channels[destChannel] + destStartSample;
  758. while (--numSamples >= 0)
  759. {
  760. *d++ += startGain * *source++;
  761. startGain += increment;
  762. }
  763. }
  764. }
  765. }
  766. /** Copies samples from another buffer to this one.
  767. @param destChannel the channel within this buffer to copy the samples to
  768. @param destStartSample the start sample within this buffer's channel
  769. @param source the source buffer to read from
  770. @param sourceChannel the channel within the source buffer to read from
  771. @param sourceStartSample the offset within the source buffer's channel to start reading samples from
  772. @param numSamples the number of samples to process
  773. @see addFrom
  774. */
  775. void copyFrom (int destChannel,
  776. int destStartSample,
  777. const AudioBuffer& source,
  778. int sourceChannel,
  779. int sourceStartSample,
  780. int numSamples) noexcept
  781. {
  782. jassert (&source != this
  783. || sourceChannel != destChannel
  784. || sourceStartSample + numSamples <= destStartSample
  785. || destStartSample + numSamples <= sourceStartSample);
  786. jassert (isPositiveAndBelow (destChannel, numChannels));
  787. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  788. jassert (isPositiveAndBelow (sourceChannel, source.numChannels));
  789. jassert (sourceStartSample >= 0 && numSamples >= 0 && sourceStartSample + numSamples <= source.size);
  790. if (numSamples > 0)
  791. {
  792. if (source.isClear)
  793. {
  794. if (! isClear)
  795. FloatVectorOperations::clear (channels[destChannel] + destStartSample, numSamples);
  796. }
  797. else
  798. {
  799. isClear = false;
  800. FloatVectorOperations::copy (channels[destChannel] + destStartSample,
  801. source.channels[sourceChannel] + sourceStartSample,
  802. numSamples);
  803. }
  804. }
  805. }
  806. /** Copies samples from an array of floats into one of the channels.
  807. The hasBeenCleared method will return false after this call if samples have
  808. been copied.
  809. @param destChannel the channel within this buffer to copy the samples to
  810. @param destStartSample the start sample within this buffer's channel
  811. @param source the source buffer to read from
  812. @param numSamples the number of samples to process
  813. @see addFrom
  814. */
  815. void copyFrom (int destChannel,
  816. int destStartSample,
  817. const Type* source,
  818. int numSamples) noexcept
  819. {
  820. jassert (isPositiveAndBelow (destChannel, numChannels));
  821. jassert (destStartSample >= 0 && numSamples >= 0 && destStartSample + numSamples <= size);
  822. jassert (source != nullptr);
  823. if (numSamples > 0)
  824. {
  825. isClear = false;
  826. FloatVectorOperations::copy (channels[destChannel] + destStartSample, source, numSamples);
  827. }
  828. }
  829. /** Copies samples from an array of floats into one of the channels, applying a gain to it.
  830. The hasBeenCleared method will return false after this call if samples have
  831. been copied.
  832. @param destChannel the channel within this buffer to copy the samples to
  833. @param destStartSample the start sample within this buffer's channel
  834. @param source the source buffer to read from
  835. @param numSamples the number of samples to process
  836. @param gain the gain to apply
  837. @see addFrom
  838. */
  839. void copyFrom (int destChannel,
  840. int destStartSample,
  841. const Type* source,
  842. int numSamples,
  843. Type gain) noexcept
  844. {
  845. jassert (isPositiveAndBelow (destChannel, numChannels));
  846. jassert (destStartSample >= 0 && numSamples >= 0 && destStartSample + numSamples <= size);
  847. jassert (source != nullptr);
  848. if (numSamples > 0)
  849. {
  850. auto* d = channels[destChannel] + destStartSample;
  851. if (! approximatelyEqual (gain, Type (1)))
  852. {
  853. if (approximatelyEqual (gain, Type()))
  854. {
  855. if (! isClear)
  856. FloatVectorOperations::clear (d, numSamples);
  857. }
  858. else
  859. {
  860. isClear = false;
  861. FloatVectorOperations::copyWithMultiply (d, source, gain, numSamples);
  862. }
  863. }
  864. else
  865. {
  866. isClear = false;
  867. FloatVectorOperations::copy (d, source, numSamples);
  868. }
  869. }
  870. }
  871. /** Copies samples from an array of floats into one of the channels, applying a gain ramp.
  872. The hasBeenCleared method will return false after this call if samples have
  873. been copied.
  874. @param destChannel the channel within this buffer to copy the samples to
  875. @param destStartSample the start sample within this buffer's channel
  876. @param source the source buffer to read from
  877. @param numSamples the number of samples to process
  878. @param startGain the gain to apply to the first sample (this is multiplied with
  879. the source samples before they are copied to this buffer)
  880. @param endGain The gain that would apply to the sample after the final sample.
  881. The gain that applies to the final sample is
  882. (numSamples - 1) / numSamples * (endGain - startGain). This
  883. ensures a continuous ramp when supplying the same value in
  884. endGain and startGain in subsequent blocks. The gain is linearly
  885. interpolated between the first and last samples.
  886. @see addFrom
  887. */
  888. void copyFromWithRamp (int destChannel,
  889. int destStartSample,
  890. const Type* source,
  891. int numSamples,
  892. Type startGain,
  893. Type endGain) noexcept
  894. {
  895. if (approximatelyEqual (startGain, endGain))
  896. {
  897. copyFrom (destChannel, destStartSample, source, numSamples, startGain);
  898. }
  899. else
  900. {
  901. jassert (isPositiveAndBelow (destChannel, numChannels));
  902. jassert (destStartSample >= 0 && numSamples >= 0 && destStartSample + numSamples <= size);
  903. jassert (source != nullptr);
  904. if (numSamples > 0)
  905. {
  906. isClear = false;
  907. const auto increment = (endGain - startGain) / (Type) numSamples;
  908. auto* d = channels[destChannel] + destStartSample;
  909. while (--numSamples >= 0)
  910. {
  911. *d++ = startGain * *source++;
  912. startGain += increment;
  913. }
  914. }
  915. }
  916. }
  917. /** Returns a Range indicating the lowest and highest sample values in a given section.
  918. @param channel the channel to read from
  919. @param startSample the start sample within the channel
  920. @param numSamples the number of samples to check
  921. */
  922. Range<Type> findMinMax (int channel, int startSample, int numSamples) const noexcept
  923. {
  924. jassert (isPositiveAndBelow (channel, numChannels));
  925. jassert (startSample >= 0 && numSamples >= 0 && startSample + numSamples <= size);
  926. if (isClear)
  927. return { Type (0), Type (0) };
  928. return FloatVectorOperations::findMinAndMax (channels[channel] + startSample, numSamples);
  929. }
  930. /** Finds the highest absolute sample value within a region of a channel. */
  931. Type getMagnitude (int channel, int startSample, int numSamples) const noexcept
  932. {
  933. jassert (isPositiveAndBelow (channel, numChannels));
  934. jassert (startSample >= 0 && numSamples >= 0 && startSample + numSamples <= size);
  935. if (isClear)
  936. return Type (0);
  937. auto r = findMinMax (channel, startSample, numSamples);
  938. return jmax (r.getStart(), -r.getStart(), r.getEnd(), -r.getEnd());
  939. }
  940. /** Finds the highest absolute sample value within a region on all channels. */
  941. Type getMagnitude (int startSample, int numSamples) const noexcept
  942. {
  943. Type mag (0);
  944. if (! isClear)
  945. for (int i = 0; i < numChannels; ++i)
  946. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  947. return mag;
  948. }
  949. /** Returns the root mean squared level for a region of a channel. */
  950. Type getRMSLevel (int channel, int startSample, int numSamples) const noexcept
  951. {
  952. jassert (isPositiveAndBelow (channel, numChannels));
  953. jassert (startSample >= 0 && numSamples >= 0 && startSample + numSamples <= size);
  954. if (numSamples <= 0 || channel < 0 || channel >= numChannels || isClear)
  955. return Type (0);
  956. auto* data = channels[channel] + startSample;
  957. double sum = 0.0;
  958. for (int i = 0; i < numSamples; ++i)
  959. {
  960. auto sample = data[i];
  961. sum += sample * sample;
  962. }
  963. return static_cast<Type> (std::sqrt (sum / numSamples));
  964. }
  965. /** Reverses a part of a channel. */
  966. void reverse (int channel, int startSample, int numSamples) const noexcept
  967. {
  968. jassert (isPositiveAndBelow (channel, numChannels));
  969. jassert (startSample >= 0 && numSamples >= 0 && startSample + numSamples <= size);
  970. if (! isClear)
  971. std::reverse (channels[channel] + startSample,
  972. channels[channel] + startSample + numSamples);
  973. }
  974. /** Reverses a part of the buffer. */
  975. void reverse (int startSample, int numSamples) const noexcept
  976. {
  977. for (int i = 0; i < numChannels; ++i)
  978. reverse (i, startSample, numSamples);
  979. }
  980. //==============================================================================
  981. /** This allows templated code that takes an AudioBuffer to access its sample type. */
  982. using SampleType = Type;
  983. private:
  984. //==============================================================================
  985. void allocateData()
  986. {
  987. #if (! JUCE_GCC || (__GNUC__ * 100 + __GNUC_MINOR__) >= 409)
  988. static_assert (alignof (Type) <= maxAlignment,
  989. "AudioBuffer cannot hold types with alignment requirements larger than that guaranteed by malloc");
  990. #endif
  991. jassert (size >= 0);
  992. auto channelListSize = (size_t) (numChannels + 1) * sizeof (Type*);
  993. auto requiredSampleAlignment = std::alignment_of_v<Type>;
  994. size_t alignmentOverflow = channelListSize % requiredSampleAlignment;
  995. if (alignmentOverflow != 0)
  996. channelListSize += requiredSampleAlignment - alignmentOverflow;
  997. allocatedBytes = (size_t) numChannels * (size_t) size * sizeof (Type) + channelListSize + 32;
  998. allocatedData.malloc (allocatedBytes);
  999. channels = unalignedPointerCast<Type**> (allocatedData.get());
  1000. auto chan = unalignedPointerCast<Type*> (allocatedData + channelListSize);
  1001. for (int i = 0; i < numChannels; ++i)
  1002. {
  1003. channels[i] = chan;
  1004. chan += size;
  1005. }
  1006. channels[numChannels] = nullptr;
  1007. isClear = false;
  1008. }
  1009. void allocateChannels (Type* const* dataToReferTo, int offset)
  1010. {
  1011. jassert (offset >= 0);
  1012. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  1013. if (numChannels < (int) numElementsInArray (preallocatedChannelSpace))
  1014. {
  1015. channels = static_cast<Type**> (preallocatedChannelSpace);
  1016. }
  1017. else
  1018. {
  1019. allocatedData.malloc (numChannels + 1, sizeof (Type*));
  1020. channels = unalignedPointerCast<Type**> (allocatedData.get());
  1021. }
  1022. for (int i = 0; i < numChannels; ++i)
  1023. {
  1024. // you have to pass in the same number of valid pointers as numChannels
  1025. jassert (dataToReferTo[i] != nullptr);
  1026. channels[i] = dataToReferTo[i] + offset;
  1027. }
  1028. channels[numChannels] = nullptr;
  1029. isClear = false;
  1030. }
  1031. /* On iOS/arm7 the alignment of `double` is greater than the alignment of
  1032. `std::max_align_t`, so we can't trust max_align_t. Instead, we query
  1033. lots of primitive types and use the maximum alignment of all of them.
  1034. */
  1035. static constexpr size_t getMaxAlignment() noexcept
  1036. {
  1037. constexpr size_t alignments[] { alignof (std::max_align_t),
  1038. alignof (void*),
  1039. alignof (float),
  1040. alignof (double),
  1041. alignof (long double),
  1042. alignof (short int),
  1043. alignof (int),
  1044. alignof (long int),
  1045. alignof (long long int),
  1046. alignof (bool),
  1047. alignof (char),
  1048. alignof (char16_t),
  1049. alignof (char32_t),
  1050. alignof (wchar_t) };
  1051. size_t max = 0;
  1052. for (const auto elem : alignments)
  1053. max = jmax (max, elem);
  1054. return max;
  1055. }
  1056. int numChannels = 0, size = 0;
  1057. size_t allocatedBytes = 0;
  1058. Type** channels;
  1059. HeapBlock<char, true> allocatedData;
  1060. Type* preallocatedChannelSpace[32];
  1061. bool isClear = false;
  1062. static constexpr size_t maxAlignment = getMaxAlignment();
  1063. JUCE_LEAK_DETECTOR (AudioBuffer)
  1064. };
  1065. //==============================================================================
  1066. template <typename Type>
  1067. bool operator== (const AudioBuffer<Type>& a, const AudioBuffer<Type>& b)
  1068. {
  1069. if (a.getNumChannels() != b.getNumChannels())
  1070. return false;
  1071. for (auto c = 0; c < a.getNumChannels(); ++c)
  1072. {
  1073. const auto begin = [c] (auto& x) { return x.getReadPointer (c); };
  1074. const auto end = [c] (auto& x) { return x.getReadPointer (c) + x.getNumSamples(); };
  1075. if (! std::equal (begin (a), end (a), begin (b), end (b)))
  1076. return false;
  1077. }
  1078. return true;
  1079. }
  1080. template <typename Type>
  1081. bool operator!= (const AudioBuffer<Type>& a, const AudioBuffer<Type>& b)
  1082. {
  1083. return ! (a == b);
  1084. }
  1085. //==============================================================================
  1086. /**
  1087. A multi-channel buffer of 32-bit floating point audio samples.
  1088. This type is here for backwards compatibility with the older AudioSampleBuffer
  1089. class, which was fixed for 32-bit data, but is otherwise the same as the new
  1090. templated AudioBuffer class.
  1091. @see AudioBuffer
  1092. */
  1093. using AudioSampleBuffer = AudioBuffer<float>;
  1094. } // namespace juce