Audio plugin host https://kx.studio/carla
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.

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