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.

1195 lines
47KB

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