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.

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