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.

409 lines
16KB

  1. /*
  2. * Carla misc utils based on Juce
  3. * Copyright (C) 2013 Raw Material Software Ltd.
  4. * Copyright (c) 2016 ROLI Ltd.
  5. * Copyright (C) 2013-2018 Filipe Coelho <falktx@falktx.com>
  6. *
  7. * Permission to use, copy, modify, and/or distribute this software for any purpose with
  8. * or without fee is hereby granted, provided that the above copyright notice and this
  9. * permission notice appear in all copies.
  10. *
  11. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  12. * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  13. * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  14. * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  15. * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  16. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  17. */
  18. #ifndef CARLA_JUCE_UTILS_HPP_INCLUDED
  19. #define CARLA_JUCE_UTILS_HPP_INCLUDED
  20. #define DISTRHO_LEAK_DETECTOR_HPP_INCLUDED
  21. #define DISTRHO_SCOPED_POINTER_HPP_INCLUDED
  22. #define DISTRHO_LEAK_DETECTOR CARLA_LEAK_DETECTOR
  23. #define DISTRHO_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR
  24. #include "CarlaUtils.hpp"
  25. #include <algorithm>
  26. #include <cmath>
  27. /** A good old-fashioned C macro concatenation helper.
  28. This combines two items (which may themselves be macros) into a single string,
  29. avoiding the pitfalls of the ## macro operator.
  30. */
  31. #define CARLA_JOIN_MACRO_HELPER(a, b) a ## b
  32. #define CARLA_JOIN_MACRO(item1, item2) CARLA_JOIN_MACRO_HELPER(item1, item2)
  33. #ifdef DEBUG
  34. /** This macro lets you embed a leak-detecting object inside a class.
  35. To use it, simply declare a CARLA_LEAK_DETECTOR(YourClassName) inside a private section
  36. of the class declaration. E.g.
  37. @code
  38. class MyClass
  39. {
  40. public:
  41. MyClass();
  42. void blahBlah();
  43. private:
  44. CARLA_LEAK_DETECTOR(MyClass)
  45. };
  46. @endcode
  47. */
  48. # define CARLA_LEAK_DETECTOR(ClassName) \
  49. friend class ::LeakedObjectDetector<ClassName>; \
  50. static const char* getLeakedObjectClassName() noexcept { return #ClassName; } \
  51. ::LeakedObjectDetector<ClassName> CARLA_JOIN_MACRO(leakDetector_, ClassName);
  52. # define CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ClassName) \
  53. CARLA_DECLARE_NON_COPY_CLASS(ClassName) \
  54. CARLA_LEAK_DETECTOR(ClassName)
  55. #else
  56. /** Don't use leak detection on release builds. */
  57. # define CARLA_LEAK_DETECTOR(ClassName)
  58. # define CARLA_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(ClassName) \
  59. CARLA_DECLARE_NON_COPY_CLASS(ClassName)
  60. #endif
  61. //=====================================================================================================================
  62. /** Converts a dBFS value to its equivalent gain level.
  63. A gain of 1.0 = 0 dB, and lower gains map onto negative decibel values. Any
  64. decibel value lower than minusInfinityDb will return a gain of 0.
  65. */
  66. static inline
  67. float decibelsToGain (const double decibels, const double minusInfinityDb = -100.0)
  68. {
  69. return decibels > minusInfinityDb
  70. ? static_cast<float>(std::pow(10.0, decibels * 0.05))
  71. : 0.0f;
  72. }
  73. //=====================================================================================================================
  74. /**
  75. Embedding an instance of this class inside another class can be used as a low-overhead
  76. way of detecting leaked instances.
  77. This class keeps an internal static count of the number of instances that are
  78. active, so that when the app is shutdown and the static destructors are called,
  79. it can check whether there are any left-over instances that may have been leaked.
  80. To use it, use the CARLA_LEAK_DETECTOR macro as a simple way to put one in your
  81. class declaration.
  82. */
  83. template <class OwnerClass>
  84. class LeakedObjectDetector
  85. {
  86. public:
  87. //=================================================================================================================
  88. LeakedObjectDetector() noexcept { ++(getCounter().numObjects); }
  89. LeakedObjectDetector(const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); }
  90. ~LeakedObjectDetector() noexcept
  91. {
  92. if (--(getCounter().numObjects) < 0)
  93. {
  94. /** If you hit this, then you've managed to delete more instances of this class than you've
  95. created.. That indicates that you're deleting some dangling pointers.
  96. Note that although this assertion will have been triggered during a destructor, it might
  97. not be this particular deletion that's at fault - the incorrect one may have happened
  98. at an earlier point in the program, and simply not been detected until now.
  99. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  100. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  101. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  102. */
  103. carla_stderr2("*** Dangling pointer deletion! Class: '%s', Count: %i", getLeakedObjectClassName(),
  104. getCounter().numObjects);
  105. }
  106. }
  107. private:
  108. //=================================================================================================================
  109. class LeakCounter
  110. {
  111. public:
  112. LeakCounter() noexcept
  113. : numObjects(0) {}
  114. ~LeakCounter() noexcept
  115. {
  116. if (numObjects > 0)
  117. {
  118. /** If you hit this, then you've leaked one or more objects of the type specified by
  119. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  120. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  121. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  122. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  123. */
  124. carla_stderr2("*** Leaked objects detected: %i instance(s) of class '%s'", numObjects,
  125. getLeakedObjectClassName());
  126. }
  127. }
  128. // this should be an atomic...
  129. volatile int numObjects;
  130. };
  131. static const char* getLeakedObjectClassName() noexcept
  132. {
  133. return OwnerClass::getLeakedObjectClassName();
  134. }
  135. static LeakCounter& getCounter() noexcept
  136. {
  137. static LeakCounter counter;
  138. return counter;
  139. }
  140. };
  141. //=====================================================================================================================
  142. /**
  143. This class holds a pointer which is automatically deleted when this object goes
  144. out of scope.
  145. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  146. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  147. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  148. created objects.
  149. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  150. to an object. If you use the assignment operator to assign a different object to a
  151. ScopedPointer, the old one will be automatically deleted.
  152. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  153. object to which it points during its lifetime. This means that making a copy of a const
  154. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  155. old one.
  156. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  157. can use the release() method.
  158. Something to note is the main difference between this class and the std::auto_ptr class,
  159. which is that ScopedPointer provides a cast-to-object operator, wheras std::auto_ptr
  160. requires that you always call get() to retrieve the pointer. The advantages of providing
  161. the cast is that you don't need to call get(), so can use the ScopedPointer in pretty much
  162. exactly the same way as a raw pointer. The disadvantage is that the compiler is free to
  163. use the cast in unexpected and sometimes dangerous ways - in particular, it becomes difficult
  164. to return a ScopedPointer as the result of a function. To avoid this causing errors,
  165. ScopedPointer contains an overloaded constructor that should cause a syntax error in these
  166. circumstances, but it does mean that instead of returning a ScopedPointer from a function,
  167. you'd need to return a raw pointer (or use a std::auto_ptr instead).
  168. */
  169. template<class ObjectType>
  170. class ScopedPointer
  171. {
  172. public:
  173. //=================================================================================================================
  174. /** Creates a ScopedPointer containing a null pointer. */
  175. ScopedPointer() noexcept
  176. : object(nullptr) {}
  177. /** Creates a ScopedPointer that owns the specified object. */
  178. ScopedPointer(ObjectType* const objectToTakePossessionOf) noexcept
  179. : object(objectToTakePossessionOf) {}
  180. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  181. Because a pointer can only belong to one ScopedPointer, this transfers
  182. the pointer from the other object to this one, and the other object is reset to
  183. be a null pointer.
  184. */
  185. ScopedPointer(ScopedPointer& objectToTransferFrom) noexcept
  186. : object(objectToTransferFrom.object)
  187. {
  188. objectToTransferFrom.object = nullptr;
  189. }
  190. /** Destructor.
  191. This will delete the object that this ScopedPointer currently refers to.
  192. */
  193. ~ScopedPointer()
  194. {
  195. delete object;
  196. }
  197. /** Changes this ScopedPointer to point to a new object.
  198. Because a pointer can only belong to one ScopedPointer, this transfers
  199. the pointer from the other object to this one, and the other object is reset to
  200. be a null pointer.
  201. If this ScopedPointer already points to an object, that object
  202. will first be deleted.
  203. */
  204. ScopedPointer& operator=(ScopedPointer& objectToTransferFrom)
  205. {
  206. if (this != objectToTransferFrom.getAddress())
  207. {
  208. // Two ScopedPointers should never be able to refer to the same object - if
  209. // this happens, you must have done something dodgy!
  210. CARLA_SAFE_ASSERT_RETURN(object == nullptr || object != objectToTransferFrom.object, *this);
  211. ObjectType* const oldObject = object;
  212. object = objectToTransferFrom.object;
  213. objectToTransferFrom.object = nullptr;
  214. delete oldObject;
  215. }
  216. return *this;
  217. }
  218. /** Changes this ScopedPointer to point to a new object.
  219. If this ScopedPointer already points to an object, that object
  220. will first be deleted.
  221. The pointer that you pass in may be a nullptr.
  222. */
  223. ScopedPointer& operator=(ObjectType* const newObjectToTakePossessionOf)
  224. {
  225. if (object != newObjectToTakePossessionOf)
  226. {
  227. ObjectType* const oldObject = object;
  228. object = newObjectToTakePossessionOf;
  229. delete oldObject;
  230. }
  231. return *this;
  232. }
  233. //=================================================================================================================
  234. /** Returns the object that this ScopedPointer refers to. */
  235. operator ObjectType*() const noexcept { return object; }
  236. /** Returns the object that this ScopedPointer refers to. */
  237. ObjectType* get() const noexcept { return object; }
  238. /** Returns the object that this ScopedPointer refers to. */
  239. ObjectType& operator*() const noexcept { return *object; }
  240. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  241. ObjectType* operator->() const noexcept { return object; }
  242. //=================================================================================================================
  243. /** Removes the current object from this ScopedPointer without deleting it.
  244. This will return the current object, and set the ScopedPointer to a null pointer.
  245. */
  246. ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; }
  247. //=================================================================================================================
  248. /** Swaps this object with that of another ScopedPointer.
  249. The two objects simply exchange their pointers.
  250. */
  251. void swapWith(ScopedPointer<ObjectType>& other) noexcept
  252. {
  253. // Two ScopedPointers should never be able to refer to the same object - if
  254. // this happens, you must have done something dodgy!
  255. CARLA_SAFE_ASSERT_RETURN(object != other.object || this == other.getAddress() || object == nullptr,);
  256. std::swap(object, other.object);
  257. }
  258. private:
  259. //=================================================================================================================
  260. ObjectType* object;
  261. // (Required as an alternative to the overloaded & operator).
  262. const ScopedPointer* getAddress() const noexcept { return this; }
  263. #ifdef CARLA_PROPER_CPP11_SUPPORT
  264. ScopedPointer(const ScopedPointer&) = delete;
  265. ScopedPointer& operator=(const ScopedPointer&) = delete;
  266. #else
  267. ScopedPointer(const ScopedPointer&);
  268. ScopedPointer& operator=(const ScopedPointer&);
  269. #endif
  270. };
  271. //=====================================================================================================================
  272. /** Compares a ScopedPointer with another pointer.
  273. This can be handy for checking whether this is a null pointer.
  274. */
  275. template<class ObjectType>
  276. bool operator==(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  277. {
  278. return static_cast<ObjectType*>(pointer1) == pointer2;
  279. }
  280. /** Compares a ScopedPointer with another pointer.
  281. This can be handy for checking whether this is a null pointer.
  282. */
  283. template<class ObjectType>
  284. bool operator!=(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  285. {
  286. return static_cast<ObjectType*>(pointer1) != pointer2;
  287. }
  288. //=====================================================================================================================
  289. /**
  290. Helper class providing an RAII-based mechanism for temporarily setting and
  291. then re-setting a value.
  292. E.g. @code
  293. int x = 1;
  294. {
  295. ScopedValueSetter setter (x, 2);
  296. // x is now 2
  297. }
  298. // x is now 1 again
  299. {
  300. ScopedValueSetter setter (x, 3, 4);
  301. // x is now 3
  302. }
  303. // x is now 4
  304. @endcode
  305. */
  306. template <typename ValueType>
  307. class ScopedValueSetter
  308. {
  309. public:
  310. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  311. given new value, and will then reset it to its original value when this object is deleted.
  312. Must be used only for 'noexcept' compatible types.
  313. */
  314. ScopedValueSetter(ValueType& valueToSet, ValueType newValue) noexcept
  315. : value(valueToSet),
  316. originalValue(valueToSet)
  317. {
  318. valueToSet = newValue;
  319. }
  320. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  321. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  322. */
  323. ScopedValueSetter(ValueType& valueToSet, ValueType newValue, ValueType valueWhenDeleted) noexcept
  324. : value(valueToSet),
  325. originalValue(valueWhenDeleted)
  326. {
  327. valueToSet = newValue;
  328. }
  329. ~ScopedValueSetter() noexcept
  330. {
  331. value = originalValue;
  332. }
  333. private:
  334. //=================================================================================================================
  335. ValueType& value;
  336. const ValueType originalValue;
  337. CARLA_DECLARE_NON_COPY_CLASS(ScopedValueSetter)
  338. CARLA_PREVENT_HEAP_ALLOCATION
  339. };
  340. //=====================================================================================================================
  341. #endif // CARLA_JUCE_UTILS_HPP_INCLUDED