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.

juce_AudioSampleBuffer.h 51KB

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