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.

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