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.

1200 lines
47KB

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