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.

406 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 float decibelsToGain (const float decibels, const float minusInfinityDb = -100.0f)
  67. {
  68. return decibels > minusInfinityDb ? std::pow (10.0f, decibels * 0.05f) : 0.0f;
  69. }
  70. //=====================================================================================================================
  71. /**
  72. Embedding an instance of this class inside another class can be used as a low-overhead
  73. way of detecting leaked instances.
  74. This class keeps an internal static count of the number of instances that are
  75. active, so that when the app is shutdown and the static destructors are called,
  76. it can check whether there are any left-over instances that may have been leaked.
  77. To use it, use the CARLA_LEAK_DETECTOR macro as a simple way to put one in your
  78. class declaration.
  79. */
  80. template <class OwnerClass>
  81. class LeakedObjectDetector
  82. {
  83. public:
  84. //=================================================================================================================
  85. LeakedObjectDetector() noexcept { ++(getCounter().numObjects); }
  86. LeakedObjectDetector(const LeakedObjectDetector&) noexcept { ++(getCounter().numObjects); }
  87. ~LeakedObjectDetector() noexcept
  88. {
  89. if (--(getCounter().numObjects) < 0)
  90. {
  91. /** If you hit this, then you've managed to delete more instances of this class than you've
  92. created.. That indicates that you're deleting some dangling pointers.
  93. Note that although this assertion will have been triggered during a destructor, it might
  94. not be this particular deletion that's at fault - the incorrect one may have happened
  95. at an earlier point in the program, and simply not been detected until now.
  96. Most errors like this are caused by using old-fashioned, non-RAII techniques for
  97. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  98. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  99. */
  100. carla_stderr2("*** Dangling pointer deletion! Class: '%s', Count: %i", getLeakedObjectClassName(),
  101. getCounter().numObjects);
  102. }
  103. }
  104. private:
  105. //=================================================================================================================
  106. class LeakCounter
  107. {
  108. public:
  109. LeakCounter() noexcept
  110. : numObjects(0) {}
  111. ~LeakCounter() noexcept
  112. {
  113. if (numObjects > 0)
  114. {
  115. /** If you hit this, then you've leaked one or more objects of the type specified by
  116. the 'OwnerClass' template parameter - the name should have been printed by the line above.
  117. If you're leaking, it's probably because you're using old-fashioned, non-RAII techniques for
  118. your object management. Tut, tut. Always, always use ScopedPointers, OwnedArrays,
  119. ReferenceCountedObjects, etc, and avoid the 'delete' operator at all costs!
  120. */
  121. carla_stderr2("*** Leaked objects detected: %i instance(s) of class '%s'", numObjects,
  122. getLeakedObjectClassName());
  123. }
  124. }
  125. // this should be an atomic...
  126. volatile int numObjects;
  127. };
  128. static const char* getLeakedObjectClassName() noexcept
  129. {
  130. return OwnerClass::getLeakedObjectClassName();
  131. }
  132. static LeakCounter& getCounter() noexcept
  133. {
  134. static LeakCounter counter;
  135. return counter;
  136. }
  137. };
  138. //=====================================================================================================================
  139. /**
  140. This class holds a pointer which is automatically deleted when this object goes
  141. out of scope.
  142. Once a pointer has been passed to a ScopedPointer, it will make sure that the pointer
  143. gets deleted when the ScopedPointer is deleted. Using the ScopedPointer on the stack or
  144. as member variables is a good way to use RAII to avoid accidentally leaking dynamically
  145. created objects.
  146. A ScopedPointer can be used in pretty much the same way that you'd use a normal pointer
  147. to an object. If you use the assignment operator to assign a different object to a
  148. ScopedPointer, the old one will be automatically deleted.
  149. A const ScopedPointer is guaranteed not to lose ownership of its object or change the
  150. object to which it points during its lifetime. This means that making a copy of a const
  151. ScopedPointer is impossible, as that would involve the new copy taking ownership from the
  152. old one.
  153. If you need to get a pointer out of a ScopedPointer without it being deleted, you
  154. can use the release() method.
  155. Something to note is the main difference between this class and the std::auto_ptr class,
  156. which is that ScopedPointer provides a cast-to-object operator, wheras std::auto_ptr
  157. requires that you always call get() to retrieve the pointer. The advantages of providing
  158. the cast is that you don't need to call get(), so can use the ScopedPointer in pretty much
  159. exactly the same way as a raw pointer. The disadvantage is that the compiler is free to
  160. use the cast in unexpected and sometimes dangerous ways - in particular, it becomes difficult
  161. to return a ScopedPointer as the result of a function. To avoid this causing errors,
  162. ScopedPointer contains an overloaded constructor that should cause a syntax error in these
  163. circumstances, but it does mean that instead of returning a ScopedPointer from a function,
  164. you'd need to return a raw pointer (or use a std::auto_ptr instead).
  165. */
  166. template<class ObjectType>
  167. class ScopedPointer
  168. {
  169. public:
  170. //=================================================================================================================
  171. /** Creates a ScopedPointer containing a null pointer. */
  172. ScopedPointer() noexcept
  173. : object(nullptr) {}
  174. /** Creates a ScopedPointer that owns the specified object. */
  175. ScopedPointer(ObjectType* const objectToTakePossessionOf) noexcept
  176. : object(objectToTakePossessionOf) {}
  177. /** Creates a ScopedPointer that takes its pointer from another ScopedPointer.
  178. Because a pointer can only belong to one ScopedPointer, this transfers
  179. the pointer from the other object to this one, and the other object is reset to
  180. be a null pointer.
  181. */
  182. ScopedPointer(ScopedPointer& objectToTransferFrom) noexcept
  183. : object(objectToTransferFrom.object)
  184. {
  185. objectToTransferFrom.object = nullptr;
  186. }
  187. /** Destructor.
  188. This will delete the object that this ScopedPointer currently refers to.
  189. */
  190. ~ScopedPointer()
  191. {
  192. delete object;
  193. }
  194. /** Changes this ScopedPointer to point to a new object.
  195. Because a pointer can only belong to one ScopedPointer, this transfers
  196. the pointer from the other object to this one, and the other object is reset to
  197. be a null pointer.
  198. If this ScopedPointer already points to an object, that object
  199. will first be deleted.
  200. */
  201. ScopedPointer& operator=(ScopedPointer& objectToTransferFrom)
  202. {
  203. if (this != objectToTransferFrom.getAddress())
  204. {
  205. // Two ScopedPointers should never be able to refer to the same object - if
  206. // this happens, you must have done something dodgy!
  207. CARLA_SAFE_ASSERT_RETURN(object == nullptr || object != objectToTransferFrom.object, *this);
  208. ObjectType* const oldObject = object;
  209. object = objectToTransferFrom.object;
  210. objectToTransferFrom.object = nullptr;
  211. delete oldObject;
  212. }
  213. return *this;
  214. }
  215. /** Changes this ScopedPointer to point to a new object.
  216. If this ScopedPointer already points to an object, that object
  217. will first be deleted.
  218. The pointer that you pass in may be a nullptr.
  219. */
  220. ScopedPointer& operator=(ObjectType* const newObjectToTakePossessionOf)
  221. {
  222. if (object != newObjectToTakePossessionOf)
  223. {
  224. ObjectType* const oldObject = object;
  225. object = newObjectToTakePossessionOf;
  226. delete oldObject;
  227. }
  228. return *this;
  229. }
  230. //=================================================================================================================
  231. /** Returns the object that this ScopedPointer refers to. */
  232. operator ObjectType*() const noexcept { return object; }
  233. /** Returns the object that this ScopedPointer refers to. */
  234. ObjectType* get() const noexcept { return object; }
  235. /** Returns the object that this ScopedPointer refers to. */
  236. ObjectType& operator*() const noexcept { return *object; }
  237. /** Lets you access methods and properties of the object that this ScopedPointer refers to. */
  238. ObjectType* operator->() const noexcept { return object; }
  239. //=================================================================================================================
  240. /** Removes the current object from this ScopedPointer without deleting it.
  241. This will return the current object, and set the ScopedPointer to a null pointer.
  242. */
  243. ObjectType* release() noexcept { ObjectType* const o = object; object = nullptr; return o; }
  244. //=================================================================================================================
  245. /** Swaps this object with that of another ScopedPointer.
  246. The two objects simply exchange their pointers.
  247. */
  248. void swapWith(ScopedPointer<ObjectType>& other) noexcept
  249. {
  250. // Two ScopedPointers should never be able to refer to the same object - if
  251. // this happens, you must have done something dodgy!
  252. CARLA_SAFE_ASSERT_RETURN(object != other.object || this == other.getAddress() || object == nullptr,);
  253. std::swap(object, other.object);
  254. }
  255. private:
  256. //=================================================================================================================
  257. ObjectType* object;
  258. // (Required as an alternative to the overloaded & operator).
  259. const ScopedPointer* getAddress() const noexcept { return this; }
  260. #ifdef CARLA_PROPER_CPP11_SUPPORT
  261. ScopedPointer(const ScopedPointer&) = delete;
  262. ScopedPointer& operator=(const ScopedPointer&) = delete;
  263. #else
  264. ScopedPointer(const ScopedPointer&);
  265. ScopedPointer& operator=(const ScopedPointer&);
  266. #endif
  267. };
  268. //=====================================================================================================================
  269. /** Compares a ScopedPointer with another pointer.
  270. This can be handy for checking whether this is a null pointer.
  271. */
  272. template<class ObjectType>
  273. bool operator==(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  274. {
  275. return static_cast<ObjectType*>(pointer1) == pointer2;
  276. }
  277. /** Compares a ScopedPointer with another pointer.
  278. This can be handy for checking whether this is a null pointer.
  279. */
  280. template<class ObjectType>
  281. bool operator!=(const ScopedPointer<ObjectType>& pointer1, ObjectType* const pointer2) noexcept
  282. {
  283. return static_cast<ObjectType*>(pointer1) != pointer2;
  284. }
  285. //=====================================================================================================================
  286. /**
  287. Helper class providing an RAII-based mechanism for temporarily setting and
  288. then re-setting a value.
  289. E.g. @code
  290. int x = 1;
  291. {
  292. ScopedValueSetter setter (x, 2);
  293. // x is now 2
  294. }
  295. // x is now 1 again
  296. {
  297. ScopedValueSetter setter (x, 3, 4);
  298. // x is now 3
  299. }
  300. // x is now 4
  301. @endcode
  302. */
  303. template <typename ValueType>
  304. class ScopedValueSetter
  305. {
  306. public:
  307. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  308. given new value, and will then reset it to its original value when this object is deleted.
  309. Must be used only for 'noexcept' compatible types.
  310. */
  311. ScopedValueSetter(ValueType& valueToSet, ValueType newValue) noexcept
  312. : value(valueToSet),
  313. originalValue(valueToSet)
  314. {
  315. valueToSet = newValue;
  316. }
  317. /** Creates a ScopedValueSetter that will immediately change the specified value to the
  318. given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
  319. */
  320. ScopedValueSetter(ValueType& valueToSet, ValueType newValue, ValueType valueWhenDeleted) noexcept
  321. : value(valueToSet),
  322. originalValue(valueWhenDeleted)
  323. {
  324. valueToSet = newValue;
  325. }
  326. ~ScopedValueSetter() noexcept
  327. {
  328. value = originalValue;
  329. }
  330. private:
  331. //=================================================================================================================
  332. ValueType& value;
  333. const ValueType originalValue;
  334. CARLA_DECLARE_NON_COPY_CLASS(ScopedValueSetter)
  335. CARLA_PREVENT_HEAP_ALLOCATION
  336. };
  337. //=====================================================================================================================
  338. #endif // CARLA_JUCE_UTILS_HPP_INCLUDED