Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1297 lines
52KB

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