Line data Source code
1 : /* 2 : * Copyright (C) 2004-2024 Savoir-faire Linux Inc. 3 : * 4 : * This program is free software: you can redistribute it and/or modify 5 : * it under the terms of the GNU General Public License as published by 6 : * the Free Software Foundation, either version 3 of the License, or 7 : * (at your option) any later version. 8 : * 9 : * This program is distributed in the hope that it will be useful, 10 : * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 : * GNU General Public License for more details. 13 : * 14 : * You should have received a copy of the GNU General Public License 15 : * along with this program. If not, see <https://www.gnu.org/licenses/>. 16 : */ 17 : 18 : #ifndef RING_TYPES_H_ 19 : #define RING_TYPES_H_ 20 : 21 : #include <type_traits> 22 : #include <memory> 23 : #include <mutex> 24 : #include <cstddef> // for size_t 25 : 26 : #include <ciso646> // fix windows compiler bug 27 : 28 : namespace jami { 29 : 30 : 31 : static constexpr size_t SIZEBUF = 16000; /** About 62.5ms of buffering at 48kHz */ 32 : 33 : /** 34 : * This meta-function is used to enable a template overload 35 : * only if given class T is a base of class U 36 : */ 37 : template<class T, class U> 38 : using enable_if_base_of = typename std::enable_if<std::is_base_of<T, U>::value, T>::type; 39 : 40 : /** 41 : * Return a shared pointer on an auto-generated global instance of class T. 42 : * This instance is created only at usage and destroyed when not, 43 : * as we keep only a weak reference on it. 44 : * But when created it's always the same object until all holders release 45 : * their sharing. 46 : * An optional MaxRespawn positive integer can be given to limit the number 47 : * of time the object can be created (i.e. different instance). 48 : * Any negative values (default) block this effect (unlimited respawn). 49 : * This function is thread-safe. 50 : */ 51 : template<class T, signed MaxRespawn = -1> 52 : std::shared_ptr<T> 53 974 : getGlobalInstance() 54 : { 55 : static std::recursive_mutex mutex; // recursive as instance calls recursively 56 974 : static std::weak_ptr<T> wlink; 57 : 58 974 : std::unique_lock<std::recursive_mutex> lock(mutex); 59 : 60 974 : if (wlink.expired()) { 61 : static signed counter {MaxRespawn}; 62 271 : if (not counter) 63 0 : return nullptr; 64 271 : auto link = std::make_shared<T>(); 65 271 : wlink = link; 66 271 : if (counter > 0) 67 0 : --counter; 68 271 : return link; 69 271 : } 70 : 71 703 : return wlink.lock(); 72 974 : } 73 : 74 : } // namespace jami 75 : 76 : #endif // RING_TYPES_H_