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.

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