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.

1107 lines
43KB

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