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.

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