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.

1135 lines
45KB

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