The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1108 lines
44KB

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